OSDN Git Service

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