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, 2016, 2017
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.332 2017/04/12 16:01:45 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 initsubs[] =
67 static const char *initcoms[] = {
68 Ttypeset, "-r", initvsn, NULL,
69 Ttypeset, "-x", "HOME", TPATH, TSHELL, NULL,
70 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
72 "integer=\\\\builtin typeset -i",
73 "local=\\\\builtin typeset",
74 /* not "alias -t --": hash -r needs to work */
75 "hash=\\\\builtin alias -t",
76 "type=\\\\builtin whence -v",
77 "autoload=\\\\builtin typeset -fu",
78 "functions=\\\\builtin typeset -f",
79 "history=\\\\builtin fc -l",
80 "nameref=\\\\builtin typeset -n",
82 "r=\\\\builtin fc -e -",
83 "login=\\\\builtin exec login",
85 /* this is what AT&T ksh seems to track, with the addition of emacs */
87 Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
88 "make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
92 static const char *restr_com[] = {
93 Ttypeset, "-r", TPATH, "ENV", TSHELL, NULL
96 static bool initio_done;
98 /* top-level parsing and execution environment */
99 static struct env env;
100 struct env *e = &env;
102 /* compile-time assertions */
103 #define cta(name, expr) struct cta_ ## name { char t[(expr) ? 1 : -1]; }
105 /* this one should be defined by the standard */
106 cta(char_is_1_char, (sizeof(char) == 1) && (sizeof(signed char) == 1) &&
107 (sizeof(unsigned char) == 1));
108 cta(char_is_8_bits, ((CHAR_BIT) == 8) && ((int)(unsigned char)0xFF == 0xFF) &&
109 ((int)(unsigned char)0x100 == 0) && ((int)(unsigned char)(int)-1 == 0xFF));
110 /* the next assertion is probably not really needed */
111 cta(short_is_2_char, sizeof(short) == 2);
112 cta(short_size_no_matter_of_signedness, sizeof(short) == sizeof(unsigned short));
113 /* the next assertion is probably not really needed */
114 cta(int_is_4_char, sizeof(int) == 4);
115 cta(int_size_no_matter_of_signedness, sizeof(int) == sizeof(unsigned int));
117 cta(long_ge_int, sizeof(long) >= sizeof(int));
118 cta(long_size_no_matter_of_signedness, sizeof(long) == sizeof(unsigned long));
120 #ifndef MKSH_LEGACY_MODE
121 /* the next assertion is probably not really needed */
122 cta(ari_is_4_char, sizeof(mksh_ari_t) == 4);
124 cta(ari_has_31_bit, 0 < (mksh_ari_t)(((((mksh_ari_t)1 << 15) << 15) - 1) * 2 + 1));
125 /* the next assertion is probably not really needed */
126 cta(uari_is_4_char, sizeof(mksh_uari_t) == 4);
127 /* but the next three are; we REQUIRE unsigned integer wraparound */
128 cta(uari_has_31_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 2 + 1));
129 cta(uari_has_32_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3));
130 cta(uari_wrap_32_bit,
131 (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3) >
132 (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 4));
134 /* these are always required */
135 cta(ari_is_signed, (mksh_ari_t)-1 < (mksh_ari_t)0);
136 cta(uari_is_unsigned, (mksh_uari_t)-1 > (mksh_uari_t)0);
137 /* we require these to have the precisely same size and assume 2s complement */
138 cta(ari_size_no_matter_of_signedness, sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
140 cta(sizet_size_no_matter_of_signedness, sizeof(ssize_t) == sizeof(size_t));
141 cta(sizet_voidptr_same_size, sizeof(size_t) == sizeof(void *));
142 cta(sizet_funcptr_same_size, sizeof(size_t) == sizeof(void (*)(void)));
143 /* our formatting routines assume this */
144 cta(ptr_fits_in_long, sizeof(size_t) <= sizeof(long));
145 cta(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
152 ALLOC_ITEM alloc_INT;
153 void *dataptr, *stkptr, *mallocptr;
154 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
161 cp = alloc(sizeof(*bufptr) - sizeof(ALLOC_ITEM), APERM);
162 /* clear the allocated space, for valgrind and to avoid UB */
163 memset(cp, 0, sizeof(*bufptr) - sizeof(ALLOC_ITEM));
164 /* undo what alloc() did to the malloc result address */
165 bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
166 /* PIE or something similar provides us with deltas here */
167 bufptr->dataptr = &rndsetupstate;
168 /* ASLR in at least Windows, Linux, some BSDs */
169 bufptr->stkptr = &bufptr;
170 /* randomised malloc in BSD (and possibly others) */
171 bufptr->mallocptr = bufptr;
172 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
173 /* glibc pointer guard */
174 sigsetjmp(bufptr->jbuf, 1);
176 /* introduce variation (and yes, second arg MBZ for portability) */
177 mksh_TIME(bufptr->tv);
179 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
180 mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
182 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
185 return ((mksh_uari_t)h);
191 kshpid = procpid = getpid();
197 static const char *empty_argv[] = {
202 isuc(const char *cx) {
209 /* uppercase a string duplicate */
210 strdupx(x, cx, ATEMP);
212 while ((*cp = ksh_toupper(*cp)))
215 /* check for UTF-8 */
216 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
219 /* free copy and out */
225 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
230 unsigned char restricted_shell, errexit, utf_flag;
232 const char *ccp, **wp;
235 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
240 for (i = 0; i < 3; ++i)
242 setmode(i, O_BINARY);
244 os2_init(&argc, &argv);
247 /* do things like getpgrp() et al. */
250 /* make sure argv[] is sane, for weird OSes */
257 /* initialise permanent Area */
259 /* max. name length: -2147483648 = 11 (+ NUL) */
260 vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
262 /* set up base environment */
265 /* set up global l->vars and l->funs */
268 /* Do this first so output routines (eg, errorf, shellf) can work */
271 /* determine the basename (without '-' or path) of the executable */
273 goto begin_parsing_kshname;
274 while ((i = ccp[argi++])) {
275 if (mksh_cdirsep(i)) {
277 begin_parsing_kshname:
287 * Turn on nohup by default. (AT&T ksh does not have a nohup
288 * option - it always sends the hup).
293 * Turn on brace expansion by default. AT&T kshs that have
294 * alternation always have it on.
296 Flag(FBRACEEXPAND) = 1;
299 * Turn on "set -x" inheritance by default.
301 Flag(FXTRACEREC) = 1;
303 /* define built-in commands and see if we were called as one */
304 ktinit(APERM, &builtins,
305 /* currently up to 54 builtins: 75% of 128 = 2^7 */
307 for (i = 0; mkshbuiltins[i].name != NULL; i++)
308 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
309 mkshbuiltins[i].func)))
310 Flag(FAS_BUILTIN) = 1;
312 if (!Flag(FAS_BUILTIN)) {
313 /* check for -T option early */
314 argi = parse_args(argv, OF_FIRSTTIME, NULL);
318 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
319 /* are we called as -sh or /bin/sh or so? */
320 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
321 /* either also turns off braceexpand */
322 #ifdef MKSH_BINSHPOSIX
323 /* enable better POSIX conformance */
324 change_flag(FPOSIX, OF_FIRSTTIME, true);
326 #ifdef MKSH_BINSHREDUCED
327 /* enable kludge/compat mode */
328 change_flag(FSH, OF_FIRSTTIME, true);
342 /* set up variable and command dictionaries */
343 ktinit(APERM, &taliases, 0);
344 ktinit(APERM, &aliases, 0);
346 ktinit(APERM, &homedirs, 0);
349 /* define shell keywords */
354 /* initialise tty size before importing environment */
358 def_path = _PATH_DEFPATH;
361 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
362 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
367 * this is uniform across all OSes unless it
368 * breaks somewhere hard; don't try to optimise,
369 * e.g. add stuff for Interix or remove /usr
370 * for HURD, because e.g. Debian GNU/HURD is
371 * "keeping a regular /usr"; this is supposed
372 * to be a sane 'basic' default PATH
374 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
375 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
376 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
377 MKSH_UNIXROOT "/usr/sbin";
381 * Set PATH to def_path (will set the path global variable).
382 * (import of environment below will probably change this setting).
385 /* setstr can't fail here */
386 setstr(vp, def_path, KSH_RETURN_ERROR);
388 #ifndef MKSH_NO_CMDLINE_EDITING
390 * Set edit mode to emacs by default, may be overridden
391 * by the environment or the user. Also, we want tab completion
392 * on in vi by default.
394 change_flag(FEMACS, OF_SPECIAL, true);
396 Flag(FVITABCOMPLETE) = 1;
400 /* import environment */
401 if (environ != NULL) {
402 wp = (const char **)environ;
403 while (*wp != NULL) {
405 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
411 typeset("IFS= \t\n", 0, 0, 0, 0);
413 /* assign default shell variable values */
414 typeset("PATHSEP=" MKSH_PATHSEPS, 0, 0, 0, 0);
415 substitute(initsubs, 0);
417 /* Figure out the current working directory and set $PWD */
420 /* Try to use existing $PWD if it is valid */
421 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
422 Tdot, true)) ? cp : NULL);
424 simplify_path(current_wd);
425 /* Only set pwd if we know where we are or if it had a bogus value */
426 if (current_wd[0] || *cp)
427 /* setstr can't fail here */
428 setstr(vp, current_wd, KSH_RETURN_ERROR);
430 for (wp = initcoms; *wp != NULL; wp++) {
435 setint_n(global("OPTIND"), 1, 10);
441 safe_prompt = ksheuid ? "$ " : "# ";
443 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
444 if (!(vp->flag & ISSET) ||
445 (!ksheuid && !strchr(str_val(vp), '#')))
446 /* setstr can't fail here */
447 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
448 setint_n((vp = global("BASHPID")), 0, 10);
450 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
452 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
454 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
456 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
458 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
460 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
462 setint_n((vp = global("RANDOM")), rndsetup(), 10);
464 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
466 /* Set this before parsing arguments */
467 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
469 /* this to note if monitor is set on command line (see below) */
470 #ifndef MKSH_UNEMPLOYED
471 Flag(FMONITOR) = 127;
473 /* this to note if utf-8 mode is set on command line (see below) */
476 if (!Flag(FAS_BUILTIN)) {
477 argi = parse_args(argv, OF_CMDLINE, NULL);
482 /* process this later only, default to off (hysterical raisins) */
486 if (Flag(FAS_BUILTIN)) {
487 /* auto-detect from environment variables, always */
489 } else if (Flag(FCOMMAND)) {
490 s = pushs(SSTRINGCMDLINE, ATEMP);
491 if (!(s->start = s->str = argv[argi++]))
492 errorf(Tf_optfoo, "", "", 'c', Treq_arg);
494 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
499 s->flags |= SF_MAYEXEC;
501 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
502 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
503 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
507 kshname = argv[argi++];
508 } else if (argi < argc && !Flag(FSTDIN)) {
509 s = pushs(SFILE, ATEMP);
512 * A bug in OS/2 extproc (like shebang) handling makes
513 * it not pass the full pathname of a script, so we need
514 * to search for it. This changes the behaviour of a
515 * simple "mksh foo", but can't be helped.
517 s->file = argv[argi++];
518 if (search_access(s->file, X_OK) != 0)
519 s->file = search_path(s->file, path, X_OK, NULL);
520 if (!s->file || !*s->file)
521 s->file = argv[argi - 1];
523 s->file = argv[argi++];
525 s->u.shf = shf_open(s->file, O_RDONLY, 0,
526 SHF_MAPHI | SHF_CLEXEC);
527 if (s->u.shf == NULL) {
528 shl_stdout_ok = false;
529 warningf(true, Tf_sD_s, s->file, cstrerror(errno));
530 /* mandated by SUSv4 */
537 s = pushs(SSTDIN, ATEMP);
539 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
541 if (isatty(0) && isatty(2)) {
542 Flag(FTALKING) = Flag(FTALKING_I) = 1;
543 /* The following only if isatty(0) */
545 s->u.shf->flags |= SHF_INTERRUPT;
550 /* this bizarreness is mandated by POSIX */
551 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
555 /* initialise job control */
557 /* do this after j_init() which calls tty_init_state() */
558 if (Flag(FTALKING)) {
560 #ifndef MKSH_ASSUME_UTF8
561 /* auto-detect from locale or environment */
563 #else /* this may not be an #elif */
567 /* always disable UTF-8 (for interactive) */
572 #ifndef MKSH_NO_CMDLINE_EDITING
578 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
579 setsig(&sigtraps[SIGWINCH], x_sigwinch,
580 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
584 if (Flag(FAS_BUILTIN)) {
589 l->argc = argc - argi;
591 * allocate a new array because otherwise, when we modify
592 * it in-place, ps(1) output changes; the meaning of argc
593 * here is slightly different as it excludes kshname, and
594 * we add a trailing NULL sentinel as well
596 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
597 l->argv[0] = kshname;
598 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
599 l->argv[l->argc + 1] = NULL;
603 /* divine the initial state of the utf8-mode Flag */
607 /* auto-detect from locale or environment */
609 #if HAVE_SETLOCALE_CTYPE
610 ccp = setlocale(LC_CTYPE, "");
611 #if HAVE_LANGINFO_CODESET
613 ccp = nl_langinfo(CODESET);
620 /* auto-detect from environment */
622 /* these were imported from environ earlier */
624 ccp = str_val(global("LC_ALL"));
626 ccp = str_val(global("LC_CTYPE"));
628 ccp = str_val(global("LANG"));
632 /* not set on command line, not FTALKING */
646 /* Disable during .profile/ENV reading */
647 restricted_shell = Flag(FRESTRICTED);
648 Flag(FRESTRICTED) = 0;
649 errexit = Flag(FERREXIT);
653 * Do this before profile/$ENV so that if it causes problems in them,
654 * user will know why things broke.
656 if (!current_wd[0] && Flag(FTALKING))
657 warningf(false, "can't determine current directory");
660 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
661 if (!Flag(FPRIVILEGED)) {
663 include(substitute("$HOME/.profile", 0), 0, NULL, true);
664 if (Flag(FTALKING)) {
665 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
668 include(cp, 0, NULL, true);
671 include(MKSH_SUID_PROFILE, 0, NULL, true);
672 /* turn off -p if not set explicitly */
673 if (Flag(FPRIVILEGED) != 1)
674 change_flag(FPRIVILEGED, OF_INTERNAL, false);
677 if (restricted_shell) {
678 c_builtin(restr_com);
679 /* After typeset command... */
680 Flag(FRESTRICTED) = 1;
682 Flag(FERREXIT) = errexit;
684 if (Flag(FTALKING) && s)
697 /* this indirection barrier reduces stack usage during normal operation */
700 main(int argc, const char *argv[])
706 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
707 if (Flag(FAS_BUILTIN)) {
708 rv = c_builtin(l->argv);
718 include(const char *name, int argc, const char **argv, bool intr_ok)
720 Source *volatile s = NULL;
722 const char **volatile old_argv;
723 volatile int old_argc;
726 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
731 old_argv = e->loc->argv;
732 old_argc = e->loc->argc;
738 if ((i = kshsetjmp(e->jbuf))) {
739 quitenv(s ? s->u.shf : NULL);
741 e->loc->argv = old_argv;
742 e->loc->argc = old_argc;
748 return (exstat & 0xFF);
751 * intr_ok is set if we are including .profile or $ENV.
752 * If user ^Cs out, we don't want to kill the shell...
754 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
763 internal_errorf(Tunexpected_type, Tunwind, Tsource, i);
771 s = pushs(SFILE, ATEMP);
773 strdupx(s->file, name, ATEMP);
777 e->loc->argv = old_argv;
778 e->loc->argc = old_argc;
780 /* & 0xff to ensure value not -1 */
784 /* spawn a command into a shell optionally keeping track of the line number */
786 command(const char *comm, int line)
788 Source *s, *sold = source;
791 s = pushs(SSTRING, ATEMP);
792 s->start = s->str = comm;
800 * run the commands from the input source, returning status.
803 shell(Source * volatile s, volatile int level)
806 volatile bool wastty = tobool(s->flags & SF_TTY);
807 volatile uint8_t attempts = 13;
808 volatile bool interactive = (level == 0) && Flag(FTALKING);
809 volatile bool sfirst = true;
810 Source *volatile old_source = source;
813 newenv(level == 2 ? E_EVAL : E_PARSE);
816 switch ((i = kshsetjmp(e->jbuf))) {
824 internal_errorf(Tf_cant_s, Tshell,
825 i == LBREAK ? Tbreak : Tcontinue);
828 /* assert: interactive == false */
831 /* we get here if SIGINT not caught or ignored */
838 * Reset any eof that was read as part of a
841 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
844 * Used by exit command to get back to
845 * top level shell. Kind of strange since
846 * interactive is set if we are reading from
847 * a tty, but to have stopped jobs, one only
848 * needs FMONITOR set (not FTALKING/SF_TTY)...
850 /* toss any input we have so far */
851 yyrecursive_pop(true);
852 s->start = s->str = null;
869 internal_errorf(Tunexpected_type, Tunwind, Tshell, i);
872 while (/* CONSTCOND */ 1) {
876 if (s->next == NULL) {
880 s->flags &= ~SF_ECHO;
886 t = compile(s, sfirst, true);
888 histsave(&s->line, NULL, HIST_FLUSH, true);
892 if (t->type == TEOF) {
893 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
894 shellf("Use 'exit' to leave mksh\n");
896 } else if (wastty && !really_exit &&
897 j_stopped_running()) {
902 * this for POSIX which says EXIT traps
903 * shall be taken in the environment
904 * immediately after the last command
911 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
912 t->u.evalflags |= DOTCOMEXEC;
913 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
914 exstat = execute(t, 0, NULL) & 0xFF;
916 if (t->type != TEOF && interactive && really_exit)
924 return (exstat & 0xFF);
927 /* return to closest error handler or shell(), exit if none found */
928 /* note: i MUST NOT be 0 */
933 * This is a kludge. We need to restore everything that was
934 * changed in the new environment, see cid 1005090337C7A669439
935 * and 10050903386452ACBF1, but fail to even save things most of
936 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
937 * which needs to be restored thus (related to Debian #696823).
938 * We did not save the shell flags, so we use a special or'd
939 * value here... this is mostly to clean up behind *other*
940 * callers of unwind(LERROR) here; exec.c has the regular case.
942 if (Flag(FERREXIT) & 0x80) {
943 /* GNU bash does not run this trapsig */
945 Flag(FERREXIT) &= ~0x80;
948 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
949 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
950 sigtraps[ksh_SIGEXIT].trap &&
951 (!Flag(FTALKING) || Flag(FERREXIT)))) {
953 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
956 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
958 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
963 while (/* CONSTCOND */ 1) {
971 kshlongjmp(e->jbuf, i);
975 e->flags |= EF_FAKE_SIGDIE;
990 * struct env includes ALLOC_ITEM for alignment constraints
991 * so first get the actually used memory, then assign it
993 cp = alloc(sizeof(struct env) - sizeof(ALLOC_ITEM), ATEMP);
994 /* undo what alloc() did to the malloc result address */
995 ep = (void *)(cp - sizeof(ALLOC_ITEM));
996 /* initialise public members of struct env (not the ALLOC_ITEM) */
1002 ep->yyrecursive_statep = NULL;
1005 /* jump buffer is invalid because flags == 0 */
1010 quitenv(struct shf *shf)
1016 yyrecursive_pop(true);
1017 while (ep->oenv && ep->oenv->loc != ep->loc)
1019 if (ep->savefd != NULL) {
1020 for (fd = 0; fd < NUFILE; fd++)
1021 /* if ep->savefd[fd] < 0, means fd was closed */
1023 restfd(fd, ep->savefd[fd]);
1025 /* Clear any write errors */
1026 shf_reopen(2, SHF_WR, shl_out);
1029 * Bottom of the stack.
1030 * Either main shell is exiting or cleanup_parents_env() was called.
1032 if (ep->oenv == NULL) {
1037 if (ep->type == E_NONE) {
1038 /* Main shell exiting? */
1039 #if HAVE_PERSISTENT_HISTORY
1044 if (ep->flags & EF_FAKE_SIGDIE) {
1045 int sig = (exstat & 0xFF) - 128;
1048 * ham up our death a bit (AT&T ksh
1049 * only seems to do this for SIGTERM)
1050 * Don't do it for SIGQUIT, since we'd
1053 if ((sig == SIGINT || sig == SIGTERM) &&
1054 (kshpgrp == kshpid)) {
1055 setsig(&sigtraps[sig], SIG_DFL,
1056 SS_RESTORE_CURR | SS_FORCE);
1065 #ifndef MKSH_NO_CMDLINE_EDITING
1068 #ifndef MKSH_NOPROSPECTOFWORK
1069 /* block at least SIGCHLD during/after afreeall */
1070 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1073 for (fd = 3; fd < NUFILE; fd++)
1074 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1081 exit(exstat & 0xFF);
1089 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1091 afree(cp + sizeof(ALLOC_ITEM), ATEMP);
1094 /* Called after a fork to cleanup stuff left over from parents environment */
1096 cleanup_parents_env(void)
1102 * Don't clean up temporary files - parent will probably need them.
1103 * Also, can't easily reclaim memory since variables, etc. could be
1107 /* close all file descriptors hiding in savefd */
1108 for (ep = e; ep; ep = ep->oenv) {
1110 for (fd = 0; fd < NUFILE; fd++)
1111 if (ep->savefd[fd] > 0)
1112 close(ep->savefd[fd]);
1113 afree(ep->savefd, &ep->area);
1117 if (ep->type != E_NONE)
1126 /* Called just before an execve cleanup stuff temporary files */
1128 cleanup_proc_env(void)
1132 for (ep = e; ep; ep = ep->oenv)
1133 remove_temps(ep->temps);
1136 /* remove temp files and free ATEMP Area */
1142 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1147 remove_temps(e->temps);
1151 * if the memory backing source is reclaimed, things
1152 * will end up badly when a function expecting it to
1153 * be valid is run; a NULL pointer is easily debugged
1155 if (source && source->areap == &e->area)
1161 remove_temps(struct temp *tp)
1164 if (tp->pid == procpid)
1171 * Initialise tty_fd. Used for tracking the size of the terminal,
1172 * saving/resetting tty modes upon forground job completion, and
1173 * for setting up the tty process group. Return values:
1174 * 0 = got controlling tty
1175 * 1 = got terminal but no controlling tty
1176 * 2 = cannot find a terminal
1178 * 4 = cannot make fd close-on-exec
1179 * An existing tty_fd is cached if no "better" one could be found,
1180 * i.e. if tty_devtty was already set or the new would not set it.
1185 int fd, rv, eno = 0;
1186 bool do_close = false, is_devtty = true;
1189 /* already got a tty which is /dev/tty */
1194 /*XXX imake style */
1196 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1201 if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
1208 /* already got a non-devtty one */
1214 if (isatty((fd = 0)) || isatty((fd = 2)))
1216 /* cannot find one */
1218 /* assert: do_close == false */
1222 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1227 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1234 tty_devtty = is_devtty;
1243 /* A shell error occurred (eg, syntax error, etc.) */
1245 #define VWARNINGF_ERRORPREFIX 1
1246 #define VWARNINGF_FILELINE 2
1247 #define VWARNINGF_BUILTIN 4
1248 #define VWARNINGF_INTERNAL 8
1250 static void vwarningf(unsigned int, const char *, va_list)
1251 MKSH_A_FORMAT(__printf__, 2, 0);
1254 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1257 if (flags & VWARNINGF_INTERNAL)
1258 shf_fprintf(shl_out, Tf_sD_, "internal error");
1259 if (flags & VWARNINGF_ERRORPREFIX)
1260 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1261 if ((flags & VWARNINGF_BUILTIN) &&
1262 /* not set when main() calls parse_args() */
1263 builtin_argv0 && builtin_argv0 != kshname)
1264 shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
1265 shf_vfprintf(shl_out, fmt, ap);
1266 shf_putchar('\n', shl_out);
1272 errorfx(int rc, const char *fmt, ...)
1278 /* debugging: note that stdout not valid */
1279 shl_stdout_ok = false;
1282 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1288 errorf(const char *fmt, ...)
1294 /* debugging: note that stdout not valid */
1295 shl_stdout_ok = false;
1298 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1303 /* like errorf(), but no unwind is done */
1305 warningf(bool fileline, const char *fmt, ...)
1310 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1316 * Used by built-in utilities to prefix shell and utility name to message
1317 * (also unwinds environments for special builtins).
1320 bi_errorf(const char *fmt, ...)
1324 /* debugging: note that stdout not valid */
1325 shl_stdout_ok = false;
1330 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1331 VWARNINGF_BUILTIN, fmt, va);
1334 /* POSIX special builtins cause non-interactive shells to exit */
1336 builtin_argv0 = NULL;
1337 /* may not want to use LERROR here */
1342 /* Called when something that shouldn't happen does */
1344 internal_errorf(const char *fmt, ...)
1349 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1355 internal_warningf(const char *fmt, ...)
1360 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1364 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1366 error_prefix(bool fileline)
1368 /* Avoid foo: foo[2]: ... */
1369 if (!fileline || !source || !source->file ||
1370 strcmp(source->file, kshname) != 0)
1371 shf_fprintf(shl_out, Tf_sD_, kshname + (*kshname == '-'));
1372 if (fileline && source && source->file != NULL) {
1373 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1374 (unsigned long)(source->errline ?
1375 source->errline : source->line));
1376 source->errline = 0;
1380 /* printf to shl_out (stderr) with flush */
1382 shellf(const char *fmt, ...)
1387 /* shl_out may not be set up yet... */
1390 shf_vfprintf(shl_out, fmt, va);
1395 /* printf to shl_stdout (stdout) */
1397 shprintf(const char *fmt, ...)
1402 internal_errorf("shl_stdout not valid");
1404 shf_vfprintf(shl_stdout, fmt, va);
1408 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1414 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1424 struct shf shf_iob[NSHF_IOB];
1433 /* force buffer allocation */
1434 shf_fdopen(1, SHF_WR, shl_stdout);
1435 shf_fdopen(2, SHF_WR, shl_out);
1436 shf_fdopen(2, SHF_WR, shl_xtrace);
1438 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1439 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1440 errorf("can't get home directory");
1441 lfp = shf_smprintf(Tf_sSs, lfp, "mksh-dbg.txt");
1444 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1445 errorf("can't open debug output file %s", lfp);
1446 if (shl_dbg_fd < FDBASE) {
1449 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1451 if ((shl_dbg_fd = nfd) == -1)
1452 errorf("can't dup debug output file");
1454 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1455 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1461 /* A dup2() with error checking */
1463 ksh_dup2(int ofd, int nfd, bool errok)
1467 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1468 errorf(Ttoo_many_files);
1471 /*XXX imake style */
1473 fcntl(nfd, F_SETFD, 0);
1480 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1481 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1488 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1489 (errno == EBADF || errno == EPERM))
1491 if (nfd < 0 || nfd > SHRT_MAX)
1492 errorf(Ttoo_many_files);
1493 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1494 return ((short)nfd);
1498 restfd(int fd, int ofd)
1501 shf_flush(&shf_iob[/* fd */ 2]);
1503 /* original fd closed */
1505 else if (fd != ofd) {
1506 /*XXX: what to do if this dup fails? */
1507 ksh_dup2(ofd, fd, true);
1518 errorf("can't create pipe - try again");
1519 pv[0] = savefd(lpv[0]);
1520 if (pv[0] != lpv[0])
1522 pv[1] = savefd(lpv[1]);
1523 if (pv[1] != lpv[1])
1526 setmode(pv[0], O_BINARY);
1527 setmode(pv[1], O_BINARY);
1539 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1540 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1543 check_fd(const char *name, int mode, const char **emsgp)
1547 if (!name[0] || name[1])
1548 goto illegal_fd_name;
1550 return (coproc_getfd(mode, emsgp));
1551 if (!ksh_isdigit(name[0])) {
1554 *emsgp = "illegal file descriptor name";
1558 if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
1560 *emsgp = "bad file descriptor";
1565 * X_OK is a kludge to disable this check for dups (x<&1):
1566 * historical shells never did this check (XXX don't know what
1567 * POSIX has to say).
1569 if (!(mode & X_OK) && fl != O_RDWR && (
1570 ((mode & R_OK) && fl != O_RDONLY) ||
1571 ((mode & W_OK) && fl != O_WRONLY))) {
1573 *emsgp = (fl == O_WRONLY) ?
1574 "fd not open for reading" :
1575 "fd not open for writing";
1581 /* Called once from main */
1585 coproc.read = coproc.readw = coproc.write = -1;
1590 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1592 coproc_read_close(int fd)
1594 if (coproc.read >= 0 && fd == coproc.read) {
1595 coproc_readw_close(fd);
1602 * Called by c_read() and by iosetup() to close the other side of the
1603 * read pipe, so reads will actually terminate.
1606 coproc_readw_close(int fd)
1608 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1609 close(coproc.readw);
1615 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1616 * when co-process input is dup'd
1619 coproc_write_close(int fd)
1621 if (coproc.write >= 0 && fd == coproc.write) {
1622 close(coproc.write);
1628 * Called to check for existence of/value of the co-process file descriptor.
1629 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1632 coproc_getfd(int mode, const char **emsgp)
1634 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1639 *emsgp = "no coprocess";
1644 * called to close file descriptors related to the coprocess (if any)
1645 * Should be called with SIGCHLD blocked.
1648 coproc_cleanup(int reuse)
1650 /* This to allow co-processes to share output pipe */
1651 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1652 if (coproc.read >= 0) {
1656 if (coproc.readw >= 0) {
1657 close(coproc.readw);
1661 if (coproc.write >= 0) {
1662 close(coproc.write);
1668 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1677 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1678 /* add "/shXXXXXX.tmp" plus NUL */
1680 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1681 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1687 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1693 cp += offsetof(struct temp, tffn[0]);
1694 memcpy(cp, dir, len);
1696 memcpy(cp, "/shXXXXXX.tmp", 14);
1697 /* point to the first of six Xes */
1700 /* cyclically attempt to open a temporary file */
1702 /* generate random part of filename */
1705 cp[len++] = digits_lc[rndget() % 36];
1708 /* check if this one works */
1709 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1710 0600)) < 0 && errno != EEXIST)
1714 if (type == TT_FUNSUB) {
1715 /* map us high and mark as close-on-exec */
1716 if ((j = savefd(i)) != i) {
1721 /* operation mode for the shf */
1726 /* shf_fdopen cannot fail, so no fd leak */
1727 tp->shf = shf_fdopen(i, j, NULL);
1736 * We use a similar collision resolution algorithm as Python 2.5.4
1737 * but with a slightly tweaked implementation written from scratch.
1740 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1741 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1743 static void tgrow(struct table *);
1744 static int tnamecmp(const void *, const void *);
1747 tgrow(struct table *tp)
1749 size_t i, j, osize, mask, perturb;
1750 struct tbl *tblp, **pp;
1751 struct tbl **ntblp, **otblp = tp->tbls;
1753 if (tp->tshift > 29)
1754 internal_errorf("hash table size limit reached");
1756 /* calculate old size, new shift and new size */
1757 osize = (size_t)1 << (tp->tshift++);
1760 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1761 /* multiplication cannot overflow: alloc2 checked that */
1762 memset(ntblp, 0, i * sizeof(struct tbl *));
1764 /* table can get very full when reaching its size limit */
1765 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1766 /* but otherwise, only 75% */
1773 for (i = 0; i < osize; i++)
1774 if ((tblp = otblp[i]) != NULL) {
1775 if ((tblp->flag & DEFINED)) {
1776 /* search for free hash table slot */
1777 j = perturb = tblp->ua.hval;
1778 goto find_first_empty_slot;
1779 find_next_empty_slot:
1780 j = (j << 2) + j + perturb + 1;
1781 perturb >>= PERTURB_SHIFT;
1782 find_first_empty_slot:
1783 pp = &ntblp[j & mask];
1785 goto find_next_empty_slot;
1786 /* found an empty hash table slot */
1789 } else if (!(tblp->flag & FINUSE)) {
1790 afree(tblp, tp->areap);
1793 afree(otblp, tp->areap);
1797 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1801 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1802 initshift : INIT_TBLSHIFT) - 1;
1806 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1808 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1810 size_t j, perturb, mask;
1811 struct tbl **pp, *p;
1813 mask = ((size_t)1 << (tp->tshift)) - 1;
1814 /* search for hash table slot matching name */
1816 goto find_first_slot;
1818 j = (j << 2) + j + perturb + 1;
1819 perturb >>= PERTURB_SHIFT;
1821 pp = &tp->tbls[j & mask];
1822 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1823 strcmp(p->name, name)))
1824 goto find_next_slot;
1825 /* p == NULL if not found, correct found entry otherwise */
1831 /* table, name (key) to enter, hash(n) */
1833 ktenter(struct table *tp, const char *n, uint32_t h)
1835 struct tbl **pp, *p;
1839 if ((p = ktscan(tp, n, h, &pp)))
1842 if (tp->nfree == 0) {
1848 /* create new tbl entry */
1850 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1851 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1854 p->areap = tp->areap;
1858 memcpy(p->name, n, len);
1860 /* enter in tp->tbls */
1867 ktwalk(struct tstate *ts, struct table *tp)
1869 ts->left = (size_t)1 << (tp->tshift);
1870 ts->next = tp->tbls;
1874 ktnext(struct tstate *ts)
1876 while (--ts->left >= 0) {
1877 struct tbl *p = *ts->next++;
1878 if (p != NULL && (p->flag & DEFINED))
1885 tnamecmp(const void *p1, const void *p2)
1887 const struct tbl *a = *((const struct tbl * const *)p1);
1888 const struct tbl *b = *((const struct tbl * const *)p2);
1890 return (strcmp(a->name, b->name));
1894 ktsort(struct table *tp)
1897 struct tbl **p, **sp, **dp;
1900 * since the table is never entirely full, no need to reserve
1901 * additional space for the trailing NULL appended below
1903 i = (size_t)1 << (tp->tshift);
1904 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1905 sp = tp->tbls; /* source */
1908 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1909 ((*dp)->flag & ARRAY)))
1911 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1918 x_sigwinch(int sig MKSH_A_UNUSED)
1920 /* this runs inside interrupt context, with errno saved */
1928 DF(const char *fmt, ...)
1934 mksh_lockfd(shl_dbg_fd);
1936 timet2mjd(&mjd, tv.tv_sec);
1937 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1938 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1939 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1940 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1941 va_start(args, fmt);
1942 shf_vfprintf(shl_dbg, fmt, args);
1944 shf_putc('\n', shl_dbg);
1946 mksh_unlkfd(shl_dbg_fd);
1951 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1956 mksh_tcget(fd, ocb);
1962 cb.c_iflag &= ~(ISTRIP);
1963 cb.c_lflag &= ~(ICANON) | ECHO;
1965 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1966 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1968 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1969 /* OSF/1 processes lnext when ~icanon */
1970 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1972 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1973 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1974 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1979 mksh_tcset(fd, &cb);