1 /* $OpenBSD: main.c,v 1.55 2015/02/09 09:09:30 jsg Exp $ */
2 /* $OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $ */
3 /* $OpenBSD: io.c,v 1.25 2014/08/11 20:28:47 guenther 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,
8 * 2011, 2012, 2013, 2014, 2015
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.300 2015/07/10 19:36:35 tg Exp $");
39 extern char **environ;
42 #define MKSHRC_PATH "~/.mkshrc"
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR MKSH_UNIXROOT "/tmp"
49 static uint8_t isuc(const char *);
50 static int main_init(int, const char *[], Source **, struct block **);
51 void chvt_reinit(void);
52 static void reclaim(void);
53 static void remove_temps(struct temp *);
54 static mksh_uari_t rndsetup(void);
56 static void x_sigwinch(int);
59 static const char initifs[] = "IFS= \t\n";
61 static const char initsubs[] =
62 "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
64 static const char *initcoms[] = {
65 Ttypeset, "-r", initvsn, NULL,
66 Ttypeset, "-x", "HOME", "PATH", "SHELL", NULL,
67 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
69 "integer=\\typeset -i",
71 /* not "alias -t --": hash -r needs to work */
72 "hash=\\builtin alias -t",
73 "type=\\builtin whence -v",
74 #if !defined(ANDROID) && !defined(MKSH_UNEMPLOYED)
75 /* not in Android for political reasons */
76 /* not in ARGE mksh due to no job control */
79 "autoload=\\typeset -fu",
80 "functions=\\typeset -f",
81 "history=\\builtin fc -l",
82 "nameref=\\typeset -n",
84 "r=\\builtin fc -e -",
85 "source=PATH=$PATH" MKSH_PATHSEPS ". \\command .",
88 /* this is what AT&T ksh seems to track, with the addition of emacs */
90 Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
91 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
95 static const char *restr_com[] = {
96 Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
99 static bool initio_done;
101 /* top-level parsing and execution environment */
102 static struct env env;
103 struct env *e = &env;
110 ALLOC_ITEM alloc_INT;
111 void *dataptr, *stkptr, *mallocptr;
112 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
119 cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
121 /* clear the allocated space, for valgrind */
122 memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
124 /* undo what alloc() did to the malloc result address */
125 bufptr = (void *)(cp - ALLOC_SIZE);
126 /* PIE or something similar provides us with deltas here */
127 bufptr->dataptr = &rndsetupstate;
128 /* ASLR in at least Windows, Linux, some BSDs */
129 bufptr->stkptr = &bufptr;
130 /* randomised malloc in BSD (and possibly others) */
131 bufptr->mallocptr = bufptr;
132 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
133 /* glibc pointer guard */
134 sigsetjmp(bufptr->jbuf, 1);
136 /* introduce variation (and yes, second arg MBZ for portability) */
137 mksh_TIME(bufptr->tv);
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 */
212 /* initialise permanent Area */
215 /* set up base environment */
218 /* set up global l->vars and l->funs */
221 /* Do this first so output routines (eg, errorf, shellf) can work */
224 /* determine the basename (without '-' or path) of the executable */
226 goto begin_parse_kshname;
227 while ((i = ccp[argi++])) {
240 * Turn on nohup by default. (AT&T ksh does not have a nohup
241 * option - it always sends the hup).
246 * Turn on brace expansion by default. AT&T kshs that have
247 * alternation always have it on.
249 Flag(FBRACEEXPAND) = 1;
252 * Turn on "set -x" inheritance by default.
254 Flag(FXTRACEREC) = 1;
256 /* define built-in commands and see if we were called as one */
257 ktinit(APERM, &builtins,
258 /* currently up to 51 builtins: 75% of 128 = 2^7 */
260 for (i = 0; mkshbuiltins[i].name != NULL; i++)
261 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
262 mkshbuiltins[i].func)))
263 Flag(FAS_BUILTIN) = 1;
265 if (!Flag(FAS_BUILTIN)) {
266 /* check for -T option early */
267 argi = parse_args(argv, OF_FIRSTTIME, NULL);
271 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
272 /* are we called as -sh or /bin/sh or so? */
273 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
274 /* either also turns off braceexpand */
275 #ifdef MKSH_BINSHPOSIX
276 /* enable better POSIX conformance */
277 change_flag(FPOSIX, OF_FIRSTTIME, true);
279 #ifdef MKSH_BINSHREDUCED
280 /* enable kludge/compat mode */
281 change_flag(FSH, OF_FIRSTTIME, true);
295 /* set up variable and command dictionaries */
296 ktinit(APERM, &taliases, 0);
297 ktinit(APERM, &aliases, 0);
299 ktinit(APERM, &homedirs, 0);
302 /* define shell keywords */
307 /* initialise tty size before importing environment */
311 def_path = _PATH_DEFPATH;
314 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
315 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
320 * this is uniform across all OSes unless it
321 * breaks somewhere; don't try to optimise,
322 * e.g. add stuff for Interix or remove /usr
323 * for HURD, because e.g. Debian GNU/HURD is
324 * "keeping a regular /usr"; this is supposed
325 * to be a sane 'basic' default PATH
327 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
328 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
329 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
330 MKSH_UNIXROOT "/usr/sbin";
334 * Set PATH to def_path (will set the path global variable).
335 * (import of environment below will probably change this setting).
338 /* setstr can't fail here */
339 setstr(vp, def_path, KSH_RETURN_ERROR);
341 #ifndef MKSH_NO_CMDLINE_EDITING
343 * Set edit mode to emacs by default, may be overridden
344 * by the environment or the user. Also, we want tab completion
345 * on in vi by default.
347 change_flag(FEMACS, OF_SPECIAL, true);
349 Flag(FVITABCOMPLETE) = 1;
353 /* import environment */
354 if (environ != NULL) {
355 wp = (const char **)environ;
356 while (*wp != NULL) {
358 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
364 typeset(initifs, 0, 0, 0, 0);
366 /* assign default shell variable values */
367 substitute(initsubs, 0);
369 /* Figure out the current working directory and set $PWD */
372 /* Try to use existing $PWD if it is valid */
373 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp, ".",
376 simplify_path(current_wd);
377 /* Only set pwd if we know where we are or if it had a bogus value */
378 if (current_wd[0] || *cp)
379 /* setstr can't fail here */
380 setstr(vp, current_wd, KSH_RETURN_ERROR);
382 for (wp = initcoms; *wp != NULL; wp++) {
387 setint_n(global("OPTIND"), 1, 10);
393 safe_prompt = ksheuid ? "$ " : "# ";
395 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
396 if (!(vp->flag & ISSET) ||
397 (!ksheuid && !strchr(str_val(vp), '#')))
398 /* setstr can't fail here */
399 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
400 setint_n((vp = global("BASHPID")), 0, 10);
402 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
404 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
406 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
408 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
410 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
412 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
414 setint_n((vp = global("RANDOM")), rndsetup(), 10);
416 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
418 /* Set this before parsing arguments */
419 Flag(FPRIVILEGED) = (
423 kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
425 /* this to note if monitor is set on command line (see below) */
426 #ifndef MKSH_UNEMPLOYED
427 Flag(FMONITOR) = 127;
429 /* this to note if utf-8 mode is set on command line (see below) */
432 if (!Flag(FAS_BUILTIN)) {
433 argi = parse_args(argv, OF_CMDLINE, NULL);
438 /* process this later only, default to off (hysterical raisins) */
442 if (Flag(FAS_BUILTIN)) {
443 /* auto-detect from environment variables, always */
445 } else if (Flag(FCOMMAND)) {
446 s = pushs(SSTRINGCMDLINE, ATEMP);
447 if (!(s->start = s->str = argv[argi++]))
448 errorf("%s %s", "-c", "requires an argument");
450 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
455 s->flags |= SF_MAYEXEC;
457 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
458 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
459 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
463 kshname = argv[argi++];
464 } else if (argi < argc && !Flag(FSTDIN)) {
465 s = pushs(SFILE, ATEMP);
468 * A bug in OS/2 extproc (like shebang) handling makes
469 * it not pass the full pathname of a script, so we need
470 * to search for it. This changes the behaviour of a
471 * simple "mksh foo", but can't be helped.
473 s->file = search_path(argv[argi++], path, X_OK, NULL);
474 if (!s->file || !*s->file)
475 s->file = argv[argi - 1];
477 s->file = argv[argi++];
479 s->u.shf = shf_open(s->file, O_RDONLY, 0,
480 SHF_MAPHI | SHF_CLEXEC);
481 if (s->u.shf == NULL) {
482 shl_stdout_ok = false;
483 warningf(true, "%s: %s", s->file, cstrerror(errno));
484 /* mandated by SUSv4 */
491 s = pushs(SSTDIN, ATEMP);
493 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
495 if (isatty(0) && isatty(2)) {
496 Flag(FTALKING) = Flag(FTALKING_I) = 1;
497 /* The following only if isatty(0) */
499 s->u.shf->flags |= SHF_INTERRUPT;
504 /* this bizarreness is mandated by POSIX */
505 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
509 /* initialise job control */
511 /* do this after j_init() which calls tty_init_state() */
512 if (Flag(FTALKING)) {
514 #ifndef MKSH_ASSUME_UTF8
515 /* auto-detect from locale or environment */
517 #else /* this may not be an #elif */
521 /* always disable UTF-8 (for interactive) */
526 #ifndef MKSH_NO_CMDLINE_EDITING
532 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
533 setsig(&sigtraps[SIGWINCH], x_sigwinch,
534 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
538 if (Flag(FAS_BUILTIN)) {
543 l->argc = argc - argi;
545 * allocate a new array because otherwise, when we modify
546 * it in-place, ps(1) output changes; the meaning of argc
547 * here is slightly different as it excludes kshname, and
548 * we add a trailing NULL sentinel as well
550 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
551 l->argv[0] = kshname;
552 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
553 l->argv[l->argc + 1] = NULL;
557 /* divine the initial state of the utf8-mode Flag */
561 /* auto-detect from locale or environment */
563 #if HAVE_SETLOCALE_CTYPE
564 ccp = setlocale(LC_CTYPE, "");
565 #if HAVE_LANGINFO_CODESET
567 ccp = nl_langinfo(CODESET);
574 /* auto-detect from environment */
576 /* these were imported from environ earlier */
578 ccp = str_val(global("LC_ALL"));
580 ccp = str_val(global("LC_CTYPE"));
582 ccp = str_val(global("LANG"));
586 /* not set on command line, not FTALKING */
600 /* Disable during .profile/ENV reading */
601 restricted_shell = Flag(FRESTRICTED);
602 Flag(FRESTRICTED) = 0;
603 errexit = Flag(FERREXIT);
607 * Do this before profile/$ENV so that if it causes problems in them,
608 * user will know why things broke.
610 if (!current_wd[0] && Flag(FTALKING))
611 warningf(false, "can't determine current directory");
614 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
615 if (!Flag(FPRIVILEGED)) {
617 include(substitute("$HOME/.profile", 0), 0, NULL, true);
618 if (Flag(FTALKING)) {
619 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
622 include(cp, 0, NULL, true);
625 include(MKSH_SUID_PROFILE, 0, NULL, true);
626 /* turn off -p if not set explicitly */
627 if (Flag(FPRIVILEGED) != 1)
628 change_flag(FPRIVILEGED, OF_INTERNAL, false);
631 if (restricted_shell) {
632 shcomexec(restr_com);
633 /* After typeset command... */
634 Flag(FRESTRICTED) = 1;
636 Flag(FERREXIT) = errexit;
638 if (Flag(FTALKING) && s)
651 /* this indirection barrier reduces stack usage during normal operation */
654 main(int argc, const char *argv[])
660 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
661 if (Flag(FAS_BUILTIN)) {
662 rv = shcomexec(l->argv);
672 include(const char *name, int argc, const char **argv, bool intr_ok)
674 Source *volatile s = NULL;
676 const char **volatile old_argv;
677 volatile int old_argc;
680 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
685 old_argv = e->loc->argv;
686 old_argc = e->loc->argc;
692 if ((i = kshsetjmp(e->jbuf))) {
693 quitenv(s ? s->u.shf : NULL);
695 e->loc->argv = old_argv;
696 e->loc->argc = old_argc;
702 return (exstat & 0xFF);
705 * intr_ok is set if we are including .profile or $ENV.
706 * If user ^Cs out, we don't want to kill the shell...
708 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
717 internal_errorf("%s %d", "include", i);
725 s = pushs(SFILE, ATEMP);
727 strdupx(s->file, name, ATEMP);
731 e->loc->argv = old_argv;
732 e->loc->argc = old_argc;
734 /* & 0xff to ensure value not -1 */
738 /* spawn a command into a shell optionally keeping track of the line number */
740 command(const char *comm, int line)
744 s = pushs(SSTRING, ATEMP);
745 s->start = s->str = comm;
747 return (shell(s, false));
751 * run the commands from the input source, returning status.
754 shell(Source * volatile s, volatile bool toplevel)
757 volatile bool wastty = tobool(s->flags & SF_TTY);
758 volatile uint8_t attempts = 13;
759 volatile bool interactive = Flag(FTALKING) && toplevel;
760 volatile bool sfirst = true;
761 Source *volatile old_source = source;
767 switch ((i = kshsetjmp(e->jbuf))) {
771 /* we get here if SIGINT not caught or ignored */
778 * Reset any eof that was read as part of a
781 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
784 * Used by exit command to get back to
785 * top level shell. Kind of strange since
786 * interactive is set if we are reading from
787 * a tty, but to have stopped jobs, one only
788 * needs FMONITOR set (not FTALKING/SF_TTY)...
790 /* toss any input we have so far */
791 yyrecursive_pop(true);
792 s->start = s->str = null;
809 internal_errorf("%s %d", "shell", i);
812 while (/* CONSTCOND */ 1) {
816 if (s->next == NULL) {
820 s->flags &= ~SF_ECHO;
826 t = compile(s, sfirst);
828 histsave(&s->line, NULL, HIST_FLUSH, true);
832 if (t->type == TEOF) {
833 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
834 shellf("Use 'exit' to leave mksh\n");
836 } else if (wastty && !really_exit &&
837 j_stopped_running()) {
842 * this for POSIX which says EXIT traps
843 * shall be taken in the environment
844 * immediately after the last command
851 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
852 t->u.evalflags |= DOTCOMEXEC;
853 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
854 exstat = execute(t, 0, NULL) & 0xFF;
856 if (t->type != TEOF && interactive && really_exit)
864 return (exstat & 0xFF);
867 /* return to closest error handler or shell(), exit if none found */
868 /* note: i MUST NOT be 0 */
873 * This is a kludge. We need to restore everything that was
874 * changed in the new environment, see cid 1005090337C7A669439
875 * and 10050903386452ACBF1, but fail to even save things most of
876 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
877 * which needs to be restored thus (related to Debian #696823).
878 * We did not save the shell flags, so we use a special or'd
879 * value here... this is mostly to clean up behind *other*
880 * callers of unwind(LERROR) here; exec.c has the regular case.
882 if (Flag(FERREXIT) & 0x80) {
883 /* GNU bash does not run this trapsig */
885 Flag(FERREXIT) &= ~0x80;
888 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
889 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
890 sigtraps[ksh_SIGEXIT].trap &&
891 (!Flag(FTALKING) || Flag(FERREXIT)))) {
893 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
896 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
898 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
903 while (/* CONSTCOND */ 1) {
910 kshlongjmp(e->jbuf, i);
914 e->flags |= EF_FAKE_SIGDIE;
919 * quitenv() may have reclaimed the memory
920 * used by source which will end badly when
921 * we jump to a function that expects it to
936 * struct env includes ALLOC_ITEM for alignment constraints
937 * so first get the actually used memory, then assign it
939 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
940 /* undo what alloc() did to the malloc result address */
941 ep = (void *)(cp - ALLOC_SIZE);
942 /* initialise public members of struct env (not the ALLOC_ITEM) */
948 ep->yyrecursive_statep = NULL;
951 /* jump buffer is invalid because flags == 0 */
956 quitenv(struct shf *shf)
962 yyrecursive_pop(true);
963 while (ep->oenv && ep->oenv->loc != ep->loc)
965 if (ep->savefd != NULL) {
966 for (fd = 0; fd < NUFILE; fd++)
967 /* if ep->savefd[fd] < 0, means fd was closed */
969 restfd(fd, ep->savefd[fd]);
971 /* Clear any write errors */
972 shf_reopen(2, SHF_WR, shl_out);
975 * Bottom of the stack.
976 * Either main shell is exiting or cleanup_parents_env() was called.
978 if (ep->oenv == NULL) {
983 if (ep->type == E_NONE) {
984 /* Main shell exiting? */
985 #if HAVE_PERSISTENT_HISTORY
990 if (ep->flags & EF_FAKE_SIGDIE) {
991 int sig = (exstat & 0xFF) - 128;
994 * ham up our death a bit (AT&T ksh
995 * only seems to do this for SIGTERM)
996 * Don't do it for SIGQUIT, since we'd
999 if ((sig == SIGINT || sig == SIGTERM) &&
1000 (kshpgrp == kshpid)) {
1001 setsig(&sigtraps[sig], SIG_DFL,
1002 SS_RESTORE_CURR | SS_FORCE);
1011 #ifndef MKSH_NO_CMDLINE_EDITING
1014 #ifndef MKSH_NOPROSPECTOFWORK
1015 /* block at least SIGCHLD during/after afreeall */
1016 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1019 for (fd = 3; fd < NUFILE; fd++)
1020 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1027 exit(exstat & 0xFF);
1035 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1037 afree(cp + ALLOC_SIZE, ATEMP);
1040 /* Called after a fork to cleanup stuff left over from parents environment */
1042 cleanup_parents_env(void)
1048 * Don't clean up temporary files - parent will probably need them.
1049 * Also, can't easily reclaim memory since variables, etc. could be
1053 /* close all file descriptors hiding in savefd */
1054 for (ep = e; ep; ep = ep->oenv) {
1056 for (fd = 0; fd < NUFILE; fd++)
1057 if (ep->savefd[fd] > 0)
1058 close(ep->savefd[fd]);
1059 afree(ep->savefd, &ep->area);
1063 if (ep->type != E_NONE)
1072 /* Called just before an execve cleanup stuff temporary files */
1074 cleanup_proc_env(void)
1078 for (ep = e; ep; ep = ep->oenv)
1079 remove_temps(ep->temps);
1082 /* remove temp files and free ATEMP Area */
1088 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1093 remove_temps(e->temps);
1099 remove_temps(struct temp *tp)
1101 for (; tp != NULL; tp = tp->next)
1102 if (tp->pid == procpid)
1107 * Initialise tty_fd. Used for tracking the size of the terminal,
1108 * saving/resetting tty modes upon forground job completion, and
1109 * for setting up the tty process group. Return values:
1110 * 0 = got controlling tty
1111 * 1 = got terminal but no controlling tty
1112 * 2 = cannot find a terminal
1114 * 4 = cannot make fd close-on-exec
1115 * An existing tty_fd is cached if no "better" one could be found,
1116 * i.e. if tty_devtty was already set or the new would not set it.
1121 int fd, rv, eno = 0;
1122 bool do_close = false, is_devtty = true;
1125 /* already got a tty which is /dev/tty */
1130 /*XXX imake style */
1132 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1137 if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1144 /* already got a non-devtty one */
1150 if (isatty((fd = 0)) || isatty((fd = 2)))
1152 /* cannot find one */
1154 /* assert: do_close == false */
1158 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1163 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1170 tty_devtty = is_devtty;
1179 /* A shell error occurred (eg, syntax error, etc.) */
1181 #define VWARNINGF_ERRORPREFIX 1
1182 #define VWARNINGF_FILELINE 2
1183 #define VWARNINGF_BUILTIN 4
1184 #define VWARNINGF_INTERNAL 8
1186 static void vwarningf(unsigned int, const char *, va_list)
1187 MKSH_A_FORMAT(__printf__, 2, 0);
1190 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1193 if (flags & VWARNINGF_INTERNAL)
1194 shf_fprintf(shl_out, "internal error: ");
1195 if (flags & VWARNINGF_ERRORPREFIX)
1196 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1197 if ((flags & VWARNINGF_BUILTIN) &&
1198 /* not set when main() calls parse_args() */
1199 builtin_argv0 && builtin_argv0 != kshname)
1200 shf_fprintf(shl_out, "%s: ", builtin_argv0);
1201 shf_vfprintf(shl_out, fmt, ap);
1202 shf_putchar('\n', shl_out);
1208 errorfx(int rc, const char *fmt, ...)
1214 /* debugging: note that stdout not valid */
1215 shl_stdout_ok = false;
1218 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1224 errorf(const char *fmt, ...)
1230 /* debugging: note that stdout not valid */
1231 shl_stdout_ok = false;
1234 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1239 /* like errorf(), but no unwind is done */
1241 warningf(bool fileline, const char *fmt, ...)
1246 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1252 * Used by built-in utilities to prefix shell and utility name to message
1253 * (also unwinds environments for special builtins).
1256 bi_errorf(const char *fmt, ...)
1260 /* debugging: note that stdout not valid */
1261 shl_stdout_ok = false;
1266 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1267 VWARNINGF_BUILTIN, fmt, va);
1271 * POSIX special builtins and ksh special builtins cause
1272 * non-interactive shells to exit.
1273 * XXX odd use of KEEPASN; also may not want LERROR here
1276 builtin_argv0 = NULL;
1281 /* Called when something that shouldn't happen does */
1283 internal_errorf(const char *fmt, ...)
1288 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1294 internal_warningf(const char *fmt, ...)
1299 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1303 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1305 error_prefix(bool fileline)
1307 /* Avoid foo: foo[2]: ... */
1308 if (!fileline || !source || !source->file ||
1309 strcmp(source->file, kshname) != 0)
1310 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1311 if (fileline && source && source->file != NULL) {
1312 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1313 (unsigned long)(source->errline ?
1314 source->errline : source->line));
1315 source->errline = 0;
1319 /* printf to shl_out (stderr) with flush */
1321 shellf(const char *fmt, ...)
1326 /* shl_out may not be set up yet... */
1329 shf_vfprintf(shl_out, fmt, va);
1334 /* printf to shl_stdout (stdout) */
1336 shprintf(const char *fmt, ...)
1341 internal_errorf("shl_stdout not valid");
1343 shf_vfprintf(shl_stdout, fmt, va);
1347 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1353 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1363 struct shf shf_iob[NSHF_IOB];
1372 /* force buffer allocation */
1373 shf_fdopen(1, SHF_WR, shl_stdout);
1374 shf_fdopen(2, SHF_WR, shl_out);
1375 shf_fdopen(2, SHF_WR, shl_xtrace);
1377 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1378 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1379 errorf("cannot get home directory");
1380 lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1383 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1384 errorf("cannot open debug output file %s", lfp);
1385 if (shl_dbg_fd < FDBASE) {
1388 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1390 if ((shl_dbg_fd = nfd) == -1)
1391 errorf("cannot dup debug output file");
1393 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1394 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1400 /* A dup2() with error checking */
1402 ksh_dup2(int ofd, int nfd, bool errok)
1406 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1407 errorf("too many files open in shell");
1410 /*XXX imake style */
1412 fcntl(nfd, F_SETFD, 0);
1419 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1420 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1427 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1428 (errno == EBADF || errno == EPERM))
1430 if (nfd < 0 || nfd > SHRT_MAX)
1431 errorf("too many files open in shell");
1432 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1433 return ((short)nfd);
1437 restfd(int fd, int ofd)
1440 shf_flush(&shf_iob[/* fd */ 2]);
1442 /* original fd closed */
1444 else if (fd != ofd) {
1445 /*XXX: what to do if this dup fails? */
1446 ksh_dup2(ofd, fd, true);
1457 errorf("can't create pipe - try again");
1458 pv[0] = savefd(lpv[0]);
1459 if (pv[0] != lpv[0])
1461 pv[1] = savefd(lpv[1]);
1462 if (pv[1] != lpv[1])
1474 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1475 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1478 check_fd(const char *name, int mode, const char **emsgp)
1482 if (name[0] == 'p' && !name[1])
1483 return (coproc_getfd(mode, emsgp));
1484 while (ksh_isdigit(*name)) {
1485 fd = fd * 10 + ksh_numdig(*name);
1488 *emsgp = "file descriptor too large";
1495 *emsgp = "illegal file descriptor name";
1498 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1500 *emsgp = "bad file descriptor";
1505 * X_OK is a kludge to disable this check for dups (x<&1):
1506 * historical shells never did this check (XXX don't know what
1507 * POSIX has to say).
1509 if (!(mode & X_OK) && fl != O_RDWR && (
1510 ((mode & R_OK) && fl != O_RDONLY) ||
1511 ((mode & W_OK) && fl != O_WRONLY))) {
1513 *emsgp = (fl == O_WRONLY) ?
1514 "fd not open for reading" :
1515 "fd not open for writing";
1521 /* Called once from main */
1525 coproc.read = coproc.readw = coproc.write = -1;
1530 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1532 coproc_read_close(int fd)
1534 if (coproc.read >= 0 && fd == coproc.read) {
1535 coproc_readw_close(fd);
1542 * Called by c_read() and by iosetup() to close the other side of the
1543 * read pipe, so reads will actually terminate.
1546 coproc_readw_close(int fd)
1548 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1549 close(coproc.readw);
1555 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1556 * when co-process input is dup'd
1559 coproc_write_close(int fd)
1561 if (coproc.write >= 0 && fd == coproc.write) {
1562 close(coproc.write);
1568 * Called to check for existence of/value of the co-process file descriptor.
1569 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1572 coproc_getfd(int mode, const char **emsgp)
1574 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1579 *emsgp = "no coprocess";
1584 * called to close file descriptors related to the coprocess (if any)
1585 * Should be called with SIGCHLD blocked.
1588 coproc_cleanup(int reuse)
1590 /* This to allow co-processes to share output pipe */
1591 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1592 if (coproc.read >= 0) {
1596 if (coproc.readw >= 0) {
1597 close(coproc.readw);
1601 if (coproc.write >= 0) {
1602 close(coproc.write);
1608 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1617 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1618 /* add "/shXXXXXX.tmp" plus NUL */
1620 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1621 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1627 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1633 cp += offsetof(struct temp, tffn[0]);
1634 memcpy(cp, dir, len);
1636 memcpy(cp, "/shXXXXXX.tmp", 14);
1637 /* point to the first of six Xes */
1640 /* cyclically attempt to open a temporary file */
1642 /* generate random part of filename */
1645 cp[len++] = digits_lc[rndget() % 36];
1648 /* check if this one works */
1649 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1650 0600)) < 0 && errno != EEXIST)
1654 if (type == TT_FUNSUB) {
1655 /* map us high and mark as close-on-exec */
1656 if ((j = savefd(i)) != i) {
1661 /* operation mode for the shf */
1666 /* shf_fdopen cannot fail, so no fd leak */
1667 tp->shf = shf_fdopen(i, j, NULL);
1676 * We use a similar collision resolution algorithm as Python 2.5.4
1677 * but with a slightly tweaked implementation written from scratch.
1680 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1681 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1683 static void tgrow(struct table *);
1684 static int tnamecmp(const void *, const void *);
1687 tgrow(struct table *tp)
1689 size_t i, j, osize, mask, perturb;
1690 struct tbl *tblp, **pp;
1691 struct tbl **ntblp, **otblp = tp->tbls;
1693 if (tp->tshift > 29)
1694 internal_errorf("hash table size limit reached");
1696 /* calculate old size, new shift and new size */
1697 osize = (size_t)1 << (tp->tshift++);
1700 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1701 /* multiplication cannot overflow: alloc2 checked that */
1702 memset(ntblp, 0, i * sizeof(struct tbl *));
1704 /* table can get very full when reaching its size limit */
1705 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1706 /* but otherwise, only 75% */
1713 for (i = 0; i < osize; i++)
1714 if ((tblp = otblp[i]) != NULL) {
1715 if ((tblp->flag & DEFINED)) {
1716 /* search for free hash table slot */
1717 j = perturb = tblp->ua.hval;
1718 goto find_first_empty_slot;
1719 find_next_empty_slot:
1720 j = (j << 2) + j + perturb + 1;
1721 perturb >>= PERTURB_SHIFT;
1722 find_first_empty_slot:
1723 pp = &ntblp[j & mask];
1725 goto find_next_empty_slot;
1726 /* found an empty hash table slot */
1729 } else if (!(tblp->flag & FINUSE)) {
1730 afree(tblp, tp->areap);
1733 afree(otblp, tp->areap);
1737 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1741 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1742 initshift : INIT_TBLSHIFT) - 1;
1746 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1748 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1750 size_t j, perturb, mask;
1751 struct tbl **pp, *p;
1753 mask = ((size_t)1 << (tp->tshift)) - 1;
1754 /* search for hash table slot matching name */
1756 goto find_first_slot;
1758 j = (j << 2) + j + perturb + 1;
1759 perturb >>= PERTURB_SHIFT;
1761 pp = &tp->tbls[j & mask];
1762 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1763 strcmp(p->name, name)))
1764 goto find_next_slot;
1765 /* p == NULL if not found, correct found entry otherwise */
1771 /* table, name (key) to enter, hash(n) */
1773 ktenter(struct table *tp, const char *n, uint32_t h)
1775 struct tbl **pp, *p;
1779 if ((p = ktscan(tp, n, h, &pp)))
1782 if (tp->nfree == 0) {
1788 /* create new tbl entry */
1790 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1791 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1794 p->areap = tp->areap;
1798 memcpy(p->name, n, len);
1800 /* enter in tp->tbls */
1807 ktwalk(struct tstate *ts, struct table *tp)
1809 ts->left = (size_t)1 << (tp->tshift);
1810 ts->next = tp->tbls;
1814 ktnext(struct tstate *ts)
1816 while (--ts->left >= 0) {
1817 struct tbl *p = *ts->next++;
1818 if (p != NULL && (p->flag & DEFINED))
1825 tnamecmp(const void *p1, const void *p2)
1827 const struct tbl *a = *((const struct tbl * const *)p1);
1828 const struct tbl *b = *((const struct tbl * const *)p2);
1830 return (strcmp(a->name, b->name));
1834 ktsort(struct table *tp)
1837 struct tbl **p, **sp, **dp;
1840 * since the table is never entirely full, no need to reserve
1841 * additional space for the trailing NULL appended below
1843 i = (size_t)1 << (tp->tshift);
1844 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1845 sp = tp->tbls; /* source */
1848 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1849 ((*dp)->flag & ARRAY)))
1851 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1858 x_sigwinch(int sig MKSH_A_UNUSED)
1860 /* this runs inside interrupt context, with errno saved */
1868 DF(const char *fmt, ...)
1874 mksh_lockfd(shl_dbg_fd);
1876 timet2mjd(&mjd, tv.tv_sec);
1877 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1878 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1879 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1880 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1881 va_start(args, fmt);
1882 shf_vfprintf(shl_dbg, fmt, args);
1884 shf_putc('\n', shl_dbg);
1886 mksh_unlkfd(shl_dbg_fd);
1891 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1896 mksh_tcget(fd, ocb);
1902 cb.c_iflag &= ~(ISTRIP);
1903 cb.c_lflag &= ~(ICANON) | ECHO;
1905 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1906 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1908 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1909 /* OSF/1 processes lnext when ~icanon */
1910 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1912 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1913 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1914 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1919 mksh_tcset(fd, &cb);