OSDN Git Service

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