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
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.322 2016/11/11 23:48:30 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[] =
69 static const char *initcoms[] = {
70 Ttypeset, "-r", initvsn, NULL,
71 Ttypeset, "-x", "HOME", TPATH, TSHELL, NULL,
72 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
74 "integer=\\typeset -i",
76 /* not "alias -t --": hash -r needs to work */
77 "hash=\\builtin alias -t",
78 "type=\\builtin whence -v",
79 "autoload=\\typeset -fu",
80 "functions=\\typeset -f",
81 "history=\\builtin fc -l",
82 "nameref=\\typeset -n",
84 "r=\\builtin fc -e -",
87 /* this is what AT&T ksh seems to track, with the addition of emacs */
89 Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
90 "make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
94 static const char *restr_com[] = {
95 Ttypeset, "-r", TPATH, "ENV", TSHELL, NULL
98 static bool initio_done;
100 /* top-level parsing and execution environment */
101 static struct env env;
102 struct env *e = &env;
109 ALLOC_ITEM alloc_INT;
110 void *dataptr, *stkptr, *mallocptr;
111 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
118 cp = alloc(sizeof(*bufptr) - sizeof(ALLOC_ITEM), APERM);
119 /* clear the allocated space, for valgrind and to avoid UB */
120 memset(cp, 0, sizeof(*bufptr) - sizeof(ALLOC_ITEM));
121 /* undo what alloc() did to the malloc result address */
122 bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
123 /* PIE or something similar provides us with deltas here */
124 bufptr->dataptr = &rndsetupstate;
125 /* ASLR in at least Windows, Linux, some BSDs */
126 bufptr->stkptr = &bufptr;
127 /* randomised malloc in BSD (and possibly others) */
128 bufptr->mallocptr = bufptr;
129 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
130 /* glibc pointer guard */
131 sigsetjmp(bufptr->jbuf, 1);
133 /* introduce variation (and yes, second arg MBZ for portability) */
134 mksh_TIME(bufptr->tv);
136 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
137 mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
139 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
142 return ((mksh_uari_t)h);
148 kshpid = procpid = getpid();
154 static const char *empty_argv[] = {
159 isuc(const char *cx) {
166 /* uppercase a string duplicate */
167 strdupx(x, cx, ATEMP);
169 while ((*cp = ksh_toupper(*cp)))
172 /* check for UTF-8 */
173 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
176 /* free copy and out */
182 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
187 unsigned char restricted_shell, errexit, utf_flag;
189 const char *ccp, **wp;
192 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
197 for (i = 0; i < 3; ++i)
199 setmode(i, O_BINARY);
202 /* do things like getpgrp() et al. */
205 /* make sure argv[] is sane, for weird OSes */
212 /* initialise permanent Area */
214 /* max. name length: -2147483648 = 11 (+ NUL) */
215 vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
217 /* set up base environment */
220 /* set up global l->vars and l->funs */
223 /* Do this first so output routines (eg, errorf, shellf) can work */
226 /* determine the basename (without '-' or path) of the executable */
228 goto begin_parsing_kshname;
229 while ((i = ccp[argi++])) {
230 if (mksh_cdirsep(i)) {
232 begin_parsing_kshname:
242 * Turn on nohup by default. (AT&T ksh does not have a nohup
243 * option - it always sends the hup).
248 * Turn on brace expansion by default. AT&T kshs that have
249 * alternation always have it on.
251 Flag(FBRACEEXPAND) = 1;
254 * Turn on "set -x" inheritance by default.
256 Flag(FXTRACEREC) = 1;
258 /* define built-in commands and see if we were called as one */
259 ktinit(APERM, &builtins,
260 /* currently up to 54 builtins: 75% of 128 = 2^7 */
262 for (i = 0; mkshbuiltins[i].name != NULL; i++)
263 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
264 mkshbuiltins[i].func)))
265 Flag(FAS_BUILTIN) = 1;
267 if (!Flag(FAS_BUILTIN)) {
268 /* check for -T option early */
269 argi = parse_args(argv, OF_FIRSTTIME, NULL);
273 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
274 /* are we called as -sh or /bin/sh or so? */
275 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
276 /* either also turns off braceexpand */
277 #ifdef MKSH_BINSHPOSIX
278 /* enable better POSIX conformance */
279 change_flag(FPOSIX, OF_FIRSTTIME, true);
281 #ifdef MKSH_BINSHREDUCED
282 /* enable kludge/compat mode */
283 change_flag(FSH, OF_FIRSTTIME, true);
297 /* set up variable and command dictionaries */
298 ktinit(APERM, &taliases, 0);
299 ktinit(APERM, &aliases, 0);
301 ktinit(APERM, &homedirs, 0);
304 /* define shell keywords */
309 /* initialise tty size before importing environment */
313 def_path = _PATH_DEFPATH;
316 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
317 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
322 * this is uniform across all OSes unless it
323 * breaks somewhere hard; don't try to optimise,
324 * e.g. add stuff for Interix or remove /usr
325 * for HURD, because e.g. Debian GNU/HURD is
326 * "keeping a regular /usr"; this is supposed
327 * to be a sane 'basic' default PATH
329 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
330 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
331 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
332 MKSH_UNIXROOT "/usr/sbin";
336 * Set PATH to def_path (will set the path global variable).
337 * (import of environment below will probably change this setting).
340 /* setstr can't fail here */
341 setstr(vp, def_path, KSH_RETURN_ERROR);
343 #ifndef MKSH_NO_CMDLINE_EDITING
345 * Set edit mode to emacs by default, may be overridden
346 * by the environment or the user. Also, we want tab completion
347 * on in vi by default.
349 change_flag(FEMACS, OF_SPECIAL, true);
351 Flag(FVITABCOMPLETE) = 1;
355 /* import environment */
356 if (environ != NULL) {
357 wp = (const char **)environ;
358 while (*wp != NULL) {
360 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
366 typeset(initifs, 0, 0, 0, 0);
368 /* assign default shell variable values */
369 substitute(initsubs, 0);
371 /* Figure out the current working directory and set $PWD */
374 /* Try to use existing $PWD if it is valid */
375 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
376 Tdot, true)) ? cp : NULL);
378 simplify_path(current_wd);
379 /* Only set pwd if we know where we are or if it had a bogus value */
380 if (current_wd[0] || *cp)
381 /* setstr can't fail here */
382 setstr(vp, current_wd, KSH_RETURN_ERROR);
384 for (wp = initcoms; *wp != NULL; wp++) {
389 setint_n(global("OPTIND"), 1, 10);
395 safe_prompt = ksheuid ? "$ " : "# ";
397 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
398 if (!(vp->flag & ISSET) ||
399 (!ksheuid && !strchr(str_val(vp), '#')))
400 /* setstr can't fail here */
401 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
402 setint_n((vp = global("BASHPID")), 0, 10);
404 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
406 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
408 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
410 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
412 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
414 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
416 setint_n((vp = global("RANDOM")), rndsetup(), 10);
418 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
420 /* Set this before parsing arguments */
421 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
423 /* this to note if monitor is set on command line (see below) */
424 #ifndef MKSH_UNEMPLOYED
425 Flag(FMONITOR) = 127;
427 /* this to note if utf-8 mode is set on command line (see below) */
430 if (!Flag(FAS_BUILTIN)) {
431 argi = parse_args(argv, OF_CMDLINE, NULL);
436 /* process this later only, default to off (hysterical raisins) */
440 if (Flag(FAS_BUILTIN)) {
441 /* auto-detect from environment variables, always */
443 } else if (Flag(FCOMMAND)) {
444 s = pushs(SSTRINGCMDLINE, ATEMP);
445 if (!(s->start = s->str = argv[argi++]))
446 errorf(Tf_optfoo, "", "", 'c', Treq_arg);
448 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
453 s->flags |= SF_MAYEXEC;
455 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
456 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
457 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
461 kshname = argv[argi++];
462 } else if (argi < argc && !Flag(FSTDIN)) {
463 s = pushs(SFILE, ATEMP);
466 * A bug in OS/2 extproc (like shebang) handling makes
467 * it not pass the full pathname of a script, so we need
468 * to search for it. This changes the behaviour of a
469 * simple "mksh foo", but can't be helped.
471 s->file = search_path(argv[argi++], path, X_OK, NULL);
472 if (!s->file || !*s->file)
473 s->file = argv[argi - 1];
475 s->file = argv[argi++];
477 s->u.shf = shf_open(s->file, O_RDONLY, 0,
478 SHF_MAPHI | SHF_CLEXEC);
479 if (s->u.shf == NULL) {
480 shl_stdout_ok = false;
481 warningf(true, Tf_sD_s, s->file, cstrerror(errno));
482 /* mandated by SUSv4 */
489 s = pushs(SSTDIN, ATEMP);
491 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
493 if (isatty(0) && isatty(2)) {
494 Flag(FTALKING) = Flag(FTALKING_I) = 1;
495 /* The following only if isatty(0) */
497 s->u.shf->flags |= SHF_INTERRUPT;
502 /* this bizarreness is mandated by POSIX */
503 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
507 /* initialise job control */
509 /* do this after j_init() which calls tty_init_state() */
510 if (Flag(FTALKING)) {
512 #ifndef MKSH_ASSUME_UTF8
513 /* auto-detect from locale or environment */
515 #else /* this may not be an #elif */
519 /* always disable UTF-8 (for interactive) */
524 #ifndef MKSH_NO_CMDLINE_EDITING
530 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
531 setsig(&sigtraps[SIGWINCH], x_sigwinch,
532 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
536 if (Flag(FAS_BUILTIN)) {
541 l->argc = argc - argi;
543 * allocate a new array because otherwise, when we modify
544 * it in-place, ps(1) output changes; the meaning of argc
545 * here is slightly different as it excludes kshname, and
546 * we add a trailing NULL sentinel as well
548 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
549 l->argv[0] = kshname;
550 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
551 l->argv[l->argc + 1] = NULL;
555 /* divine the initial state of the utf8-mode Flag */
559 /* auto-detect from locale or environment */
561 #if HAVE_SETLOCALE_CTYPE
562 ccp = setlocale(LC_CTYPE, "");
563 #if HAVE_LANGINFO_CODESET
565 ccp = nl_langinfo(CODESET);
572 /* auto-detect from environment */
574 /* these were imported from environ earlier */
576 ccp = str_val(global("LC_ALL"));
578 ccp = str_val(global("LC_CTYPE"));
580 ccp = str_val(global("LANG"));
584 /* not set on command line, not FTALKING */
598 /* Disable during .profile/ENV reading */
599 restricted_shell = Flag(FRESTRICTED);
600 Flag(FRESTRICTED) = 0;
601 errexit = Flag(FERREXIT);
605 * Do this before profile/$ENV so that if it causes problems in them,
606 * user will know why things broke.
608 if (!current_wd[0] && Flag(FTALKING))
609 warningf(false, "can't determine current directory");
612 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
613 if (!Flag(FPRIVILEGED)) {
615 include(substitute("$HOME/.profile", 0), 0, NULL, true);
616 if (Flag(FTALKING)) {
617 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
620 include(cp, 0, NULL, true);
623 include(MKSH_SUID_PROFILE, 0, NULL, true);
624 /* turn off -p if not set explicitly */
625 if (Flag(FPRIVILEGED) != 1)
626 change_flag(FPRIVILEGED, OF_INTERNAL, false);
629 if (restricted_shell) {
630 shcomexec(restr_com);
631 /* After typeset command... */
632 Flag(FRESTRICTED) = 1;
634 Flag(FERREXIT) = errexit;
636 if (Flag(FTALKING) && s)
649 /* this indirection barrier reduces stack usage during normal operation */
652 main(int argc, const char *argv[])
658 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
659 if (Flag(FAS_BUILTIN)) {
660 rv = shcomexec(l->argv);
670 include(const char *name, int argc, const char **argv, bool intr_ok)
672 Source *volatile s = NULL;
674 const char **volatile old_argv;
675 volatile int old_argc;
678 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
683 old_argv = e->loc->argv;
684 old_argc = e->loc->argc;
690 if ((i = kshsetjmp(e->jbuf))) {
691 quitenv(s ? s->u.shf : NULL);
693 e->loc->argv = old_argv;
694 e->loc->argc = old_argc;
700 return (exstat & 0xFF);
703 * intr_ok is set if we are including .profile or $ENV.
704 * If user ^Cs out, we don't want to kill the shell...
706 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
715 internal_errorf("include %d", i);
723 s = pushs(SFILE, ATEMP);
725 strdupx(s->file, name, ATEMP);
729 e->loc->argv = old_argv;
730 e->loc->argc = old_argc;
732 /* & 0xff to ensure value not -1 */
736 /* spawn a command into a shell optionally keeping track of the line number */
738 command(const char *comm, int line)
740 Source *s, *sold = source;
743 s = pushs(SSTRING, ATEMP);
744 s->start = s->str = comm;
746 rv = shell(s, false);
752 * run the commands from the input source, returning status.
755 shell(Source * volatile s, volatile bool toplevel)
758 volatile bool wastty = tobool(s->flags & SF_TTY);
759 volatile uint8_t attempts = 13;
760 volatile bool interactive = Flag(FTALKING) && toplevel;
761 volatile bool sfirst = true;
762 Source *volatile old_source = source;
768 switch ((i = kshsetjmp(e->jbuf))) {
772 /* we get here if SIGINT not caught or ignored */
779 * Reset any eof that was read as part of a
782 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
785 * Used by exit command to get back to
786 * top level shell. Kind of strange since
787 * interactive is set if we are reading from
788 * a tty, but to have stopped jobs, one only
789 * needs FMONITOR set (not FTALKING/SF_TTY)...
791 /* toss any input we have so far */
792 yyrecursive_pop(true);
793 s->start = s->str = null;
810 internal_errorf("shell %d", i);
813 while (/* CONSTCOND */ 1) {
817 if (s->next == NULL) {
821 s->flags &= ~SF_ECHO;
827 t = compile(s, sfirst);
829 histsave(&s->line, NULL, HIST_FLUSH, true);
833 if (t->type == TEOF) {
834 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
835 shellf("Use 'exit' to leave mksh\n");
837 } else if (wastty && !really_exit &&
838 j_stopped_running()) {
843 * this for POSIX which says EXIT traps
844 * shall be taken in the environment
845 * immediately after the last command
852 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
853 t->u.evalflags |= DOTCOMEXEC;
854 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
855 exstat = execute(t, 0, NULL) & 0xFF;
857 if (t->type != TEOF && interactive && really_exit)
865 return (exstat & 0xFF);
868 /* return to closest error handler or shell(), exit if none found */
869 /* note: i MUST NOT be 0 */
874 * This is a kludge. We need to restore everything that was
875 * changed in the new environment, see cid 1005090337C7A669439
876 * and 10050903386452ACBF1, but fail to even save things most of
877 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
878 * which needs to be restored thus (related to Debian #696823).
879 * We did not save the shell flags, so we use a special or'd
880 * value here... this is mostly to clean up behind *other*
881 * callers of unwind(LERROR) here; exec.c has the regular case.
883 if (Flag(FERREXIT) & 0x80) {
884 /* GNU bash does not run this trapsig */
886 Flag(FERREXIT) &= ~0x80;
889 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
890 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
891 sigtraps[ksh_SIGEXIT].trap &&
892 (!Flag(FTALKING) || Flag(FERREXIT)))) {
894 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
897 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
899 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
904 while (/* CONSTCOND */ 1) {
911 kshlongjmp(e->jbuf, i);
915 e->flags |= EF_FAKE_SIGDIE;
930 * struct env includes ALLOC_ITEM for alignment constraints
931 * so first get the actually used memory, then assign it
933 cp = alloc(sizeof(struct env) - sizeof(ALLOC_ITEM), ATEMP);
934 /* undo what alloc() did to the malloc result address */
935 ep = (void *)(cp - sizeof(ALLOC_ITEM));
936 /* initialise public members of struct env (not the ALLOC_ITEM) */
942 ep->yyrecursive_statep = NULL;
945 /* jump buffer is invalid because flags == 0 */
950 quitenv(struct shf *shf)
956 yyrecursive_pop(true);
957 while (ep->oenv && ep->oenv->loc != ep->loc)
959 if (ep->savefd != NULL) {
960 for (fd = 0; fd < NUFILE; fd++)
961 /* if ep->savefd[fd] < 0, means fd was closed */
963 restfd(fd, ep->savefd[fd]);
965 /* Clear any write errors */
966 shf_reopen(2, SHF_WR, shl_out);
969 * Bottom of the stack.
970 * Either main shell is exiting or cleanup_parents_env() was called.
972 if (ep->oenv == NULL) {
977 if (ep->type == E_NONE) {
978 /* Main shell exiting? */
979 #if HAVE_PERSISTENT_HISTORY
984 if (ep->flags & EF_FAKE_SIGDIE) {
985 int sig = (exstat & 0xFF) - 128;
988 * ham up our death a bit (AT&T ksh
989 * only seems to do this for SIGTERM)
990 * Don't do it for SIGQUIT, since we'd
993 if ((sig == SIGINT || sig == SIGTERM) &&
994 (kshpgrp == kshpid)) {
995 setsig(&sigtraps[sig], SIG_DFL,
996 SS_RESTORE_CURR | SS_FORCE);
1005 #ifndef MKSH_NO_CMDLINE_EDITING
1008 #ifndef MKSH_NOPROSPECTOFWORK
1009 /* block at least SIGCHLD during/after afreeall */
1010 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1013 for (fd = 3; fd < NUFILE; fd++)
1014 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1021 exit(exstat & 0xFF);
1029 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1031 afree(cp + sizeof(ALLOC_ITEM), ATEMP);
1034 /* Called after a fork to cleanup stuff left over from parents environment */
1036 cleanup_parents_env(void)
1042 * Don't clean up temporary files - parent will probably need them.
1043 * Also, can't easily reclaim memory since variables, etc. could be
1047 /* close all file descriptors hiding in savefd */
1048 for (ep = e; ep; ep = ep->oenv) {
1050 for (fd = 0; fd < NUFILE; fd++)
1051 if (ep->savefd[fd] > 0)
1052 close(ep->savefd[fd]);
1053 afree(ep->savefd, &ep->area);
1057 if (ep->type != E_NONE)
1066 /* Called just before an execve cleanup stuff temporary files */
1068 cleanup_proc_env(void)
1072 for (ep = e; ep; ep = ep->oenv)
1073 remove_temps(ep->temps);
1076 /* remove temp files and free ATEMP Area */
1082 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1087 remove_temps(e->temps);
1091 * if the memory backing source is reclaimed, things
1092 * will end up badly when a function expecting it to
1093 * be valid is run; a NULL pointer is easily debugged
1095 if (source && source->areap == &e->area)
1101 remove_temps(struct temp *tp)
1104 if (tp->pid == procpid)
1111 * Initialise tty_fd. Used for tracking the size of the terminal,
1112 * saving/resetting tty modes upon forground job completion, and
1113 * for setting up the tty process group. Return values:
1114 * 0 = got controlling tty
1115 * 1 = got terminal but no controlling tty
1116 * 2 = cannot find a terminal
1118 * 4 = cannot make fd close-on-exec
1119 * An existing tty_fd is cached if no "better" one could be found,
1120 * i.e. if tty_devtty was already set or the new would not set it.
1125 int fd, rv, eno = 0;
1126 bool do_close = false, is_devtty = true;
1129 /* already got a tty which is /dev/tty */
1134 /*XXX imake style */
1136 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1141 if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
1148 /* already got a non-devtty one */
1154 if (isatty((fd = 0)) || isatty((fd = 2)))
1156 /* cannot find one */
1158 /* assert: do_close == false */
1162 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1167 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1174 tty_devtty = is_devtty;
1183 /* A shell error occurred (eg, syntax error, etc.) */
1185 #define VWARNINGF_ERRORPREFIX 1
1186 #define VWARNINGF_FILELINE 2
1187 #define VWARNINGF_BUILTIN 4
1188 #define VWARNINGF_INTERNAL 8
1190 static void vwarningf(unsigned int, const char *, va_list)
1191 MKSH_A_FORMAT(__printf__, 2, 0);
1194 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1197 if (flags & VWARNINGF_INTERNAL)
1198 shf_fprintf(shl_out, Tf_sD_, "internal error");
1199 if (flags & VWARNINGF_ERRORPREFIX)
1200 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1201 if ((flags & VWARNINGF_BUILTIN) &&
1202 /* not set when main() calls parse_args() */
1203 builtin_argv0 && builtin_argv0 != kshname)
1204 shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
1205 shf_vfprintf(shl_out, fmt, ap);
1206 shf_putchar('\n', shl_out);
1212 errorfx(int rc, const char *fmt, ...)
1218 /* debugging: note that stdout not valid */
1219 shl_stdout_ok = false;
1222 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1228 errorf(const char *fmt, ...)
1234 /* debugging: note that stdout not valid */
1235 shl_stdout_ok = false;
1238 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1243 /* like errorf(), but no unwind is done */
1245 warningf(bool fileline, const char *fmt, ...)
1250 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1256 * Used by built-in utilities to prefix shell and utility name to message
1257 * (also unwinds environments for special builtins).
1260 bi_errorf(const char *fmt, ...)
1264 /* debugging: note that stdout not valid */
1265 shl_stdout_ok = false;
1270 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1271 VWARNINGF_BUILTIN, fmt, va);
1275 * POSIX special builtins and ksh special builtins cause
1276 * non-interactive shells to exit. XXX may not want LERROR here
1279 builtin_argv0 = NULL;
1284 /* Called when something that shouldn't happen does */
1286 internal_errorf(const char *fmt, ...)
1291 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1297 internal_warningf(const char *fmt, ...)
1302 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1306 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1308 error_prefix(bool fileline)
1310 /* Avoid foo: foo[2]: ... */
1311 if (!fileline || !source || !source->file ||
1312 strcmp(source->file, kshname) != 0)
1313 shf_fprintf(shl_out, Tf_sD_, kshname + (*kshname == '-'));
1314 if (fileline && source && source->file != NULL) {
1315 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1316 (unsigned long)(source->errline ?
1317 source->errline : source->line));
1318 source->errline = 0;
1322 /* printf to shl_out (stderr) with flush */
1324 shellf(const char *fmt, ...)
1329 /* shl_out may not be set up yet... */
1332 shf_vfprintf(shl_out, fmt, va);
1337 /* printf to shl_stdout (stdout) */
1339 shprintf(const char *fmt, ...)
1344 internal_errorf("shl_stdout not valid");
1346 shf_vfprintf(shl_stdout, fmt, va);
1350 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1356 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1366 struct shf shf_iob[NSHF_IOB];
1375 /* force buffer allocation */
1376 shf_fdopen(1, SHF_WR, shl_stdout);
1377 shf_fdopen(2, SHF_WR, shl_out);
1378 shf_fdopen(2, SHF_WR, shl_xtrace);
1380 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1381 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1382 errorf("cannot get home directory");
1383 lfp = shf_smprintf(Tf_sSs, lfp, "mksh-dbg.txt");
1386 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1387 errorf("cannot open debug output file %s", lfp);
1388 if (shl_dbg_fd < FDBASE) {
1391 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1393 if ((shl_dbg_fd = nfd) == -1)
1394 errorf("cannot dup debug output file");
1396 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1397 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1403 /* A dup2() with error checking */
1405 ksh_dup2(int ofd, int nfd, bool errok)
1409 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1410 errorf("too many files open in shell");
1413 /*XXX imake style */
1415 fcntl(nfd, F_SETFD, 0);
1422 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1423 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1430 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1431 (errno == EBADF || errno == EPERM))
1433 if (nfd < 0 || nfd > SHRT_MAX)
1434 errorf("too many files open in shell");
1435 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1436 return ((short)nfd);
1440 restfd(int fd, int ofd)
1443 shf_flush(&shf_iob[/* fd */ 2]);
1445 /* original fd closed */
1447 else if (fd != ofd) {
1448 /*XXX: what to do if this dup fails? */
1449 ksh_dup2(ofd, fd, true);
1460 errorf("can't create pipe - try again");
1461 pv[0] = savefd(lpv[0]);
1462 if (pv[0] != lpv[0])
1464 pv[1] = savefd(lpv[1]);
1465 if (pv[1] != lpv[1])
1477 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1478 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1481 check_fd(const char *name, int mode, const char **emsgp)
1485 if (!name[0] || name[1])
1486 goto illegal_fd_name;
1488 return (coproc_getfd(mode, emsgp));
1489 if (!ksh_isdigit(name[0])) {
1492 *emsgp = "illegal file descriptor name";
1496 if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
1498 *emsgp = "bad file descriptor";
1503 * X_OK is a kludge to disable this check for dups (x<&1):
1504 * historical shells never did this check (XXX don't know what
1505 * POSIX has to say).
1507 if (!(mode & X_OK) && fl != O_RDWR && (
1508 ((mode & R_OK) && fl != O_RDONLY) ||
1509 ((mode & W_OK) && fl != O_WRONLY))) {
1511 *emsgp = (fl == O_WRONLY) ?
1512 "fd not open for reading" :
1513 "fd not open for writing";
1519 /* Called once from main */
1523 coproc.read = coproc.readw = coproc.write = -1;
1528 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1530 coproc_read_close(int fd)
1532 if (coproc.read >= 0 && fd == coproc.read) {
1533 coproc_readw_close(fd);
1540 * Called by c_read() and by iosetup() to close the other side of the
1541 * read pipe, so reads will actually terminate.
1544 coproc_readw_close(int fd)
1546 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1547 close(coproc.readw);
1553 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1554 * when co-process input is dup'd
1557 coproc_write_close(int fd)
1559 if (coproc.write >= 0 && fd == coproc.write) {
1560 close(coproc.write);
1566 * Called to check for existence of/value of the co-process file descriptor.
1567 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1570 coproc_getfd(int mode, const char **emsgp)
1572 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1577 *emsgp = "no coprocess";
1582 * called to close file descriptors related to the coprocess (if any)
1583 * Should be called with SIGCHLD blocked.
1586 coproc_cleanup(int reuse)
1588 /* This to allow co-processes to share output pipe */
1589 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1590 if (coproc.read >= 0) {
1594 if (coproc.readw >= 0) {
1595 close(coproc.readw);
1599 if (coproc.write >= 0) {
1600 close(coproc.write);
1606 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1615 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1616 /* add "/shXXXXXX.tmp" plus NUL */
1618 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1619 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1625 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1631 cp += offsetof(struct temp, tffn[0]);
1632 memcpy(cp, dir, len);
1634 memcpy(cp, "/shXXXXXX.tmp", 14);
1635 /* point to the first of six Xes */
1638 /* cyclically attempt to open a temporary file */
1640 /* generate random part of filename */
1643 cp[len++] = digits_lc[rndget() % 36];
1646 /* check if this one works */
1647 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1648 0600)) < 0 && errno != EEXIST)
1652 if (type == TT_FUNSUB) {
1653 /* map us high and mark as close-on-exec */
1654 if ((j = savefd(i)) != i) {
1659 /* operation mode for the shf */
1664 /* shf_fdopen cannot fail, so no fd leak */
1665 tp->shf = shf_fdopen(i, j, NULL);
1674 * We use a similar collision resolution algorithm as Python 2.5.4
1675 * but with a slightly tweaked implementation written from scratch.
1678 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1679 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1681 static void tgrow(struct table *);
1682 static int tnamecmp(const void *, const void *);
1685 tgrow(struct table *tp)
1687 size_t i, j, osize, mask, perturb;
1688 struct tbl *tblp, **pp;
1689 struct tbl **ntblp, **otblp = tp->tbls;
1691 if (tp->tshift > 29)
1692 internal_errorf("hash table size limit reached");
1694 /* calculate old size, new shift and new size */
1695 osize = (size_t)1 << (tp->tshift++);
1698 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1699 /* multiplication cannot overflow: alloc2 checked that */
1700 memset(ntblp, 0, i * sizeof(struct tbl *));
1702 /* table can get very full when reaching its size limit */
1703 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1704 /* but otherwise, only 75% */
1711 for (i = 0; i < osize; i++)
1712 if ((tblp = otblp[i]) != NULL) {
1713 if ((tblp->flag & DEFINED)) {
1714 /* search for free hash table slot */
1715 j = perturb = tblp->ua.hval;
1716 goto find_first_empty_slot;
1717 find_next_empty_slot:
1718 j = (j << 2) + j + perturb + 1;
1719 perturb >>= PERTURB_SHIFT;
1720 find_first_empty_slot:
1721 pp = &ntblp[j & mask];
1723 goto find_next_empty_slot;
1724 /* found an empty hash table slot */
1727 } else if (!(tblp->flag & FINUSE)) {
1728 afree(tblp, tp->areap);
1731 afree(otblp, tp->areap);
1735 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1739 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1740 initshift : INIT_TBLSHIFT) - 1;
1744 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1746 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1748 size_t j, perturb, mask;
1749 struct tbl **pp, *p;
1751 mask = ((size_t)1 << (tp->tshift)) - 1;
1752 /* search for hash table slot matching name */
1754 goto find_first_slot;
1756 j = (j << 2) + j + perturb + 1;
1757 perturb >>= PERTURB_SHIFT;
1759 pp = &tp->tbls[j & mask];
1760 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1761 strcmp(p->name, name)))
1762 goto find_next_slot;
1763 /* p == NULL if not found, correct found entry otherwise */
1769 /* table, name (key) to enter, hash(n) */
1771 ktenter(struct table *tp, const char *n, uint32_t h)
1773 struct tbl **pp, *p;
1777 if ((p = ktscan(tp, n, h, &pp)))
1780 if (tp->nfree == 0) {
1786 /* create new tbl entry */
1788 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1789 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1792 p->areap = tp->areap;
1796 memcpy(p->name, n, len);
1798 /* enter in tp->tbls */
1805 ktwalk(struct tstate *ts, struct table *tp)
1807 ts->left = (size_t)1 << (tp->tshift);
1808 ts->next = tp->tbls;
1812 ktnext(struct tstate *ts)
1814 while (--ts->left >= 0) {
1815 struct tbl *p = *ts->next++;
1816 if (p != NULL && (p->flag & DEFINED))
1823 tnamecmp(const void *p1, const void *p2)
1825 const struct tbl *a = *((const struct tbl * const *)p1);
1826 const struct tbl *b = *((const struct tbl * const *)p2);
1828 return (strcmp(a->name, b->name));
1832 ktsort(struct table *tp)
1835 struct tbl **p, **sp, **dp;
1838 * since the table is never entirely full, no need to reserve
1839 * additional space for the trailing NULL appended below
1841 i = (size_t)1 << (tp->tshift);
1842 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1843 sp = tp->tbls; /* source */
1846 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1847 ((*dp)->flag & ARRAY)))
1849 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1856 x_sigwinch(int sig MKSH_A_UNUSED)
1858 /* this runs inside interrupt context, with errno saved */
1866 DF(const char *fmt, ...)
1872 mksh_lockfd(shl_dbg_fd);
1874 timet2mjd(&mjd, tv.tv_sec);
1875 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1876 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1877 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1878 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1879 va_start(args, fmt);
1880 shf_vfprintf(shl_dbg, fmt, args);
1882 shf_putc('\n', shl_dbg);
1884 mksh_unlkfd(shl_dbg_fd);
1889 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1894 mksh_tcget(fd, ocb);
1900 cb.c_iflag &= ~(ISTRIP);
1901 cb.c_lflag &= ~(ICANON) | ECHO;
1903 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1904 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1906 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1907 /* OSF/1 processes lnext when ~icanon */
1908 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1910 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1911 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1912 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1917 mksh_tcset(fd, &cb);