1 /* $OpenBSD: main.c,v 1.57 2015/09/10 22:48:58 nicm Exp $ */
2 /* $OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $ */
3 /* $OpenBSD: io.c,v 1.26 2015/09/11 08:00:27 guenther Exp $ */
4 /* $OpenBSD: table.c,v 1.16 2015/09/01 13:12:31 tedu Exp $ */
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
8 * 2011, 2012, 2013, 2014, 2015
9 * mirabilos <m@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.306 2015/10/09 21:36:57 tg Exp $");
39 extern char **environ;
42 #define MKSHRC_PATH "~/.mkshrc"
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR MKSH_UNIXROOT "/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", "SHELL", NULL,
67 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
69 "integer=\\typeset -i",
71 /* not "alias -t --": hash -r needs to work */
72 "hash=\\builtin alias -t",
73 "type=\\builtin whence -v",
74 "autoload=\\typeset -fu",
75 "functions=\\typeset -f",
76 "history=\\builtin fc -l",
77 "nameref=\\typeset -n",
79 "r=\\builtin fc -e -",
82 /* this is what AT&T ksh seems to track, with the addition of emacs */
84 Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
85 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
89 static const char *restr_com[] = {
90 Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
93 static bool initio_done;
95 /* top-level parsing and execution environment */
96 static struct env env;
104 ALLOC_ITEM alloc_INT;
105 void *dataptr, *stkptr, *mallocptr;
106 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
113 cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
115 /* clear the allocated space, for valgrind */
116 memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
118 /* undo what alloc() did to the malloc result address */
119 bufptr = (void *)(cp - ALLOC_SIZE);
120 /* PIE or something similar provides us with deltas here */
121 bufptr->dataptr = &rndsetupstate;
122 /* ASLR in at least Windows, Linux, some BSDs */
123 bufptr->stkptr = &bufptr;
124 /* randomised malloc in BSD (and possibly others) */
125 bufptr->mallocptr = bufptr;
126 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
127 /* glibc pointer guard */
128 sigsetjmp(bufptr->jbuf, 1);
130 /* introduce variation (and yes, second arg MBZ for portability) */
131 mksh_TIME(bufptr->tv);
133 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
136 return ((mksh_uari_t)h);
142 kshpid = procpid = getpid();
148 static const char *empty_argv[] = {
153 isuc(const char *cx) {
160 /* uppercase a string duplicate */
161 strdupx(x, cx, ATEMP);
163 while ((*cp = ksh_toupper(*cp)))
166 /* check for UTF-8 */
167 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
170 /* free copy and out */
176 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
181 unsigned char restricted_shell, errexit, utf_flag;
183 const char *ccp, **wp;
186 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
191 for (i = 0; i < 3; ++i)
193 setmode(i, O_BINARY);
196 /* do things like getpgrp() et al. */
199 /* make sure argv[] is sane, for weird OSes */
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 54 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" MKSH_EXE_EXT)) {
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 = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
322 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
323 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
324 MKSH_UNIXROOT "/usr/sbin";
328 * Set PATH to def_path (will set the path global variable).
329 * (import of environment below will probably change this setting).
332 /* setstr can't fail here */
333 setstr(vp, def_path, KSH_RETURN_ERROR);
335 #ifndef MKSH_NO_CMDLINE_EDITING
337 * Set edit mode to emacs by default, may be overridden
338 * by the environment or the user. Also, we want tab completion
339 * on in vi by default.
341 change_flag(FEMACS, OF_SPECIAL, true);
343 Flag(FVITABCOMPLETE) = 1;
347 /* import environment */
348 if (environ != NULL) {
349 wp = (const char **)environ;
350 while (*wp != NULL) {
352 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
358 typeset(initifs, 0, 0, 0, 0);
360 /* assign default shell variable values */
361 substitute(initsubs, 0);
363 /* Figure out the current working directory and set $PWD */
366 /* Try to use existing $PWD if it is valid */
367 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp, ".",
370 simplify_path(current_wd);
371 /* Only set pwd if we know where we are or if it had a bogus value */
372 if (current_wd[0] || *cp)
373 /* setstr can't fail here */
374 setstr(vp, current_wd, KSH_RETURN_ERROR);
376 for (wp = initcoms; *wp != NULL; wp++) {
381 setint_n(global("OPTIND"), 1, 10);
387 safe_prompt = ksheuid ? "$ " : "# ";
389 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
390 if (!(vp->flag & ISSET) ||
391 (!ksheuid && !strchr(str_val(vp), '#')))
392 /* setstr can't fail here */
393 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
394 setint_n((vp = global("BASHPID")), 0, 10);
396 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
398 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
400 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
402 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
404 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
406 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
408 setint_n((vp = global("RANDOM")), rndsetup(), 10);
410 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
412 /* Set this before parsing arguments */
413 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
415 /* this to note if monitor is set on command line (see below) */
416 #ifndef MKSH_UNEMPLOYED
417 Flag(FMONITOR) = 127;
419 /* this to note if utf-8 mode is set on command line (see below) */
422 if (!Flag(FAS_BUILTIN)) {
423 argi = parse_args(argv, OF_CMDLINE, NULL);
428 /* process this later only, default to off (hysterical raisins) */
432 if (Flag(FAS_BUILTIN)) {
433 /* auto-detect from environment variables, always */
435 } else if (Flag(FCOMMAND)) {
436 s = pushs(SSTRINGCMDLINE, ATEMP);
437 if (!(s->start = s->str = argv[argi++]))
438 errorf("%s %s", "-c", "requires an argument");
440 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
445 s->flags |= SF_MAYEXEC;
447 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
448 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
449 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
453 kshname = argv[argi++];
454 } else if (argi < argc && !Flag(FSTDIN)) {
455 s = pushs(SFILE, ATEMP);
458 * A bug in OS/2 extproc (like shebang) handling makes
459 * it not pass the full pathname of a script, so we need
460 * to search for it. This changes the behaviour of a
461 * simple "mksh foo", but can't be helped.
463 s->file = search_path(argv[argi++], path, X_OK, NULL);
464 if (!s->file || !*s->file)
465 s->file = argv[argi - 1];
467 s->file = argv[argi++];
469 s->u.shf = shf_open(s->file, O_RDONLY, 0,
470 SHF_MAPHI | SHF_CLEXEC);
471 if (s->u.shf == NULL) {
472 shl_stdout_ok = false;
473 warningf(true, "%s: %s", s->file, cstrerror(errno));
474 /* mandated by SUSv4 */
481 s = pushs(SSTDIN, ATEMP);
483 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
485 if (isatty(0) && isatty(2)) {
486 Flag(FTALKING) = Flag(FTALKING_I) = 1;
487 /* The following only if isatty(0) */
489 s->u.shf->flags |= SHF_INTERRUPT;
494 /* this bizarreness is mandated by POSIX */
495 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
499 /* initialise job control */
501 /* do this after j_init() which calls tty_init_state() */
502 if (Flag(FTALKING)) {
504 #ifndef MKSH_ASSUME_UTF8
505 /* auto-detect from locale or environment */
507 #else /* this may not be an #elif */
511 /* always disable UTF-8 (for interactive) */
516 #ifndef MKSH_NO_CMDLINE_EDITING
522 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
523 setsig(&sigtraps[SIGWINCH], x_sigwinch,
524 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
528 if (Flag(FAS_BUILTIN)) {
533 l->argc = argc - argi;
535 * allocate a new array because otherwise, when we modify
536 * it in-place, ps(1) output changes; the meaning of argc
537 * here is slightly different as it excludes kshname, and
538 * we add a trailing NULL sentinel as well
540 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
541 l->argv[0] = kshname;
542 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
543 l->argv[l->argc + 1] = NULL;
547 /* divine the initial state of the utf8-mode Flag */
551 /* auto-detect from locale or environment */
553 #if HAVE_SETLOCALE_CTYPE
554 ccp = setlocale(LC_CTYPE, "");
555 #if HAVE_LANGINFO_CODESET
557 ccp = nl_langinfo(CODESET);
564 /* auto-detect from environment */
566 /* these were imported from environ earlier */
568 ccp = str_val(global("LC_ALL"));
570 ccp = str_val(global("LC_CTYPE"));
572 ccp = str_val(global("LANG"));
576 /* not set on command line, not FTALKING */
590 /* Disable during .profile/ENV reading */
591 restricted_shell = Flag(FRESTRICTED);
592 Flag(FRESTRICTED) = 0;
593 errexit = Flag(FERREXIT);
597 * Do this before profile/$ENV so that if it causes problems in them,
598 * user will know why things broke.
600 if (!current_wd[0] && Flag(FTALKING))
601 warningf(false, "can't determine current directory");
604 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
605 if (!Flag(FPRIVILEGED)) {
607 include(substitute("$HOME/.profile", 0), 0, NULL, true);
608 if (Flag(FTALKING)) {
609 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
612 include(cp, 0, NULL, true);
615 include(MKSH_SUID_PROFILE, 0, NULL, true);
616 /* turn off -p if not set explicitly */
617 if (Flag(FPRIVILEGED) != 1)
618 change_flag(FPRIVILEGED, OF_INTERNAL, false);
621 if (restricted_shell) {
622 shcomexec(restr_com);
623 /* After typeset command... */
624 Flag(FRESTRICTED) = 1;
626 Flag(FERREXIT) = errexit;
628 if (Flag(FTALKING) && s)
641 /* this indirection barrier reduces stack usage during normal operation */
644 main(int argc, const char *argv[])
650 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
651 if (Flag(FAS_BUILTIN)) {
652 rv = shcomexec(l->argv);
662 include(const char *name, int argc, const char **argv, bool intr_ok)
664 Source *volatile s = NULL;
666 const char **volatile old_argv;
667 volatile int old_argc;
670 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
675 old_argv = e->loc->argv;
676 old_argc = e->loc->argc;
682 if ((i = kshsetjmp(e->jbuf))) {
683 quitenv(s ? s->u.shf : NULL);
685 e->loc->argv = old_argv;
686 e->loc->argc = old_argc;
692 return (exstat & 0xFF);
695 * intr_ok is set if we are including .profile or $ENV.
696 * If user ^Cs out, we don't want to kill the shell...
698 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
707 internal_errorf("%s %d", "include", i);
715 s = pushs(SFILE, ATEMP);
717 strdupx(s->file, name, ATEMP);
721 e->loc->argv = old_argv;
722 e->loc->argc = old_argc;
724 /* & 0xff to ensure value not -1 */
728 /* spawn a command into a shell optionally keeping track of the line number */
730 command(const char *comm, int line)
734 s = pushs(SSTRING, ATEMP);
735 s->start = s->str = comm;
737 return (shell(s, false));
741 * run the commands from the input source, returning status.
744 shell(Source * volatile s, volatile bool toplevel)
747 volatile bool wastty = tobool(s->flags & SF_TTY);
748 volatile uint8_t attempts = 13;
749 volatile bool interactive = Flag(FTALKING) && toplevel;
750 volatile bool sfirst = true;
751 Source *volatile old_source = source;
757 switch ((i = kshsetjmp(e->jbuf))) {
761 /* we get here if SIGINT not caught or ignored */
768 * Reset any eof that was read as part of a
771 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
774 * Used by exit command to get back to
775 * top level shell. Kind of strange since
776 * interactive is set if we are reading from
777 * a tty, but to have stopped jobs, one only
778 * needs FMONITOR set (not FTALKING/SF_TTY)...
780 /* toss any input we have so far */
781 yyrecursive_pop(true);
782 s->start = s->str = null;
799 internal_errorf("%s %d", "shell", i);
802 while (/* CONSTCOND */ 1) {
806 if (s->next == NULL) {
810 s->flags &= ~SF_ECHO;
816 t = compile(s, sfirst);
818 histsave(&s->line, NULL, HIST_FLUSH, true);
822 if (t->type == TEOF) {
823 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
824 shellf("Use 'exit' to leave mksh\n");
826 } else if (wastty && !really_exit &&
827 j_stopped_running()) {
832 * this for POSIX which says EXIT traps
833 * shall be taken in the environment
834 * immediately after the last command
841 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
842 t->u.evalflags |= DOTCOMEXEC;
843 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
844 exstat = execute(t, 0, NULL) & 0xFF;
846 if (t->type != TEOF && interactive && really_exit)
854 return (exstat & 0xFF);
857 /* return to closest error handler or shell(), exit if none found */
858 /* note: i MUST NOT be 0 */
863 * This is a kludge. We need to restore everything that was
864 * changed in the new environment, see cid 1005090337C7A669439
865 * and 10050903386452ACBF1, but fail to even save things most of
866 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
867 * which needs to be restored thus (related to Debian #696823).
868 * We did not save the shell flags, so we use a special or'd
869 * value here... this is mostly to clean up behind *other*
870 * callers of unwind(LERROR) here; exec.c has the regular case.
872 if (Flag(FERREXIT) & 0x80) {
873 /* GNU bash does not run this trapsig */
875 Flag(FERREXIT) &= ~0x80;
878 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
879 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
880 sigtraps[ksh_SIGEXIT].trap &&
881 (!Flag(FTALKING) || Flag(FERREXIT)))) {
883 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
886 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
888 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
893 while (/* CONSTCOND */ 1) {
900 kshlongjmp(e->jbuf, i);
904 e->flags |= EF_FAKE_SIGDIE;
909 * quitenv() may have reclaimed the memory
910 * used by source which will end badly when
911 * we jump to a function that expects it to
926 * struct env includes ALLOC_ITEM for alignment constraints
927 * so first get the actually used memory, then assign it
929 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
930 /* undo what alloc() did to the malloc result address */
931 ep = (void *)(cp - ALLOC_SIZE);
932 /* initialise public members of struct env (not the ALLOC_ITEM) */
938 ep->yyrecursive_statep = NULL;
941 /* jump buffer is invalid because flags == 0 */
946 quitenv(struct shf *shf)
952 yyrecursive_pop(true);
953 while (ep->oenv && ep->oenv->loc != ep->loc)
955 if (ep->savefd != NULL) {
956 for (fd = 0; fd < NUFILE; fd++)
957 /* if ep->savefd[fd] < 0, means fd was closed */
959 restfd(fd, ep->savefd[fd]);
961 /* Clear any write errors */
962 shf_reopen(2, SHF_WR, shl_out);
965 * Bottom of the stack.
966 * Either main shell is exiting or cleanup_parents_env() was called.
968 if (ep->oenv == NULL) {
973 if (ep->type == E_NONE) {
974 /* Main shell exiting? */
975 #if HAVE_PERSISTENT_HISTORY
980 if (ep->flags & EF_FAKE_SIGDIE) {
981 int sig = (exstat & 0xFF) - 128;
984 * ham up our death a bit (AT&T ksh
985 * only seems to do this for SIGTERM)
986 * Don't do it for SIGQUIT, since we'd
989 if ((sig == SIGINT || sig == SIGTERM) &&
990 (kshpgrp == kshpid)) {
991 setsig(&sigtraps[sig], SIG_DFL,
992 SS_RESTORE_CURR | SS_FORCE);
1001 #ifndef MKSH_NO_CMDLINE_EDITING
1004 #ifndef MKSH_NOPROSPECTOFWORK
1005 /* block at least SIGCHLD during/after afreeall */
1006 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1009 for (fd = 3; fd < NUFILE; fd++)
1010 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1017 exit(exstat & 0xFF);
1025 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1027 afree(cp + ALLOC_SIZE, ATEMP);
1030 /* Called after a fork to cleanup stuff left over from parents environment */
1032 cleanup_parents_env(void)
1038 * Don't clean up temporary files - parent will probably need them.
1039 * Also, can't easily reclaim memory since variables, etc. could be
1043 /* close all file descriptors hiding in savefd */
1044 for (ep = e; ep; ep = ep->oenv) {
1046 for (fd = 0; fd < NUFILE; fd++)
1047 if (ep->savefd[fd] > 0)
1048 close(ep->savefd[fd]);
1049 afree(ep->savefd, &ep->area);
1053 if (ep->type != E_NONE)
1062 /* Called just before an execve cleanup stuff temporary files */
1064 cleanup_proc_env(void)
1068 for (ep = e; ep; ep = ep->oenv)
1069 remove_temps(ep->temps);
1072 /* remove temp files and free ATEMP Area */
1078 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1083 remove_temps(e->temps);
1089 remove_temps(struct temp *tp)
1091 for (; tp != NULL; tp = tp->next)
1092 if (tp->pid == procpid)
1097 * Initialise tty_fd. Used for tracking the size of the terminal,
1098 * saving/resetting tty modes upon forground job completion, and
1099 * for setting up the tty process group. Return values:
1100 * 0 = got controlling tty
1101 * 1 = got terminal but no controlling tty
1102 * 2 = cannot find a terminal
1104 * 4 = cannot make fd close-on-exec
1105 * An existing tty_fd is cached if no "better" one could be found,
1106 * i.e. if tty_devtty was already set or the new would not set it.
1111 int fd, rv, eno = 0;
1112 bool do_close = false, is_devtty = true;
1115 /* already got a tty which is /dev/tty */
1120 /*XXX imake style */
1122 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1127 if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1134 /* already got a non-devtty one */
1140 if (isatty((fd = 0)) || isatty((fd = 2)))
1142 /* cannot find one */
1144 /* assert: do_close == false */
1148 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1153 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1160 tty_devtty = is_devtty;
1169 /* A shell error occurred (eg, syntax error, etc.) */
1171 #define VWARNINGF_ERRORPREFIX 1
1172 #define VWARNINGF_FILELINE 2
1173 #define VWARNINGF_BUILTIN 4
1174 #define VWARNINGF_INTERNAL 8
1176 static void vwarningf(unsigned int, const char *, va_list)
1177 MKSH_A_FORMAT(__printf__, 2, 0);
1180 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1183 if (flags & VWARNINGF_INTERNAL)
1184 shf_fprintf(shl_out, "internal error: ");
1185 if (flags & VWARNINGF_ERRORPREFIX)
1186 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1187 if ((flags & VWARNINGF_BUILTIN) &&
1188 /* not set when main() calls parse_args() */
1189 builtin_argv0 && builtin_argv0 != kshname)
1190 shf_fprintf(shl_out, "%s: ", builtin_argv0);
1191 shf_vfprintf(shl_out, fmt, ap);
1192 shf_putchar('\n', shl_out);
1198 errorfx(int rc, const char *fmt, ...)
1204 /* debugging: note that stdout not valid */
1205 shl_stdout_ok = false;
1208 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1214 errorf(const char *fmt, ...)
1220 /* debugging: note that stdout not valid */
1221 shl_stdout_ok = false;
1224 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1229 /* like errorf(), but no unwind is done */
1231 warningf(bool fileline, const char *fmt, ...)
1236 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1242 * Used by built-in utilities to prefix shell and utility name to message
1243 * (also unwinds environments for special builtins).
1246 bi_errorf(const char *fmt, ...)
1250 /* debugging: note that stdout not valid */
1251 shl_stdout_ok = false;
1256 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1257 VWARNINGF_BUILTIN, fmt, va);
1261 * POSIX special builtins and ksh special builtins cause
1262 * non-interactive shells to exit. XXX may not want LERROR here
1265 builtin_argv0 = NULL;
1270 /* Called when something that shouldn't happen does */
1272 internal_errorf(const char *fmt, ...)
1277 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1283 internal_warningf(const char *fmt, ...)
1288 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1292 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1294 error_prefix(bool fileline)
1296 /* Avoid foo: foo[2]: ... */
1297 if (!fileline || !source || !source->file ||
1298 strcmp(source->file, kshname) != 0)
1299 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1300 if (fileline && source && source->file != NULL) {
1301 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1302 (unsigned long)(source->errline ?
1303 source->errline : source->line));
1304 source->errline = 0;
1308 /* printf to shl_out (stderr) with flush */
1310 shellf(const char *fmt, ...)
1315 /* shl_out may not be set up yet... */
1318 shf_vfprintf(shl_out, fmt, va);
1323 /* printf to shl_stdout (stdout) */
1325 shprintf(const char *fmt, ...)
1330 internal_errorf("shl_stdout not valid");
1332 shf_vfprintf(shl_stdout, fmt, va);
1336 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1342 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1352 struct shf shf_iob[NSHF_IOB];
1361 /* force buffer allocation */
1362 shf_fdopen(1, SHF_WR, shl_stdout);
1363 shf_fdopen(2, SHF_WR, shl_out);
1364 shf_fdopen(2, SHF_WR, shl_xtrace);
1366 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1367 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1368 errorf("cannot get home directory");
1369 lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1372 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1373 errorf("cannot open debug output file %s", lfp);
1374 if (shl_dbg_fd < FDBASE) {
1377 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1379 if ((shl_dbg_fd = nfd) == -1)
1380 errorf("cannot dup debug output file");
1382 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1383 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1389 /* A dup2() with error checking */
1391 ksh_dup2(int ofd, int nfd, bool errok)
1395 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1396 errorf("too many files open in shell");
1399 /*XXX imake style */
1401 fcntl(nfd, F_SETFD, 0);
1408 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1409 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1416 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1417 (errno == EBADF || errno == EPERM))
1419 if (nfd < 0 || nfd > SHRT_MAX)
1420 errorf("too many files open in shell");
1421 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1422 return ((short)nfd);
1426 restfd(int fd, int ofd)
1429 shf_flush(&shf_iob[/* fd */ 2]);
1431 /* original fd closed */
1433 else if (fd != ofd) {
1434 /*XXX: what to do if this dup fails? */
1435 ksh_dup2(ofd, fd, true);
1446 errorf("can't create pipe - try again");
1447 pv[0] = savefd(lpv[0]);
1448 if (pv[0] != lpv[0])
1450 pv[1] = savefd(lpv[1]);
1451 if (pv[1] != lpv[1])
1463 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1464 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1467 check_fd(const char *name, int mode, const char **emsgp)
1471 if (name[0] == 'p' && !name[1])
1472 return (coproc_getfd(mode, emsgp));
1473 while (ksh_isdigit(*name)) {
1474 fd = fd * 10 + ksh_numdig(*name);
1477 *emsgp = "file descriptor too large";
1484 *emsgp = "illegal file descriptor name";
1487 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1489 *emsgp = "bad file descriptor";
1494 * X_OK is a kludge to disable this check for dups (x<&1):
1495 * historical shells never did this check (XXX don't know what
1496 * POSIX has to say).
1498 if (!(mode & X_OK) && fl != O_RDWR && (
1499 ((mode & R_OK) && fl != O_RDONLY) ||
1500 ((mode & W_OK) && fl != O_WRONLY))) {
1502 *emsgp = (fl == O_WRONLY) ?
1503 "fd not open for reading" :
1504 "fd not open for writing";
1510 /* Called once from main */
1514 coproc.read = coproc.readw = coproc.write = -1;
1519 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1521 coproc_read_close(int fd)
1523 if (coproc.read >= 0 && fd == coproc.read) {
1524 coproc_readw_close(fd);
1531 * Called by c_read() and by iosetup() to close the other side of the
1532 * read pipe, so reads will actually terminate.
1535 coproc_readw_close(int fd)
1537 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1538 close(coproc.readw);
1544 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1545 * when co-process input is dup'd
1548 coproc_write_close(int fd)
1550 if (coproc.write >= 0 && fd == coproc.write) {
1551 close(coproc.write);
1557 * Called to check for existence of/value of the co-process file descriptor.
1558 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1561 coproc_getfd(int mode, const char **emsgp)
1563 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1568 *emsgp = "no coprocess";
1573 * called to close file descriptors related to the coprocess (if any)
1574 * Should be called with SIGCHLD blocked.
1577 coproc_cleanup(int reuse)
1579 /* This to allow co-processes to share output pipe */
1580 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1581 if (coproc.read >= 0) {
1585 if (coproc.readw >= 0) {
1586 close(coproc.readw);
1590 if (coproc.write >= 0) {
1591 close(coproc.write);
1597 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1606 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1607 /* add "/shXXXXXX.tmp" plus NUL */
1609 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1610 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1616 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1622 cp += offsetof(struct temp, tffn[0]);
1623 memcpy(cp, dir, len);
1625 memcpy(cp, "/shXXXXXX.tmp", 14);
1626 /* point to the first of six Xes */
1629 /* cyclically attempt to open a temporary file */
1631 /* generate random part of filename */
1634 cp[len++] = digits_lc[rndget() % 36];
1637 /* check if this one works */
1638 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1639 0600)) < 0 && errno != EEXIST)
1643 if (type == TT_FUNSUB) {
1644 /* map us high and mark as close-on-exec */
1645 if ((j = savefd(i)) != i) {
1650 /* operation mode for the shf */
1655 /* shf_fdopen cannot fail, so no fd leak */
1656 tp->shf = shf_fdopen(i, j, NULL);
1665 * We use a similar collision resolution algorithm as Python 2.5.4
1666 * but with a slightly tweaked implementation written from scratch.
1669 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1670 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1672 static void tgrow(struct table *);
1673 static int tnamecmp(const void *, const void *);
1676 tgrow(struct table *tp)
1678 size_t i, j, osize, mask, perturb;
1679 struct tbl *tblp, **pp;
1680 struct tbl **ntblp, **otblp = tp->tbls;
1682 if (tp->tshift > 29)
1683 internal_errorf("hash table size limit reached");
1685 /* calculate old size, new shift and new size */
1686 osize = (size_t)1 << (tp->tshift++);
1689 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1690 /* multiplication cannot overflow: alloc2 checked that */
1691 memset(ntblp, 0, i * sizeof(struct tbl *));
1693 /* table can get very full when reaching its size limit */
1694 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1695 /* but otherwise, only 75% */
1702 for (i = 0; i < osize; i++)
1703 if ((tblp = otblp[i]) != NULL) {
1704 if ((tblp->flag & DEFINED)) {
1705 /* search for free hash table slot */
1706 j = perturb = tblp->ua.hval;
1707 goto find_first_empty_slot;
1708 find_next_empty_slot:
1709 j = (j << 2) + j + perturb + 1;
1710 perturb >>= PERTURB_SHIFT;
1711 find_first_empty_slot:
1712 pp = &ntblp[j & mask];
1714 goto find_next_empty_slot;
1715 /* found an empty hash table slot */
1718 } else if (!(tblp->flag & FINUSE)) {
1719 afree(tblp, tp->areap);
1722 afree(otblp, tp->areap);
1726 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1730 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1731 initshift : INIT_TBLSHIFT) - 1;
1735 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1737 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1739 size_t j, perturb, mask;
1740 struct tbl **pp, *p;
1742 mask = ((size_t)1 << (tp->tshift)) - 1;
1743 /* search for hash table slot matching name */
1745 goto find_first_slot;
1747 j = (j << 2) + j + perturb + 1;
1748 perturb >>= PERTURB_SHIFT;
1750 pp = &tp->tbls[j & mask];
1751 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1752 strcmp(p->name, name)))
1753 goto find_next_slot;
1754 /* p == NULL if not found, correct found entry otherwise */
1760 /* table, name (key) to enter, hash(n) */
1762 ktenter(struct table *tp, const char *n, uint32_t h)
1764 struct tbl **pp, *p;
1768 if ((p = ktscan(tp, n, h, &pp)))
1771 if (tp->nfree == 0) {
1777 /* create new tbl entry */
1779 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1780 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1783 p->areap = tp->areap;
1787 memcpy(p->name, n, len);
1789 /* enter in tp->tbls */
1796 ktwalk(struct tstate *ts, struct table *tp)
1798 ts->left = (size_t)1 << (tp->tshift);
1799 ts->next = tp->tbls;
1803 ktnext(struct tstate *ts)
1805 while (--ts->left >= 0) {
1806 struct tbl *p = *ts->next++;
1807 if (p != NULL && (p->flag & DEFINED))
1814 tnamecmp(const void *p1, const void *p2)
1816 const struct tbl *a = *((const struct tbl * const *)p1);
1817 const struct tbl *b = *((const struct tbl * const *)p2);
1819 return (strcmp(a->name, b->name));
1823 ktsort(struct table *tp)
1826 struct tbl **p, **sp, **dp;
1829 * since the table is never entirely full, no need to reserve
1830 * additional space for the trailing NULL appended below
1832 i = (size_t)1 << (tp->tshift);
1833 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1834 sp = tp->tbls; /* source */
1837 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1838 ((*dp)->flag & ARRAY)))
1840 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1847 x_sigwinch(int sig MKSH_A_UNUSED)
1849 /* this runs inside interrupt context, with errno saved */
1857 DF(const char *fmt, ...)
1863 mksh_lockfd(shl_dbg_fd);
1865 timet2mjd(&mjd, tv.tv_sec);
1866 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1867 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1868 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1869 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1870 va_start(args, fmt);
1871 shf_vfprintf(shl_dbg, fmt, args);
1873 shf_putc('\n', shl_dbg);
1875 mksh_unlkfd(shl_dbg_fd);
1880 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1885 mksh_tcget(fd, ocb);
1891 cb.c_iflag &= ~(ISTRIP);
1892 cb.c_lflag &= ~(ICANON) | ECHO;
1894 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1895 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1897 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1898 /* OSF/1 processes lnext when ~icanon */
1899 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1901 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1902 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1903 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1908 mksh_tcset(fd, &cb);