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.342 2017/04/28 11:13:47 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)
239 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
245 for (i = 0; i < 3; ++i)
247 setmode(i, O_BINARY);
249 os2_init(&argc, &argv);
252 /* do things like getpgrp() et al. */
255 /* make sure argv[] is sane, for weird OSes */
262 /* initialise permanent Area */
264 /* max. name length: -2147483648 = 11 (+ NUL) */
265 vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
267 /* set up base environment */
270 /* set up global l->vars and l->funs */
273 /* Do this first so output routines (eg, errorf, shellf) can work */
276 /* determine the basename (without '-' or path) of the executable */
278 goto begin_parsing_kshname;
279 while ((i = ccp[argi++])) {
280 if (mksh_cdirsep(i)) {
282 begin_parsing_kshname:
292 * Turn on nohup by default. (AT&T ksh does not have a nohup
293 * option - it always sends the hup).
298 * Turn on brace expansion by default. AT&T kshs that have
299 * alternation always have it on.
301 Flag(FBRACEEXPAND) = 1;
304 * Turn on "set -x" inheritance by default.
306 Flag(FXTRACEREC) = 1;
308 /* define built-in commands and see if we were called as one */
309 ktinit(APERM, &builtins,
310 /* currently up to 54 builtins: 75% of 128 = 2^7 */
312 for (i = 0; mkshbuiltins[i].name != NULL; i++)
313 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
314 mkshbuiltins[i].func)))
315 Flag(FAS_BUILTIN) = 1;
317 if (!Flag(FAS_BUILTIN)) {
318 /* check for -T option early */
319 argi = parse_args(argv, OF_FIRSTTIME, NULL);
323 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
324 /* are we called as -sh or /bin/sh or so? */
325 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
326 /* either also turns off braceexpand */
327 #ifdef MKSH_BINSHPOSIX
328 /* enable better POSIX conformance */
329 change_flag(FPOSIX, OF_FIRSTTIME, true);
331 #ifdef MKSH_BINSHREDUCED
332 /* enable kludge/compat mode */
333 change_flag(FSH, OF_FIRSTTIME, true);
345 /* set up variable and command dictionaries */
346 ktinit(APERM, &taliases, 0);
347 ktinit(APERM, &aliases, 0);
349 ktinit(APERM, &homedirs, 0);
352 /* define shell keywords */
357 /* initialise tty size before importing environment */
361 def_path = _PATH_DEFPATH;
364 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
365 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
370 * this is uniform across all OSes unless it
371 * breaks somewhere hard; don't try to optimise,
372 * e.g. add stuff for Interix or remove /usr
373 * for HURD, because e.g. Debian GNU/HURD is
374 * "keeping a regular /usr"; this is supposed
375 * to be a sane 'basic' default PATH
377 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
378 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
379 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
380 MKSH_UNIXROOT "/usr/sbin";
384 * Set PATH to def_path (will set the path global variable).
385 * (import of environment below will probably change this setting).
388 /* setstr can't fail here */
389 setstr(vp, def_path, KSH_RETURN_ERROR);
391 #ifndef MKSH_NO_CMDLINE_EDITING
393 * Set edit mode to emacs by default, may be overridden
394 * by the environment or the user. Also, we want tab completion
395 * on in vi by default.
397 change_flag(FEMACS, OF_SPECIAL, true);
399 Flag(FVITABCOMPLETE) = 1;
403 /* import environment */
404 if (environ != NULL) {
405 wp = (const char **)environ;
406 while (*wp != NULL) {
408 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
413 /* override default PATH regardless of environment */
414 #ifdef MKSH_DEFPATH_OVERRIDE
416 setstr(vp, MKSH_DEFPATH_OVERRIDE, KSH_RETURN_ERROR);
420 typeset(TinitIFS, 0, 0, 0, 0);
422 /* assign default shell variable values */
423 typeset("PATHSEP=" MKSH_PATHSEPS, 0, 0, 0, 0);
424 substitute(initsubs, 0);
426 /* Figure out the current working directory and set $PWD */
429 /* Try to use existing $PWD if it is valid */
430 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
431 Tdot, true)) ? cp : NULL);
433 simplify_path(current_wd);
434 /* Only set pwd if we know where we are or if it had a bogus value */
435 if (current_wd[0] || *cp)
436 /* setstr can't fail here */
437 setstr(vp, current_wd, KSH_RETURN_ERROR);
439 for (wp = initcoms; *wp != NULL; wp++) {
444 setint_n(global("OPTIND"), 1, 10);
450 safe_prompt = ksheuid ? "$ " : "# ";
452 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
453 if (!(vp->flag & ISSET) ||
454 (!ksheuid && !strchr(str_val(vp), '#')))
455 /* setstr can't fail here */
456 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
457 setint_n((vp = global("BASHPID")), 0, 10);
459 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
461 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
463 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
465 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
467 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
469 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
471 setint_n((vp = global("RANDOM")), rndsetup(), 10);
473 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
475 /* Set this before parsing arguments */
476 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
478 /* this to note if monitor is set on command line (see below) */
479 #ifndef MKSH_UNEMPLOYED
480 Flag(FMONITOR) = 127;
482 /* this to note if utf-8 mode is set on command line (see below) */
485 if (!Flag(FAS_BUILTIN)) {
486 argi = parse_args(argv, OF_CMDLINE, NULL);
491 /* process this later only, default to off (hysterical raisins) */
495 if (Flag(FAS_BUILTIN)) {
496 /* auto-detect from environment variables, always */
498 } else if (Flag(FCOMMAND)) {
499 s = pushs(SSTRINGCMDLINE, ATEMP);
500 if (!(s->start = s->str = argv[argi++]))
501 errorf(Tf_optfoo, "", "", 'c', Treq_arg);
503 if (ctype(*s->str, C_QUOTE))
508 s->flags |= SF_MAYEXEC;
510 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
511 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
512 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
516 kshname = argv[argi++];
517 } else if (argi < argc && !Flag(FSTDIN)) {
518 s = pushs(SFILE, ATEMP);
521 * A bug in OS/2 extproc (like shebang) handling makes
522 * it not pass the full pathname of a script, so we need
523 * to search for it. This changes the behaviour of a
524 * simple "mksh foo", but can't be helped.
526 s->file = argv[argi++];
527 if (search_access(s->file, X_OK) != 0)
528 s->file = search_path(s->file, path, X_OK, NULL);
529 if (!s->file || !*s->file)
530 s->file = argv[argi - 1];
532 s->file = argv[argi++];
534 s->u.shf = shf_open(s->file, O_RDONLY, 0,
535 SHF_MAPHI | SHF_CLEXEC);
536 if (s->u.shf == NULL) {
537 shl_stdout_ok = false;
538 warningf(true, Tf_sD_s, s->file, cstrerror(errno));
539 /* mandated by SUSv4 */
546 s = pushs(SSTDIN, ATEMP);
548 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
550 if (isatty(0) && isatty(2)) {
551 Flag(FTALKING) = Flag(FTALKING_I) = 1;
552 /* The following only if isatty(0) */
554 s->u.shf->flags |= SHF_INTERRUPT;
559 /* this bizarreness is mandated by POSIX */
560 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
564 /* initialise job control */
566 /* do this after j_init() which calls tty_init_state() */
567 if (Flag(FTALKING)) {
569 #ifndef MKSH_ASSUME_UTF8
570 /* auto-detect from locale or environment */
572 #else /* this may not be an #elif */
576 /* always disable UTF-8 (for interactive) */
581 #ifndef MKSH_NO_CMDLINE_EDITING
587 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
588 setsig(&sigtraps[SIGWINCH], x_sigwinch,
589 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
593 if (Flag(FAS_BUILTIN)) {
598 l->argc = argc - argi;
600 * allocate a new array because otherwise, when we modify
601 * it in-place, ps(1) output changes; the meaning of argc
602 * here is slightly different as it excludes kshname, and
603 * we add a trailing NULL sentinel as well
605 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
606 l->argv[0] = kshname;
607 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
608 l->argv[l->argc + 1] = NULL;
612 /* divine the initial state of the utf8-mode Flag */
616 /* auto-detect from locale or environment */
618 #if HAVE_SETLOCALE_CTYPE
619 ccp = setlocale(LC_CTYPE, "");
620 #if HAVE_LANGINFO_CODESET
622 ccp = nl_langinfo(CODESET);
629 /* auto-detect from environment */
631 /* these were imported from environ earlier */
633 ccp = str_val(global("LC_ALL"));
635 ccp = str_val(global("LC_CTYPE"));
637 ccp = str_val(global("LANG"));
641 /* not set on command line, not FTALKING */
655 /* Disable during .profile/ENV reading */
656 restricted_shell = Flag(FRESTRICTED);
657 Flag(FRESTRICTED) = 0;
658 errexit = Flag(FERREXIT);
662 * Do this before profile/$ENV so that if it causes problems in them,
663 * user will know why things broke.
665 if (!current_wd[0] && Flag(FTALKING))
666 warningf(false, "can't determine current directory");
669 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
670 if (!Flag(FPRIVILEGED)) {
672 include(substitute("$HOME/.profile", 0), 0, NULL, true);
673 if (Flag(FTALKING)) {
674 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
677 include(cp, 0, NULL, true);
680 include(MKSH_SUID_PROFILE, 0, NULL, true);
681 /* turn off -p if not set explicitly */
682 if (Flag(FPRIVILEGED) != 1)
683 change_flag(FPRIVILEGED, OF_INTERNAL, false);
686 if (restricted_shell) {
687 c_builtin(restr_com);
688 /* After typeset command... */
689 Flag(FRESTRICTED) = 1;
691 Flag(FERREXIT) = errexit;
693 if (Flag(FTALKING) && s)
706 /* this indirection barrier reduces stack usage during normal operation */
709 main(int argc, const char *argv[])
715 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
716 if (Flag(FAS_BUILTIN)) {
717 rv = c_builtin(l->argv);
727 include(const char *name, int argc, const char **argv, bool intr_ok)
729 Source *volatile s = NULL;
731 const char **volatile old_argv;
732 volatile int old_argc;
735 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
740 old_argv = e->loc->argv;
741 old_argc = e->loc->argc;
747 if ((i = kshsetjmp(e->jbuf))) {
748 quitenv(s ? s->u.shf : NULL);
750 e->loc->argv = old_argv;
751 e->loc->argc = old_argc;
757 return (exstat & 0xFF);
760 * intr_ok is set if we are including .profile or $ENV.
761 * If user ^Cs out, we don't want to kill the shell...
763 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
772 internal_errorf(Tunexpected_type, Tunwind, Tsource, i);
780 s = pushs(SFILE, ATEMP);
782 strdupx(s->file, name, ATEMP);
786 e->loc->argv = old_argv;
787 e->loc->argc = old_argc;
789 /* & 0xff to ensure value not -1 */
793 /* spawn a command into a shell optionally keeping track of the line number */
795 command(const char *comm, int line)
797 Source *s, *sold = source;
800 s = pushs(SSTRING, ATEMP);
801 s->start = s->str = comm;
809 * run the commands from the input source, returning status.
812 shell(Source * volatile s, volatile int level)
815 volatile bool wastty = tobool(s->flags & SF_TTY);
816 volatile uint8_t attempts = 13;
817 volatile bool interactive = (level == 0) && Flag(FTALKING);
818 volatile bool sfirst = true;
819 Source *volatile old_source = source;
822 newenv(level == 2 ? E_EVAL : E_PARSE);
825 switch ((i = kshsetjmp(e->jbuf))) {
833 internal_errorf(Tf_cant_s, Tshell,
834 i == LBREAK ? Tbreak : Tcontinue);
837 /* assert: interactive == false */
840 /* we get here if SIGINT not caught or ignored */
847 * Reset any eof that was read as part of a
850 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
853 * Used by exit command to get back to
854 * top level shell. Kind of strange since
855 * interactive is set if we are reading from
856 * a tty, but to have stopped jobs, one only
857 * needs FMONITOR set (not FTALKING/SF_TTY)...
859 /* toss any input we have so far */
860 yyrecursive_pop(true);
861 s->start = s->str = null;
878 internal_errorf(Tunexpected_type, Tunwind, Tshell, i);
881 while (/* CONSTCOND */ 1) {
885 if (s->next == NULL) {
889 s->flags &= ~SF_ECHO;
895 t = compile(s, sfirst, true);
897 histsave(&s->line, NULL, HIST_FLUSH, true);
901 if (t->type == TEOF) {
902 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
903 shellf("Use 'exit' to leave mksh\n");
905 } else if (wastty && !really_exit &&
906 j_stopped_running()) {
911 * this for POSIX which says EXIT traps
912 * shall be taken in the environment
913 * immediately after the last command
920 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
921 t->u.evalflags |= DOTCOMEXEC;
922 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
923 exstat = execute(t, 0, NULL) & 0xFF;
925 if (t->type != TEOF && interactive && really_exit)
933 return (exstat & 0xFF);
936 /* return to closest error handler or shell(), exit if none found */
937 /* note: i MUST NOT be 0 */
942 * This is a kludge. We need to restore everything that was
943 * changed in the new environment, see cid 1005090337C7A669439
944 * and 10050903386452ACBF1, but fail to even save things most of
945 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
946 * which needs to be restored thus (related to Debian #696823).
947 * We did not save the shell flags, so we use a special or'd
948 * value here... this is mostly to clean up behind *other*
949 * callers of unwind(LERROR) here; exec.c has the regular case.
951 if (Flag(FERREXIT) & 0x80) {
952 /* GNU bash does not run this trapsig */
954 Flag(FERREXIT) &= ~0x80;
957 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
958 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
959 sigtraps[ksh_SIGEXIT].trap &&
960 (!Flag(FTALKING) || Flag(FERREXIT)))) {
962 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
965 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
967 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
972 while (/* CONSTCOND */ 1) {
980 kshlongjmp(e->jbuf, i);
984 e->flags |= EF_FAKE_SIGDIE;
999 * struct env includes ALLOC_ITEM for alignment constraints
1000 * so first get the actually used memory, then assign it
1002 cp = alloc(sizeof(struct env) - sizeof(ALLOC_ITEM), ATEMP);
1003 /* undo what alloc() did to the malloc result address */
1004 ep = (void *)(cp - sizeof(ALLOC_ITEM));
1005 /* initialise public members of struct env (not the ALLOC_ITEM) */
1011 ep->yyrecursive_statep = NULL;
1014 /* jump buffer is invalid because flags == 0 */
1019 quitenv(struct shf *shf)
1025 yyrecursive_pop(true);
1026 while (ep->oenv && ep->oenv->loc != ep->loc)
1028 if (ep->savefd != NULL) {
1029 for (fd = 0; fd < NUFILE; fd++)
1030 /* if ep->savefd[fd] < 0, means fd was closed */
1032 restfd(fd, ep->savefd[fd]);
1034 /* Clear any write errors */
1035 shf_reopen(2, SHF_WR, shl_out);
1038 * Bottom of the stack.
1039 * Either main shell is exiting or cleanup_parents_env() was called.
1041 if (ep->oenv == NULL) {
1046 if (ep->type == E_NONE) {
1047 /* Main shell exiting? */
1048 #if HAVE_PERSISTENT_HISTORY
1053 if (ep->flags & EF_FAKE_SIGDIE) {
1054 int sig = (exstat & 0xFF) - 128;
1057 * ham up our death a bit (AT&T ksh
1058 * only seems to do this for SIGTERM)
1059 * Don't do it for SIGQUIT, since we'd
1062 if ((sig == SIGINT || sig == SIGTERM) &&
1063 (kshpgrp == kshpid)) {
1064 setsig(&sigtraps[sig], SIG_DFL,
1065 SS_RESTORE_CURR | SS_FORCE);
1074 #ifndef MKSH_NO_CMDLINE_EDITING
1077 #ifndef MKSH_NOPROSPECTOFWORK
1078 /* block at least SIGCHLD during/after afreeall */
1079 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1082 for (fd = 3; fd < NUFILE; fd++)
1083 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1090 exit(exstat & 0xFF);
1098 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1100 afree(cp + sizeof(ALLOC_ITEM), ATEMP);
1103 /* Called after a fork to cleanup stuff left over from parents environment */
1105 cleanup_parents_env(void)
1111 * Don't clean up temporary files - parent will probably need them.
1112 * Also, can't easily reclaim memory since variables, etc. could be
1116 /* close all file descriptors hiding in savefd */
1117 for (ep = e; ep; ep = ep->oenv) {
1119 for (fd = 0; fd < NUFILE; fd++)
1120 if (ep->savefd[fd] > 0)
1121 close(ep->savefd[fd]);
1122 afree(ep->savefd, &ep->area);
1126 if (ep->type != E_NONE)
1135 /* Called just before an execve cleanup stuff temporary files */
1137 cleanup_proc_env(void)
1141 for (ep = e; ep; ep = ep->oenv)
1142 remove_temps(ep->temps);
1145 /* remove temp files and free ATEMP Area */
1151 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1156 remove_temps(e->temps);
1160 * if the memory backing source is reclaimed, things
1161 * will end up badly when a function expecting it to
1162 * be valid is run; a NULL pointer is easily debugged
1164 if (source && source->areap == &e->area)
1170 remove_temps(struct temp *tp)
1173 if (tp->pid == procpid)
1180 * Initialise tty_fd. Used for tracking the size of the terminal,
1181 * saving/resetting tty modes upon forground job completion, and
1182 * for setting up the tty process group. Return values:
1183 * 0 = got controlling tty
1184 * 1 = got terminal but no controlling tty
1185 * 2 = cannot find a terminal
1187 * 4 = cannot make fd close-on-exec
1188 * An existing tty_fd is cached if no "better" one could be found,
1189 * i.e. if tty_devtty was already set or the new would not set it.
1194 int fd, rv, eno = 0;
1195 bool do_close = false, is_devtty = true;
1198 /* already got a tty which is /dev/tty */
1203 /*XXX imake style */
1205 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1210 if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
1217 /* already got a non-devtty one */
1223 if (isatty((fd = 0)) || isatty((fd = 2)))
1225 /* cannot find one */
1227 /* assert: do_close == false */
1231 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1236 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1243 tty_devtty = is_devtty;
1252 /* A shell error occurred (eg, syntax error, etc.) */
1254 #define VWARNINGF_ERRORPREFIX 1
1255 #define VWARNINGF_FILELINE 2
1256 #define VWARNINGF_BUILTIN 4
1257 #define VWARNINGF_INTERNAL 8
1259 static void vwarningf(unsigned int, const char *, va_list)
1260 MKSH_A_FORMAT(__printf__, 2, 0);
1263 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1266 if (flags & VWARNINGF_INTERNAL)
1267 shf_fprintf(shl_out, Tf_sD_, "internal error");
1268 if (flags & VWARNINGF_ERRORPREFIX)
1269 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1270 if ((flags & VWARNINGF_BUILTIN) &&
1271 /* not set when main() calls parse_args() */
1272 builtin_argv0 && builtin_argv0 != kshname)
1273 shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
1274 shf_vfprintf(shl_out, fmt, ap);
1275 shf_putchar('\n', shl_out);
1281 errorfx(int rc, const char *fmt, ...)
1287 /* debugging: note that stdout not valid */
1288 shl_stdout_ok = false;
1291 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1297 errorf(const char *fmt, ...)
1303 /* debugging: note that stdout not valid */
1304 shl_stdout_ok = false;
1307 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1312 /* like errorf(), but no unwind is done */
1314 warningf(bool fileline, const char *fmt, ...)
1319 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1325 * Used by built-in utilities to prefix shell and utility name to message
1326 * (also unwinds environments for special builtins).
1329 bi_errorf(const char *fmt, ...)
1333 /* debugging: note that stdout not valid */
1334 shl_stdout_ok = false;
1339 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1340 VWARNINGF_BUILTIN, fmt, va);
1343 /* POSIX special builtins cause non-interactive shells to exit */
1345 builtin_argv0 = NULL;
1346 /* may not want to use LERROR here */
1351 /* Called when something that shouldn't happen does */
1353 internal_errorf(const char *fmt, ...)
1358 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1364 internal_warningf(const char *fmt, ...)
1369 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1373 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1375 error_prefix(bool fileline)
1377 /* Avoid foo: foo[2]: ... */
1378 if (!fileline || !source || !source->file ||
1379 strcmp(source->file, kshname) != 0)
1380 shf_fprintf(shl_out, Tf_sD_, kshname + (*kshname == '-'));
1381 if (fileline && source && source->file != NULL) {
1382 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1383 (unsigned long)(source->errline ?
1384 source->errline : source->line));
1385 source->errline = 0;
1389 /* printf to shl_out (stderr) with flush */
1391 shellf(const char *fmt, ...)
1396 /* shl_out may not be set up yet... */
1399 shf_vfprintf(shl_out, fmt, va);
1404 /* printf to shl_stdout (stdout) */
1406 shprintf(const char *fmt, ...)
1411 internal_errorf("shl_stdout not valid");
1413 shf_vfprintf(shl_stdout, fmt, va);
1417 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1423 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1433 struct shf shf_iob[NSHF_IOB];
1442 /* force buffer allocation */
1443 shf_fdopen(1, SHF_WR, shl_stdout);
1444 shf_fdopen(2, SHF_WR, shl_out);
1445 shf_fdopen(2, SHF_WR, shl_xtrace);
1447 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1448 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1449 errorf("can't get home directory");
1450 lfp = shf_smprintf(Tf_sSs, lfp, "mksh-dbg.txt");
1453 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1454 errorf("can't open debug output file %s", lfp);
1455 if (shl_dbg_fd < FDBASE) {
1458 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1460 if ((shl_dbg_fd = nfd) == -1)
1461 errorf("can't dup debug output file");
1463 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1464 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1470 /* A dup2() with error checking */
1472 ksh_dup2(int ofd, int nfd, bool errok)
1476 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1477 errorf(Ttoo_many_files);
1480 /*XXX imake style */
1482 fcntl(nfd, F_SETFD, 0);
1489 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1490 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1497 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1498 (errno == EBADF || errno == EPERM))
1500 if (nfd < 0 || nfd > SHRT_MAX)
1501 errorf(Ttoo_many_files);
1502 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1503 return ((short)nfd);
1507 restfd(int fd, int ofd)
1510 shf_flush(&shf_iob[/* fd */ 2]);
1512 /* original fd closed */
1514 else if (fd != ofd) {
1515 /*XXX: what to do if this dup fails? */
1516 ksh_dup2(ofd, fd, true);
1527 errorf("can't create pipe - try again");
1528 pv[0] = savefd(lpv[0]);
1529 if (pv[0] != lpv[0])
1531 pv[1] = savefd(lpv[1]);
1532 if (pv[1] != lpv[1])
1535 setmode(pv[0], O_BINARY);
1536 setmode(pv[1], O_BINARY);
1548 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1549 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1552 check_fd(const char *name, int mode, const char **emsgp)
1556 if (!name[0] || name[1])
1557 goto illegal_fd_name;
1559 return (coproc_getfd(mode, emsgp));
1560 if (!ctype(name[0], C_DIGIT)) {
1563 *emsgp = "illegal file descriptor name";
1567 if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
1569 *emsgp = "bad file descriptor";
1574 * X_OK is a kludge to disable this check for dups (x<&1):
1575 * historical shells never did this check (XXX don't know what
1576 * POSIX has to say).
1578 if (!(mode & X_OK) && fl != O_RDWR && (
1579 ((mode & R_OK) && fl != O_RDONLY) ||
1580 ((mode & W_OK) && fl != O_WRONLY))) {
1582 *emsgp = (fl == O_WRONLY) ?
1583 "fd not open for reading" :
1584 "fd not open for writing";
1590 /* Called once from main */
1594 coproc.read = coproc.readw = coproc.write = -1;
1599 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1601 coproc_read_close(int fd)
1603 if (coproc.read >= 0 && fd == coproc.read) {
1604 coproc_readw_close(fd);
1611 * Called by c_read() and by iosetup() to close the other side of the
1612 * read pipe, so reads will actually terminate.
1615 coproc_readw_close(int fd)
1617 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1618 close(coproc.readw);
1624 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1625 * when co-process input is dup'd
1628 coproc_write_close(int fd)
1630 if (coproc.write >= 0 && fd == coproc.write) {
1631 close(coproc.write);
1637 * Called to check for existence of/value of the co-process file descriptor.
1638 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1641 coproc_getfd(int mode, const char **emsgp)
1643 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1648 *emsgp = "no coprocess";
1653 * called to close file descriptors related to the coprocess (if any)
1654 * Should be called with SIGCHLD blocked.
1657 coproc_cleanup(int reuse)
1659 /* This to allow co-processes to share output pipe */
1660 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1661 if (coproc.read >= 0) {
1665 if (coproc.readw >= 0) {
1666 close(coproc.readw);
1670 if (coproc.write >= 0) {
1671 close(coproc.write);
1677 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1686 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1687 /* add "/shXXXXXX.tmp" plus NUL */
1689 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1690 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1696 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1702 cp += offsetof(struct temp, tffn[0]);
1703 memcpy(cp, dir, len);
1705 memcpy(cp, "/shXXXXXX.tmp", 14);
1706 /* point to the first of six Xes */
1709 /* cyclically attempt to open a temporary file */
1711 /* generate random part of filename */
1714 cp[len++] = digits_lc[rndget() % 36];
1717 /* check if this one works */
1718 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1719 0600)) < 0 && errno != EEXIST)
1723 if (type == TT_FUNSUB) {
1724 /* map us high and mark as close-on-exec */
1725 if ((j = savefd(i)) != i) {
1730 /* operation mode for the shf */
1735 /* shf_fdopen cannot fail, so no fd leak */
1736 tp->shf = shf_fdopen(i, j, NULL);
1745 * We use a similar collision resolution algorithm as Python 2.5.4
1746 * but with a slightly tweaked implementation written from scratch.
1749 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1750 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1752 static void tgrow(struct table *);
1753 static int tnamecmp(const void *, const void *);
1756 tgrow(struct table *tp)
1758 size_t i, j, osize, mask, perturb;
1759 struct tbl *tblp, **pp;
1760 struct tbl **ntblp, **otblp = tp->tbls;
1762 if (tp->tshift > 29)
1763 internal_errorf("hash table size limit reached");
1765 /* calculate old size, new shift and new size */
1766 osize = (size_t)1 << (tp->tshift++);
1769 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1770 /* multiplication cannot overflow: alloc2 checked that */
1771 memset(ntblp, 0, i * sizeof(struct tbl *));
1773 /* table can get very full when reaching its size limit */
1774 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1775 /* but otherwise, only 75% */
1782 for (i = 0; i < osize; i++)
1783 if ((tblp = otblp[i]) != NULL) {
1784 if ((tblp->flag & DEFINED)) {
1785 /* search for free hash table slot */
1786 j = perturb = tblp->ua.hval;
1787 goto find_first_empty_slot;
1788 find_next_empty_slot:
1789 j = (j << 2) + j + perturb + 1;
1790 perturb >>= PERTURB_SHIFT;
1791 find_first_empty_slot:
1792 pp = &ntblp[j & mask];
1794 goto find_next_empty_slot;
1795 /* found an empty hash table slot */
1798 } else if (!(tblp->flag & FINUSE)) {
1799 afree(tblp, tp->areap);
1802 afree(otblp, tp->areap);
1806 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1810 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1811 initshift : INIT_TBLSHIFT) - 1;
1815 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1817 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1819 size_t j, perturb, mask;
1820 struct tbl **pp, *p;
1822 mask = ((size_t)1 << (tp->tshift)) - 1;
1823 /* search for hash table slot matching name */
1825 goto find_first_slot;
1827 j = (j << 2) + j + perturb + 1;
1828 perturb >>= PERTURB_SHIFT;
1830 pp = &tp->tbls[j & mask];
1831 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1832 strcmp(p->name, name)))
1833 goto find_next_slot;
1834 /* p == NULL if not found, correct found entry otherwise */
1840 /* table, name (key) to enter, hash(n) */
1842 ktenter(struct table *tp, const char *n, uint32_t h)
1844 struct tbl **pp, *p;
1848 if ((p = ktscan(tp, n, h, &pp)))
1851 if (tp->nfree == 0) {
1857 /* create new tbl entry */
1859 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1860 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1863 p->areap = tp->areap;
1867 memcpy(p->name, n, len);
1869 /* enter in tp->tbls */
1876 ktwalk(struct tstate *ts, struct table *tp)
1878 ts->left = (size_t)1 << (tp->tshift);
1879 ts->next = tp->tbls;
1883 ktnext(struct tstate *ts)
1885 while (--ts->left >= 0) {
1886 struct tbl *p = *ts->next++;
1887 if (p != NULL && (p->flag & DEFINED))
1894 tnamecmp(const void *p1, const void *p2)
1896 const struct tbl *a = *((const struct tbl * const *)p1);
1897 const struct tbl *b = *((const struct tbl * const *)p2);
1899 return (ascstrcmp(a->name, b->name));
1903 ktsort(struct table *tp)
1906 struct tbl **p, **sp, **dp;
1909 * since the table is never entirely full, no need to reserve
1910 * additional space for the trailing NULL appended below
1912 i = (size_t)1 << (tp->tshift);
1913 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1914 sp = tp->tbls; /* source */
1917 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1918 ((*dp)->flag & ARRAY)))
1920 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1927 x_sigwinch(int sig MKSH_A_UNUSED)
1929 /* this runs inside interrupt context, with errno saved */
1937 DF(const char *fmt, ...)
1943 mksh_lockfd(shl_dbg_fd);
1945 timet2mjd(&mjd, tv.tv_sec);
1946 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1947 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1948 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1949 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1950 va_start(args, fmt);
1951 shf_vfprintf(shl_dbg, fmt, args);
1953 shf_putc('\n', shl_dbg);
1955 mksh_unlkfd(shl_dbg_fd);
1960 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1965 mksh_tcget(fd, ocb);
1971 cb.c_iflag &= ~(ISTRIP);
1972 cb.c_lflag &= ~(ICANON) | ECHO;
1974 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1975 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1977 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1978 /* OSF/1 processes lnext when ~icanon */
1979 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1981 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1982 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1983 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1988 mksh_tcset(fd, &cb);