1 /* $OpenBSD: main.c,v 1.52 2013/06/15 17:25:19 millert Exp $ */
2 /* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt Exp $ */
3 /* $OpenBSD: io.c,v 1.22 2006/03/17 16:30:13 millert Exp $ */
4 /* $OpenBSD: table.c,v 1.15 2012/02/19 07:52:30 otto Exp $ */
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
9 * Thorsten Glaser <tg@mirbsd.org>
11 * Provided that these terms and disclaimer and all copyright notices
12 * are retained or reproduced in an accompanying document, permission
13 * is granted to deal in this work without restriction, including un-
14 * limited rights to use, publicly perform, distribute, sell, modify,
15 * merge, give away, or sublicence.
17 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18 * the utmost extent permitted by applicable law, neither express nor
19 * implied; without malicious intent or gross negligence. In no event
20 * may a licensor, author or contributor be held liable for indirect,
21 * direct, other damage, loss, or other issues arising in any way out
22 * of dealing in the work, even if advised of the possibility of such
23 * damage or existence of a defect, except proven that it results out
24 * of said person's immediate fault when using the work as intended.
30 #if HAVE_LANGINFO_CODESET
33 #if HAVE_SETLOCALE_CTYPE
37 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.269 2013/07/25 18:07:46 tg Exp $");
39 extern char **environ;
42 #define MKSHRC_PATH "~/.mkshrc"
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR "/tmp"
49 static uint8_t isuc(const char *);
50 static int main_init(int, const char *[], Source **, struct block **);
51 uint32_t chvt_rndsetup(const void *, size_t);
52 void chvt_reinit(void);
53 static void reclaim(void);
54 static void remove_temps(struct temp *);
55 static mksh_uari_t rndsetup(void);
57 static void x_sigwinch(int);
60 static const char initifs[] = "IFS= \t\n";
62 static const char initsubs[] =
63 "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
65 static const char *initcoms[] = {
66 Ttypeset, "-r", initvsn, NULL,
67 Ttypeset, "-x", "HOME", "PATH", "RANDOM", "SHELL", NULL,
68 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
72 /* not "alias -t --": hash -r needs to work */
75 #if !defined(ANDROID) && !defined(MKSH_UNEMPLOYED)
76 /* not in Android for political reasons */
77 /* not in ARGE mksh due to no job control */
79 "suspend=kill -STOP $$",
81 "autoload=typeset -fu",
82 "functions=typeset -f",
87 "source=PATH=$PATH:. command .",
90 /* this is what AT&T ksh seems to track, with the addition of emacs */
92 "cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
93 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
97 static const char *restr_com[] = {
98 Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
101 static bool initio_done;
103 /* top-level parsing and execution environment */
104 static struct env env;
105 struct env *e = &env;
112 ALLOC_ITEM alloc_INT;
113 void *dataptr, *stkptr, *mallocptr;
114 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
121 cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
123 /* clear the allocated space, for valgrind */
124 memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
126 /* undo what alloc() did to the malloc result address */
127 bufptr = (void *)(cp - ALLOC_SIZE);
128 /* PIE or something similar provides us with deltas here */
129 bufptr->dataptr = &rndsetupstate;
130 /* ASLR in at least Windows, Linux, some BSDs */
131 bufptr->stkptr = &bufptr;
132 /* randomised malloc in BSD (and possibly others) */
133 bufptr->mallocptr = bufptr;
134 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
135 /* glibc pointer guard */
136 sigsetjmp(bufptr->jbuf, 1);
138 /* introduce variation (and yes, second arg MBZ for portability) */
139 mksh_TIME(bufptr->tv);
141 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
144 return ((mksh_uari_t)h);
148 chvt_rndsetup(const void *bp, size_t sz)
153 /* variation through pid, ppid, and the works */
154 NZATUpdateMem(h, &rndsetupstate, sizeof(rndsetupstate));
155 /* some variation, some possibly entropy, depending on OE */
156 NZATUpdateMem(h, bp, sz);
165 kshpid = procpid = getpid();
171 static const char *empty_argv[] = {
176 isuc(const char *cx) {
183 /* uppercase a string duplicate */
184 strdupx(x, cx, ATEMP);
186 while ((*cp = ksh_toupper(*cp)))
189 /* check for UTF-8 */
190 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
193 /* free copy and out */
199 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
204 unsigned char restricted, errexit, utf_flag;
206 const char *ccp, **wp;
209 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
213 /* do things like getpgrp() et al. */
216 /* make sure argv[] is sane */
223 /* initialise permanent Area */
226 /* set up base environment */
229 /* set up global l->vars and l->funs */
232 /* Do this first so output routines (eg, errorf, shellf) can work */
235 /* determine the basename (without '-' or path) of the executable */
237 goto begin_parse_kshname;
238 while ((i = ccp[argi++])) {
250 /* define built-in commands and see if we were called as one */
251 ktinit(APERM, &builtins,
252 /* currently up to 51 builtins: 75% of 128 = 2^7 */
254 for (i = 0; mkshbuiltins[i].name != NULL; i++)
255 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
256 mkshbuiltins[i].func)))
257 Flag(FAS_BUILTIN) = 1;
259 if (!Flag(FAS_BUILTIN)) {
260 /* check for -T option early */
261 argi = parse_args(argv, OF_FIRSTTIME, NULL);
265 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
266 /* are we called as -sh or /bin/sh or so? */
267 if (!strcmp(ccp, "sh")) {
268 /* either also turns off braceexpand */
269 #ifdef MKSH_BINSHPOSIX
270 /* enable better POSIX conformance */
271 change_flag(FPOSIX, OF_FIRSTTIME, true);
273 #ifdef MKSH_BINSHREDUCED
274 /* enable kludge/compat mode */
275 change_flag(FSH, OF_FIRSTTIME, true);
289 /* set up variable and command dictionaries */
290 ktinit(APERM, &taliases, 0);
291 ktinit(APERM, &aliases, 0);
293 ktinit(APERM, &homedirs, 0);
296 /* define shell keywords */
301 /* initialise tty size before importing environment */
305 def_path = _PATH_DEFPATH;
308 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
309 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
314 * this is uniform across all OSes unless it
315 * breaks somewhere; don't try to optimise,
316 * e.g. add stuff for Interix or remove /usr
317 * for HURD, because e.g. Debian GNU/HURD is
318 * "keeping a regular /usr"; this is supposed
319 * to be a sane 'basic' default PATH
321 def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
325 * Set PATH to def_path (will set the path global variable).
326 * (import of environment below will probably change this setting).
329 /* setstr can't fail here */
330 setstr(vp, def_path, KSH_RETURN_ERROR);
333 * Turn on nohup by default for now - will change to off
334 * by default once people are aware of its existence
335 * (AT&T ksh does not have a nohup option - it always sends
341 * Turn on brace expansion by default. AT&T kshs that have
342 * alternation always have it on.
344 Flag(FBRACEEXPAND) = 1;
347 * Turn on "set -x" inheritance by default.
349 Flag(FXTRACEREC) = 1;
351 #ifndef MKSH_NO_CMDLINE_EDITING
353 * Set edit mode to emacs by default, may be overridden
354 * by the environment or the user. Also, we want tab completion
355 * on in vi by default.
357 change_flag(FEMACS, OF_SPECIAL, true);
359 Flag(FVITABCOMPLETE) = 1;
363 /* import environment */
365 for (wp = (const char **)environ; *wp != NULL; wp++)
366 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
369 typeset(initifs, 0, 0, 0, 0);
371 /* assign default shell variable values */
372 substitute(initsubs, 0);
374 /* Figure out the current working directory and set $PWD */
377 /* Try to use existing $PWD if it is valid */
378 set_current_wd((cp[0] == '/' && test_eval(NULL, TO_FILEQ, cp, ".",
381 simplify_path(current_wd);
382 /* Only set pwd if we know where we are or if it had a bogus value */
383 if (current_wd[0] || *cp)
384 /* setstr can't fail here */
385 setstr(vp, current_wd, KSH_RETURN_ERROR);
387 for (wp = initcoms; *wp != NULL; wp++) {
392 setint_n(global("OPTIND"), 1, 10);
398 safe_prompt = ksheuid ? "$ " : "# ";
400 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
401 if (!(vp->flag & ISSET) ||
402 (!ksheuid && !strchr(str_val(vp), '#')))
403 /* setstr can't fail here */
404 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
405 setint_n((vp = global("BASHPID")), 0, 10);
407 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
409 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
411 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
413 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
415 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
417 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
419 setint_n((vp = global("RANDOM")), rndsetup(), 10);
421 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
423 /* Set this before parsing arguments */
424 Flag(FPRIVILEGED) = kshuid != ksheuid || kshgid != kshegid;
426 /* this to note if monitor is set on command line (see below) */
427 #ifndef MKSH_UNEMPLOYED
428 Flag(FMONITOR) = 127;
430 /* this to note if utf-8 mode is set on command line (see below) */
433 if (!Flag(FAS_BUILTIN)) {
434 argi = parse_args(argv, OF_CMDLINE, NULL);
439 #if defined(DEBUG) && !defined(MKSH_LEGACY_MODE)
440 /* test wraparound of arithmetic types */
443 volatile unsigned long xul;
445 volatile unsigned int xui;
446 volatile mksh_ari_t xa;
447 volatile mksh_uari_t xua, xua2;
469 if ((xua2 != 2147483648UL) ||
470 (xl != (-2147483647L-1)) || (xul != 2147483648UL) ||
471 (xi != -1) || (xui != 4294967295U) ||
472 (xa != 0) || (xua != 0) || (xc != 255))
473 errorf("integer wraparound test failed");
477 /* process this later only, default to off (hysterical raisins) */
481 if (Flag(FAS_BUILTIN)) {
482 /* auto-detect from environment variables, always */
484 } else if (Flag(FCOMMAND)) {
485 s = pushs(SSTRINGCMDLINE, ATEMP);
486 if (!(s->start = s->str = argv[argi++]))
487 errorf("%s %s", "-c", "requires an argument");
488 #if !defined(MKSH_SMALL)
490 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
495 s->flags |= SF_MAYEXEC;
498 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
499 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
500 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
504 kshname = argv[argi++];
505 } else if (argi < argc && !Flag(FSTDIN)) {
506 s = pushs(SFILE, ATEMP);
507 s->file = argv[argi++];
508 s->u.shf = shf_open(s->file, O_RDONLY, 0,
509 SHF_MAPHI | SHF_CLEXEC);
510 if (s->u.shf == NULL) {
511 shl_stdout_ok = false;
512 warningf(true, "%s: %s", s->file, cstrerror(errno));
513 /* mandated by SUSv4 */
520 s = pushs(SSTDIN, ATEMP);
522 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
524 if (isatty(0) && isatty(2)) {
525 Flag(FTALKING) = Flag(FTALKING_I) = 1;
526 /* The following only if isatty(0) */
528 s->u.shf->flags |= SHF_INTERRUPT;
533 /* this bizarreness is mandated by POSIX */
534 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
538 /* initialise job control */
540 /* do this after j_init() which calls tty_init_state() */
541 if (Flag(FTALKING)) {
543 #ifndef MKSH_ASSUME_UTF8
544 /* auto-detect from locale or environment */
546 #elif MKSH_ASSUME_UTF8
549 /* always disable UTF-8 (for interactive) */
553 #ifndef MKSH_NO_CMDLINE_EDITING
559 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
560 setsig(&sigtraps[SIGWINCH], x_sigwinch,
561 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
565 if (Flag(FAS_BUILTIN)) {
570 l->argc = argc - argi;
572 * allocate a new array because otherwise, when we modify
573 * it in-place, ps(1) output changes; the meaning of argc
574 * here is slightly different as it excludes kshname, and
575 * we add a trailing NULL sentinel as well
577 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
578 l->argv[0] = kshname;
579 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
580 l->argv[l->argc + 1] = NULL;
584 /* divine the initial state of the utf8-mode Flag */
588 /* auto-detect from locale or environment */
590 #if HAVE_SETLOCALE_CTYPE
591 ccp = setlocale(LC_CTYPE, "");
592 #if HAVE_LANGINFO_CODESET
594 ccp = nl_langinfo(CODESET);
601 /* auto-detect from environment */
603 /* these were imported from environ earlier */
605 ccp = str_val(global("LC_ALL"));
607 ccp = str_val(global("LC_CTYPE"));
609 ccp = str_val(global("LANG"));
613 /* not set on command line, not FTALKING */
627 /* Disable during .profile/ENV reading */
628 restricted = Flag(FRESTRICTED);
629 Flag(FRESTRICTED) = 0;
630 errexit = Flag(FERREXIT);
634 * Do this before profile/$ENV so that if it causes problems in them,
635 * user will know why things broke.
637 if (!current_wd[0] && Flag(FTALKING))
638 warningf(false, "can't determine current directory");
641 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
642 if (!Flag(FPRIVILEGED))
643 include(substitute("$HOME/.profile", 0), 0,
646 if (Flag(FPRIVILEGED))
647 include(MKSH_SUID_PROFILE, 0, NULL, true);
648 else if (Flag(FTALKING)) {
652 env_file = substitute(substitute("${ENV:-" MKSHRC_PATH "}", 0),
654 if (*env_file != '\0')
655 include(env_file, 0, NULL, true);
659 shcomexec(restr_com);
660 /* After typeset command... */
661 Flag(FRESTRICTED) = 1;
663 Flag(FERREXIT) = errexit;
665 if (Flag(FTALKING) && s)
678 /* this indirection barrier reduces stack usage during normal operation */
681 main(int argc, const char *argv[])
687 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
688 if (Flag(FAS_BUILTIN)) {
689 rv = shcomexec(l->argv);
699 include(const char *name, int argc, const char **argv, bool intr_ok)
701 Source *volatile s = NULL;
703 const char **volatile old_argv;
704 volatile int old_argc;
707 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
712 old_argv = e->loc->argv;
713 old_argc = e->loc->argc;
719 if ((i = kshsetjmp(e->jbuf))) {
720 quitenv(s ? s->u.shf : NULL);
722 e->loc->argv = old_argv;
723 e->loc->argc = old_argc;
729 return (exstat & 0xFF);
732 * intr_ok is set if we are including .profile or $ENV.
733 * If user ^Cs out, we don't want to kill the shell...
735 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
744 internal_errorf("%s %d", "include", i);
752 s = pushs(SFILE, ATEMP);
754 strdupx(s->file, name, ATEMP);
758 e->loc->argv = old_argv;
759 e->loc->argc = old_argc;
761 /* & 0xff to ensure value not -1 */
765 /* spawn a command into a shell optionally keeping track of the line number */
767 command(const char *comm, int line)
771 s = pushs(SSTRING, ATEMP);
772 s->start = s->str = comm;
774 return (shell(s, false));
778 * run the commands from the input source, returning status.
781 shell(Source * volatile s, volatile bool toplevel)
784 volatile bool wastty = tobool(s->flags & SF_TTY);
785 volatile uint8_t attempts = 13;
786 volatile bool interactive = Flag(FTALKING) && toplevel;
787 volatile bool sfirst = true;
788 Source *volatile old_source = source;
794 switch ((i = kshsetjmp(e->jbuf))) {
798 /* we get here if SIGINT not caught or ignored */
805 * Reset any eof that was read as part of a
808 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
811 * Used by exit command to get back to
812 * top level shell. Kind of strange since
813 * interactive is set if we are reading from
814 * a tty, but to have stopped jobs, one only
815 * needs FMONITOR set (not FTALKING/SF_TTY)...
817 /* toss any input we have so far */
818 yyrecursive_pop(true);
819 s->start = s->str = null;
836 internal_errorf("%s %d", "shell", i);
839 while (/* CONSTCOND */ 1) {
843 if (s->next == NULL) {
847 s->flags &= ~SF_ECHO;
853 t = compile(s, sfirst);
857 if (t->type == TEOF) {
858 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
859 shellf("Use 'exit' to leave mksh\n");
861 } else if (wastty && !really_exit &&
862 j_stopped_running()) {
867 * this for POSIX which says EXIT traps
868 * shall be taken in the environment
869 * immediately after the last command
877 #if !defined(MKSH_SMALL)
878 else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
879 t->u.evalflags |= DOTCOMEXEC;
881 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
882 exstat = execute(t, 0, NULL) & 0xFF;
884 if (t->type != TEOF && interactive && really_exit)
892 return (exstat & 0xFF);
895 /* return to closest error handler or shell(), exit if none found */
896 /* note: i MUST NOT be 0 */
901 * This is a kludge. We need to restore everything that was
902 * changed in the new environment, see cid 1005090337C7A669439
903 * and 10050903386452ACBF1, but fail to even save things most of
904 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
905 * which needs to be restored thus (related to Debian #696823).
906 * We did not save the shell flags, so we use a special or'd
907 * value here... this is mostly to clean up behind *other*
908 * callers of unwind(LERROR) here; exec.c has the regular case.
910 if (Flag(FERREXIT) & 0x80) {
911 /* GNU bash does not run this trapsig */
913 Flag(FERREXIT) &= ~0x80;
916 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
917 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
918 sigtraps[ksh_SIGEXIT].trap &&
919 (!Flag(FTALKING) || Flag(FERREXIT)))) {
921 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
924 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
926 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
931 while (/* CONSTCOND */ 1) {
938 kshlongjmp(e->jbuf, i);
942 e->flags |= EF_FAKE_SIGDIE;
957 * struct env includes ALLOC_ITEM for alignment constraints
958 * so first get the actually used memory, then assign it
960 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
961 /* undo what alloc() did to the malloc result address */
962 ep = (void *)(cp - ALLOC_SIZE);
963 /* initialise public members of struct env (not the ALLOC_ITEM) */
969 ep->yyrecursive_statep = NULL;
972 /* jump buffer is invalid because flags == 0 */
977 quitenv(struct shf *shf)
983 yyrecursive_pop(true);
984 while (ep->oenv && ep->oenv->loc != ep->loc)
986 if (ep->savefd != NULL) {
987 for (fd = 0; fd < NUFILE; fd++)
988 /* if ep->savefd[fd] < 0, means fd was closed */
990 restfd(fd, ep->savefd[fd]);
992 /* Clear any write errors */
993 shf_reopen(2, SHF_WR, shl_out);
996 * Bottom of the stack.
997 * Either main shell is exiting or cleanup_parents_env() was called.
999 if (ep->oenv == NULL) {
1004 if (ep->type == E_NONE) {
1005 /* Main shell exiting? */
1006 #if HAVE_PERSISTENT_HISTORY
1011 if (ep->flags & EF_FAKE_SIGDIE) {
1012 int sig = (exstat & 0xFF) - 128;
1015 * ham up our death a bit (AT&T ksh
1016 * only seems to do this for SIGTERM)
1017 * Don't do it for SIGQUIT, since we'd
1020 if ((sig == SIGINT || sig == SIGTERM) &&
1021 (kshpgrp == kshpid)) {
1022 setsig(&sigtraps[sig], SIG_DFL,
1023 SS_RESTORE_CURR | SS_FORCE);
1032 #ifndef MKSH_NO_CMDLINE_EDITING
1035 #ifndef MKSH_NOPROSPECTOFWORK
1036 /* block at least SIGCHLD during/after afreeall */
1037 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1040 for (fd = 3; fd < NUFILE; fd++)
1041 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1048 exit(exstat & 0xFF);
1056 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1058 afree(cp + ALLOC_SIZE, ATEMP);
1061 /* Called after a fork to cleanup stuff left over from parents environment */
1063 cleanup_parents_env(void)
1071 * Don't clean up temporary files - parent will probably need them.
1072 * Also, can't easily reclaim memory since variables, etc. could be
1076 /* close all file descriptors hiding in savefd */
1077 for (ep = e; ep; ep = ep->oenv) {
1079 for (fd = 0; fd < NUFILE; fd++)
1080 if (ep->savefd[fd] > 0)
1081 close(ep->savefd[fd]);
1082 afree(ep->savefd, &ep->area);
1086 if (ep->type != E_NONE)
1095 /* Called just before an execve cleanup stuff temporary files */
1097 cleanup_proc_env(void)
1101 for (ep = e; ep; ep = ep->oenv)
1102 remove_temps(ep->temps);
1105 /* remove temp files and free ATEMP Area */
1111 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1116 remove_temps(e->temps);
1122 remove_temps(struct temp *tp)
1124 for (; tp != NULL; tp = tp->next)
1125 if (tp->pid == procpid)
1130 * Initialise tty_fd. Used for tracking the size of the terminal,
1131 * saving/resetting tty modes upon forground job completion, and
1132 * for setting up the tty process group. Return values:
1133 * 0 = got controlling tty
1134 * 1 = got terminal but no controlling tty
1135 * 2 = cannot find a terminal
1137 * 4 = cannot make fd close-on-exec
1138 * An existing tty_fd is cached if no "better" one could be found,
1139 * i.e. if tty_devtty was already set or the new would not set it.
1144 int fd, rv, eno = 0;
1145 bool do_close = false, is_devtty = true;
1148 /* already got a tty which is /dev/tty */
1153 /*XXX imake style */
1155 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1160 if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1167 /* already got a non-devtty one */
1173 if (isatty((fd = 0)) || isatty((fd = 2)))
1175 /* cannot find one */
1177 /* assert: do_close == false */
1181 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1186 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1193 tty_devtty = is_devtty;
1202 /* A shell error occurred (eg, syntax error, etc.) */
1204 #define VWARNINGF_ERRORPREFIX 1
1205 #define VWARNINGF_FILELINE 2
1206 #define VWARNINGF_BUILTIN 4
1207 #define VWARNINGF_INTERNAL 8
1209 static void vwarningf(unsigned int, const char *, va_list)
1210 MKSH_A_FORMAT(__printf__, 2, 0);
1213 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1216 if (flags & VWARNINGF_INTERNAL)
1217 shf_fprintf(shl_out, "internal error: ");
1218 if (flags & VWARNINGF_ERRORPREFIX)
1219 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1220 if ((flags & VWARNINGF_BUILTIN) &&
1221 /* not set when main() calls parse_args() */
1222 builtin_argv0 && builtin_argv0 != kshname)
1223 shf_fprintf(shl_out, "%s: ", builtin_argv0);
1224 shf_vfprintf(shl_out, fmt, ap);
1225 shf_putchar('\n', shl_out);
1231 errorfx(int rc, const char *fmt, ...)
1237 /* debugging: note that stdout not valid */
1238 shl_stdout_ok = false;
1241 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1247 errorf(const char *fmt, ...)
1253 /* debugging: note that stdout not valid */
1254 shl_stdout_ok = false;
1257 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1262 /* like errorf(), but no unwind is done */
1264 warningf(bool fileline, const char *fmt, ...)
1269 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1275 * Used by built-in utilities to prefix shell and utility name to message
1276 * (also unwinds environments for special builtins).
1279 bi_errorf(const char *fmt, ...)
1283 /* debugging: note that stdout not valid */
1284 shl_stdout_ok = false;
1289 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1290 VWARNINGF_BUILTIN, fmt, va);
1294 * POSIX special builtins and ksh special builtins cause
1295 * non-interactive shells to exit.
1296 * XXX odd use of KEEPASN; also may not want LERROR here
1298 if (builtin_flag & SPEC_BI) {
1299 builtin_argv0 = NULL;
1304 /* Called when something that shouldn't happen does */
1306 internal_errorf(const char *fmt, ...)
1311 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1317 internal_warningf(const char *fmt, ...)
1322 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1326 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1328 error_prefix(bool fileline)
1330 /* Avoid foo: foo[2]: ... */
1331 if (!fileline || !source || !source->file ||
1332 strcmp(source->file, kshname) != 0)
1333 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1334 if (fileline && source && source->file != NULL) {
1335 shf_fprintf(shl_out, "%s[%d]: ", source->file,
1336 source->errline > 0 ? source->errline : source->line);
1337 source->errline = 0;
1341 /* printf to shl_out (stderr) with flush */
1343 shellf(const char *fmt, ...)
1348 /* shl_out may not be set up yet... */
1351 shf_vfprintf(shl_out, fmt, va);
1356 /* printf to shl_stdout (stdout) */
1358 shprintf(const char *fmt, ...)
1363 internal_errorf("shl_stdout not valid");
1365 shf_vfprintf(shl_stdout, fmt, va);
1369 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1375 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1385 struct shf shf_iob[NSHF_IOB];
1394 /* force buffer allocation */
1395 shf_fdopen(1, SHF_WR, shl_stdout);
1396 shf_fdopen(2, SHF_WR, shl_out);
1397 shf_fdopen(2, SHF_WR, shl_xtrace);
1399 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1400 if ((lfp = getenv("HOME")) == NULL || *lfp != '/')
1401 errorf("cannot get home directory");
1402 lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1405 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1406 errorf("cannot open debug output file %s", lfp);
1407 if (shl_dbg_fd < FDBASE) {
1410 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1412 if ((shl_dbg_fd = nfd) == -1)
1413 errorf("cannot dup debug output file");
1415 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1416 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1422 /* A dup2() with error checking */
1424 ksh_dup2(int ofd, int nfd, bool errok)
1428 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1429 errorf("too many files open in shell");
1432 /*XXX imake style */
1434 fcntl(nfd, F_SETFD, 0);
1441 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1442 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1449 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1452 if (nfd < 0 || nfd > SHRT_MAX)
1453 errorf("too many files open in shell");
1454 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1455 return ((short)nfd);
1459 restfd(int fd, int ofd)
1462 shf_flush(&shf_iob[/* fd */ 2]);
1464 /* original fd closed */
1466 else if (fd != ofd) {
1467 /*XXX: what to do if this dup fails? */
1468 ksh_dup2(ofd, fd, true);
1479 errorf("can't create pipe - try again");
1480 pv[0] = savefd(lpv[0]);
1481 if (pv[0] != lpv[0])
1483 pv[1] = savefd(lpv[1]);
1484 if (pv[1] != lpv[1])
1496 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1497 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1500 check_fd(const char *name, int mode, const char **emsgp)
1504 if (name[0] == 'p' && !name[1])
1505 return (coproc_getfd(mode, emsgp));
1506 for (fd = 0; ksh_isdigit(*name); ++name)
1507 fd = (fd * 10) + *name - '0';
1508 if (*name || fd >= FDBASE) {
1510 *emsgp = "illegal file descriptor name";
1513 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1515 *emsgp = "bad file descriptor";
1520 * X_OK is a kludge to disable this check for dups (x<&1):
1521 * historical shells never did this check (XXX don't know what
1522 * POSIX has to say).
1524 if (!(mode & X_OK) && fl != O_RDWR && (
1525 ((mode & R_OK) && fl != O_RDONLY) ||
1526 ((mode & W_OK) && fl != O_WRONLY))) {
1528 *emsgp = (fl == O_WRONLY) ?
1529 "fd not open for reading" :
1530 "fd not open for writing";
1536 /* Called once from main */
1540 coproc.read = coproc.readw = coproc.write = -1;
1545 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1547 coproc_read_close(int fd)
1549 if (coproc.read >= 0 && fd == coproc.read) {
1550 coproc_readw_close(fd);
1557 * Called by c_read() and by iosetup() to close the other side of the
1558 * read pipe, so reads will actually terminate.
1561 coproc_readw_close(int fd)
1563 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1564 close(coproc.readw);
1570 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1571 * when co-process input is dup'd
1574 coproc_write_close(int fd)
1576 if (coproc.write >= 0 && fd == coproc.write) {
1577 close(coproc.write);
1583 * Called to check for existence of/value of the co-process file descriptor.
1584 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1587 coproc_getfd(int mode, const char **emsgp)
1589 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1594 *emsgp = "no coprocess";
1599 * called to close file descriptors related to the coprocess (if any)
1600 * Should be called with SIGCHLD blocked.
1603 coproc_cleanup(int reuse)
1605 /* This to allow co-processes to share output pipe */
1606 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1607 if (coproc.read >= 0) {
1611 if (coproc.readw >= 0) {
1612 close(coproc.readw);
1616 if (coproc.write >= 0) {
1617 close(coproc.write);
1623 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1632 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1633 /* add "/shXXXXXX.tmp" plus NUL */
1635 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1636 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1642 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1648 cp += offsetof(struct temp, tffn[0]);
1649 memcpy(cp, dir, len);
1651 memcpy(cp, "/shXXXXXX.tmp", 14);
1652 /* point to the first of six Xes */
1654 /* generate random part of filename */
1658 cp[++len] = i < 26 ? 'a' + i : '0' + i - 26;
1661 /* cyclically attempt to open a temporary file */
1662 while ((i = open(tp->tffn, O_CREAT | O_EXCL | O_RDWR, 0600)) < 0) {
1663 if (errno != EEXIST)
1665 /* count down from z to a then from 9 to 0 */
1666 while (cp[len] == '0')
1673 /* do another cycle */
1676 if (type == TT_FUNSUB) {
1677 /* map us high and mark as close-on-exec */
1678 if ((j = savefd(i)) != i) {
1683 /* operation mode for the shf */
1688 /* shf_fdopen cannot fail, so no fd leak */
1689 tp->shf = shf_fdopen(i, j, NULL);
1698 * We use a similar collision resolution algorithm as Python 2.5.4
1699 * but with a slightly tweaked implementation written from scratch.
1702 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1703 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1705 static void tgrow(struct table *);
1706 static int tnamecmp(const void *, const void *);
1709 tgrow(struct table *tp)
1711 size_t i, j, osize, mask, perturb;
1712 struct tbl *tblp, **pp;
1713 struct tbl **ntblp, **otblp = tp->tbls;
1715 if (tp->tshift > 29)
1716 internal_errorf("hash table size limit reached");
1718 /* calculate old size, new shift and new size */
1719 osize = (size_t)1 << (tp->tshift++);
1722 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1723 /* multiplication cannot overflow: alloc2 checked that */
1724 memset(ntblp, 0, i * sizeof(struct tbl *));
1726 /* table can get very full when reaching its size limit */
1727 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1728 /* but otherwise, only 75% */
1735 for (i = 0; i < osize; i++)
1736 if ((tblp = otblp[i]) != NULL) {
1737 if ((tblp->flag & DEFINED)) {
1738 /* search for free hash table slot */
1739 j = perturb = tblp->ua.hval;
1740 goto find_first_empty_slot;
1741 find_next_empty_slot:
1742 j = (j << 2) + j + perturb + 1;
1743 perturb >>= PERTURB_SHIFT;
1744 find_first_empty_slot:
1745 pp = &ntblp[j & mask];
1747 goto find_next_empty_slot;
1748 /* found an empty hash table slot */
1751 } else if (!(tblp->flag & FINUSE)) {
1752 afree(tblp, tp->areap);
1755 afree(otblp, tp->areap);
1759 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1763 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1764 initshift : INIT_TBLSHIFT) - 1;
1768 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1770 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1772 size_t j, perturb, mask;
1773 struct tbl **pp, *p;
1775 mask = ((size_t)1 << (tp->tshift)) - 1;
1776 /* search for hash table slot matching name */
1778 goto find_first_slot;
1780 j = (j << 2) + j + perturb + 1;
1781 perturb >>= PERTURB_SHIFT;
1783 pp = &tp->tbls[j & mask];
1784 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1785 strcmp(p->name, name)))
1786 goto find_next_slot;
1787 /* p == NULL if not found, correct found entry otherwise */
1793 /* table, name (key) to enter, hash(n) */
1795 ktenter(struct table *tp, const char *n, uint32_t h)
1797 struct tbl **pp, *p;
1801 if ((p = ktscan(tp, n, h, &pp)))
1804 if (tp->nfree == 0) {
1810 /* create new tbl entry */
1812 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1813 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1816 p->areap = tp->areap;
1820 memcpy(p->name, n, len);
1822 /* enter in tp->tbls */
1829 ktwalk(struct tstate *ts, struct table *tp)
1831 ts->left = (size_t)1 << (tp->tshift);
1832 ts->next = tp->tbls;
1836 ktnext(struct tstate *ts)
1838 while (--ts->left >= 0) {
1839 struct tbl *p = *ts->next++;
1840 if (p != NULL && (p->flag & DEFINED))
1847 tnamecmp(const void *p1, const void *p2)
1849 const struct tbl *a = *((const struct tbl * const *)p1);
1850 const struct tbl *b = *((const struct tbl * const *)p2);
1852 return (strcmp(a->name, b->name));
1856 ktsort(struct table *tp)
1859 struct tbl **p, **sp, **dp;
1862 * since the table is never entirely full, no need to reserve
1863 * additional space for the trailing NULL appended below
1865 i = (size_t)1 << (tp->tshift);
1866 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1867 sp = tp->tbls; /* source */
1870 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1871 ((*dp)->flag & ARRAY)))
1873 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1880 x_sigwinch(int sig MKSH_A_UNUSED)
1882 /* this runs inside interrupt context, with errno saved */
1890 DF(const char *fmt, ...)
1896 mksh_lockfd(shl_dbg_fd);
1898 timet2mjd(&mjd, tv.tv_sec);
1899 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1900 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1901 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1902 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1903 va_start(args, fmt);
1904 shf_vfprintf(shl_dbg, fmt, args);
1906 shf_putc('\n', shl_dbg);
1908 mksh_unlkfd(shl_dbg_fd);
1913 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1918 mksh_tcget(fd, ocb);
1924 cb.c_lflag &= ~(ICANON) | ECHO;
1926 cb.c_iflag &= ~(INLCR | ICRNL);
1927 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1929 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1930 /* OSF/1 processes lnext when ~icanon */
1931 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1933 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1934 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1935 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1940 mksh_tcset(fd, &cb);