1 /* $OpenBSD: main.c,v 1.54 2013/11/28 10:33:37 sobrado Exp $ */
2 /* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt Exp $ */
3 /* $OpenBSD: io.c,v 1.23 2013/12/17 16:37:06 deraadt Exp $ */
4 /* $OpenBSD: table.c,v 1.15 2012/02/19 07:52:30 otto Exp $ */
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
8 * 2011, 2012, 2013, 2014
9 * Thorsten Glaser <tg@mirbsd.org>
11 * Provided that these terms and disclaimer and all copyright notices
12 * are retained or reproduced in an accompanying document, permission
13 * is granted to deal in this work without restriction, including un-
14 * limited rights to use, publicly perform, distribute, sell, modify,
15 * merge, give away, or sublicence.
17 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18 * the utmost extent permitted by applicable law, neither express nor
19 * implied; without malicious intent or gross negligence. In no event
20 * may a licensor, author or contributor be held liable for indirect,
21 * direct, other damage, loss, or other issues arising in any way out
22 * of dealing in the work, even if advised of the possibility of such
23 * damage or existence of a defect, except proven that it results out
24 * of said person's immediate fault when using the work as intended.
30 #if HAVE_LANGINFO_CODESET
33 #if HAVE_SETLOCALE_CTYPE
37 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.280 2014/06/09 12:28:17 tg Exp $");
39 extern char **environ;
42 #define MKSHRC_PATH "~/.mkshrc"
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR "/tmp"
49 static uint8_t isuc(const char *);
50 static int main_init(int, const char *[], Source **, struct block **);
51 void chvt_reinit(void);
52 static void reclaim(void);
53 static void remove_temps(struct temp *);
54 static mksh_uari_t rndsetup(void);
56 static void x_sigwinch(int);
59 static const char initifs[] = "IFS= \t\n";
61 static const char initsubs[] =
62 "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
64 static const char *initcoms[] = {
65 Ttypeset, "-r", initvsn, NULL,
66 Ttypeset, "-x", "HOME", "PATH", "RANDOM", "SHELL", NULL,
67 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
71 /* not "alias -t --": hash -r needs to work */
74 #if !defined(ANDROID) && !defined(MKSH_UNEMPLOYED)
75 /* not in Android for political reasons */
76 /* not in ARGE mksh due to no job control */
79 "autoload=typeset -fu",
80 "functions=typeset -f",
85 "source=PATH=$PATH:. command .",
88 /* this is what AT&T ksh seems to track, with the addition of emacs */
90 "cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
91 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
95 static const char *restr_com[] = {
96 Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
99 static bool initio_done;
101 /* top-level parsing and execution environment */
102 static struct env env;
103 struct env *e = &env;
110 ALLOC_ITEM alloc_INT;
111 void *dataptr, *stkptr, *mallocptr;
112 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
119 cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
121 /* clear the allocated space, for valgrind */
122 memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
124 /* undo what alloc() did to the malloc result address */
125 bufptr = (void *)(cp - ALLOC_SIZE);
126 /* PIE or something similar provides us with deltas here */
127 bufptr->dataptr = &rndsetupstate;
128 /* ASLR in at least Windows, Linux, some BSDs */
129 bufptr->stkptr = &bufptr;
130 /* randomised malloc in BSD (and possibly others) */
131 bufptr->mallocptr = bufptr;
132 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
133 /* glibc pointer guard */
134 sigsetjmp(bufptr->jbuf, 1);
136 /* introduce variation (and yes, second arg MBZ for portability) */
137 mksh_TIME(bufptr->tv);
139 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
142 return ((mksh_uari_t)h);
148 kshpid = procpid = getpid();
154 static const char *empty_argv[] = {
159 isuc(const char *cx) {
166 /* uppercase a string duplicate */
167 strdupx(x, cx, ATEMP);
169 while ((*cp = ksh_toupper(*cp)))
172 /* check for UTF-8 */
173 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
176 /* free copy and out */
182 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
187 unsigned char restricted, errexit, utf_flag;
189 const char *ccp, **wp;
192 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
196 /* do things like getpgrp() et al. */
199 /* make sure argv[] is sane */
206 /* initialise permanent Area */
209 /* set up base environment */
212 /* set up global l->vars and l->funs */
215 /* Do this first so output routines (eg, errorf, shellf) can work */
218 /* determine the basename (without '-' or path) of the executable */
220 goto begin_parse_kshname;
221 while ((i = ccp[argi++])) {
234 * Turn on nohup by default. (AT&T ksh does not have a nohup
235 * option - it always sends the hup).
240 * Turn on brace expansion by default. AT&T kshs that have
241 * alternation always have it on.
243 Flag(FBRACEEXPAND) = 1;
246 * Turn on "set -x" inheritance by default.
248 Flag(FXTRACEREC) = 1;
250 /* define built-in commands and see if we were called as one */
251 ktinit(APERM, &builtins,
252 /* currently up to 51 builtins: 75% of 128 = 2^7 */
254 for (i = 0; mkshbuiltins[i].name != NULL; i++)
255 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
256 mkshbuiltins[i].func)))
257 Flag(FAS_BUILTIN) = 1;
259 if (!Flag(FAS_BUILTIN)) {
260 /* check for -T option early */
261 argi = parse_args(argv, OF_FIRSTTIME, NULL);
265 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
266 /* are we called as -sh or /bin/sh or so? */
267 if (!strcmp(ccp, "sh")) {
268 /* either also turns off braceexpand */
269 #ifdef MKSH_BINSHPOSIX
270 /* enable better POSIX conformance */
271 change_flag(FPOSIX, OF_FIRSTTIME, true);
273 #ifdef MKSH_BINSHREDUCED
274 /* enable kludge/compat mode */
275 change_flag(FSH, OF_FIRSTTIME, true);
289 /* set up variable and command dictionaries */
290 ktinit(APERM, &taliases, 0);
291 ktinit(APERM, &aliases, 0);
293 ktinit(APERM, &homedirs, 0);
296 /* define shell keywords */
301 /* initialise tty size before importing environment */
305 def_path = _PATH_DEFPATH;
308 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
309 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
314 * this is uniform across all OSes unless it
315 * breaks somewhere; don't try to optimise,
316 * e.g. add stuff for Interix or remove /usr
317 * for HURD, because e.g. Debian GNU/HURD is
318 * "keeping a regular /usr"; this is supposed
319 * to be a sane 'basic' default PATH
321 def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
325 * Set PATH to def_path (will set the path global variable).
326 * (import of environment below will probably change this setting).
329 /* setstr can't fail here */
330 setstr(vp, def_path, KSH_RETURN_ERROR);
332 #ifndef MKSH_NO_CMDLINE_EDITING
334 * Set edit mode to emacs by default, may be overridden
335 * by the environment or the user. Also, we want tab completion
336 * on in vi by default.
338 change_flag(FEMACS, OF_SPECIAL, true);
340 Flag(FVITABCOMPLETE) = 1;
344 /* import environment */
345 if (environ != NULL) {
346 wp = (const char **)environ;
347 while (*wp != NULL) {
349 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
355 typeset(initifs, 0, 0, 0, 0);
357 /* assign default shell variable values */
358 substitute(initsubs, 0);
360 /* Figure out the current working directory and set $PWD */
363 /* Try to use existing $PWD if it is valid */
364 set_current_wd((cp[0] == '/' && test_eval(NULL, TO_FILEQ, cp, ".",
367 simplify_path(current_wd);
368 /* Only set pwd if we know where we are or if it had a bogus value */
369 if (current_wd[0] || *cp)
370 /* setstr can't fail here */
371 setstr(vp, current_wd, KSH_RETURN_ERROR);
373 for (wp = initcoms; *wp != NULL; wp++) {
378 setint_n(global("OPTIND"), 1, 10);
384 safe_prompt = ksheuid ? "$ " : "# ";
386 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
387 if (!(vp->flag & ISSET) ||
388 (!ksheuid && !strchr(str_val(vp), '#')))
389 /* setstr can't fail here */
390 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
391 setint_n((vp = global("BASHPID")), 0, 10);
393 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
395 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
397 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
399 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
401 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
403 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
405 setint_n((vp = global("RANDOM")), rndsetup(), 10);
407 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
409 /* Set this before parsing arguments */
410 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
412 /* this to note if monitor is set on command line (see below) */
413 #ifndef MKSH_UNEMPLOYED
414 Flag(FMONITOR) = 127;
416 /* this to note if utf-8 mode is set on command line (see below) */
419 if (!Flag(FAS_BUILTIN)) {
420 argi = parse_args(argv, OF_CMDLINE, NULL);
425 /* process this later only, default to off (hysterical raisins) */
429 if (Flag(FAS_BUILTIN)) {
430 /* auto-detect from environment variables, always */
432 } else if (Flag(FCOMMAND)) {
433 s = pushs(SSTRINGCMDLINE, ATEMP);
434 if (!(s->start = s->str = argv[argi++]))
435 errorf("%s %s", "-c", "requires an argument");
437 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
442 s->flags |= SF_MAYEXEC;
444 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
445 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
446 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
450 kshname = argv[argi++];
451 } else if (argi < argc && !Flag(FSTDIN)) {
452 s = pushs(SFILE, ATEMP);
453 s->file = argv[argi++];
454 s->u.shf = shf_open(s->file, O_RDONLY, 0,
455 SHF_MAPHI | SHF_CLEXEC);
456 if (s->u.shf == NULL) {
457 shl_stdout_ok = false;
458 warningf(true, "%s: %s", s->file, cstrerror(errno));
459 /* mandated by SUSv4 */
466 s = pushs(SSTDIN, ATEMP);
468 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
470 if (isatty(0) && isatty(2)) {
471 Flag(FTALKING) = Flag(FTALKING_I) = 1;
472 /* The following only if isatty(0) */
474 s->u.shf->flags |= SHF_INTERRUPT;
479 /* this bizarreness is mandated by POSIX */
480 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
484 /* initialise job control */
486 /* do this after j_init() which calls tty_init_state() */
487 if (Flag(FTALKING)) {
489 #ifndef MKSH_ASSUME_UTF8
490 /* auto-detect from locale or environment */
492 #else /* this may not be an #elif */
496 /* always disable UTF-8 (for interactive) */
501 #ifndef MKSH_NO_CMDLINE_EDITING
507 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
508 setsig(&sigtraps[SIGWINCH], x_sigwinch,
509 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
513 if (Flag(FAS_BUILTIN)) {
518 l->argc = argc - argi;
520 * allocate a new array because otherwise, when we modify
521 * it in-place, ps(1) output changes; the meaning of argc
522 * here is slightly different as it excludes kshname, and
523 * we add a trailing NULL sentinel as well
525 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
526 l->argv[0] = kshname;
527 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
528 l->argv[l->argc + 1] = NULL;
532 /* divine the initial state of the utf8-mode Flag */
536 /* auto-detect from locale or environment */
538 #if HAVE_SETLOCALE_CTYPE
539 ccp = setlocale(LC_CTYPE, "");
540 #if HAVE_LANGINFO_CODESET
542 ccp = nl_langinfo(CODESET);
549 /* auto-detect from environment */
551 /* these were imported from environ earlier */
553 ccp = str_val(global("LC_ALL"));
555 ccp = str_val(global("LC_CTYPE"));
557 ccp = str_val(global("LANG"));
561 /* not set on command line, not FTALKING */
575 /* Disable during .profile/ENV reading */
576 restricted = Flag(FRESTRICTED);
577 Flag(FRESTRICTED) = 0;
578 errexit = Flag(FERREXIT);
582 * Do this before profile/$ENV so that if it causes problems in them,
583 * user will know why things broke.
585 if (!current_wd[0] && Flag(FTALKING))
586 warningf(false, "can't determine current directory");
589 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
590 if (!Flag(FPRIVILEGED)) {
592 include(substitute("$HOME/.profile", 0), 0, NULL, true);
593 if (Flag(FTALKING)) {
594 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
597 include(cp, 0, NULL, true);
600 include(MKSH_SUID_PROFILE, 0, NULL, true);
601 /* turn off -p if not set explicitly */
602 if (Flag(FPRIVILEGED) != 1)
603 change_flag(FPRIVILEGED, OF_INTERNAL, false);
607 shcomexec(restr_com);
608 /* After typeset command... */
609 Flag(FRESTRICTED) = 1;
611 Flag(FERREXIT) = errexit;
613 if (Flag(FTALKING) && s)
626 /* this indirection barrier reduces stack usage during normal operation */
629 main(int argc, const char *argv[])
635 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
636 if (Flag(FAS_BUILTIN)) {
637 rv = shcomexec(l->argv);
647 include(const char *name, int argc, const char **argv, bool intr_ok)
649 Source *volatile s = NULL;
651 const char **volatile old_argv;
652 volatile int old_argc;
655 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
660 old_argv = e->loc->argv;
661 old_argc = e->loc->argc;
667 if ((i = kshsetjmp(e->jbuf))) {
668 quitenv(s ? s->u.shf : NULL);
670 e->loc->argv = old_argv;
671 e->loc->argc = old_argc;
677 return (exstat & 0xFF);
680 * intr_ok is set if we are including .profile or $ENV.
681 * If user ^Cs out, we don't want to kill the shell...
683 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
692 internal_errorf("%s %d", "include", i);
700 s = pushs(SFILE, ATEMP);
702 strdupx(s->file, name, ATEMP);
706 e->loc->argv = old_argv;
707 e->loc->argc = old_argc;
709 /* & 0xff to ensure value not -1 */
713 /* spawn a command into a shell optionally keeping track of the line number */
715 command(const char *comm, int line)
719 s = pushs(SSTRING, ATEMP);
720 s->start = s->str = comm;
722 return (shell(s, false));
726 * run the commands from the input source, returning status.
729 shell(Source * volatile s, volatile bool toplevel)
732 volatile bool wastty = tobool(s->flags & SF_TTY);
733 volatile uint8_t attempts = 13;
734 volatile bool interactive = Flag(FTALKING) && toplevel;
735 volatile bool sfirst = true;
736 Source *volatile old_source = source;
742 switch ((i = kshsetjmp(e->jbuf))) {
746 /* we get here if SIGINT not caught or ignored */
753 * Reset any eof that was read as part of a
756 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
759 * Used by exit command to get back to
760 * top level shell. Kind of strange since
761 * interactive is set if we are reading from
762 * a tty, but to have stopped jobs, one only
763 * needs FMONITOR set (not FTALKING/SF_TTY)...
765 /* toss any input we have so far */
766 yyrecursive_pop(true);
767 s->start = s->str = null;
784 internal_errorf("%s %d", "shell", i);
787 while (/* CONSTCOND */ 1) {
791 if (s->next == NULL) {
795 s->flags &= ~SF_ECHO;
801 t = compile(s, sfirst);
805 if (t->type == TEOF) {
806 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
807 shellf("Use 'exit' to leave mksh\n");
809 } else if (wastty && !really_exit &&
810 j_stopped_running()) {
815 * this for POSIX which says EXIT traps
816 * shall be taken in the environment
817 * immediately after the last command
824 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
825 t->u.evalflags |= DOTCOMEXEC;
826 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
827 exstat = execute(t, 0, NULL) & 0xFF;
829 if (t->type != TEOF && interactive && really_exit)
837 return (exstat & 0xFF);
840 /* return to closest error handler or shell(), exit if none found */
841 /* note: i MUST NOT be 0 */
846 * This is a kludge. We need to restore everything that was
847 * changed in the new environment, see cid 1005090337C7A669439
848 * and 10050903386452ACBF1, but fail to even save things most of
849 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
850 * which needs to be restored thus (related to Debian #696823).
851 * We did not save the shell flags, so we use a special or'd
852 * value here... this is mostly to clean up behind *other*
853 * callers of unwind(LERROR) here; exec.c has the regular case.
855 if (Flag(FERREXIT) & 0x80) {
856 /* GNU bash does not run this trapsig */
858 Flag(FERREXIT) &= ~0x80;
861 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
862 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
863 sigtraps[ksh_SIGEXIT].trap &&
864 (!Flag(FTALKING) || Flag(FERREXIT)))) {
866 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
869 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
871 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
876 while (/* CONSTCOND */ 1) {
883 kshlongjmp(e->jbuf, i);
887 e->flags |= EF_FAKE_SIGDIE;
902 * struct env includes ALLOC_ITEM for alignment constraints
903 * so first get the actually used memory, then assign it
905 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
906 /* undo what alloc() did to the malloc result address */
907 ep = (void *)(cp - ALLOC_SIZE);
908 /* initialise public members of struct env (not the ALLOC_ITEM) */
914 ep->yyrecursive_statep = NULL;
917 /* jump buffer is invalid because flags == 0 */
922 quitenv(struct shf *shf)
928 yyrecursive_pop(true);
929 while (ep->oenv && ep->oenv->loc != ep->loc)
931 if (ep->savefd != NULL) {
932 for (fd = 0; fd < NUFILE; fd++)
933 /* if ep->savefd[fd] < 0, means fd was closed */
935 restfd(fd, ep->savefd[fd]);
937 /* Clear any write errors */
938 shf_reopen(2, SHF_WR, shl_out);
941 * Bottom of the stack.
942 * Either main shell is exiting or cleanup_parents_env() was called.
944 if (ep->oenv == NULL) {
949 if (ep->type == E_NONE) {
950 /* Main shell exiting? */
951 #if HAVE_PERSISTENT_HISTORY
956 if (ep->flags & EF_FAKE_SIGDIE) {
957 int sig = (exstat & 0xFF) - 128;
960 * ham up our death a bit (AT&T ksh
961 * only seems to do this for SIGTERM)
962 * Don't do it for SIGQUIT, since we'd
965 if ((sig == SIGINT || sig == SIGTERM) &&
966 (kshpgrp == kshpid)) {
967 setsig(&sigtraps[sig], SIG_DFL,
968 SS_RESTORE_CURR | SS_FORCE);
977 #ifndef MKSH_NO_CMDLINE_EDITING
980 #ifndef MKSH_NOPROSPECTOFWORK
981 /* block at least SIGCHLD during/after afreeall */
982 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
985 for (fd = 3; fd < NUFILE; fd++)
986 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1001 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1003 afree(cp + ALLOC_SIZE, ATEMP);
1006 /* Called after a fork to cleanup stuff left over from parents environment */
1008 cleanup_parents_env(void)
1016 * Don't clean up temporary files - parent will probably need them.
1017 * Also, can't easily reclaim memory since variables, etc. could be
1021 /* close all file descriptors hiding in savefd */
1022 for (ep = e; ep; ep = ep->oenv) {
1024 for (fd = 0; fd < NUFILE; fd++)
1025 if (ep->savefd[fd] > 0)
1026 close(ep->savefd[fd]);
1027 afree(ep->savefd, &ep->area);
1031 if (ep->type != E_NONE)
1040 /* Called just before an execve cleanup stuff temporary files */
1042 cleanup_proc_env(void)
1046 for (ep = e; ep; ep = ep->oenv)
1047 remove_temps(ep->temps);
1050 /* remove temp files and free ATEMP Area */
1056 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1061 remove_temps(e->temps);
1067 remove_temps(struct temp *tp)
1069 for (; tp != NULL; tp = tp->next)
1070 if (tp->pid == procpid)
1075 * Initialise tty_fd. Used for tracking the size of the terminal,
1076 * saving/resetting tty modes upon forground job completion, and
1077 * for setting up the tty process group. Return values:
1078 * 0 = got controlling tty
1079 * 1 = got terminal but no controlling tty
1080 * 2 = cannot find a terminal
1082 * 4 = cannot make fd close-on-exec
1083 * An existing tty_fd is cached if no "better" one could be found,
1084 * i.e. if tty_devtty was already set or the new would not set it.
1089 int fd, rv, eno = 0;
1090 bool do_close = false, is_devtty = true;
1093 /* already got a tty which is /dev/tty */
1098 /*XXX imake style */
1100 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1105 if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1112 /* already got a non-devtty one */
1118 if (isatty((fd = 0)) || isatty((fd = 2)))
1120 /* cannot find one */
1122 /* assert: do_close == false */
1126 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1131 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1138 tty_devtty = is_devtty;
1147 /* A shell error occurred (eg, syntax error, etc.) */
1149 #define VWARNINGF_ERRORPREFIX 1
1150 #define VWARNINGF_FILELINE 2
1151 #define VWARNINGF_BUILTIN 4
1152 #define VWARNINGF_INTERNAL 8
1154 static void vwarningf(unsigned int, const char *, va_list)
1155 MKSH_A_FORMAT(__printf__, 2, 0);
1158 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1161 if (flags & VWARNINGF_INTERNAL)
1162 shf_fprintf(shl_out, "internal error: ");
1163 if (flags & VWARNINGF_ERRORPREFIX)
1164 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1165 if ((flags & VWARNINGF_BUILTIN) &&
1166 /* not set when main() calls parse_args() */
1167 builtin_argv0 && builtin_argv0 != kshname)
1168 shf_fprintf(shl_out, "%s: ", builtin_argv0);
1169 shf_vfprintf(shl_out, fmt, ap);
1170 shf_putchar('\n', shl_out);
1176 errorfx(int rc, const char *fmt, ...)
1182 /* debugging: note that stdout not valid */
1183 shl_stdout_ok = false;
1186 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1192 errorf(const char *fmt, ...)
1198 /* debugging: note that stdout not valid */
1199 shl_stdout_ok = false;
1202 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1207 /* like errorf(), but no unwind is done */
1209 warningf(bool fileline, const char *fmt, ...)
1214 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1220 * Used by built-in utilities to prefix shell and utility name to message
1221 * (also unwinds environments for special builtins).
1224 bi_errorf(const char *fmt, ...)
1228 /* debugging: note that stdout not valid */
1229 shl_stdout_ok = false;
1234 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1235 VWARNINGF_BUILTIN, fmt, va);
1239 * POSIX special builtins and ksh special builtins cause
1240 * non-interactive shells to exit.
1241 * XXX odd use of KEEPASN; also may not want LERROR here
1243 if (builtin_flag & SPEC_BI) {
1244 builtin_argv0 = NULL;
1249 /* Called when something that shouldn't happen does */
1251 internal_errorf(const char *fmt, ...)
1256 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1262 internal_warningf(const char *fmt, ...)
1267 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1271 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1273 error_prefix(bool fileline)
1275 /* Avoid foo: foo[2]: ... */
1276 if (!fileline || !source || !source->file ||
1277 strcmp(source->file, kshname) != 0)
1278 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1279 if (fileline && source && source->file != NULL) {
1280 shf_fprintf(shl_out, "%s[%d]: ", source->file,
1281 source->errline > 0 ? source->errline : source->line);
1282 source->errline = 0;
1286 /* printf to shl_out (stderr) with flush */
1288 shellf(const char *fmt, ...)
1293 /* shl_out may not be set up yet... */
1296 shf_vfprintf(shl_out, fmt, va);
1301 /* printf to shl_stdout (stdout) */
1303 shprintf(const char *fmt, ...)
1308 internal_errorf("shl_stdout not valid");
1310 shf_vfprintf(shl_stdout, fmt, va);
1314 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1320 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1330 struct shf shf_iob[NSHF_IOB];
1339 /* force buffer allocation */
1340 shf_fdopen(1, SHF_WR, shl_stdout);
1341 shf_fdopen(2, SHF_WR, shl_out);
1342 shf_fdopen(2, SHF_WR, shl_xtrace);
1344 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1345 if ((lfp = getenv("HOME")) == NULL || *lfp != '/')
1346 errorf("cannot get home directory");
1347 lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1350 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1351 errorf("cannot open debug output file %s", lfp);
1352 if (shl_dbg_fd < FDBASE) {
1355 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1357 if ((shl_dbg_fd = nfd) == -1)
1358 errorf("cannot dup debug output file");
1360 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1361 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1367 /* A dup2() with error checking */
1369 ksh_dup2(int ofd, int nfd, bool errok)
1373 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1374 errorf("too many files open in shell");
1377 /*XXX imake style */
1379 fcntl(nfd, F_SETFD, 0);
1386 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1387 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1394 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1397 if (nfd < 0 || nfd > SHRT_MAX)
1398 errorf("too many files open in shell");
1399 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1400 return ((short)nfd);
1404 restfd(int fd, int ofd)
1407 shf_flush(&shf_iob[/* fd */ 2]);
1409 /* original fd closed */
1411 else if (fd != ofd) {
1412 /*XXX: what to do if this dup fails? */
1413 ksh_dup2(ofd, fd, true);
1424 errorf("can't create pipe - try again");
1425 pv[0] = savefd(lpv[0]);
1426 if (pv[0] != lpv[0])
1428 pv[1] = savefd(lpv[1]);
1429 if (pv[1] != lpv[1])
1441 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1442 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1445 check_fd(const char *name, int mode, const char **emsgp)
1449 if (name[0] == 'p' && !name[1])
1450 return (coproc_getfd(mode, emsgp));
1451 for (fd = 0; ksh_isdigit(*name); ++name)
1452 fd = (fd * 10) + *name - '0';
1453 if (*name || fd >= FDBASE) {
1455 *emsgp = "illegal file descriptor name";
1458 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1460 *emsgp = "bad file descriptor";
1465 * X_OK is a kludge to disable this check for dups (x<&1):
1466 * historical shells never did this check (XXX don't know what
1467 * POSIX has to say).
1469 if (!(mode & X_OK) && fl != O_RDWR && (
1470 ((mode & R_OK) && fl != O_RDONLY) ||
1471 ((mode & W_OK) && fl != O_WRONLY))) {
1473 *emsgp = (fl == O_WRONLY) ?
1474 "fd not open for reading" :
1475 "fd not open for writing";
1481 /* Called once from main */
1485 coproc.read = coproc.readw = coproc.write = -1;
1490 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1492 coproc_read_close(int fd)
1494 if (coproc.read >= 0 && fd == coproc.read) {
1495 coproc_readw_close(fd);
1502 * Called by c_read() and by iosetup() to close the other side of the
1503 * read pipe, so reads will actually terminate.
1506 coproc_readw_close(int fd)
1508 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1509 close(coproc.readw);
1515 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1516 * when co-process input is dup'd
1519 coproc_write_close(int fd)
1521 if (coproc.write >= 0 && fd == coproc.write) {
1522 close(coproc.write);
1528 * Called to check for existence of/value of the co-process file descriptor.
1529 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1532 coproc_getfd(int mode, const char **emsgp)
1534 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1539 *emsgp = "no coprocess";
1544 * called to close file descriptors related to the coprocess (if any)
1545 * Should be called with SIGCHLD blocked.
1548 coproc_cleanup(int reuse)
1550 /* This to allow co-processes to share output pipe */
1551 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1552 if (coproc.read >= 0) {
1556 if (coproc.readw >= 0) {
1557 close(coproc.readw);
1561 if (coproc.write >= 0) {
1562 close(coproc.write);
1568 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1577 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1578 /* add "/shXXXXXX.tmp" plus NUL */
1580 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1581 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1587 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1593 cp += offsetof(struct temp, tffn[0]);
1594 memcpy(cp, dir, len);
1596 memcpy(cp, "/shXXXXXX.tmp", 14);
1597 /* point to the first of six Xes */
1599 /* generate random part of filename */
1603 cp[++len] = i < 26 ? 'a' + i : '0' + i - 26;
1606 /* cyclically attempt to open a temporary file */
1607 while ((i = open(tp->tffn, O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1609 if (errno != EEXIST)
1611 /* count down from z to a then from 9 to 0 */
1612 while (cp[len] == '0')
1619 /* do another cycle */
1622 if (type == TT_FUNSUB) {
1623 /* map us high and mark as close-on-exec */
1624 if ((j = savefd(i)) != i) {
1629 /* operation mode for the shf */
1634 /* shf_fdopen cannot fail, so no fd leak */
1635 tp->shf = shf_fdopen(i, j, NULL);
1644 * We use a similar collision resolution algorithm as Python 2.5.4
1645 * but with a slightly tweaked implementation written from scratch.
1648 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1649 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1651 static void tgrow(struct table *);
1652 static int tnamecmp(const void *, const void *);
1655 tgrow(struct table *tp)
1657 size_t i, j, osize, mask, perturb;
1658 struct tbl *tblp, **pp;
1659 struct tbl **ntblp, **otblp = tp->tbls;
1661 if (tp->tshift > 29)
1662 internal_errorf("hash table size limit reached");
1664 /* calculate old size, new shift and new size */
1665 osize = (size_t)1 << (tp->tshift++);
1668 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1669 /* multiplication cannot overflow: alloc2 checked that */
1670 memset(ntblp, 0, i * sizeof(struct tbl *));
1672 /* table can get very full when reaching its size limit */
1673 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1674 /* but otherwise, only 75% */
1681 for (i = 0; i < osize; i++)
1682 if ((tblp = otblp[i]) != NULL) {
1683 if ((tblp->flag & DEFINED)) {
1684 /* search for free hash table slot */
1685 j = perturb = tblp->ua.hval;
1686 goto find_first_empty_slot;
1687 find_next_empty_slot:
1688 j = (j << 2) + j + perturb + 1;
1689 perturb >>= PERTURB_SHIFT;
1690 find_first_empty_slot:
1691 pp = &ntblp[j & mask];
1693 goto find_next_empty_slot;
1694 /* found an empty hash table slot */
1697 } else if (!(tblp->flag & FINUSE)) {
1698 afree(tblp, tp->areap);
1701 afree(otblp, tp->areap);
1705 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1709 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1710 initshift : INIT_TBLSHIFT) - 1;
1714 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1716 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1718 size_t j, perturb, mask;
1719 struct tbl **pp, *p;
1721 mask = ((size_t)1 << (tp->tshift)) - 1;
1722 /* search for hash table slot matching name */
1724 goto find_first_slot;
1726 j = (j << 2) + j + perturb + 1;
1727 perturb >>= PERTURB_SHIFT;
1729 pp = &tp->tbls[j & mask];
1730 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1731 strcmp(p->name, name)))
1732 goto find_next_slot;
1733 /* p == NULL if not found, correct found entry otherwise */
1739 /* table, name (key) to enter, hash(n) */
1741 ktenter(struct table *tp, const char *n, uint32_t h)
1743 struct tbl **pp, *p;
1747 if ((p = ktscan(tp, n, h, &pp)))
1750 if (tp->nfree == 0) {
1756 /* create new tbl entry */
1758 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1759 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1762 p->areap = tp->areap;
1766 memcpy(p->name, n, len);
1768 /* enter in tp->tbls */
1775 ktwalk(struct tstate *ts, struct table *tp)
1777 ts->left = (size_t)1 << (tp->tshift);
1778 ts->next = tp->tbls;
1782 ktnext(struct tstate *ts)
1784 while (--ts->left >= 0) {
1785 struct tbl *p = *ts->next++;
1786 if (p != NULL && (p->flag & DEFINED))
1793 tnamecmp(const void *p1, const void *p2)
1795 const struct tbl *a = *((const struct tbl * const *)p1);
1796 const struct tbl *b = *((const struct tbl * const *)p2);
1798 return (strcmp(a->name, b->name));
1802 ktsort(struct table *tp)
1805 struct tbl **p, **sp, **dp;
1808 * since the table is never entirely full, no need to reserve
1809 * additional space for the trailing NULL appended below
1811 i = (size_t)1 << (tp->tshift);
1812 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1813 sp = tp->tbls; /* source */
1816 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1817 ((*dp)->flag & ARRAY)))
1819 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1826 x_sigwinch(int sig MKSH_A_UNUSED)
1828 /* this runs inside interrupt context, with errno saved */
1836 DF(const char *fmt, ...)
1842 mksh_lockfd(shl_dbg_fd);
1844 timet2mjd(&mjd, tv.tv_sec);
1845 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1846 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1847 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1848 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1849 va_start(args, fmt);
1850 shf_vfprintf(shl_dbg, fmt, args);
1852 shf_putc('\n', shl_dbg);
1854 mksh_unlkfd(shl_dbg_fd);
1859 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1864 mksh_tcget(fd, ocb);
1870 cb.c_iflag &= ~(ISTRIP);
1871 cb.c_lflag &= ~(ICANON) | ECHO;
1873 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1874 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1876 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1877 /* OSF/1 processes lnext when ~icanon */
1878 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1880 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1881 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1882 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1887 mksh_tcset(fd, &cb);