OSDN Git Service

Disable various mksh builtins.
[android-x86/external-mksh.git] / src / main.c
1 /*      $OpenBSD: main.c,v 1.57 2015/09/10 22:48:58 nicm Exp $  */
2 /*      $OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $       */
3 /*      $OpenBSD: io.c,v 1.26 2015/09/11 08:00:27 guenther Exp $        */
4 /*      $OpenBSD: table.c,v 1.16 2015/09/01 13:12:31 tedu Exp $ */
5
6 /*-
7  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
8  *               2011, 2012, 2013, 2014, 2015, 2016
9  *      mirabilos <m@mirbsd.org>
10  *
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.
16  *
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.
25  */
26
27 #define EXTERN
28 #include "sh.h"
29
30 #if HAVE_LANGINFO_CODESET
31 #include <langinfo.h>
32 #endif
33 #if HAVE_SETLOCALE_CTYPE
34 #include <locale.h>
35 #endif
36
37 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.317 2016/08/04 20:51:35 tg Exp $");
38
39 extern char **environ;
40
41 #ifndef MKSHRC_PATH
42 #define MKSHRC_PATH     "~/.mkshrc"
43 #endif
44
45 #ifndef MKSH_DEFAULT_TMPDIR
46 #define MKSH_DEFAULT_TMPDIR     MKSH_UNIXROOT "/tmp"
47 #endif
48
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);
55 #ifdef SIGWINCH
56 static void x_sigwinch(int);
57 #endif
58
59 static const char initifs[] = "IFS= \t\n";
60
61 static const char initsubs[] =
62     "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
63
64 static const char *initcoms[] = {
65         Ttypeset, "-r", initvsn, NULL,
66         Ttypeset, "-x", "HOME", TPATH, TSHELL, NULL,
67         Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
68         Talias,
69         "integer=\\typeset -i",
70         "local=\\typeset",
71         /* not "alias -t --": hash -r needs to work */
72         "hash=\\builtin alias -t",
73         "type=\\builtin whence -v",
74         "autoload=\\typeset -fu",
75         "functions=\\typeset -f",
76         "history=\\builtin fc -l",
77         "nameref=\\typeset -n",
78         "nohup=nohup ",
79         "r=\\builtin fc -e -",
80         "login=\\exec login",
81         NULL,
82          /* this is what AT&T ksh seems to track, with the addition of emacs */
83         Talias, "-tU",
84         Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
85         "make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
86         NULL
87 };
88
89 static const char *restr_com[] = {
90         Ttypeset, "-r", TPATH, "ENV", TSHELL, NULL
91 };
92
93 static bool initio_done;
94
95 /* top-level parsing and execution environment */
96 static struct env env;
97 struct env *e = &env;
98
99 static mksh_uari_t
100 rndsetup(void)
101 {
102         register uint32_t h;
103         struct {
104                 ALLOC_ITEM alloc_INT;
105                 void *dataptr, *stkptr, *mallocptr;
106 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
107                 sigjmp_buf jbuf;
108 #endif
109                 struct timeval tv;
110         } *bufptr;
111         char *cp;
112
113         cp = alloc(sizeof(*bufptr) - sizeof(ALLOC_ITEM), APERM);
114 #ifdef DEBUG
115         /* clear the allocated space, for valgrind */
116         memset(cp, 0, sizeof(*bufptr) - sizeof(ALLOC_ITEM));
117 #endif
118         /* undo what alloc() did to the malloc result address */
119         bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
120         /* PIE or something similar provides us with deltas here */
121         bufptr->dataptr = &rndsetupstate;
122         /* ASLR in at least Windows, Linux, some BSDs */
123         bufptr->stkptr = &bufptr;
124         /* randomised malloc in BSD (and possibly others) */
125         bufptr->mallocptr = bufptr;
126 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
127         /* glibc pointer guard */
128         sigsetjmp(bufptr->jbuf, 1);
129 #endif
130         /* introduce variation (and yes, second arg MBZ for portability) */
131         mksh_TIME(bufptr->tv);
132
133 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
134         mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
135 #endif
136         h = chvt_rndsetup(bufptr, sizeof(*bufptr));
137
138         afree(cp, APERM);
139         return ((mksh_uari_t)h);
140 }
141
142 void
143 chvt_reinit(void)
144 {
145         kshpid = procpid = getpid();
146         ksheuid = geteuid();
147         kshpgrp = getpgrp();
148         kshppid = getppid();
149 }
150
151 static const char *empty_argv[] = {
152         Tmksh, NULL
153 };
154
155 static uint8_t
156 isuc(const char *cx) {
157         char *cp, *x;
158         uint8_t rv = 0;
159
160         if (!cx || !*cx)
161                 return (0);
162
163         /* uppercase a string duplicate */
164         strdupx(x, cx, ATEMP);
165         cp = x;
166         while ((*cp = ksh_toupper(*cp)))
167                 ++cp;
168
169         /* check for UTF-8 */
170         if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
171                 rv = 1;
172
173         /* free copy and out */
174         afree(x, ATEMP);
175         return (rv);
176 }
177
178 static int
179 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
180 {
181         int argi, i;
182         Source *s = NULL;
183         struct block *l;
184         unsigned char restricted_shell, errexit, utf_flag;
185         char *cp;
186         const char *ccp, **wp;
187         struct tbl *vp;
188         struct stat s_stdin;
189 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
190         ssize_t k;
191 #endif
192
193 #ifdef __OS2__
194         for (i = 0; i < 3; ++i)
195                 if (!isatty(i))
196                         setmode(i, O_BINARY);
197 #endif
198
199         /* do things like getpgrp() et al. */
200         chvt_reinit();
201
202         /* make sure argv[] is sane, for weird OSes */
203         if (!*argv) {
204                 argv = empty_argv;
205                 argc = 1;
206         }
207         kshname = argv[0];
208
209         /* initialise permanent Area */
210         ainit(&aperm);
211         /* max. name length: -2147483648 = 11 (+ NUL) */
212         vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
213
214         /* set up base environment */
215         env.type = E_NONE;
216         ainit(&env.area);
217         /* set up global l->vars and l->funs */
218         newblock();
219
220         /* Do this first so output routines (eg, errorf, shellf) can work */
221         initio();
222
223         /* determine the basename (without '-' or path) of the executable */
224         ccp = kshname;
225         goto begin_parse_kshname;
226         while ((i = ccp[argi++])) {
227                 if (i == '/') {
228                         ccp += argi;
229  begin_parse_kshname:
230                         argi = 0;
231                         if (*ccp == '-')
232                                 ++ccp;
233                 }
234         }
235         if (!*ccp)
236                 ccp = empty_argv[0];
237
238         /*
239          * Turn on nohup by default. (AT&T ksh does not have a nohup
240          * option - it always sends the hup).
241          */
242         Flag(FNOHUP) = 1;
243
244         /*
245          * Turn on brace expansion by default. AT&T kshs that have
246          * alternation always have it on.
247          */
248         Flag(FBRACEEXPAND) = 1;
249
250         /*
251          * Turn on "set -x" inheritance by default.
252          */
253         Flag(FXTRACEREC) = 1;
254
255         /* define built-in commands and see if we were called as one */
256         ktinit(APERM, &builtins,
257             /* currently up to 54 builtins: 75% of 128 = 2^7 */
258             7);
259         for (i = 0; mkshbuiltins[i].name != NULL; i++)
260                 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
261                     mkshbuiltins[i].func)))
262                         Flag(FAS_BUILTIN) = 1;
263
264         if (!Flag(FAS_BUILTIN)) {
265                 /* check for -T option early */
266                 argi = parse_args(argv, OF_FIRSTTIME, NULL);
267                 if (argi < 0)
268                         return (1);
269
270 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
271                 /* are we called as -sh or /bin/sh or so? */
272                 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
273                         /* either also turns off braceexpand */
274 #ifdef MKSH_BINSHPOSIX
275                         /* enable better POSIX conformance */
276                         change_flag(FPOSIX, OF_FIRSTTIME, true);
277 #endif
278 #ifdef MKSH_BINSHREDUCED
279                         /* enable kludge/compat mode */
280                         change_flag(FSH, OF_FIRSTTIME, true);
281 #endif
282                 }
283 #endif
284         }
285
286         initvar();
287
288         initctypes();
289
290         inittraps();
291
292         coproc_init();
293
294         /* set up variable and command dictionaries */
295         ktinit(APERM, &taliases, 0);
296         ktinit(APERM, &aliases, 0);
297 #ifndef MKSH_NOPWNAM
298         ktinit(APERM, &homedirs, 0);
299 #endif
300
301         /* define shell keywords */
302         initkeywords();
303
304         init_histvec();
305
306         /* initialise tty size before importing environment */
307         change_winsz();
308
309 #ifdef _PATH_DEFPATH
310         def_path = _PATH_DEFPATH;
311 #else
312 #ifdef _CS_PATH
313         if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
314             confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
315                 def_path = cp;
316         else
317 #endif
318                 /*
319                  * this is uniform across all OSes unless it
320                  * breaks somewhere hard; don't try to optimise,
321                  * e.g. add stuff for Interix or remove /usr
322                  * for HURD, because e.g. Debian GNU/HURD is
323                  * "keeping a regular /usr"; this is supposed
324                  * to be a sane 'basic' default PATH
325                  */
326                 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
327                     MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
328                     MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
329                     MKSH_UNIXROOT "/usr/sbin";
330 #endif
331
332         /*
333          * Set PATH to def_path (will set the path global variable).
334          * (import of environment below will probably change this setting).
335          */
336         vp = global(TPATH);
337         /* setstr can't fail here */
338         setstr(vp, def_path, KSH_RETURN_ERROR);
339
340 #ifndef MKSH_NO_CMDLINE_EDITING
341         /*
342          * Set edit mode to emacs by default, may be overridden
343          * by the environment or the user. Also, we want tab completion
344          * on in vi by default.
345          */
346         change_flag(FEMACS, OF_SPECIAL, true);
347 #if !MKSH_S_NOVI
348         Flag(FVITABCOMPLETE) = 1;
349 #endif
350 #endif
351
352         /* import environment */
353         if (environ != NULL) {
354                 wp = (const char **)environ;
355                 while (*wp != NULL) {
356                         rndpush(*wp);
357                         typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
358                         ++wp;
359                 }
360         }
361
362         /* for security */
363         typeset(initifs, 0, 0, 0, 0);
364
365         /* assign default shell variable values */
366         substitute(initsubs, 0);
367
368         /* Figure out the current working directory and set $PWD */
369         vp = global(TPWD);
370         cp = str_val(vp);
371         /* Try to use existing $PWD if it is valid */
372         set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
373             Tdot, true)) ? cp : NULL);
374         if (current_wd[0])
375                 simplify_path(current_wd);
376         /* Only set pwd if we know where we are or if it had a bogus value */
377         if (current_wd[0] || *cp)
378                 /* setstr can't fail here */
379                 setstr(vp, current_wd, KSH_RETURN_ERROR);
380
381         for (wp = initcoms; *wp != NULL; wp++) {
382                 shcomexec(wp);
383                 while (*wp != NULL)
384                         wp++;
385         }
386         setint_n(global("OPTIND"), 1, 10);
387
388         kshuid = getuid();
389         kshgid = getgid();
390         kshegid = getegid();
391
392         safe_prompt = ksheuid ? "$ " : "# ";
393         vp = global("PS1");
394         /* Set PS1 if unset or we are root and prompt doesn't contain a # */
395         if (!(vp->flag & ISSET) ||
396             (!ksheuid && !strchr(str_val(vp), '#')))
397                 /* setstr can't fail here */
398                 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
399         setint_n((vp = global("BASHPID")), 0, 10);
400         vp->flag |= INT_U;
401         setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
402         vp->flag |= INT_U;
403         setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
404         vp->flag |= INT_U;
405         setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
406         vp->flag |= INT_U;
407         setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
408         vp->flag |= INT_U;
409         setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
410         vp->flag |= INT_U;
411         setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
412         vp->flag |= INT_U;
413         setint_n((vp = global("RANDOM")), rndsetup(), 10);
414         vp->flag |= INT_U;
415         setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
416
417         /* Set this before parsing arguments */
418         Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
419
420         /* this to note if monitor is set on command line (see below) */
421 #ifndef MKSH_UNEMPLOYED
422         Flag(FMONITOR) = 127;
423 #endif
424         /* this to note if utf-8 mode is set on command line (see below) */
425         UTFMODE = 2;
426
427         if (!Flag(FAS_BUILTIN)) {
428                 argi = parse_args(argv, OF_CMDLINE, NULL);
429                 if (argi < 0)
430                         return (1);
431         }
432
433         /* process this later only, default to off (hysterical raisins) */
434         utf_flag = UTFMODE;
435         UTFMODE = 0;
436
437         if (Flag(FAS_BUILTIN)) {
438                 /* auto-detect from environment variables, always */
439                 utf_flag = 3;
440         } else if (Flag(FCOMMAND)) {
441                 s = pushs(SSTRINGCMDLINE, ATEMP);
442                 if (!(s->start = s->str = argv[argi++]))
443                         errorf(Tf_optfoo, "", "", 'c', Treq_arg);
444                 while (*s->str) {
445                         if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
446                                 break;
447                         s->str++;
448                 }
449                 if (!*s->str)
450                         s->flags |= SF_MAYEXEC;
451                 s->str = s->start;
452 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
453                 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
454                 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
455                         ++argi;
456 #endif
457                 if (argv[argi])
458                         kshname = argv[argi++];
459         } else if (argi < argc && !Flag(FSTDIN)) {
460                 s = pushs(SFILE, ATEMP);
461 #ifdef __OS2__
462                 /*
463                  * A bug in OS/2 extproc (like shebang) handling makes
464                  * it not pass the full pathname of a script, so we need
465                  * to search for it. This changes the behaviour of a
466                  * simple "mksh foo", but can't be helped.
467                  */
468                 s->file = search_path(argv[argi++], path, X_OK, NULL);
469                 if (!s->file || !*s->file)
470                         s->file = argv[argi - 1];
471 #else
472                 s->file = argv[argi++];
473 #endif
474                 s->u.shf = shf_open(s->file, O_RDONLY, 0,
475                     SHF_MAPHI | SHF_CLEXEC);
476                 if (s->u.shf == NULL) {
477                         shl_stdout_ok = false;
478                         warningf(true, Tf_sD_s, s->file, cstrerror(errno));
479                         /* mandated by SUSv4 */
480                         exstat = 127;
481                         unwind(LERROR);
482                 }
483                 kshname = s->file;
484         } else {
485                 Flag(FSTDIN) = 1;
486                 s = pushs(SSTDIN, ATEMP);
487                 s->file = "<stdin>";
488                 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
489                     NULL);
490                 if (isatty(0) && isatty(2)) {
491                         Flag(FTALKING) = Flag(FTALKING_I) = 1;
492                         /* The following only if isatty(0) */
493                         s->flags |= SF_TTY;
494                         s->u.shf->flags |= SHF_INTERRUPT;
495                         s->file = NULL;
496                 }
497         }
498
499         /* this bizarreness is mandated by POSIX */
500         if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
501             Flag(FTALKING))
502                 reset_nonblock(0);
503
504         /* initialise job control */
505         j_init();
506         /* do this after j_init() which calls tty_init_state() */
507         if (Flag(FTALKING)) {
508                 if (utf_flag == 2) {
509 #ifndef MKSH_ASSUME_UTF8
510                         /* auto-detect from locale or environment */
511                         utf_flag = 4;
512 #else /* this may not be an #elif */
513 #if MKSH_ASSUME_UTF8
514                         utf_flag = 1;
515 #else
516                         /* always disable UTF-8 (for interactive) */
517                         utf_flag = 0;
518 #endif
519 #endif
520                 }
521 #ifndef MKSH_NO_CMDLINE_EDITING
522                 x_init();
523 #endif
524         }
525
526 #ifdef SIGWINCH
527         sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
528         setsig(&sigtraps[SIGWINCH], x_sigwinch,
529             SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
530 #endif
531
532         l = e->loc;
533         if (Flag(FAS_BUILTIN)) {
534                 l->argc = argc;
535                 l->argv = argv;
536                 l->argv[0] = ccp;
537         } else {
538                 l->argc = argc - argi;
539                 /*
540                  * allocate a new array because otherwise, when we modify
541                  * it in-place, ps(1) output changes; the meaning of argc
542                  * here is slightly different as it excludes kshname, and
543                  * we add a trailing NULL sentinel as well
544                  */
545                 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
546                 l->argv[0] = kshname;
547                 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
548                 l->argv[l->argc + 1] = NULL;
549                 getopts_reset(1);
550         }
551
552         /* divine the initial state of the utf8-mode Flag */
553         ccp = null;
554         switch (utf_flag) {
555
556         /* auto-detect from locale or environment */
557         case 4:
558 #if HAVE_SETLOCALE_CTYPE
559                 ccp = setlocale(LC_CTYPE, "");
560 #if HAVE_LANGINFO_CODESET
561                 if (!isuc(ccp))
562                         ccp = nl_langinfo(CODESET);
563 #endif
564                 if (!isuc(ccp))
565                         ccp = null;
566                 /* FALLTHROUGH */
567 #endif
568
569         /* auto-detect from environment */
570         case 3:
571                 /* these were imported from environ earlier */
572                 if (ccp == null)
573                         ccp = str_val(global("LC_ALL"));
574                 if (ccp == null)
575                         ccp = str_val(global("LC_CTYPE"));
576                 if (ccp == null)
577                         ccp = str_val(global("LANG"));
578                 UTFMODE = isuc(ccp);
579                 break;
580
581         /* not set on command line, not FTALKING */
582         case 2:
583         /* unknown values */
584         default:
585                 utf_flag = 0;
586                 /* FALLTHROUGH */
587
588         /* known values */
589         case 1:
590         case 0:
591                 UTFMODE = utf_flag;
592                 break;
593         }
594
595         /* Disable during .profile/ENV reading */
596         restricted_shell = Flag(FRESTRICTED);
597         Flag(FRESTRICTED) = 0;
598         errexit = Flag(FERREXIT);
599         Flag(FERREXIT) = 0;
600
601         /*
602          * Do this before profile/$ENV so that if it causes problems in them,
603          * user will know why things broke.
604          */
605         if (!current_wd[0] && Flag(FTALKING))
606                 warningf(false, "can't determine current directory");
607
608         if (Flag(FLOGIN))
609                 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
610         if (!Flag(FPRIVILEGED)) {
611                 if (Flag(FLOGIN))
612                         include(substitute("$HOME/.profile", 0), 0, NULL, true);
613                 if (Flag(FTALKING)) {
614                         cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
615                             0), DOTILDE);
616                         if (cp[0] != '\0')
617                                 include(cp, 0, NULL, true);
618                 }
619         } else {
620                 include(MKSH_SUID_PROFILE, 0, NULL, true);
621                 /* turn off -p if not set explicitly */
622                 if (Flag(FPRIVILEGED) != 1)
623                         change_flag(FPRIVILEGED, OF_INTERNAL, false);
624         }
625
626         if (restricted_shell) {
627                 shcomexec(restr_com);
628                 /* After typeset command... */
629                 Flag(FRESTRICTED) = 1;
630         }
631         Flag(FERREXIT) = errexit;
632
633         if (Flag(FTALKING) && s)
634                 hist_init(s);
635         else
636                 /* set after ENV */
637                 Flag(FTRACKALL) = 1;
638
639         alarm_init();
640
641         *sp = s;
642         *lp = l;
643         return (0);
644 }
645
646 /* this indirection barrier reduces stack usage during normal operation */
647
648 int
649 main(int argc, const char *argv[])
650 {
651         int rv;
652         Source *s;
653         struct block *l;
654
655         if ((rv = main_init(argc, argv, &s, &l)) == 0) {
656                 if (Flag(FAS_BUILTIN)) {
657                         rv = shcomexec(l->argv);
658                 } else {
659                         shell(s, true);
660                         /* NOTREACHED */
661                 }
662         }
663         return (rv);
664 }
665
666 int
667 include(const char *name, int argc, const char **argv, bool intr_ok)
668 {
669         Source *volatile s = NULL;
670         struct shf *shf;
671         const char **volatile old_argv;
672         volatile int old_argc;
673         int i;
674
675         shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
676         if (shf == NULL)
677                 return (-1);
678
679         if (argv) {
680                 old_argv = e->loc->argv;
681                 old_argc = e->loc->argc;
682         } else {
683                 old_argv = NULL;
684                 old_argc = 0;
685         }
686         newenv(E_INCL);
687         if ((i = kshsetjmp(e->jbuf))) {
688                 quitenv(s ? s->u.shf : NULL);
689                 if (old_argv) {
690                         e->loc->argv = old_argv;
691                         e->loc->argc = old_argc;
692                 }
693                 switch (i) {
694                 case LRETURN:
695                 case LERROR:
696                         /* see below */
697                         return (exstat & 0xFF);
698                 case LINTR:
699                         /*
700                          * intr_ok is set if we are including .profile or $ENV.
701                          * If user ^Cs out, we don't want to kill the shell...
702                          */
703                         if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
704                                 return (1);
705                         /* FALLTHROUGH */
706                 case LEXIT:
707                 case LLEAVE:
708                 case LSHELL:
709                         unwind(i);
710                         /* NOTREACHED */
711                 default:
712                         internal_errorf("include %d", i);
713                         /* NOTREACHED */
714                 }
715         }
716         if (argv) {
717                 e->loc->argv = argv;
718                 e->loc->argc = argc;
719         }
720         s = pushs(SFILE, ATEMP);
721         s->u.shf = shf;
722         strdupx(s->file, name, ATEMP);
723         i = shell(s, false);
724         quitenv(s->u.shf);
725         if (old_argv) {
726                 e->loc->argv = old_argv;
727                 e->loc->argc = old_argc;
728         }
729         /* & 0xff to ensure value not -1 */
730         return (i & 0xFF);
731 }
732
733 /* spawn a command into a shell optionally keeping track of the line number */
734 int
735 command(const char *comm, int line)
736 {
737         Source *s, *sold = source;
738         int rv;
739
740         s = pushs(SSTRING, ATEMP);
741         s->start = s->str = comm;
742         s->line = line;
743         rv = shell(s, false);
744         source = sold;
745         return (rv);
746 }
747
748 /*
749  * run the commands from the input source, returning status.
750  */
751 int
752 shell(Source * volatile s, volatile bool toplevel)
753 {
754         struct op *t;
755         volatile bool wastty = tobool(s->flags & SF_TTY);
756         volatile uint8_t attempts = 13;
757         volatile bool interactive = Flag(FTALKING) && toplevel;
758         volatile bool sfirst = true;
759         Source *volatile old_source = source;
760         int i;
761
762         newenv(E_PARSE);
763         if (interactive)
764                 really_exit = false;
765         switch ((i = kshsetjmp(e->jbuf))) {
766         case 0:
767                 break;
768         case LINTR:
769                 /* we get here if SIGINT not caught or ignored */
770         case LERROR:
771         case LSHELL:
772                 if (interactive) {
773                         if (i == LINTR)
774                                 shellf("\n");
775                         /*
776                          * Reset any eof that was read as part of a
777                          * multiline command.
778                          */
779                         if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
780                                 s->type = SSTDIN;
781                         /*
782                          * Used by exit command to get back to
783                          * top level shell. Kind of strange since
784                          * interactive is set if we are reading from
785                          * a tty, but to have stopped jobs, one only
786                          * needs FMONITOR set (not FTALKING/SF_TTY)...
787                          */
788                         /* toss any input we have so far */
789                         yyrecursive_pop(true);
790                         s->start = s->str = null;
791                         retrace_info = NULL;
792                         herep = heres;
793                         break;
794                 }
795                 /* FALLTHROUGH */
796         case LEXIT:
797         case LLEAVE:
798         case LRETURN:
799                 source = old_source;
800                 quitenv(NULL);
801                 /* keep on going */
802                 unwind(i);
803                 /* NOTREACHED */
804         default:
805                 source = old_source;
806                 quitenv(NULL);
807                 internal_errorf("shell %d", i);
808                 /* NOTREACHED */
809         }
810         while (/* CONSTCOND */ 1) {
811                 if (trap)
812                         runtraps(0);
813
814                 if (s->next == NULL) {
815                         if (Flag(FVERBOSE))
816                                 s->flags |= SF_ECHO;
817                         else
818                                 s->flags &= ~SF_ECHO;
819                 }
820                 if (interactive) {
821                         j_notify();
822                         set_prompt(PS1, s);
823                 }
824                 t = compile(s, sfirst);
825                 if (interactive)
826                         histsave(&s->line, NULL, HIST_FLUSH, true);
827                 sfirst = false;
828                 if (!t)
829                         goto source_no_tree;
830                 if (t->type == TEOF) {
831                         if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
832                                 shellf("Use 'exit' to leave mksh\n");
833                                 s->type = SSTDIN;
834                         } else if (wastty && !really_exit &&
835                             j_stopped_running()) {
836                                 really_exit = true;
837                                 s->type = SSTDIN;
838                         } else {
839                                 /*
840                                  * this for POSIX which says EXIT traps
841                                  * shall be taken in the environment
842                                  * immediately after the last command
843                                  * executed.
844                                  */
845                                 if (toplevel)
846                                         unwind(LEXIT);
847                                 break;
848                         }
849                 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
850                         t->u.evalflags |= DOTCOMEXEC;
851                 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
852                         exstat = execute(t, 0, NULL) & 0xFF;
853
854                 if (t->type != TEOF && interactive && really_exit)
855                         really_exit = false;
856
857  source_no_tree:
858                 reclaim();
859         }
860         quitenv(NULL);
861         source = old_source;
862         return (exstat & 0xFF);
863 }
864
865 /* return to closest error handler or shell(), exit if none found */
866 /* note: i MUST NOT be 0 */
867 void
868 unwind(int i)
869 {
870         /*
871          * This is a kludge. We need to restore everything that was
872          * changed in the new environment, see cid 1005090337C7A669439
873          * and 10050903386452ACBF1, but fail to even save things most of
874          * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
875          * which needs to be restored thus (related to Debian #696823).
876          * We did not save the shell flags, so we use a special or'd
877          * value here... this is mostly to clean up behind *other*
878          * callers of unwind(LERROR) here; exec.c has the regular case.
879          */
880         if (Flag(FERREXIT) & 0x80) {
881                 /* GNU bash does not run this trapsig */
882                 trapsig(ksh_SIGERR);
883                 Flag(FERREXIT) &= ~0x80;
884         }
885
886         /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
887         if (i == LEXIT || ((i == LERROR || i == LINTR) &&
888             sigtraps[ksh_SIGEXIT].trap &&
889             (!Flag(FTALKING) || Flag(FERREXIT)))) {
890                 ++trap_nested;
891                 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
892                 --trap_nested;
893                 i = LLEAVE;
894         } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
895                 ++trap_nested;
896                 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
897                 --trap_nested;
898                 i = LLEAVE;
899         }
900
901         while (/* CONSTCOND */ 1) {
902                 switch (e->type) {
903                 case E_PARSE:
904                 case E_FUNC:
905                 case E_INCL:
906                 case E_LOOP:
907                 case E_ERRH:
908                         kshlongjmp(e->jbuf, i);
909                         /* NOTREACHED */
910                 case E_NONE:
911                         if (i == LINTR)
912                                 e->flags |= EF_FAKE_SIGDIE;
913                         /* FALLTHROUGH */
914                 default:
915                         quitenv(NULL);
916                 }
917         }
918 }
919
920 void
921 newenv(int type)
922 {
923         struct env *ep;
924         char *cp;
925
926         /*
927          * struct env includes ALLOC_ITEM for alignment constraints
928          * so first get the actually used memory, then assign it
929          */
930         cp = alloc(sizeof(struct env) - sizeof(ALLOC_ITEM), ATEMP);
931         /* undo what alloc() did to the malloc result address */
932         ep = (void *)(cp - sizeof(ALLOC_ITEM));
933         /* initialise public members of struct env (not the ALLOC_ITEM) */
934         ainit(&ep->area);
935         ep->oenv = e;
936         ep->loc = e->loc;
937         ep->savefd = NULL;
938         ep->temps = NULL;
939         ep->yyrecursive_statep = NULL;
940         ep->type = type;
941         ep->flags = 0;
942         /* jump buffer is invalid because flags == 0 */
943         e = ep;
944 }
945
946 void
947 quitenv(struct shf *shf)
948 {
949         struct env *ep = e;
950         char *cp;
951         int fd;
952
953         yyrecursive_pop(true);
954         while (ep->oenv && ep->oenv->loc != ep->loc)
955                 popblock();
956         if (ep->savefd != NULL) {
957                 for (fd = 0; fd < NUFILE; fd++)
958                         /* if ep->savefd[fd] < 0, means fd was closed */
959                         if (ep->savefd[fd])
960                                 restfd(fd, ep->savefd[fd]);
961                 if (ep->savefd[2])
962                         /* Clear any write errors */
963                         shf_reopen(2, SHF_WR, shl_out);
964         }
965         /*
966          * Bottom of the stack.
967          * Either main shell is exiting or cleanup_parents_env() was called.
968          */
969         if (ep->oenv == NULL) {
970 #ifdef DEBUG_LEAKS
971                 int i;
972 #endif
973
974                 if (ep->type == E_NONE) {
975                         /* Main shell exiting? */
976 #if HAVE_PERSISTENT_HISTORY
977                         if (Flag(FTALKING))
978                                 hist_finish();
979 #endif
980                         j_exit();
981                         if (ep->flags & EF_FAKE_SIGDIE) {
982                                 int sig = (exstat & 0xFF) - 128;
983
984                                 /*
985                                  * ham up our death a bit (AT&T ksh
986                                  * only seems to do this for SIGTERM)
987                                  * Don't do it for SIGQUIT, since we'd
988                                  * dump a core..
989                                  */
990                                 if ((sig == SIGINT || sig == SIGTERM) &&
991                                     (kshpgrp == kshpid)) {
992                                         setsig(&sigtraps[sig], SIG_DFL,
993                                             SS_RESTORE_CURR | SS_FORCE);
994                                         kill(0, sig);
995                                 }
996                         }
997                 }
998                 if (shf)
999                         shf_close(shf);
1000                 reclaim();
1001 #ifdef DEBUG_LEAKS
1002 #ifndef MKSH_NO_CMDLINE_EDITING
1003                 x_done();
1004 #endif
1005 #ifndef MKSH_NOPROSPECTOFWORK
1006                 /* block at least SIGCHLD during/after afreeall */
1007                 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1008 #endif
1009                 afreeall(APERM);
1010                 for (fd = 3; fd < NUFILE; fd++)
1011                         if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1012                             (i & FD_CLOEXEC))
1013                                 close(fd);
1014                 close(2);
1015                 close(1);
1016                 close(0);
1017 #endif
1018                 exit(exstat & 0xFF);
1019         }
1020         if (shf)
1021                 shf_close(shf);
1022         reclaim();
1023
1024         e = e->oenv;
1025
1026         /* free the struct env - tricky due to the ALLOC_ITEM inside */
1027         cp = (void *)ep;
1028         afree(cp + sizeof(ALLOC_ITEM), ATEMP);
1029 }
1030
1031 /* Called after a fork to cleanup stuff left over from parents environment */
1032 void
1033 cleanup_parents_env(void)
1034 {
1035         struct env *ep;
1036         int fd;
1037
1038         /*
1039          * Don't clean up temporary files - parent will probably need them.
1040          * Also, can't easily reclaim memory since variables, etc. could be
1041          * anywhere.
1042          */
1043
1044         /* close all file descriptors hiding in savefd */
1045         for (ep = e; ep; ep = ep->oenv) {
1046                 if (ep->savefd) {
1047                         for (fd = 0; fd < NUFILE; fd++)
1048                                 if (ep->savefd[fd] > 0)
1049                                         close(ep->savefd[fd]);
1050                         afree(ep->savefd, &ep->area);
1051                         ep->savefd = NULL;
1052                 }
1053 #ifdef DEBUG_LEAKS
1054                 if (ep->type != E_NONE)
1055                         ep->type = E_GONE;
1056 #endif
1057         }
1058 #ifndef DEBUG_LEAKS
1059         e->oenv = NULL;
1060 #endif
1061 }
1062
1063 /* Called just before an execve cleanup stuff temporary files */
1064 void
1065 cleanup_proc_env(void)
1066 {
1067         struct env *ep;
1068
1069         for (ep = e; ep; ep = ep->oenv)
1070                 remove_temps(ep->temps);
1071 }
1072
1073 /* remove temp files and free ATEMP Area */
1074 static void
1075 reclaim(void)
1076 {
1077         struct block *l;
1078
1079         while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1080                 e->loc = l->next;
1081                 afreeall(&l->area);
1082         }
1083
1084         remove_temps(e->temps);
1085         e->temps = NULL;
1086
1087         /*
1088          * if the memory backing source is reclaimed, things
1089          * will end up badly when a function expecting it to
1090          * be valid is run; a NULL pointer is easily debugged
1091          */
1092         if (source && source->areap == &e->area)
1093                 source = NULL;
1094         afreeall(&e->area);
1095 }
1096
1097 static void
1098 remove_temps(struct temp *tp)
1099 {
1100         while (tp) {
1101                 if (tp->pid == procpid)
1102                         unlink(tp->tffn);
1103                 tp = tp->next;
1104         }
1105 }
1106
1107 /*
1108  * Initialise tty_fd. Used for tracking the size of the terminal,
1109  * saving/resetting tty modes upon forground job completion, and
1110  * for setting up the tty process group. Return values:
1111  *      0 = got controlling tty
1112  *      1 = got terminal but no controlling tty
1113  *      2 = cannot find a terminal
1114  *      3 = cannot dup fd
1115  *      4 = cannot make fd close-on-exec
1116  * An existing tty_fd is cached if no "better" one could be found,
1117  * i.e. if tty_devtty was already set or the new would not set it.
1118  */
1119 int
1120 tty_init_fd(void)
1121 {
1122         int fd, rv, eno = 0;
1123         bool do_close = false, is_devtty = true;
1124
1125         if (tty_devtty) {
1126                 /* already got a tty which is /dev/tty */
1127                 return (0);
1128         }
1129
1130 #ifdef _UWIN
1131         /*XXX imake style */
1132         if (isatty(3)) {
1133                 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1134                 fd = 3;
1135                 goto got_fd;
1136         }
1137 #endif
1138         if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
1139                 do_close = true;
1140                 goto got_fd;
1141         }
1142         eno = errno;
1143
1144         if (tty_fd >= 0) {
1145                 /* already got a non-devtty one */
1146                 rv = 1;
1147                 goto out;
1148         }
1149         is_devtty = false;
1150
1151         if (isatty((fd = 0)) || isatty((fd = 2)))
1152                 goto got_fd;
1153         /* cannot find one */
1154         rv = 2;
1155         /* assert: do_close == false */
1156         goto out;
1157
1158  got_fd:
1159         if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1160                 eno = errno;
1161                 rv = 3;
1162                 goto out;
1163         }
1164         if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1165                 eno = errno;
1166                 close(rv);
1167                 rv = 4;
1168                 goto out;
1169         }
1170         tty_fd = rv;
1171         tty_devtty = is_devtty;
1172         rv = eno = 0;
1173  out:
1174         if (do_close)
1175                 close(fd);
1176         errno = eno;
1177         return (rv);
1178 }
1179
1180 /* A shell error occurred (eg, syntax error, etc.) */
1181
1182 #define VWARNINGF_ERRORPREFIX   1
1183 #define VWARNINGF_FILELINE      2
1184 #define VWARNINGF_BUILTIN       4
1185 #define VWARNINGF_INTERNAL      8
1186
1187 static void vwarningf(unsigned int, const char *, va_list)
1188     MKSH_A_FORMAT(__printf__, 2, 0);
1189
1190 static void
1191 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1192 {
1193         if (fmt) {
1194                 if (flags & VWARNINGF_INTERNAL)
1195                         shf_fprintf(shl_out, Tf_sD_, "internal error");
1196                 if (flags & VWARNINGF_ERRORPREFIX)
1197                         error_prefix(tobool(flags & VWARNINGF_FILELINE));
1198                 if ((flags & VWARNINGF_BUILTIN) &&
1199                     /* not set when main() calls parse_args() */
1200                     builtin_argv0 && builtin_argv0 != kshname)
1201                         shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
1202                 shf_vfprintf(shl_out, fmt, ap);
1203                 shf_putchar('\n', shl_out);
1204         }
1205         shf_flush(shl_out);
1206 }
1207
1208 void
1209 errorfx(int rc, const char *fmt, ...)
1210 {
1211         va_list va;
1212
1213         exstat = rc;
1214
1215         /* debugging: note that stdout not valid */
1216         shl_stdout_ok = false;
1217
1218         va_start(va, fmt);
1219         vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1220         va_end(va);
1221         unwind(LERROR);
1222 }
1223
1224 void
1225 errorf(const char *fmt, ...)
1226 {
1227         va_list va;
1228
1229         exstat = 1;
1230
1231         /* debugging: note that stdout not valid */
1232         shl_stdout_ok = false;
1233
1234         va_start(va, fmt);
1235         vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1236         va_end(va);
1237         unwind(LERROR);
1238 }
1239
1240 /* like errorf(), but no unwind is done */
1241 void
1242 warningf(bool fileline, const char *fmt, ...)
1243 {
1244         va_list va;
1245
1246         va_start(va, fmt);
1247         vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1248             fmt, va);
1249         va_end(va);
1250 }
1251
1252 /*
1253  * Used by built-in utilities to prefix shell and utility name to message
1254  * (also unwinds environments for special builtins).
1255  */
1256 void
1257 bi_errorf(const char *fmt, ...)
1258 {
1259         va_list va;
1260
1261         /* debugging: note that stdout not valid */
1262         shl_stdout_ok = false;
1263
1264         exstat = 1;
1265
1266         va_start(va, fmt);
1267         vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1268             VWARNINGF_BUILTIN, fmt, va);
1269         va_end(va);
1270
1271         /*
1272          * POSIX special builtins and ksh special builtins cause
1273          * non-interactive shells to exit. XXX may not want LERROR here
1274          */
1275         if (builtin_spec) {
1276                 builtin_argv0 = NULL;
1277                 unwind(LERROR);
1278         }
1279 }
1280
1281 /* Called when something that shouldn't happen does */
1282 void
1283 internal_errorf(const char *fmt, ...)
1284 {
1285         va_list va;
1286
1287         va_start(va, fmt);
1288         vwarningf(VWARNINGF_INTERNAL, fmt, va);
1289         va_end(va);
1290         unwind(LERROR);
1291 }
1292
1293 void
1294 internal_warningf(const char *fmt, ...)
1295 {
1296         va_list va;
1297
1298         va_start(va, fmt);
1299         vwarningf(VWARNINGF_INTERNAL, fmt, va);
1300         va_end(va);
1301 }
1302
1303 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1304 void
1305 error_prefix(bool fileline)
1306 {
1307         /* Avoid foo: foo[2]: ... */
1308         if (!fileline || !source || !source->file ||
1309             strcmp(source->file, kshname) != 0)
1310                 shf_fprintf(shl_out, Tf_sD_, 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;
1316         }
1317 }
1318
1319 /* printf to shl_out (stderr) with flush */
1320 void
1321 shellf(const char *fmt, ...)
1322 {
1323         va_list va;
1324
1325         if (!initio_done)
1326                 /* shl_out may not be set up yet... */
1327                 return;
1328         va_start(va, fmt);
1329         shf_vfprintf(shl_out, fmt, va);
1330         va_end(va);
1331         shf_flush(shl_out);
1332 }
1333
1334 /* printf to shl_stdout (stdout) */
1335 void
1336 shprintf(const char *fmt, ...)
1337 {
1338         va_list va;
1339
1340         if (!shl_stdout_ok)
1341                 internal_errorf("shl_stdout not valid");
1342         va_start(va, fmt);
1343         shf_vfprintf(shl_stdout, fmt, va);
1344         va_end(va);
1345 }
1346
1347 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1348 int
1349 can_seek(int fd)
1350 {
1351         struct stat statb;
1352
1353         return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1354             SHF_UNBUF : 0);
1355 }
1356
1357 #ifdef DF
1358 int shl_dbg_fd;
1359 #define NSHF_IOB 4
1360 #else
1361 #define NSHF_IOB 3
1362 #endif
1363 struct shf shf_iob[NSHF_IOB];
1364
1365 void
1366 initio(void)
1367 {
1368 #ifdef DF
1369         const char *lfp;
1370 #endif
1371
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);
1376 #ifdef DF
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(Tf_sSs, lfp, "mksh-dbg.txt");
1381         }
1382
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) {
1386                 int nfd;
1387
1388                 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1389                 close(shl_dbg_fd);
1390                 if ((shl_dbg_fd = nfd) == -1)
1391                         errorf("cannot dup debug output file");
1392         }
1393         fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1394         shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1395         DF("=== open ===");
1396 #endif
1397         initio_done = true;
1398 }
1399
1400 /* A dup2() with error checking */
1401 int
1402 ksh_dup2(int ofd, int nfd, bool errok)
1403 {
1404         int rv;
1405
1406         if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1407                 errorf("too many files open in shell");
1408
1409 #ifdef __ultrix
1410         /*XXX imake style */
1411         if (rv >= 0)
1412                 fcntl(nfd, F_SETFD, 0);
1413 #endif
1414
1415         return (rv);
1416 }
1417
1418 /*
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.
1421  */
1422 short
1423 savefd(int fd)
1424 {
1425         int nfd = fd;
1426
1427         if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1428             (errno == EBADF || errno == EPERM))
1429                 return (-1);
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);
1434 }
1435
1436 void
1437 restfd(int fd, int ofd)
1438 {
1439         if (fd == 2)
1440                 shf_flush(&shf_iob[/* fd */ 2]);
1441         if (ofd < 0)
1442                 /* original fd closed */
1443                 close(fd);
1444         else if (fd != ofd) {
1445                 /*XXX: what to do if this dup fails? */
1446                 ksh_dup2(ofd, fd, true);
1447                 close(ofd);
1448         }
1449 }
1450
1451 void
1452 openpipe(int *pv)
1453 {
1454         int lpv[2];
1455
1456         if (pipe(lpv) < 0)
1457                 errorf("can't create pipe - try again");
1458         pv[0] = savefd(lpv[0]);
1459         if (pv[0] != lpv[0])
1460                 close(lpv[0]);
1461         pv[1] = savefd(lpv[1]);
1462         if (pv[1] != lpv[1])
1463                 close(lpv[1]);
1464 }
1465
1466 void
1467 closepipe(int *pv)
1468 {
1469         close(pv[0]);
1470         close(pv[1]);
1471 }
1472
1473 /*
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.
1476  */
1477 int
1478 check_fd(const char *name, int mode, const char **emsgp)
1479 {
1480         int fd, fl;
1481
1482         if (!name[0] || name[1])
1483                 goto illegal_fd_name;
1484         if (name[0] == 'p')
1485                 return (coproc_getfd(mode, emsgp));
1486         if (!ksh_isdigit(name[0])) {
1487  illegal_fd_name:
1488                 if (emsgp)
1489                         *emsgp = "illegal file descriptor name";
1490                 return (-1);
1491         }
1492
1493         if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
1494                 if (emsgp)
1495                         *emsgp = "bad file descriptor";
1496                 return (-1);
1497         }
1498         fl &= O_ACCMODE;
1499         /*
1500          * X_OK is a kludge to disable this check for dups (x<&1):
1501          * historical shells never did this check (XXX don't know what
1502          * POSIX has to say).
1503          */
1504         if (!(mode & X_OK) && fl != O_RDWR && (
1505             ((mode & R_OK) && fl != O_RDONLY) ||
1506             ((mode & W_OK) && fl != O_WRONLY))) {
1507                 if (emsgp)
1508                         *emsgp = (fl == O_WRONLY) ?
1509                             "fd not open for reading" :
1510                             "fd not open for writing";
1511                 return (-1);
1512         }
1513         return (fd);
1514 }
1515
1516 /* Called once from main */
1517 void
1518 coproc_init(void)
1519 {
1520         coproc.read = coproc.readw = coproc.write = -1;
1521         coproc.njobs = 0;
1522         coproc.id = 0;
1523 }
1524
1525 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1526 void
1527 coproc_read_close(int fd)
1528 {
1529         if (coproc.read >= 0 && fd == coproc.read) {
1530                 coproc_readw_close(fd);
1531                 close(coproc.read);
1532                 coproc.read = -1;
1533         }
1534 }
1535
1536 /*
1537  * Called by c_read() and by iosetup() to close the other side of the
1538  * read pipe, so reads will actually terminate.
1539  */
1540 void
1541 coproc_readw_close(int fd)
1542 {
1543         if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1544                 close(coproc.readw);
1545                 coproc.readw = -1;
1546         }
1547 }
1548
1549 /*
1550  * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1551  * when co-process input is dup'd
1552  */
1553 void
1554 coproc_write_close(int fd)
1555 {
1556         if (coproc.write >= 0 && fd == coproc.write) {
1557                 close(coproc.write);
1558                 coproc.write = -1;
1559         }
1560 }
1561
1562 /*
1563  * Called to check for existence of/value of the co-process file descriptor.
1564  * (Used by check_fd() and by c_read/c_print to deal with -p option).
1565  */
1566 int
1567 coproc_getfd(int mode, const char **emsgp)
1568 {
1569         int fd = (mode & R_OK) ? coproc.read : coproc.write;
1570
1571         if (fd >= 0)
1572                 return (fd);
1573         if (emsgp)
1574                 *emsgp = "no coprocess";
1575         return (-1);
1576 }
1577
1578 /*
1579  * called to close file descriptors related to the coprocess (if any)
1580  * Should be called with SIGCHLD blocked.
1581  */
1582 void
1583 coproc_cleanup(int reuse)
1584 {
1585         /* This to allow co-processes to share output pipe */
1586         if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1587                 if (coproc.read >= 0) {
1588                         close(coproc.read);
1589                         coproc.read = -1;
1590                 }
1591                 if (coproc.readw >= 0) {
1592                         close(coproc.readw);
1593                         coproc.readw = -1;
1594                 }
1595         }
1596         if (coproc.write >= 0) {
1597                 close(coproc.write);
1598                 coproc.write = -1;
1599         }
1600 }
1601
1602 struct temp *
1603 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1604 {
1605         char *cp;
1606         size_t len;
1607         int i, j;
1608         struct temp *tp;
1609         const char *dir;
1610         struct stat sb;
1611
1612         dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1613         /* add "/shXXXXXX.tmp" plus NUL */
1614         len = strlen(dir);
1615         checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1616         tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1617
1618         tp->shf = NULL;
1619         tp->pid = procpid;
1620         tp->type = type;
1621
1622         if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1623                 tp->tffn[0] = '\0';
1624                 goto maketemp_out;
1625         }
1626
1627         cp = (void *)tp;
1628         cp += offsetof(struct temp, tffn[0]);
1629         memcpy(cp, dir, len);
1630         cp += len;
1631         memcpy(cp, "/shXXXXXX.tmp", 14);
1632         /* point to the first of six Xes */
1633         cp += 3;
1634
1635         /* cyclically attempt to open a temporary file */
1636         do {
1637                 /* generate random part of filename */
1638                 len = 0;
1639                 do {
1640                         cp[len++] = digits_lc[rndget() % 36];
1641                 } while (len < 6);
1642
1643                 /* check if this one works */
1644                 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1645                     0600)) < 0 && errno != EEXIST)
1646                         goto maketemp_out;
1647         } while (i < 0);
1648
1649         if (type == TT_FUNSUB) {
1650                 /* map us high and mark as close-on-exec */
1651                 if ((j = savefd(i)) != i) {
1652                         close(i);
1653                         i = j;
1654                 }
1655
1656                 /* operation mode for the shf */
1657                 j = SHF_RD;
1658         } else
1659                 j = SHF_WR;
1660
1661         /* shf_fdopen cannot fail, so no fd leak */
1662         tp->shf = shf_fdopen(i, j, NULL);
1663
1664  maketemp_out:
1665         tp->next = *tlist;
1666         *tlist = tp;
1667         return (tp);
1668 }
1669
1670 /*
1671  * We use a similar collision resolution algorithm as Python 2.5.4
1672  * but with a slightly tweaked implementation written from scratch.
1673  */
1674
1675 #define INIT_TBLSHIFT   3       /* initial table shift (2^3 = 8) */
1676 #define PERTURB_SHIFT   5       /* see Python 2.5.4 Objects/dictobject.c */
1677
1678 static void tgrow(struct table *);
1679 static int tnamecmp(const void *, const void *);
1680
1681 static void
1682 tgrow(struct table *tp)
1683 {
1684         size_t i, j, osize, mask, perturb;
1685         struct tbl *tblp, **pp;
1686         struct tbl **ntblp, **otblp = tp->tbls;
1687
1688         if (tp->tshift > 29)
1689                 internal_errorf("hash table size limit reached");
1690
1691         /* calculate old size, new shift and new size */
1692         osize = (size_t)1 << (tp->tshift++);
1693         i = osize << 1;
1694
1695         ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1696         /* multiplication cannot overflow: alloc2 checked that */
1697         memset(ntblp, 0, i * sizeof(struct tbl *));
1698
1699         /* table can get very full when reaching its size limit */
1700         tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1701             /* but otherwise, only 75% */
1702             ((i * 3) / 4);
1703         tp->tbls = ntblp;
1704         if (otblp == NULL)
1705                 return;
1706
1707         mask = i - 1;
1708         for (i = 0; i < osize; i++)
1709                 if ((tblp = otblp[i]) != NULL) {
1710                         if ((tblp->flag & DEFINED)) {
1711                                 /* search for free hash table slot */
1712                                 j = perturb = tblp->ua.hval;
1713                                 goto find_first_empty_slot;
1714  find_next_empty_slot:
1715                                 j = (j << 2) + j + perturb + 1;
1716                                 perturb >>= PERTURB_SHIFT;
1717  find_first_empty_slot:
1718                                 pp = &ntblp[j & mask];
1719                                 if (*pp != NULL)
1720                                         goto find_next_empty_slot;
1721                                 /* found an empty hash table slot */
1722                                 *pp = tblp;
1723                                 tp->nfree--;
1724                         } else if (!(tblp->flag & FINUSE)) {
1725                                 afree(tblp, tp->areap);
1726                         }
1727                 }
1728         afree(otblp, tp->areap);
1729 }
1730
1731 void
1732 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1733 {
1734         tp->areap = ap;
1735         tp->tbls = NULL;
1736         tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1737             initshift : INIT_TBLSHIFT) - 1;
1738         tgrow(tp);
1739 }
1740
1741 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1742 struct tbl *
1743 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1744 {
1745         size_t j, perturb, mask;
1746         struct tbl **pp, *p;
1747
1748         mask = ((size_t)1 << (tp->tshift)) - 1;
1749         /* search for hash table slot matching name */
1750         j = perturb = h;
1751         goto find_first_slot;
1752  find_next_slot:
1753         j = (j << 2) + j + perturb + 1;
1754         perturb >>= PERTURB_SHIFT;
1755  find_first_slot:
1756         pp = &tp->tbls[j & mask];
1757         if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1758             strcmp(p->name, name)))
1759                 goto find_next_slot;
1760         /* p == NULL if not found, correct found entry otherwise */
1761         if (ppp)
1762                 *ppp = pp;
1763         return (p);
1764 }
1765
1766 /* table, name (key) to enter, hash(n) */
1767 struct tbl *
1768 ktenter(struct table *tp, const char *n, uint32_t h)
1769 {
1770         struct tbl **pp, *p;
1771         size_t len;
1772
1773  Search:
1774         if ((p = ktscan(tp, n, h, &pp)))
1775                 return (p);
1776
1777         if (tp->nfree == 0) {
1778                 /* too full */
1779                 tgrow(tp);
1780                 goto Search;
1781         }
1782
1783         /* create new tbl entry */
1784         len = strlen(n);
1785         checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1786         p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1787         p->flag = 0;
1788         p->type = 0;
1789         p->areap = tp->areap;
1790         p->ua.hval = h;
1791         p->u2.field = 0;
1792         p->u.array = NULL;
1793         memcpy(p->name, n, len);
1794
1795         /* enter in tp->tbls */
1796         tp->nfree--;
1797         *pp = p;
1798         return (p);
1799 }
1800
1801 void
1802 ktwalk(struct tstate *ts, struct table *tp)
1803 {
1804         ts->left = (size_t)1 << (tp->tshift);
1805         ts->next = tp->tbls;
1806 }
1807
1808 struct tbl *
1809 ktnext(struct tstate *ts)
1810 {
1811         while (--ts->left >= 0) {
1812                 struct tbl *p = *ts->next++;
1813                 if (p != NULL && (p->flag & DEFINED))
1814                         return (p);
1815         }
1816         return (NULL);
1817 }
1818
1819 static int
1820 tnamecmp(const void *p1, const void *p2)
1821 {
1822         const struct tbl *a = *((const struct tbl * const *)p1);
1823         const struct tbl *b = *((const struct tbl * const *)p2);
1824
1825         return (strcmp(a->name, b->name));
1826 }
1827
1828 struct tbl **
1829 ktsort(struct table *tp)
1830 {
1831         size_t i;
1832         struct tbl **p, **sp, **dp;
1833
1834         /*
1835          * since the table is never entirely full, no need to reserve
1836          * additional space for the trailing NULL appended below
1837          */
1838         i = (size_t)1 << (tp->tshift);
1839         p = alloc2(i, sizeof(struct tbl *), ATEMP);
1840         sp = tp->tbls;          /* source */
1841         dp = p;                 /* dest */
1842         while (i--)
1843                 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1844                     ((*dp)->flag & ARRAY)))
1845                         dp++;
1846         qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1847         p[i] = NULL;
1848         return (p);
1849 }
1850
1851 #ifdef SIGWINCH
1852 static void
1853 x_sigwinch(int sig MKSH_A_UNUSED)
1854 {
1855         /* this runs inside interrupt context, with errno saved */
1856
1857         got_winch = 1;
1858 }
1859 #endif
1860
1861 #ifdef DF
1862 void
1863 DF(const char *fmt, ...)
1864 {
1865         va_list args;
1866         struct timeval tv;
1867         mirtime_mjd mjd;
1868
1869         mksh_lockfd(shl_dbg_fd);
1870         mksh_TIME(tv);
1871         timet2mjd(&mjd, tv.tv_sec);
1872         shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1873             (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1874             (unsigned)mjd.sec % 60, (unsigned)getpid(),
1875             (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1876         va_start(args, fmt);
1877         shf_vfprintf(shl_dbg, fmt, args);
1878         va_end(args);
1879         shf_putc('\n', shl_dbg);
1880         shf_flush(shl_dbg);
1881         mksh_unlkfd(shl_dbg_fd);
1882 }
1883 #endif
1884
1885 void
1886 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1887 {
1888         mksh_ttyst cb;
1889
1890         if (ocb)
1891                 mksh_tcget(fd, ocb);
1892         else
1893                 ocb = &tty_state;
1894
1895         cb = *ocb;
1896         if (forread) {
1897                 cb.c_iflag &= ~(ISTRIP);
1898                 cb.c_lflag &= ~(ICANON) | ECHO;
1899         } else {
1900                 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
1901                 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1902         }
1903 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1904         /* OSF/1 processes lnext when ~icanon */
1905         cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1906 #endif
1907         /* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
1908 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1909         cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1910 #endif
1911         cb.c_cc[VTIME] = 0;
1912         cb.c_cc[VMIN] = 1;
1913
1914         mksh_tcset(fd, &cb);
1915 }