1 /* $OpenBSD: main.c,v 1.54 2013/11/28 10:33:37 sobrado 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
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.284 2014/10/03 17:19:27 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 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,
71 /* not "alias -t --": hash -r needs to work */
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",
85 "source=PATH=$PATH:. command .",
88 /* this is what AT&T ksh seems to track, with the addition of emacs */
90 "cat", "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)
196 /* do things like getpgrp() et al. */
199 /* make sure argv[] is sane */
206 /* initialise permanent Area */
209 /* set up base environment */
212 /* set up global l->vars and l->funs */
215 /* Do this first so output routines (eg, errorf, shellf) can work */
218 /* determine the basename (without '-' or path) of the executable */
220 goto begin_parse_kshname;
221 while ((i = ccp[argi++])) {
234 * Turn on nohup by default. (AT&T ksh does not have a nohup
235 * option - it always sends the hup).
240 * Turn on brace expansion by default. AT&T kshs that have
241 * alternation always have it on.
243 Flag(FBRACEEXPAND) = 1;
246 * Turn on "set -x" inheritance by default.
248 Flag(FXTRACEREC) = 1;
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);
332 #ifndef MKSH_NO_CMDLINE_EDITING
334 * Set edit mode to emacs by default, may be overridden
335 * by the environment or the user. Also, we want tab completion
336 * on in vi by default.
338 change_flag(FEMACS, OF_SPECIAL, true);
340 Flag(FVITABCOMPLETE) = 1;
344 /* import environment */
345 if (environ != NULL) {
346 wp = (const char **)environ;
347 while (*wp != NULL) {
349 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
355 typeset(initifs, 0, 0, 0, 0);
357 /* assign default shell variable values */
358 substitute(initsubs, 0);
360 /* Figure out the current working directory and set $PWD */
363 /* Try to use existing $PWD if it is valid */
364 set_current_wd((cp[0] == '/' && test_eval(NULL, TO_FILEQ, cp, ".",
367 simplify_path(current_wd);
368 /* Only set pwd if we know where we are or if it had a bogus value */
369 if (current_wd[0] || *cp)
370 /* setstr can't fail here */
371 setstr(vp, current_wd, KSH_RETURN_ERROR);
373 for (wp = initcoms; *wp != NULL; wp++) {
378 setint_n(global("OPTIND"), 1, 10);
384 safe_prompt = ksheuid ? "$ " : "# ";
386 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
387 if (!(vp->flag & ISSET) ||
388 (!ksheuid && !strchr(str_val(vp), '#')))
389 /* setstr can't fail here */
390 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
391 setint_n((vp = global("BASHPID")), 0, 10);
393 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
395 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
397 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
399 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
401 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
403 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
405 setint_n((vp = global("RANDOM")), rndsetup(), 10);
407 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
409 /* Set this before parsing arguments */
410 Flag(FPRIVILEGED) = (
414 kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
416 /* this to note if monitor is set on command line (see below) */
417 #ifndef MKSH_UNEMPLOYED
418 Flag(FMONITOR) = 127;
420 /* this to note if utf-8 mode is set on command line (see below) */
423 if (!Flag(FAS_BUILTIN)) {
424 argi = parse_args(argv, OF_CMDLINE, NULL);
429 /* process this later only, default to off (hysterical raisins) */
433 if (Flag(FAS_BUILTIN)) {
434 /* auto-detect from environment variables, always */
436 } else if (Flag(FCOMMAND)) {
437 s = pushs(SSTRINGCMDLINE, ATEMP);
438 if (!(s->start = s->str = argv[argi++]))
439 errorf("%s %s", "-c", "requires an argument");
441 if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
446 s->flags |= SF_MAYEXEC;
448 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
449 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
450 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
454 kshname = argv[argi++];
455 } else if (argi < argc && !Flag(FSTDIN)) {
456 s = pushs(SFILE, ATEMP);
457 s->file = argv[argi++];
458 s->u.shf = shf_open(s->file, O_RDONLY, 0,
459 SHF_MAPHI | SHF_CLEXEC);
460 if (s->u.shf == NULL) {
461 shl_stdout_ok = false;
462 warningf(true, "%s: %s", s->file, cstrerror(errno));
463 /* mandated by SUSv4 */
470 s = pushs(SSTDIN, ATEMP);
472 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
474 if (isatty(0) && isatty(2)) {
475 Flag(FTALKING) = Flag(FTALKING_I) = 1;
476 /* The following only if isatty(0) */
478 s->u.shf->flags |= SHF_INTERRUPT;
483 /* this bizarreness is mandated by POSIX */
484 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
488 /* initialise job control */
490 /* do this after j_init() which calls tty_init_state() */
491 if (Flag(FTALKING)) {
493 #ifndef MKSH_ASSUME_UTF8
494 /* auto-detect from locale or environment */
496 #else /* this may not be an #elif */
500 /* always disable UTF-8 (for interactive) */
505 #ifndef MKSH_NO_CMDLINE_EDITING
511 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
512 setsig(&sigtraps[SIGWINCH], x_sigwinch,
513 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
517 if (Flag(FAS_BUILTIN)) {
522 l->argc = argc - argi;
524 * allocate a new array because otherwise, when we modify
525 * it in-place, ps(1) output changes; the meaning of argc
526 * here is slightly different as it excludes kshname, and
527 * we add a trailing NULL sentinel as well
529 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
530 l->argv[0] = kshname;
531 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
532 l->argv[l->argc + 1] = NULL;
536 /* divine the initial state of the utf8-mode Flag */
540 /* auto-detect from locale or environment */
542 #if HAVE_SETLOCALE_CTYPE
543 ccp = setlocale(LC_CTYPE, "");
544 #if HAVE_LANGINFO_CODESET
546 ccp = nl_langinfo(CODESET);
553 /* auto-detect from environment */
555 /* these were imported from environ earlier */
557 ccp = str_val(global("LC_ALL"));
559 ccp = str_val(global("LC_CTYPE"));
561 ccp = str_val(global("LANG"));
565 /* not set on command line, not FTALKING */
579 /* Disable during .profile/ENV reading */
580 restricted_shell = Flag(FRESTRICTED);
581 Flag(FRESTRICTED) = 0;
582 errexit = Flag(FERREXIT);
586 * Do this before profile/$ENV so that if it causes problems in them,
587 * user will know why things broke.
589 if (!current_wd[0] && Flag(FTALKING))
590 warningf(false, "can't determine current directory");
593 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
594 if (!Flag(FPRIVILEGED)) {
596 include(substitute("$HOME/.profile", 0), 0, NULL, true);
597 if (Flag(FTALKING)) {
598 cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
601 include(cp, 0, NULL, true);
604 include(MKSH_SUID_PROFILE, 0, NULL, true);
605 /* turn off -p if not set explicitly */
606 if (Flag(FPRIVILEGED) != 1)
607 change_flag(FPRIVILEGED, OF_INTERNAL, false);
610 if (restricted_shell) {
611 shcomexec(restr_com);
612 /* After typeset command... */
613 Flag(FRESTRICTED) = 1;
615 Flag(FERREXIT) = errexit;
617 if (Flag(FTALKING) && s)
630 /* this indirection barrier reduces stack usage during normal operation */
633 main(int argc, const char *argv[])
639 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
640 if (Flag(FAS_BUILTIN)) {
641 rv = shcomexec(l->argv);
651 include(const char *name, int argc, const char **argv, bool intr_ok)
653 Source *volatile s = NULL;
655 const char **volatile old_argv;
656 volatile int old_argc;
659 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
664 old_argv = e->loc->argv;
665 old_argc = e->loc->argc;
671 if ((i = kshsetjmp(e->jbuf))) {
672 quitenv(s ? s->u.shf : NULL);
674 e->loc->argv = old_argv;
675 e->loc->argc = old_argc;
681 return (exstat & 0xFF);
684 * intr_ok is set if we are including .profile or $ENV.
685 * If user ^Cs out, we don't want to kill the shell...
687 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
696 internal_errorf("%s %d", "include", i);
704 s = pushs(SFILE, ATEMP);
706 strdupx(s->file, name, ATEMP);
710 e->loc->argv = old_argv;
711 e->loc->argc = old_argc;
713 /* & 0xff to ensure value not -1 */
717 /* spawn a command into a shell optionally keeping track of the line number */
719 command(const char *comm, int line)
723 s = pushs(SSTRING, ATEMP);
724 s->start = s->str = comm;
726 return (shell(s, false));
730 * run the commands from the input source, returning status.
733 shell(Source * volatile s, volatile bool toplevel)
736 volatile bool wastty = tobool(s->flags & SF_TTY);
737 volatile uint8_t attempts = 13;
738 volatile bool interactive = Flag(FTALKING) && toplevel;
739 volatile bool sfirst = true;
740 Source *volatile old_source = source;
746 switch ((i = kshsetjmp(e->jbuf))) {
750 /* we get here if SIGINT not caught or ignored */
757 * Reset any eof that was read as part of a
760 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
763 * Used by exit command to get back to
764 * top level shell. Kind of strange since
765 * interactive is set if we are reading from
766 * a tty, but to have stopped jobs, one only
767 * needs FMONITOR set (not FTALKING/SF_TTY)...
769 /* toss any input we have so far */
770 yyrecursive_pop(true);
771 s->start = s->str = null;
788 internal_errorf("%s %d", "shell", i);
791 while (/* CONSTCOND */ 1) {
795 if (s->next == NULL) {
799 s->flags &= ~SF_ECHO;
805 t = compile(s, sfirst);
809 if (t->type == TEOF) {
810 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
811 shellf("Use 'exit' to leave mksh\n");
813 } else if (wastty && !really_exit &&
814 j_stopped_running()) {
819 * this for POSIX which says EXIT traps
820 * shall be taken in the environment
821 * immediately after the last command
828 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
829 t->u.evalflags |= DOTCOMEXEC;
830 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
831 exstat = execute(t, 0, NULL) & 0xFF;
833 if (t->type != TEOF && interactive && really_exit)
841 return (exstat & 0xFF);
844 /* return to closest error handler or shell(), exit if none found */
845 /* note: i MUST NOT be 0 */
850 * This is a kludge. We need to restore everything that was
851 * changed in the new environment, see cid 1005090337C7A669439
852 * and 10050903386452ACBF1, but fail to even save things most of
853 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
854 * which needs to be restored thus (related to Debian #696823).
855 * We did not save the shell flags, so we use a special or'd
856 * value here... this is mostly to clean up behind *other*
857 * callers of unwind(LERROR) here; exec.c has the regular case.
859 if (Flag(FERREXIT) & 0x80) {
860 /* GNU bash does not run this trapsig */
862 Flag(FERREXIT) &= ~0x80;
865 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
866 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
867 sigtraps[ksh_SIGEXIT].trap &&
868 (!Flag(FTALKING) || Flag(FERREXIT)))) {
870 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
873 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
875 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
880 while (/* CONSTCOND */ 1) {
887 kshlongjmp(e->jbuf, i);
891 e->flags |= EF_FAKE_SIGDIE;
906 * struct env includes ALLOC_ITEM for alignment constraints
907 * so first get the actually used memory, then assign it
909 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
910 /* undo what alloc() did to the malloc result address */
911 ep = (void *)(cp - ALLOC_SIZE);
912 /* initialise public members of struct env (not the ALLOC_ITEM) */
918 ep->yyrecursive_statep = NULL;
921 /* jump buffer is invalid because flags == 0 */
926 quitenv(struct shf *shf)
932 yyrecursive_pop(true);
933 while (ep->oenv && ep->oenv->loc != ep->loc)
935 if (ep->savefd != NULL) {
936 for (fd = 0; fd < NUFILE; fd++)
937 /* if ep->savefd[fd] < 0, means fd was closed */
939 restfd(fd, ep->savefd[fd]);
941 /* Clear any write errors */
942 shf_reopen(2, SHF_WR, shl_out);
945 * Bottom of the stack.
946 * Either main shell is exiting or cleanup_parents_env() was called.
948 if (ep->oenv == NULL) {
953 if (ep->type == E_NONE) {
954 /* Main shell exiting? */
955 #if HAVE_PERSISTENT_HISTORY
960 if (ep->flags & EF_FAKE_SIGDIE) {
961 int sig = (exstat & 0xFF) - 128;
964 * ham up our death a bit (AT&T ksh
965 * only seems to do this for SIGTERM)
966 * Don't do it for SIGQUIT, since we'd
969 if ((sig == SIGINT || sig == SIGTERM) &&
970 (kshpgrp == kshpid)) {
971 setsig(&sigtraps[sig], SIG_DFL,
972 SS_RESTORE_CURR | SS_FORCE);
981 #ifndef MKSH_NO_CMDLINE_EDITING
984 #ifndef MKSH_NOPROSPECTOFWORK
985 /* block at least SIGCHLD during/after afreeall */
986 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
989 for (fd = 3; fd < NUFILE; fd++)
990 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1005 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1007 afree(cp + ALLOC_SIZE, ATEMP);
1010 /* Called after a fork to cleanup stuff left over from parents environment */
1012 cleanup_parents_env(void)
1020 * Don't clean up temporary files - parent will probably need them.
1021 * Also, can't easily reclaim memory since variables, etc. could be
1025 /* close all file descriptors hiding in savefd */
1026 for (ep = e; ep; ep = ep->oenv) {
1028 for (fd = 0; fd < NUFILE; fd++)
1029 if (ep->savefd[fd] > 0)
1030 close(ep->savefd[fd]);
1031 afree(ep->savefd, &ep->area);
1035 if (ep->type != E_NONE)
1044 /* Called just before an execve cleanup stuff temporary files */
1046 cleanup_proc_env(void)
1050 for (ep = e; ep; ep = ep->oenv)
1051 remove_temps(ep->temps);
1054 /* remove temp files and free ATEMP Area */
1060 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1065 remove_temps(e->temps);
1071 remove_temps(struct temp *tp)
1073 for (; tp != NULL; tp = tp->next)
1074 if (tp->pid == procpid)
1079 * Initialise tty_fd. Used for tracking the size of the terminal,
1080 * saving/resetting tty modes upon forground job completion, and
1081 * for setting up the tty process group. Return values:
1082 * 0 = got controlling tty
1083 * 1 = got terminal but no controlling tty
1084 * 2 = cannot find a terminal
1086 * 4 = cannot make fd close-on-exec
1087 * An existing tty_fd is cached if no "better" one could be found,
1088 * i.e. if tty_devtty was already set or the new would not set it.
1093 int fd, rv, eno = 0;
1094 bool do_close = false, is_devtty = true;
1097 /* already got a tty which is /dev/tty */
1102 /*XXX imake style */
1104 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1109 if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
1116 /* already got a non-devtty one */
1122 if (isatty((fd = 0)) || isatty((fd = 2)))
1124 /* cannot find one */
1126 /* assert: do_close == false */
1130 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1135 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1142 tty_devtty = is_devtty;
1151 /* A shell error occurred (eg, syntax error, etc.) */
1153 #define VWARNINGF_ERRORPREFIX 1
1154 #define VWARNINGF_FILELINE 2
1155 #define VWARNINGF_BUILTIN 4
1156 #define VWARNINGF_INTERNAL 8
1158 static void vwarningf(unsigned int, const char *, va_list)
1159 MKSH_A_FORMAT(__printf__, 2, 0);
1162 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1165 if (flags & VWARNINGF_INTERNAL)
1166 shf_fprintf(shl_out, "internal error: ");
1167 if (flags & VWARNINGF_ERRORPREFIX)
1168 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1169 if ((flags & VWARNINGF_BUILTIN) &&
1170 /* not set when main() calls parse_args() */
1171 builtin_argv0 && builtin_argv0 != kshname)
1172 shf_fprintf(shl_out, "%s: ", builtin_argv0);
1173 shf_vfprintf(shl_out, fmt, ap);
1174 shf_putchar('\n', shl_out);
1180 errorfx(int rc, const char *fmt, ...)
1186 /* debugging: note that stdout not valid */
1187 shl_stdout_ok = false;
1190 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1196 errorf(const char *fmt, ...)
1202 /* debugging: note that stdout not valid */
1203 shl_stdout_ok = false;
1206 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1211 /* like errorf(), but no unwind is done */
1213 warningf(bool fileline, const char *fmt, ...)
1218 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1224 * Used by built-in utilities to prefix shell and utility name to message
1225 * (also unwinds environments for special builtins).
1228 bi_errorf(const char *fmt, ...)
1232 /* debugging: note that stdout not valid */
1233 shl_stdout_ok = false;
1238 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1239 VWARNINGF_BUILTIN, fmt, va);
1243 * POSIX special builtins and ksh special builtins cause
1244 * non-interactive shells to exit.
1245 * XXX odd use of KEEPASN; also may not want LERROR here
1247 if (builtin_flag & SPEC_BI) {
1248 builtin_argv0 = NULL;
1253 /* Called when something that shouldn't happen does */
1255 internal_errorf(const char *fmt, ...)
1260 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1266 internal_warningf(const char *fmt, ...)
1271 vwarningf(VWARNINGF_INTERNAL, fmt, va);
1275 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1277 error_prefix(bool fileline)
1279 /* Avoid foo: foo[2]: ... */
1280 if (!fileline || !source || !source->file ||
1281 strcmp(source->file, kshname) != 0)
1282 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1283 if (fileline && source && source->file != NULL) {
1284 shf_fprintf(shl_out, "%s[%d]: ", source->file,
1285 source->errline > 0 ? source->errline : source->line);
1286 source->errline = 0;
1290 /* printf to shl_out (stderr) with flush */
1292 shellf(const char *fmt, ...)
1297 /* shl_out may not be set up yet... */
1300 shf_vfprintf(shl_out, fmt, va);
1305 /* printf to shl_stdout (stdout) */
1307 shprintf(const char *fmt, ...)
1312 internal_errorf("shl_stdout not valid");
1314 shf_vfprintf(shl_stdout, fmt, va);
1318 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1324 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1334 struct shf shf_iob[NSHF_IOB];
1343 /* force buffer allocation */
1344 shf_fdopen(1, SHF_WR, shl_stdout);
1345 shf_fdopen(2, SHF_WR, shl_out);
1346 shf_fdopen(2, SHF_WR, shl_xtrace);
1348 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1349 if ((lfp = getenv("HOME")) == NULL || *lfp != '/')
1350 errorf("cannot get home directory");
1351 lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
1354 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1355 errorf("cannot open debug output file %s", lfp);
1356 if (shl_dbg_fd < FDBASE) {
1359 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1361 if ((shl_dbg_fd = nfd) == -1)
1362 errorf("cannot dup debug output file");
1364 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1365 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1371 /* A dup2() with error checking */
1373 ksh_dup2(int ofd, int nfd, bool errok)
1377 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1378 errorf("too many files open in shell");
1381 /*XXX imake style */
1383 fcntl(nfd, F_SETFD, 0);
1390 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1391 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1398 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1401 if (nfd < 0 || nfd > SHRT_MAX)
1402 errorf("too many files open in shell");
1403 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1404 return ((short)nfd);
1408 restfd(int fd, int ofd)
1411 shf_flush(&shf_iob[/* fd */ 2]);
1413 /* original fd closed */
1415 else if (fd != ofd) {
1416 /*XXX: what to do if this dup fails? */
1417 ksh_dup2(ofd, fd, true);
1428 errorf("can't create pipe - try again");
1429 pv[0] = savefd(lpv[0]);
1430 if (pv[0] != lpv[0])
1432 pv[1] = savefd(lpv[1]);
1433 if (pv[1] != lpv[1])
1445 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1446 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1449 check_fd(const char *name, int mode, const char **emsgp)
1453 if (name[0] == 'p' && !name[1])
1454 return (coproc_getfd(mode, emsgp));
1455 for (fd = 0; ksh_isdigit(*name); ++name)
1456 fd = (fd * 10) + *name - '0';
1457 if (*name || fd >= FDBASE) {
1459 *emsgp = "illegal file descriptor name";
1462 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1464 *emsgp = "bad file descriptor";
1469 * X_OK is a kludge to disable this check for dups (x<&1):
1470 * historical shells never did this check (XXX don't know what
1471 * POSIX has to say).
1473 if (!(mode & X_OK) && fl != O_RDWR && (
1474 ((mode & R_OK) && fl != O_RDONLY) ||
1475 ((mode & W_OK) && fl != O_WRONLY))) {
1477 *emsgp = (fl == O_WRONLY) ?
1478 "fd not open for reading" :
1479 "fd not open for writing";
1485 /* Called once from main */
1489 coproc.read = coproc.readw = coproc.write = -1;
1494 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1496 coproc_read_close(int fd)
1498 if (coproc.read >= 0 && fd == coproc.read) {
1499 coproc_readw_close(fd);
1506 * Called by c_read() and by iosetup() to close the other side of the
1507 * read pipe, so reads will actually terminate.
1510 coproc_readw_close(int fd)
1512 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1513 close(coproc.readw);
1519 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1520 * when co-process input is dup'd
1523 coproc_write_close(int fd)
1525 if (coproc.write >= 0 && fd == coproc.write) {
1526 close(coproc.write);
1532 * Called to check for existence of/value of the co-process file descriptor.
1533 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1536 coproc_getfd(int mode, const char **emsgp)
1538 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1543 *emsgp = "no coprocess";
1548 * called to close file descriptors related to the coprocess (if any)
1549 * Should be called with SIGCHLD blocked.
1552 coproc_cleanup(int reuse)
1554 /* This to allow co-processes to share output pipe */
1555 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1556 if (coproc.read >= 0) {
1560 if (coproc.readw >= 0) {
1561 close(coproc.readw);
1565 if (coproc.write >= 0) {
1566 close(coproc.write);
1572 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1581 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1582 /* add "/shXXXXXX.tmp" plus NUL */
1584 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1585 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1591 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1597 cp += offsetof(struct temp, tffn[0]);
1598 memcpy(cp, dir, len);
1600 memcpy(cp, "/shXXXXXX.tmp", 14);
1601 /* point to the first of six Xes */
1603 /* generate random part of filename */
1607 cp[++len] = i < 26 ? 'a' + i : '0' + i - 26;
1610 /* cyclically attempt to open a temporary file */
1611 while ((i = open(tp->tffn, O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1613 if (errno != EEXIST)
1615 /* count down from z to a then from 9 to 0 */
1616 while (cp[len] == '0')
1623 /* do another cycle */
1626 if (type == TT_FUNSUB) {
1627 /* map us high and mark as close-on-exec */
1628 if ((j = savefd(i)) != i) {
1633 /* operation mode for the shf */
1638 /* shf_fdopen cannot fail, so no fd leak */
1639 tp->shf = shf_fdopen(i, j, NULL);
1648 * We use a similar collision resolution algorithm as Python 2.5.4
1649 * but with a slightly tweaked implementation written from scratch.
1652 #define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
1653 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1655 static void tgrow(struct table *);
1656 static int tnamecmp(const void *, const void *);
1659 tgrow(struct table *tp)
1661 size_t i, j, osize, mask, perturb;
1662 struct tbl *tblp, **pp;
1663 struct tbl **ntblp, **otblp = tp->tbls;
1665 if (tp->tshift > 29)
1666 internal_errorf("hash table size limit reached");
1668 /* calculate old size, new shift and new size */
1669 osize = (size_t)1 << (tp->tshift++);
1672 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1673 /* multiplication cannot overflow: alloc2 checked that */
1674 memset(ntblp, 0, i * sizeof(struct tbl *));
1676 /* table can get very full when reaching its size limit */
1677 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1678 /* but otherwise, only 75% */
1685 for (i = 0; i < osize; i++)
1686 if ((tblp = otblp[i]) != NULL) {
1687 if ((tblp->flag & DEFINED)) {
1688 /* search for free hash table slot */
1689 j = perturb = tblp->ua.hval;
1690 goto find_first_empty_slot;
1691 find_next_empty_slot:
1692 j = (j << 2) + j + perturb + 1;
1693 perturb >>= PERTURB_SHIFT;
1694 find_first_empty_slot:
1695 pp = &ntblp[j & mask];
1697 goto find_next_empty_slot;
1698 /* found an empty hash table slot */
1701 } else if (!(tblp->flag & FINUSE)) {
1702 afree(tblp, tp->areap);
1705 afree(otblp, tp->areap);
1709 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1713 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1714 initshift : INIT_TBLSHIFT) - 1;
1718 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1720 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1722 size_t j, perturb, mask;
1723 struct tbl **pp, *p;
1725 mask = ((size_t)1 << (tp->tshift)) - 1;
1726 /* search for hash table slot matching name */
1728 goto find_first_slot;
1730 j = (j << 2) + j + perturb + 1;
1731 perturb >>= PERTURB_SHIFT;
1733 pp = &tp->tbls[j & mask];
1734 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1735 strcmp(p->name, name)))
1736 goto find_next_slot;
1737 /* p == NULL if not found, correct found entry otherwise */
1743 /* table, name (key) to enter, hash(n) */
1745 ktenter(struct table *tp, const char *n, uint32_t h)
1747 struct tbl **pp, *p;
1751 if ((p = ktscan(tp, n, h, &pp)))
1754 if (tp->nfree == 0) {
1760 /* create new tbl entry */
1762 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1763 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1766 p->areap = tp->areap;
1770 memcpy(p->name, n, len);
1772 /* enter in tp->tbls */
1779 ktwalk(struct tstate *ts, struct table *tp)
1781 ts->left = (size_t)1 << (tp->tshift);
1782 ts->next = tp->tbls;
1786 ktnext(struct tstate *ts)
1788 while (--ts->left >= 0) {
1789 struct tbl *p = *ts->next++;
1790 if (p != NULL && (p->flag & DEFINED))
1797 tnamecmp(const void *p1, const void *p2)
1799 const struct tbl *a = *((const struct tbl * const *)p1);
1800 const struct tbl *b = *((const struct tbl * const *)p2);
1802 return (strcmp(a->name, b->name));
1806 ktsort(struct table *tp)
1809 struct tbl **p, **sp, **dp;
1812 * since the table is never entirely full, no need to reserve
1813 * additional space for the trailing NULL appended below
1815 i = (size_t)1 << (tp->tshift);
1816 p = alloc2(i, sizeof(struct tbl *), ATEMP);
1817 sp = tp->tbls; /* source */
1820 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1821 ((*dp)->flag & ARRAY)))
1823 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1830 x_sigwinch(int sig MKSH_A_UNUSED)
1832 /* this runs inside interrupt context, with errno saved */
1840 DF(const char *fmt, ...)
1846 mksh_lockfd(shl_dbg_fd);
1848 timet2mjd(&mjd, tv.tv_sec);
1849 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1850 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1851 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1852 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1853 va_start(args, fmt);
1854 shf_vfprintf(shl_dbg, fmt, args);
1856 shf_putc('\n', shl_dbg);
1858 mksh_unlkfd(shl_dbg_fd);
1863 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1868 mksh_tcget(fd, ocb);
1874 cb.c_iflag &= ~(ISTRIP);
1875 cb.c_lflag &= ~(ICANON) | ECHO;
1877 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1878 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1880 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1881 /* OSF/1 processes lnext when ~icanon */
1882 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1884 /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1885 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1886 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1891 mksh_tcset(fd, &cb);