ash: do not let EXIT trap to fire in `trap`
[oweals/busybox.git] / shell / ash.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * ash shell port for busybox
4  *
5  * Copyright (c) 1989, 1991, 1993, 1994
6  *      The Regents of the University of California.  All rights reserved.
7  *
8  * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9  * was re-ported from NetBSD and debianized.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * Kenneth Almquist.
13  *
14  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
15  *
16  * Original BSD copyright notice is retained at the end of this file.
17  */
18
19 /*
20  * The following should be set to reflect the type of system you have:
21  *      JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22  *      define SYSV if you are running under System V.
23  *      define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24  *      define DEBUG=2 to compile in and turn on debugging.
25  *
26  * When debugging is on, debugging info will be written to ./trace and
27  * a quit signal will generate a core dump.
28  */
29 #define DEBUG 0
30 /* Tweak debug output verbosity here */
31 #define DEBUG_TIME 0
32 #define DEBUG_PID 1
33 #define DEBUG_SIG 1
34
35 #define PROFILE 0
36
37 #define IFS_BROKEN
38
39 #define JOBS ENABLE_ASH_JOB_CONTROL
40
41 #if DEBUG
42 # ifndef _GNU_SOURCE
43 #  define _GNU_SOURCE
44 # endif
45 #endif
46
47 #include "busybox.h" /* for applet_names */
48 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49 //#include "applet_tables.h" doesn't work
50 #include <paths.h>
51 #include <setjmp.h>
52 #include <fnmatch.h>
53 #include "math.h"
54
55 #if defined SINGLE_APPLET_MAIN
56 /* STANDALONE does not make sense, and won't compile */
57 #undef CONFIG_FEATURE_SH_STANDALONE
58 #undef ENABLE_FEATURE_SH_STANDALONE
59 #undef IF_FEATURE_SH_STANDALONE
60 #undef IF_NOT_FEATURE_SH_STANDALONE(...)
61 #define ENABLE_FEATURE_SH_STANDALONE 0
62 #define IF_FEATURE_SH_STANDALONE(...)
63 #define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
64 #endif
65
66 #ifndef PIPE_BUF
67 # define PIPE_BUF 4096           /* amount of buffering in a pipe */
68 #endif
69
70 #if defined(__uClinux__)
71 # error "Do not even bother, ash will not run on NOMMU machine"
72 #endif
73
74
75 /* ============ Hash table sizes. Configurable. */
76
77 #define VTABSIZE 39
78 #define ATABSIZE 39
79 #define CMDTABLESIZE 31         /* should be prime */
80
81
82 /* ============ Shell options */
83
84 static const char *const optletters_optnames[] = {
85         "e"   "errexit",
86         "f"   "noglob",
87         "I"   "ignoreeof",
88         "i"   "interactive",
89         "m"   "monitor",
90         "n"   "noexec",
91         "s"   "stdin",
92         "x"   "xtrace",
93         "v"   "verbose",
94         "C"   "noclobber",
95         "a"   "allexport",
96         "b"   "notify",
97         "u"   "nounset",
98         "\0"  "vi"
99 #if DEBUG
100         ,"\0"  "nolog"
101         ,"\0"  "debug"
102 #endif
103 };
104
105 #define optletters(n) optletters_optnames[(n)][0]
106 #define optnames(n) (&optletters_optnames[(n)][1])
107
108 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
109
110
111 /* ============ Misc data */
112
113 static const char homestr[] ALIGN1 = "HOME";
114 static const char snlfmt[] ALIGN1 = "%s\n";
115 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
116
117 /*
118  * We enclose jmp_buf in a structure so that we can declare pointers to
119  * jump locations.  The global variable handler contains the location to
120  * jump to when an exception occurs, and the global variable exception_type
121  * contains a code identifying the exception.  To implement nested
122  * exception handlers, the user should save the value of handler on entry
123  * to an inner scope, set handler to point to a jmploc structure for the
124  * inner scope, and restore handler on exit from the scope.
125  */
126 struct jmploc {
127         jmp_buf loc;
128 };
129
130 struct globals_misc {
131         /* pid of main shell */
132         int rootpid;
133         /* shell level: 0 for the main shell, 1 for its children, and so on */
134         int shlvl;
135 #define rootshell (!shlvl)
136         char *minusc;  /* argument to -c option */
137
138         char *curdir; // = nullstr;     /* current working directory */
139         char *physdir; // = nullstr;    /* physical working directory */
140
141         char *arg0; /* value of $0 */
142
143         struct jmploc *exception_handler;
144
145         volatile int suppress_int; /* counter */
146         volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
147         /* last pending signal */
148         volatile /*sig_atomic_t*/ smallint pending_sig;
149         smallint exception_type; /* kind of exception (0..5) */
150         /* exceptions */
151 #define EXINT 0         /* SIGINT received */
152 #define EXERROR 1       /* a generic error */
153 #define EXSHELLPROC 2   /* execute a shell procedure */
154 #define EXEXEC 3        /* command execution failed */
155 #define EXEXIT 4        /* exit the shell */
156 #define EXSIG 5         /* trapped signal in wait(1) */
157
158         smallint isloginsh;
159         char nullstr[1];        /* zero length string */
160
161         char optlist[NOPTS];
162 #define eflag optlist[0]
163 #define fflag optlist[1]
164 #define Iflag optlist[2]
165 #define iflag optlist[3]
166 #define mflag optlist[4]
167 #define nflag optlist[5]
168 #define sflag optlist[6]
169 #define xflag optlist[7]
170 #define vflag optlist[8]
171 #define Cflag optlist[9]
172 #define aflag optlist[10]
173 #define bflag optlist[11]
174 #define uflag optlist[12]
175 #define viflag optlist[13]
176 #if DEBUG
177 #define nolog optlist[14]
178 #define debug optlist[15]
179 #endif
180
181         /* trap handler commands */
182         /*
183          * Sigmode records the current value of the signal handlers for the various
184          * modes.  A value of zero means that the current handler is not known.
185          * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
186          */
187         char sigmode[NSIG - 1];
188 #define S_DFL      1            /* default signal handling (SIG_DFL) */
189 #define S_CATCH    2            /* signal is caught */
190 #define S_IGN      3            /* signal is ignored (SIG_IGN) */
191 #define S_HARD_IGN 4            /* signal is ignored permenantly */
192
193         /* indicates specified signal received */
194         uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
195         char *trap[NSIG];
196
197         /* Rarely referenced stuff */
198 #if ENABLE_ASH_RANDOM_SUPPORT
199         /* Random number generators */
200         int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
201         uint32_t random_LCG;        /* LCG (fast but weak) */
202 #endif
203         pid_t backgndpid;        /* pid of last background process */
204         smallint job_warning;    /* user was warned about stopped jobs (can be 2, 1 or 0). */
205 };
206 extern struct globals_misc *const ash_ptr_to_globals_misc;
207 #define G_misc (*ash_ptr_to_globals_misc)
208 #define rootpid     (G_misc.rootpid    )
209 #define shlvl       (G_misc.shlvl      )
210 #define minusc      (G_misc.minusc     )
211 #define curdir      (G_misc.curdir     )
212 #define physdir     (G_misc.physdir    )
213 #define arg0        (G_misc.arg0       )
214 #define exception_handler (G_misc.exception_handler)
215 #define exception_type    (G_misc.exception_type   )
216 #define suppress_int      (G_misc.suppress_int     )
217 #define pending_int       (G_misc.pending_int      )
218 #define pending_sig       (G_misc.pending_sig      )
219 #define isloginsh   (G_misc.isloginsh  )
220 #define nullstr     (G_misc.nullstr    )
221 #define optlist     (G_misc.optlist    )
222 #define sigmode     (G_misc.sigmode    )
223 #define gotsig      (G_misc.gotsig     )
224 #define trap        (G_misc.trap       )
225 #define random_galois_LFSR (G_misc.random_galois_LFSR)
226 #define random_LCG         (G_misc.random_LCG        )
227 #define backgndpid  (G_misc.backgndpid )
228 #define job_warning (G_misc.job_warning)
229 #define INIT_G_misc() do { \
230         (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
231         barrier(); \
232         curdir = nullstr; \
233         physdir = nullstr; \
234 } while (0)
235
236
237 /* ============ DEBUG */
238 #if DEBUG
239 static void trace_printf(const char *fmt, ...);
240 static void trace_vprintf(const char *fmt, va_list va);
241 # define TRACE(param)    trace_printf param
242 # define TRACEV(param)   trace_vprintf param
243 # define close(fd) do { \
244         int dfd = (fd); \
245         if (close(dfd) < 0) \
246                 bb_error_msg("bug on %d: closing %d(0x%x)", \
247                         __LINE__, dfd, dfd); \
248 } while (0)
249 #else
250 # define TRACE(param)
251 # define TRACEV(param)
252 #endif
253
254
255 /* ============ Utility functions */
256 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
257
258 /* C99 says: "char" declaration may be signed or unsigned by default */
259 #define signed_char2int(sc) ((int)(signed char)(sc))
260
261 static int isdigit_str9(const char *str)
262 {
263         int maxlen = 9 + 1; /* max 9 digits: 999999999 */
264         while (--maxlen && isdigit(*str))
265                 str++;
266         return (*str == '\0');
267 }
268
269
270 /* ============ Interrupts / exceptions */
271 /*
272  * These macros allow the user to suspend the handling of interrupt signals
273  * over a period of time.  This is similar to SIGHOLD or to sigblock, but
274  * much more efficient and portable.  (But hacking the kernel is so much
275  * more fun than worrying about efficiency and portability. :-))
276  */
277 #define INT_OFF do { \
278         suppress_int++; \
279         xbarrier(); \
280 } while (0)
281
282 /*
283  * Called to raise an exception.  Since C doesn't include exceptions, we
284  * just do a longjmp to the exception handler.  The type of exception is
285  * stored in the global variable "exception_type".
286  */
287 static void raise_exception(int) NORETURN;
288 static void
289 raise_exception(int e)
290 {
291 #if DEBUG
292         if (exception_handler == NULL)
293                 abort();
294 #endif
295         INT_OFF;
296         exception_type = e;
297         longjmp(exception_handler->loc, 1);
298 }
299 #if DEBUG
300 #define raise_exception(e) do { \
301         TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
302         raise_exception(e); \
303 } while (0)
304 #endif
305
306 /*
307  * Called from trap.c when a SIGINT is received.  (If the user specifies
308  * that SIGINT is to be trapped or ignored using the trap builtin, then
309  * this routine is not called.)  Suppressint is nonzero when interrupts
310  * are held using the INT_OFF macro.  (The test for iflag is just
311  * defensive programming.)
312  */
313 static void raise_interrupt(void) NORETURN;
314 static void
315 raise_interrupt(void)
316 {
317         int ex_type;
318
319         pending_int = 0;
320         /* Signal is not automatically unmasked after it is raised,
321          * do it ourself - unmask all signals */
322         sigprocmask_allsigs(SIG_UNBLOCK);
323         /* pending_sig = 0; - now done in onsig() */
324
325         ex_type = EXSIG;
326         if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
327                 if (!(rootshell && iflag)) {
328                         /* Kill ourself with SIGINT */
329                         signal(SIGINT, SIG_DFL);
330                         raise(SIGINT);
331                 }
332                 ex_type = EXINT;
333         }
334         raise_exception(ex_type);
335         /* NOTREACHED */
336 }
337 #if DEBUG
338 #define raise_interrupt() do { \
339         TRACE(("raising interrupt on line %d\n", __LINE__)); \
340         raise_interrupt(); \
341 } while (0)
342 #endif
343
344 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
345 int_on(void)
346 {
347         xbarrier();
348         if (--suppress_int == 0 && pending_int) {
349                 raise_interrupt();
350         }
351 }
352 #define INT_ON int_on()
353 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
354 force_int_on(void)
355 {
356         xbarrier();
357         suppress_int = 0;
358         if (pending_int)
359                 raise_interrupt();
360 }
361 #define FORCE_INT_ON force_int_on()
362
363 #define SAVE_INT(v) ((v) = suppress_int)
364
365 #define RESTORE_INT(v) do { \
366         xbarrier(); \
367         suppress_int = (v); \
368         if (suppress_int == 0 && pending_int) \
369                 raise_interrupt(); \
370 } while (0)
371
372
373 /* ============ Stdout/stderr output */
374
375 static void
376 outstr(const char *p, FILE *file)
377 {
378         INT_OFF;
379         fputs(p, file);
380         INT_ON;
381 }
382
383 static void
384 flush_stdout_stderr(void)
385 {
386         INT_OFF;
387         fflush(stdout);
388         fflush(stderr);
389         INT_ON;
390 }
391
392 static void
393 flush_stderr(void)
394 {
395         INT_OFF;
396         fflush(stderr);
397         INT_ON;
398 }
399
400 static void
401 outcslow(int c, FILE *dest)
402 {
403         INT_OFF;
404         putc(c, dest);
405         fflush(dest);
406         INT_ON;
407 }
408
409 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
410 static int
411 out1fmt(const char *fmt, ...)
412 {
413         va_list ap;
414         int r;
415
416         INT_OFF;
417         va_start(ap, fmt);
418         r = vprintf(fmt, ap);
419         va_end(ap);
420         INT_ON;
421         return r;
422 }
423
424 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
425 static int
426 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
427 {
428         va_list ap;
429         int ret;
430
431         va_start(ap, fmt);
432         INT_OFF;
433         ret = vsnprintf(outbuf, length, fmt, ap);
434         va_end(ap);
435         INT_ON;
436         return ret;
437 }
438
439 static void
440 out1str(const char *p)
441 {
442         outstr(p, stdout);
443 }
444
445 static void
446 out2str(const char *p)
447 {
448         outstr(p, stderr);
449         flush_stderr();
450 }
451
452
453 /* ============ Parser structures */
454
455 /* control characters in argument strings */
456 #define CTLESC       ((unsigned char)'\201')    /* escape next character */
457 #define CTLVAR       ((unsigned char)'\202')    /* variable defn */
458 #define CTLENDVAR    ((unsigned char)'\203')
459 #define CTLBACKQ     ((unsigned char)'\204')
460 #define CTLQUOTE 01             /* ored with CTLBACKQ code if in quotes */
461 /*      CTLBACKQ | CTLQUOTE == '\205' */
462 #define CTLARI       ((unsigned char)'\206')    /* arithmetic expression */
463 #define CTLENDARI    ((unsigned char)'\207')
464 #define CTLQUOTEMARK ((unsigned char)'\210')
465
466 /* variable substitution byte (follows CTLVAR) */
467 #define VSTYPE  0x0f            /* type of variable substitution */
468 #define VSNUL   0x10            /* colon--treat the empty string as unset */
469 #define VSQUOTE 0x80            /* inside double quotes--suppress splitting */
470
471 /* values of VSTYPE field */
472 #define VSNORMAL        0x1     /* normal variable:  $var or ${var} */
473 #define VSMINUS         0x2     /* ${var-text} */
474 #define VSPLUS          0x3     /* ${var+text} */
475 #define VSQUESTION      0x4     /* ${var?message} */
476 #define VSASSIGN        0x5     /* ${var=text} */
477 #define VSTRIMRIGHT     0x6     /* ${var%pattern} */
478 #define VSTRIMRIGHTMAX  0x7     /* ${var%%pattern} */
479 #define VSTRIMLEFT      0x8     /* ${var#pattern} */
480 #define VSTRIMLEFTMAX   0x9     /* ${var##pattern} */
481 #define VSLENGTH        0xa     /* ${#var} */
482 #if ENABLE_ASH_BASH_COMPAT
483 #define VSSUBSTR        0xc     /* ${var:position:length} */
484 #define VSREPLACE       0xd     /* ${var/pattern/replacement} */
485 #define VSREPLACEALL    0xe     /* ${var//pattern/replacement} */
486 #endif
487
488 static const char dolatstr[] ALIGN1 = {
489         CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
490 };
491
492 #define NCMD      0
493 #define NPIPE     1
494 #define NREDIR    2
495 #define NBACKGND  3
496 #define NSUBSHELL 4
497 #define NAND      5
498 #define NOR       6
499 #define NSEMI     7
500 #define NIF       8
501 #define NWHILE    9
502 #define NUNTIL   10
503 #define NFOR     11
504 #define NCASE    12
505 #define NCLIST   13
506 #define NDEFUN   14
507 #define NARG     15
508 #define NTO      16
509 #if ENABLE_ASH_BASH_COMPAT
510 #define NTO2     17
511 #endif
512 #define NCLOBBER 18
513 #define NFROM    19
514 #define NFROMTO  20
515 #define NAPPEND  21
516 #define NTOFD    22
517 #define NFROMFD  23
518 #define NHERE    24
519 #define NXHERE   25
520 #define NNOT     26
521 #define N_NUMBER 27
522
523 union node;
524
525 struct ncmd {
526         smallint type; /* Nxxxx */
527         union node *assign;
528         union node *args;
529         union node *redirect;
530 };
531
532 struct npipe {
533         smallint type;
534         smallint pipe_backgnd;
535         struct nodelist *cmdlist;
536 };
537
538 struct nredir {
539         smallint type;
540         union node *n;
541         union node *redirect;
542 };
543
544 struct nbinary {
545         smallint type;
546         union node *ch1;
547         union node *ch2;
548 };
549
550 struct nif {
551         smallint type;
552         union node *test;
553         union node *ifpart;
554         union node *elsepart;
555 };
556
557 struct nfor {
558         smallint type;
559         union node *args;
560         union node *body;
561         char *var;
562 };
563
564 struct ncase {
565         smallint type;
566         union node *expr;
567         union node *cases;
568 };
569
570 struct nclist {
571         smallint type;
572         union node *next;
573         union node *pattern;
574         union node *body;
575 };
576
577 struct narg {
578         smallint type;
579         union node *next;
580         char *text;
581         struct nodelist *backquote;
582 };
583
584 /* nfile and ndup layout must match!
585  * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
586  * that it is actually NTO2 (>&file), and change its type.
587  */
588 struct nfile {
589         smallint type;
590         union node *next;
591         int fd;
592         int _unused_dupfd;
593         union node *fname;
594         char *expfname;
595 };
596
597 struct ndup {
598         smallint type;
599         union node *next;
600         int fd;
601         int dupfd;
602         union node *vname;
603         char *_unused_expfname;
604 };
605
606 struct nhere {
607         smallint type;
608         union node *next;
609         int fd;
610         union node *doc;
611 };
612
613 struct nnot {
614         smallint type;
615         union node *com;
616 };
617
618 union node {
619         smallint type;
620         struct ncmd ncmd;
621         struct npipe npipe;
622         struct nredir nredir;
623         struct nbinary nbinary;
624         struct nif nif;
625         struct nfor nfor;
626         struct ncase ncase;
627         struct nclist nclist;
628         struct narg narg;
629         struct nfile nfile;
630         struct ndup ndup;
631         struct nhere nhere;
632         struct nnot nnot;
633 };
634
635 /*
636  * NODE_EOF is returned by parsecmd when it encounters an end of file.
637  * It must be distinct from NULL.
638  */
639 #define NODE_EOF ((union node *) -1L)
640
641 struct nodelist {
642         struct nodelist *next;
643         union node *n;
644 };
645
646 struct funcnode {
647         int count;
648         union node n;
649 };
650
651 /*
652  * Free a parse tree.
653  */
654 static void
655 freefunc(struct funcnode *f)
656 {
657         if (f && --f->count < 0)
658                 free(f);
659 }
660
661
662 /* ============ Debugging output */
663
664 #if DEBUG
665
666 static FILE *tracefile;
667
668 static void
669 trace_printf(const char *fmt, ...)
670 {
671         va_list va;
672
673         if (debug != 1)
674                 return;
675         if (DEBUG_TIME)
676                 fprintf(tracefile, "%u ", (int) time(NULL));
677         if (DEBUG_PID)
678                 fprintf(tracefile, "[%u] ", (int) getpid());
679         if (DEBUG_SIG)
680                 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
681         va_start(va, fmt);
682         vfprintf(tracefile, fmt, va);
683         va_end(va);
684 }
685
686 static void
687 trace_vprintf(const char *fmt, va_list va)
688 {
689         if (debug != 1)
690                 return;
691         if (DEBUG_TIME)
692                 fprintf(tracefile, "%u ", (int) time(NULL));
693         if (DEBUG_PID)
694                 fprintf(tracefile, "[%u] ", (int) getpid());
695         if (DEBUG_SIG)
696                 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
697         vfprintf(tracefile, fmt, va);
698 }
699
700 static void
701 trace_puts(const char *s)
702 {
703         if (debug != 1)
704                 return;
705         fputs(s, tracefile);
706 }
707
708 static void
709 trace_puts_quoted(char *s)
710 {
711         char *p;
712         char c;
713
714         if (debug != 1)
715                 return;
716         putc('"', tracefile);
717         for (p = s; *p; p++) {
718                 switch (*p) {
719                 case '\n':  c = 'n';  goto backslash;
720                 case '\t':  c = 't';  goto backslash;
721                 case '\r':  c = 'r';  goto backslash;
722                 case '"':  c = '"';  goto backslash;
723                 case '\\':  c = '\\';  goto backslash;
724                 case CTLESC:  c = 'e';  goto backslash;
725                 case CTLVAR:  c = 'v';  goto backslash;
726                 case CTLVAR+CTLQUOTE:  c = 'V'; goto backslash;
727                 case CTLBACKQ:  c = 'q';  goto backslash;
728                 case CTLBACKQ+CTLQUOTE:  c = 'Q'; goto backslash;
729  backslash:
730                         putc('\\', tracefile);
731                         putc(c, tracefile);
732                         break;
733                 default:
734                         if (*p >= ' ' && *p <= '~')
735                                 putc(*p, tracefile);
736                         else {
737                                 putc('\\', tracefile);
738                                 putc(*p >> 6 & 03, tracefile);
739                                 putc(*p >> 3 & 07, tracefile);
740                                 putc(*p & 07, tracefile);
741                         }
742                         break;
743                 }
744         }
745         putc('"', tracefile);
746 }
747
748 static void
749 trace_puts_args(char **ap)
750 {
751         if (debug != 1)
752                 return;
753         if (!*ap)
754                 return;
755         while (1) {
756                 trace_puts_quoted(*ap);
757                 if (!*++ap) {
758                         putc('\n', tracefile);
759                         break;
760                 }
761                 putc(' ', tracefile);
762         }
763 }
764
765 static void
766 opentrace(void)
767 {
768         char s[100];
769 #ifdef O_APPEND
770         int flags;
771 #endif
772
773         if (debug != 1) {
774                 if (tracefile)
775                         fflush(tracefile);
776                 /* leave open because libedit might be using it */
777                 return;
778         }
779         strcpy(s, "./trace");
780         if (tracefile) {
781                 if (!freopen(s, "a", tracefile)) {
782                         fprintf(stderr, "Can't re-open %s\n", s);
783                         debug = 0;
784                         return;
785                 }
786         } else {
787                 tracefile = fopen(s, "a");
788                 if (tracefile == NULL) {
789                         fprintf(stderr, "Can't open %s\n", s);
790                         debug = 0;
791                         return;
792                 }
793         }
794 #ifdef O_APPEND
795         flags = fcntl(fileno(tracefile), F_GETFL);
796         if (flags >= 0)
797                 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
798 #endif
799         setlinebuf(tracefile);
800         fputs("\nTracing started.\n", tracefile);
801 }
802
803 static void
804 indent(int amount, char *pfx, FILE *fp)
805 {
806         int i;
807
808         for (i = 0; i < amount; i++) {
809                 if (pfx && i == amount - 1)
810                         fputs(pfx, fp);
811                 putc('\t', fp);
812         }
813 }
814
815 /* little circular references here... */
816 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
817
818 static void
819 sharg(union node *arg, FILE *fp)
820 {
821         char *p;
822         struct nodelist *bqlist;
823         int subtype;
824
825         if (arg->type != NARG) {
826                 out1fmt("<node type %d>\n", arg->type);
827                 abort();
828         }
829         bqlist = arg->narg.backquote;
830         for (p = arg->narg.text; *p; p++) {
831                 switch (*p) {
832                 case CTLESC:
833                         putc(*++p, fp);
834                         break;
835                 case CTLVAR:
836                         putc('$', fp);
837                         putc('{', fp);
838                         subtype = *++p;
839                         if (subtype == VSLENGTH)
840                                 putc('#', fp);
841
842                         while (*p != '=')
843                                 putc(*p++, fp);
844
845                         if (subtype & VSNUL)
846                                 putc(':', fp);
847
848                         switch (subtype & VSTYPE) {
849                         case VSNORMAL:
850                                 putc('}', fp);
851                                 break;
852                         case VSMINUS:
853                                 putc('-', fp);
854                                 break;
855                         case VSPLUS:
856                                 putc('+', fp);
857                                 break;
858                         case VSQUESTION:
859                                 putc('?', fp);
860                                 break;
861                         case VSASSIGN:
862                                 putc('=', fp);
863                                 break;
864                         case VSTRIMLEFT:
865                                 putc('#', fp);
866                                 break;
867                         case VSTRIMLEFTMAX:
868                                 putc('#', fp);
869                                 putc('#', fp);
870                                 break;
871                         case VSTRIMRIGHT:
872                                 putc('%', fp);
873                                 break;
874                         case VSTRIMRIGHTMAX:
875                                 putc('%', fp);
876                                 putc('%', fp);
877                                 break;
878                         case VSLENGTH:
879                                 break;
880                         default:
881                                 out1fmt("<subtype %d>", subtype);
882                         }
883                         break;
884                 case CTLENDVAR:
885                         putc('}', fp);
886                         break;
887                 case CTLBACKQ:
888                 case CTLBACKQ|CTLQUOTE:
889                         putc('$', fp);
890                         putc('(', fp);
891                         shtree(bqlist->n, -1, NULL, fp);
892                         putc(')', fp);
893                         break;
894                 default:
895                         putc(*p, fp);
896                         break;
897                 }
898         }
899 }
900
901 static void
902 shcmd(union node *cmd, FILE *fp)
903 {
904         union node *np;
905         int first;
906         const char *s;
907         int dftfd;
908
909         first = 1;
910         for (np = cmd->ncmd.args; np; np = np->narg.next) {
911                 if (!first)
912                         putc(' ', fp);
913                 sharg(np, fp);
914                 first = 0;
915         }
916         for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
917                 if (!first)
918                         putc(' ', fp);
919                 dftfd = 0;
920                 switch (np->nfile.type) {
921                 case NTO:      s = ">>"+1; dftfd = 1; break;
922                 case NCLOBBER: s = ">|"; dftfd = 1; break;
923                 case NAPPEND:  s = ">>"; dftfd = 1; break;
924 #if ENABLE_ASH_BASH_COMPAT
925                 case NTO2:
926 #endif
927                 case NTOFD:    s = ">&"; dftfd = 1; break;
928                 case NFROM:    s = "<"; break;
929                 case NFROMFD:  s = "<&"; break;
930                 case NFROMTO:  s = "<>"; break;
931                 default:       s = "*error*"; break;
932                 }
933                 if (np->nfile.fd != dftfd)
934                         fprintf(fp, "%d", np->nfile.fd);
935                 fputs(s, fp);
936                 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
937                         fprintf(fp, "%d", np->ndup.dupfd);
938                 } else {
939                         sharg(np->nfile.fname, fp);
940                 }
941                 first = 0;
942         }
943 }
944
945 static void
946 shtree(union node *n, int ind, char *pfx, FILE *fp)
947 {
948         struct nodelist *lp;
949         const char *s;
950
951         if (n == NULL)
952                 return;
953
954         indent(ind, pfx, fp);
955
956         if (n == NODE_EOF) {
957                 fputs("<EOF>", fp);
958                 return;
959         }
960
961         switch (n->type) {
962         case NSEMI:
963                 s = "; ";
964                 goto binop;
965         case NAND:
966                 s = " && ";
967                 goto binop;
968         case NOR:
969                 s = " || ";
970  binop:
971                 shtree(n->nbinary.ch1, ind, NULL, fp);
972                 /* if (ind < 0) */
973                         fputs(s, fp);
974                 shtree(n->nbinary.ch2, ind, NULL, fp);
975                 break;
976         case NCMD:
977                 shcmd(n, fp);
978                 if (ind >= 0)
979                         putc('\n', fp);
980                 break;
981         case NPIPE:
982                 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
983                         shtree(lp->n, 0, NULL, fp);
984                         if (lp->next)
985                                 fputs(" | ", fp);
986                 }
987                 if (n->npipe.pipe_backgnd)
988                         fputs(" &", fp);
989                 if (ind >= 0)
990                         putc('\n', fp);
991                 break;
992         default:
993                 fprintf(fp, "<node type %d>", n->type);
994                 if (ind >= 0)
995                         putc('\n', fp);
996                 break;
997         }
998 }
999
1000 static void
1001 showtree(union node *n)
1002 {
1003         trace_puts("showtree called\n");
1004         shtree(n, 1, NULL, stderr);
1005 }
1006
1007 #endif /* DEBUG */
1008
1009
1010 /* ============ Parser data */
1011
1012 /*
1013  * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1014  */
1015 struct strlist {
1016         struct strlist *next;
1017         char *text;
1018 };
1019
1020 struct alias;
1021
1022 struct strpush {
1023         struct strpush *prev;   /* preceding string on stack */
1024         char *prev_string;
1025         int prev_left_in_line;
1026 #if ENABLE_ASH_ALIAS
1027         struct alias *ap;       /* if push was associated with an alias */
1028 #endif
1029         char *string;           /* remember the string since it may change */
1030 };
1031
1032 struct parsefile {
1033         struct parsefile *prev; /* preceding file on stack */
1034         int linno;              /* current line */
1035         int fd;                 /* file descriptor (or -1 if string) */
1036         int left_in_line;       /* number of chars left in this line */
1037         int left_in_buffer;     /* number of chars left in this buffer past the line */
1038         char *next_to_pgetc;    /* next char in buffer */
1039         char *buf;              /* input buffer */
1040         struct strpush *strpush; /* for pushing strings at this level */
1041         struct strpush basestrpush; /* so pushing one is fast */
1042 };
1043
1044 static struct parsefile basepf;        /* top level input file */
1045 static struct parsefile *g_parsefile = &basepf;  /* current input file */
1046 static int startlinno;                 /* line # where last token started */
1047 static char *commandname;              /* currently executing command */
1048 static struct strlist *cmdenviron;     /* environment for builtin command */
1049 static uint8_t exitstatus;             /* exit status of last command */
1050
1051
1052 /* ============ Message printing */
1053
1054 static void
1055 ash_vmsg(const char *msg, va_list ap)
1056 {
1057         fprintf(stderr, "%s: ", arg0);
1058         if (commandname) {
1059                 if (strcmp(arg0, commandname))
1060                         fprintf(stderr, "%s: ", commandname);
1061                 if (!iflag || g_parsefile->fd)
1062                         fprintf(stderr, "line %d: ", startlinno);
1063         }
1064         vfprintf(stderr, msg, ap);
1065         outcslow('\n', stderr);
1066 }
1067
1068 /*
1069  * Exverror is called to raise the error exception.  If the second argument
1070  * is not NULL then error prints an error message using printf style
1071  * formatting.  It then raises the error exception.
1072  */
1073 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1074 static void
1075 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1076 {
1077 #if DEBUG
1078         if (msg) {
1079                 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1080                 TRACEV((msg, ap));
1081                 TRACE(("\") pid=%d\n", getpid()));
1082         } else
1083                 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1084         if (msg)
1085 #endif
1086                 ash_vmsg(msg, ap);
1087
1088         flush_stdout_stderr();
1089         raise_exception(cond);
1090         /* NOTREACHED */
1091 }
1092
1093 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1094 static void
1095 ash_msg_and_raise_error(const char *msg, ...)
1096 {
1097         va_list ap;
1098
1099         va_start(ap, msg);
1100         ash_vmsg_and_raise(EXERROR, msg, ap);
1101         /* NOTREACHED */
1102         va_end(ap);
1103 }
1104
1105 static void raise_error_syntax(const char *) NORETURN;
1106 static void
1107 raise_error_syntax(const char *msg)
1108 {
1109         ash_msg_and_raise_error("syntax error: %s", msg);
1110         /* NOTREACHED */
1111 }
1112
1113 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1114 static void
1115 ash_msg_and_raise(int cond, const char *msg, ...)
1116 {
1117         va_list ap;
1118
1119         va_start(ap, msg);
1120         ash_vmsg_and_raise(cond, msg, ap);
1121         /* NOTREACHED */
1122         va_end(ap);
1123 }
1124
1125 /*
1126  * error/warning routines for external builtins
1127  */
1128 static void
1129 ash_msg(const char *fmt, ...)
1130 {
1131         va_list ap;
1132
1133         va_start(ap, fmt);
1134         ash_vmsg(fmt, ap);
1135         va_end(ap);
1136 }
1137
1138 /*
1139  * Return a string describing an error.  The returned string may be a
1140  * pointer to a static buffer that will be overwritten on the next call.
1141  * Action describes the operation that got the error.
1142  */
1143 static const char *
1144 errmsg(int e, const char *em)
1145 {
1146         if (e == ENOENT || e == ENOTDIR) {
1147                 return em;
1148         }
1149         return strerror(e);
1150 }
1151
1152
1153 /* ============ Memory allocation */
1154
1155 /*
1156  * It appears that grabstackstr() will barf with such alignments
1157  * because stalloc() will return a string allocated in a new stackblock.
1158  */
1159 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1160 enum {
1161         /* Most machines require the value returned from malloc to be aligned
1162          * in some way.  The following macro will get this right
1163          * on many machines.  */
1164         SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1165         /* Minimum size of a block */
1166         MINSIZE = SHELL_ALIGN(504),
1167 };
1168
1169 struct stack_block {
1170         struct stack_block *prev;
1171         char space[MINSIZE];
1172 };
1173
1174 struct stackmark {
1175         struct stack_block *stackp;
1176         char *stacknxt;
1177         size_t stacknleft;
1178         struct stackmark *marknext;
1179 };
1180
1181
1182 struct globals_memstack {
1183         struct stack_block *g_stackp; // = &stackbase;
1184         struct stackmark *markp;
1185         char *g_stacknxt; // = stackbase.space;
1186         char *sstrend; // = stackbase.space + MINSIZE;
1187         size_t g_stacknleft; // = MINSIZE;
1188         int    herefd; // = -1;
1189         struct stack_block stackbase;
1190 };
1191 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1192 #define G_memstack (*ash_ptr_to_globals_memstack)
1193 #define g_stackp     (G_memstack.g_stackp    )
1194 #define markp        (G_memstack.markp       )
1195 #define g_stacknxt   (G_memstack.g_stacknxt  )
1196 #define sstrend      (G_memstack.sstrend     )
1197 #define g_stacknleft (G_memstack.g_stacknleft)
1198 #define herefd       (G_memstack.herefd      )
1199 #define stackbase    (G_memstack.stackbase   )
1200 #define INIT_G_memstack() do { \
1201         (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1202         barrier(); \
1203         g_stackp = &stackbase; \
1204         g_stacknxt = stackbase.space; \
1205         g_stacknleft = MINSIZE; \
1206         sstrend = stackbase.space + MINSIZE; \
1207         herefd = -1; \
1208 } while (0)
1209
1210 #define stackblock()     ((void *)g_stacknxt)
1211 #define stackblocksize() g_stacknleft
1212
1213
1214 static void *
1215 ckrealloc(void * p, size_t nbytes)
1216 {
1217         p = realloc(p, nbytes);
1218         if (!p)
1219                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1220         return p;
1221 }
1222
1223 static void *
1224 ckmalloc(size_t nbytes)
1225 {
1226         return ckrealloc(NULL, nbytes);
1227 }
1228
1229 static void *
1230 ckzalloc(size_t nbytes)
1231 {
1232         return memset(ckmalloc(nbytes), 0, nbytes);
1233 }
1234
1235 /*
1236  * Make a copy of a string in safe storage.
1237  */
1238 static char *
1239 ckstrdup(const char *s)
1240 {
1241         char *p = strdup(s);
1242         if (!p)
1243                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1244         return p;
1245 }
1246
1247 /*
1248  * Parse trees for commands are allocated in lifo order, so we use a stack
1249  * to make this more efficient, and also to avoid all sorts of exception
1250  * handling code to handle interrupts in the middle of a parse.
1251  *
1252  * The size 504 was chosen because the Ultrix malloc handles that size
1253  * well.
1254  */
1255 static void *
1256 stalloc(size_t nbytes)
1257 {
1258         char *p;
1259         size_t aligned;
1260
1261         aligned = SHELL_ALIGN(nbytes);
1262         if (aligned > g_stacknleft) {
1263                 size_t len;
1264                 size_t blocksize;
1265                 struct stack_block *sp;
1266
1267                 blocksize = aligned;
1268                 if (blocksize < MINSIZE)
1269                         blocksize = MINSIZE;
1270                 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1271                 if (len < blocksize)
1272                         ash_msg_and_raise_error(bb_msg_memory_exhausted);
1273                 INT_OFF;
1274                 sp = ckmalloc(len);
1275                 sp->prev = g_stackp;
1276                 g_stacknxt = sp->space;
1277                 g_stacknleft = blocksize;
1278                 sstrend = g_stacknxt + blocksize;
1279                 g_stackp = sp;
1280                 INT_ON;
1281         }
1282         p = g_stacknxt;
1283         g_stacknxt += aligned;
1284         g_stacknleft -= aligned;
1285         return p;
1286 }
1287
1288 static void *
1289 stzalloc(size_t nbytes)
1290 {
1291         return memset(stalloc(nbytes), 0, nbytes);
1292 }
1293
1294 static void
1295 stunalloc(void *p)
1296 {
1297 #if DEBUG
1298         if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1299                 write(STDERR_FILENO, "stunalloc\n", 10);
1300                 abort();
1301         }
1302 #endif
1303         g_stacknleft += g_stacknxt - (char *)p;
1304         g_stacknxt = p;
1305 }
1306
1307 /*
1308  * Like strdup but works with the ash stack.
1309  */
1310 static char *
1311 ststrdup(const char *p)
1312 {
1313         size_t len = strlen(p) + 1;
1314         return memcpy(stalloc(len), p, len);
1315 }
1316
1317 static void
1318 setstackmark(struct stackmark *mark)
1319 {
1320         mark->stackp = g_stackp;
1321         mark->stacknxt = g_stacknxt;
1322         mark->stacknleft = g_stacknleft;
1323         mark->marknext = markp;
1324         markp = mark;
1325 }
1326
1327 static void
1328 popstackmark(struct stackmark *mark)
1329 {
1330         struct stack_block *sp;
1331
1332         if (!mark->stackp)
1333                 return;
1334
1335         INT_OFF;
1336         markp = mark->marknext;
1337         while (g_stackp != mark->stackp) {
1338                 sp = g_stackp;
1339                 g_stackp = sp->prev;
1340                 free(sp);
1341         }
1342         g_stacknxt = mark->stacknxt;
1343         g_stacknleft = mark->stacknleft;
1344         sstrend = mark->stacknxt + mark->stacknleft;
1345         INT_ON;
1346 }
1347
1348 /*
1349  * When the parser reads in a string, it wants to stick the string on the
1350  * stack and only adjust the stack pointer when it knows how big the
1351  * string is.  Stackblock (defined in stack.h) returns a pointer to a block
1352  * of space on top of the stack and stackblocklen returns the length of
1353  * this block.  Growstackblock will grow this space by at least one byte,
1354  * possibly moving it (like realloc).  Grabstackblock actually allocates the
1355  * part of the block that has been used.
1356  */
1357 static void
1358 growstackblock(void)
1359 {
1360         size_t newlen;
1361
1362         newlen = g_stacknleft * 2;
1363         if (newlen < g_stacknleft)
1364                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1365         if (newlen < 128)
1366                 newlen += 128;
1367
1368         if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1369                 struct stack_block *oldstackp;
1370                 struct stackmark *xmark;
1371                 struct stack_block *sp;
1372                 struct stack_block *prevstackp;
1373                 size_t grosslen;
1374
1375                 INT_OFF;
1376                 oldstackp = g_stackp;
1377                 sp = g_stackp;
1378                 prevstackp = sp->prev;
1379                 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1380                 sp = ckrealloc(sp, grosslen);
1381                 sp->prev = prevstackp;
1382                 g_stackp = sp;
1383                 g_stacknxt = sp->space;
1384                 g_stacknleft = newlen;
1385                 sstrend = sp->space + newlen;
1386
1387                 /*
1388                  * Stack marks pointing to the start of the old block
1389                  * must be relocated to point to the new block
1390                  */
1391                 xmark = markp;
1392                 while (xmark != NULL && xmark->stackp == oldstackp) {
1393                         xmark->stackp = g_stackp;
1394                         xmark->stacknxt = g_stacknxt;
1395                         xmark->stacknleft = g_stacknleft;
1396                         xmark = xmark->marknext;
1397                 }
1398                 INT_ON;
1399         } else {
1400                 char *oldspace = g_stacknxt;
1401                 size_t oldlen = g_stacknleft;
1402                 char *p = stalloc(newlen);
1403
1404                 /* free the space we just allocated */
1405                 g_stacknxt = memcpy(p, oldspace, oldlen);
1406                 g_stacknleft += newlen;
1407         }
1408 }
1409
1410 static void
1411 grabstackblock(size_t len)
1412 {
1413         len = SHELL_ALIGN(len);
1414         g_stacknxt += len;
1415         g_stacknleft -= len;
1416 }
1417
1418 /*
1419  * The following routines are somewhat easier to use than the above.
1420  * The user declares a variable of type STACKSTR, which may be declared
1421  * to be a register.  The macro STARTSTACKSTR initializes things.  Then
1422  * the user uses the macro STPUTC to add characters to the string.  In
1423  * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1424  * grown as necessary.  When the user is done, she can just leave the
1425  * string there and refer to it using stackblock().  Or she can allocate
1426  * the space for it using grabstackstr().  If it is necessary to allow
1427  * someone else to use the stack temporarily and then continue to grow
1428  * the string, the user should use grabstack to allocate the space, and
1429  * then call ungrabstr(p) to return to the previous mode of operation.
1430  *
1431  * USTPUTC is like STPUTC except that it doesn't check for overflow.
1432  * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1433  * is space for at least one character.
1434  */
1435 static void *
1436 growstackstr(void)
1437 {
1438         size_t len = stackblocksize();
1439         if (herefd >= 0 && len >= 1024) {
1440                 full_write(herefd, stackblock(), len);
1441                 return stackblock();
1442         }
1443         growstackblock();
1444         return (char *)stackblock() + len;
1445 }
1446
1447 /*
1448  * Called from CHECKSTRSPACE.
1449  */
1450 static char *
1451 makestrspace(size_t newlen, char *p)
1452 {
1453         size_t len = p - g_stacknxt;
1454         size_t size = stackblocksize();
1455
1456         for (;;) {
1457                 size_t nleft;
1458
1459                 size = stackblocksize();
1460                 nleft = size - len;
1461                 if (nleft >= newlen)
1462                         break;
1463                 growstackblock();
1464         }
1465         return (char *)stackblock() + len;
1466 }
1467
1468 static char *
1469 stack_nputstr(const char *s, size_t n, char *p)
1470 {
1471         p = makestrspace(n, p);
1472         p = (char *)memcpy(p, s, n) + n;
1473         return p;
1474 }
1475
1476 static char *
1477 stack_putstr(const char *s, char *p)
1478 {
1479         return stack_nputstr(s, strlen(s), p);
1480 }
1481
1482 static char *
1483 _STPUTC(int c, char *p)
1484 {
1485         if (p == sstrend)
1486                 p = growstackstr();
1487         *p++ = c;
1488         return p;
1489 }
1490
1491 #define STARTSTACKSTR(p)        ((p) = stackblock())
1492 #define STPUTC(c, p)            ((p) = _STPUTC((c), (p)))
1493 #define CHECKSTRSPACE(n, p) do { \
1494         char *q = (p); \
1495         size_t l = (n); \
1496         size_t m = sstrend - q; \
1497         if (l > m) \
1498                 (p) = makestrspace(l, q); \
1499 } while (0)
1500 #define USTPUTC(c, p)           (*(p)++ = (c))
1501 #define STACKSTRNUL(p) do { \
1502         if ((p) == sstrend) \
1503                 (p) = growstackstr(); \
1504         *(p) = '\0'; \
1505 } while (0)
1506 #define STUNPUTC(p)             (--(p))
1507 #define STTOPC(p)               ((p)[-1])
1508 #define STADJUST(amount, p)     ((p) += (amount))
1509
1510 #define grabstackstr(p)         stalloc((char *)(p) - (char *)stackblock())
1511 #define ungrabstackstr(s, p)    stunalloc(s)
1512 #define stackstrend()           ((void *)sstrend)
1513
1514
1515 /* ============ String helpers */
1516
1517 /*
1518  * prefix -- see if pfx is a prefix of string.
1519  */
1520 static char *
1521 prefix(const char *string, const char *pfx)
1522 {
1523         while (*pfx) {
1524                 if (*pfx++ != *string++)
1525                         return NULL;
1526         }
1527         return (char *) string;
1528 }
1529
1530 /*
1531  * Check for a valid number.  This should be elsewhere.
1532  */
1533 static int
1534 is_number(const char *p)
1535 {
1536         do {
1537                 if (!isdigit(*p))
1538                         return 0;
1539         } while (*++p != '\0');
1540         return 1;
1541 }
1542
1543 /*
1544  * Convert a string of digits to an integer, printing an error message on
1545  * failure.
1546  */
1547 static int
1548 number(const char *s)
1549 {
1550         if (!is_number(s))
1551                 ash_msg_and_raise_error(msg_illnum, s);
1552         return atoi(s);
1553 }
1554
1555 /*
1556  * Produce a possibly single quoted string suitable as input to the shell.
1557  * The return string is allocated on the stack.
1558  */
1559 static char *
1560 single_quote(const char *s)
1561 {
1562         char *p;
1563
1564         STARTSTACKSTR(p);
1565
1566         do {
1567                 char *q;
1568                 size_t len;
1569
1570                 len = strchrnul(s, '\'') - s;
1571
1572                 q = p = makestrspace(len + 3, p);
1573
1574                 *q++ = '\'';
1575                 q = (char *)memcpy(q, s, len) + len;
1576                 *q++ = '\'';
1577                 s += len;
1578
1579                 STADJUST(q - p, p);
1580
1581                 len = strspn(s, "'");
1582                 if (!len)
1583                         break;
1584
1585                 q = p = makestrspace(len + 3, p);
1586
1587                 *q++ = '"';
1588                 q = (char *)memcpy(q, s, len) + len;
1589                 *q++ = '"';
1590                 s += len;
1591
1592                 STADJUST(q - p, p);
1593         } while (*s);
1594
1595         USTPUTC(0, p);
1596
1597         return stackblock();
1598 }
1599
1600
1601 /* ============ nextopt */
1602
1603 static char **argptr;                  /* argument list for builtin commands */
1604 static char *optionarg;                /* set by nextopt (like getopt) */
1605 static char *optptr;                   /* used by nextopt */
1606
1607 /*
1608  * XXX - should get rid of. Have all builtins use getopt(3).
1609  * The library getopt must have the BSD extension static variable
1610  * "optreset", otherwise it can't be used within the shell safely.
1611  *
1612  * Standard option processing (a la getopt) for builtin routines.
1613  * The only argument that is passed to nextopt is the option string;
1614  * the other arguments are unnecessary. It returns the character,
1615  * or '\0' on end of input.
1616  */
1617 static int
1618 nextopt(const char *optstring)
1619 {
1620         char *p;
1621         const char *q;
1622         char c;
1623
1624         p = optptr;
1625         if (p == NULL || *p == '\0') {
1626                 /* We ate entire "-param", take next one */
1627                 p = *argptr;
1628                 if (p == NULL)
1629                         return '\0';
1630                 if (*p != '-')
1631                         return '\0';
1632                 if (*++p == '\0') /* just "-" ? */
1633                         return '\0';
1634                 argptr++;
1635                 if (LONE_DASH(p)) /* "--" ? */
1636                         return '\0';
1637                 /* p => next "-param" */
1638         }
1639         /* p => some option char in the middle of a "-param" */
1640         c = *p++;
1641         for (q = optstring; *q != c;) {
1642                 if (*q == '\0')
1643                         ash_msg_and_raise_error("illegal option -%c", c);
1644                 if (*++q == ':')
1645                         q++;
1646         }
1647         if (*++q == ':') {
1648                 if (*p == '\0') {
1649                         p = *argptr++;
1650                         if (p == NULL)
1651                                 ash_msg_and_raise_error("no arg for -%c option", c);
1652                 }
1653                 optionarg = p;
1654                 p = NULL;
1655         }
1656         optptr = p;
1657         return c;
1658 }
1659
1660
1661 /* ============ Shell variables */
1662
1663 /*
1664  * The parsefile structure pointed to by the global variable parsefile
1665  * contains information about the current file being read.
1666  */
1667 struct shparam {
1668         int nparam;             /* # of positional parameters (without $0) */
1669 #if ENABLE_ASH_GETOPTS
1670         int optind;             /* next parameter to be processed by getopts */
1671         int optoff;             /* used by getopts */
1672 #endif
1673         unsigned char malloced; /* if parameter list dynamically allocated */
1674         char **p;               /* parameter list */
1675 };
1676
1677 /*
1678  * Free the list of positional parameters.
1679  */
1680 static void
1681 freeparam(volatile struct shparam *param)
1682 {
1683         if (param->malloced) {
1684                 char **ap, **ap1;
1685                 ap = ap1 = param->p;
1686                 while (*ap)
1687                         free(*ap++);
1688                 free(ap1);
1689         }
1690 }
1691
1692 #if ENABLE_ASH_GETOPTS
1693 static void FAST_FUNC getoptsreset(const char *value);
1694 #endif
1695
1696 struct var {
1697         struct var *next;               /* next entry in hash list */
1698         int flags;                      /* flags are defined above */
1699         const char *text;               /* name=value */
1700         void (*func)(const char *) FAST_FUNC; /* function to be called when  */
1701                                         /* the variable gets set/unset */
1702 };
1703
1704 struct localvar {
1705         struct localvar *next;          /* next local variable in list */
1706         struct var *vp;                 /* the variable that was made local */
1707         int flags;                      /* saved flags */
1708         const char *text;               /* saved text */
1709 };
1710
1711 /* flags */
1712 #define VEXPORT         0x01    /* variable is exported */
1713 #define VREADONLY       0x02    /* variable cannot be modified */
1714 #define VSTRFIXED       0x04    /* variable struct is statically allocated */
1715 #define VTEXTFIXED      0x08    /* text is statically allocated */
1716 #define VSTACK          0x10    /* text is allocated on the stack */
1717 #define VUNSET          0x20    /* the variable is not set */
1718 #define VNOFUNC         0x40    /* don't call the callback function */
1719 #define VNOSET          0x80    /* do not set variable - just readonly test */
1720 #define VNOSAVE         0x100   /* when text is on the heap before setvareq */
1721 #if ENABLE_ASH_RANDOM_SUPPORT
1722 # define VDYNAMIC       0x200   /* dynamic variable */
1723 #else
1724 # define VDYNAMIC       0
1725 #endif
1726
1727 #ifdef IFS_BROKEN
1728 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1729 #define defifs (defifsvar + 4)
1730 #else
1731 static const char defifs[] ALIGN1 = " \t\n";
1732 #endif
1733
1734
1735 /* Need to be before varinit_data[] */
1736 #if ENABLE_LOCALE_SUPPORT
1737 static void FAST_FUNC
1738 change_lc_all(const char *value)
1739 {
1740         if (value && *value != '\0')
1741                 setlocale(LC_ALL, value);
1742 }
1743 static void FAST_FUNC
1744 change_lc_ctype(const char *value)
1745 {
1746         if (value && *value != '\0')
1747                 setlocale(LC_CTYPE, value);
1748 }
1749 #endif
1750 #if ENABLE_ASH_MAIL
1751 static void chkmail(void);
1752 static void changemail(const char *) FAST_FUNC;
1753 #endif
1754 static void changepath(const char *) FAST_FUNC;
1755 #if ENABLE_ASH_RANDOM_SUPPORT
1756 static void change_random(const char *) FAST_FUNC;
1757 #endif
1758
1759 static const struct {
1760         int flags;
1761         const char *text;
1762         void (*func)(const char *) FAST_FUNC;
1763 } varinit_data[] = {
1764 #ifdef IFS_BROKEN
1765         { VSTRFIXED|VTEXTFIXED       , defifsvar   , NULL            },
1766 #else
1767         { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0"     , NULL            },
1768 #endif
1769 #if ENABLE_ASH_MAIL
1770         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0"    , changemail      },
1771         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail      },
1772 #endif
1773         { VSTRFIXED|VTEXTFIXED       , bb_PATH_root_path, changepath },
1774         { VSTRFIXED|VTEXTFIXED       , "PS1=$ "    , NULL            },
1775         { VSTRFIXED|VTEXTFIXED       , "PS2=> "    , NULL            },
1776         { VSTRFIXED|VTEXTFIXED       , "PS4=+ "    , NULL            },
1777 #if ENABLE_ASH_GETOPTS
1778         { VSTRFIXED|VTEXTFIXED       , "OPTIND=1"  , getoptsreset    },
1779 #endif
1780 #if ENABLE_ASH_RANDOM_SUPPORT
1781         { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1782 #endif
1783 #if ENABLE_LOCALE_SUPPORT
1784         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0"  , change_lc_all   },
1785         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1786 #endif
1787 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1788         { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL            },
1789 #endif
1790 };
1791
1792 struct redirtab;
1793
1794 struct globals_var {
1795         struct shparam shellparam;      /* $@ current positional parameters */
1796         struct redirtab *redirlist;
1797         int g_nullredirs;
1798         int preverrout_fd;   /* save fd2 before print debug if xflag is set. */
1799         struct var *vartab[VTABSIZE];
1800         struct var varinit[ARRAY_SIZE(varinit_data)];
1801 };
1802 extern struct globals_var *const ash_ptr_to_globals_var;
1803 #define G_var (*ash_ptr_to_globals_var)
1804 #define shellparam    (G_var.shellparam   )
1805 //#define redirlist     (G_var.redirlist    )
1806 #define g_nullredirs  (G_var.g_nullredirs )
1807 #define preverrout_fd (G_var.preverrout_fd)
1808 #define vartab        (G_var.vartab       )
1809 #define varinit       (G_var.varinit      )
1810 #define INIT_G_var() do { \
1811         unsigned i; \
1812         (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1813         barrier(); \
1814         for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1815                 varinit[i].flags = varinit_data[i].flags; \
1816                 varinit[i].text  = varinit_data[i].text; \
1817                 varinit[i].func  = varinit_data[i].func; \
1818         } \
1819 } while (0)
1820
1821 #define vifs      varinit[0]
1822 #if ENABLE_ASH_MAIL
1823 # define vmail    (&vifs)[1]
1824 # define vmpath   (&vmail)[1]
1825 # define vpath    (&vmpath)[1]
1826 #else
1827 # define vpath    (&vifs)[1]
1828 #endif
1829 #define vps1      (&vpath)[1]
1830 #define vps2      (&vps1)[1]
1831 #define vps4      (&vps2)[1]
1832 #if ENABLE_ASH_GETOPTS
1833 # define voptind  (&vps4)[1]
1834 # if ENABLE_ASH_RANDOM_SUPPORT
1835 #  define vrandom (&voptind)[1]
1836 # endif
1837 #else
1838 # if ENABLE_ASH_RANDOM_SUPPORT
1839 #  define vrandom (&vps4)[1]
1840 # endif
1841 #endif
1842
1843 /*
1844  * The following macros access the values of the above variables.
1845  * They have to skip over the name.  They return the null string
1846  * for unset variables.
1847  */
1848 #define ifsval()        (vifs.text + 4)
1849 #define ifsset()        ((vifs.flags & VUNSET) == 0)
1850 #if ENABLE_ASH_MAIL
1851 # define mailval()      (vmail.text + 5)
1852 # define mpathval()     (vmpath.text + 9)
1853 # define mpathset()     ((vmpath.flags & VUNSET) == 0)
1854 #endif
1855 #define pathval()       (vpath.text + 5)
1856 #define ps1val()        (vps1.text + 4)
1857 #define ps2val()        (vps2.text + 4)
1858 #define ps4val()        (vps4.text + 4)
1859 #if ENABLE_ASH_GETOPTS
1860 # define optindval()    (voptind.text + 7)
1861 #endif
1862
1863
1864 #define is_name(c)      ((c) == '_' || isalpha((unsigned char)(c)))
1865 #define is_in_name(c)   ((c) == '_' || isalnum((unsigned char)(c)))
1866
1867 #if ENABLE_ASH_GETOPTS
1868 static void FAST_FUNC
1869 getoptsreset(const char *value)
1870 {
1871         shellparam.optind = number(value);
1872         shellparam.optoff = -1;
1873 }
1874 #endif
1875
1876 /*
1877  * Return of a legal variable name (a letter or underscore followed by zero or
1878  * more letters, underscores, and digits).
1879  */
1880 static char *
1881 endofname(const char *name)
1882 {
1883         char *p;
1884
1885         p = (char *) name;
1886         if (!is_name(*p))
1887                 return p;
1888         while (*++p) {
1889                 if (!is_in_name(*p))
1890                         break;
1891         }
1892         return p;
1893 }
1894
1895 /*
1896  * Compares two strings up to the first = or '\0'.  The first
1897  * string must be terminated by '='; the second may be terminated by
1898  * either '=' or '\0'.
1899  */
1900 static int
1901 varcmp(const char *p, const char *q)
1902 {
1903         int c, d;
1904
1905         while ((c = *p) == (d = *q)) {
1906                 if (!c || c == '=')
1907                         goto out;
1908                 p++;
1909                 q++;
1910         }
1911         if (c == '=')
1912                 c = '\0';
1913         if (d == '=')
1914                 d = '\0';
1915  out:
1916         return c - d;
1917 }
1918
1919 static int
1920 varequal(const char *a, const char *b)
1921 {
1922         return !varcmp(a, b);
1923 }
1924
1925 /*
1926  * Find the appropriate entry in the hash table from the name.
1927  */
1928 static struct var **
1929 hashvar(const char *p)
1930 {
1931         unsigned hashval;
1932
1933         hashval = ((unsigned char) *p) << 4;
1934         while (*p && *p != '=')
1935                 hashval += (unsigned char) *p++;
1936         return &vartab[hashval % VTABSIZE];
1937 }
1938
1939 static int
1940 vpcmp(const void *a, const void *b)
1941 {
1942         return varcmp(*(const char **)a, *(const char **)b);
1943 }
1944
1945 /*
1946  * This routine initializes the builtin variables.
1947  */
1948 static void
1949 initvar(void)
1950 {
1951         struct var *vp;
1952         struct var *end;
1953         struct var **vpp;
1954
1955         /*
1956          * PS1 depends on uid
1957          */
1958 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1959         vps1.text = "PS1=\\w \\$ ";
1960 #else
1961         if (!geteuid())
1962                 vps1.text = "PS1=# ";
1963 #endif
1964         vp = varinit;
1965         end = vp + ARRAY_SIZE(varinit);
1966         do {
1967                 vpp = hashvar(vp->text);
1968                 vp->next = *vpp;
1969                 *vpp = vp;
1970         } while (++vp < end);
1971 }
1972
1973 static struct var **
1974 findvar(struct var **vpp, const char *name)
1975 {
1976         for (; *vpp; vpp = &(*vpp)->next) {
1977                 if (varequal((*vpp)->text, name)) {
1978                         break;
1979                 }
1980         }
1981         return vpp;
1982 }
1983
1984 /*
1985  * Find the value of a variable.  Returns NULL if not set.
1986  */
1987 static const char *
1988 lookupvar(const char *name)
1989 {
1990         struct var *v;
1991
1992         v = *findvar(hashvar(name), name);
1993         if (v) {
1994 #if ENABLE_ASH_RANDOM_SUPPORT
1995         /*
1996          * Dynamic variables are implemented roughly the same way they are
1997          * in bash. Namely, they're "special" so long as they aren't unset.
1998          * As soon as they're unset, they're no longer dynamic, and dynamic
1999          * lookup will no longer happen at that point. -- PFM.
2000          */
2001                 if ((v->flags & VDYNAMIC))
2002                         (*v->func)(NULL);
2003 #endif
2004                 if (!(v->flags & VUNSET))
2005                         return strchrnul(v->text, '=') + 1;
2006         }
2007         return NULL;
2008 }
2009
2010 /*
2011  * Search the environment of a builtin command.
2012  */
2013 static const char *
2014 bltinlookup(const char *name)
2015 {
2016         struct strlist *sp;
2017
2018         for (sp = cmdenviron; sp; sp = sp->next) {
2019                 if (varequal(sp->text, name))
2020                         return strchrnul(sp->text, '=') + 1;
2021         }
2022         return lookupvar(name);
2023 }
2024
2025 /*
2026  * Same as setvar except that the variable and value are passed in
2027  * the first argument as name=value.  Since the first argument will
2028  * be actually stored in the table, it should not be a string that
2029  * will go away.
2030  * Called with interrupts off.
2031  */
2032 static void
2033 setvareq(char *s, int flags)
2034 {
2035         struct var *vp, **vpp;
2036
2037         vpp = hashvar(s);
2038         flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2039         vp = *findvar(vpp, s);
2040         if (vp) {
2041                 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2042                         const char *n;
2043
2044                         if (flags & VNOSAVE)
2045                                 free(s);
2046                         n = vp->text;
2047                         ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2048                 }
2049
2050                 if (flags & VNOSET)
2051                         return;
2052
2053                 if (vp->func && (flags & VNOFUNC) == 0)
2054                         (*vp->func)(strchrnul(s, '=') + 1);
2055
2056                 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2057                         free((char*)vp->text);
2058
2059                 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2060         } else {
2061                 if (flags & VNOSET)
2062                         return;
2063                 /* not found */
2064                 vp = ckzalloc(sizeof(*vp));
2065                 vp->next = *vpp;
2066                 /*vp->func = NULL; - ckzalloc did it */
2067                 *vpp = vp;
2068         }
2069         if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2070                 s = ckstrdup(s);
2071         vp->text = s;
2072         vp->flags = flags;
2073 }
2074
2075 /*
2076  * Set the value of a variable.  The flags argument is ored with the
2077  * flags of the variable.  If val is NULL, the variable is unset.
2078  */
2079 static void
2080 setvar(const char *name, const char *val, int flags)
2081 {
2082         char *p, *q;
2083         size_t namelen;
2084         char *nameeq;
2085         size_t vallen;
2086
2087         q = endofname(name);
2088         p = strchrnul(q, '=');
2089         namelen = p - name;
2090         if (!namelen || p != q)
2091                 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2092         vallen = 0;
2093         if (val == NULL) {
2094                 flags |= VUNSET;
2095         } else {
2096                 vallen = strlen(val);
2097         }
2098         INT_OFF;
2099         nameeq = ckmalloc(namelen + vallen + 2);
2100         p = (char *)memcpy(nameeq, name, namelen) + namelen;
2101         if (val) {
2102                 *p++ = '=';
2103                 p = (char *)memcpy(p, val, vallen) + vallen;
2104         }
2105         *p = '\0';
2106         setvareq(nameeq, flags | VNOSAVE);
2107         INT_ON;
2108 }
2109
2110 #if ENABLE_ASH_GETOPTS
2111 /*
2112  * Safe version of setvar, returns 1 on success 0 on failure.
2113  */
2114 static int
2115 setvarsafe(const char *name, const char *val, int flags)
2116 {
2117         int err;
2118         volatile int saveint;
2119         struct jmploc *volatile savehandler = exception_handler;
2120         struct jmploc jmploc;
2121
2122         SAVE_INT(saveint);
2123         if (setjmp(jmploc.loc))
2124                 err = 1;
2125         else {
2126                 exception_handler = &jmploc;
2127                 setvar(name, val, flags);
2128                 err = 0;
2129         }
2130         exception_handler = savehandler;
2131         RESTORE_INT(saveint);
2132         return err;
2133 }
2134 #endif
2135
2136 /*
2137  * Unset the specified variable.
2138  */
2139 static int
2140 unsetvar(const char *s)
2141 {
2142         struct var **vpp;
2143         struct var *vp;
2144         int retval;
2145
2146         vpp = findvar(hashvar(s), s);
2147         vp = *vpp;
2148         retval = 2;
2149         if (vp) {
2150                 int flags = vp->flags;
2151
2152                 retval = 1;
2153                 if (flags & VREADONLY)
2154                         goto out;
2155 #if ENABLE_ASH_RANDOM_SUPPORT
2156                 vp->flags &= ~VDYNAMIC;
2157 #endif
2158                 if (flags & VUNSET)
2159                         goto ok;
2160                 if ((flags & VSTRFIXED) == 0) {
2161                         INT_OFF;
2162                         if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2163                                 free((char*)vp->text);
2164                         *vpp = vp->next;
2165                         free(vp);
2166                         INT_ON;
2167                 } else {
2168                         setvar(s, 0, 0);
2169                         vp->flags &= ~VEXPORT;
2170                 }
2171  ok:
2172                 retval = 0;
2173         }
2174  out:
2175         return retval;
2176 }
2177
2178 /*
2179  * Process a linked list of variable assignments.
2180  */
2181 static void
2182 listsetvar(struct strlist *list_set_var, int flags)
2183 {
2184         struct strlist *lp = list_set_var;
2185
2186         if (!lp)
2187                 return;
2188         INT_OFF;
2189         do {
2190                 setvareq(lp->text, flags);
2191                 lp = lp->next;
2192         } while (lp);
2193         INT_ON;
2194 }
2195
2196 /*
2197  * Generate a list of variables satisfying the given conditions.
2198  */
2199 static char **
2200 listvars(int on, int off, char ***end)
2201 {
2202         struct var **vpp;
2203         struct var *vp;
2204         char **ep;
2205         int mask;
2206
2207         STARTSTACKSTR(ep);
2208         vpp = vartab;
2209         mask = on | off;
2210         do {
2211                 for (vp = *vpp; vp; vp = vp->next) {
2212                         if ((vp->flags & mask) == on) {
2213                                 if (ep == stackstrend())
2214                                         ep = growstackstr();
2215                                 *ep++ = (char *) vp->text;
2216                         }
2217                 }
2218         } while (++vpp < vartab + VTABSIZE);
2219         if (ep == stackstrend())
2220                 ep = growstackstr();
2221         if (end)
2222                 *end = ep;
2223         *ep++ = NULL;
2224         return grabstackstr(ep);
2225 }
2226
2227
2228 /* ============ Path search helper
2229  *
2230  * The variable path (passed by reference) should be set to the start
2231  * of the path before the first call; path_advance will update
2232  * this value as it proceeds.  Successive calls to path_advance will return
2233  * the possible path expansions in sequence.  If an option (indicated by
2234  * a percent sign) appears in the path entry then the global variable
2235  * pathopt will be set to point to it; otherwise pathopt will be set to
2236  * NULL.
2237  */
2238 static const char *pathopt;     /* set by path_advance */
2239
2240 static char *
2241 path_advance(const char **path, const char *name)
2242 {
2243         const char *p;
2244         char *q;
2245         const char *start;
2246         size_t len;
2247
2248         if (*path == NULL)
2249                 return NULL;
2250         start = *path;
2251         for (p = start; *p && *p != ':' && *p != '%'; p++)
2252                 continue;
2253         len = p - start + strlen(name) + 2;     /* "2" is for '/' and '\0' */
2254         while (stackblocksize() < len)
2255                 growstackblock();
2256         q = stackblock();
2257         if (p != start) {
2258                 memcpy(q, start, p - start);
2259                 q += p - start;
2260                 *q++ = '/';
2261         }
2262         strcpy(q, name);
2263         pathopt = NULL;
2264         if (*p == '%') {
2265                 pathopt = ++p;
2266                 while (*p && *p != ':')
2267                         p++;
2268         }
2269         if (*p == ':')
2270                 *path = p + 1;
2271         else
2272                 *path = NULL;
2273         return stalloc(len);
2274 }
2275
2276
2277 /* ============ Prompt */
2278
2279 static smallint doprompt;                   /* if set, prompt the user */
2280 static smallint needprompt;                 /* true if interactive and at start of line */
2281
2282 #if ENABLE_FEATURE_EDITING
2283 static line_input_t *line_input_state;
2284 static const char *cmdedit_prompt;
2285 static void
2286 putprompt(const char *s)
2287 {
2288         if (ENABLE_ASH_EXPAND_PRMT) {
2289                 free((char*)cmdedit_prompt);
2290                 cmdedit_prompt = ckstrdup(s);
2291                 return;
2292         }
2293         cmdedit_prompt = s;
2294 }
2295 #else
2296 static void
2297 putprompt(const char *s)
2298 {
2299         out2str(s);
2300 }
2301 #endif
2302
2303 #if ENABLE_ASH_EXPAND_PRMT
2304 /* expandstr() needs parsing machinery, so it is far away ahead... */
2305 static const char *expandstr(const char *ps);
2306 #else
2307 #define expandstr(s) s
2308 #endif
2309
2310 static void
2311 setprompt(int whichprompt)
2312 {
2313         const char *prompt;
2314 #if ENABLE_ASH_EXPAND_PRMT
2315         struct stackmark smark;
2316 #endif
2317
2318         needprompt = 0;
2319
2320         switch (whichprompt) {
2321         case 1:
2322                 prompt = ps1val();
2323                 break;
2324         case 2:
2325                 prompt = ps2val();
2326                 break;
2327         default:                        /* 0 */
2328                 prompt = nullstr;
2329         }
2330 #if ENABLE_ASH_EXPAND_PRMT
2331         setstackmark(&smark);
2332         stalloc(stackblocksize());
2333 #endif
2334         putprompt(expandstr(prompt));
2335 #if ENABLE_ASH_EXPAND_PRMT
2336         popstackmark(&smark);
2337 #endif
2338 }
2339
2340
2341 /* ============ The cd and pwd commands */
2342
2343 #define CD_PHYSICAL 1
2344 #define CD_PRINT 2
2345
2346 static int
2347 cdopt(void)
2348 {
2349         int flags = 0;
2350         int i, j;
2351
2352         j = 'L';
2353         while ((i = nextopt("LP")) != '\0') {
2354                 if (i != j) {
2355                         flags ^= CD_PHYSICAL;
2356                         j = i;
2357                 }
2358         }
2359
2360         return flags;
2361 }
2362
2363 /*
2364  * Update curdir (the name of the current directory) in response to a
2365  * cd command.
2366  */
2367 static const char *
2368 updatepwd(const char *dir)
2369 {
2370         char *new;
2371         char *p;
2372         char *cdcomppath;
2373         const char *lim;
2374
2375         cdcomppath = ststrdup(dir);
2376         STARTSTACKSTR(new);
2377         if (*dir != '/') {
2378                 if (curdir == nullstr)
2379                         return 0;
2380                 new = stack_putstr(curdir, new);
2381         }
2382         new = makestrspace(strlen(dir) + 2, new);
2383         lim = (char *)stackblock() + 1;
2384         if (*dir != '/') {
2385                 if (new[-1] != '/')
2386                         USTPUTC('/', new);
2387                 if (new > lim && *lim == '/')
2388                         lim++;
2389         } else {
2390                 USTPUTC('/', new);
2391                 cdcomppath++;
2392                 if (dir[1] == '/' && dir[2] != '/') {
2393                         USTPUTC('/', new);
2394                         cdcomppath++;
2395                         lim++;
2396                 }
2397         }
2398         p = strtok(cdcomppath, "/");
2399         while (p) {
2400                 switch (*p) {
2401                 case '.':
2402                         if (p[1] == '.' && p[2] == '\0') {
2403                                 while (new > lim) {
2404                                         STUNPUTC(new);
2405                                         if (new[-1] == '/')
2406                                                 break;
2407                                 }
2408                                 break;
2409                         }
2410                         if (p[1] == '\0')
2411                                 break;
2412                         /* fall through */
2413                 default:
2414                         new = stack_putstr(p, new);
2415                         USTPUTC('/', new);
2416                 }
2417                 p = strtok(0, "/");
2418         }
2419         if (new > lim)
2420                 STUNPUTC(new);
2421         *new = 0;
2422         return stackblock();
2423 }
2424
2425 /*
2426  * Find out what the current directory is. If we already know the current
2427  * directory, this routine returns immediately.
2428  */
2429 static char *
2430 getpwd(void)
2431 {
2432         char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2433         return dir ? dir : nullstr;
2434 }
2435
2436 static void
2437 setpwd(const char *val, int setold)
2438 {
2439         char *oldcur, *dir;
2440
2441         oldcur = dir = curdir;
2442
2443         if (setold) {
2444                 setvar("OLDPWD", oldcur, VEXPORT);
2445         }
2446         INT_OFF;
2447         if (physdir != nullstr) {
2448                 if (physdir != oldcur)
2449                         free(physdir);
2450                 physdir = nullstr;
2451         }
2452         if (oldcur == val || !val) {
2453                 char *s = getpwd();
2454                 physdir = s;
2455                 if (!val)
2456                         dir = s;
2457         } else
2458                 dir = ckstrdup(val);
2459         if (oldcur != dir && oldcur != nullstr) {
2460                 free(oldcur);
2461         }
2462         curdir = dir;
2463         INT_ON;
2464         setvar("PWD", dir, VEXPORT);
2465 }
2466
2467 static void hashcd(void);
2468
2469 /*
2470  * Actually do the chdir.  We also call hashcd to let the routines in exec.c
2471  * know that the current directory has changed.
2472  */
2473 static int
2474 docd(const char *dest, int flags)
2475 {
2476         const char *dir = 0;
2477         int err;
2478
2479         TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2480
2481         INT_OFF;
2482         if (!(flags & CD_PHYSICAL)) {
2483                 dir = updatepwd(dest);
2484                 if (dir)
2485                         dest = dir;
2486         }
2487         err = chdir(dest);
2488         if (err)
2489                 goto out;
2490         setpwd(dir, 1);
2491         hashcd();
2492  out:
2493         INT_ON;
2494         return err;
2495 }
2496
2497 static int FAST_FUNC
2498 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2499 {
2500         const char *dest;
2501         const char *path;
2502         const char *p;
2503         char c;
2504         struct stat statb;
2505         int flags;
2506
2507         flags = cdopt();
2508         dest = *argptr;
2509         if (!dest)
2510                 dest = bltinlookup(homestr);
2511         else if (LONE_DASH(dest)) {
2512                 dest = bltinlookup("OLDPWD");
2513                 flags |= CD_PRINT;
2514         }
2515         if (!dest)
2516                 dest = nullstr;
2517         if (*dest == '/')
2518                 goto step7;
2519         if (*dest == '.') {
2520                 c = dest[1];
2521  dotdot:
2522                 switch (c) {
2523                 case '\0':
2524                 case '/':
2525                         goto step6;
2526                 case '.':
2527                         c = dest[2];
2528                         if (c != '.')
2529                                 goto dotdot;
2530                 }
2531         }
2532         if (!*dest)
2533                 dest = ".";
2534         path = bltinlookup("CDPATH");
2535         if (!path) {
2536  step6:
2537  step7:
2538                 p = dest;
2539                 goto docd;
2540         }
2541         do {
2542                 c = *path;
2543                 p = path_advance(&path, dest);
2544                 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2545                         if (c && c != ':')
2546                                 flags |= CD_PRINT;
2547  docd:
2548                         if (!docd(p, flags))
2549                                 goto out;
2550                         break;
2551                 }
2552         } while (path);
2553         ash_msg_and_raise_error("can't cd to %s", dest);
2554         /* NOTREACHED */
2555  out:
2556         if (flags & CD_PRINT)
2557                 out1fmt(snlfmt, curdir);
2558         return 0;
2559 }
2560
2561 static int FAST_FUNC
2562 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2563 {
2564         int flags;
2565         const char *dir = curdir;
2566
2567         flags = cdopt();
2568         if (flags) {
2569                 if (physdir == nullstr)
2570                         setpwd(dir, 0);
2571                 dir = physdir;
2572         }
2573         out1fmt(snlfmt, dir);
2574         return 0;
2575 }
2576
2577
2578 /* ============ ... */
2579
2580
2581 #define IBUFSIZ COMMON_BUFSIZE
2582 /* buffer for top level input file */
2583 #define basebuf bb_common_bufsiz1
2584
2585 /* Syntax classes */
2586 #define CWORD     0             /* character is nothing special */
2587 #define CNL       1             /* newline character */
2588 #define CBACK     2             /* a backslash character */
2589 #define CSQUOTE   3             /* single quote */
2590 #define CDQUOTE   4             /* double quote */
2591 #define CENDQUOTE 5             /* a terminating quote */
2592 #define CBQUOTE   6             /* backwards single quote */
2593 #define CVAR      7             /* a dollar sign */
2594 #define CENDVAR   8             /* a '}' character */
2595 #define CLP       9             /* a left paren in arithmetic */
2596 #define CRP      10             /* a right paren in arithmetic */
2597 #define CENDFILE 11             /* end of file */
2598 #define CCTL     12             /* like CWORD, except it must be escaped */
2599 #define CSPCL    13             /* these terminate a word */
2600 #define CIGN     14             /* character should be ignored */
2601
2602 #if ENABLE_ASH_ALIAS
2603 #define SYNBASE       130
2604 #define PEOF         -130
2605 #define PEOA         -129
2606 #define PEOA_OR_PEOF PEOA
2607 #else
2608 #define SYNBASE       129
2609 #define PEOF         -129
2610 #define PEOA_OR_PEOF PEOF
2611 #endif
2612
2613 /* number syntax index */
2614 #define BASESYNTAX 0    /* not in quotes */
2615 #define DQSYNTAX   1    /* in double quotes */
2616 #define SQSYNTAX   2    /* in single quotes */
2617 #define ARISYNTAX  3    /* in arithmetic */
2618 #define PSSYNTAX   4    /* prompt */
2619
2620 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2621 #define USE_SIT_FUNCTION
2622 #endif
2623
2624 #if ENABLE_SH_MATH_SUPPORT
2625 static const char S_I_T[][4] = {
2626 #if ENABLE_ASH_ALIAS
2627         { CSPCL, CIGN, CIGN, CIGN },            /* 0, PEOA */
2628 #endif
2629         { CSPCL, CWORD, CWORD, CWORD },         /* 1, ' ' */
2630         { CNL, CNL, CNL, CNL },                 /* 2, \n */
2631         { CWORD, CCTL, CCTL, CWORD },           /* 3, !*-/:=?[]~ */
2632         { CDQUOTE, CENDQUOTE, CWORD, CWORD },   /* 4, '"' */
2633         { CVAR, CVAR, CWORD, CVAR },            /* 5, $ */
2634         { CSQUOTE, CWORD, CENDQUOTE, CWORD },   /* 6, "'" */
2635         { CSPCL, CWORD, CWORD, CLP },           /* 7, ( */
2636         { CSPCL, CWORD, CWORD, CRP },           /* 8, ) */
2637         { CBACK, CBACK, CCTL, CBACK },          /* 9, \ */
2638         { CBQUOTE, CBQUOTE, CWORD, CBQUOTE },   /* 10, ` */
2639         { CENDVAR, CENDVAR, CWORD, CENDVAR },   /* 11, } */
2640 #ifndef USE_SIT_FUNCTION
2641         { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2642         { CWORD, CWORD, CWORD, CWORD },         /* 13, 0-9A-Za-z */
2643         { CCTL, CCTL, CCTL, CCTL }              /* 14, CTLESC ... */
2644 #endif
2645 };
2646 #else
2647 static const char S_I_T[][3] = {
2648 #if ENABLE_ASH_ALIAS
2649         { CSPCL, CIGN, CIGN },                  /* 0, PEOA */
2650 #endif
2651         { CSPCL, CWORD, CWORD },                /* 1, ' ' */
2652         { CNL, CNL, CNL },                      /* 2, \n */
2653         { CWORD, CCTL, CCTL },                  /* 3, !*-/:=?[]~ */
2654         { CDQUOTE, CENDQUOTE, CWORD },          /* 4, '"' */
2655         { CVAR, CVAR, CWORD },                  /* 5, $ */
2656         { CSQUOTE, CWORD, CENDQUOTE },          /* 6, "'" */
2657         { CSPCL, CWORD, CWORD },                /* 7, ( */
2658         { CSPCL, CWORD, CWORD },                /* 8, ) */
2659         { CBACK, CBACK, CCTL },                 /* 9, \ */
2660         { CBQUOTE, CBQUOTE, CWORD },            /* 10, ` */
2661         { CENDVAR, CENDVAR, CWORD },            /* 11, } */
2662 #ifndef USE_SIT_FUNCTION
2663         { CENDFILE, CENDFILE, CENDFILE },       /* 12, PEOF */
2664         { CWORD, CWORD, CWORD },                /* 13, 0-9A-Za-z */
2665         { CCTL, CCTL, CCTL }                    /* 14, CTLESC ... */
2666 #endif
2667 };
2668 #endif /* SH_MATH_SUPPORT */
2669
2670 #ifdef USE_SIT_FUNCTION
2671
2672 static int
2673 SIT(int c, int syntax)
2674 {
2675         static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2676 #if ENABLE_ASH_ALIAS
2677         static const char syntax_index_table[] ALIGN1 = {
2678                 1, 2, 1, 3, 4, 5, 1, 6,         /* "\t\n !\"$&'" */
2679                 7, 8, 3, 3, 3, 3, 1, 1,         /* "()*-/:;<" */
2680                 3, 1, 3, 3, 9, 3, 10, 1,        /* "=>?[\\]`|" */
2681                 11, 3                           /* "}~" */
2682         };
2683 #else
2684         static const char syntax_index_table[] ALIGN1 = {
2685                 0, 1, 0, 2, 3, 4, 0, 5,         /* "\t\n !\"$&'" */
2686                 6, 7, 2, 2, 2, 2, 0, 0,         /* "()*-/:;<" */
2687                 2, 0, 2, 2, 8, 2, 9, 0,         /* "=>?[\\]`|" */
2688                 10, 2                           /* "}~" */
2689         };
2690 #endif
2691         const char *s;
2692         int indx;
2693
2694         if (c == PEOF) {         /* 2^8+2 */
2695                 return CENDFILE;
2696         }
2697 #if ENABLE_ASH_ALIAS
2698         if (c == PEOA) {         /* 2^8+1 */
2699                 indx = 0;
2700         } else
2701 #endif
2702         {
2703                 if ((unsigned char)c >= CTLESC
2704                  && (unsigned char)c <= CTLQUOTEMARK
2705                 ) {
2706                         return CCTL;
2707                 }
2708                 s = strchrnul(spec_symbls, c);
2709                 if (*s == '\0') {
2710                         return CWORD;
2711                 }
2712                 indx = syntax_index_table[s - spec_symbls];
2713         }
2714         return S_I_T[indx][syntax];
2715 }
2716
2717 #else   /* !USE_SIT_FUNCTION */
2718
2719 #if ENABLE_ASH_ALIAS
2720 #define CSPCL_CIGN_CIGN_CIGN                     0
2721 #define CSPCL_CWORD_CWORD_CWORD                  1
2722 #define CNL_CNL_CNL_CNL                          2
2723 #define CWORD_CCTL_CCTL_CWORD                    3
2724 #define CDQUOTE_CENDQUOTE_CWORD_CWORD            4
2725 #define CVAR_CVAR_CWORD_CVAR                     5
2726 #define CSQUOTE_CWORD_CENDQUOTE_CWORD            6
2727 #define CSPCL_CWORD_CWORD_CLP                    7
2728 #define CSPCL_CWORD_CWORD_CRP                    8
2729 #define CBACK_CBACK_CCTL_CBACK                   9
2730 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE           10
2731 #define CENDVAR_CENDVAR_CWORD_CENDVAR           11
2732 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE     12
2733 #define CWORD_CWORD_CWORD_CWORD                 13
2734 #define CCTL_CCTL_CCTL_CCTL                     14
2735 #else
2736 #define CSPCL_CWORD_CWORD_CWORD                  0
2737 #define CNL_CNL_CNL_CNL                          1
2738 #define CWORD_CCTL_CCTL_CWORD                    2
2739 #define CDQUOTE_CENDQUOTE_CWORD_CWORD            3
2740 #define CVAR_CVAR_CWORD_CVAR                     4
2741 #define CSQUOTE_CWORD_CENDQUOTE_CWORD            5
2742 #define CSPCL_CWORD_CWORD_CLP                    6
2743 #define CSPCL_CWORD_CWORD_CRP                    7
2744 #define CBACK_CBACK_CCTL_CBACK                   8
2745 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE            9
2746 #define CENDVAR_CENDVAR_CWORD_CENDVAR           10
2747 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE     11
2748 #define CWORD_CWORD_CWORD_CWORD                 12
2749 #define CCTL_CCTL_CCTL_CCTL                     13
2750 #endif
2751
2752 static const char syntax_index_table[258] = {
2753         /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2754         /*   0  PEOF */      CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2755 #if ENABLE_ASH_ALIAS
2756         /*   1  PEOA */      CSPCL_CIGN_CIGN_CIGN,
2757 #endif
2758         /*   2  -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2759         /*   3  -127 CTLESC       */ CCTL_CCTL_CCTL_CCTL,
2760         /*   4  -126 CTLVAR       */ CCTL_CCTL_CCTL_CCTL,
2761         /*   5  -125 CTLENDVAR    */ CCTL_CCTL_CCTL_CCTL,
2762         /*   6  -124 CTLBACKQ     */ CCTL_CCTL_CCTL_CCTL,
2763         /*   7  -123 CTLQUOTE     */ CCTL_CCTL_CCTL_CCTL,
2764         /*   8  -122 CTLARI       */ CCTL_CCTL_CCTL_CCTL,
2765         /*   9  -121 CTLENDARI    */ CCTL_CCTL_CCTL_CCTL,
2766         /*  10  -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2767         /*  11  -119      */ CWORD_CWORD_CWORD_CWORD,
2768         /*  12  -118      */ CWORD_CWORD_CWORD_CWORD,
2769         /*  13  -117      */ CWORD_CWORD_CWORD_CWORD,
2770         /*  14  -116      */ CWORD_CWORD_CWORD_CWORD,
2771         /*  15  -115      */ CWORD_CWORD_CWORD_CWORD,
2772         /*  16  -114      */ CWORD_CWORD_CWORD_CWORD,
2773         /*  17  -113      */ CWORD_CWORD_CWORD_CWORD,
2774         /*  18  -112      */ CWORD_CWORD_CWORD_CWORD,
2775         /*  19  -111      */ CWORD_CWORD_CWORD_CWORD,
2776         /*  20  -110      */ CWORD_CWORD_CWORD_CWORD,
2777         /*  21  -109      */ CWORD_CWORD_CWORD_CWORD,
2778         /*  22  -108      */ CWORD_CWORD_CWORD_CWORD,
2779         /*  23  -107      */ CWORD_CWORD_CWORD_CWORD,
2780         /*  24  -106      */ CWORD_CWORD_CWORD_CWORD,
2781         /*  25  -105      */ CWORD_CWORD_CWORD_CWORD,
2782         /*  26  -104      */ CWORD_CWORD_CWORD_CWORD,
2783         /*  27  -103      */ CWORD_CWORD_CWORD_CWORD,
2784         /*  28  -102      */ CWORD_CWORD_CWORD_CWORD,
2785         /*  29  -101      */ CWORD_CWORD_CWORD_CWORD,
2786         /*  30  -100      */ CWORD_CWORD_CWORD_CWORD,
2787         /*  31   -99      */ CWORD_CWORD_CWORD_CWORD,
2788         /*  32   -98      */ CWORD_CWORD_CWORD_CWORD,
2789         /*  33   -97      */ CWORD_CWORD_CWORD_CWORD,
2790         /*  34   -96      */ CWORD_CWORD_CWORD_CWORD,
2791         /*  35   -95      */ CWORD_CWORD_CWORD_CWORD,
2792         /*  36   -94      */ CWORD_CWORD_CWORD_CWORD,
2793         /*  37   -93      */ CWORD_CWORD_CWORD_CWORD,
2794         /*  38   -92      */ CWORD_CWORD_CWORD_CWORD,
2795         /*  39   -91      */ CWORD_CWORD_CWORD_CWORD,
2796         /*  40   -90      */ CWORD_CWORD_CWORD_CWORD,
2797         /*  41   -89      */ CWORD_CWORD_CWORD_CWORD,
2798         /*  42   -88      */ CWORD_CWORD_CWORD_CWORD,
2799         /*  43   -87      */ CWORD_CWORD_CWORD_CWORD,
2800         /*  44   -86      */ CWORD_CWORD_CWORD_CWORD,
2801         /*  45   -85      */ CWORD_CWORD_CWORD_CWORD,
2802         /*  46   -84      */ CWORD_CWORD_CWORD_CWORD,
2803         /*  47   -83      */ CWORD_CWORD_CWORD_CWORD,
2804         /*  48   -82      */ CWORD_CWORD_CWORD_CWORD,
2805         /*  49   -81      */ CWORD_CWORD_CWORD_CWORD,
2806         /*  50   -80      */ CWORD_CWORD_CWORD_CWORD,
2807         /*  51   -79      */ CWORD_CWORD_CWORD_CWORD,
2808         /*  52   -78      */ CWORD_CWORD_CWORD_CWORD,
2809         /*  53   -77      */ CWORD_CWORD_CWORD_CWORD,
2810         /*  54   -76      */ CWORD_CWORD_CWORD_CWORD,
2811         /*  55   -75      */ CWORD_CWORD_CWORD_CWORD,
2812         /*  56   -74      */ CWORD_CWORD_CWORD_CWORD,
2813         /*  57   -73      */ CWORD_CWORD_CWORD_CWORD,
2814         /*  58   -72      */ CWORD_CWORD_CWORD_CWORD,
2815         /*  59   -71      */ CWORD_CWORD_CWORD_CWORD,
2816         /*  60   -70      */ CWORD_CWORD_CWORD_CWORD,
2817         /*  61   -69      */ CWORD_CWORD_CWORD_CWORD,
2818         /*  62   -68      */ CWORD_CWORD_CWORD_CWORD,
2819         /*  63   -67      */ CWORD_CWORD_CWORD_CWORD,
2820         /*  64   -66      */ CWORD_CWORD_CWORD_CWORD,
2821         /*  65   -65      */ CWORD_CWORD_CWORD_CWORD,
2822         /*  66   -64      */ CWORD_CWORD_CWORD_CWORD,
2823         /*  67   -63      */ CWORD_CWORD_CWORD_CWORD,
2824         /*  68   -62      */ CWORD_CWORD_CWORD_CWORD,
2825         /*  69   -61      */ CWORD_CWORD_CWORD_CWORD,
2826         /*  70   -60      */ CWORD_CWORD_CWORD_CWORD,
2827         /*  71   -59      */ CWORD_CWORD_CWORD_CWORD,
2828         /*  72   -58      */ CWORD_CWORD_CWORD_CWORD,
2829         /*  73   -57      */ CWORD_CWORD_CWORD_CWORD,
2830         /*  74   -56      */ CWORD_CWORD_CWORD_CWORD,
2831         /*  75   -55      */ CWORD_CWORD_CWORD_CWORD,
2832         /*  76   -54      */ CWORD_CWORD_CWORD_CWORD,
2833         /*  77   -53      */ CWORD_CWORD_CWORD_CWORD,
2834         /*  78   -52      */ CWORD_CWORD_CWORD_CWORD,
2835         /*  79   -51      */ CWORD_CWORD_CWORD_CWORD,
2836         /*  80   -50      */ CWORD_CWORD_CWORD_CWORD,
2837         /*  81   -49      */ CWORD_CWORD_CWORD_CWORD,
2838         /*  82   -48      */ CWORD_CWORD_CWORD_CWORD,
2839         /*  83   -47      */ CWORD_CWORD_CWORD_CWORD,
2840         /*  84   -46      */ CWORD_CWORD_CWORD_CWORD,
2841         /*  85   -45      */ CWORD_CWORD_CWORD_CWORD,
2842         /*  86   -44      */ CWORD_CWORD_CWORD_CWORD,
2843         /*  87   -43      */ CWORD_CWORD_CWORD_CWORD,
2844         /*  88   -42      */ CWORD_CWORD_CWORD_CWORD,
2845         /*  89   -41      */ CWORD_CWORD_CWORD_CWORD,
2846         /*  90   -40      */ CWORD_CWORD_CWORD_CWORD,
2847         /*  91   -39      */ CWORD_CWORD_CWORD_CWORD,
2848         /*  92   -38      */ CWORD_CWORD_CWORD_CWORD,
2849         /*  93   -37      */ CWORD_CWORD_CWORD_CWORD,
2850         /*  94   -36      */ CWORD_CWORD_CWORD_CWORD,
2851         /*  95   -35      */ CWORD_CWORD_CWORD_CWORD,
2852         /*  96   -34      */ CWORD_CWORD_CWORD_CWORD,
2853         /*  97   -33      */ CWORD_CWORD_CWORD_CWORD,
2854         /*  98   -32      */ CWORD_CWORD_CWORD_CWORD,
2855         /*  99   -31      */ CWORD_CWORD_CWORD_CWORD,
2856         /* 100   -30      */ CWORD_CWORD_CWORD_CWORD,
2857         /* 101   -29      */ CWORD_CWORD_CWORD_CWORD,
2858         /* 102   -28      */ CWORD_CWORD_CWORD_CWORD,
2859         /* 103   -27      */ CWORD_CWORD_CWORD_CWORD,
2860         /* 104   -26      */ CWORD_CWORD_CWORD_CWORD,
2861         /* 105   -25      */ CWORD_CWORD_CWORD_CWORD,
2862         /* 106   -24      */ CWORD_CWORD_CWORD_CWORD,
2863         /* 107   -23      */ CWORD_CWORD_CWORD_CWORD,
2864         /* 108   -22      */ CWORD_CWORD_CWORD_CWORD,
2865         /* 109   -21      */ CWORD_CWORD_CWORD_CWORD,
2866         /* 110   -20      */ CWORD_CWORD_CWORD_CWORD,
2867         /* 111   -19      */ CWORD_CWORD_CWORD_CWORD,
2868         /* 112   -18      */ CWORD_CWORD_CWORD_CWORD,
2869         /* 113   -17      */ CWORD_CWORD_CWORD_CWORD,
2870         /* 114   -16      */ CWORD_CWORD_CWORD_CWORD,
2871         /* 115   -15      */ CWORD_CWORD_CWORD_CWORD,
2872         /* 116   -14      */ CWORD_CWORD_CWORD_CWORD,
2873         /* 117   -13      */ CWORD_CWORD_CWORD_CWORD,
2874         /* 118   -12      */ CWORD_CWORD_CWORD_CWORD,
2875         /* 119   -11      */ CWORD_CWORD_CWORD_CWORD,
2876         /* 120   -10      */ CWORD_CWORD_CWORD_CWORD,
2877         /* 121    -9      */ CWORD_CWORD_CWORD_CWORD,
2878         /* 122    -8      */ CWORD_CWORD_CWORD_CWORD,
2879         /* 123    -7      */ CWORD_CWORD_CWORD_CWORD,
2880         /* 124    -6      */ CWORD_CWORD_CWORD_CWORD,
2881         /* 125    -5      */ CWORD_CWORD_CWORD_CWORD,
2882         /* 126    -4      */ CWORD_CWORD_CWORD_CWORD,
2883         /* 127    -3      */ CWORD_CWORD_CWORD_CWORD,
2884         /* 128    -2      */ CWORD_CWORD_CWORD_CWORD,
2885         /* 129    -1      */ CWORD_CWORD_CWORD_CWORD,
2886         /* 130     0      */ CWORD_CWORD_CWORD_CWORD,
2887         /* 131     1      */ CWORD_CWORD_CWORD_CWORD,
2888         /* 132     2      */ CWORD_CWORD_CWORD_CWORD,
2889         /* 133     3      */ CWORD_CWORD_CWORD_CWORD,
2890         /* 134     4      */ CWORD_CWORD_CWORD_CWORD,
2891         /* 135     5      */ CWORD_CWORD_CWORD_CWORD,
2892         /* 136     6      */ CWORD_CWORD_CWORD_CWORD,
2893         /* 137     7      */ CWORD_CWORD_CWORD_CWORD,
2894         /* 138     8      */ CWORD_CWORD_CWORD_CWORD,
2895         /* 139     9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2896         /* 140    10 "\n" */ CNL_CNL_CNL_CNL,
2897         /* 141    11      */ CWORD_CWORD_CWORD_CWORD,
2898         /* 142    12      */ CWORD_CWORD_CWORD_CWORD,
2899         /* 143    13      */ CWORD_CWORD_CWORD_CWORD,
2900         /* 144    14      */ CWORD_CWORD_CWORD_CWORD,
2901         /* 145    15      */ CWORD_CWORD_CWORD_CWORD,
2902         /* 146    16      */ CWORD_CWORD_CWORD_CWORD,
2903         /* 147    17      */ CWORD_CWORD_CWORD_CWORD,
2904         /* 148    18      */ CWORD_CWORD_CWORD_CWORD,
2905         /* 149    19      */ CWORD_CWORD_CWORD_CWORD,
2906         /* 150    20      */ CWORD_CWORD_CWORD_CWORD,
2907         /* 151    21      */ CWORD_CWORD_CWORD_CWORD,
2908         /* 152    22      */ CWORD_CWORD_CWORD_CWORD,
2909         /* 153    23      */ CWORD_CWORD_CWORD_CWORD,
2910         /* 154    24      */ CWORD_CWORD_CWORD_CWORD,
2911         /* 155    25      */ CWORD_CWORD_CWORD_CWORD,
2912         /* 156    26      */ CWORD_CWORD_CWORD_CWORD,
2913         /* 157    27      */ CWORD_CWORD_CWORD_CWORD,
2914         /* 158    28      */ CWORD_CWORD_CWORD_CWORD,
2915         /* 159    29      */ CWORD_CWORD_CWORD_CWORD,
2916         /* 160    30      */ CWORD_CWORD_CWORD_CWORD,
2917         /* 161    31      */ CWORD_CWORD_CWORD_CWORD,
2918         /* 162    32  " " */ CSPCL_CWORD_CWORD_CWORD,
2919         /* 163    33  "!" */ CWORD_CCTL_CCTL_CWORD,
2920         /* 164    34  """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2921         /* 165    35  "#" */ CWORD_CWORD_CWORD_CWORD,
2922         /* 166    36  "$" */ CVAR_CVAR_CWORD_CVAR,
2923         /* 167    37  "%" */ CWORD_CWORD_CWORD_CWORD,
2924         /* 168    38  "&" */ CSPCL_CWORD_CWORD_CWORD,
2925         /* 169    39  "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2926         /* 170    40  "(" */ CSPCL_CWORD_CWORD_CLP,
2927         /* 171    41  ")" */ CSPCL_CWORD_CWORD_CRP,
2928         /* 172    42  "*" */ CWORD_CCTL_CCTL_CWORD,
2929         /* 173    43  "+" */ CWORD_CWORD_CWORD_CWORD,
2930         /* 174    44  "," */ CWORD_CWORD_CWORD_CWORD,
2931         /* 175    45  "-" */ CWORD_CCTL_CCTL_CWORD,
2932         /* 176    46  "." */ CWORD_CWORD_CWORD_CWORD,
2933         /* 177    47  "/" */ CWORD_CCTL_CCTL_CWORD,
2934         /* 178    48  "0" */ CWORD_CWORD_CWORD_CWORD,
2935         /* 179    49  "1" */ CWORD_CWORD_CWORD_CWORD,
2936         /* 180    50  "2" */ CWORD_CWORD_CWORD_CWORD,
2937         /* 181    51  "3" */ CWORD_CWORD_CWORD_CWORD,
2938         /* 182    52  "4" */ CWORD_CWORD_CWORD_CWORD,
2939         /* 183    53  "5" */ CWORD_CWORD_CWORD_CWORD,
2940         /* 184    54  "6" */ CWORD_CWORD_CWORD_CWORD,
2941         /* 185    55  "7" */ CWORD_CWORD_CWORD_CWORD,
2942         /* 186    56  "8" */ CWORD_CWORD_CWORD_CWORD,
2943         /* 187    57  "9" */ CWORD_CWORD_CWORD_CWORD,
2944         /* 188    58  ":" */ CWORD_CCTL_CCTL_CWORD,
2945         /* 189    59  ";" */ CSPCL_CWORD_CWORD_CWORD,
2946         /* 190    60  "<" */ CSPCL_CWORD_CWORD_CWORD,
2947         /* 191    61  "=" */ CWORD_CCTL_CCTL_CWORD,
2948         /* 192    62  ">" */ CSPCL_CWORD_CWORD_CWORD,
2949         /* 193    63  "?" */ CWORD_CCTL_CCTL_CWORD,
2950         /* 194    64  "@" */ CWORD_CWORD_CWORD_CWORD,
2951         /* 195    65  "A" */ CWORD_CWORD_CWORD_CWORD,
2952         /* 196    66  "B" */ CWORD_CWORD_CWORD_CWORD,
2953         /* 197    67  "C" */ CWORD_CWORD_CWORD_CWORD,
2954         /* 198    68  "D" */ CWORD_CWORD_CWORD_CWORD,
2955         /* 199    69  "E" */ CWORD_CWORD_CWORD_CWORD,
2956         /* 200    70  "F" */ CWORD_CWORD_CWORD_CWORD,
2957         /* 201    71  "G" */ CWORD_CWORD_CWORD_CWORD,
2958         /* 202    72  "H" */ CWORD_CWORD_CWORD_CWORD,
2959         /* 203    73  "I" */ CWORD_CWORD_CWORD_CWORD,
2960         /* 204    74  "J" */ CWORD_CWORD_CWORD_CWORD,
2961         /* 205    75  "K" */ CWORD_CWORD_CWORD_CWORD,
2962         /* 206    76  "L" */ CWORD_CWORD_CWORD_CWORD,
2963         /* 207    77  "M" */ CWORD_CWORD_CWORD_CWORD,
2964         /* 208    78  "N" */ CWORD_CWORD_CWORD_CWORD,
2965         /* 209    79  "O" */ CWORD_CWORD_CWORD_CWORD,
2966         /* 210    80  "P" */ CWORD_CWORD_CWORD_CWORD,
2967         /* 211    81  "Q" */ CWORD_CWORD_CWORD_CWORD,
2968         /* 212    82  "R" */ CWORD_CWORD_CWORD_CWORD,
2969         /* 213    83  "S" */ CWORD_CWORD_CWORD_CWORD,
2970         /* 214    84  "T" */ CWORD_CWORD_CWORD_CWORD,
2971         /* 215    85  "U" */ CWORD_CWORD_CWORD_CWORD,
2972         /* 216    86  "V" */ CWORD_CWORD_CWORD_CWORD,
2973         /* 217    87  "W" */ CWORD_CWORD_CWORD_CWORD,
2974         /* 218    88  "X" */ CWORD_CWORD_CWORD_CWORD,
2975         /* 219    89  "Y" */ CWORD_CWORD_CWORD_CWORD,
2976         /* 220    90  "Z" */ CWORD_CWORD_CWORD_CWORD,
2977         /* 221    91  "[" */ CWORD_CCTL_CCTL_CWORD,
2978         /* 222    92  "\" */ CBACK_CBACK_CCTL_CBACK,
2979         /* 223    93  "]" */ CWORD_CCTL_CCTL_CWORD,
2980         /* 224    94  "^" */ CWORD_CWORD_CWORD_CWORD,
2981         /* 225    95  "_" */ CWORD_CWORD_CWORD_CWORD,
2982         /* 226    96  "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2983         /* 227    97  "a" */ CWORD_CWORD_CWORD_CWORD,
2984         /* 228    98  "b" */ CWORD_CWORD_CWORD_CWORD,
2985         /* 229    99  "c" */ CWORD_CWORD_CWORD_CWORD,
2986         /* 230   100  "d" */ CWORD_CWORD_CWORD_CWORD,
2987         /* 231   101  "e" */ CWORD_CWORD_CWORD_CWORD,
2988         /* 232   102  "f" */ CWORD_CWORD_CWORD_CWORD,
2989         /* 233   103  "g" */ CWORD_CWORD_CWORD_CWORD,
2990         /* 234   104  "h" */ CWORD_CWORD_CWORD_CWORD,
2991         /* 235   105  "i" */ CWORD_CWORD_CWORD_CWORD,
2992         /* 236   106  "j" */ CWORD_CWORD_CWORD_CWORD,
2993         /* 237   107  "k" */ CWORD_CWORD_CWORD_CWORD,
2994         /* 238   108  "l" */ CWORD_CWORD_CWORD_CWORD,
2995         /* 239   109  "m" */ CWORD_CWORD_CWORD_CWORD,
2996         /* 240   110  "n" */ CWORD_CWORD_CWORD_CWORD,
2997         /* 241   111  "o" */ CWORD_CWORD_CWORD_CWORD,
2998         /* 242   112  "p" */ CWORD_CWORD_CWORD_CWORD,
2999         /* 243   113  "q" */ CWORD_CWORD_CWORD_CWORD,
3000         /* 244   114  "r" */ CWORD_CWORD_CWORD_CWORD,
3001         /* 245   115  "s" */ CWORD_CWORD_CWORD_CWORD,
3002         /* 246   116  "t" */ CWORD_CWORD_CWORD_CWORD,
3003         /* 247   117  "u" */ CWORD_CWORD_CWORD_CWORD,
3004         /* 248   118  "v" */ CWORD_CWORD_CWORD_CWORD,
3005         /* 249   119  "w" */ CWORD_CWORD_CWORD_CWORD,
3006         /* 250   120  "x" */ CWORD_CWORD_CWORD_CWORD,
3007         /* 251   121  "y" */ CWORD_CWORD_CWORD_CWORD,
3008         /* 252   122  "z" */ CWORD_CWORD_CWORD_CWORD,
3009         /* 253   123  "{" */ CWORD_CWORD_CWORD_CWORD,
3010         /* 254   124  "|" */ CSPCL_CWORD_CWORD_CWORD,
3011         /* 255   125  "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3012         /* 256   126  "~" */ CWORD_CCTL_CCTL_CWORD,
3013         /* 257   127      */ CWORD_CWORD_CWORD_CWORD,
3014 };
3015
3016 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3017
3018 #endif  /* USE_SIT_FUNCTION */
3019
3020
3021 /* ============ Alias handling */
3022
3023 #if ENABLE_ASH_ALIAS
3024
3025 #define ALIASINUSE 1
3026 #define ALIASDEAD  2
3027
3028 struct alias {
3029         struct alias *next;
3030         char *name;
3031         char *val;
3032         int flag;
3033 };
3034
3035
3036 static struct alias **atab; // [ATABSIZE];
3037 #define INIT_G_alias() do { \
3038         atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3039 } while (0)
3040
3041
3042 static struct alias **
3043 __lookupalias(const char *name) {
3044         unsigned int hashval;
3045         struct alias **app;
3046         const char *p;
3047         unsigned int ch;
3048
3049         p = name;
3050
3051         ch = (unsigned char)*p;
3052         hashval = ch << 4;
3053         while (ch) {
3054                 hashval += ch;
3055                 ch = (unsigned char)*++p;
3056         }
3057         app = &atab[hashval % ATABSIZE];
3058
3059         for (; *app; app = &(*app)->next) {
3060                 if (strcmp(name, (*app)->name) == 0) {
3061                         break;
3062                 }
3063         }
3064
3065         return app;
3066 }
3067
3068 static struct alias *
3069 lookupalias(const char *name, int check)
3070 {
3071         struct alias *ap = *__lookupalias(name);
3072
3073         if (check && ap && (ap->flag & ALIASINUSE))
3074                 return NULL;
3075         return ap;
3076 }
3077
3078 static struct alias *
3079 freealias(struct alias *ap)
3080 {
3081         struct alias *next;
3082
3083         if (ap->flag & ALIASINUSE) {
3084                 ap->flag |= ALIASDEAD;
3085                 return ap;
3086         }
3087
3088         next = ap->next;
3089         free(ap->name);
3090         free(ap->val);
3091         free(ap);
3092         return next;
3093 }
3094
3095 static void
3096 setalias(const char *name, const char *val)
3097 {
3098         struct alias *ap, **app;
3099
3100         app = __lookupalias(name);
3101         ap = *app;
3102         INT_OFF;
3103         if (ap) {
3104                 if (!(ap->flag & ALIASINUSE)) {
3105                         free(ap->val);
3106                 }
3107                 ap->val = ckstrdup(val);
3108                 ap->flag &= ~ALIASDEAD;
3109         } else {
3110                 /* not found */
3111                 ap = ckzalloc(sizeof(struct alias));
3112                 ap->name = ckstrdup(name);
3113                 ap->val = ckstrdup(val);
3114                 /*ap->flag = 0; - ckzalloc did it */
3115                 /*ap->next = NULL;*/
3116                 *app = ap;
3117         }
3118         INT_ON;
3119 }
3120
3121 static int
3122 unalias(const char *name)
3123 {
3124         struct alias **app;
3125
3126         app = __lookupalias(name);
3127
3128         if (*app) {
3129                 INT_OFF;
3130                 *app = freealias(*app);
3131                 INT_ON;
3132                 return 0;
3133         }
3134
3135         return 1;
3136 }
3137
3138 static void
3139 rmaliases(void)
3140 {
3141         struct alias *ap, **app;
3142         int i;
3143
3144         INT_OFF;
3145         for (i = 0; i < ATABSIZE; i++) {
3146                 app = &atab[i];
3147                 for (ap = *app; ap; ap = *app) {
3148                         *app = freealias(*app);
3149                         if (ap == *app) {
3150                                 app = &ap->next;
3151                         }
3152                 }
3153         }
3154         INT_ON;
3155 }
3156
3157 static void
3158 printalias(const struct alias *ap)
3159 {
3160         out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3161 }
3162
3163 /*
3164  * TODO - sort output
3165  */
3166 static int FAST_FUNC
3167 aliascmd(int argc UNUSED_PARAM, char **argv)
3168 {
3169         char *n, *v;
3170         int ret = 0;
3171         struct alias *ap;
3172
3173         if (!argv[1]) {
3174                 int i;
3175
3176                 for (i = 0; i < ATABSIZE; i++) {
3177                         for (ap = atab[i]; ap; ap = ap->next) {
3178                                 printalias(ap);
3179                         }
3180                 }
3181                 return 0;
3182         }
3183         while ((n = *++argv) != NULL) {
3184                 v = strchr(n+1, '=');
3185                 if (v == NULL) { /* n+1: funny ksh stuff */
3186                         ap = *__lookupalias(n);
3187                         if (ap == NULL) {
3188                                 fprintf(stderr, "%s: %s not found\n", "alias", n);
3189                                 ret = 1;
3190                         } else
3191                                 printalias(ap);
3192                 } else {
3193                         *v++ = '\0';
3194                         setalias(n, v);
3195                 }
3196         }
3197
3198         return ret;
3199 }
3200
3201 static int FAST_FUNC
3202 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3203 {
3204         int i;
3205
3206         while ((i = nextopt("a")) != '\0') {
3207                 if (i == 'a') {
3208                         rmaliases();
3209                         return 0;
3210                 }
3211         }
3212         for (i = 0; *argptr; argptr++) {
3213                 if (unalias(*argptr)) {
3214                         fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3215                         i = 1;
3216                 }
3217         }
3218
3219         return i;
3220 }
3221
3222 #endif /* ASH_ALIAS */
3223
3224
3225 /* ============ jobs.c */
3226
3227 /* Mode argument to forkshell.  Don't change FORK_FG or FORK_BG. */
3228 #define FORK_FG 0
3229 #define FORK_BG 1
3230 #define FORK_NOJOB 2
3231
3232 /* mode flags for showjob(s) */
3233 #define SHOW_ONLY_PGID  0x01    /* show only pgid (jobs -p) */
3234 #define SHOW_PIDS       0x02    /* show individual pids, not just one line per job */
3235 #define SHOW_CHANGED    0x04    /* only jobs whose state has changed */
3236
3237 /*
3238  * A job structure contains information about a job.  A job is either a
3239  * single process or a set of processes contained in a pipeline.  In the
3240  * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3241  * array of pids.
3242  */
3243 struct procstat {
3244         pid_t   pid;            /* process id */
3245         int     status;         /* last process status from wait() */
3246         char    *cmd;           /* text of command being run */
3247 };
3248
3249 struct job {
3250         struct procstat ps0;    /* status of process */
3251         struct procstat *ps;    /* status or processes when more than one */
3252 #if JOBS
3253         int stopstatus;         /* status of a stopped job */
3254 #endif
3255         uint32_t
3256                 nprocs: 16,     /* number of processes */
3257                 state: 8,
3258 #define JOBRUNNING      0       /* at least one proc running */
3259 #define JOBSTOPPED      1       /* all procs are stopped */
3260 #define JOBDONE         2       /* all procs are completed */
3261 #if JOBS
3262                 sigint: 1,      /* job was killed by SIGINT */
3263                 jobctl: 1,      /* job running under job control */
3264 #endif
3265                 waited: 1,      /* true if this entry has been waited for */
3266                 used: 1,        /* true if this entry is in used */
3267                 changed: 1;     /* true if status has changed */
3268         struct job *prev_job;   /* previous job */
3269 };
3270
3271 static struct job *makejob(/*union node *,*/ int);
3272 #if !JOBS
3273 #define forkshell(job, node, mode) forkshell(job, mode)
3274 #endif
3275 static int forkshell(struct job *, union node *, int);
3276 static int waitforjob(struct job *);
3277
3278 #if !JOBS
3279 enum { doing_jobctl = 0 };
3280 #define setjobctl(on) do {} while (0)
3281 #else
3282 static smallint doing_jobctl; //references:8
3283 static void setjobctl(int);
3284 #endif
3285
3286 /*
3287  * Ignore a signal.
3288  */
3289 static void
3290 ignoresig(int signo)
3291 {
3292         /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293         if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294                 /* No, need to do it */
3295                 signal(signo, SIG_IGN);
3296         }
3297         sigmode[signo - 1] = S_HARD_IGN;
3298 }
3299
3300 /*
3301  * Signal handler. Only one usage site - in setsignal()
3302  */
3303 static void
3304 onsig(int signo)
3305 {
3306         gotsig[signo - 1] = 1;
3307
3308         if (signo == SIGINT && !trap[SIGINT]) {
3309                 if (!suppress_int) {
3310                         pending_sig = 0;
3311                         raise_interrupt(); /* does not return */
3312                 }
3313                 pending_int = 1;
3314         } else {
3315                 pending_sig = signo;
3316         }
3317 }
3318
3319 /*
3320  * Set the signal handler for the specified signal.  The routine figures
3321  * out what it should be set to.
3322  */
3323 static void
3324 setsignal(int signo)
3325 {
3326         char *t;
3327         char cur_act, new_act;
3328         struct sigaction act;
3329
3330         t = trap[signo];
3331         new_act = S_DFL;
3332         if (t != NULL) { /* trap for this sig is set */
3333                 new_act = S_CATCH;
3334                 if (t[0] == '\0') /* trap is "": ignore this sig */
3335                         new_act = S_IGN;
3336         }
3337
3338         if (rootshell && new_act == S_DFL) {
3339                 switch (signo) {
3340                 case SIGINT:
3341                         if (iflag || minusc || sflag == 0)
3342                                 new_act = S_CATCH;
3343                         break;
3344                 case SIGQUIT:
3345 #if DEBUG
3346                         if (debug)
3347                                 break;
3348 #endif
3349                         /* man bash:
3350                          * "In all cases, bash ignores SIGQUIT. Non-builtin
3351                          * commands run by bash have signal handlers
3352                          * set to the values inherited by the shell
3353                          * from its parent". */
3354                         new_act = S_IGN;
3355                         break;
3356                 case SIGTERM:
3357                         if (iflag)
3358                                 new_act = S_IGN;
3359                         break;
3360 #if JOBS
3361                 case SIGTSTP:
3362                 case SIGTTOU:
3363                         if (mflag)
3364                                 new_act = S_IGN;
3365                         break;
3366 #endif
3367                 }
3368         }
3369 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3370 //whereas we have to restore it to what shell got on entry
3371 //from the parent. See comment above
3372
3373         t = &sigmode[signo - 1];
3374         cur_act = *t;
3375         if (cur_act == 0) {
3376                 /* current setting is not yet known */
3377                 if (sigaction(signo, NULL, &act)) {
3378                         /* pretend it worked; maybe we should give a warning,
3379                          * but other shells don't. We don't alter sigmode,
3380                          * so we retry every time.
3381                          * btw, in Linux it never fails. --vda */
3382                         return;
3383                 }
3384                 if (act.sa_handler == SIG_IGN) {
3385                         cur_act = S_HARD_IGN;
3386                         if (mflag
3387                          && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3388                         ) {
3389                                 cur_act = S_IGN;   /* don't hard ignore these */
3390                         }
3391                 }
3392         }
3393         if (cur_act == S_HARD_IGN || cur_act == new_act)
3394                 return;
3395
3396         act.sa_handler = SIG_DFL;
3397         switch (new_act) {
3398         case S_CATCH:
3399                 act.sa_handler = onsig;
3400                 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401                 sigfillset(&act.sa_mask); /* ditto */
3402                 break;
3403         case S_IGN:
3404                 act.sa_handler = SIG_IGN;
3405                 break;
3406         }
3407         sigaction_set(signo, &act);
3408
3409         *t = new_act;
3410 }
3411
3412 /* mode flags for set_curjob */
3413 #define CUR_DELETE 2
3414 #define CUR_RUNNING 1
3415 #define CUR_STOPPED 0
3416
3417 /* mode flags for dowait */
3418 #define DOWAIT_NONBLOCK WNOHANG
3419 #define DOWAIT_BLOCK    0
3420
3421 #if JOBS
3422 /* pgrp of shell on invocation */
3423 static int initialpgrp; //references:2
3424 static int ttyfd = -1; //5
3425 #endif
3426 /* array of jobs */
3427 static struct job *jobtab; //5
3428 /* size of array */
3429 static unsigned njobs; //4
3430 /* current job */
3431 static struct job *curjob; //lots
3432 /* number of presumed living untracked jobs */
3433 static int jobless; //4
3434
3435 static void
3436 set_curjob(struct job *jp, unsigned mode)
3437 {
3438         struct job *jp1;
3439         struct job **jpp, **curp;
3440
3441         /* first remove from list */
3442         jpp = curp = &curjob;
3443         do {
3444                 jp1 = *jpp;
3445                 if (jp1 == jp)
3446                         break;
3447                 jpp = &jp1->prev_job;
3448         } while (1);
3449         *jpp = jp1->prev_job;
3450
3451         /* Then re-insert in correct position */
3452         jpp = curp;
3453         switch (mode) {
3454         default:
3455 #if DEBUG
3456                 abort();
3457 #endif
3458         case CUR_DELETE:
3459                 /* job being deleted */
3460                 break;
3461         case CUR_RUNNING:
3462                 /* newly created job or backgrounded job,
3463                    put after all stopped jobs. */
3464                 do {
3465                         jp1 = *jpp;
3466 #if JOBS
3467                         if (!jp1 || jp1->state != JOBSTOPPED)
3468 #endif
3469                                 break;
3470                         jpp = &jp1->prev_job;
3471                 } while (1);
3472                 /* FALLTHROUGH */
3473 #if JOBS
3474         case CUR_STOPPED:
3475 #endif
3476                 /* newly stopped job - becomes curjob */
3477                 jp->prev_job = *jpp;
3478                 *jpp = jp;
3479                 break;
3480         }
3481 }
3482
3483 #if JOBS || DEBUG
3484 static int
3485 jobno(const struct job *jp)
3486 {
3487         return jp - jobtab + 1;
3488 }
3489 #endif
3490
3491 /*
3492  * Convert a job name to a job structure.
3493  */
3494 #if !JOBS
3495 #define getjob(name, getctl) getjob(name)
3496 #endif
3497 static struct job *
3498 getjob(const char *name, int getctl)
3499 {
3500         struct job *jp;
3501         struct job *found;
3502         const char *err_msg = "%s: no such job";
3503         unsigned num;
3504         int c;
3505         const char *p;
3506         char *(*match)(const char *, const char *);
3507
3508         jp = curjob;
3509         p = name;
3510         if (!p)
3511                 goto currentjob;
3512
3513         if (*p != '%')
3514                 goto err;
3515
3516         c = *++p;
3517         if (!c)
3518                 goto currentjob;
3519
3520         if (!p[1]) {
3521                 if (c == '+' || c == '%') {
3522  currentjob:
3523                         err_msg = "No current job";
3524                         goto check;
3525                 }
3526                 if (c == '-') {
3527                         if (jp)
3528                                 jp = jp->prev_job;
3529                         err_msg = "No previous job";
3530  check:
3531                         if (!jp)
3532                                 goto err;
3533                         goto gotit;
3534                 }
3535         }
3536
3537         if (is_number(p)) {
3538                 num = atoi(p);
3539                 if (num < njobs) {
3540                         jp = jobtab + num - 1;
3541                         if (jp->used)
3542                                 goto gotit;
3543                         goto err;
3544                 }
3545         }
3546
3547         match = prefix;
3548         if (*p == '?') {
3549                 match = strstr;
3550                 p++;
3551         }
3552
3553         found = NULL;
3554         while (jp) {
3555                 if (match(jp->ps[0].cmd, p)) {
3556                         if (found)
3557                                 goto err;
3558                         found = jp;
3559                         err_msg = "%s: ambiguous";
3560                 }
3561                 jp = jp->prev_job;
3562         }
3563         if (!found)
3564                 goto err;
3565         jp = found;
3566
3567  gotit:
3568 #if JOBS
3569         err_msg = "job %s not created under job control";
3570         if (getctl && jp->jobctl == 0)
3571                 goto err;
3572 #endif
3573         return jp;
3574  err:
3575         ash_msg_and_raise_error(err_msg, name);
3576 }
3577
3578 /*
3579  * Mark a job structure as unused.
3580  */
3581 static void
3582 freejob(struct job *jp)
3583 {
3584         struct procstat *ps;
3585         int i;
3586
3587         INT_OFF;
3588         for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589                 if (ps->cmd != nullstr)
3590                         free(ps->cmd);
3591         }
3592         if (jp->ps != &jp->ps0)
3593                 free(jp->ps);
3594         jp->used = 0;
3595         set_curjob(jp, CUR_DELETE);
3596         INT_ON;
3597 }
3598
3599 #if JOBS
3600 static void
3601 xtcsetpgrp(int fd, pid_t pgrp)
3602 {
3603         if (tcsetpgrp(fd, pgrp))
3604                 ash_msg_and_raise_error("can't set tty process group (%m)");
3605 }
3606
3607 /*
3608  * Turn job control on and off.
3609  *
3610  * Note:  This code assumes that the third arg to ioctl is a character
3611  * pointer, which is true on Berkeley systems but not System V.  Since
3612  * System V doesn't have job control yet, this isn't a problem now.
3613  *
3614  * Called with interrupts off.
3615  */
3616 static void
3617 setjobctl(int on)
3618 {
3619         int fd;
3620         int pgrp;
3621
3622         if (on == doing_jobctl || rootshell == 0)
3623                 return;
3624         if (on) {
3625                 int ofd;
3626                 ofd = fd = open(_PATH_TTY, O_RDWR);
3627                 if (fd < 0) {
3628         /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629          * That sometimes helps to acquire controlling tty.
3630          * Obviously, a workaround for bugs when someone
3631          * failed to provide a controlling tty to bash! :) */
3632                         fd = 2;
3633                         while (!isatty(fd))
3634                                 if (--fd < 0)
3635                                         goto out;
3636                 }
3637                 fd = fcntl(fd, F_DUPFD, 10);
3638                 if (ofd >= 0)
3639                         close(ofd);
3640                 if (fd < 0)
3641                         goto out;
3642                 /* fd is a tty at this point */
3643                 close_on_exec_on(fd);
3644                 do { /* while we are in the background */
3645                         pgrp = tcgetpgrp(fd);
3646                         if (pgrp < 0) {
3647  out:
3648                                 ash_msg("can't access tty; job control turned off");
3649                                 mflag = on = 0;
3650                                 goto close;
3651                         }
3652                         if (pgrp == getpgrp())
3653                                 break;
3654                         killpg(0, SIGTTIN);
3655                 } while (1);
3656                 initialpgrp = pgrp;
3657
3658                 setsignal(SIGTSTP);
3659                 setsignal(SIGTTOU);
3660                 setsignal(SIGTTIN);
3661                 pgrp = rootpid;
3662                 setpgid(0, pgrp);
3663                 xtcsetpgrp(fd, pgrp);
3664         } else {
3665                 /* turning job control off */
3666                 fd = ttyfd;
3667                 pgrp = initialpgrp;
3668                 /* was xtcsetpgrp, but this can make exiting ash
3669                  * loop forever if pty is already deleted */
3670                 tcsetpgrp(fd, pgrp);
3671                 setpgid(0, pgrp);
3672                 setsignal(SIGTSTP);
3673                 setsignal(SIGTTOU);
3674                 setsignal(SIGTTIN);
3675  close:
3676                 if (fd >= 0)
3677                         close(fd);
3678                 fd = -1;
3679         }
3680         ttyfd = fd;
3681         doing_jobctl = on;
3682 }
3683
3684 static int FAST_FUNC
3685 killcmd(int argc, char **argv)
3686 {
3687         int i = 1;
3688         if (argv[1] && strcmp(argv[1], "-l") != 0) {
3689                 do {
3690                         if (argv[i][0] == '%') {
3691                                 struct job *jp = getjob(argv[i], 0);
3692                                 unsigned pid = jp->ps[0].pid;
3693                                 /* Enough space for ' -NNN<nul>' */
3694                                 argv[i] = alloca(sizeof(int)*3 + 3);
3695                                 /* kill_main has matching code to expect
3696                                  * leading space. Needed to not confuse
3697                                  * negative pids with "kill -SIGNAL_NO" syntax */
3698                                 sprintf(argv[i], " -%u", pid);
3699                         }
3700                 } while (argv[++i]);
3701         }
3702         return kill_main(argc, argv);
3703 }
3704
3705 static void
3706 showpipe(struct job *jp, FILE *out)
3707 {
3708         struct procstat *sp;
3709         struct procstat *spend;
3710
3711         spend = jp->ps + jp->nprocs;
3712         for (sp = jp->ps + 1; sp < spend; sp++)
3713                 fprintf(out, " | %s", sp->cmd);
3714         outcslow('\n', out);
3715         flush_stdout_stderr();
3716 }
3717
3718
3719 static int
3720 restartjob(struct job *jp, int mode)
3721 {
3722         struct procstat *ps;
3723         int i;
3724         int status;
3725         pid_t pgid;
3726
3727         INT_OFF;
3728         if (jp->state == JOBDONE)
3729                 goto out;
3730         jp->state = JOBRUNNING;
3731         pgid = jp->ps->pid;
3732         if (mode == FORK_FG)
3733                 xtcsetpgrp(ttyfd, pgid);
3734         killpg(pgid, SIGCONT);
3735         ps = jp->ps;
3736         i = jp->nprocs;
3737         do {
3738                 if (WIFSTOPPED(ps->status)) {
3739                         ps->status = -1;
3740                 }
3741                 ps++;
3742         } while (--i);
3743  out:
3744         status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3745         INT_ON;
3746         return status;
3747 }
3748
3749 static int FAST_FUNC
3750 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3751 {
3752         struct job *jp;
3753         FILE *out;
3754         int mode;
3755         int retval;
3756
3757         mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3758         nextopt(nullstr);
3759         argv = argptr;
3760         out = stdout;
3761         do {
3762                 jp = getjob(*argv, 1);
3763                 if (mode == FORK_BG) {
3764                         set_curjob(jp, CUR_RUNNING);
3765                         fprintf(out, "[%d] ", jobno(jp));
3766                 }
3767                 outstr(jp->ps->cmd, out);
3768                 showpipe(jp, out);
3769                 retval = restartjob(jp, mode);
3770         } while (*argv && *++argv);
3771         return retval;
3772 }
3773 #endif
3774
3775 static int
3776 sprint_status(char *s, int status, int sigonly)
3777 {
3778         int col;
3779         int st;
3780
3781         col = 0;
3782         if (!WIFEXITED(status)) {
3783 #if JOBS
3784                 if (WIFSTOPPED(status))
3785                         st = WSTOPSIG(status);
3786                 else
3787 #endif
3788                         st = WTERMSIG(status);
3789                 if (sigonly) {
3790                         if (st == SIGINT || st == SIGPIPE)
3791                                 goto out;
3792 #if JOBS
3793                         if (WIFSTOPPED(status))
3794                                 goto out;
3795 #endif
3796                 }
3797                 st &= 0x7f;
3798                 col = fmtstr(s, 32, strsignal(st));
3799                 if (WCOREDUMP(status)) {
3800                         col += fmtstr(s + col, 16, " (core dumped)");
3801                 }
3802         } else if (!sigonly) {
3803                 st = WEXITSTATUS(status);
3804                 if (st)
3805                         col = fmtstr(s, 16, "Done(%d)", st);
3806                 else
3807                         col = fmtstr(s, 16, "Done");
3808         }
3809  out:
3810         return col;
3811 }
3812
3813 static int
3814 dowait(int wait_flags, struct job *job)
3815 {
3816         int pid;
3817         int status;
3818         struct job *jp;
3819         struct job *thisjob;
3820         int state;
3821
3822         TRACE(("dowait(0x%x) called\n", wait_flags));
3823
3824         /* Do a wait system call. If job control is compiled in, we accept
3825          * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826          * NB: _not_ safe_waitpid, we need to detect EINTR */
3827         pid = waitpid(-1, &status,
3828                         (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3829         TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830                                 pid, status, errno, strerror(errno)));
3831         if (pid <= 0)
3832                 return pid;
3833
3834         INT_OFF;
3835         thisjob = NULL;
3836         for (jp = curjob; jp; jp = jp->prev_job) {
3837                 struct procstat *sp;
3838                 struct procstat *spend;
3839                 if (jp->state == JOBDONE)
3840                         continue;
3841                 state = JOBDONE;
3842                 spend = jp->ps + jp->nprocs;
3843                 sp = jp->ps;
3844                 do {
3845                         if (sp->pid == pid) {
3846                                 TRACE(("Job %d: changing status of proc %d "
3847                                         "from 0x%x to 0x%x\n",
3848                                         jobno(jp), pid, sp->status, status));
3849                                 sp->status = status;
3850                                 thisjob = jp;
3851                         }
3852                         if (sp->status == -1)
3853                                 state = JOBRUNNING;
3854 #if JOBS
3855                         if (state == JOBRUNNING)
3856                                 continue;
3857                         if (WIFSTOPPED(sp->status)) {
3858                                 jp->stopstatus = sp->status;
3859                                 state = JOBSTOPPED;
3860                         }
3861 #endif
3862                 } while (++sp < spend);
3863                 if (thisjob)
3864                         goto gotjob;
3865         }
3866 #if JOBS
3867         if (!WIFSTOPPED(status))
3868 #endif
3869                 jobless--;
3870         goto out;
3871
3872  gotjob:
3873         if (state != JOBRUNNING) {
3874                 thisjob->changed = 1;
3875
3876                 if (thisjob->state != state) {
3877                         TRACE(("Job %d: changing state from %d to %d\n",
3878                                 jobno(thisjob), thisjob->state, state));
3879                         thisjob->state = state;
3880 #if JOBS
3881                         if (state == JOBSTOPPED) {
3882                                 set_curjob(thisjob, CUR_STOPPED);
3883                         }
3884 #endif
3885                 }
3886         }
3887
3888  out:
3889         INT_ON;
3890
3891         if (thisjob && thisjob == job) {
3892                 char s[48 + 1];
3893                 int len;
3894
3895                 len = sprint_status(s, status, 1);
3896                 if (len) {
3897                         s[len] = '\n';
3898                         s[len + 1] = '\0';
3899                         out2str(s);
3900                 }
3901         }
3902         return pid;
3903 }
3904
3905 static int
3906 blocking_wait_with_raise_on_sig(struct job *job)
3907 {
3908         pid_t pid = dowait(DOWAIT_BLOCK, job);
3909         if (pid <= 0 && pending_sig)
3910                 raise_exception(EXSIG);
3911         return pid;
3912 }
3913
3914 #if JOBS
3915 static void
3916 showjob(FILE *out, struct job *jp, int mode)
3917 {
3918         struct procstat *ps;
3919         struct procstat *psend;
3920         int col;
3921         int indent_col;
3922         char s[80];
3923
3924         ps = jp->ps;
3925
3926         if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3927                 /* just output process (group) id of pipeline */
3928                 fprintf(out, "%d\n", ps->pid);
3929                 return;
3930         }
3931
3932         col = fmtstr(s, 16, "[%d]   ", jobno(jp));
3933         indent_col = col;
3934
3935         if (jp == curjob)
3936                 s[col - 3] = '+';
3937         else if (curjob && jp == curjob->prev_job)
3938                 s[col - 3] = '-';
3939
3940         if (mode & SHOW_PIDS)
3941                 col += fmtstr(s + col, 16, "%d ", ps->pid);
3942
3943         psend = ps + jp->nprocs;
3944
3945         if (jp->state == JOBRUNNING) {
3946                 strcpy(s + col, "Running");
3947                 col += sizeof("Running") - 1;
3948         } else {
3949                 int status = psend[-1].status;
3950                 if (jp->state == JOBSTOPPED)
3951                         status = jp->stopstatus;
3952                 col += sprint_status(s + col, status, 0);
3953         }
3954         /* By now, "[JOBID]*  [maybe PID] STATUS" is printed */
3955
3956         /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957          * or prints several "PID             | <cmdN>" lines,
3958          * depending on SHOW_PIDS bit.
3959          * We do not print status of individual processes
3960          * between PID and <cmdN>. bash does it, but not very well:
3961          * first line shows overall job status, not process status,
3962          * making it impossible to know 1st process status.
3963          */
3964         goto start;
3965         while (1) {
3966                 /* for each process */
3967                 s[0] = '\0';
3968                 col = 33;
3969                 if (mode & SHOW_PIDS)
3970                         col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3971  start:
3972                 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3973                 if (ps != jp->ps)
3974                         fprintf(out, "| ");
3975                 fprintf(out, "%s", ps->cmd);
3976                 if (++ps == psend)
3977                         break;
3978         }
3979         outcslow('\n', out);
3980
3981         jp->changed = 0;
3982
3983         if (jp->state == JOBDONE) {
3984                 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3985                 freejob(jp);
3986         }
3987 }
3988
3989 /*
3990  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3991  * statuses have changed since the last call to showjobs.
3992  */
3993 static void
3994 showjobs(FILE *out, int mode)
3995 {
3996         struct job *jp;
3997
3998         TRACE(("showjobs(0x%x) called\n", mode));
3999
4000         /* Handle all finished jobs */
4001         while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4002                 continue;
4003
4004         for (jp = curjob; jp; jp = jp->prev_job) {
4005                 if (!(mode & SHOW_CHANGED) || jp->changed) {
4006                         showjob(out, jp, mode);
4007                 }
4008         }
4009 }
4010
4011 static int FAST_FUNC
4012 jobscmd(int argc UNUSED_PARAM, char **argv)
4013 {
4014         int mode, m;
4015
4016         mode = 0;
4017         while ((m = nextopt("lp")) != '\0') {
4018                 if (m == 'l')
4019                         mode |= SHOW_PIDS;
4020                 else
4021                         mode |= SHOW_ONLY_PGID;
4022         }
4023
4024         argv = argptr;
4025         if (*argv) {
4026                 do
4027                         showjob(stdout, getjob(*argv, 0), mode);
4028                 while (*++argv);
4029         } else
4030                 showjobs(stdout, mode);
4031
4032         return 0;
4033 }
4034 #endif /* JOBS */
4035
4036 static int
4037 getstatus(struct job *job)
4038 {
4039         int status;
4040         int retval;
4041
4042         status = job->ps[job->nprocs - 1].status;
4043         retval = WEXITSTATUS(status);
4044         if (!WIFEXITED(status)) {
4045 #if JOBS
4046                 retval = WSTOPSIG(status);
4047                 if (!WIFSTOPPED(status))
4048 #endif
4049                 {
4050                         /* XXX: limits number of signals */
4051                         retval = WTERMSIG(status);
4052 #if JOBS
4053                         if (retval == SIGINT)
4054                                 job->sigint = 1;
4055 #endif
4056                 }
4057                 retval += 128;
4058         }
4059         TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4060                 jobno(job), job->nprocs, status, retval));
4061         return retval;
4062 }
4063
4064 static int FAST_FUNC
4065 waitcmd(int argc UNUSED_PARAM, char **argv)
4066 {
4067         struct job *job;
4068         int retval;
4069         struct job *jp;
4070
4071         if (pending_sig)
4072                 raise_exception(EXSIG);
4073
4074         nextopt(nullstr);
4075         retval = 0;
4076
4077         argv = argptr;
4078         if (!*argv) {
4079                 /* wait for all jobs */
4080                 for (;;) {
4081                         jp = curjob;
4082                         while (1) {
4083                                 if (!jp) /* no running procs */
4084                                         goto ret;
4085                                 if (jp->state == JOBRUNNING)
4086                                         break;
4087                                 jp->waited = 1;
4088                                 jp = jp->prev_job;
4089                         }
4090         /* man bash:
4091          * "When bash is waiting for an asynchronous command via
4092          * the wait builtin, the reception of a signal for which a trap
4093          * has been set will cause the wait builtin to return immediately
4094          * with an exit status greater than 128, immediately after which
4095          * the trap is executed."
4096          * Do we do it that way? */
4097                         blocking_wait_with_raise_on_sig(NULL);
4098                 }
4099         }
4100
4101         retval = 127;
4102         do {
4103                 if (**argv != '%') {
4104                         pid_t pid = number(*argv);
4105                         job = curjob;
4106                         while (1) {
4107                                 if (!job)
4108                                         goto repeat;
4109                                 if (job->ps[job->nprocs - 1].pid == pid)
4110                                         break;
4111                                 job = job->prev_job;
4112                         }
4113                 } else
4114                         job = getjob(*argv, 0);
4115                 /* loop until process terminated or stopped */
4116                 while (job->state == JOBRUNNING)
4117                         blocking_wait_with_raise_on_sig(NULL);
4118                 job->waited = 1;
4119                 retval = getstatus(job);
4120  repeat: ;
4121         } while (*++argv);
4122
4123  ret:
4124         return retval;
4125 }
4126
4127 static struct job *
4128 growjobtab(void)
4129 {
4130         size_t len;
4131         ptrdiff_t offset;
4132         struct job *jp, *jq;
4133
4134         len = njobs * sizeof(*jp);
4135         jq = jobtab;
4136         jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4137
4138         offset = (char *)jp - (char *)jq;
4139         if (offset) {
4140                 /* Relocate pointers */
4141                 size_t l = len;
4142
4143                 jq = (struct job *)((char *)jq + l);
4144                 while (l) {
4145                         l -= sizeof(*jp);
4146                         jq--;
4147 #define joff(p) ((struct job *)((char *)(p) + l))
4148 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4149                         if (joff(jp)->ps == &jq->ps0)
4150                                 jmove(joff(jp)->ps);
4151                         if (joff(jp)->prev_job)
4152                                 jmove(joff(jp)->prev_job);
4153                 }
4154                 if (curjob)
4155                         jmove(curjob);
4156 #undef joff
4157 #undef jmove
4158         }
4159
4160         njobs += 4;
4161         jobtab = jp;
4162         jp = (struct job *)((char *)jp + len);
4163         jq = jp + 3;
4164         do {
4165                 jq->used = 0;
4166         } while (--jq >= jp);
4167         return jp;
4168 }
4169
4170 /*
4171  * Return a new job structure.
4172  * Called with interrupts off.
4173  */
4174 static struct job *
4175 makejob(/*union node *node,*/ int nprocs)
4176 {
4177         int i;
4178         struct job *jp;
4179
4180         for (i = njobs, jp = jobtab; ; jp++) {
4181                 if (--i < 0) {
4182                         jp = growjobtab();
4183                         break;
4184                 }
4185                 if (jp->used == 0)
4186                         break;
4187                 if (jp->state != JOBDONE || !jp->waited)
4188                         continue;
4189 #if JOBS
4190                 if (doing_jobctl)
4191                         continue;
4192 #endif
4193                 freejob(jp);
4194                 break;
4195         }
4196         memset(jp, 0, sizeof(*jp));
4197 #if JOBS
4198         /* jp->jobctl is a bitfield.
4199          * "jp->jobctl |= jobctl" likely to give awful code */
4200         if (doing_jobctl)
4201                 jp->jobctl = 1;
4202 #endif
4203         jp->prev_job = curjob;
4204         curjob = jp;
4205         jp->used = 1;
4206         jp->ps = &jp->ps0;
4207         if (nprocs > 1) {
4208                 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4209         }
4210         TRACE(("makejob(%d) returns %%%d\n", nprocs,
4211                                 jobno(jp)));
4212         return jp;
4213 }
4214
4215 #if JOBS
4216 /*
4217  * Return a string identifying a command (to be printed by the
4218  * jobs command).
4219  */
4220 static char *cmdnextc;
4221
4222 static void
4223 cmdputs(const char *s)
4224 {
4225         static const char vstype[VSTYPE + 1][3] = {
4226                 "", "}", "-", "+", "?", "=",
4227                 "%", "%%", "#", "##"
4228                 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4229         };
4230
4231         const char *p, *str;
4232         char c, cc[2] = " ";
4233         char *nextc;
4234         int subtype = 0;
4235         int quoted = 0;
4236
4237         nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4238         p = s;
4239         while ((c = *p++) != 0) {
4240                 str = NULL;
4241                 switch (c) {
4242                 case CTLESC:
4243                         c = *p++;
4244                         break;
4245                 case CTLVAR:
4246                         subtype = *p++;
4247                         if ((subtype & VSTYPE) == VSLENGTH)
4248                                 str = "${#";
4249                         else
4250                                 str = "${";
4251                         if (!(subtype & VSQUOTE) == !(quoted & 1))
4252                                 goto dostr;
4253                         quoted ^= 1;
4254                         c = '"';
4255                         break;
4256                 case CTLENDVAR:
4257                         str = "\"}" + !(quoted & 1);
4258                         quoted >>= 1;
4259                         subtype = 0;
4260                         goto dostr;
4261                 case CTLBACKQ:
4262                         str = "$(...)";
4263                         goto dostr;
4264                 case CTLBACKQ+CTLQUOTE:
4265                         str = "\"$(...)\"";
4266                         goto dostr;
4267 #if ENABLE_SH_MATH_SUPPORT
4268                 case CTLARI:
4269                         str = "$((";
4270                         goto dostr;
4271                 case CTLENDARI:
4272                         str = "))";
4273                         goto dostr;
4274 #endif
4275                 case CTLQUOTEMARK:
4276                         quoted ^= 1;
4277                         c = '"';
4278                         break;
4279                 case '=':
4280                         if (subtype == 0)
4281                                 break;
4282                         if ((subtype & VSTYPE) != VSNORMAL)
4283                                 quoted <<= 1;
4284                         str = vstype[subtype & VSTYPE];
4285                         if (subtype & VSNUL)
4286                                 c = ':';
4287                         else
4288                                 goto checkstr;
4289                         break;
4290                 case '\'':
4291                 case '\\':
4292                 case '"':
4293                 case '$':
4294                         /* These can only happen inside quotes */
4295                         cc[0] = c;
4296                         str = cc;
4297                         c = '\\';
4298                         break;
4299                 default:
4300                         break;
4301                 }
4302                 USTPUTC(c, nextc);
4303  checkstr:
4304                 if (!str)
4305                         continue;
4306  dostr:
4307                 while ((c = *str++) != '\0') {
4308                         USTPUTC(c, nextc);
4309                 }
4310         }
4311         if (quoted & 1) {
4312                 USTPUTC('"', nextc);
4313         }
4314         *nextc = 0;
4315         cmdnextc = nextc;
4316 }
4317
4318 /* cmdtxt() and cmdlist() call each other */
4319 static void cmdtxt(union node *n);
4320
4321 static void
4322 cmdlist(union node *np, int sep)
4323 {
4324         for (; np; np = np->narg.next) {
4325                 if (!sep)
4326                         cmdputs(" ");
4327                 cmdtxt(np);
4328                 if (sep && np->narg.next)
4329                         cmdputs(" ");
4330         }
4331 }
4332
4333 static void
4334 cmdtxt(union node *n)
4335 {
4336         union node *np;
4337         struct nodelist *lp;
4338         const char *p;
4339
4340         if (!n)
4341                 return;
4342         switch (n->type) {
4343         default:
4344 #if DEBUG
4345                 abort();
4346 #endif
4347         case NPIPE:
4348                 lp = n->npipe.cmdlist;
4349                 for (;;) {
4350                         cmdtxt(lp->n);
4351                         lp = lp->next;
4352                         if (!lp)
4353                                 break;
4354                         cmdputs(" | ");
4355                 }
4356                 break;
4357         case NSEMI:
4358                 p = "; ";
4359                 goto binop;
4360         case NAND:
4361                 p = " && ";
4362                 goto binop;
4363         case NOR:
4364                 p = " || ";
4365  binop:
4366                 cmdtxt(n->nbinary.ch1);
4367                 cmdputs(p);
4368                 n = n->nbinary.ch2;
4369                 goto donode;
4370         case NREDIR:
4371         case NBACKGND:
4372                 n = n->nredir.n;
4373                 goto donode;
4374         case NNOT:
4375                 cmdputs("!");
4376                 n = n->nnot.com;
4377  donode:
4378                 cmdtxt(n);
4379                 break;
4380         case NIF:
4381                 cmdputs("if ");
4382                 cmdtxt(n->nif.test);
4383                 cmdputs("; then ");
4384                 if (n->nif.elsepart) {
4385                         cmdtxt(n->nif.ifpart);
4386                         cmdputs("; else ");
4387                         n = n->nif.elsepart;
4388                 } else {
4389                         n = n->nif.ifpart;
4390                 }
4391                 p = "; fi";
4392                 goto dotail;
4393         case NSUBSHELL:
4394                 cmdputs("(");
4395                 n = n->nredir.n;
4396                 p = ")";
4397                 goto dotail;
4398         case NWHILE:
4399                 p = "while ";
4400                 goto until;
4401         case NUNTIL:
4402                 p = "until ";
4403  until:
4404                 cmdputs(p);
4405                 cmdtxt(n->nbinary.ch1);
4406                 n = n->nbinary.ch2;
4407                 p = "; done";
4408  dodo:
4409                 cmdputs("; do ");
4410  dotail:
4411                 cmdtxt(n);
4412                 goto dotail2;
4413         case NFOR:
4414                 cmdputs("for ");
4415                 cmdputs(n->nfor.var);
4416                 cmdputs(" in ");
4417                 cmdlist(n->nfor.args, 1);
4418                 n = n->nfor.body;
4419                 p = "; done";
4420                 goto dodo;
4421         case NDEFUN:
4422                 cmdputs(n->narg.text);
4423                 p = "() { ... }";
4424                 goto dotail2;
4425         case NCMD:
4426                 cmdlist(n->ncmd.args, 1);
4427                 cmdlist(n->ncmd.redirect, 0);
4428                 break;
4429         case NARG:
4430                 p = n->narg.text;
4431  dotail2:
4432                 cmdputs(p);
4433                 break;
4434         case NHERE:
4435         case NXHERE:
4436                 p = "<<...";
4437                 goto dotail2;
4438         case NCASE:
4439                 cmdputs("case ");
4440                 cmdputs(n->ncase.expr->narg.text);
4441                 cmdputs(" in ");
4442                 for (np = n->ncase.cases; np; np = np->nclist.next) {
4443                         cmdtxt(np->nclist.pattern);
4444                         cmdputs(") ");
4445                         cmdtxt(np->nclist.body);
4446                         cmdputs(";; ");
4447                 }
4448                 p = "esac";
4449                 goto dotail2;
4450         case NTO:
4451                 p = ">";
4452                 goto redir;
4453         case NCLOBBER:
4454                 p = ">|";
4455                 goto redir;
4456         case NAPPEND:
4457                 p = ">>";
4458                 goto redir;
4459 #if ENABLE_ASH_BASH_COMPAT
4460         case NTO2:
4461 #endif
4462         case NTOFD:
4463                 p = ">&";
4464                 goto redir;
4465         case NFROM:
4466                 p = "<";
4467                 goto redir;
4468         case NFROMFD:
4469                 p = "<&";
4470                 goto redir;
4471         case NFROMTO:
4472                 p = "<>";
4473  redir:
4474                 cmdputs(utoa(n->nfile.fd));
4475                 cmdputs(p);
4476                 if (n->type == NTOFD || n->type == NFROMFD) {
4477                         cmdputs(utoa(n->ndup.dupfd));
4478                         break;
4479                 }
4480                 n = n->nfile.fname;
4481                 goto donode;
4482         }
4483 }
4484
4485 static char *
4486 commandtext(union node *n)
4487 {
4488         char *name;
4489
4490         STARTSTACKSTR(cmdnextc);
4491         cmdtxt(n);
4492         name = stackblock();
4493         TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4494                         name, cmdnextc, cmdnextc));
4495         return ckstrdup(name);
4496 }
4497 #endif /* JOBS */
4498
4499 /*
4500  * Fork off a subshell.  If we are doing job control, give the subshell its
4501  * own process group.  Jp is a job structure that the job is to be added to.
4502  * N is the command that will be evaluated by the child.  Both jp and n may
4503  * be NULL.  The mode parameter can be one of the following:
4504  *      FORK_FG - Fork off a foreground process.
4505  *      FORK_BG - Fork off a background process.
4506  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
4507  *                   process group even if job control is on.
4508  *
4509  * When job control is turned off, background processes have their standard
4510  * input redirected to /dev/null (except for the second and later processes
4511  * in a pipeline).
4512  *
4513  * Called with interrupts off.
4514  */
4515 /*
4516  * Clear traps on a fork.
4517  */
4518 static void
4519 clear_traps(void)
4520 {
4521         char **tp;
4522
4523         for (tp = trap; tp < &trap[NSIG]; tp++) {
4524                 if (*tp && **tp) {      /* trap not NULL or "" (SIG_IGN) */
4525                         INT_OFF;
4526                         free(*tp);
4527                         *tp = NULL;
4528                         if ((tp - trap) != 0)
4529                                 setsignal(tp - trap);
4530                         INT_ON;
4531                 }
4532         }
4533 }
4534
4535 /* Lives far away from here, needed for forkchild */
4536 static void closescript(void);
4537
4538 /* Called after fork(), in child */
4539 #if !JOBS
4540 # define forkchild(jp, n, mode) forkchild(jp, mode)
4541 #endif
4542 static void
4543 forkchild(struct job *jp, union node *n, int mode)
4544 {
4545         int oldlvl;
4546
4547         TRACE(("Child shell %d\n", getpid()));
4548         oldlvl = shlvl;
4549         shlvl++;
4550
4551         /* man bash: "Non-builtin commands run by bash have signal handlers
4552          * set to the values inherited by the shell from its parent".
4553          * Do we do it correctly? */
4554
4555         closescript();
4556
4557         if (mode == FORK_NOJOB          /* is it `xxx` ? */
4558          && n && n->type == NCMD        /* is it single cmd? */
4559         /* && n->ncmd.args->type == NARG - always true? */
4560          && strcmp(n->ncmd.args->narg.text, "trap") == 0
4561          && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4562         /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4563         ) {
4564                 TRACE(("Trap hack\n"));
4565                 /* Awful hack for `trap` or $(trap).
4566                  *
4567                  * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4568                  * contains an example where "trap" is executed in a subshell:
4569                  *
4570                  * save_traps=$(trap)
4571                  * ...
4572                  * eval "$save_traps"
4573                  *
4574                  * Standard does not say that "trap" in subshell shall print
4575                  * parent shell's traps. It only says that its output
4576                  * must have suitable form, but then, in the above example
4577                  * (which is not supposed to be normative), it implies that.
4578                  *
4579                  * bash (and probably other shell) does implement it
4580                  * (traps are reset to defaults, but "trap" still shows them),
4581                  * but as a result, "trap" logic is hopelessly messed up:
4582                  *
4583                  * # trap
4584                  * trap -- 'echo Ho' SIGWINCH  <--- we have a handler
4585                  * # (trap)        <--- trap is in subshell - no output (correct, traps are reset)
4586                  * # true | trap   <--- trap is in subshell - no output (ditto)
4587                  * # echo `true | trap`    <--- in subshell - output (but traps are reset!)
4588                  * trap -- 'echo Ho' SIGWINCH
4589                  * # echo `(trap)`         <--- in subshell in subshell - output
4590                  * trap -- 'echo Ho' SIGWINCH
4591                  * # echo `true | (trap)`  <--- in subshell in subshell in subshell - output!
4592                  * trap -- 'echo Ho' SIGWINCH
4593                  *
4594                  * The rules when to forget and when to not forget traps
4595                  * get really complex and nonsensical.
4596                  *
4597                  * Our solution: ONLY bare $(trap) or `trap` is special.
4598                  */
4599                 free(trap[0]); /* Prevent EXIT trap from firing in `trap` */
4600                 trap[0] = NULL;
4601         } else {
4602                 clear_traps();
4603         }
4604 #if JOBS
4605         /* do job control only in root shell */
4606         doing_jobctl = 0;
4607         if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4608                 pid_t pgrp;
4609
4610                 if (jp->nprocs == 0)
4611                         pgrp = getpid();
4612                 else
4613                         pgrp = jp->ps[0].pid;
4614                 /* this can fail because we are doing it in the parent also */
4615                 setpgid(0, pgrp);
4616                 if (mode == FORK_FG)
4617                         xtcsetpgrp(ttyfd, pgrp);
4618                 setsignal(SIGTSTP);
4619                 setsignal(SIGTTOU);
4620         } else
4621 #endif
4622         if (mode == FORK_BG) {
4623                 /* man bash: "When job control is not in effect,
4624                  * asynchronous commands ignore SIGINT and SIGQUIT" */
4625                 ignoresig(SIGINT);
4626                 ignoresig(SIGQUIT);
4627                 if (jp->nprocs == 0) {
4628                         close(0);
4629                         if (open(bb_dev_null, O_RDONLY) != 0)
4630                                 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4631                 }
4632         }
4633         if (!oldlvl) {
4634                 if (iflag) { /* why if iflag only? */
4635                         setsignal(SIGINT);
4636                         setsignal(SIGTERM);
4637                 }
4638                 /* man bash:
4639                  * "In all cases, bash ignores SIGQUIT. Non-builtin
4640                  * commands run by bash have signal handlers
4641                  * set to the values inherited by the shell
4642                  * from its parent".
4643                  * Take care of the second rule: */
4644                 setsignal(SIGQUIT);
4645         }
4646 #if JOBS
4647         if (n && n->type == NCMD
4648          && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4649         ) {
4650                 TRACE(("Job hack\n"));
4651                 /* "jobs": we do not want to clear job list for it,
4652                  * instead we remove only _its_ own_ job from job list.
4653                  * This makes "jobs .... | cat" more useful.
4654                  */
4655                 freejob(curjob);
4656                 return;
4657         }
4658 #endif
4659         for (jp = curjob; jp; jp = jp->prev_job)
4660                 freejob(jp);
4661         jobless = 0;
4662 }
4663
4664 /* Called after fork(), in parent */
4665 #if !JOBS
4666 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4667 #endif
4668 static void
4669 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4670 {
4671         TRACE(("In parent shell: child = %d\n", pid));
4672         if (!jp) {
4673                 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4674                         continue;
4675                 jobless++;
4676                 return;
4677         }
4678 #if JOBS
4679         if (mode != FORK_NOJOB && jp->jobctl) {
4680                 int pgrp;
4681
4682                 if (jp->nprocs == 0)
4683                         pgrp = pid;
4684                 else
4685                         pgrp = jp->ps[0].pid;
4686                 /* This can fail because we are doing it in the child also */
4687                 setpgid(pid, pgrp);
4688         }
4689 #endif
4690         if (mode == FORK_BG) {
4691                 backgndpid = pid;               /* set $! */
4692                 set_curjob(jp, CUR_RUNNING);
4693         }
4694         if (jp) {
4695                 struct procstat *ps = &jp->ps[jp->nprocs++];
4696                 ps->pid = pid;
4697                 ps->status = -1;
4698                 ps->cmd = nullstr;
4699 #if JOBS
4700                 if (doing_jobctl && n)
4701                         ps->cmd = commandtext(n);
4702 #endif
4703         }
4704 }
4705
4706 static int
4707 forkshell(struct job *jp, union node *n, int mode)
4708 {
4709         int pid;
4710
4711         TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4712         pid = fork();
4713         if (pid < 0) {
4714                 TRACE(("Fork failed, errno=%d", errno));
4715                 if (jp)
4716                         freejob(jp);
4717                 ash_msg_and_raise_error("can't fork");
4718         }
4719         if (pid == 0)
4720                 forkchild(jp, n, mode);
4721         else
4722                 forkparent(jp, n, mode, pid);
4723         return pid;
4724 }
4725
4726 /*
4727  * Wait for job to finish.
4728  *
4729  * Under job control we have the problem that while a child process
4730  * is running interrupts generated by the user are sent to the child
4731  * but not to the shell.  This means that an infinite loop started by
4732  * an interactive user may be hard to kill.  With job control turned off,
4733  * an interactive user may place an interactive program inside a loop.
4734  * If the interactive program catches interrupts, the user doesn't want
4735  * these interrupts to also abort the loop.  The approach we take here
4736  * is to have the shell ignore interrupt signals while waiting for a
4737  * foreground process to terminate, and then send itself an interrupt
4738  * signal if the child process was terminated by an interrupt signal.
4739  * Unfortunately, some programs want to do a bit of cleanup and then
4740  * exit on interrupt; unless these processes terminate themselves by
4741  * sending a signal to themselves (instead of calling exit) they will
4742  * confuse this approach.
4743  *
4744  * Called with interrupts off.
4745  */
4746 static int
4747 waitforjob(struct job *jp)
4748 {
4749         int st;
4750
4751         TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4752
4753         INT_OFF;
4754         while (jp->state == JOBRUNNING) {
4755                 /* In non-interactive shells, we _can_ get
4756                  * a keyboard signal here and be EINTRed,
4757                  * but we just loop back, waiting for command to complete.
4758                  *
4759                  * man bash:
4760                  * "If bash is waiting for a command to complete and receives
4761                  * a signal for which a trap has been set, the trap
4762                  * will not be executed until the command completes."
4763                  *
4764                  * Reality is that even if trap is not set, bash
4765                  * will not act on the signal until command completes.
4766                  * Try this. sleep5intoff.c:
4767                  * #include <signal.h>
4768                  * #include <unistd.h>
4769                  * int main() {
4770                  *         sigset_t set;
4771                  *         sigemptyset(&set);
4772                  *         sigaddset(&set, SIGINT);
4773                  *         sigaddset(&set, SIGQUIT);
4774                  *         sigprocmask(SIG_BLOCK, &set, NULL);
4775                  *         sleep(5);
4776                  *         return 0;
4777                  * }
4778                  * $ bash -c './sleep5intoff; echo hi'
4779                  * ^C^C^C^C <--- pressing ^C once a second
4780                  * $ _
4781                  * $ bash -c './sleep5intoff; echo hi'
4782                  * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4783                  * $ _
4784                  */
4785                 dowait(DOWAIT_BLOCK, jp);
4786         }
4787         INT_ON;
4788
4789         st = getstatus(jp);
4790 #if JOBS
4791         if (jp->jobctl) {
4792                 xtcsetpgrp(ttyfd, rootpid);
4793                 /*
4794                  * This is truly gross.
4795                  * If we're doing job control, then we did a TIOCSPGRP which
4796                  * caused us (the shell) to no longer be in the controlling
4797                  * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
4798                  * intuit from the subprocess exit status whether a SIGINT
4799                  * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
4800                  */
4801                 if (jp->sigint) /* TODO: do the same with all signals */
4802                         raise(SIGINT); /* ... by raise(jp->sig) instead? */
4803         }
4804         if (jp->state == JOBDONE)
4805 #endif
4806                 freejob(jp);
4807         return st;
4808 }
4809
4810 /*
4811  * return 1 if there are stopped jobs, otherwise 0
4812  */
4813 static int
4814 stoppedjobs(void)
4815 {
4816         struct job *jp;
4817         int retval;
4818
4819         retval = 0;
4820         if (job_warning)
4821                 goto out;
4822         jp = curjob;
4823         if (jp && jp->state == JOBSTOPPED) {
4824                 out2str("You have stopped jobs.\n");
4825                 job_warning = 2;
4826                 retval++;
4827         }
4828  out:
4829         return retval;
4830 }
4831
4832
4833 /* ============ redir.c
4834  *
4835  * Code for dealing with input/output redirection.
4836  */
4837
4838 #define EMPTY -2                /* marks an unused slot in redirtab */
4839 #define CLOSED -3               /* marks a slot of previously-closed fd */
4840
4841 /*
4842  * Open a file in noclobber mode.
4843  * The code was copied from bash.
4844  */
4845 static int
4846 noclobberopen(const char *fname)
4847 {
4848         int r, fd;
4849         struct stat finfo, finfo2;
4850
4851         /*
4852          * If the file exists and is a regular file, return an error
4853          * immediately.
4854          */
4855         r = stat(fname, &finfo);
4856         if (r == 0 && S_ISREG(finfo.st_mode)) {
4857                 errno = EEXIST;
4858                 return -1;
4859         }
4860
4861         /*
4862          * If the file was not present (r != 0), make sure we open it
4863          * exclusively so that if it is created before we open it, our open
4864          * will fail.  Make sure that we do not truncate an existing file.
4865          * Note that we don't turn on O_EXCL unless the stat failed -- if the
4866          * file was not a regular file, we leave O_EXCL off.
4867          */
4868         if (r != 0)
4869                 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4870         fd = open(fname, O_WRONLY|O_CREAT, 0666);
4871
4872         /* If the open failed, return the file descriptor right away. */
4873         if (fd < 0)
4874                 return fd;
4875
4876         /*
4877          * OK, the open succeeded, but the file may have been changed from a
4878          * non-regular file to a regular file between the stat and the open.
4879          * We are assuming that the O_EXCL open handles the case where FILENAME
4880          * did not exist and is symlinked to an existing file between the stat
4881          * and open.
4882          */
4883
4884         /*
4885          * If we can open it and fstat the file descriptor, and neither check
4886          * revealed that it was a regular file, and the file has not been
4887          * replaced, return the file descriptor.
4888          */
4889         if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4890          && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4891                 return fd;
4892
4893         /* The file has been replaced.  badness. */
4894         close(fd);
4895         errno = EEXIST;
4896         return -1;
4897 }
4898
4899 /*
4900  * Handle here documents.  Normally we fork off a process to write the
4901  * data to a pipe.  If the document is short, we can stuff the data in
4902  * the pipe without forking.
4903  */
4904 /* openhere needs this forward reference */
4905 static void expandhere(union node *arg, int fd);
4906 static int
4907 openhere(union node *redir)
4908 {
4909         int pip[2];
4910         size_t len = 0;
4911
4912         if (pipe(pip) < 0)
4913                 ash_msg_and_raise_error("pipe call failed");
4914         if (redir->type == NHERE) {
4915                 len = strlen(redir->nhere.doc->narg.text);
4916                 if (len <= PIPE_BUF) {
4917                         full_write(pip[1], redir->nhere.doc->narg.text, len);
4918                         goto out;
4919                 }
4920         }
4921         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4922                 /* child */
4923                 close(pip[0]);
4924                 ignoresig(SIGINT);  //signal(SIGINT, SIG_IGN);
4925                 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4926                 ignoresig(SIGHUP);  //signal(SIGHUP, SIG_IGN);
4927                 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4928                 signal(SIGPIPE, SIG_DFL);
4929                 if (redir->type == NHERE)
4930                         full_write(pip[1], redir->nhere.doc->narg.text, len);
4931                 else /* NXHERE */
4932                         expandhere(redir->nhere.doc, pip[1]);
4933                 _exit(EXIT_SUCCESS);
4934         }
4935  out:
4936         close(pip[1]);
4937         return pip[0];
4938 }
4939
4940 static int
4941 openredirect(union node *redir)
4942 {
4943         char *fname;
4944         int f;
4945
4946         switch (redir->nfile.type) {
4947         case NFROM:
4948                 fname = redir->nfile.expfname;
4949                 f = open(fname, O_RDONLY);
4950                 if (f < 0)
4951                         goto eopen;
4952                 break;
4953         case NFROMTO:
4954                 fname = redir->nfile.expfname;
4955                 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4956                 if (f < 0)
4957                         goto ecreate;
4958                 break;
4959         case NTO:
4960 #if ENABLE_ASH_BASH_COMPAT
4961         case NTO2:
4962 #endif
4963                 /* Take care of noclobber mode. */
4964                 if (Cflag) {
4965                         fname = redir->nfile.expfname;
4966                         f = noclobberopen(fname);
4967                         if (f < 0)
4968                                 goto ecreate;
4969                         break;
4970                 }
4971                 /* FALLTHROUGH */
4972         case NCLOBBER:
4973                 fname = redir->nfile.expfname;
4974                 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4975                 if (f < 0)
4976                         goto ecreate;
4977                 break;
4978         case NAPPEND:
4979                 fname = redir->nfile.expfname;
4980                 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4981                 if (f < 0)
4982                         goto ecreate;
4983                 break;
4984         default:
4985 #if DEBUG
4986                 abort();
4987 #endif
4988                 /* Fall through to eliminate warning. */
4989 /* Our single caller does this itself */
4990 //      case NTOFD:
4991 //      case NFROMFD:
4992 //              f = -1;
4993 //              break;
4994         case NHERE:
4995         case NXHERE:
4996                 f = openhere(redir);
4997                 break;
4998         }
4999
5000         return f;
5001  ecreate:
5002         ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5003  eopen:
5004         ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5005 }
5006
5007 /*
5008  * Copy a file descriptor to be >= to.  Returns -1
5009  * if the source file descriptor is closed, EMPTY if there are no unused
5010  * file descriptors left.
5011  */
5012 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5013  * old code was doing close(to) prior to copyfd() to achieve the same */
5014 enum {
5015         COPYFD_EXACT   = (int)~(INT_MAX),
5016         COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5017 };
5018 static int
5019 copyfd(int from, int to)
5020 {
5021         int newfd;
5022
5023         if (to & COPYFD_EXACT) {
5024                 to &= ~COPYFD_EXACT;
5025                 /*if (from != to)*/
5026                         newfd = dup2(from, to);
5027         } else {
5028                 newfd = fcntl(from, F_DUPFD, to);
5029         }
5030         if (newfd < 0) {
5031                 if (errno == EMFILE)
5032                         return EMPTY;
5033                 /* Happens when source fd is not open: try "echo >&99" */
5034                 ash_msg_and_raise_error("%d: %m", from);
5035         }
5036         return newfd;
5037 }
5038
5039 /* Struct def and variable are moved down to the first usage site */
5040 struct two_fd_t {
5041         int orig, copy;
5042 };
5043 struct redirtab {
5044         struct redirtab *next;
5045         int nullredirs;
5046         int pair_count;
5047         struct two_fd_t two_fd[];
5048 };
5049 #define redirlist (G_var.redirlist)
5050
5051 static int need_to_remember(struct redirtab *rp, int fd)
5052 {
5053         int i;
5054
5055         if (!rp) /* remembering was not requested */
5056                 return 0;
5057
5058         for (i = 0; i < rp->pair_count; i++) {
5059                 if (rp->two_fd[i].orig == fd) {
5060                         /* already remembered */
5061                         return 0;
5062                 }
5063         }
5064         return 1;
5065 }
5066
5067 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5068 static int is_hidden_fd(struct redirtab *rp, int fd)
5069 {
5070         int i;
5071         struct parsefile *pf;
5072
5073         if (fd == -1)
5074                 return 0;
5075         pf = g_parsefile;
5076         while (pf) {
5077                 if (fd == pf->fd) {
5078                         return 1;
5079                 }
5080                 pf = pf->prev;
5081         }
5082         if (!rp)
5083                 return 0;
5084         fd |= COPYFD_RESTORE;
5085         for (i = 0; i < rp->pair_count; i++) {
5086                 if (rp->two_fd[i].copy == fd) {
5087                         return 1;
5088                 }
5089         }
5090         return 0;
5091 }
5092
5093 /*
5094  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
5095  * old file descriptors are stashed away so that the redirection can be
5096  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
5097  * standard output, and the standard error if it becomes a duplicate of
5098  * stdout, is saved in memory.
5099  */
5100 /* flags passed to redirect */
5101 #define REDIR_PUSH    01        /* save previous values of file descriptors */
5102 #define REDIR_SAVEFD2 03        /* set preverrout */
5103 static void
5104 redirect(union node *redir, int flags)
5105 {
5106         struct redirtab *sv;
5107         int sv_pos;
5108         int i;
5109         int fd;
5110         int newfd;
5111         int copied_fd2 = -1;
5112
5113         g_nullredirs++;
5114         if (!redir) {
5115                 return;
5116         }
5117
5118         sv = NULL;
5119         sv_pos = 0;
5120         INT_OFF;
5121         if (flags & REDIR_PUSH) {
5122                 union node *tmp = redir;
5123                 do {
5124                         sv_pos++;
5125 #if ENABLE_ASH_BASH_COMPAT
5126                         if (redir->nfile.type == NTO2)
5127                                 sv_pos++;
5128 #endif
5129                         tmp = tmp->nfile.next;
5130                 } while (tmp);
5131                 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5132                 sv->next = redirlist;
5133                 sv->pair_count = sv_pos;
5134                 redirlist = sv;
5135                 sv->nullredirs = g_nullredirs - 1;
5136                 g_nullredirs = 0;
5137                 while (sv_pos > 0) {
5138                         sv_pos--;
5139                         sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5140                 }
5141         }
5142
5143         do {
5144                 fd = redir->nfile.fd;
5145                 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5146                         int right_fd = redir->ndup.dupfd;
5147                         /* redirect from/to same file descriptor? */
5148                         if (right_fd == fd)
5149                                 continue;
5150                         /* echo >&10 and 10 is a fd opened to the sh script? */
5151                         if (is_hidden_fd(sv, right_fd)) {
5152                                 errno = EBADF; /* as if it is closed */
5153                                 ash_msg_and_raise_error("%d: %m", right_fd);
5154                         }
5155                         newfd = -1;
5156                 } else {
5157                         newfd = openredirect(redir); /* always >= 0 */
5158                         if (fd == newfd) {
5159                                 /* Descriptor wasn't open before redirect.
5160                                  * Mark it for close in the future */
5161                                 if (need_to_remember(sv, fd)) {
5162                                         goto remember_to_close;
5163                                 }
5164                                 continue;
5165                         }
5166                 }
5167 #if ENABLE_ASH_BASH_COMPAT
5168  redirect_more:
5169 #endif
5170                 if (need_to_remember(sv, fd)) {
5171                         /* Copy old descriptor */
5172                         i = fcntl(fd, F_DUPFD, 10);
5173 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5174  * are closed in popredir() in the child, preventing them from leaking
5175  * into child. (popredir() also cleans up the mess in case of failures)
5176  */
5177                         if (i == -1) {
5178                                 i = errno;
5179                                 if (i != EBADF) {
5180                                         /* Strange error (e.g. "too many files" EMFILE?) */
5181                                         if (newfd >= 0)
5182                                                 close(newfd);
5183                                         errno = i;
5184                                         ash_msg_and_raise_error("%d: %m", fd);
5185                                         /* NOTREACHED */
5186                                 }
5187                                 /* EBADF: it is not open - good, remember to close it */
5188  remember_to_close:
5189                                 i = CLOSED;
5190                         } else { /* fd is open, save its copy */
5191                                 /* "exec fd>&-" should not close fds
5192                                  * which point to script file(s).
5193                                  * Force them to be restored afterwards */
5194                                 if (is_hidden_fd(sv, fd))
5195                                         i |= COPYFD_RESTORE;
5196                         }
5197                         if (fd == 2)
5198                                 copied_fd2 = i;
5199                         sv->two_fd[sv_pos].orig = fd;
5200                         sv->two_fd[sv_pos].copy = i;
5201                         sv_pos++;
5202                 }
5203                 if (newfd < 0) {
5204                         /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5205                         if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5206                                 /* Don't want to trigger debugging */
5207                                 if (fd != -1)
5208                                         close(fd);
5209                         } else {
5210                                 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5211                         }
5212                 } else if (fd != newfd) { /* move newfd to fd */
5213                         copyfd(newfd, fd | COPYFD_EXACT);
5214 #if ENABLE_ASH_BASH_COMPAT
5215                         if (!(redir->nfile.type == NTO2 && fd == 2))
5216 #endif
5217                                 close(newfd);
5218                 }
5219 #if ENABLE_ASH_BASH_COMPAT
5220                 if (redir->nfile.type == NTO2 && fd == 1) {
5221                         /* We already redirected it to fd 1, now copy it to 2 */
5222                         newfd = 1;
5223                         fd = 2;
5224                         goto redirect_more;
5225                 }
5226 #endif
5227         } while ((redir = redir->nfile.next) != NULL);
5228
5229         INT_ON;
5230         if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5231                 preverrout_fd = copied_fd2;
5232 }
5233
5234 /*
5235  * Undo the effects of the last redirection.
5236  */
5237 static void
5238 popredir(int drop, int restore)
5239 {
5240         struct redirtab *rp;
5241         int i;
5242
5243         if (--g_nullredirs >= 0)
5244                 return;
5245         INT_OFF;
5246         rp = redirlist;
5247         for (i = 0; i < rp->pair_count; i++) {
5248                 int fd = rp->two_fd[i].orig;
5249                 int copy = rp->two_fd[i].copy;
5250                 if (copy == CLOSED) {
5251                         if (!drop)
5252                                 close(fd);
5253                         continue;
5254                 }
5255                 if (copy != EMPTY) {
5256                         if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5257                                 copy &= ~COPYFD_RESTORE;
5258                                 /*close(fd);*/
5259                                 copyfd(copy, fd | COPYFD_EXACT);
5260                         }
5261                         close(copy & ~COPYFD_RESTORE);
5262                 }
5263         }
5264         redirlist = rp->next;
5265         g_nullredirs = rp->nullredirs;
5266         free(rp);
5267         INT_ON;
5268 }
5269
5270 /*
5271  * Undo all redirections.  Called on error or interrupt.
5272  */
5273
5274 /*
5275  * Discard all saved file descriptors.
5276  */
5277 static void
5278 clearredir(int drop)
5279 {
5280         for (;;) {
5281                 g_nullredirs = 0;
5282                 if (!redirlist)
5283                         break;
5284                 popredir(drop, /*restore:*/ 0);
5285         }
5286 }
5287
5288 static int
5289 redirectsafe(union node *redir, int flags)
5290 {
5291         int err;
5292         volatile int saveint;
5293         struct jmploc *volatile savehandler = exception_handler;
5294         struct jmploc jmploc;
5295
5296         SAVE_INT(saveint);
5297         /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5298         err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5299         if (!err) {
5300                 exception_handler = &jmploc;
5301                 redirect(redir, flags);
5302         }
5303         exception_handler = savehandler;
5304         if (err && exception_type != EXERROR)
5305                 longjmp(exception_handler->loc, 1);
5306         RESTORE_INT(saveint);
5307         return err;
5308 }
5309
5310
5311 /* ============ Routines to expand arguments to commands
5312  *
5313  * We have to deal with backquotes, shell variables, and file metacharacters.
5314  */
5315
5316 #if ENABLE_SH_MATH_SUPPORT
5317 static arith_t
5318 ash_arith(const char *s)
5319 {
5320         arith_eval_hooks_t math_hooks;
5321         arith_t result;
5322         int errcode = 0;
5323
5324         math_hooks.lookupvar = lookupvar;
5325         math_hooks.setvar = setvar;
5326         math_hooks.endofname = endofname;
5327
5328         INT_OFF;
5329         result = arith(s, &errcode, &math_hooks);
5330         if (errcode < 0) {
5331                 if (errcode == -3)
5332                         ash_msg_and_raise_error("exponent less than 0");
5333                 if (errcode == -2)
5334                         ash_msg_and_raise_error("divide by zero");
5335                 if (errcode == -5)
5336                         ash_msg_and_raise_error("expression recursion loop detected");
5337                 raise_error_syntax(s);
5338         }
5339         INT_ON;
5340
5341         return result;
5342 }
5343 #endif
5344
5345 /*
5346  * expandarg flags
5347  */
5348 #define EXP_FULL        0x1     /* perform word splitting & file globbing */
5349 #define EXP_TILDE       0x2     /* do normal tilde expansion */
5350 #define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
5351 #define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
5352 #define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
5353 #define EXP_RECORD      0x20    /* need to record arguments for ifs breakup */
5354 #define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
5355 #define EXP_WORD        0x80    /* expand word in parameter expansion */
5356 #define EXP_QWORD       0x100   /* expand word in quoted parameter expansion */
5357 /*
5358  * rmescape() flags
5359  */
5360 #define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
5361 #define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
5362 #define RMESCAPE_QUOTED 0x4     /* Remove CTLESC unless in quotes */
5363 #define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
5364 #define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
5365
5366 /*
5367  * Structure specifying which parts of the string should be searched
5368  * for IFS characters.
5369  */
5370 struct ifsregion {
5371         struct ifsregion *next; /* next region in list */
5372         int begoff;             /* offset of start of region */
5373         int endoff;             /* offset of end of region */
5374         int nulonly;            /* search for nul bytes only */
5375 };
5376
5377 struct arglist {
5378         struct strlist *list;
5379         struct strlist **lastp;
5380 };
5381
5382 /* output of current string */
5383 static char *expdest;
5384 /* list of back quote expressions */
5385 static struct nodelist *argbackq;
5386 /* first struct in list of ifs regions */
5387 static struct ifsregion ifsfirst;
5388 /* last struct in list */
5389 static struct ifsregion *ifslastp;
5390 /* holds expanded arg list */
5391 static struct arglist exparg;
5392
5393 /*
5394  * Our own itoa().
5395  */
5396 static int
5397 cvtnum(arith_t num)
5398 {
5399         int len;
5400
5401         expdest = makestrspace(32, expdest);
5402         len = fmtstr(expdest, 32, arith_t_fmt, num);
5403         STADJUST(len, expdest);
5404         return len;
5405 }
5406
5407 static size_t
5408 esclen(const char *start, const char *p)
5409 {
5410         size_t esc = 0;
5411
5412         while (p > start && (unsigned char)*--p == CTLESC) {
5413                 esc++;
5414         }
5415         return esc;
5416 }
5417
5418 /*
5419  * Remove any CTLESC characters from a string.
5420  */
5421 static char *
5422 rmescapes(char *str, int flag)
5423 {
5424         static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5425
5426         char *p, *q, *r;
5427         unsigned inquotes;
5428         unsigned protect_against_glob;
5429         unsigned globbing;
5430
5431         p = strpbrk(str, qchars);
5432         if (!p)
5433                 return str;
5434
5435         q = p;
5436         r = str;
5437         if (flag & RMESCAPE_ALLOC) {
5438                 size_t len = p - str;
5439                 size_t fulllen = len + strlen(p) + 1;
5440
5441                 if (flag & RMESCAPE_GROW) {
5442                         r = makestrspace(fulllen, expdest);
5443                 } else if (flag & RMESCAPE_HEAP) {
5444                         r = ckmalloc(fulllen);
5445                 } else {
5446                         r = stalloc(fulllen);
5447                 }
5448                 q = r;
5449                 if (len > 0) {
5450                         q = (char *)memcpy(q, str, len) + len;
5451                 }
5452         }
5453
5454         inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5455         globbing = flag & RMESCAPE_GLOB;
5456         protect_against_glob = globbing;
5457         while (*p) {
5458                 if (*p == CTLQUOTEMARK) {
5459 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5460 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5461 // Note: both inquotes and protect_against_glob only affect whether
5462 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5463                         inquotes = ~inquotes;
5464                         p++;
5465                         protect_against_glob = globbing;
5466                         continue;
5467                 }
5468                 if (*p == '\\') {
5469                         /* naked back slash */
5470                         protect_against_glob = 0;
5471                         goto copy;
5472                 }
5473                 if (*p == CTLESC) {
5474                         p++;
5475                         if (protect_against_glob && inquotes && *p != '/') {
5476                                 *q++ = '\\';
5477                         }
5478                 }
5479                 protect_against_glob = globbing;
5480  copy:
5481                 *q++ = *p++;
5482         }
5483         *q = '\0';
5484         if (flag & RMESCAPE_GROW) {
5485                 expdest = r;
5486                 STADJUST(q - r + 1, expdest);
5487         }
5488         return r;
5489 }
5490 #define pmatch(a, b) !fnmatch((a), (b), 0)
5491
5492 /*
5493  * Prepare a pattern for a expmeta (internal glob(3)) call.
5494  *
5495  * Returns an stalloced string.
5496  */
5497 static char *
5498 preglob(const char *pattern, int quoted, int flag)
5499 {
5500         flag |= RMESCAPE_GLOB;
5501         if (quoted) {
5502                 flag |= RMESCAPE_QUOTED;
5503         }
5504         return rmescapes((char *)pattern, flag);
5505 }
5506
5507 /*
5508  * Put a string on the stack.
5509  */
5510 static void
5511 memtodest(const char *p, size_t len, int syntax, int quotes)
5512 {
5513         char *q = expdest;
5514
5515         q = makestrspace(quotes ? len * 2 : len, q);
5516
5517         while (len--) {
5518                 int c = signed_char2int(*p++);
5519                 if (!c)
5520                         continue;
5521                 if (quotes) {
5522                         int n = SIT(c, syntax);
5523                         if (n == CCTL || n == CBACK)
5524                                 USTPUTC(CTLESC, q);
5525                 }
5526                 USTPUTC(c, q);
5527         }
5528
5529         expdest = q;
5530 }
5531
5532 static void
5533 strtodest(const char *p, int syntax, int quotes)
5534 {
5535         memtodest(p, strlen(p), syntax, quotes);
5536 }
5537
5538 /*
5539  * Record the fact that we have to scan this region of the
5540  * string for IFS characters.
5541  */
5542 static void
5543 recordregion(int start, int end, int nulonly)
5544 {
5545         struct ifsregion *ifsp;
5546
5547         if (ifslastp == NULL) {
5548                 ifsp = &ifsfirst;
5549         } else {
5550                 INT_OFF;
5551                 ifsp = ckzalloc(sizeof(*ifsp));
5552                 /*ifsp->next = NULL; - ckzalloc did it */
5553                 ifslastp->next = ifsp;
5554                 INT_ON;
5555         }
5556         ifslastp = ifsp;
5557         ifslastp->begoff = start;
5558         ifslastp->endoff = end;
5559         ifslastp->nulonly = nulonly;
5560 }
5561
5562 static void
5563 removerecordregions(int endoff)
5564 {
5565         if (ifslastp == NULL)
5566                 return;
5567
5568         if (ifsfirst.endoff > endoff) {
5569                 while (ifsfirst.next != NULL) {
5570                         struct ifsregion *ifsp;
5571                         INT_OFF;
5572                         ifsp = ifsfirst.next->next;
5573                         free(ifsfirst.next);
5574                         ifsfirst.next = ifsp;
5575                         INT_ON;
5576                 }
5577                 if (ifsfirst.begoff > endoff)
5578                         ifslastp = NULL;
5579                 else {
5580                         ifslastp = &ifsfirst;
5581                         ifsfirst.endoff = endoff;
5582                 }
5583                 return;
5584         }
5585
5586         ifslastp = &ifsfirst;
5587         while (ifslastp->next && ifslastp->next->begoff < endoff)
5588                 ifslastp=ifslastp->next;
5589         while (ifslastp->next != NULL) {
5590                 struct ifsregion *ifsp;
5591                 INT_OFF;
5592                 ifsp = ifslastp->next->next;
5593                 free(ifslastp->next);
5594                 ifslastp->next = ifsp;
5595                 INT_ON;
5596         }
5597         if (ifslastp->endoff > endoff)
5598                 ifslastp->endoff = endoff;
5599 }
5600
5601 static char *
5602 exptilde(char *startp, char *p, int flags)
5603 {
5604         char c;
5605         char *name;
5606         struct passwd *pw;
5607         const char *home;
5608         int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5609         int startloc;
5610
5611         name = p + 1;
5612
5613         while ((c = *++p) != '\0') {
5614                 switch (c) {
5615                 case CTLESC:
5616                         return startp;
5617                 case CTLQUOTEMARK:
5618                         return startp;
5619                 case ':':
5620                         if (flags & EXP_VARTILDE)
5621                                 goto done;
5622                         break;
5623                 case '/':
5624                 case CTLENDVAR:
5625                         goto done;
5626                 }
5627         }
5628  done:
5629         *p = '\0';
5630         if (*name == '\0') {
5631                 home = lookupvar(homestr);
5632         } else {
5633                 pw = getpwnam(name);
5634                 if (pw == NULL)
5635                         goto lose;
5636                 home = pw->pw_dir;
5637         }
5638         if (!home || !*home)
5639                 goto lose;
5640         *p = c;
5641         startloc = expdest - (char *)stackblock();
5642         strtodest(home, SQSYNTAX, quotes);
5643         recordregion(startloc, expdest - (char *)stackblock(), 0);
5644         return p;
5645  lose:
5646         *p = c;
5647         return startp;
5648 }
5649
5650 /*
5651  * Execute a command inside back quotes.  If it's a builtin command, we
5652  * want to save its output in a block obtained from malloc.  Otherwise
5653  * we fork off a subprocess and get the output of the command via a pipe.
5654  * Should be called with interrupts off.
5655  */
5656 struct backcmd {                /* result of evalbackcmd */
5657         int fd;                 /* file descriptor to read from */
5658         int nleft;              /* number of chars in buffer */
5659         char *buf;              /* buffer */
5660         struct job *jp;         /* job structure for command */
5661 };
5662
5663 /* These forward decls are needed to use "eval" code for backticks handling: */
5664 static uint8_t back_exitstatus; /* exit status of backquoted command */
5665 #define EV_EXIT 01              /* exit after evaluating tree */
5666 static void evaltree(union node *, int);
5667
5668 static void FAST_FUNC
5669 evalbackcmd(union node *n, struct backcmd *result)
5670 {
5671         int saveherefd;
5672
5673         result->fd = -1;
5674         result->buf = NULL;
5675         result->nleft = 0;
5676         result->jp = NULL;
5677         if (n == NULL)
5678                 goto out;
5679
5680         saveherefd = herefd;
5681         herefd = -1;
5682
5683         {
5684                 int pip[2];
5685                 struct job *jp;
5686
5687                 if (pipe(pip) < 0)
5688                         ash_msg_and_raise_error("pipe call failed");
5689                 jp = makejob(/*n,*/ 1);
5690                 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5691                         FORCE_INT_ON;
5692                         close(pip[0]);
5693                         if (pip[1] != 1) {
5694                                 /*close(1);*/
5695                                 copyfd(pip[1], 1 | COPYFD_EXACT);
5696                                 close(pip[1]);
5697                         }
5698                         eflag = 0;
5699                         evaltree(n, EV_EXIT); /* actually evaltreenr... */
5700                         /* NOTREACHED */
5701                 }
5702                 close(pip[1]);
5703                 result->fd = pip[0];
5704                 result->jp = jp;
5705         }
5706         herefd = saveherefd;
5707  out:
5708         TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5709                 result->fd, result->buf, result->nleft, result->jp));
5710 }
5711
5712 /*
5713  * Expand stuff in backwards quotes.
5714  */
5715 static void
5716 expbackq(union node *cmd, int quoted, int quotes)
5717 {
5718         struct backcmd in;
5719         int i;
5720         char buf[128];
5721         char *p;
5722         char *dest;
5723         int startloc;
5724         int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5725         struct stackmark smark;
5726
5727         INT_OFF;
5728         setstackmark(&smark);
5729         dest = expdest;
5730         startloc = dest - (char *)stackblock();
5731         grabstackstr(dest);
5732         evalbackcmd(cmd, &in);
5733         popstackmark(&smark);
5734
5735         p = in.buf;
5736         i = in.nleft;
5737         if (i == 0)
5738                 goto read;
5739         for (;;) {
5740                 memtodest(p, i, syntax, quotes);
5741  read:
5742                 if (in.fd < 0)
5743                         break;
5744                 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5745                 TRACE(("expbackq: read returns %d\n", i));
5746                 if (i <= 0)
5747                         break;
5748                 p = buf;
5749         }
5750
5751         free(in.buf);
5752         if (in.fd >= 0) {
5753                 close(in.fd);
5754                 back_exitstatus = waitforjob(in.jp);
5755         }
5756         INT_ON;
5757
5758         /* Eat all trailing newlines */
5759         dest = expdest;
5760         for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5761                 STUNPUTC(dest);
5762         expdest = dest;
5763
5764         if (quoted == 0)
5765                 recordregion(startloc, dest - (char *)stackblock(), 0);
5766         TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5767                 (dest - (char *)stackblock()) - startloc,
5768                 (dest - (char *)stackblock()) - startloc,
5769                 stackblock() + startloc));
5770 }
5771
5772 #if ENABLE_SH_MATH_SUPPORT
5773 /*
5774  * Expand arithmetic expression.  Backup to start of expression,
5775  * evaluate, place result in (backed up) result, adjust string position.
5776  */
5777 static void
5778 expari(int quotes)
5779 {
5780         char *p, *start;
5781         int begoff;
5782         int flag;
5783         int len;
5784
5785         /* ifsfree(); */
5786
5787         /*
5788          * This routine is slightly over-complicated for
5789          * efficiency.  Next we scan backwards looking for the
5790          * start of arithmetic.
5791          */
5792         start = stackblock();
5793         p = expdest - 1;
5794         *p = '\0';
5795         p--;
5796         do {
5797                 int esc;
5798
5799                 while (*p != CTLARI) {
5800                         p--;
5801 #if DEBUG
5802                         if (p < start) {
5803                                 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5804                         }
5805 #endif
5806                 }
5807
5808                 esc = esclen(start, p);
5809                 if (!(esc % 2)) {
5810                         break;
5811                 }
5812
5813                 p -= esc + 1;
5814         } while (1);
5815
5816         begoff = p - start;
5817
5818         removerecordregions(begoff);
5819
5820         flag = p[1];
5821
5822         expdest = p;
5823
5824         if (quotes)
5825                 rmescapes(p + 2, 0);
5826
5827         len = cvtnum(ash_arith(p + 2));
5828
5829         if (flag != '"')
5830                 recordregion(begoff, begoff + len, 0);
5831 }
5832 #endif
5833
5834 /* argstr needs it */
5835 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5836
5837 /*
5838  * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
5839  * characters to allow for further processing.  Otherwise treat
5840  * $@ like $* since no splitting will be performed.
5841  *
5842  * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5843  * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5844  * for correct expansion of "B=$A" word.
5845  */
5846 static void
5847 argstr(char *p, int flags, struct strlist *var_str_list)
5848 {
5849         static const char spclchars[] ALIGN1 = {
5850                 '=',
5851                 ':',
5852                 CTLQUOTEMARK,
5853                 CTLENDVAR,
5854                 CTLESC,
5855                 CTLVAR,
5856                 CTLBACKQ,
5857                 CTLBACKQ | CTLQUOTE,
5858 #if ENABLE_SH_MATH_SUPPORT
5859                 CTLENDARI,
5860 #endif
5861                 0
5862         };
5863         const char *reject = spclchars;
5864         int c;
5865         int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5866         int breakall = flags & EXP_WORD;
5867         int inquotes;
5868         size_t length;
5869         int startloc;
5870
5871         if (!(flags & EXP_VARTILDE)) {
5872                 reject += 2;
5873         } else if (flags & EXP_VARTILDE2) {
5874                 reject++;
5875         }
5876         inquotes = 0;
5877         length = 0;
5878         if (flags & EXP_TILDE) {
5879                 char *q;
5880
5881                 flags &= ~EXP_TILDE;
5882  tilde:
5883                 q = p;
5884                 if (*q == CTLESC && (flags & EXP_QWORD))
5885                         q++;
5886                 if (*q == '~')
5887                         p = exptilde(p, q, flags);
5888         }
5889  start:
5890         startloc = expdest - (char *)stackblock();
5891         for (;;) {
5892                 length += strcspn(p + length, reject);
5893                 c = (unsigned char) p[length];
5894                 if (c) {
5895                         if (!(c & 0x80)
5896 #if ENABLE_SH_MATH_SUPPORT
5897                          || c == CTLENDARI
5898 #endif
5899                         ) {
5900                                 /* c == '=' || c == ':' || c == CTLENDARI */
5901                                 length++;
5902                         }
5903                 }
5904                 if (length > 0) {
5905                         int newloc;
5906                         expdest = stack_nputstr(p, length, expdest);
5907                         newloc = expdest - (char *)stackblock();
5908                         if (breakall && !inquotes && newloc > startloc) {
5909                                 recordregion(startloc, newloc, 0);
5910                         }
5911                         startloc = newloc;
5912                 }
5913                 p += length + 1;
5914                 length = 0;
5915
5916                 switch (c) {
5917                 case '\0':
5918                         goto breakloop;
5919                 case '=':
5920                         if (flags & EXP_VARTILDE2) {
5921                                 p--;
5922                                 continue;
5923                         }
5924                         flags |= EXP_VARTILDE2;
5925                         reject++;
5926                         /* fall through */
5927                 case ':':
5928                         /*
5929                          * sort of a hack - expand tildes in variable
5930                          * assignments (after the first '=' and after ':'s).
5931                          */
5932                         if (*--p == '~') {
5933                                 goto tilde;
5934                         }
5935                         continue;
5936                 }
5937
5938                 switch (c) {
5939                 case CTLENDVAR: /* ??? */
5940                         goto breakloop;
5941                 case CTLQUOTEMARK:
5942                         /* "$@" syntax adherence hack */
5943                         if (!inquotes
5944                          && memcmp(p, dolatstr, 4) == 0
5945                          && (  p[4] == CTLQUOTEMARK
5946                             || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5947                             )
5948                         ) {
5949                                 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5950                                 goto start;
5951                         }
5952                         inquotes = !inquotes;
5953  addquote:
5954                         if (quotes) {
5955                                 p--;
5956                                 length++;
5957                                 startloc++;
5958                         }
5959                         break;
5960                 case CTLESC:
5961                         startloc++;
5962                         length++;
5963                         goto addquote;
5964                 case CTLVAR:
5965                         p = evalvar(p, flags, var_str_list);
5966                         goto start;
5967                 case CTLBACKQ:
5968                         c = '\0';
5969                 case CTLBACKQ|CTLQUOTE:
5970                         expbackq(argbackq->n, c, quotes);
5971                         argbackq = argbackq->next;
5972                         goto start;
5973 #if ENABLE_SH_MATH_SUPPORT
5974                 case CTLENDARI:
5975                         p--;
5976                         expari(quotes);
5977                         goto start;
5978 #endif
5979                 }
5980         }
5981  breakloop:
5982         ;
5983 }
5984
5985 static char *
5986 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5987         int zero)
5988 {
5989 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5990 // as part of a larger change when he added support for ${var/a/b}.
5991 // However, it broke # and % operators:
5992 //
5993 //var=ababcdcd
5994 //                 ok       bad
5995 //echo ${var#ab}   abcdcd   abcdcd
5996 //echo ${var##ab}  abcdcd   abcdcd
5997 //echo ${var#a*b}  abcdcd   ababcdcd  (!)
5998 //echo ${var##a*b} cdcd     cdcd
5999 //echo ${var#?}    babcdcd  ababcdcd  (!)
6000 //echo ${var##?}   babcdcd  babcdcd
6001 //echo ${var#*}    ababcdcd babcdcd   (!)
6002 //echo ${var##*}
6003 //echo ${var%cd}   ababcd   ababcd
6004 //echo ${var%%cd}  ababcd   abab      (!)
6005 //echo ${var%c*d}  ababcd   ababcd
6006 //echo ${var%%c*d} abab     ababcdcd  (!)
6007 //echo ${var%?}    ababcdc  ababcdc
6008 //echo ${var%%?}   ababcdc  ababcdcd  (!)
6009 //echo ${var%*}    ababcdcd ababcdcd
6010 //echo ${var%%*}
6011 //
6012 // Commenting it back out helped. Remove it completely if it really
6013 // is not needed.
6014
6015         char *loc, *loc2; //, *full;
6016         char c;
6017
6018         loc = startp;
6019         loc2 = rmesc;
6020         do {
6021                 int match; // = strlen(str);
6022                 const char *s = loc2;
6023
6024                 c = *loc2;
6025                 if (zero) {
6026                         *loc2 = '\0';
6027                         s = rmesc;
6028                 }
6029                 match = pmatch(str, s); // this line was deleted
6030
6031 //              // chop off end if its '*'
6032 //              full = strrchr(str, '*');
6033 //              if (full && full != str)
6034 //                      match--;
6035 //
6036 //              // If str starts with '*' replace with s.
6037 //              if ((*str == '*') && strlen(s) >= match) {
6038 //                      full = xstrdup(s);
6039 //                      strncpy(full+strlen(s)-match+1, str+1, match-1);
6040 //              } else
6041 //                      full = xstrndup(str, match);
6042 //              match = strncmp(s, full, strlen(full));
6043 //              free(full);
6044 //
6045                 *loc2 = c;
6046                 if (match) // if (!match)
6047                         return loc;
6048                 if (quotes && *loc == CTLESC)
6049                         loc++;
6050                 loc++;
6051                 loc2++;
6052         } while (c);
6053         return 0;
6054 }
6055
6056 static char *
6057 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6058         int zero)
6059 {
6060         int esc = 0;
6061         char *loc;
6062         char *loc2;
6063
6064         for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6065                 int match;
6066                 char c = *loc2;
6067                 const char *s = loc2;
6068                 if (zero) {
6069                         *loc2 = '\0';
6070                         s = rmesc;
6071                 }
6072                 match = pmatch(str, s);
6073                 *loc2 = c;
6074                 if (match)
6075                         return loc;
6076                 loc--;
6077                 if (quotes) {
6078                         if (--esc < 0) {
6079                                 esc = esclen(startp, loc);
6080                         }
6081                         if (esc % 2) {
6082                                 esc--;
6083                                 loc--;
6084                         }
6085                 }
6086         }
6087         return 0;
6088 }
6089
6090 static void varunset(const char *, const char *, const char *, int) NORETURN;
6091 static void
6092 varunset(const char *end, const char *var, const char *umsg, int varflags)
6093 {
6094         const char *msg;
6095         const char *tail;
6096
6097         tail = nullstr;
6098         msg = "parameter not set";
6099         if (umsg) {
6100                 if (*end == CTLENDVAR) {
6101                         if (varflags & VSNUL)
6102                                 tail = " or null";
6103                 } else {
6104                         msg = umsg;
6105                 }
6106         }
6107         ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6108 }
6109
6110 #if ENABLE_ASH_BASH_COMPAT
6111 static char *
6112 parse_sub_pattern(char *arg, int inquotes)
6113 {
6114         char *idx, *repl = NULL;
6115         unsigned char c;
6116
6117         idx = arg;
6118         while (1) {
6119                 c = *arg;
6120                 if (!c)
6121                         break;
6122                 if (c == '/') {
6123                         /* Only the first '/' seen is our separator */
6124                         if (!repl) {
6125                                 repl = idx + 1;
6126                                 c = '\0';
6127                         }
6128                 }
6129                 *idx++ = c;
6130                 if (!inquotes && c == '\\' && arg[1] == '\\')
6131                         arg++; /* skip both \\, not just first one */
6132                 arg++;
6133         }
6134         *idx = c; /* NUL */
6135
6136         return repl;
6137 }
6138 #endif /* ENABLE_ASH_BASH_COMPAT */
6139
6140 static const char *
6141 subevalvar(char *p, char *str, int strloc, int subtype,
6142                 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6143 {
6144         struct nodelist *saveargbackq = argbackq;
6145         char *startp;
6146         char *loc;
6147         char *rmesc, *rmescend;
6148         IF_ASH_BASH_COMPAT(char *repl = NULL;)
6149         IF_ASH_BASH_COMPAT(char null = '\0';)
6150         IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6151         int saveherefd = herefd;
6152         int amount, workloc, resetloc;
6153         int zero;
6154         char *(*scan)(char*, char*, char*, char*, int, int);
6155
6156         herefd = -1;
6157         argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6158                         var_str_list);
6159         STPUTC('\0', expdest);
6160         herefd = saveherefd;
6161         argbackq = saveargbackq;
6162         startp = (char *)stackblock() + startloc;
6163
6164         switch (subtype) {
6165         case VSASSIGN:
6166                 setvar(str, startp, 0);
6167                 amount = startp - expdest;
6168                 STADJUST(amount, expdest);
6169                 return startp;
6170
6171 #if ENABLE_ASH_BASH_COMPAT
6172         case VSSUBSTR:
6173                 loc = str = stackblock() + strloc;
6174                 /* Read POS in ${var:POS:LEN} */
6175                 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6176                 len = str - startp - 1;
6177
6178                 /* *loc != '\0', guaranteed by parser */
6179                 if (quotes) {
6180                         char *ptr;
6181
6182                         /* Adjust the length by the number of escapes */
6183                         for (ptr = startp; ptr < (str - 1); ptr++) {
6184                                 if (*ptr == CTLESC) {
6185                                         len--;
6186                                         ptr++;
6187                                 }
6188                         }
6189                 }
6190                 orig_len = len;
6191
6192                 if (*loc++ == ':') {
6193                         /* ${var::LEN} */
6194                         len = number(loc);
6195                 } else {
6196                         /* Skip POS in ${var:POS:LEN} */
6197                         len = orig_len;
6198                         while (*loc && *loc != ':') {
6199                                 /* TODO?
6200                                  * bash complains on: var=qwe; echo ${var:1a:123}
6201                                 if (!isdigit(*loc))
6202                                         ash_msg_and_raise_error(msg_illnum, str);
6203                                  */
6204                                 loc++;
6205                         }
6206                         if (*loc++ == ':') {
6207                                 len = number(loc);
6208                         }
6209                 }
6210                 if (pos >= orig_len) {
6211                         pos = 0;
6212                         len = 0;
6213                 }
6214                 if (len > (orig_len - pos))
6215                         len = orig_len - pos;
6216
6217                 for (str = startp; pos; str++, pos--) {
6218                         if (quotes && *str == CTLESC)
6219                                 str++;
6220                 }
6221                 for (loc = startp; len; len--) {
6222                         if (quotes && *str == CTLESC)
6223                                 *loc++ = *str++;
6224                         *loc++ = *str++;
6225                 }
6226                 *loc = '\0';
6227                 amount = loc - expdest;
6228                 STADJUST(amount, expdest);
6229                 return loc;
6230 #endif
6231
6232         case VSQUESTION:
6233                 varunset(p, str, startp, varflags);
6234                 /* NOTREACHED */
6235         }
6236         resetloc = expdest - (char *)stackblock();
6237
6238         /* We'll comeback here if we grow the stack while handling
6239          * a VSREPLACE or VSREPLACEALL, since our pointers into the
6240          * stack will need rebasing, and we'll need to remove our work
6241          * areas each time
6242          */
6243  IF_ASH_BASH_COMPAT(restart:)
6244
6245         amount = expdest - ((char *)stackblock() + resetloc);
6246         STADJUST(-amount, expdest);
6247         startp = (char *)stackblock() + startloc;
6248
6249         rmesc = startp;
6250         rmescend = (char *)stackblock() + strloc;
6251         if (quotes) {
6252                 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6253                 if (rmesc != startp) {
6254                         rmescend = expdest;
6255                         startp = (char *)stackblock() + startloc;
6256                 }
6257         }
6258         rmescend--;
6259         str = (char *)stackblock() + strloc;
6260         preglob(str, varflags & VSQUOTE, 0);
6261         workloc = expdest - (char *)stackblock();
6262
6263 #if ENABLE_ASH_BASH_COMPAT
6264         if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6265                 char *idx, *end, *restart_detect;
6266
6267                 if (!repl) {
6268                         repl = parse_sub_pattern(str, varflags & VSQUOTE);
6269                         if (!repl)
6270                                 repl = &null;
6271                 }
6272
6273                 /* If there's no pattern to match, return the expansion unmolested */
6274                 if (*str == '\0')
6275                         return 0;
6276
6277                 len = 0;
6278                 idx = startp;
6279                 end = str - 1;
6280                 while (idx < end) {
6281                         loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6282                         if (!loc) {
6283                                 /* No match, advance */
6284                                 restart_detect = stackblock();
6285                                 STPUTC(*idx, expdest);
6286                                 if (quotes && *idx == CTLESC) {
6287                                         idx++;
6288                                         len++;
6289                                         STPUTC(*idx, expdest);
6290                                 }
6291                                 if (stackblock() != restart_detect)
6292                                         goto restart;
6293                                 idx++;
6294                                 len++;
6295                                 rmesc++;
6296                                 continue;
6297                         }
6298
6299                         if (subtype == VSREPLACEALL) {
6300                                 while (idx < loc) {
6301                                         if (quotes && *idx == CTLESC)
6302                                                 idx++;
6303                                         idx++;
6304                                         rmesc++;
6305                                 }
6306                         } else {
6307                                 idx = loc;
6308                         }
6309
6310                         for (loc = repl; *loc; loc++) {
6311                                 restart_detect = stackblock();
6312                                 STPUTC(*loc, expdest);
6313                                 if (stackblock() != restart_detect)
6314                                         goto restart;
6315                                 len++;
6316                         }
6317
6318                         if (subtype == VSREPLACE) {
6319                                 while (*idx) {
6320                                         restart_detect = stackblock();
6321                                         STPUTC(*idx, expdest);
6322                                         if (stackblock() != restart_detect)
6323                                                 goto restart;
6324                                         len++;
6325                                         idx++;
6326                                 }
6327                                 break;
6328                         }
6329                 }
6330
6331                 /* We've put the replaced text into a buffer at workloc, now
6332                  * move it to the right place and adjust the stack.
6333                  */
6334                 startp = stackblock() + startloc;
6335                 STPUTC('\0', expdest);
6336                 memmove(startp, stackblock() + workloc, len);
6337                 startp[len++] = '\0';
6338                 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6339                 STADJUST(-amount, expdest);
6340                 return startp;
6341         }
6342 #endif /* ENABLE_ASH_BASH_COMPAT */
6343
6344         subtype -= VSTRIMRIGHT;
6345 #if DEBUG
6346         if (subtype < 0 || subtype > 7)
6347                 abort();
6348 #endif
6349         /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6350         zero = subtype >> 1;
6351         /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6352         scan = (subtype & 1) ^ zero ? scanleft : scanright;
6353
6354         loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6355         if (loc) {
6356                 if (zero) {
6357                         memmove(startp, loc, str - loc);
6358                         loc = startp + (str - loc) - 1;
6359                 }
6360                 *loc = '\0';
6361                 amount = loc - expdest;
6362                 STADJUST(amount, expdest);
6363         }
6364         return loc;
6365 }
6366
6367 /*
6368  * Add the value of a specialized variable to the stack string.
6369  */
6370 static ssize_t
6371 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6372 {
6373         int num;
6374         const char *p;
6375         int i;
6376         int sep = 0;
6377         int sepq = 0;
6378         ssize_t len = 0;
6379         char **ap;
6380         int syntax;
6381         int quoted = varflags & VSQUOTE;
6382         int subtype = varflags & VSTYPE;
6383         int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6384
6385         if (quoted && (flags & EXP_FULL))
6386                 sep = 1 << CHAR_BIT;
6387
6388         syntax = quoted ? DQSYNTAX : BASESYNTAX;
6389         switch (*name) {
6390         case '$':
6391                 num = rootpid;
6392                 goto numvar;
6393         case '?':
6394                 num = exitstatus;
6395                 goto numvar;
6396         case '#':
6397                 num = shellparam.nparam;
6398                 goto numvar;
6399         case '!':
6400                 num = backgndpid;
6401                 if (num == 0)
6402                         return -1;
6403  numvar:
6404                 len = cvtnum(num);
6405                 break;
6406         case '-':
6407                 expdest = makestrspace(NOPTS, expdest);
6408                 for (i = NOPTS - 1; i >= 0; i--) {
6409                         if (optlist[i]) {
6410                                 USTPUTC(optletters(i), expdest);
6411                                 len++;
6412                         }
6413                 }
6414                 break;
6415         case '@':
6416                 if (sep)
6417                         goto param;
6418                 /* fall through */
6419         case '*':
6420                 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6421                 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6422                         sepq = 1;
6423  param:
6424                 ap = shellparam.p;
6425                 if (!ap)
6426                         return -1;
6427                 while ((p = *ap++) != NULL) {
6428                         size_t partlen;
6429
6430                         partlen = strlen(p);
6431                         len += partlen;
6432
6433                         if (!(subtype == VSPLUS || subtype == VSLENGTH))
6434                                 memtodest(p, partlen, syntax, quotes);
6435
6436                         if (*ap && sep) {
6437                                 char *q;
6438
6439                                 len++;
6440                                 if (subtype == VSPLUS || subtype == VSLENGTH) {
6441                                         continue;
6442                                 }
6443                                 q = expdest;
6444                                 if (sepq)
6445                                         STPUTC(CTLESC, q);
6446                                 STPUTC(sep, q);
6447                                 expdest = q;
6448                         }
6449                 }
6450                 return len;
6451         case '0':
6452         case '1':
6453         case '2':
6454         case '3':
6455         case '4':
6456         case '5':
6457         case '6':
6458         case '7':
6459         case '8':
6460         case '9':
6461                 num = atoi(name); /* number(name) fails on ${N#str} etc */
6462                 if (num < 0 || num > shellparam.nparam)
6463                         return -1;
6464                 p = num ? shellparam.p[num - 1] : arg0;
6465                 goto value;
6466         default:
6467                 /* NB: name has form "VAR=..." */
6468
6469                 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6470                  * which should be considered before we check variables. */
6471                 if (var_str_list) {
6472                         unsigned name_len = (strchrnul(name, '=') - name) + 1;
6473                         p = NULL;
6474                         do {
6475                                 char *str, *eq;
6476                                 str = var_str_list->text;
6477                                 eq = strchr(str, '=');
6478                                 if (!eq) /* stop at first non-assignment */
6479                                         break;
6480                                 eq++;
6481                                 if (name_len == (unsigned)(eq - str)
6482                                  && strncmp(str, name, name_len) == 0) {
6483                                         p = eq;
6484                                         /* goto value; - WRONG! */
6485                                         /* think "A=1 A=2 B=$A" */
6486                                 }
6487                                 var_str_list = var_str_list->next;
6488                         } while (var_str_list);
6489                         if (p)
6490                                 goto value;
6491                 }
6492                 p = lookupvar(name);
6493  value:
6494                 if (!p)
6495                         return -1;
6496
6497                 len = strlen(p);
6498                 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6499                         memtodest(p, len, syntax, quotes);
6500                 return len;
6501         }
6502
6503         if (subtype == VSPLUS || subtype == VSLENGTH)
6504                 STADJUST(-len, expdest);
6505         return len;
6506 }
6507
6508 /*
6509  * Expand a variable, and return a pointer to the next character in the
6510  * input string.
6511  */
6512 static char *
6513 evalvar(char *p, int flags, struct strlist *var_str_list)
6514 {
6515         char varflags;
6516         char subtype;
6517         char quoted;
6518         char easy;
6519         char *var;
6520         int patloc;
6521         int startloc;
6522         ssize_t varlen;
6523
6524         varflags = (unsigned char) *p++;
6525         subtype = varflags & VSTYPE;
6526         quoted = varflags & VSQUOTE;
6527         var = p;
6528         easy = (!quoted || (*var == '@' && shellparam.nparam));
6529         startloc = expdest - (char *)stackblock();
6530         p = strchr(p, '=') + 1;
6531
6532  again:
6533         varlen = varvalue(var, varflags, flags, var_str_list);
6534         if (varflags & VSNUL)
6535                 varlen--;
6536
6537         if (subtype == VSPLUS) {
6538                 varlen = -1 - varlen;
6539                 goto vsplus;
6540         }
6541
6542         if (subtype == VSMINUS) {
6543  vsplus:
6544                 if (varlen < 0) {
6545                         argstr(
6546                                 p, flags | EXP_TILDE |
6547                                         (quoted ? EXP_QWORD : EXP_WORD),
6548                                 var_str_list
6549                         );
6550                         goto end;
6551                 }
6552                 if (easy)
6553                         goto record;
6554                 goto end;
6555         }
6556
6557         if (subtype == VSASSIGN || subtype == VSQUESTION) {
6558                 if (varlen < 0) {
6559                         if (subevalvar(p, var, /* strloc: */ 0,
6560                                         subtype, startloc, varflags,
6561                                         /* quotes: */ 0,
6562                                         var_str_list)
6563                         ) {
6564                                 varflags &= ~VSNUL;
6565                                 /*
6566                                  * Remove any recorded regions beyond
6567                                  * start of variable
6568                                  */
6569                                 removerecordregions(startloc);
6570                                 goto again;
6571                         }
6572                         goto end;
6573                 }
6574                 if (easy)
6575                         goto record;
6576                 goto end;
6577         }
6578
6579         if (varlen < 0 && uflag)
6580                 varunset(p, var, 0, 0);
6581
6582         if (subtype == VSLENGTH) {
6583                 cvtnum(varlen > 0 ? varlen : 0);
6584                 goto record;
6585         }
6586
6587         if (subtype == VSNORMAL) {
6588                 if (easy)
6589                         goto record;
6590                 goto end;
6591         }
6592
6593 #if DEBUG
6594         switch (subtype) {
6595         case VSTRIMLEFT:
6596         case VSTRIMLEFTMAX:
6597         case VSTRIMRIGHT:
6598         case VSTRIMRIGHTMAX:
6599 #if ENABLE_ASH_BASH_COMPAT
6600         case VSSUBSTR:
6601         case VSREPLACE:
6602         case VSREPLACEALL:
6603 #endif
6604                 break;
6605         default:
6606                 abort();
6607         }
6608 #endif
6609
6610         if (varlen >= 0) {
6611                 /*
6612                  * Terminate the string and start recording the pattern
6613                  * right after it
6614                  */
6615                 STPUTC('\0', expdest);
6616                 patloc = expdest - (char *)stackblock();
6617                 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6618                                 startloc, varflags,
6619 //TODO: | EXP_REDIR too? All other such places do it too
6620                                 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6621                                 var_str_list)
6622                 ) {
6623                         int amount = expdest - (
6624                                 (char *)stackblock() + patloc - 1
6625                         );
6626                         STADJUST(-amount, expdest);
6627                 }
6628                 /* Remove any recorded regions beyond start of variable */
6629                 removerecordregions(startloc);
6630  record:
6631                 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6632         }
6633
6634  end:
6635         if (subtype != VSNORMAL) {      /* skip to end of alternative */
6636                 int nesting = 1;
6637                 for (;;) {
6638                         char c = *p++;
6639                         if (c == CTLESC)
6640                                 p++;
6641                         else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6642                                 if (varlen >= 0)
6643                                         argbackq = argbackq->next;
6644                         } else if (c == CTLVAR) {
6645                                 if ((*p++ & VSTYPE) != VSNORMAL)
6646                                         nesting++;
6647                         } else if (c == CTLENDVAR) {
6648                                 if (--nesting == 0)
6649                                         break;
6650                         }
6651                 }
6652         }
6653         return p;
6654 }
6655
6656 /*
6657  * Break the argument string into pieces based upon IFS and add the
6658  * strings to the argument list.  The regions of the string to be
6659  * searched for IFS characters have been stored by recordregion.
6660  */
6661 static void
6662 ifsbreakup(char *string, struct arglist *arglist)
6663 {
6664         struct ifsregion *ifsp;
6665         struct strlist *sp;
6666         char *start;
6667         char *p;
6668         char *q;
6669         const char *ifs, *realifs;
6670         int ifsspc;
6671         int nulonly;
6672
6673         start = string;
6674         if (ifslastp != NULL) {
6675                 ifsspc = 0;
6676                 nulonly = 0;
6677                 realifs = ifsset() ? ifsval() : defifs;
6678                 ifsp = &ifsfirst;
6679                 do {
6680                         p = string + ifsp->begoff;
6681                         nulonly = ifsp->nulonly;
6682                         ifs = nulonly ? nullstr : realifs;
6683                         ifsspc = 0;
6684                         while (p < string + ifsp->endoff) {
6685                                 q = p;
6686                                 if (*p == CTLESC)
6687                                         p++;
6688                                 if (!strchr(ifs, *p)) {
6689                                         p++;
6690                                         continue;
6691                                 }
6692                                 if (!nulonly)
6693                                         ifsspc = (strchr(defifs, *p) != NULL);
6694                                 /* Ignore IFS whitespace at start */
6695                                 if (q == start && ifsspc) {
6696                                         p++;
6697                                         start = p;
6698                                         continue;
6699                                 }
6700                                 *q = '\0';
6701                                 sp = stzalloc(sizeof(*sp));
6702                                 sp->text = start;
6703                                 *arglist->lastp = sp;
6704                                 arglist->lastp = &sp->next;
6705                                 p++;
6706                                 if (!nulonly) {
6707                                         for (;;) {
6708                                                 if (p >= string + ifsp->endoff) {
6709                                                         break;
6710                                                 }
6711                                                 q = p;
6712                                                 if (*p == CTLESC)
6713                                                         p++;
6714                                                 if (strchr(ifs, *p) == NULL) {
6715                                                         p = q;
6716                                                         break;
6717                                                 }
6718                                                 if (strchr(defifs, *p) == NULL) {
6719                                                         if (ifsspc) {
6720                                                                 p++;
6721                                                                 ifsspc = 0;
6722                                                         } else {
6723                                                                 p = q;
6724                                                                 break;
6725                                                         }
6726                                                 } else
6727                                                         p++;
6728                                         }
6729                                 }
6730                                 start = p;
6731                         } /* while */
6732                         ifsp = ifsp->next;
6733                 } while (ifsp != NULL);
6734                 if (nulonly)
6735                         goto add;
6736         }
6737
6738         if (!*start)
6739                 return;
6740
6741  add:
6742         sp = stzalloc(sizeof(*sp));
6743         sp->text = start;
6744         *arglist->lastp = sp;
6745         arglist->lastp = &sp->next;
6746 }
6747
6748 static void
6749 ifsfree(void)
6750 {
6751         struct ifsregion *p;
6752
6753         INT_OFF;
6754         p = ifsfirst.next;
6755         do {
6756                 struct ifsregion *ifsp;
6757                 ifsp = p->next;
6758                 free(p);
6759                 p = ifsp;
6760         } while (p);
6761         ifslastp = NULL;
6762         ifsfirst.next = NULL;
6763         INT_ON;
6764 }
6765
6766 /*
6767  * Add a file name to the list.
6768  */
6769 static void
6770 addfname(const char *name)
6771 {
6772         struct strlist *sp;
6773
6774         sp = stzalloc(sizeof(*sp));
6775         sp->text = ststrdup(name);
6776         *exparg.lastp = sp;
6777         exparg.lastp = &sp->next;
6778 }
6779
6780 static char *expdir;
6781
6782 /*
6783  * Do metacharacter (i.e. *, ?, [...]) expansion.
6784  */
6785 static void
6786 expmeta(char *enddir, char *name)
6787 {
6788         char *p;
6789         const char *cp;
6790         char *start;
6791         char *endname;
6792         int metaflag;
6793         struct stat statb;
6794         DIR *dirp;
6795         struct dirent *dp;
6796         int atend;
6797         int matchdot;
6798
6799         metaflag = 0;
6800         start = name;
6801         for (p = name; *p; p++) {
6802                 if (*p == '*' || *p == '?')
6803                         metaflag = 1;
6804                 else if (*p == '[') {
6805                         char *q = p + 1;
6806                         if (*q == '!')
6807                                 q++;
6808                         for (;;) {
6809                                 if (*q == '\\')
6810                                         q++;
6811                                 if (*q == '/' || *q == '\0')
6812                                         break;
6813                                 if (*++q == ']') {
6814                                         metaflag = 1;
6815                                         break;
6816                                 }
6817                         }
6818                 } else if (*p == '\\')
6819                         p++;
6820                 else if (*p == '/') {
6821                         if (metaflag)
6822                                 goto out;
6823                         start = p + 1;
6824                 }
6825         }
6826  out:
6827         if (metaflag == 0) {    /* we've reached the end of the file name */
6828                 if (enddir != expdir)
6829                         metaflag++;
6830                 p = name;
6831                 do {
6832                         if (*p == '\\')
6833                                 p++;
6834                         *enddir++ = *p;
6835                 } while (*p++);
6836                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6837                         addfname(expdir);
6838                 return;
6839         }
6840         endname = p;
6841         if (name < start) {
6842                 p = name;
6843                 do {
6844                         if (*p == '\\')
6845                                 p++;
6846                         *enddir++ = *p++;
6847                 } while (p < start);
6848         }
6849         if (enddir == expdir) {
6850                 cp = ".";
6851         } else if (enddir == expdir + 1 && *expdir == '/') {
6852                 cp = "/";
6853         } else {
6854                 cp = expdir;
6855                 enddir[-1] = '\0';
6856         }
6857         dirp = opendir(cp);
6858         if (dirp == NULL)
6859                 return;
6860         if (enddir != expdir)
6861                 enddir[-1] = '/';
6862         if (*endname == 0) {
6863                 atend = 1;
6864         } else {
6865                 atend = 0;
6866                 *endname++ = '\0';
6867         }
6868         matchdot = 0;
6869         p = start;
6870         if (*p == '\\')
6871                 p++;
6872         if (*p == '.')
6873                 matchdot++;
6874         while (!pending_int && (dp = readdir(dirp)) != NULL) {
6875                 if (dp->d_name[0] == '.' && !matchdot)
6876                         continue;
6877                 if (pmatch(start, dp->d_name)) {
6878                         if (atend) {
6879                                 strcpy(enddir, dp->d_name);
6880                                 addfname(expdir);
6881                         } else {
6882                                 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6883                                         continue;
6884                                 p[-1] = '/';
6885                                 expmeta(p, endname);
6886                         }
6887                 }
6888         }
6889         closedir(dirp);
6890         if (!atend)
6891                 endname[-1] = '/';
6892 }
6893
6894 static struct strlist *
6895 msort(struct strlist *list, int len)
6896 {
6897         struct strlist *p, *q = NULL;
6898         struct strlist **lpp;
6899         int half;
6900         int n;
6901
6902         if (len <= 1)
6903                 return list;
6904         half = len >> 1;
6905         p = list;
6906         for (n = half; --n >= 0;) {
6907                 q = p;
6908                 p = p->next;
6909         }
6910         q->next = NULL;                 /* terminate first half of list */
6911         q = msort(list, half);          /* sort first half of list */
6912         p = msort(p, len - half);               /* sort second half */
6913         lpp = &list;
6914         for (;;) {
6915 #if ENABLE_LOCALE_SUPPORT
6916                 if (strcoll(p->text, q->text) < 0)
6917 #else
6918                 if (strcmp(p->text, q->text) < 0)
6919 #endif
6920                                                 {
6921                         *lpp = p;
6922                         lpp = &p->next;
6923                         p = *lpp;
6924                         if (p == NULL) {
6925                                 *lpp = q;
6926                                 break;
6927                         }
6928                 } else {
6929                         *lpp = q;
6930                         lpp = &q->next;
6931                         q = *lpp;
6932                         if (q == NULL) {
6933                                 *lpp = p;
6934                                 break;
6935                         }
6936                 }
6937         }
6938         return list;
6939 }
6940
6941 /*
6942  * Sort the results of file name expansion.  It calculates the number of
6943  * strings to sort and then calls msort (short for merge sort) to do the
6944  * work.
6945  */
6946 static struct strlist *
6947 expsort(struct strlist *str)
6948 {
6949         int len;
6950         struct strlist *sp;
6951
6952         len = 0;
6953         for (sp = str; sp; sp = sp->next)
6954                 len++;
6955         return msort(str, len);
6956 }
6957
6958 static void
6959 expandmeta(struct strlist *str /*, int flag*/)
6960 {
6961         static const char metachars[] ALIGN1 = {
6962                 '*', '?', '[', 0
6963         };
6964         /* TODO - EXP_REDIR */
6965
6966         while (str) {
6967                 struct strlist **savelastp;
6968                 struct strlist *sp;
6969                 char *p;
6970
6971                 if (fflag)
6972                         goto nometa;
6973                 if (!strpbrk(str->text, metachars))
6974                         goto nometa;
6975                 savelastp = exparg.lastp;
6976
6977                 INT_OFF;
6978                 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6979                 {
6980                         int i = strlen(str->text);
6981                         expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6982                 }
6983
6984                 expmeta(expdir, p);
6985                 free(expdir);
6986                 if (p != str->text)
6987                         free(p);
6988                 INT_ON;
6989                 if (exparg.lastp == savelastp) {
6990                         /*
6991                          * no matches
6992                          */
6993  nometa:
6994                         *exparg.lastp = str;
6995                         rmescapes(str->text, 0);
6996                         exparg.lastp = &str->next;
6997                 } else {
6998                         *exparg.lastp = NULL;
6999                         *savelastp = sp = expsort(*savelastp);
7000                         while (sp->next != NULL)
7001                                 sp = sp->next;
7002                         exparg.lastp = &sp->next;
7003                 }
7004                 str = str->next;
7005         }
7006 }
7007
7008 /*
7009  * Perform variable substitution and command substitution on an argument,
7010  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
7011  * perform splitting and file name expansion.  When arglist is NULL, perform
7012  * here document expansion.
7013  */
7014 static void
7015 expandarg(union node *arg, struct arglist *arglist, int flag)
7016 {
7017         struct strlist *sp;
7018         char *p;
7019
7020         argbackq = arg->narg.backquote;
7021         STARTSTACKSTR(expdest);
7022         ifsfirst.next = NULL;
7023         ifslastp = NULL;
7024         argstr(arg->narg.text, flag,
7025                         /* var_str_list: */ arglist ? arglist->list : NULL);
7026         p = _STPUTC('\0', expdest);
7027         expdest = p - 1;
7028         if (arglist == NULL) {
7029                 return;                 /* here document expanded */
7030         }
7031         p = grabstackstr(p);
7032         exparg.lastp = &exparg.list;
7033         /*
7034          * TODO - EXP_REDIR
7035          */
7036         if (flag & EXP_FULL) {
7037                 ifsbreakup(p, &exparg);
7038                 *exparg.lastp = NULL;
7039                 exparg.lastp = &exparg.list;
7040                 expandmeta(exparg.list /*, flag*/);
7041         } else {
7042                 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7043                         rmescapes(p, 0);
7044                 sp = stzalloc(sizeof(*sp));
7045                 sp->text = p;
7046                 *exparg.lastp = sp;
7047                 exparg.lastp = &sp->next;
7048         }
7049         if (ifsfirst.next)
7050                 ifsfree();
7051         *exparg.lastp = NULL;
7052         if (exparg.list) {
7053                 *arglist->lastp = exparg.list;
7054                 arglist->lastp = exparg.lastp;
7055         }
7056 }
7057
7058 /*
7059  * Expand shell variables and backquotes inside a here document.
7060  */
7061 static void
7062 expandhere(union node *arg, int fd)
7063 {
7064         herefd = fd;
7065         expandarg(arg, (struct arglist *)NULL, 0);
7066         full_write(fd, stackblock(), expdest - (char *)stackblock());
7067 }
7068
7069 /*
7070  * Returns true if the pattern matches the string.
7071  */
7072 static int
7073 patmatch(char *pattern, const char *string)
7074 {
7075         return pmatch(preglob(pattern, 0, 0), string);
7076 }
7077
7078 /*
7079  * See if a pattern matches in a case statement.
7080  */
7081 static int
7082 casematch(union node *pattern, char *val)
7083 {
7084         struct stackmark smark;
7085         int result;
7086
7087         setstackmark(&smark);
7088         argbackq = pattern->narg.backquote;
7089         STARTSTACKSTR(expdest);
7090         ifslastp = NULL;
7091         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7092                         /* var_str_list: */ NULL);
7093         STACKSTRNUL(expdest);
7094         result = patmatch(stackblock(), val);
7095         popstackmark(&smark);
7096         return result;
7097 }
7098
7099
7100 /* ============ find_command */
7101
7102 struct builtincmd {
7103         const char *name;
7104         int (*builtin)(int, char **) FAST_FUNC;
7105         /* unsigned flags; */
7106 };
7107 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7108 /* "regular" builtins always take precedence over commands,
7109  * regardless of PATH=....%builtin... position */
7110 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7111 #define IS_BUILTIN_ASSIGN(b)  ((b)->name[0] & 4)
7112
7113 struct cmdentry {
7114         smallint cmdtype;       /* CMDxxx */
7115         union param {
7116                 int index;
7117                 /* index >= 0 for commands without path (slashes) */
7118                 /* (TODO: what exactly does the value mean? PATH position?) */
7119                 /* index == -1 for commands with slashes */
7120                 /* index == (-2 - applet_no) for NOFORK applets */
7121                 const struct builtincmd *cmd;
7122                 struct funcnode *func;
7123         } u;
7124 };
7125 /* values of cmdtype */
7126 #define CMDUNKNOWN      -1      /* no entry in table for command */
7127 #define CMDNORMAL       0       /* command is an executable program */
7128 #define CMDFUNCTION     1       /* command is a shell function */
7129 #define CMDBUILTIN      2       /* command is a shell builtin */
7130
7131 /* action to find_command() */
7132 #define DO_ERR          0x01    /* prints errors */
7133 #define DO_ABS          0x02    /* checks absolute paths */
7134 #define DO_NOFUNC       0x04    /* don't return shell functions, for command */
7135 #define DO_ALTPATH      0x08    /* using alternate path */
7136 #define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
7137
7138 static void find_command(char *, struct cmdentry *, int, const char *);
7139
7140
7141 /* ============ Hashing commands */
7142
7143 /*
7144  * When commands are first encountered, they are entered in a hash table.
7145  * This ensures that a full path search will not have to be done for them
7146  * on each invocation.
7147  *
7148  * We should investigate converting to a linear search, even though that
7149  * would make the command name "hash" a misnomer.
7150  */
7151
7152 struct tblentry {
7153         struct tblentry *next;  /* next entry in hash chain */
7154         union param param;      /* definition of builtin function */
7155         smallint cmdtype;       /* CMDxxx */
7156         char rehash;            /* if set, cd done since entry created */
7157         char cmdname[1];        /* name of command */
7158 };
7159
7160 static struct tblentry **cmdtable;
7161 #define INIT_G_cmdtable() do { \
7162         cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7163 } while (0)
7164
7165 static int builtinloc = -1;     /* index in path of %builtin, or -1 */
7166
7167
7168 static void
7169 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7170 {
7171         int repeated = 0;
7172
7173 #if ENABLE_FEATURE_SH_STANDALONE
7174         if (applet_no >= 0) {
7175                 if (APPLET_IS_NOEXEC(applet_no)) {
7176                         while (*envp)
7177                                 putenv(*envp++);
7178                         run_applet_no_and_exit(applet_no, argv);
7179                 }
7180                 /* re-exec ourselves with the new arguments */
7181                 execve(bb_busybox_exec_path, argv, envp);
7182                 /* If they called chroot or otherwise made the binary no longer
7183                  * executable, fall through */
7184         }
7185 #endif
7186
7187  repeat:
7188 #ifdef SYSV
7189         do {
7190                 execve(cmd, argv, envp);
7191         } while (errno == EINTR);
7192 #else
7193         execve(cmd, argv, envp);
7194 #endif
7195         if (repeated) {
7196                 free(argv);
7197                 return;
7198         }
7199         if (errno == ENOEXEC) {
7200                 char **ap;
7201                 char **new;
7202
7203                 for (ap = argv; *ap; ap++)
7204                         continue;
7205                 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7206                 ap[1] = cmd;
7207                 ap[0] = cmd = (char *)DEFAULT_SHELL;
7208                 ap += 2;
7209                 argv++;
7210                 while ((*ap++ = *argv++) != NULL)
7211                         continue;
7212                 argv = new;
7213                 repeated++;
7214                 goto repeat;
7215         }
7216 }
7217
7218 /*
7219  * Exec a program.  Never returns.  If you change this routine, you may
7220  * have to change the find_command routine as well.
7221  */
7222 static void shellexec(char **, const char *, int) NORETURN;
7223 static void
7224 shellexec(char **argv, const char *path, int idx)
7225 {
7226         char *cmdname;
7227         int e;
7228         char **envp;
7229         int exerrno;
7230 #if ENABLE_FEATURE_SH_STANDALONE
7231         int applet_no = -1;
7232 #endif
7233
7234         clearredir(/*drop:*/ 1);
7235         envp = listvars(VEXPORT, VUNSET, 0);
7236         if (strchr(argv[0], '/') != NULL
7237 #if ENABLE_FEATURE_SH_STANDALONE
7238          || (applet_no = find_applet_by_name(argv[0])) >= 0
7239 #endif
7240         ) {
7241                 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7242                 e = errno;
7243         } else {
7244                 e = ENOENT;
7245                 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7246                         if (--idx < 0 && pathopt == NULL) {
7247                                 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7248                                 if (errno != ENOENT && errno != ENOTDIR)
7249                                         e = errno;
7250                         }
7251                         stunalloc(cmdname);
7252                 }
7253         }
7254
7255         /* Map to POSIX errors */
7256         switch (e) {
7257         case EACCES:
7258                 exerrno = 126;
7259                 break;
7260         case ENOENT:
7261                 exerrno = 127;
7262                 break;
7263         default:
7264                 exerrno = 2;
7265                 break;
7266         }
7267         exitstatus = exerrno;
7268         TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7269                 argv[0], e, suppress_int));
7270         ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7271         /* NOTREACHED */
7272 }
7273
7274 static void
7275 printentry(struct tblentry *cmdp)
7276 {
7277         int idx;
7278         const char *path;
7279         char *name;
7280
7281         idx = cmdp->param.index;
7282         path = pathval();
7283         do {
7284                 name = path_advance(&path, cmdp->cmdname);
7285                 stunalloc(name);
7286         } while (--idx >= 0);
7287         out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7288 }
7289
7290 /*
7291  * Clear out command entries.  The argument specifies the first entry in
7292  * PATH which has changed.
7293  */
7294 static void
7295 clearcmdentry(int firstchange)
7296 {
7297         struct tblentry **tblp;
7298         struct tblentry **pp;
7299         struct tblentry *cmdp;
7300
7301         INT_OFF;
7302         for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7303                 pp = tblp;
7304                 while ((cmdp = *pp) != NULL) {
7305                         if ((cmdp->cmdtype == CMDNORMAL &&
7306                              cmdp->param.index >= firstchange)
7307                          || (cmdp->cmdtype == CMDBUILTIN &&
7308                              builtinloc >= firstchange)
7309                         ) {
7310                                 *pp = cmdp->next;
7311                                 free(cmdp);
7312                         } else {
7313                                 pp = &cmdp->next;
7314                         }
7315                 }
7316         }
7317         INT_ON;
7318 }
7319
7320 /*
7321  * Locate a command in the command hash table.  If "add" is nonzero,
7322  * add the command to the table if it is not already present.  The
7323  * variable "lastcmdentry" is set to point to the address of the link
7324  * pointing to the entry, so that delete_cmd_entry can delete the
7325  * entry.
7326  *
7327  * Interrupts must be off if called with add != 0.
7328  */
7329 static struct tblentry **lastcmdentry;
7330
7331 static struct tblentry *
7332 cmdlookup(const char *name, int add)
7333 {
7334         unsigned int hashval;
7335         const char *p;
7336         struct tblentry *cmdp;
7337         struct tblentry **pp;
7338
7339         p = name;
7340         hashval = (unsigned char)*p << 4;
7341         while (*p)
7342                 hashval += (unsigned char)*p++;
7343         hashval &= 0x7FFF;
7344         pp = &cmdtable[hashval % CMDTABLESIZE];
7345         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7346                 if (strcmp(cmdp->cmdname, name) == 0)
7347                         break;
7348                 pp = &cmdp->next;
7349         }
7350         if (add && cmdp == NULL) {
7351                 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7352                                 + strlen(name)
7353                                 /* + 1 - already done because
7354                                  * tblentry::cmdname is char[1] */);
7355                 /*cmdp->next = NULL; - ckzalloc did it */
7356                 cmdp->cmdtype = CMDUNKNOWN;
7357                 strcpy(cmdp->cmdname, name);
7358         }
7359         lastcmdentry = pp;
7360         return cmdp;
7361 }
7362
7363 /*
7364  * Delete the command entry returned on the last lookup.
7365  */
7366 static void
7367 delete_cmd_entry(void)
7368 {
7369         struct tblentry *cmdp;
7370
7371         INT_OFF;
7372         cmdp = *lastcmdentry;
7373         *lastcmdentry = cmdp->next;
7374         if (cmdp->cmdtype == CMDFUNCTION)
7375                 freefunc(cmdp->param.func);
7376         free(cmdp);
7377         INT_ON;
7378 }
7379
7380 /*
7381  * Add a new command entry, replacing any existing command entry for
7382  * the same name - except special builtins.
7383  */
7384 static void
7385 addcmdentry(char *name, struct cmdentry *entry)
7386 {
7387         struct tblentry *cmdp;
7388
7389         cmdp = cmdlookup(name, 1);
7390         if (cmdp->cmdtype == CMDFUNCTION) {
7391                 freefunc(cmdp->param.func);
7392         }
7393         cmdp->cmdtype = entry->cmdtype;
7394         cmdp->param = entry->u;
7395         cmdp->rehash = 0;
7396 }
7397
7398 static int FAST_FUNC
7399 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7400 {
7401         struct tblentry **pp;
7402         struct tblentry *cmdp;
7403         int c;
7404         struct cmdentry entry;
7405         char *name;
7406
7407         if (nextopt("r") != '\0') {
7408                 clearcmdentry(0);
7409                 return 0;
7410         }
7411
7412         if (*argptr == NULL) {
7413                 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7414                         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7415                                 if (cmdp->cmdtype == CMDNORMAL)
7416                                         printentry(cmdp);
7417                         }
7418                 }
7419                 return 0;
7420         }
7421
7422         c = 0;
7423         while ((name = *argptr) != NULL) {
7424                 cmdp = cmdlookup(name, 0);
7425                 if (cmdp != NULL
7426                  && (cmdp->cmdtype == CMDNORMAL
7427                      || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7428                 ) {
7429                         delete_cmd_entry();
7430                 }
7431                 find_command(name, &entry, DO_ERR, pathval());
7432                 if (entry.cmdtype == CMDUNKNOWN)
7433                         c = 1;
7434                 argptr++;
7435         }
7436         return c;
7437 }
7438
7439 /*
7440  * Called when a cd is done.  Marks all commands so the next time they
7441  * are executed they will be rehashed.
7442  */
7443 static void
7444 hashcd(void)
7445 {
7446         struct tblentry **pp;
7447         struct tblentry *cmdp;
7448
7449         for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7450                 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7451                         if (cmdp->cmdtype == CMDNORMAL
7452                          || (cmdp->cmdtype == CMDBUILTIN
7453                              && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7454                              && builtinloc > 0)
7455                         ) {
7456                                 cmdp->rehash = 1;
7457                         }
7458                 }
7459         }
7460 }
7461
7462 /*
7463  * Fix command hash table when PATH changed.
7464  * Called before PATH is changed.  The argument is the new value of PATH;
7465  * pathval() still returns the old value at this point.
7466  * Called with interrupts off.
7467  */
7468 static void FAST_FUNC
7469 changepath(const char *new)
7470 {
7471         const char *old;
7472         int firstchange;
7473         int idx;
7474         int idx_bltin;
7475
7476         old = pathval();
7477         firstchange = 9999;     /* assume no change */
7478         idx = 0;
7479         idx_bltin = -1;
7480         for (;;) {
7481                 if (*old != *new) {
7482                         firstchange = idx;
7483                         if ((*old == '\0' && *new == ':')
7484                          || (*old == ':' && *new == '\0'))
7485                                 firstchange++;
7486                         old = new;      /* ignore subsequent differences */
7487                 }
7488                 if (*new == '\0')
7489                         break;
7490                 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7491                         idx_bltin = idx;
7492                 if (*new == ':')
7493                         idx++;
7494                 new++, old++;
7495         }
7496         if (builtinloc < 0 && idx_bltin >= 0)
7497                 builtinloc = idx_bltin;             /* zap builtins */
7498         if (builtinloc >= 0 && idx_bltin < 0)
7499                 firstchange = 0;
7500         clearcmdentry(firstchange);
7501         builtinloc = idx_bltin;
7502 }
7503
7504 #define TEOF 0
7505 #define TNL 1
7506 #define TREDIR 2
7507 #define TWORD 3
7508 #define TSEMI 4
7509 #define TBACKGND 5
7510 #define TAND 6
7511 #define TOR 7
7512 #define TPIPE 8
7513 #define TLP 9
7514 #define TRP 10
7515 #define TENDCASE 11
7516 #define TENDBQUOTE 12
7517 #define TNOT 13
7518 #define TCASE 14
7519 #define TDO 15
7520 #define TDONE 16
7521 #define TELIF 17
7522 #define TELSE 18
7523 #define TESAC 19
7524 #define TFI 20
7525 #define TFOR 21
7526 #define TIF 22
7527 #define TIN 23
7528 #define TTHEN 24
7529 #define TUNTIL 25
7530 #define TWHILE 26
7531 #define TBEGIN 27
7532 #define TEND 28
7533 typedef smallint token_id_t;
7534
7535 /* first char is indicating which tokens mark the end of a list */
7536 static const char *const tokname_array[] = {
7537         "\1end of file",
7538         "\0newline",
7539         "\0redirection",
7540         "\0word",
7541         "\0;",
7542         "\0&",
7543         "\0&&",
7544         "\0||",
7545         "\0|",
7546         "\0(",
7547         "\1)",
7548         "\1;;",
7549         "\1`",
7550 #define KWDOFFSET 13
7551         /* the following are keywords */
7552         "\0!",
7553         "\0case",
7554         "\1do",
7555         "\1done",
7556         "\1elif",
7557         "\1else",
7558         "\1esac",
7559         "\1fi",
7560         "\0for",
7561         "\0if",
7562         "\0in",
7563         "\1then",
7564         "\0until",
7565         "\0while",
7566         "\0{",
7567         "\1}",
7568 };
7569
7570 static const char *
7571 tokname(int tok)
7572 {
7573         static char buf[16];
7574
7575 //try this:
7576 //if (tok < TSEMI) return tokname_array[tok] + 1;
7577 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7578 //return buf;
7579
7580         if (tok >= TSEMI)
7581                 buf[0] = '"';
7582         sprintf(buf + (tok >= TSEMI), "%s%c",
7583                         tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7584         return buf;
7585 }
7586
7587 /* Wrapper around strcmp for qsort/bsearch/... */
7588 static int
7589 pstrcmp(const void *a, const void *b)
7590 {
7591         return strcmp((char*) a, (*(char**) b) + 1);
7592 }
7593
7594 static const char *const *
7595 findkwd(const char *s)
7596 {
7597         return bsearch(s, tokname_array + KWDOFFSET,
7598                         ARRAY_SIZE(tokname_array) - KWDOFFSET,
7599                         sizeof(tokname_array[0]), pstrcmp);
7600 }
7601
7602 /*
7603  * Locate and print what a word is...
7604  */
7605 static int
7606 describe_command(char *command, int describe_command_verbose)
7607 {
7608         struct cmdentry entry;
7609         struct tblentry *cmdp;
7610 #if ENABLE_ASH_ALIAS
7611         const struct alias *ap;
7612 #endif
7613         const char *path = pathval();
7614
7615         if (describe_command_verbose) {
7616                 out1str(command);
7617         }
7618
7619         /* First look at the keywords */
7620         if (findkwd(command)) {
7621                 out1str(describe_command_verbose ? " is a shell keyword" : command);
7622                 goto out;
7623         }
7624
7625 #if ENABLE_ASH_ALIAS
7626         /* Then look at the aliases */
7627         ap = lookupalias(command, 0);
7628         if (ap != NULL) {
7629                 if (!describe_command_verbose) {
7630                         out1str("alias ");
7631                         printalias(ap);
7632                         return 0;
7633                 }
7634                 out1fmt(" is an alias for %s", ap->val);
7635                 goto out;
7636         }
7637 #endif
7638         /* Then check if it is a tracked alias */
7639         cmdp = cmdlookup(command, 0);
7640         if (cmdp != NULL) {
7641                 entry.cmdtype = cmdp->cmdtype;
7642                 entry.u = cmdp->param;
7643         } else {
7644                 /* Finally use brute force */
7645                 find_command(command, &entry, DO_ABS, path);
7646         }
7647
7648         switch (entry.cmdtype) {
7649         case CMDNORMAL: {
7650                 int j = entry.u.index;
7651                 char *p;
7652                 if (j < 0) {
7653                         p = command;
7654                 } else {
7655                         do {
7656                                 p = path_advance(&path, command);
7657                                 stunalloc(p);
7658                         } while (--j >= 0);
7659                 }
7660                 if (describe_command_verbose) {
7661                         out1fmt(" is%s %s",
7662                                 (cmdp ? " a tracked alias for" : nullstr), p
7663                         );
7664                 } else {
7665                         out1str(p);
7666                 }
7667                 break;
7668         }
7669
7670         case CMDFUNCTION:
7671                 if (describe_command_verbose) {
7672                         out1str(" is a shell function");
7673                 } else {
7674                         out1str(command);
7675                 }
7676                 break;
7677
7678         case CMDBUILTIN:
7679                 if (describe_command_verbose) {
7680                         out1fmt(" is a %sshell builtin",
7681                                 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7682                                         "special " : nullstr
7683                         );
7684                 } else {
7685                         out1str(command);
7686                 }
7687                 break;
7688
7689         default:
7690                 if (describe_command_verbose) {
7691                         out1str(": not found\n");
7692                 }
7693                 return 127;
7694         }
7695  out:
7696         outstr("\n", stdout);
7697         return 0;
7698 }
7699
7700 static int FAST_FUNC
7701 typecmd(int argc UNUSED_PARAM, char **argv)
7702 {
7703         int i = 1;
7704         int err = 0;
7705         int verbose = 1;
7706
7707         /* type -p ... ? (we don't bother checking for 'p') */
7708         if (argv[1] && argv[1][0] == '-') {
7709                 i++;
7710                 verbose = 0;
7711         }
7712         while (argv[i]) {
7713                 err |= describe_command(argv[i++], verbose);
7714         }
7715         return err;
7716 }
7717
7718 #if ENABLE_ASH_CMDCMD
7719 static int FAST_FUNC
7720 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7721 {
7722         int c;
7723         enum {
7724                 VERIFY_BRIEF = 1,
7725                 VERIFY_VERBOSE = 2,
7726         } verify = 0;
7727
7728         while ((c = nextopt("pvV")) != '\0')
7729                 if (c == 'V')
7730                         verify |= VERIFY_VERBOSE;
7731                 else if (c == 'v')
7732                         verify |= VERIFY_BRIEF;
7733 #if DEBUG
7734                 else if (c != 'p')
7735                         abort();
7736 #endif
7737         /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7738         if (verify && (*argptr != NULL)) {
7739                 return describe_command(*argptr, verify - VERIFY_BRIEF);
7740         }
7741
7742         return 0;
7743 }
7744 #endif
7745
7746
7747 /* ============ eval.c */
7748
7749 static int funcblocksize;       /* size of structures in function */
7750 static int funcstringsize;      /* size of strings in node */
7751 static void *funcblock;         /* block to allocate function from */
7752 static char *funcstring;        /* block to allocate strings from */
7753
7754 /* flags in argument to evaltree */
7755 #define EV_EXIT    01           /* exit after evaluating tree */
7756 #define EV_TESTED  02           /* exit status is checked; ignore -e flag */
7757 #define EV_BACKCMD 04           /* command executing within back quotes */
7758
7759 static const short nodesize[N_NUMBER] = {
7760         [NCMD     ] = SHELL_ALIGN(sizeof(struct ncmd)),
7761         [NPIPE    ] = SHELL_ALIGN(sizeof(struct npipe)),
7762         [NREDIR   ] = SHELL_ALIGN(sizeof(struct nredir)),
7763         [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7764         [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7765         [NAND     ] = SHELL_ALIGN(sizeof(struct nbinary)),
7766         [NOR      ] = SHELL_ALIGN(sizeof(struct nbinary)),
7767         [NSEMI    ] = SHELL_ALIGN(sizeof(struct nbinary)),
7768         [NIF      ] = SHELL_ALIGN(sizeof(struct nif)),
7769         [NWHILE   ] = SHELL_ALIGN(sizeof(struct nbinary)),
7770         [NUNTIL   ] = SHELL_ALIGN(sizeof(struct nbinary)),
7771         [NFOR     ] = SHELL_ALIGN(sizeof(struct nfor)),
7772         [NCASE    ] = SHELL_ALIGN(sizeof(struct ncase)),
7773         [NCLIST   ] = SHELL_ALIGN(sizeof(struct nclist)),
7774         [NDEFUN   ] = SHELL_ALIGN(sizeof(struct narg)),
7775         [NARG     ] = SHELL_ALIGN(sizeof(struct narg)),
7776         [NTO      ] = SHELL_ALIGN(sizeof(struct nfile)),
7777 #if ENABLE_ASH_BASH_COMPAT
7778         [NTO2     ] = SHELL_ALIGN(sizeof(struct nfile)),
7779 #endif
7780         [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7781         [NFROM    ] = SHELL_ALIGN(sizeof(struct nfile)),
7782         [NFROMTO  ] = SHELL_ALIGN(sizeof(struct nfile)),
7783         [NAPPEND  ] = SHELL_ALIGN(sizeof(struct nfile)),
7784         [NTOFD    ] = SHELL_ALIGN(sizeof(struct ndup)),
7785         [NFROMFD  ] = SHELL_ALIGN(sizeof(struct ndup)),
7786         [NHERE    ] = SHELL_ALIGN(sizeof(struct nhere)),
7787         [NXHERE   ] = SHELL_ALIGN(sizeof(struct nhere)),
7788         [NNOT     ] = SHELL_ALIGN(sizeof(struct nnot)),
7789 };
7790
7791 static void calcsize(union node *n);
7792
7793 static void
7794 sizenodelist(struct nodelist *lp)
7795 {
7796         while (lp) {
7797                 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7798                 calcsize(lp->n);
7799                 lp = lp->next;
7800         }
7801 }
7802
7803 static void
7804 calcsize(union node *n)
7805 {
7806         if (n == NULL)
7807                 return;
7808         funcblocksize += nodesize[n->type];
7809         switch (n->type) {
7810         case NCMD:
7811                 calcsize(n->ncmd.redirect);
7812                 calcsize(n->ncmd.args);
7813                 calcsize(n->ncmd.assign);
7814                 break;
7815         case NPIPE:
7816                 sizenodelist(n->npipe.cmdlist);
7817                 break;
7818         case NREDIR:
7819         case NBACKGND:
7820         case NSUBSHELL:
7821                 calcsize(n->nredir.redirect);
7822                 calcsize(n->nredir.n);
7823                 break;
7824         case NAND:
7825         case NOR:
7826         case NSEMI:
7827         case NWHILE:
7828         case NUNTIL:
7829                 calcsize(n->nbinary.ch2);
7830                 calcsize(n->nbinary.ch1);
7831                 break;
7832         case NIF:
7833                 calcsize(n->nif.elsepart);
7834                 calcsize(n->nif.ifpart);
7835                 calcsize(n->nif.test);
7836                 break;
7837         case NFOR:
7838                 funcstringsize += strlen(n->nfor.var) + 1;
7839                 calcsize(n->nfor.body);
7840                 calcsize(n->nfor.args);
7841                 break;
7842         case NCASE:
7843                 calcsize(n->ncase.cases);
7844                 calcsize(n->ncase.expr);
7845                 break;
7846         case NCLIST:
7847                 calcsize(n->nclist.body);
7848                 calcsize(n->nclist.pattern);
7849                 calcsize(n->nclist.next);
7850                 break;
7851         case NDEFUN:
7852         case NARG:
7853                 sizenodelist(n->narg.backquote);
7854                 funcstringsize += strlen(n->narg.text) + 1;
7855                 calcsize(n->narg.next);
7856                 break;
7857         case NTO:
7858 #if ENABLE_ASH_BASH_COMPAT
7859         case NTO2:
7860 #endif
7861         case NCLOBBER:
7862         case NFROM:
7863         case NFROMTO:
7864         case NAPPEND:
7865                 calcsize(n->nfile.fname);
7866                 calcsize(n->nfile.next);
7867                 break;
7868         case NTOFD:
7869         case NFROMFD:
7870                 calcsize(n->ndup.vname);
7871                 calcsize(n->ndup.next);
7872         break;
7873         case NHERE:
7874         case NXHERE:
7875                 calcsize(n->nhere.doc);
7876                 calcsize(n->nhere.next);
7877                 break;
7878         case NNOT:
7879                 calcsize(n->nnot.com);
7880                 break;
7881         };
7882 }
7883
7884 static char *
7885 nodeckstrdup(char *s)
7886 {
7887         char *rtn = funcstring;
7888
7889         strcpy(funcstring, s);
7890         funcstring += strlen(s) + 1;
7891         return rtn;
7892 }
7893
7894 static union node *copynode(union node *);
7895
7896 static struct nodelist *
7897 copynodelist(struct nodelist *lp)
7898 {
7899         struct nodelist *start;
7900         struct nodelist **lpp;
7901
7902         lpp = &start;
7903         while (lp) {
7904                 *lpp = funcblock;
7905                 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7906                 (*lpp)->n = copynode(lp->n);
7907                 lp = lp->next;
7908                 lpp = &(*lpp)->next;
7909         }
7910         *lpp = NULL;
7911         return start;
7912 }
7913
7914 static union node *
7915 copynode(union node *n)
7916 {
7917         union node *new;
7918
7919         if (n == NULL)
7920                 return NULL;
7921         new = funcblock;
7922         funcblock = (char *) funcblock + nodesize[n->type];
7923
7924         switch (n->type) {
7925         case NCMD:
7926                 new->ncmd.redirect = copynode(n->ncmd.redirect);
7927                 new->ncmd.args = copynode(n->ncmd.args);
7928                 new->ncmd.assign = copynode(n->ncmd.assign);
7929                 break;
7930         case NPIPE:
7931                 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7932                 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7933                 break;
7934         case NREDIR:
7935         case NBACKGND:
7936         case NSUBSHELL:
7937                 new->nredir.redirect = copynode(n->nredir.redirect);
7938                 new->nredir.n = copynode(n->nredir.n);
7939                 break;
7940         case NAND:
7941         case NOR:
7942         case NSEMI:
7943         case NWHILE:
7944         case NUNTIL:
7945                 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7946                 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7947                 break;
7948         case NIF:
7949                 new->nif.elsepart = copynode(n->nif.elsepart);
7950                 new->nif.ifpart = copynode(n->nif.ifpart);
7951                 new->nif.test = copynode(n->nif.test);
7952                 break;
7953         case NFOR:
7954                 new->nfor.var = nodeckstrdup(n->nfor.var);
7955                 new->nfor.body = copynode(n->nfor.body);
7956                 new->nfor.args = copynode(n->nfor.args);
7957                 break;
7958         case NCASE:
7959                 new->ncase.cases = copynode(n->ncase.cases);
7960                 new->ncase.expr = copynode(n->ncase.expr);
7961                 break;
7962         case NCLIST:
7963                 new->nclist.body = copynode(n->nclist.body);
7964                 new->nclist.pattern = copynode(n->nclist.pattern);
7965                 new->nclist.next = copynode(n->nclist.next);
7966                 break;
7967         case NDEFUN:
7968         case NARG:
7969                 new->narg.backquote = copynodelist(n->narg.backquote);
7970                 new->narg.text = nodeckstrdup(n->narg.text);
7971                 new->narg.next = copynode(n->narg.next);
7972                 break;
7973         case NTO:
7974 #if ENABLE_ASH_BASH_COMPAT
7975         case NTO2:
7976 #endif
7977         case NCLOBBER:
7978         case NFROM:
7979         case NFROMTO:
7980         case NAPPEND:
7981                 new->nfile.fname = copynode(n->nfile.fname);
7982                 new->nfile.fd = n->nfile.fd;
7983                 new->nfile.next = copynode(n->nfile.next);
7984                 break;
7985         case NTOFD:
7986         case NFROMFD:
7987                 new->ndup.vname = copynode(n->ndup.vname);
7988                 new->ndup.dupfd = n->ndup.dupfd;
7989                 new->ndup.fd = n->ndup.fd;
7990                 new->ndup.next = copynode(n->ndup.next);
7991                 break;
7992         case NHERE:
7993         case NXHERE:
7994                 new->nhere.doc = copynode(n->nhere.doc);
7995                 new->nhere.fd = n->nhere.fd;
7996                 new->nhere.next = copynode(n->nhere.next);
7997                 break;
7998         case NNOT:
7999                 new->nnot.com = copynode(n->nnot.com);
8000                 break;
8001         };
8002         new->type = n->type;
8003         return new;
8004 }
8005
8006 /*
8007  * Make a copy of a parse tree.
8008  */
8009 static struct funcnode *
8010 copyfunc(union node *n)
8011 {
8012         struct funcnode *f;
8013         size_t blocksize;
8014
8015         funcblocksize = offsetof(struct funcnode, n);
8016         funcstringsize = 0;
8017         calcsize(n);
8018         blocksize = funcblocksize;
8019         f = ckmalloc(blocksize + funcstringsize);
8020         funcblock = (char *) f + offsetof(struct funcnode, n);
8021         funcstring = (char *) f + blocksize;
8022         copynode(n);
8023         f->count = 0;
8024         return f;
8025 }
8026
8027 /*
8028  * Define a shell function.
8029  */
8030 static void
8031 defun(char *name, union node *func)
8032 {
8033         struct cmdentry entry;
8034
8035         INT_OFF;
8036         entry.cmdtype = CMDFUNCTION;
8037         entry.u.func = copyfunc(func);
8038         addcmdentry(name, &entry);
8039         INT_ON;
8040 }
8041
8042 /* Reasons for skipping commands (see comment on breakcmd routine) */
8043 #define SKIPBREAK      (1 << 0)
8044 #define SKIPCONT       (1 << 1)
8045 #define SKIPFUNC       (1 << 2)
8046 #define SKIPFILE       (1 << 3)
8047 #define SKIPEVAL       (1 << 4)
8048 static smallint evalskip;       /* set to SKIPxxx if we are skipping commands */
8049 static int skipcount;           /* number of levels to skip */
8050 static int funcnest;            /* depth of function calls */
8051 static int loopnest;            /* current loop nesting level */
8052
8053 /* Forward decl way out to parsing code - dotrap needs it */
8054 static int evalstring(char *s, int mask);
8055
8056 /* Called to execute a trap.
8057  * Single callsite - at the end of evaltree().
8058  * If we return non-zero, exaltree raises EXEXIT exception.
8059  *
8060  * Perhaps we should avoid entering new trap handlers
8061  * while we are executing a trap handler. [is it a TODO?]
8062  */
8063 static int
8064 dotrap(void)
8065 {
8066         uint8_t *g;
8067         int sig;
8068         uint8_t savestatus;
8069
8070         savestatus = exitstatus;
8071         pending_sig = 0;
8072         xbarrier();
8073
8074         TRACE(("dotrap entered\n"));
8075         for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8076                 int want_exexit;
8077                 char *t;
8078
8079                 if (*g == 0)
8080                         continue;
8081                 t = trap[sig];
8082                 /* non-trapped SIGINT is handled separately by raise_interrupt,
8083                  * don't upset it by resetting gotsig[SIGINT-1] */
8084                 if (sig == SIGINT && !t)
8085                         continue;
8086
8087                 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8088                 *g = 0;
8089                 if (!t)
8090                         continue;
8091                 want_exexit = evalstring(t, SKIPEVAL);
8092                 exitstatus = savestatus;
8093                 if (want_exexit) {
8094                         TRACE(("dotrap returns %d\n", want_exexit));
8095                         return want_exexit;
8096                 }
8097         }
8098
8099         TRACE(("dotrap returns 0\n"));
8100         return 0;
8101 }
8102
8103 /* forward declarations - evaluation is fairly recursive business... */
8104 static void evalloop(union node *, int);
8105 static void evalfor(union node *, int);
8106 static void evalcase(union node *, int);
8107 static void evalsubshell(union node *, int);
8108 static void expredir(union node *);
8109 static void evalpipe(union node *, int);
8110 static void evalcommand(union node *, int);
8111 static int evalbltin(const struct builtincmd *, int, char **);
8112 static void prehash(union node *);
8113
8114 /*
8115  * Evaluate a parse tree.  The value is left in the global variable
8116  * exitstatus.
8117  */
8118 static void
8119 evaltree(union node *n, int flags)
8120 {
8121         struct jmploc *volatile savehandler = exception_handler;
8122         struct jmploc jmploc;
8123         int checkexit = 0;
8124         void (*evalfn)(union node *, int);
8125         int status;
8126         int int_level;
8127
8128         SAVE_INT(int_level);
8129
8130         if (n == NULL) {
8131                 TRACE(("evaltree(NULL) called\n"));
8132                 goto out1;
8133         }
8134         TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8135
8136         exception_handler = &jmploc;
8137         {
8138                 int err = setjmp(jmploc.loc);
8139                 if (err) {
8140                         /* if it was a signal, check for trap handlers */
8141                         if (exception_type == EXSIG) {
8142                                 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8143                                                 exception_type, err));
8144                                 goto out;
8145                         }
8146                         /* continue on the way out */
8147                         TRACE(("exception %d in evaltree, propagating err=%d\n",
8148                                         exception_type, err));
8149                         exception_handler = savehandler;
8150                         longjmp(exception_handler->loc, err);
8151                 }
8152         }
8153
8154         switch (n->type) {
8155         default:
8156 #if DEBUG
8157                 out1fmt("Node type = %d\n", n->type);
8158                 fflush(stdout);
8159                 break;
8160 #endif
8161         case NNOT:
8162                 evaltree(n->nnot.com, EV_TESTED);
8163                 status = !exitstatus;
8164                 goto setstatus;
8165         case NREDIR:
8166                 expredir(n->nredir.redirect);
8167                 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8168                 if (!status) {
8169                         evaltree(n->nredir.n, flags & EV_TESTED);
8170                         status = exitstatus;
8171                 }
8172                 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8173                 goto setstatus;
8174         case NCMD:
8175                 evalfn = evalcommand;
8176  checkexit:
8177                 if (eflag && !(flags & EV_TESTED))
8178                         checkexit = ~0;
8179                 goto calleval;
8180         case NFOR:
8181                 evalfn = evalfor;
8182                 goto calleval;
8183         case NWHILE:
8184         case NUNTIL:
8185                 evalfn = evalloop;
8186                 goto calleval;
8187         case NSUBSHELL:
8188         case NBACKGND:
8189                 evalfn = evalsubshell;
8190                 goto calleval;
8191         case NPIPE:
8192                 evalfn = evalpipe;
8193                 goto checkexit;
8194         case NCASE:
8195                 evalfn = evalcase;
8196                 goto calleval;
8197         case NAND:
8198         case NOR:
8199         case NSEMI: {
8200
8201 #if NAND + 1 != NOR
8202 #error NAND + 1 != NOR
8203 #endif
8204 #if NOR + 1 != NSEMI
8205 #error NOR + 1 != NSEMI
8206 #endif
8207                 unsigned is_or = n->type - NAND;
8208                 evaltree(
8209                         n->nbinary.ch1,
8210                         (flags | ((is_or >> 1) - 1)) & EV_TESTED
8211                 );
8212                 if (!exitstatus == is_or)
8213                         break;
8214                 if (!evalskip) {
8215                         n = n->nbinary.ch2;
8216  evaln:
8217                         evalfn = evaltree;
8218  calleval:
8219                         evalfn(n, flags);
8220                         break;
8221                 }
8222                 break;
8223         }
8224         case NIF:
8225                 evaltree(n->nif.test, EV_TESTED);
8226                 if (evalskip)
8227                         break;
8228                 if (exitstatus == 0) {
8229                         n = n->nif.ifpart;
8230                         goto evaln;
8231                 }
8232                 if (n->nif.elsepart) {
8233                         n = n->nif.elsepart;
8234                         goto evaln;
8235                 }
8236                 goto success;
8237         case NDEFUN:
8238                 defun(n->narg.text, n->narg.next);
8239  success:
8240                 status = 0;
8241  setstatus:
8242                 exitstatus = status;
8243                 break;
8244         }
8245
8246  out:
8247         exception_handler = savehandler;
8248  out1:
8249         if (checkexit & exitstatus)
8250                 evalskip |= SKIPEVAL;
8251         else if (pending_sig && dotrap())
8252                 goto exexit;
8253
8254         if (flags & EV_EXIT) {
8255  exexit:
8256                 raise_exception(EXEXIT);
8257         }
8258
8259         RESTORE_INT(int_level);
8260         TRACE(("leaving evaltree (no interrupts)\n"));
8261 }
8262
8263 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8264 static
8265 #endif
8266 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8267
8268 static void
8269 evalloop(union node *n, int flags)
8270 {
8271         int status;
8272
8273         loopnest++;
8274         status = 0;
8275         flags &= EV_TESTED;
8276         for (;;) {
8277                 int i;
8278
8279                 evaltree(n->nbinary.ch1, EV_TESTED);
8280                 if (evalskip) {
8281  skipping:
8282                         if (evalskip == SKIPCONT && --skipcount <= 0) {
8283                                 evalskip = 0;
8284                                 continue;
8285                         }
8286                         if (evalskip == SKIPBREAK && --skipcount <= 0)
8287                                 evalskip = 0;
8288                         break;
8289                 }
8290                 i = exitstatus;
8291                 if (n->type != NWHILE)
8292                         i = !i;
8293                 if (i != 0)
8294                         break;
8295                 evaltree(n->nbinary.ch2, flags);
8296                 status = exitstatus;
8297                 if (evalskip)
8298                         goto skipping;
8299         }
8300         loopnest--;
8301         exitstatus = status;
8302 }
8303
8304 static void
8305 evalfor(union node *n, int flags)
8306 {
8307         struct arglist arglist;
8308         union node *argp;
8309         struct strlist *sp;
8310         struct stackmark smark;
8311
8312         setstackmark(&smark);
8313         arglist.list = NULL;
8314         arglist.lastp = &arglist.list;
8315         for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8316                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8317                 /* XXX */
8318                 if (evalskip)
8319                         goto out;
8320         }
8321         *arglist.lastp = NULL;
8322
8323         exitstatus = 0;
8324         loopnest++;
8325         flags &= EV_TESTED;
8326         for (sp = arglist.list; sp; sp = sp->next) {
8327                 setvar(n->nfor.var, sp->text, 0);
8328                 evaltree(n->nfor.body, flags);
8329                 if (evalskip) {
8330                         if (evalskip == SKIPCONT && --skipcount <= 0) {
8331                                 evalskip = 0;
8332                                 continue;
8333                         }
8334                         if (evalskip == SKIPBREAK && --skipcount <= 0)
8335                                 evalskip = 0;
8336                         break;
8337                 }
8338         }
8339         loopnest--;
8340  out:
8341         popstackmark(&smark);
8342 }
8343
8344 static void
8345 evalcase(union node *n, int flags)
8346 {
8347         union node *cp;
8348         union node *patp;
8349         struct arglist arglist;
8350         struct stackmark smark;
8351
8352         setstackmark(&smark);
8353         arglist.list = NULL;
8354         arglist.lastp = &arglist.list;
8355         expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8356         exitstatus = 0;
8357         for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8358                 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8359                         if (casematch(patp, arglist.list->text)) {
8360                                 if (evalskip == 0) {
8361                                         evaltree(cp->nclist.body, flags);
8362                                 }
8363                                 goto out;
8364                         }
8365                 }
8366         }
8367  out:
8368         popstackmark(&smark);
8369 }
8370
8371 /*
8372  * Kick off a subshell to evaluate a tree.
8373  */
8374 static void
8375 evalsubshell(union node *n, int flags)
8376 {
8377         struct job *jp;
8378         int backgnd = (n->type == NBACKGND);
8379         int status;
8380
8381         expredir(n->nredir.redirect);
8382         if (!backgnd && flags & EV_EXIT && !trap[0])
8383                 goto nofork;
8384         INT_OFF;
8385         jp = makejob(/*n,*/ 1);
8386         if (forkshell(jp, n, backgnd) == 0) {
8387                 INT_ON;
8388                 flags |= EV_EXIT;
8389                 if (backgnd)
8390                         flags &=~ EV_TESTED;
8391  nofork:
8392                 redirect(n->nredir.redirect, 0);
8393                 evaltreenr(n->nredir.n, flags);
8394                 /* never returns */
8395         }
8396         status = 0;
8397         if (!backgnd)
8398                 status = waitforjob(jp);
8399         exitstatus = status;
8400         INT_ON;
8401 }
8402
8403 /*
8404  * Compute the names of the files in a redirection list.
8405  */
8406 static void fixredir(union node *, const char *, int);
8407 static void
8408 expredir(union node *n)
8409 {
8410         union node *redir;
8411
8412         for (redir = n; redir; redir = redir->nfile.next) {
8413                 struct arglist fn;
8414
8415                 fn.list = NULL;
8416                 fn.lastp = &fn.list;
8417                 switch (redir->type) {
8418                 case NFROMTO:
8419                 case NFROM:
8420                 case NTO:
8421 #if ENABLE_ASH_BASH_COMPAT
8422                 case NTO2:
8423 #endif
8424                 case NCLOBBER:
8425                 case NAPPEND:
8426                         expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8427 #if ENABLE_ASH_BASH_COMPAT
8428  store_expfname:
8429 #endif
8430                         redir->nfile.expfname = fn.list->text;
8431                         break;
8432                 case NFROMFD:
8433                 case NTOFD: /* >& */
8434                         if (redir->ndup.vname) {
8435                                 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8436                                 if (fn.list == NULL)
8437                                         ash_msg_and_raise_error("redir error");
8438 #if ENABLE_ASH_BASH_COMPAT
8439 //FIXME: we used expandarg with different args!
8440                                 if (!isdigit_str9(fn.list->text)) {
8441                                         /* >&file, not >&fd */
8442                                         if (redir->nfile.fd != 1) /* 123>&file - BAD */
8443                                                 ash_msg_and_raise_error("redir error");
8444                                         redir->type = NTO2;
8445                                         goto store_expfname;
8446                                 }
8447 #endif
8448                                 fixredir(redir, fn.list->text, 1);
8449                         }
8450                         break;
8451                 }
8452         }
8453 }
8454
8455 /*
8456  * Evaluate a pipeline.  All the processes in the pipeline are children
8457  * of the process creating the pipeline.  (This differs from some versions
8458  * of the shell, which make the last process in a pipeline the parent
8459  * of all the rest.)
8460  */
8461 static void
8462 evalpipe(union node *n, int flags)
8463 {
8464         struct job *jp;
8465         struct nodelist *lp;
8466         int pipelen;
8467         int prevfd;
8468         int pip[2];
8469
8470         TRACE(("evalpipe(0x%lx) called\n", (long)n));
8471         pipelen = 0;
8472         for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8473                 pipelen++;
8474         flags |= EV_EXIT;
8475         INT_OFF;
8476         jp = makejob(/*n,*/ pipelen);
8477         prevfd = -1;
8478         for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8479                 prehash(lp->n);
8480                 pip[1] = -1;
8481                 if (lp->next) {
8482                         if (pipe(pip) < 0) {
8483                                 close(prevfd);
8484                                 ash_msg_and_raise_error("pipe call failed");
8485                         }
8486                 }
8487                 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8488                         INT_ON;
8489                         if (pip[1] >= 0) {
8490                                 close(pip[0]);
8491                         }
8492                         if (prevfd > 0) {
8493                                 dup2(prevfd, 0);
8494                                 close(prevfd);
8495                         }
8496                         if (pip[1] > 1) {
8497                                 dup2(pip[1], 1);
8498                                 close(pip[1]);
8499                         }
8500                         evaltreenr(lp->n, flags);
8501                         /* never returns */
8502                 }
8503                 if (prevfd >= 0)
8504                         close(prevfd);
8505                 prevfd = pip[0];
8506                 /* Don't want to trigger debugging */
8507                 if (pip[1] != -1)
8508                         close(pip[1]);
8509         }
8510         if (n->npipe.pipe_backgnd == 0) {
8511                 exitstatus = waitforjob(jp);
8512                 TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
8513         }
8514         INT_ON;
8515 }
8516
8517 /*
8518  * Controls whether the shell is interactive or not.
8519  */
8520 static void
8521 setinteractive(int on)
8522 {
8523         static smallint is_interactive;
8524
8525         if (++on == is_interactive)
8526                 return;
8527         is_interactive = on;
8528         setsignal(SIGINT);
8529         setsignal(SIGQUIT);
8530         setsignal(SIGTERM);
8531 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8532         if (is_interactive > 1) {
8533                 /* Looks like they want an interactive shell */
8534                 static smallint did_banner;
8535
8536                 if (!did_banner) {
8537                         out1fmt(
8538                                 "\n\n"
8539                                 "%s built-in shell (ash)\n"
8540                                 "Enter 'help' for a list of built-in commands."
8541                                 "\n\n",
8542                                 bb_banner);
8543                         did_banner = 1;
8544                 }
8545         }
8546 #endif
8547 }
8548
8549 static void
8550 optschanged(void)
8551 {
8552 #if DEBUG
8553         opentrace();
8554 #endif
8555         setinteractive(iflag);
8556         setjobctl(mflag);
8557 #if ENABLE_FEATURE_EDITING_VI
8558         if (viflag)
8559                 line_input_state->flags |= VI_MODE;
8560         else
8561                 line_input_state->flags &= ~VI_MODE;
8562 #else
8563         viflag = 0; /* forcibly keep the option off */
8564 #endif
8565 }
8566
8567 static struct localvar *localvars;
8568
8569 /*
8570  * Called after a function returns.
8571  * Interrupts must be off.
8572  */
8573 static void
8574 poplocalvars(void)
8575 {
8576         struct localvar *lvp;
8577         struct var *vp;
8578
8579         while ((lvp = localvars) != NULL) {
8580                 localvars = lvp->next;
8581                 vp = lvp->vp;
8582                 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8583                 if (vp == NULL) {       /* $- saved */
8584                         memcpy(optlist, lvp->text, sizeof(optlist));
8585                         free((char*)lvp->text);
8586                         optschanged();
8587                 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8588                         unsetvar(vp->text);
8589                 } else {
8590                         if (vp->func)
8591                                 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8592                         if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8593                                 free((char*)vp->text);
8594                         vp->flags = lvp->flags;
8595                         vp->text = lvp->text;
8596                 }
8597                 free(lvp);
8598         }
8599 }
8600
8601 static int
8602 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8603 {
8604         volatile struct shparam saveparam;
8605         struct localvar *volatile savelocalvars;
8606         struct jmploc *volatile savehandler;
8607         struct jmploc jmploc;
8608         int e;
8609
8610         saveparam = shellparam;
8611         savelocalvars = localvars;
8612         e = setjmp(jmploc.loc);
8613         if (e) {
8614                 goto funcdone;
8615         }
8616         INT_OFF;
8617         savehandler = exception_handler;
8618         exception_handler = &jmploc;
8619         localvars = NULL;
8620         shellparam.malloced = 0;
8621         func->count++;
8622         funcnest++;
8623         INT_ON;
8624         shellparam.nparam = argc - 1;
8625         shellparam.p = argv + 1;
8626 #if ENABLE_ASH_GETOPTS
8627         shellparam.optind = 1;
8628         shellparam.optoff = -1;
8629 #endif
8630         evaltree(&func->n, flags & EV_TESTED);
8631  funcdone:
8632         INT_OFF;
8633         funcnest--;
8634         freefunc(func);
8635         poplocalvars();
8636         localvars = savelocalvars;
8637         freeparam(&shellparam);
8638         shellparam = saveparam;
8639         exception_handler = savehandler;
8640         INT_ON;
8641         evalskip &= ~SKIPFUNC;
8642         return e;
8643 }
8644
8645 #if ENABLE_ASH_CMDCMD
8646 static char **
8647 parse_command_args(char **argv, const char **path)
8648 {
8649         char *cp, c;
8650
8651         for (;;) {
8652                 cp = *++argv;
8653                 if (!cp)
8654                         return 0;
8655                 if (*cp++ != '-')
8656                         break;
8657                 c = *cp++;
8658                 if (!c)
8659                         break;
8660                 if (c == '-' && !*cp) {
8661                         argv++;
8662                         break;
8663                 }
8664                 do {
8665                         switch (c) {
8666                         case 'p':
8667                                 *path = bb_default_path;
8668                                 break;
8669                         default:
8670                                 /* run 'typecmd' for other options */
8671                                 return 0;
8672                         }
8673                         c = *cp++;
8674                 } while (c);
8675         }
8676         return argv;
8677 }
8678 #endif
8679
8680 /*
8681  * Make a variable a local variable.  When a variable is made local, it's
8682  * value and flags are saved in a localvar structure.  The saved values
8683  * will be restored when the shell function returns.  We handle the name
8684  * "-" as a special case.
8685  */
8686 static void
8687 mklocal(char *name)
8688 {
8689         struct localvar *lvp;
8690         struct var **vpp;
8691         struct var *vp;
8692
8693         INT_OFF;
8694         lvp = ckzalloc(sizeof(struct localvar));
8695         if (LONE_DASH(name)) {
8696                 char *p;
8697                 p = ckmalloc(sizeof(optlist));
8698                 lvp->text = memcpy(p, optlist, sizeof(optlist));
8699                 vp = NULL;
8700         } else {
8701                 char *eq;
8702
8703                 vpp = hashvar(name);
8704                 vp = *findvar(vpp, name);
8705                 eq = strchr(name, '=');
8706                 if (vp == NULL) {
8707                         if (eq)
8708                                 setvareq(name, VSTRFIXED);
8709                         else
8710                                 setvar(name, NULL, VSTRFIXED);
8711                         vp = *vpp;      /* the new variable */
8712                         lvp->flags = VUNSET;
8713                 } else {
8714                         lvp->text = vp->text;
8715                         lvp->flags = vp->flags;
8716                         vp->flags |= VSTRFIXED|VTEXTFIXED;
8717                         if (eq)
8718                                 setvareq(name, 0);
8719                 }
8720         }
8721         lvp->vp = vp;
8722         lvp->next = localvars;
8723         localvars = lvp;
8724         INT_ON;
8725 }
8726
8727 /*
8728  * The "local" command.
8729  */
8730 static int FAST_FUNC
8731 localcmd(int argc UNUSED_PARAM, char **argv)
8732 {
8733         char *name;
8734
8735         argv = argptr;
8736         while ((name = *argv++) != NULL) {
8737                 mklocal(name);
8738         }
8739         return 0;
8740 }
8741
8742 static int FAST_FUNC
8743 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8744 {
8745         return 1;
8746 }
8747
8748 static int FAST_FUNC
8749 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8750 {
8751         return 0;
8752 }
8753
8754 static int FAST_FUNC
8755 execcmd(int argc UNUSED_PARAM, char **argv)
8756 {
8757         if (argv[1]) {
8758                 iflag = 0;              /* exit on error */
8759                 mflag = 0;
8760                 optschanged();
8761                 shellexec(argv + 1, pathval(), 0);
8762         }
8763         return 0;
8764 }
8765
8766 /*
8767  * The return command.
8768  */
8769 static int FAST_FUNC
8770 returncmd(int argc UNUSED_PARAM, char **argv)
8771 {
8772         /*
8773          * If called outside a function, do what ksh does;
8774          * skip the rest of the file.
8775          */
8776         evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8777         return argv[1] ? number(argv[1]) : exitstatus;
8778 }
8779
8780 /* Forward declarations for builtintab[] */
8781 static int breakcmd(int, char **) FAST_FUNC;
8782 static int dotcmd(int, char **) FAST_FUNC;
8783 static int evalcmd(int, char **) FAST_FUNC;
8784 static int exitcmd(int, char **) FAST_FUNC;
8785 static int exportcmd(int, char **) FAST_FUNC;
8786 #if ENABLE_ASH_GETOPTS
8787 static int getoptscmd(int, char **) FAST_FUNC;
8788 #endif
8789 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8790 static int helpcmd(int, char **) FAST_FUNC;
8791 #endif
8792 #if ENABLE_SH_MATH_SUPPORT
8793 static int letcmd(int, char **) FAST_FUNC;
8794 #endif
8795 static int readcmd(int, char **) FAST_FUNC;
8796 static int setcmd(int, char **) FAST_FUNC;
8797 static int shiftcmd(int, char **) FAST_FUNC;
8798 static int timescmd(int, char **) FAST_FUNC;
8799 static int trapcmd(int, char **) FAST_FUNC;
8800 static int umaskcmd(int, char **) FAST_FUNC;
8801 static int unsetcmd(int, char **) FAST_FUNC;
8802 static int ulimitcmd(int, char **) FAST_FUNC;
8803
8804 #define BUILTIN_NOSPEC          "0"
8805 #define BUILTIN_SPECIAL         "1"
8806 #define BUILTIN_REGULAR         "2"
8807 #define BUILTIN_SPEC_REG        "3"
8808 #define BUILTIN_ASSIGN          "4"
8809 #define BUILTIN_SPEC_ASSG       "5"
8810 #define BUILTIN_REG_ASSG        "6"
8811 #define BUILTIN_SPEC_REG_ASSG   "7"
8812
8813 /* Stubs for calling non-FAST_FUNC's */
8814 #if ENABLE_ASH_BUILTIN_ECHO
8815 static int FAST_FUNC echocmd(int argc, char **argv)   { return echo_main(argc, argv); }
8816 #endif
8817 #if ENABLE_ASH_BUILTIN_PRINTF
8818 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8819 #endif
8820 #if ENABLE_ASH_BUILTIN_TEST
8821 static int FAST_FUNC testcmd(int argc, char **argv)   { return test_main(argc, argv); }
8822 #endif
8823
8824 /* Keep these in proper order since it is searched via bsearch() */
8825 static const struct builtincmd builtintab[] = {
8826         { BUILTIN_SPEC_REG      ".", dotcmd },
8827         { BUILTIN_SPEC_REG      ":", truecmd },
8828 #if ENABLE_ASH_BUILTIN_TEST
8829         { BUILTIN_REGULAR       "[", testcmd },
8830 #if ENABLE_ASH_BASH_COMPAT
8831         { BUILTIN_REGULAR       "[[", testcmd },
8832 #endif
8833 #endif
8834 #if ENABLE_ASH_ALIAS
8835         { BUILTIN_REG_ASSG      "alias", aliascmd },
8836 #endif
8837 #if JOBS
8838         { BUILTIN_REGULAR       "bg", fg_bgcmd },
8839 #endif
8840         { BUILTIN_SPEC_REG      "break", breakcmd },
8841         { BUILTIN_REGULAR       "cd", cdcmd },
8842         { BUILTIN_NOSPEC        "chdir", cdcmd },
8843 #if ENABLE_ASH_CMDCMD
8844         { BUILTIN_REGULAR       "command", commandcmd },
8845 #endif
8846         { BUILTIN_SPEC_REG      "continue", breakcmd },
8847 #if ENABLE_ASH_BUILTIN_ECHO
8848         { BUILTIN_REGULAR       "echo", echocmd },
8849 #endif
8850         { BUILTIN_SPEC_REG      "eval", evalcmd },
8851         { BUILTIN_SPEC_REG      "exec", execcmd },
8852         { BUILTIN_SPEC_REG      "exit", exitcmd },
8853         { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8854         { BUILTIN_REGULAR       "false", falsecmd },
8855 #if JOBS
8856         { BUILTIN_REGULAR       "fg", fg_bgcmd },
8857 #endif
8858 #if ENABLE_ASH_GETOPTS
8859         { BUILTIN_REGULAR       "getopts", getoptscmd },
8860 #endif
8861         { BUILTIN_NOSPEC        "hash", hashcmd },
8862 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8863         { BUILTIN_NOSPEC        "help", helpcmd },
8864 #endif
8865 #if JOBS
8866         { BUILTIN_REGULAR       "jobs", jobscmd },
8867         { BUILTIN_REGULAR       "kill", killcmd },
8868 #endif
8869 #if ENABLE_SH_MATH_SUPPORT
8870         { BUILTIN_NOSPEC        "let", letcmd },
8871 #endif
8872         { BUILTIN_ASSIGN        "local", localcmd },
8873 #if ENABLE_ASH_BUILTIN_PRINTF
8874         { BUILTIN_REGULAR       "printf", printfcmd },
8875 #endif
8876         { BUILTIN_NOSPEC        "pwd", pwdcmd },
8877         { BUILTIN_REGULAR       "read", readcmd },
8878         { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8879         { BUILTIN_SPEC_REG      "return", returncmd },
8880         { BUILTIN_SPEC_REG      "set", setcmd },
8881         { BUILTIN_SPEC_REG      "shift", shiftcmd },
8882         { BUILTIN_SPEC_REG      "source", dotcmd },
8883 #if ENABLE_ASH_BUILTIN_TEST
8884         { BUILTIN_REGULAR       "test", testcmd },
8885 #endif
8886         { BUILTIN_SPEC_REG      "times", timescmd },
8887         { BUILTIN_SPEC_REG      "trap", trapcmd },
8888         { BUILTIN_REGULAR       "true", truecmd },
8889         { BUILTIN_NOSPEC        "type", typecmd },
8890         { BUILTIN_NOSPEC        "ulimit", ulimitcmd },
8891         { BUILTIN_REGULAR       "umask", umaskcmd },
8892 #if ENABLE_ASH_ALIAS
8893         { BUILTIN_REGULAR       "unalias", unaliascmd },
8894 #endif
8895         { BUILTIN_SPEC_REG      "unset", unsetcmd },
8896         { BUILTIN_REGULAR       "wait", waitcmd },
8897 };
8898
8899 /* Should match the above table! */
8900 #define COMMANDCMD (builtintab + \
8901         2 + \
8902         1 * ENABLE_ASH_BUILTIN_TEST + \
8903         1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8904         1 * ENABLE_ASH_ALIAS + \
8905         1 * ENABLE_ASH_JOB_CONTROL + \
8906         3)
8907 #define EXECCMD (builtintab + \
8908         2 + \
8909         1 * ENABLE_ASH_BUILTIN_TEST + \
8910         1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8911         1 * ENABLE_ASH_ALIAS + \
8912         1 * ENABLE_ASH_JOB_CONTROL + \
8913         3 + \
8914         1 * ENABLE_ASH_CMDCMD + \
8915         1 + \
8916         ENABLE_ASH_BUILTIN_ECHO + \
8917         1)
8918
8919 /*
8920  * Search the table of builtin commands.
8921  */
8922 static struct builtincmd *
8923 find_builtin(const char *name)
8924 {
8925         struct builtincmd *bp;
8926
8927         bp = bsearch(
8928                 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8929                 pstrcmp
8930         );
8931         return bp;
8932 }
8933
8934 /*
8935  * Execute a simple command.
8936  */
8937 static int
8938 isassignment(const char *p)
8939 {
8940         const char *q = endofname(p);
8941         if (p == q)
8942                 return 0;
8943         return *q == '=';
8944 }
8945 static int FAST_FUNC
8946 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8947 {
8948         /* Preserve exitstatus of a previous possible redirection
8949          * as POSIX mandates */
8950         return back_exitstatus;
8951 }
8952 static void
8953 evalcommand(union node *cmd, int flags)
8954 {
8955         static const struct builtincmd null_bltin = {
8956                 "\0\0", bltincmd /* why three NULs? */
8957         };
8958         struct stackmark smark;
8959         union node *argp;
8960         struct arglist arglist;
8961         struct arglist varlist;
8962         char **argv;
8963         int argc;
8964         const struct strlist *sp;
8965         struct cmdentry cmdentry;
8966         struct job *jp;
8967         char *lastarg;
8968         const char *path;
8969         int spclbltin;
8970         int status;
8971         char **nargv;
8972         struct builtincmd *bcmd;
8973         smallint cmd_is_exec;
8974         smallint pseudovarflag = 0;
8975
8976         /* First expand the arguments. */
8977         TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8978         setstackmark(&smark);
8979         back_exitstatus = 0;
8980
8981         cmdentry.cmdtype = CMDBUILTIN;
8982         cmdentry.u.cmd = &null_bltin;
8983         varlist.lastp = &varlist.list;
8984         *varlist.lastp = NULL;
8985         arglist.lastp = &arglist.list;
8986         *arglist.lastp = NULL;
8987
8988         argc = 0;
8989         if (cmd->ncmd.args) {
8990                 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8991                 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8992         }
8993
8994         for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8995                 struct strlist **spp;
8996
8997                 spp = arglist.lastp;
8998                 if (pseudovarflag && isassignment(argp->narg.text))
8999                         expandarg(argp, &arglist, EXP_VARTILDE);
9000                 else
9001                         expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9002
9003                 for (sp = *spp; sp; sp = sp->next)
9004                         argc++;
9005         }
9006
9007         argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9008         for (sp = arglist.list; sp; sp = sp->next) {
9009                 TRACE(("evalcommand arg: %s\n", sp->text));
9010                 *nargv++ = sp->text;
9011         }
9012         *nargv = NULL;
9013
9014         lastarg = NULL;
9015         if (iflag && funcnest == 0 && argc > 0)
9016                 lastarg = nargv[-1];
9017
9018         preverrout_fd = 2;
9019         expredir(cmd->ncmd.redirect);
9020         status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9021
9022         path = vpath.text;
9023         for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9024                 struct strlist **spp;
9025                 char *p;
9026
9027                 spp = varlist.lastp;
9028                 expandarg(argp, &varlist, EXP_VARTILDE);
9029
9030                 /*
9031                  * Modify the command lookup path, if a PATH= assignment
9032                  * is present
9033                  */
9034                 p = (*spp)->text;
9035                 if (varequal(p, path))
9036                         path = p;
9037         }
9038
9039         /* Print the command if xflag is set. */
9040         if (xflag) {
9041                 int n;
9042                 const char *p = " %s";
9043
9044                 p++;
9045                 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9046
9047                 sp = varlist.list;
9048                 for (n = 0; n < 2; n++) {
9049                         while (sp) {
9050                                 fdprintf(preverrout_fd, p, sp->text);
9051                                 sp = sp->next;
9052                                 if (*p == '%') {
9053                                         p--;
9054                                 }
9055                         }
9056                         sp = arglist.list;
9057                 }
9058                 safe_write(preverrout_fd, "\n", 1);
9059         }
9060
9061         cmd_is_exec = 0;
9062         spclbltin = -1;
9063
9064         /* Now locate the command. */
9065         if (argc) {
9066                 const char *oldpath;
9067                 int cmd_flag = DO_ERR;
9068
9069                 path += 5;
9070                 oldpath = path;
9071                 for (;;) {
9072                         find_command(argv[0], &cmdentry, cmd_flag, path);
9073                         if (cmdentry.cmdtype == CMDUNKNOWN) {
9074                                 flush_stderr();
9075                                 status = 127;
9076                                 goto bail;
9077                         }
9078
9079                         /* implement bltin and command here */
9080                         if (cmdentry.cmdtype != CMDBUILTIN)
9081                                 break;
9082                         if (spclbltin < 0)
9083                                 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9084                         if (cmdentry.u.cmd == EXECCMD)
9085                                 cmd_is_exec = 1;
9086 #if ENABLE_ASH_CMDCMD
9087                         if (cmdentry.u.cmd == COMMANDCMD) {
9088                                 path = oldpath;
9089                                 nargv = parse_command_args(argv, &path);
9090                                 if (!nargv)
9091                                         break;
9092                                 argc -= nargv - argv;
9093                                 argv = nargv;
9094                                 cmd_flag |= DO_NOFUNC;
9095                         } else
9096 #endif
9097                                 break;
9098                 }
9099         }
9100
9101         if (status) {
9102                 /* We have a redirection error. */
9103                 if (spclbltin > 0)
9104                         raise_exception(EXERROR);
9105  bail:
9106                 exitstatus = status;
9107                 goto out;
9108         }
9109
9110         /* Execute the command. */
9111         switch (cmdentry.cmdtype) {
9112         default:
9113
9114 #if ENABLE_FEATURE_SH_NOFORK
9115 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9116  * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9117         {
9118                 /* find_command() encodes applet_no as (-2 - applet_no) */
9119                 int applet_no = (- cmdentry.u.index - 2);
9120                 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9121                         listsetvar(varlist.list, VEXPORT|VSTACK);
9122                         /* run <applet>_main() */
9123                         exitstatus = run_nofork_applet(applet_no, argv);
9124                         break;
9125                 }
9126         }
9127 #endif
9128                 /* Fork off a child process if necessary. */
9129                 if (!(flags & EV_EXIT) || trap[0]) {
9130                         INT_OFF;
9131                         jp = makejob(/*cmd,*/ 1);
9132                         if (forkshell(jp, cmd, FORK_FG) != 0) {
9133                                 exitstatus = waitforjob(jp);
9134                                 INT_ON;
9135                                 TRACE(("forked child exited with %d\n", exitstatus));
9136                                 break;
9137                         }
9138                         FORCE_INT_ON;
9139                 }
9140                 listsetvar(varlist.list, VEXPORT|VSTACK);
9141                 shellexec(argv, path, cmdentry.u.index);
9142                 /* NOTREACHED */
9143
9144         case CMDBUILTIN:
9145                 cmdenviron = varlist.list;
9146                 if (cmdenviron) {
9147                         struct strlist *list = cmdenviron;
9148                         int i = VNOSET;
9149                         if (spclbltin > 0 || argc == 0) {
9150                                 i = 0;
9151                                 if (cmd_is_exec && argc > 1)
9152                                         i = VEXPORT;
9153                         }
9154                         listsetvar(list, i);
9155                 }
9156                 /* Tight loop with builtins only:
9157                  * "while kill -0 $child; do true; done"
9158                  * will never exit even if $child died, unless we do this
9159                  * to reap the zombie and make kill detect that it's gone: */
9160                 dowait(DOWAIT_NONBLOCK, NULL);
9161
9162                 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9163                         int exit_status;
9164                         int i = exception_type;
9165                         if (i == EXEXIT)
9166                                 goto raise;
9167                         exit_status = 2;
9168                         if (i == EXINT)
9169                                 exit_status = 128 + SIGINT;
9170                         if (i == EXSIG)
9171                                 exit_status = 128 + pending_sig;
9172                         exitstatus = exit_status;
9173                         if (i == EXINT || spclbltin > 0) {
9174  raise:
9175                                 longjmp(exception_handler->loc, 1);
9176                         }
9177                         FORCE_INT_ON;
9178                 }
9179                 break;
9180
9181         case CMDFUNCTION:
9182                 listsetvar(varlist.list, 0);
9183                 /* See above for the rationale */
9184                 dowait(DOWAIT_NONBLOCK, NULL);
9185                 if (evalfun(cmdentry.u.func, argc, argv, flags))
9186                         goto raise;
9187                 break;
9188         }
9189
9190  out:
9191         popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9192         if (lastarg) {
9193                 /* dsl: I think this is intended to be used to support
9194                  * '_' in 'vi' command mode during line editing...
9195                  * However I implemented that within libedit itself.
9196                  */
9197                 setvar("_", lastarg, 0);
9198         }
9199         popstackmark(&smark);
9200 }
9201
9202 static int
9203 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9204 {
9205         char *volatile savecmdname;
9206         struct jmploc *volatile savehandler;
9207         struct jmploc jmploc;
9208         int i;
9209
9210         savecmdname = commandname;
9211         i = setjmp(jmploc.loc);
9212         if (i)
9213                 goto cmddone;
9214         savehandler = exception_handler;
9215         exception_handler = &jmploc;
9216         commandname = argv[0];
9217         argptr = argv + 1;
9218         optptr = NULL;                  /* initialize nextopt */
9219         exitstatus = (*cmd->builtin)(argc, argv);
9220         flush_stdout_stderr();
9221  cmddone:
9222         exitstatus |= ferror(stdout);
9223         clearerr(stdout);
9224         commandname = savecmdname;
9225         exception_handler = savehandler;
9226
9227         return i;
9228 }
9229
9230 static int
9231 goodname(const char *p)
9232 {
9233         return !*endofname(p);
9234 }
9235
9236
9237 /*
9238  * Search for a command.  This is called before we fork so that the
9239  * location of the command will be available in the parent as well as
9240  * the child.  The check for "goodname" is an overly conservative
9241  * check that the name will not be subject to expansion.
9242  */
9243 static void
9244 prehash(union node *n)
9245 {
9246         struct cmdentry entry;
9247
9248         if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9249                 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9250 }
9251
9252
9253 /* ============ Builtin commands
9254  *
9255  * Builtin commands whose functions are closely tied to evaluation
9256  * are implemented here.
9257  */
9258
9259 /*
9260  * Handle break and continue commands.  Break, continue, and return are
9261  * all handled by setting the evalskip flag.  The evaluation routines
9262  * above all check this flag, and if it is set they start skipping
9263  * commands rather than executing them.  The variable skipcount is
9264  * the number of loops to break/continue, or the number of function
9265  * levels to return.  (The latter is always 1.)  It should probably
9266  * be an error to break out of more loops than exist, but it isn't
9267  * in the standard shell so we don't make it one here.
9268  */
9269 static int FAST_FUNC
9270 breakcmd(int argc UNUSED_PARAM, char **argv)
9271 {
9272         int n = argv[1] ? number(argv[1]) : 1;
9273
9274         if (n <= 0)
9275                 ash_msg_and_raise_error(msg_illnum, argv[1]);
9276         if (n > loopnest)
9277                 n = loopnest;
9278         if (n > 0) {
9279                 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9280                 skipcount = n;
9281         }
9282         return 0;
9283 }
9284
9285
9286 /* ============ input.c
9287  *
9288  * This implements the input routines used by the parser.
9289  */
9290
9291 enum {
9292         INPUT_PUSH_FILE = 1,
9293         INPUT_NOFILE_OK = 2,
9294 };
9295
9296 static smallint checkkwd;
9297 /* values of checkkwd variable */
9298 #define CHKALIAS        0x1
9299 #define CHKKWD          0x2
9300 #define CHKNL           0x4
9301
9302 /*
9303  * Push a string back onto the input at this current parsefile level.
9304  * We handle aliases this way.
9305  */
9306 #if !ENABLE_ASH_ALIAS
9307 #define pushstring(s, ap) pushstring(s)
9308 #endif
9309 static void
9310 pushstring(char *s, struct alias *ap)
9311 {
9312         struct strpush *sp;
9313         int len;
9314
9315         len = strlen(s);
9316         INT_OFF;
9317         if (g_parsefile->strpush) {
9318                 sp = ckzalloc(sizeof(*sp));
9319                 sp->prev = g_parsefile->strpush;
9320         } else {
9321                 sp = &(g_parsefile->basestrpush);
9322         }
9323         g_parsefile->strpush = sp;
9324         sp->prev_string = g_parsefile->next_to_pgetc;
9325         sp->prev_left_in_line = g_parsefile->left_in_line;
9326 #if ENABLE_ASH_ALIAS
9327         sp->ap = ap;
9328         if (ap) {
9329                 ap->flag |= ALIASINUSE;
9330                 sp->string = s;
9331         }
9332 #endif
9333         g_parsefile->next_to_pgetc = s;
9334         g_parsefile->left_in_line = len;
9335         INT_ON;
9336 }
9337
9338 static void
9339 popstring(void)
9340 {
9341         struct strpush *sp = g_parsefile->strpush;
9342
9343         INT_OFF;
9344 #if ENABLE_ASH_ALIAS
9345         if (sp->ap) {
9346                 if (g_parsefile->next_to_pgetc[-1] == ' '
9347                  || g_parsefile->next_to_pgetc[-1] == '\t'
9348                 ) {
9349                         checkkwd |= CHKALIAS;
9350                 }
9351                 if (sp->string != sp->ap->val) {
9352                         free(sp->string);
9353                 }
9354                 sp->ap->flag &= ~ALIASINUSE;
9355                 if (sp->ap->flag & ALIASDEAD) {
9356                         unalias(sp->ap->name);
9357                 }
9358         }
9359 #endif
9360         g_parsefile->next_to_pgetc = sp->prev_string;
9361         g_parsefile->left_in_line = sp->prev_left_in_line;
9362         g_parsefile->strpush = sp->prev;
9363         if (sp != &(g_parsefile->basestrpush))
9364                 free(sp);
9365         INT_ON;
9366 }
9367
9368 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9369 //it peeks whether it is &>, and then pushes back both chars.
9370 //This function needs to save last *next_to_pgetc to buf[0]
9371 //to make two pungetc() reliable. Currently,
9372 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9373 static int
9374 preadfd(void)
9375 {
9376         int nr;
9377         char *buf = g_parsefile->buf;
9378
9379         g_parsefile->next_to_pgetc = buf;
9380 #if ENABLE_FEATURE_EDITING
9381  retry:
9382         if (!iflag || g_parsefile->fd != STDIN_FILENO)
9383                 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9384         else {
9385 #if ENABLE_FEATURE_TAB_COMPLETION
9386                 line_input_state->path_lookup = pathval();
9387 #endif
9388                 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9389                 if (nr == 0) {
9390                         /* Ctrl+C pressed */
9391                         if (trap[SIGINT]) {
9392                                 buf[0] = '\n';
9393                                 buf[1] = '\0';
9394                                 raise(SIGINT);
9395                                 return 1;
9396                         }
9397                         goto retry;
9398                 }
9399                 if (nr < 0 && errno == 0) {
9400                         /* Ctrl+D pressed */
9401                         nr = 0;
9402                 }
9403         }
9404 #else
9405         nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9406 #endif
9407
9408 #if 0
9409 /* nonblock_safe_read() handles this problem */
9410         if (nr < 0) {
9411                 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9412                         int flags = fcntl(0, F_GETFL);
9413                         if (flags >= 0 && (flags & O_NONBLOCK)) {
9414                                 flags &= ~O_NONBLOCK;
9415                                 if (fcntl(0, F_SETFL, flags) >= 0) {
9416                                         out2str("sh: turning off NDELAY mode\n");
9417                                         goto retry;
9418                                 }
9419                         }
9420                 }
9421         }
9422 #endif
9423         return nr;
9424 }
9425
9426 /*
9427  * Refill the input buffer and return the next input character:
9428  *
9429  * 1) If a string was pushed back on the input, pop it;
9430  * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9431  *    or we are reading from a string so we can't refill the buffer,
9432  *    return EOF.
9433  * 3) If there is more stuff in this buffer, use it else call read to fill it.
9434  * 4) Process input up to the next newline, deleting nul characters.
9435  */
9436 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9437 #define pgetc_debug(...) ((void)0)
9438 /*
9439  * NB: due to SIT(c) internals (syntax_index_table[] vector),
9440  * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9441  * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9442  * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9443  */
9444 static int
9445 preadbuffer(void)
9446 {
9447         char *q;
9448         int more;
9449
9450         while (g_parsefile->strpush) {
9451 #if ENABLE_ASH_ALIAS
9452                 if (g_parsefile->left_in_line == -1
9453                  && g_parsefile->strpush->ap
9454                  && g_parsefile->next_to_pgetc[-1] != ' '
9455                  && g_parsefile->next_to_pgetc[-1] != '\t'
9456                 ) {
9457                         pgetc_debug("preadbuffer PEOA");
9458                         return PEOA;
9459                 }
9460 #endif
9461                 popstring();
9462                 /* try "pgetc" now: */
9463                 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9464                                 g_parsefile->left_in_line,
9465                                 g_parsefile->next_to_pgetc,
9466                                 g_parsefile->next_to_pgetc);
9467                 if (--g_parsefile->left_in_line >= 0)
9468                         return (unsigned char)(*g_parsefile->next_to_pgetc++);
9469         }
9470         /* on both branches above g_parsefile->left_in_line < 0.
9471          * "pgetc" needs refilling.
9472          */
9473
9474         /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9475          * pungetc() may increment it a few times.
9476          * Assuming it won't increment it to less than -90.
9477          */
9478         if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9479                 pgetc_debug("preadbuffer PEOF1");
9480                 /* even in failure keep left_in_line and next_to_pgetc
9481                  * in lock step, for correct multi-layer pungetc.
9482                  * left_in_line was decremented before preadbuffer(),
9483                  * must inc next_to_pgetc: */
9484                 g_parsefile->next_to_pgetc++;
9485                 return PEOF;
9486         }
9487
9488         more = g_parsefile->left_in_buffer;
9489         if (more <= 0) {
9490                 flush_stdout_stderr();
9491  again:
9492                 more = preadfd();
9493                 if (more <= 0) {
9494                         /* don't try reading again */
9495                         g_parsefile->left_in_line = -99;
9496                         pgetc_debug("preadbuffer PEOF2");
9497                         g_parsefile->next_to_pgetc++;
9498                         return PEOF;
9499                 }
9500         }
9501
9502         /* Find out where's the end of line.
9503          * Set g_parsefile->left_in_line
9504          * and g_parsefile->left_in_buffer acordingly.
9505          * NUL chars are deleted.
9506          */
9507         q = g_parsefile->next_to_pgetc;
9508         for (;;) {
9509                 char c;
9510
9511                 more--;
9512
9513                 c = *q;
9514                 if (c == '\0') {
9515                         memmove(q, q + 1, more);
9516                 } else {
9517                         q++;
9518                         if (c == '\n') {
9519                                 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9520                                 break;
9521                         }
9522                 }
9523
9524                 if (more <= 0) {
9525                         g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9526                         if (g_parsefile->left_in_line < 0)
9527                                 goto again;
9528                         break;
9529                 }
9530         }
9531         g_parsefile->left_in_buffer = more;
9532
9533         if (vflag) {
9534                 char save = *q;
9535                 *q = '\0';
9536                 out2str(g_parsefile->next_to_pgetc);
9537                 *q = save;
9538         }
9539
9540         pgetc_debug("preadbuffer at %d:%p'%s'",
9541                         g_parsefile->left_in_line,
9542                         g_parsefile->next_to_pgetc,
9543                         g_parsefile->next_to_pgetc);
9544         return signed_char2int(*g_parsefile->next_to_pgetc++);
9545 }
9546
9547 #define pgetc_as_macro() \
9548         (--g_parsefile->left_in_line >= 0 \
9549         ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9550         : preadbuffer() \
9551         )
9552
9553 static int
9554 pgetc(void)
9555 {
9556         pgetc_debug("pgetc_fast at %d:%p'%s'",
9557                         g_parsefile->left_in_line,
9558                         g_parsefile->next_to_pgetc,
9559                         g_parsefile->next_to_pgetc);
9560         return pgetc_as_macro();
9561 }
9562
9563 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9564 #define pgetc_fast() pgetc()
9565 #else
9566 #define pgetc_fast() pgetc_as_macro()
9567 #endif
9568
9569 /*
9570  * Same as pgetc(), but ignores PEOA.
9571  */
9572 #if ENABLE_ASH_ALIAS
9573 static int
9574 pgetc2(void)
9575 {
9576         int c;
9577         do {
9578                 pgetc_debug("pgetc_fast at %d:%p'%s'",
9579                                 g_parsefile->left_in_line,
9580                                 g_parsefile->next_to_pgetc,
9581                                 g_parsefile->next_to_pgetc);
9582                 c = pgetc_fast();
9583         } while (c == PEOA);
9584         return c;
9585 }
9586 #else
9587 #define pgetc2() pgetc()
9588 #endif
9589
9590 /*
9591  * Read a line from the script.
9592  */
9593 static char *
9594 pfgets(char *line, int len)
9595 {
9596         char *p = line;
9597         int nleft = len;
9598         int c;
9599
9600         while (--nleft > 0) {
9601                 c = pgetc2();
9602                 if (c == PEOF) {
9603                         if (p == line)
9604                                 return NULL;
9605                         break;
9606                 }
9607                 *p++ = c;
9608                 if (c == '\n')
9609                         break;
9610         }
9611         *p = '\0';
9612         return line;
9613 }
9614
9615 /*
9616  * Undo the last call to pgetc.  Only one character may be pushed back.
9617  * PEOF may be pushed back.
9618  */
9619 static void
9620 pungetc(void)
9621 {
9622         g_parsefile->left_in_line++;
9623         g_parsefile->next_to_pgetc--;
9624         pgetc_debug("pushed back to %d:%p'%s'",
9625                         g_parsefile->left_in_line,
9626                         g_parsefile->next_to_pgetc,
9627                         g_parsefile->next_to_pgetc);
9628 }
9629
9630 /*
9631  * To handle the "." command, a stack of input files is used.  Pushfile
9632  * adds a new entry to the stack and popfile restores the previous level.
9633  */
9634 static void
9635 pushfile(void)
9636 {
9637         struct parsefile *pf;
9638
9639         pf = ckzalloc(sizeof(*pf));
9640         pf->prev = g_parsefile;
9641         pf->fd = -1;
9642         /*pf->strpush = NULL; - ckzalloc did it */
9643         /*pf->basestrpush.prev = NULL;*/
9644         g_parsefile = pf;
9645 }
9646
9647 static void
9648 popfile(void)
9649 {
9650         struct parsefile *pf = g_parsefile;
9651
9652         INT_OFF;
9653         if (pf->fd >= 0)
9654                 close(pf->fd);
9655         free(pf->buf);
9656         while (pf->strpush)
9657                 popstring();
9658         g_parsefile = pf->prev;
9659         free(pf);
9660         INT_ON;
9661 }
9662
9663 /*
9664  * Return to top level.
9665  */
9666 static void
9667 popallfiles(void)
9668 {
9669         while (g_parsefile != &basepf)
9670                 popfile();
9671 }
9672
9673 /*
9674  * Close the file(s) that the shell is reading commands from.  Called
9675  * after a fork is done.
9676  */
9677 static void
9678 closescript(void)
9679 {
9680         popallfiles();
9681         if (g_parsefile->fd > 0) {
9682                 close(g_parsefile->fd);
9683                 g_parsefile->fd = 0;
9684         }
9685 }
9686
9687 /*
9688  * Like setinputfile, but takes an open file descriptor.  Call this with
9689  * interrupts off.
9690  */
9691 static void
9692 setinputfd(int fd, int push)
9693 {
9694         close_on_exec_on(fd);
9695         if (push) {
9696                 pushfile();
9697                 g_parsefile->buf = NULL;
9698         }
9699         g_parsefile->fd = fd;
9700         if (g_parsefile->buf == NULL)
9701                 g_parsefile->buf = ckmalloc(IBUFSIZ);
9702         g_parsefile->left_in_buffer = 0;
9703         g_parsefile->left_in_line = 0;
9704         g_parsefile->linno = 1;
9705 }
9706
9707 /*
9708  * Set the input to take input from a file.  If push is set, push the
9709  * old input onto the stack first.
9710  */
9711 static int
9712 setinputfile(const char *fname, int flags)
9713 {
9714         int fd;
9715         int fd2;
9716
9717         INT_OFF;
9718         fd = open(fname, O_RDONLY);
9719         if (fd < 0) {
9720                 if (flags & INPUT_NOFILE_OK)
9721                         goto out;
9722                 ash_msg_and_raise_error("can't open '%s'", fname);
9723         }
9724         if (fd < 10) {
9725                 fd2 = copyfd(fd, 10);
9726                 close(fd);
9727                 if (fd2 < 0)
9728                         ash_msg_and_raise_error("out of file descriptors");
9729                 fd = fd2;
9730         }
9731         setinputfd(fd, flags & INPUT_PUSH_FILE);
9732  out:
9733         INT_ON;
9734         return fd;
9735 }
9736
9737 /*
9738  * Like setinputfile, but takes input from a string.
9739  */
9740 static void
9741 setinputstring(char *string)
9742 {
9743         INT_OFF;
9744         pushfile();
9745         g_parsefile->next_to_pgetc = string;
9746         g_parsefile->left_in_line = strlen(string);
9747         g_parsefile->buf = NULL;
9748         g_parsefile->linno = 1;
9749         INT_ON;
9750 }
9751
9752
9753 /* ============ mail.c
9754  *
9755  * Routines to check for mail.
9756  */
9757
9758 #if ENABLE_ASH_MAIL
9759
9760 #define MAXMBOXES 10
9761
9762 /* times of mailboxes */
9763 static time_t mailtime[MAXMBOXES];
9764 /* Set if MAIL or MAILPATH is changed. */
9765 static smallint mail_var_path_changed;
9766
9767 /*
9768  * Print appropriate message(s) if mail has arrived.
9769  * If mail_var_path_changed is set,
9770  * then the value of MAIL has mail_var_path_changed,
9771  * so we just update the values.
9772  */
9773 static void
9774 chkmail(void)
9775 {
9776         const char *mpath;
9777         char *p;
9778         char *q;
9779         time_t *mtp;
9780         struct stackmark smark;
9781         struct stat statb;
9782
9783         setstackmark(&smark);
9784         mpath = mpathset() ? mpathval() : mailval();
9785         for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9786                 p = path_advance(&mpath, nullstr);
9787                 if (p == NULL)
9788                         break;
9789                 if (*p == '\0')
9790                         continue;
9791                 for (q = p; *q; q++)
9792                         continue;
9793 #if DEBUG
9794                 if (q[-1] != '/')
9795                         abort();
9796 #endif
9797                 q[-1] = '\0';                   /* delete trailing '/' */
9798                 if (stat(p, &statb) < 0) {
9799                         *mtp = 0;
9800                         continue;
9801                 }
9802                 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9803                         fprintf(
9804                                 stderr, snlfmt,
9805                                 pathopt ? pathopt : "you have mail"
9806                         );
9807                 }
9808                 *mtp = statb.st_mtime;
9809         }
9810         mail_var_path_changed = 0;
9811         popstackmark(&smark);
9812 }
9813
9814 static void FAST_FUNC
9815 changemail(const char *val UNUSED_PARAM)
9816 {
9817         mail_var_path_changed = 1;
9818 }
9819
9820 #endif /* ASH_MAIL */
9821
9822
9823 /* ============ ??? */
9824
9825 /*
9826  * Set the shell parameters.
9827  */
9828 static void
9829 setparam(char **argv)
9830 {
9831         char **newparam;
9832         char **ap;
9833         int nparam;
9834
9835         for (nparam = 0; argv[nparam]; nparam++)
9836                 continue;
9837         ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9838         while (*argv) {
9839                 *ap++ = ckstrdup(*argv++);
9840         }
9841         *ap = NULL;
9842         freeparam(&shellparam);
9843         shellparam.malloced = 1;
9844         shellparam.nparam = nparam;
9845         shellparam.p = newparam;
9846 #if ENABLE_ASH_GETOPTS
9847         shellparam.optind = 1;
9848         shellparam.optoff = -1;
9849 #endif
9850 }
9851
9852 /*
9853  * Process shell options.  The global variable argptr contains a pointer
9854  * to the argument list; we advance it past the options.
9855  *
9856  * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9857  * For a non-interactive shell, an error condition encountered
9858  * by a special built-in ... shall cause the shell to write a diagnostic message
9859  * to standard error and exit as shown in the following table:
9860  * Error                                           Special Built-In
9861  * ...
9862  * Utility syntax error (option or operand error)  Shall exit
9863  * ...
9864  * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9865  * we see that bash does not do that (set "finishes" with error code 1 instead,
9866  * and shell continues), and people rely on this behavior!
9867  * Testcase:
9868  * set -o barfoo 2>/dev/null
9869  * echo $?
9870  *
9871  * Oh well. Let's mimic that.
9872  */
9873 static int
9874 plus_minus_o(char *name, int val)
9875 {
9876         int i;
9877
9878         if (name) {
9879                 for (i = 0; i < NOPTS; i++) {
9880                         if (strcmp(name, optnames(i)) == 0) {
9881                                 optlist[i] = val;
9882                                 return 0;
9883                         }
9884                 }
9885                 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9886                 return 1;
9887         }
9888         for (i = 0; i < NOPTS; i++) {
9889                 if (val) {
9890                         out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9891                 } else {
9892                         out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9893                 }
9894         }
9895         return 0;
9896 }
9897 static void
9898 setoption(int flag, int val)
9899 {
9900         int i;
9901
9902         for (i = 0; i < NOPTS; i++) {
9903                 if (optletters(i) == flag) {
9904                         optlist[i] = val;
9905                         return;
9906                 }
9907         }
9908         ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9909         /* NOTREACHED */
9910 }
9911 static int
9912 options(int cmdline)
9913 {
9914         char *p;
9915         int val;
9916         int c;
9917
9918         if (cmdline)
9919                 minusc = NULL;
9920         while ((p = *argptr) != NULL) {
9921                 c = *p++;
9922                 if (c != '-' && c != '+')
9923                         break;
9924                 argptr++;
9925                 val = 0; /* val = 0 if c == '+' */
9926                 if (c == '-') {
9927                         val = 1;
9928                         if (p[0] == '\0' || LONE_DASH(p)) {
9929                                 if (!cmdline) {
9930                                         /* "-" means turn off -x and -v */
9931                                         if (p[0] == '\0')
9932                                                 xflag = vflag = 0;
9933                                         /* "--" means reset params */
9934                                         else if (*argptr == NULL)
9935                                                 setparam(argptr);
9936                                 }
9937                                 break;    /* "-" or  "--" terminates options */
9938                         }
9939                 }
9940                 /* first char was + or - */
9941                 while ((c = *p++) != '\0') {
9942                         /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9943                         if (c == 'c' && cmdline) {
9944                                 minusc = p;     /* command is after shell args */
9945                         } else if (c == 'o') {
9946                                 if (plus_minus_o(*argptr, val)) {
9947                                         /* it already printed err message */
9948                                         return 1; /* error */
9949                                 }
9950                                 if (*argptr)
9951                                         argptr++;
9952                         } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9953                                 isloginsh = 1;
9954                         /* bash does not accept +-login, we also won't */
9955                         } else if (cmdline && val && (c == '-')) { /* long options */
9956                                 if (strcmp(p, "login") == 0)
9957                                         isloginsh = 1;
9958                                 break;
9959                         } else {
9960                                 setoption(c, val);
9961                         }
9962                 }
9963         }
9964         return 0;
9965 }
9966
9967 /*
9968  * The shift builtin command.
9969  */
9970 static int FAST_FUNC
9971 shiftcmd(int argc UNUSED_PARAM, char **argv)
9972 {
9973         int n;
9974         char **ap1, **ap2;
9975
9976         n = 1;
9977         if (argv[1])
9978                 n = number(argv[1]);
9979         if (n > shellparam.nparam)
9980                 n = 0; /* bash compat, was = shellparam.nparam; */
9981         INT_OFF;
9982         shellparam.nparam -= n;
9983         for (ap1 = shellparam.p; --n >= 0; ap1++) {
9984                 if (shellparam.malloced)
9985                         free(*ap1);
9986         }
9987         ap2 = shellparam.p;
9988         while ((*ap2++ = *ap1++) != NULL)
9989                 continue;
9990 #if ENABLE_ASH_GETOPTS
9991         shellparam.optind = 1;
9992         shellparam.optoff = -1;
9993 #endif
9994         INT_ON;
9995         return 0;
9996 }
9997
9998 /*
9999  * POSIX requires that 'set' (but not export or readonly) output the
10000  * variables in lexicographic order - by the locale's collating order (sigh).
10001  * Maybe we could keep them in an ordered balanced binary tree
10002  * instead of hashed lists.
10003  * For now just roll 'em through qsort for printing...
10004  */
10005 static int
10006 showvars(const char *sep_prefix, int on, int off)
10007 {
10008         const char *sep;
10009         char **ep, **epend;
10010
10011         ep = listvars(on, off, &epend);
10012         qsort(ep, epend - ep, sizeof(char *), vpcmp);
10013
10014         sep = *sep_prefix ? " " : sep_prefix;
10015
10016         for (; ep < epend; ep++) {
10017                 const char *p;
10018                 const char *q;
10019
10020                 p = strchrnul(*ep, '=');
10021                 q = nullstr;
10022                 if (*p)
10023                         q = single_quote(++p);
10024                 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10025         }
10026         return 0;
10027 }
10028
10029 /*
10030  * The set command builtin.
10031  */
10032 static int FAST_FUNC
10033 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10034 {
10035         int retval;
10036
10037         if (!argv[1])
10038                 return showvars(nullstr, 0, VUNSET);
10039         INT_OFF;
10040         retval = 1;
10041         if (!options(0)) { /* if no parse error... */
10042                 retval = 0;
10043                 optschanged();
10044                 if (*argptr != NULL) {
10045                         setparam(argptr);
10046                 }
10047         }
10048         INT_ON;
10049         return retval;
10050 }
10051
10052 #if ENABLE_ASH_RANDOM_SUPPORT
10053 static void FAST_FUNC
10054 change_random(const char *value)
10055 {
10056         /* Galois LFSR parameter */
10057         /* Taps at 32 31 29 1: */
10058         enum { MASK = 0x8000000b };
10059         /* Another example - taps at 32 31 30 10: */
10060         /* MASK = 0x00400007 */
10061
10062         if (value == NULL) {
10063                 /* "get", generate */
10064                 uint32_t t;
10065
10066                 /* LCG has period of 2^32 and alternating lowest bit */
10067                 random_LCG = 1664525 * random_LCG + 1013904223;
10068                 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10069                 t = (random_galois_LFSR << 1);
10070                 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10071                         t ^= MASK;
10072                 random_galois_LFSR = t;
10073                 /* Both are weak, combining them gives better randomness
10074                  * and ~2^64 period. & 0x7fff is probably bash compat
10075                  * for $RANDOM range. Combining with subtraction is
10076                  * just for fun. + and ^ would work equally well. */
10077                 t = (t - random_LCG) & 0x7fff;
10078                 /* set without recursion */
10079                 setvar(vrandom.text, utoa(t), VNOFUNC);
10080                 vrandom.flags &= ~VNOFUNC;
10081         } else {
10082                 /* set/reset */
10083                 random_galois_LFSR = random_LCG = strtoul(value, NULL, 10);
10084         }
10085 }
10086 #endif
10087
10088 #if ENABLE_ASH_GETOPTS
10089 static int
10090 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10091 {
10092         char *p, *q;
10093         char c = '?';
10094         int done = 0;
10095         int err = 0;
10096         char s[12];
10097         char **optnext;
10098
10099         if (*param_optind < 1)
10100                 return 1;
10101         optnext = optfirst + *param_optind - 1;
10102
10103         if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10104                 p = NULL;
10105         else
10106                 p = optnext[-1] + *optoff;
10107         if (p == NULL || *p == '\0') {
10108                 /* Current word is done, advance */
10109                 p = *optnext;
10110                 if (p == NULL || *p != '-' || *++p == '\0') {
10111  atend:
10112                         p = NULL;
10113                         done = 1;
10114                         goto out;
10115                 }
10116                 optnext++;
10117                 if (LONE_DASH(p))        /* check for "--" */
10118                         goto atend;
10119         }
10120
10121         c = *p++;
10122         for (q = optstr; *q != c;) {
10123                 if (*q == '\0') {
10124                         if (optstr[0] == ':') {
10125                                 s[0] = c;
10126                                 s[1] = '\0';
10127                                 err |= setvarsafe("OPTARG", s, 0);
10128                         } else {
10129                                 fprintf(stderr, "Illegal option -%c\n", c);
10130                                 unsetvar("OPTARG");
10131                         }
10132                         c = '?';
10133                         goto out;
10134                 }
10135                 if (*++q == ':')
10136                         q++;
10137         }
10138
10139         if (*++q == ':') {
10140                 if (*p == '\0' && (p = *optnext) == NULL) {
10141                         if (optstr[0] == ':') {
10142                                 s[0] = c;
10143                                 s[1] = '\0';
10144                                 err |= setvarsafe("OPTARG", s, 0);
10145                                 c = ':';
10146                         } else {
10147                                 fprintf(stderr, "No arg for -%c option\n", c);
10148                                 unsetvar("OPTARG");
10149                                 c = '?';
10150                         }
10151                         goto out;
10152                 }
10153
10154                 if (p == *optnext)
10155                         optnext++;
10156                 err |= setvarsafe("OPTARG", p, 0);
10157                 p = NULL;
10158         } else
10159                 err |= setvarsafe("OPTARG", nullstr, 0);
10160  out:
10161         *optoff = p ? p - *(optnext - 1) : -1;
10162         *param_optind = optnext - optfirst + 1;
10163         fmtstr(s, sizeof(s), "%d", *param_optind);
10164         err |= setvarsafe("OPTIND", s, VNOFUNC);
10165         s[0] = c;
10166         s[1] = '\0';
10167         err |= setvarsafe(optvar, s, 0);
10168         if (err) {
10169                 *param_optind = 1;
10170                 *optoff = -1;
10171                 flush_stdout_stderr();
10172                 raise_exception(EXERROR);
10173         }
10174         return done;
10175 }
10176
10177 /*
10178  * The getopts builtin.  Shellparam.optnext points to the next argument
10179  * to be processed.  Shellparam.optptr points to the next character to
10180  * be processed in the current argument.  If shellparam.optnext is NULL,
10181  * then it's the first time getopts has been called.
10182  */
10183 static int FAST_FUNC
10184 getoptscmd(int argc, char **argv)
10185 {
10186         char **optbase;
10187
10188         if (argc < 3)
10189                 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10190         if (argc == 3) {
10191                 optbase = shellparam.p;
10192                 if (shellparam.optind > shellparam.nparam + 1) {
10193                         shellparam.optind = 1;
10194                         shellparam.optoff = -1;
10195                 }
10196         } else {
10197                 optbase = &argv[3];
10198                 if (shellparam.optind > argc - 2) {
10199                         shellparam.optind = 1;
10200                         shellparam.optoff = -1;
10201                 }
10202         }
10203
10204         return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10205                         &shellparam.optoff);
10206 }
10207 #endif /* ASH_GETOPTS */
10208
10209
10210 /* ============ Shell parser */
10211
10212 struct heredoc {
10213         struct heredoc *next;   /* next here document in list */
10214         union node *here;       /* redirection node */
10215         char *eofmark;          /* string indicating end of input */
10216         smallint striptabs;     /* if set, strip leading tabs */
10217 };
10218
10219 static smallint tokpushback;           /* last token pushed back */
10220 static smallint parsebackquote;        /* nonzero if we are inside backquotes */
10221 static smallint quoteflag;             /* set if (part of) last token was quoted */
10222 static token_id_t lasttoken;           /* last token read (integer id Txxx) */
10223 static struct heredoc *heredoclist;    /* list of here documents to read */
10224 static char *wordtext;                 /* text of last word returned by readtoken */
10225 static struct nodelist *backquotelist;
10226 static union node *redirnode;
10227 static struct heredoc *heredoc;
10228
10229 /*
10230  * Called when an unexpected token is read during the parse.  The argument
10231  * is the token that is expected, or -1 if more than one type of token can
10232  * occur at this point.
10233  */
10234 static void raise_error_unexpected_syntax(int) NORETURN;
10235 static void
10236 raise_error_unexpected_syntax(int token)
10237 {
10238         char msg[64];
10239         int l;
10240
10241         l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10242         if (token >= 0)
10243                 sprintf(msg + l, " (expecting %s)", tokname(token));
10244         raise_error_syntax(msg);
10245         /* NOTREACHED */
10246 }
10247
10248 #define EOFMARKLEN 79
10249
10250 /* parsing is heavily cross-recursive, need these forward decls */
10251 static union node *andor(void);
10252 static union node *pipeline(void);
10253 static union node *parse_command(void);
10254 static void parseheredoc(void);
10255 static char peektoken(void);
10256 static int readtoken(void);
10257
10258 static union node *
10259 list(int nlflag)
10260 {
10261         union node *n1, *n2, *n3;
10262         int tok;
10263
10264         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10265         if (nlflag == 2 && peektoken())
10266                 return NULL;
10267         n1 = NULL;
10268         for (;;) {
10269                 n2 = andor();
10270                 tok = readtoken();
10271                 if (tok == TBACKGND) {
10272                         if (n2->type == NPIPE) {
10273                                 n2->npipe.pipe_backgnd = 1;
10274                         } else {
10275                                 if (n2->type != NREDIR) {
10276                                         n3 = stzalloc(sizeof(struct nredir));
10277                                         n3->nredir.n = n2;
10278                                         /*n3->nredir.redirect = NULL; - stzalloc did it */
10279                                         n2 = n3;
10280                                 }
10281                                 n2->type = NBACKGND;
10282                         }
10283                 }
10284                 if (n1 == NULL) {
10285                         n1 = n2;
10286                 } else {
10287                         n3 = stzalloc(sizeof(struct nbinary));
10288                         n3->type = NSEMI;
10289                         n3->nbinary.ch1 = n1;
10290                         n3->nbinary.ch2 = n2;
10291                         n1 = n3;
10292                 }
10293                 switch (tok) {
10294                 case TBACKGND:
10295                 case TSEMI:
10296                         tok = readtoken();
10297                         /* fall through */
10298                 case TNL:
10299                         if (tok == TNL) {
10300                                 parseheredoc();
10301                                 if (nlflag == 1)
10302                                         return n1;
10303                         } else {
10304                                 tokpushback = 1;
10305                         }
10306                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10307                         if (peektoken())
10308                                 return n1;
10309                         break;
10310                 case TEOF:
10311                         if (heredoclist)
10312                                 parseheredoc();
10313                         else
10314                                 pungetc();              /* push back EOF on input */
10315                         return n1;
10316                 default:
10317                         if (nlflag == 1)
10318                                 raise_error_unexpected_syntax(-1);
10319                         tokpushback = 1;
10320                         return n1;
10321                 }
10322         }
10323 }
10324
10325 static union node *
10326 andor(void)
10327 {
10328         union node *n1, *n2, *n3;
10329         int t;
10330
10331         n1 = pipeline();
10332         for (;;) {
10333                 t = readtoken();
10334                 if (t == TAND) {
10335                         t = NAND;
10336                 } else if (t == TOR) {
10337                         t = NOR;
10338                 } else {
10339                         tokpushback = 1;
10340                         return n1;
10341                 }
10342                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10343                 n2 = pipeline();
10344                 n3 = stzalloc(sizeof(struct nbinary));
10345                 n3->type = t;
10346                 n3->nbinary.ch1 = n1;
10347                 n3->nbinary.ch2 = n2;
10348                 n1 = n3;
10349         }
10350 }
10351
10352 static union node *
10353 pipeline(void)
10354 {
10355         union node *n1, *n2, *pipenode;
10356         struct nodelist *lp, *prev;
10357         int negate;
10358
10359         negate = 0;
10360         TRACE(("pipeline: entered\n"));
10361         if (readtoken() == TNOT) {
10362                 negate = !negate;
10363                 checkkwd = CHKKWD | CHKALIAS;
10364         } else
10365                 tokpushback = 1;
10366         n1 = parse_command();
10367         if (readtoken() == TPIPE) {
10368                 pipenode = stzalloc(sizeof(struct npipe));
10369                 pipenode->type = NPIPE;
10370                 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10371                 lp = stzalloc(sizeof(struct nodelist));
10372                 pipenode->npipe.cmdlist = lp;
10373                 lp->n = n1;
10374                 do {
10375                         prev = lp;
10376                         lp = stzalloc(sizeof(struct nodelist));
10377                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10378                         lp->n = parse_command();
10379                         prev->next = lp;
10380                 } while (readtoken() == TPIPE);
10381                 lp->next = NULL;
10382                 n1 = pipenode;
10383         }
10384         tokpushback = 1;
10385         if (negate) {
10386                 n2 = stzalloc(sizeof(struct nnot));
10387                 n2->type = NNOT;
10388                 n2->nnot.com = n1;
10389                 return n2;
10390         }
10391         return n1;
10392 }
10393
10394 static union node *
10395 makename(void)
10396 {
10397         union node *n;
10398
10399         n = stzalloc(sizeof(struct narg));
10400         n->type = NARG;
10401         /*n->narg.next = NULL; - stzalloc did it */
10402         n->narg.text = wordtext;
10403         n->narg.backquote = backquotelist;
10404         return n;
10405 }
10406
10407 static void
10408 fixredir(union node *n, const char *text, int err)
10409 {
10410         int fd;
10411
10412         TRACE(("Fix redir %s %d\n", text, err));
10413         if (!err)
10414                 n->ndup.vname = NULL;
10415
10416         fd = bb_strtou(text, NULL, 10);
10417         if (!errno && fd >= 0)
10418                 n->ndup.dupfd = fd;
10419         else if (LONE_DASH(text))
10420                 n->ndup.dupfd = -1;
10421         else {
10422                 if (err)
10423                         raise_error_syntax("bad fd number");
10424                 n->ndup.vname = makename();
10425         }
10426 }
10427
10428 /*
10429  * Returns true if the text contains nothing to expand (no dollar signs
10430  * or backquotes).
10431  */
10432 static int
10433 noexpand(const char *text)
10434 {
10435         const char *p;
10436         char c;
10437
10438         p = text;
10439         while ((c = *p++) != '\0') {
10440                 if (c == CTLQUOTEMARK)
10441                         continue;
10442                 if (c == CTLESC)
10443                         p++;
10444                 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10445                         return 0;
10446         }
10447         return 1;
10448 }
10449
10450 static void
10451 parsefname(void)
10452 {
10453         union node *n = redirnode;
10454
10455         if (readtoken() != TWORD)
10456                 raise_error_unexpected_syntax(-1);
10457         if (n->type == NHERE) {
10458                 struct heredoc *here = heredoc;
10459                 struct heredoc *p;
10460                 int i;
10461
10462                 if (quoteflag == 0)
10463                         n->type = NXHERE;
10464                 TRACE(("Here document %d\n", n->type));
10465                 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10466                         raise_error_syntax("illegal eof marker for << redirection");
10467                 rmescapes(wordtext, 0);
10468                 here->eofmark = wordtext;
10469                 here->next = NULL;
10470                 if (heredoclist == NULL)
10471                         heredoclist = here;
10472                 else {
10473                         for (p = heredoclist; p->next; p = p->next)
10474                                 continue;
10475                         p->next = here;
10476                 }
10477         } else if (n->type == NTOFD || n->type == NFROMFD) {
10478                 fixredir(n, wordtext, 0);
10479         } else {
10480                 n->nfile.fname = makename();
10481         }
10482 }
10483
10484 static union node *
10485 simplecmd(void)
10486 {
10487         union node *args, **app;
10488         union node *n = NULL;
10489         union node *vars, **vpp;
10490         union node **rpp, *redir;
10491         int savecheckkwd;
10492 #if ENABLE_ASH_BASH_COMPAT
10493         smallint double_brackets_flag = 0;
10494 #endif
10495
10496         args = NULL;
10497         app = &args;
10498         vars = NULL;
10499         vpp = &vars;
10500         redir = NULL;
10501         rpp = &redir;
10502
10503         savecheckkwd = CHKALIAS;
10504         for (;;) {
10505                 int t;
10506                 checkkwd = savecheckkwd;
10507                 t = readtoken();
10508                 switch (t) {
10509 #if ENABLE_ASH_BASH_COMPAT
10510                 case TAND: /* "&&" */
10511                 case TOR: /* "||" */
10512                         if (!double_brackets_flag) {
10513                                 tokpushback = 1;
10514                                 goto out;
10515                         }
10516                         wordtext = (char *) (t == TAND ? "-a" : "-o");
10517 #endif
10518                 case TWORD:
10519                         n = stzalloc(sizeof(struct narg));
10520                         n->type = NARG;
10521                         /*n->narg.next = NULL; - stzalloc did it */
10522                         n->narg.text = wordtext;
10523 #if ENABLE_ASH_BASH_COMPAT
10524                         if (strcmp("[[", wordtext) == 0)
10525                                 double_brackets_flag = 1;
10526                         else if (strcmp("]]", wordtext) == 0)
10527                                 double_brackets_flag = 0;
10528 #endif
10529                         n->narg.backquote = backquotelist;
10530                         if (savecheckkwd && isassignment(wordtext)) {
10531                                 *vpp = n;
10532                                 vpp = &n->narg.next;
10533                         } else {
10534                                 *app = n;
10535                                 app = &n->narg.next;
10536                                 savecheckkwd = 0;
10537                         }
10538                         break;
10539                 case TREDIR:
10540                         *rpp = n = redirnode;
10541                         rpp = &n->nfile.next;
10542                         parsefname();   /* read name of redirection file */
10543                         break;
10544                 case TLP:
10545                         if (args && app == &args->narg.next
10546                          && !vars && !redir
10547                         ) {
10548                                 struct builtincmd *bcmd;
10549                                 const char *name;
10550
10551                                 /* We have a function */
10552                                 if (readtoken() != TRP)
10553                                         raise_error_unexpected_syntax(TRP);
10554                                 name = n->narg.text;
10555                                 if (!goodname(name)
10556                                  || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10557                                 ) {
10558                                         raise_error_syntax("bad function name");
10559                                 }
10560                                 n->type = NDEFUN;
10561                                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10562                                 n->narg.next = parse_command();
10563                                 return n;
10564                         }
10565                         /* fall through */
10566                 default:
10567                         tokpushback = 1;
10568                         goto out;
10569                 }
10570         }
10571  out:
10572         *app = NULL;
10573         *vpp = NULL;
10574         *rpp = NULL;
10575         n = stzalloc(sizeof(struct ncmd));
10576         n->type = NCMD;
10577         n->ncmd.args = args;
10578         n->ncmd.assign = vars;
10579         n->ncmd.redirect = redir;
10580         return n;
10581 }
10582
10583 static union node *
10584 parse_command(void)
10585 {
10586         union node *n1, *n2;
10587         union node *ap, **app;
10588         union node *cp, **cpp;
10589         union node *redir, **rpp;
10590         union node **rpp2;
10591         int t;
10592
10593         redir = NULL;
10594         rpp2 = &redir;
10595
10596         switch (readtoken()) {
10597         default:
10598                 raise_error_unexpected_syntax(-1);
10599                 /* NOTREACHED */
10600         case TIF:
10601                 n1 = stzalloc(sizeof(struct nif));
10602                 n1->type = NIF;
10603                 n1->nif.test = list(0);
10604                 if (readtoken() != TTHEN)
10605                         raise_error_unexpected_syntax(TTHEN);
10606                 n1->nif.ifpart = list(0);
10607                 n2 = n1;
10608                 while (readtoken() == TELIF) {
10609                         n2->nif.elsepart = stzalloc(sizeof(struct nif));
10610                         n2 = n2->nif.elsepart;
10611                         n2->type = NIF;
10612                         n2->nif.test = list(0);
10613                         if (readtoken() != TTHEN)
10614                                 raise_error_unexpected_syntax(TTHEN);
10615                         n2->nif.ifpart = list(0);
10616                 }
10617                 if (lasttoken == TELSE)
10618                         n2->nif.elsepart = list(0);
10619                 else {
10620                         n2->nif.elsepart = NULL;
10621                         tokpushback = 1;
10622                 }
10623                 t = TFI;
10624                 break;
10625         case TWHILE:
10626         case TUNTIL: {
10627                 int got;
10628                 n1 = stzalloc(sizeof(struct nbinary));
10629                 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10630                 n1->nbinary.ch1 = list(0);
10631                 got = readtoken();
10632                 if (got != TDO) {
10633                         TRACE(("expecting DO got %s %s\n", tokname(got),
10634                                         got == TWORD ? wordtext : ""));
10635                         raise_error_unexpected_syntax(TDO);
10636                 }
10637                 n1->nbinary.ch2 = list(0);
10638                 t = TDONE;
10639                 break;
10640         }
10641         case TFOR:
10642                 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10643                         raise_error_syntax("bad for loop variable");
10644                 n1 = stzalloc(sizeof(struct nfor));
10645                 n1->type = NFOR;
10646                 n1->nfor.var = wordtext;
10647                 checkkwd = CHKKWD | CHKALIAS;
10648                 if (readtoken() == TIN) {
10649                         app = &ap;
10650                         while (readtoken() == TWORD) {
10651                                 n2 = stzalloc(sizeof(struct narg));
10652                                 n2->type = NARG;
10653                                 /*n2->narg.next = NULL; - stzalloc did it */
10654                                 n2->narg.text = wordtext;
10655                                 n2->narg.backquote = backquotelist;
10656                                 *app = n2;
10657                                 app = &n2->narg.next;
10658                         }
10659                         *app = NULL;
10660                         n1->nfor.args = ap;
10661                         if (lasttoken != TNL && lasttoken != TSEMI)
10662                                 raise_error_unexpected_syntax(-1);
10663                 } else {
10664                         n2 = stzalloc(sizeof(struct narg));
10665                         n2->type = NARG;
10666                         /*n2->narg.next = NULL; - stzalloc did it */
10667                         n2->narg.text = (char *)dolatstr;
10668                         /*n2->narg.backquote = NULL;*/
10669                         n1->nfor.args = n2;
10670                         /*
10671                          * Newline or semicolon here is optional (but note
10672                          * that the original Bourne shell only allowed NL).
10673                          */
10674                         if (lasttoken != TNL && lasttoken != TSEMI)
10675                                 tokpushback = 1;
10676                 }
10677                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10678                 if (readtoken() != TDO)
10679                         raise_error_unexpected_syntax(TDO);
10680                 n1->nfor.body = list(0);
10681                 t = TDONE;
10682                 break;
10683         case TCASE:
10684                 n1 = stzalloc(sizeof(struct ncase));
10685                 n1->type = NCASE;
10686                 if (readtoken() != TWORD)
10687                         raise_error_unexpected_syntax(TWORD);
10688                 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10689                 n2->type = NARG;
10690                 /*n2->narg.next = NULL; - stzalloc did it */
10691                 n2->narg.text = wordtext;
10692                 n2->narg.backquote = backquotelist;
10693                 do {
10694                         checkkwd = CHKKWD | CHKALIAS;
10695                 } while (readtoken() == TNL);
10696                 if (lasttoken != TIN)
10697                         raise_error_unexpected_syntax(TIN);
10698                 cpp = &n1->ncase.cases;
10699  next_case:
10700                 checkkwd = CHKNL | CHKKWD;
10701                 t = readtoken();
10702                 while (t != TESAC) {
10703                         if (lasttoken == TLP)
10704                                 readtoken();
10705                         *cpp = cp = stzalloc(sizeof(struct nclist));
10706                         cp->type = NCLIST;
10707                         app = &cp->nclist.pattern;
10708                         for (;;) {
10709                                 *app = ap = stzalloc(sizeof(struct narg));
10710                                 ap->type = NARG;
10711                                 /*ap->narg.next = NULL; - stzalloc did it */
10712                                 ap->narg.text = wordtext;
10713                                 ap->narg.backquote = backquotelist;
10714                                 if (readtoken() != TPIPE)
10715                                         break;
10716                                 app = &ap->narg.next;
10717                                 readtoken();
10718                         }
10719                         //ap->narg.next = NULL;
10720                         if (lasttoken != TRP)
10721                                 raise_error_unexpected_syntax(TRP);
10722                         cp->nclist.body = list(2);
10723
10724                         cpp = &cp->nclist.next;
10725
10726                         checkkwd = CHKNL | CHKKWD;
10727                         t = readtoken();
10728                         if (t != TESAC) {
10729                                 if (t != TENDCASE)
10730                                         raise_error_unexpected_syntax(TENDCASE);
10731                                 goto next_case;
10732                         }
10733                 }
10734                 *cpp = NULL;
10735                 goto redir;
10736         case TLP:
10737                 n1 = stzalloc(sizeof(struct nredir));
10738                 n1->type = NSUBSHELL;
10739                 n1->nredir.n = list(0);
10740                 /*n1->nredir.redirect = NULL; - stzalloc did it */
10741                 t = TRP;
10742                 break;
10743         case TBEGIN:
10744                 n1 = list(0);
10745                 t = TEND;
10746                 break;
10747         case TWORD:
10748         case TREDIR:
10749                 tokpushback = 1;
10750                 return simplecmd();
10751         }
10752
10753         if (readtoken() != t)
10754                 raise_error_unexpected_syntax(t);
10755
10756  redir:
10757         /* Now check for redirection which may follow command */
10758         checkkwd = CHKKWD | CHKALIAS;
10759         rpp = rpp2;
10760         while (readtoken() == TREDIR) {
10761                 *rpp = n2 = redirnode;
10762                 rpp = &n2->nfile.next;
10763                 parsefname();
10764         }
10765         tokpushback = 1;
10766         *rpp = NULL;
10767         if (redir) {
10768                 if (n1->type != NSUBSHELL) {
10769                         n2 = stzalloc(sizeof(struct nredir));
10770                         n2->type = NREDIR;
10771                         n2->nredir.n = n1;
10772                         n1 = n2;
10773                 }
10774                 n1->nredir.redirect = redir;
10775         }
10776         return n1;
10777 }
10778
10779 #if ENABLE_ASH_BASH_COMPAT
10780 static int decode_dollar_squote(void)
10781 {
10782         static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10783         int c, cnt;
10784         char *p;
10785         char buf[4];
10786
10787         c = pgetc();
10788         p = strchr(C_escapes, c);
10789         if (p) {
10790                 buf[0] = c;
10791                 p = buf;
10792                 cnt = 3;
10793                 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10794                         do {
10795                                 c = pgetc();
10796                                 *++p = c;
10797                         } while ((unsigned char)(c - '0') <= 7 && --cnt);
10798                         pungetc();
10799                 } else if (c == 'x') { /* \xHH */
10800                         do {
10801                                 c = pgetc();
10802                                 *++p = c;
10803                         } while (isxdigit(c) && --cnt);
10804                         pungetc();
10805                         if (cnt == 3) { /* \x but next char is "bad" */
10806                                 c = 'x';
10807                                 goto unrecognized;
10808                         }
10809                 } else { /* simple seq like \\ or \t */
10810                         p++;
10811                 }
10812                 *p = '\0';
10813                 p = buf;
10814                 c = bb_process_escape_sequence((void*)&p);
10815         } else { /* unrecognized "\z": print both chars unless ' or " */
10816                 if (c != '\'' && c != '"') {
10817  unrecognized:
10818                         c |= 0x100; /* "please encode \, then me" */
10819                 }
10820         }
10821         return c;
10822 }
10823 #endif
10824
10825 /*
10826  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
10827  * is not NULL, read a here document.  In the latter case, eofmark is the
10828  * word which marks the end of the document and striptabs is true if
10829  * leading tabs should be stripped from the document.  The argument firstc
10830  * is the first character of the input token or document.
10831  *
10832  * Because C does not have internal subroutines, I have simulated them
10833  * using goto's to implement the subroutine linkage.  The following macros
10834  * will run code that appears at the end of readtoken1.
10835  */
10836 #define CHECKEND()      {goto checkend; checkend_return:;}
10837 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
10838 #define PARSESUB()      {goto parsesub; parsesub_return:;}
10839 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10840 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10841 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
10842 static int
10843 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10844 {
10845         /* NB: syntax parameter fits into smallint */
10846         int c = firstc;
10847         char *out;
10848         int len;
10849         char line[EOFMARKLEN + 1];
10850         struct nodelist *bqlist;
10851         smallint quotef;
10852         smallint dblquote;
10853         smallint oldstyle;
10854         smallint prevsyntax; /* syntax before arithmetic */
10855 #if ENABLE_ASH_EXPAND_PRMT
10856         smallint pssyntax;   /* we are expanding a prompt string */
10857 #endif
10858         int varnest;         /* levels of variables expansion */
10859         int arinest;         /* levels of arithmetic expansion */
10860         int parenlevel;      /* levels of parens in arithmetic */
10861         int dqvarnest;       /* levels of variables expansion within double quotes */
10862
10863         IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10864
10865 #if __GNUC__
10866         /* Avoid longjmp clobbering */
10867         (void) &out;
10868         (void) &quotef;
10869         (void) &dblquote;
10870         (void) &varnest;
10871         (void) &arinest;
10872         (void) &parenlevel;
10873         (void) &dqvarnest;
10874         (void) &oldstyle;
10875         (void) &prevsyntax;
10876         (void) &syntax;
10877 #endif
10878         startlinno = g_parsefile->linno;
10879         bqlist = NULL;
10880         quotef = 0;
10881         oldstyle = 0;
10882         prevsyntax = 0;
10883 #if ENABLE_ASH_EXPAND_PRMT
10884         pssyntax = (syntax == PSSYNTAX);
10885         if (pssyntax)
10886                 syntax = DQSYNTAX;
10887 #endif
10888         dblquote = (syntax == DQSYNTAX);
10889         varnest = 0;
10890         arinest = 0;
10891         parenlevel = 0;
10892         dqvarnest = 0;
10893
10894         STARTSTACKSTR(out);
10895  loop:
10896         /* For each line, until end of word */
10897         {
10898                 CHECKEND();     /* set c to PEOF if at end of here document */
10899                 for (;;) {      /* until end of line or end of word */
10900                         CHECKSTRSPACE(4, out);  /* permit 4 calls to USTPUTC */
10901                         switch (SIT(c, syntax)) {
10902                         case CNL:       /* '\n' */
10903                                 if (syntax == BASESYNTAX)
10904                                         goto endword;   /* exit outer loop */
10905                                 USTPUTC(c, out);
10906                                 g_parsefile->linno++;
10907                                 if (doprompt)
10908                                         setprompt(2);
10909                                 c = pgetc();
10910                                 goto loop;              /* continue outer loop */
10911                         case CWORD:
10912                                 USTPUTC(c, out);
10913                                 break;
10914                         case CCTL:
10915                                 if (eofmark == NULL || dblquote)
10916                                         USTPUTC(CTLESC, out);
10917 #if ENABLE_ASH_BASH_COMPAT
10918                                 if (c == '\\' && bash_dollar_squote) {
10919                                         c = decode_dollar_squote();
10920                                         if (c & 0x100) {
10921                                                 USTPUTC('\\', out);
10922                                                 c = (unsigned char)c;
10923                                         }
10924                                 }
10925 #endif
10926                                 USTPUTC(c, out);
10927                                 break;
10928                         case CBACK:     /* backslash */
10929                                 c = pgetc2();
10930                                 if (c == PEOF) {
10931                                         USTPUTC(CTLESC, out);
10932                                         USTPUTC('\\', out);
10933                                         pungetc();
10934                                 } else if (c == '\n') {
10935                                         if (doprompt)
10936                                                 setprompt(2);
10937                                 } else {
10938 #if ENABLE_ASH_EXPAND_PRMT
10939                                         if (c == '$' && pssyntax) {
10940                                                 USTPUTC(CTLESC, out);
10941                                                 USTPUTC('\\', out);
10942                                         }
10943 #endif
10944                                         if (dblquote && c != '\\'
10945                                          && c != '`' && c != '$'
10946                                          && (c != '"' || eofmark != NULL)
10947                                         ) {
10948                                                 USTPUTC(CTLESC, out);
10949                                                 USTPUTC('\\', out);
10950                                         }
10951                                         if (SIT(c, SQSYNTAX) == CCTL)
10952                                                 USTPUTC(CTLESC, out);
10953                                         USTPUTC(c, out);
10954                                         quotef = 1;
10955                                 }
10956                                 break;
10957                         case CSQUOTE:
10958                                 syntax = SQSYNTAX;
10959  quotemark:
10960                                 if (eofmark == NULL) {
10961                                         USTPUTC(CTLQUOTEMARK, out);
10962                                 }
10963                                 break;
10964                         case CDQUOTE:
10965                                 syntax = DQSYNTAX;
10966                                 dblquote = 1;
10967                                 goto quotemark;
10968                         case CENDQUOTE:
10969                                 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10970                                 if (eofmark != NULL && arinest == 0
10971                                  && varnest == 0
10972                                 ) {
10973                                         USTPUTC(c, out);
10974                                 } else {
10975                                         if (dqvarnest == 0) {
10976                                                 syntax = BASESYNTAX;
10977                                                 dblquote = 0;
10978                                         }
10979                                         quotef = 1;
10980                                         goto quotemark;
10981                                 }
10982                                 break;
10983                         case CVAR:      /* '$' */
10984                                 PARSESUB();             /* parse substitution */
10985                                 break;
10986                         case CENDVAR:   /* '}' */
10987                                 if (varnest > 0) {
10988                                         varnest--;
10989                                         if (dqvarnest > 0) {
10990                                                 dqvarnest--;
10991                                         }
10992                                         USTPUTC(CTLENDVAR, out);
10993                                 } else {
10994                                         USTPUTC(c, out);
10995                                 }
10996                                 break;
10997 #if ENABLE_SH_MATH_SUPPORT
10998                         case CLP:       /* '(' in arithmetic */
10999                                 parenlevel++;
11000                                 USTPUTC(c, out);
11001                                 break;
11002                         case CRP:       /* ')' in arithmetic */
11003                                 if (parenlevel > 0) {
11004                                         USTPUTC(c, out);
11005                                         --parenlevel;
11006                                 } else {
11007                                         if (pgetc() == ')') {
11008                                                 if (--arinest == 0) {
11009                                                         USTPUTC(CTLENDARI, out);
11010                                                         syntax = prevsyntax;
11011                                                         dblquote = (syntax == DQSYNTAX);
11012                                                 } else
11013                                                         USTPUTC(')', out);
11014                                         } else {
11015                                                 /*
11016                                                  * unbalanced parens
11017                                                  *  (don't 2nd guess - no error)
11018                                                  */
11019                                                 pungetc();
11020                                                 USTPUTC(')', out);
11021                                         }
11022                                 }
11023                                 break;
11024 #endif
11025                         case CBQUOTE:   /* '`' */
11026                                 PARSEBACKQOLD();
11027                                 break;
11028                         case CENDFILE:
11029                                 goto endword;           /* exit outer loop */
11030                         case CIGN:
11031                                 break;
11032                         default:
11033                                 if (varnest == 0) {
11034 #if ENABLE_ASH_BASH_COMPAT
11035                                         if (c == '&') {
11036                                                 if (pgetc() == '>')
11037                                                         c = 0x100 + '>'; /* flag &> */
11038                                                 pungetc();
11039                                         }
11040 #endif
11041                                         goto endword;   /* exit outer loop */
11042                                 }
11043 #if ENABLE_ASH_ALIAS
11044                                 if (c != PEOA)
11045 #endif
11046                                         USTPUTC(c, out);
11047
11048                         }
11049                         c = pgetc_fast();
11050                 } /* for (;;) */
11051         }
11052  endword:
11053 #if ENABLE_SH_MATH_SUPPORT
11054         if (syntax == ARISYNTAX)
11055                 raise_error_syntax("missing '))'");
11056 #endif
11057         if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11058                 raise_error_syntax("unterminated quoted string");
11059         if (varnest != 0) {
11060                 startlinno = g_parsefile->linno;
11061                 /* { */
11062                 raise_error_syntax("missing '}'");
11063         }
11064         USTPUTC('\0', out);
11065         len = out - (char *)stackblock();
11066         out = stackblock();
11067         if (eofmark == NULL) {
11068                 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11069                  && quotef == 0
11070                 ) {
11071                         if (isdigit_str9(out)) {
11072                                 PARSEREDIR(); /* passed as params: out, c */
11073                                 lasttoken = TREDIR;
11074                                 return lasttoken;
11075                         }
11076                         /* else: non-number X seen, interpret it
11077                          * as "NNNX>file" = "NNNX >file" */
11078                 }
11079                 pungetc();
11080         }
11081         quoteflag = quotef;
11082         backquotelist = bqlist;
11083         grabstackblock(len);
11084         wordtext = out;
11085         lasttoken = TWORD;
11086         return lasttoken;
11087 /* end of readtoken routine */
11088
11089 /*
11090  * Check to see whether we are at the end of the here document.  When this
11091  * is called, c is set to the first character of the next input line.  If
11092  * we are at the end of the here document, this routine sets the c to PEOF.
11093  */
11094 checkend: {
11095         if (eofmark) {
11096 #if ENABLE_ASH_ALIAS
11097                 if (c == PEOA) {
11098                         c = pgetc2();
11099                 }
11100 #endif
11101                 if (striptabs) {
11102                         while (c == '\t') {
11103                                 c = pgetc2();
11104                         }
11105                 }
11106                 if (c == *eofmark) {
11107                         if (pfgets(line, sizeof(line)) != NULL) {
11108                                 char *p, *q;
11109
11110                                 p = line;
11111                                 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11112                                         continue;
11113                                 if (*p == '\n' && *q == '\0') {
11114                                         c = PEOF;
11115                                         g_parsefile->linno++;
11116                                         needprompt = doprompt;
11117                                 } else {
11118                                         pushstring(line, NULL);
11119                                 }
11120                         }
11121                 }
11122         }
11123         goto checkend_return;
11124 }
11125
11126 /*
11127  * Parse a redirection operator.  The variable "out" points to a string
11128  * specifying the fd to be redirected.  The variable "c" contains the
11129  * first character of the redirection operator.
11130  */
11131 parseredir: {
11132         /* out is already checked to be a valid number or "" */
11133         int fd = (*out == '\0' ? -1 : atoi(out));
11134         union node *np;
11135
11136         np = stzalloc(sizeof(struct nfile));
11137         if (c == '>') {
11138                 np->nfile.fd = 1;
11139                 c = pgetc();
11140                 if (c == '>')
11141                         np->type = NAPPEND;
11142                 else if (c == '|')
11143                         np->type = NCLOBBER;
11144                 else if (c == '&')
11145                         np->type = NTOFD;
11146                         /* it also can be NTO2 (>&file), but we can't figure it out yet */
11147                 else {
11148                         np->type = NTO;
11149                         pungetc();
11150                 }
11151         }
11152 #if ENABLE_ASH_BASH_COMPAT
11153         else if (c == 0x100 + '>') { /* this flags &> redirection */
11154                 np->nfile.fd = 1;
11155                 pgetc(); /* this is '>', no need to check */
11156                 np->type = NTO2;
11157         }
11158 #endif
11159         else { /* c == '<' */
11160                 /*np->nfile.fd = 0; - stzalloc did it */
11161                 c = pgetc();
11162                 switch (c) {
11163                 case '<':
11164                         if (sizeof(struct nfile) != sizeof(struct nhere)) {
11165                                 np = stzalloc(sizeof(struct nhere));
11166                                 /*np->nfile.fd = 0; - stzalloc did it */
11167                         }
11168                         np->type = NHERE;
11169                         heredoc = stzalloc(sizeof(struct heredoc));
11170                         heredoc->here = np;
11171                         c = pgetc();
11172                         if (c == '-') {
11173                                 heredoc->striptabs = 1;
11174                         } else {
11175                                 /*heredoc->striptabs = 0; - stzalloc did it */
11176                                 pungetc();
11177                         }
11178                         break;
11179
11180                 case '&':
11181                         np->type = NFROMFD;
11182                         break;
11183
11184                 case '>':
11185                         np->type = NFROMTO;
11186                         break;
11187
11188                 default:
11189                         np->type = NFROM;
11190                         pungetc();
11191                         break;
11192                 }
11193         }
11194         if (fd >= 0)
11195                 np->nfile.fd = fd;
11196         redirnode = np;
11197         goto parseredir_return;
11198 }
11199
11200 /*
11201  * Parse a substitution.  At this point, we have read the dollar sign
11202  * and nothing else.
11203  */
11204
11205 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11206  * (assuming ascii char codes, as the original implementation did) */
11207 #define is_special(c) \
11208         (((unsigned)(c) - 33 < 32) \
11209                         && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11210 parsesub: {
11211         int subtype;
11212         int typeloc;
11213         int flags;
11214         char *p;
11215         static const char types[] ALIGN1 = "}-+?=";
11216
11217         c = pgetc();
11218         if (c <= PEOA_OR_PEOF
11219          || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11220         ) {
11221 #if ENABLE_ASH_BASH_COMPAT
11222                 if (c == '\'')
11223                         bash_dollar_squote = 1;
11224                 else
11225 #endif
11226                         USTPUTC('$', out);
11227                 pungetc();
11228         } else if (c == '(') {  /* $(command) or $((arith)) */
11229                 if (pgetc() == '(') {
11230 #if ENABLE_SH_MATH_SUPPORT
11231                         PARSEARITH();
11232 #else
11233                         raise_error_syntax("you disabled math support for $((arith)) syntax");
11234 #endif
11235                 } else {
11236                         pungetc();
11237                         PARSEBACKQNEW();
11238                 }
11239         } else {
11240                 USTPUTC(CTLVAR, out);
11241                 typeloc = out - (char *)stackblock();
11242                 USTPUTC(VSNORMAL, out);
11243                 subtype = VSNORMAL;
11244                 if (c == '{') {
11245                         c = pgetc();
11246                         if (c == '#') {
11247                                 c = pgetc();
11248                                 if (c == '}')
11249                                         c = '#';
11250                                 else
11251                                         subtype = VSLENGTH;
11252                         } else
11253                                 subtype = 0;
11254                 }
11255                 if (c > PEOA_OR_PEOF && is_name(c)) {
11256                         do {
11257                                 STPUTC(c, out);
11258                                 c = pgetc();
11259                         } while (c > PEOA_OR_PEOF && is_in_name(c));
11260                 } else if (isdigit(c)) {
11261                         do {
11262                                 STPUTC(c, out);
11263                                 c = pgetc();
11264                         } while (isdigit(c));
11265                 } else if (is_special(c)) {
11266                         USTPUTC(c, out);
11267                         c = pgetc();
11268                 } else {
11269  badsub:
11270                         raise_error_syntax("bad substitution");
11271                 }
11272
11273                 STPUTC('=', out);
11274                 flags = 0;
11275                 if (subtype == 0) {
11276                         switch (c) {
11277                         case ':':
11278                                 c = pgetc();
11279 #if ENABLE_ASH_BASH_COMPAT
11280                                 if (c == ':' || c == '$' || isdigit(c)) {
11281                                         pungetc();
11282                                         subtype = VSSUBSTR;
11283                                         break;
11284                                 }
11285 #endif
11286                                 flags = VSNUL;
11287                                 /*FALLTHROUGH*/
11288                         default:
11289                                 p = strchr(types, c);
11290                                 if (p == NULL)
11291                                         goto badsub;
11292                                 subtype = p - types + VSNORMAL;
11293                                 break;
11294                         case '%':
11295                         case '#': {
11296                                 int cc = c;
11297                                 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11298                                 c = pgetc();
11299                                 if (c == cc)
11300                                         subtype++;
11301                                 else
11302                                         pungetc();
11303                                 break;
11304                         }
11305 #if ENABLE_ASH_BASH_COMPAT
11306                         case '/':
11307                                 subtype = VSREPLACE;
11308                                 c = pgetc();
11309                                 if (c == '/')
11310                                         subtype++; /* VSREPLACEALL */
11311                                 else
11312                                         pungetc();
11313                                 break;
11314 #endif
11315                         }
11316                 } else {
11317                         pungetc();
11318                 }
11319                 if (dblquote || arinest)
11320                         flags |= VSQUOTE;
11321                 *((char *)stackblock() + typeloc) = subtype | flags;
11322                 if (subtype != VSNORMAL) {
11323                         varnest++;
11324                         if (dblquote || arinest) {
11325                                 dqvarnest++;
11326                         }
11327                 }
11328         }
11329         goto parsesub_return;
11330 }
11331
11332 /*
11333  * Called to parse command substitutions.  Newstyle is set if the command
11334  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11335  * list of commands (passed by reference), and savelen is the number of
11336  * characters on the top of the stack which must be preserved.
11337  */
11338 parsebackq: {
11339         struct nodelist **nlpp;
11340         smallint savepbq;
11341         union node *n;
11342         char *volatile str;
11343         struct jmploc jmploc;
11344         struct jmploc *volatile savehandler;
11345         size_t savelen;
11346         smallint saveprompt = 0;
11347
11348 #ifdef __GNUC__
11349         (void) &saveprompt;
11350 #endif
11351         savepbq = parsebackquote;
11352         if (setjmp(jmploc.loc)) {
11353                 free(str);
11354                 parsebackquote = 0;
11355                 exception_handler = savehandler;
11356                 longjmp(exception_handler->loc, 1);
11357         }
11358         INT_OFF;
11359         str = NULL;
11360         savelen = out - (char *)stackblock();
11361         if (savelen > 0) {
11362                 str = ckmalloc(savelen);
11363                 memcpy(str, stackblock(), savelen);
11364         }
11365         savehandler = exception_handler;
11366         exception_handler = &jmploc;
11367         INT_ON;
11368         if (oldstyle) {
11369                 /* We must read until the closing backquote, giving special
11370                    treatment to some slashes, and then push the string and
11371                    reread it as input, interpreting it normally.  */
11372                 char *pout;
11373                 int pc;
11374                 size_t psavelen;
11375                 char *pstr;
11376
11377
11378                 STARTSTACKSTR(pout);
11379                 for (;;) {
11380                         if (needprompt) {
11381                                 setprompt(2);
11382                         }
11383                         pc = pgetc();
11384                         switch (pc) {
11385                         case '`':
11386                                 goto done;
11387
11388                         case '\\':
11389                                 pc = pgetc();
11390                                 if (pc == '\n') {
11391                                         g_parsefile->linno++;
11392                                         if (doprompt)
11393                                                 setprompt(2);
11394                                         /*
11395                                          * If eating a newline, avoid putting
11396                                          * the newline into the new character
11397                                          * stream (via the STPUTC after the
11398                                          * switch).
11399                                          */
11400                                         continue;
11401                                 }
11402                                 if (pc != '\\' && pc != '`' && pc != '$'
11403                                  && (!dblquote || pc != '"'))
11404                                         STPUTC('\\', pout);
11405                                 if (pc > PEOA_OR_PEOF) {
11406                                         break;
11407                                 }
11408                                 /* fall through */
11409
11410                         case PEOF:
11411 #if ENABLE_ASH_ALIAS
11412                         case PEOA:
11413 #endif
11414                                 startlinno = g_parsefile->linno;
11415                                 raise_error_syntax("EOF in backquote substitution");
11416
11417                         case '\n':
11418                                 g_parsefile->linno++;
11419                                 needprompt = doprompt;
11420                                 break;
11421
11422                         default:
11423                                 break;
11424                         }
11425                         STPUTC(pc, pout);
11426                 }
11427  done:
11428                 STPUTC('\0', pout);
11429                 psavelen = pout - (char *)stackblock();
11430                 if (psavelen > 0) {
11431                         pstr = grabstackstr(pout);
11432                         setinputstring(pstr);
11433                 }
11434         }
11435         nlpp = &bqlist;
11436         while (*nlpp)
11437                 nlpp = &(*nlpp)->next;
11438         *nlpp = stzalloc(sizeof(**nlpp));
11439         /* (*nlpp)->next = NULL; - stzalloc did it */
11440         parsebackquote = oldstyle;
11441
11442         if (oldstyle) {
11443                 saveprompt = doprompt;
11444                 doprompt = 0;
11445         }
11446
11447         n = list(2);
11448
11449         if (oldstyle)
11450                 doprompt = saveprompt;
11451         else if (readtoken() != TRP)
11452                 raise_error_unexpected_syntax(TRP);
11453
11454         (*nlpp)->n = n;
11455         if (oldstyle) {
11456                 /*
11457                  * Start reading from old file again, ignoring any pushed back
11458                  * tokens left from the backquote parsing
11459                  */
11460                 popfile();
11461                 tokpushback = 0;
11462         }
11463         while (stackblocksize() <= savelen)
11464                 growstackblock();
11465         STARTSTACKSTR(out);
11466         if (str) {
11467                 memcpy(out, str, savelen);
11468                 STADJUST(savelen, out);
11469                 INT_OFF;
11470                 free(str);
11471                 str = NULL;
11472                 INT_ON;
11473         }
11474         parsebackquote = savepbq;
11475         exception_handler = savehandler;
11476         if (arinest || dblquote)
11477                 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11478         else
11479                 USTPUTC(CTLBACKQ, out);
11480         if (oldstyle)
11481                 goto parsebackq_oldreturn;
11482         goto parsebackq_newreturn;
11483 }
11484
11485 #if ENABLE_SH_MATH_SUPPORT
11486 /*
11487  * Parse an arithmetic expansion (indicate start of one and set state)
11488  */
11489 parsearith: {
11490         if (++arinest == 1) {
11491                 prevsyntax = syntax;
11492                 syntax = ARISYNTAX;
11493                 USTPUTC(CTLARI, out);
11494                 if (dblquote)
11495                         USTPUTC('"', out);
11496                 else
11497                         USTPUTC(' ', out);
11498         } else {
11499                 /*
11500                  * we collapse embedded arithmetic expansion to
11501                  * parenthesis, which should be equivalent
11502                  */
11503                 USTPUTC('(', out);
11504         }
11505         goto parsearith_return;
11506 }
11507 #endif
11508
11509 } /* end of readtoken */
11510
11511 /*
11512  * Read the next input token.
11513  * If the token is a word, we set backquotelist to the list of cmds in
11514  *      backquotes.  We set quoteflag to true if any part of the word was
11515  *      quoted.
11516  * If the token is TREDIR, then we set redirnode to a structure containing
11517  *      the redirection.
11518  * In all cases, the variable startlinno is set to the number of the line
11519  *      on which the token starts.
11520  *
11521  * [Change comment:  here documents and internal procedures]
11522  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
11523  *  word parsing code into a separate routine.  In this case, readtoken
11524  *  doesn't need to have any internal procedures, but parseword does.
11525  *  We could also make parseoperator in essence the main routine, and
11526  *  have parseword (readtoken1?) handle both words and redirection.]
11527  */
11528 #define NEW_xxreadtoken
11529 #ifdef NEW_xxreadtoken
11530 /* singles must be first! */
11531 static const char xxreadtoken_chars[7] ALIGN1 = {
11532         '\n', '(', ')', /* singles */
11533         '&', '|', ';',  /* doubles */
11534         0
11535 };
11536
11537 #define xxreadtoken_singles 3
11538 #define xxreadtoken_doubles 3
11539
11540 static const char xxreadtoken_tokens[] ALIGN1 = {
11541         TNL, TLP, TRP,          /* only single occurrence allowed */
11542         TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11543         TEOF,                   /* corresponds to trailing nul */
11544         TAND, TOR, TENDCASE     /* if double occurrence */
11545 };
11546
11547 static int
11548 xxreadtoken(void)
11549 {
11550         int c;
11551
11552         if (tokpushback) {
11553                 tokpushback = 0;
11554                 return lasttoken;
11555         }
11556         if (needprompt) {
11557                 setprompt(2);
11558         }
11559         startlinno = g_parsefile->linno;
11560         for (;;) {                      /* until token or start of word found */
11561                 c = pgetc_fast();
11562                 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11563                         continue;
11564
11565                 if (c == '#') {
11566                         while ((c = pgetc()) != '\n' && c != PEOF)
11567                                 continue;
11568                         pungetc();
11569                 } else if (c == '\\') {
11570                         if (pgetc() != '\n') {
11571                                 pungetc();
11572                                 break; /* return readtoken1(...) */
11573                         }
11574                         startlinno = ++g_parsefile->linno;
11575                         if (doprompt)
11576                                 setprompt(2);
11577                 } else {
11578                         const char *p;
11579
11580                         p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11581                         if (c != PEOF) {
11582                                 if (c == '\n') {
11583                                         g_parsefile->linno++;
11584                                         needprompt = doprompt;
11585                                 }
11586
11587                                 p = strchr(xxreadtoken_chars, c);
11588                                 if (p == NULL)
11589                                         break; /* return readtoken1(...) */
11590
11591                                 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11592                                         int cc = pgetc();
11593                                         if (cc == c) {    /* double occurrence? */
11594                                                 p += xxreadtoken_doubles + 1;
11595                                         } else {
11596                                                 pungetc();
11597 #if ENABLE_ASH_BASH_COMPAT
11598                                                 if (c == '&' && cc == '>') /* &> */
11599                                                         break; /* return readtoken1(...) */
11600 #endif
11601                                         }
11602                                 }
11603                         }
11604                         lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11605                         return lasttoken;
11606                 }
11607         } /* for (;;) */
11608
11609         return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11610 }
11611 #else /* old xxreadtoken */
11612 #define RETURN(token)   return lasttoken = token
11613 static int
11614 xxreadtoken(void)
11615 {
11616         int c;
11617
11618         if (tokpushback) {
11619                 tokpushback = 0;
11620                 return lasttoken;
11621         }
11622         if (needprompt) {
11623                 setprompt(2);
11624         }
11625         startlinno = g_parsefile->linno;
11626         for (;;) {      /* until token or start of word found */
11627                 c = pgetc_fast();
11628                 switch (c) {
11629                 case ' ': case '\t':
11630 #if ENABLE_ASH_ALIAS
11631                 case PEOA:
11632 #endif
11633                         continue;
11634                 case '#':
11635                         while ((c = pgetc()) != '\n' && c != PEOF)
11636                                 continue;
11637                         pungetc();
11638                         continue;
11639                 case '\\':
11640                         if (pgetc() == '\n') {
11641                                 startlinno = ++g_parsefile->linno;
11642                                 if (doprompt)
11643                                         setprompt(2);
11644                                 continue;
11645                         }
11646                         pungetc();
11647                         goto breakloop;
11648                 case '\n':
11649                         g_parsefile->linno++;
11650                         needprompt = doprompt;
11651                         RETURN(TNL);
11652                 case PEOF:
11653                         RETURN(TEOF);
11654                 case '&':
11655                         if (pgetc() == '&')
11656                                 RETURN(TAND);
11657                         pungetc();
11658                         RETURN(TBACKGND);
11659                 case '|':
11660                         if (pgetc() == '|')
11661                                 RETURN(TOR);
11662                         pungetc();
11663                         RETURN(TPIPE);
11664                 case ';':
11665                         if (pgetc() == ';')
11666                                 RETURN(TENDCASE);
11667                         pungetc();
11668                         RETURN(TSEMI);
11669                 case '(':
11670                         RETURN(TLP);
11671                 case ')':
11672                         RETURN(TRP);
11673                 default:
11674                         goto breakloop;
11675                 }
11676         }
11677  breakloop:
11678         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11679 #undef RETURN
11680 }
11681 #endif /* old xxreadtoken */
11682
11683 static int
11684 readtoken(void)
11685 {
11686         int t;
11687 #if DEBUG
11688         smallint alreadyseen = tokpushback;
11689 #endif
11690
11691 #if ENABLE_ASH_ALIAS
11692  top:
11693 #endif
11694
11695         t = xxreadtoken();
11696
11697         /*
11698          * eat newlines
11699          */
11700         if (checkkwd & CHKNL) {
11701                 while (t == TNL) {
11702                         parseheredoc();
11703                         t = xxreadtoken();
11704                 }
11705         }
11706
11707         if (t != TWORD || quoteflag) {
11708                 goto out;
11709         }
11710
11711         /*
11712          * check for keywords
11713          */
11714         if (checkkwd & CHKKWD) {
11715                 const char *const *pp;
11716
11717                 pp = findkwd(wordtext);
11718                 if (pp) {
11719                         lasttoken = t = pp - tokname_array;
11720                         TRACE(("keyword %s recognized\n", tokname(t)));
11721                         goto out;
11722                 }
11723         }
11724
11725         if (checkkwd & CHKALIAS) {
11726 #if ENABLE_ASH_ALIAS
11727                 struct alias *ap;
11728                 ap = lookupalias(wordtext, 1);
11729                 if (ap != NULL) {
11730                         if (*ap->val) {
11731                                 pushstring(ap->val, ap);
11732                         }
11733                         goto top;
11734                 }
11735 #endif
11736         }
11737  out:
11738         checkkwd = 0;
11739 #if DEBUG
11740         if (!alreadyseen)
11741                 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11742         else
11743                 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11744 #endif
11745         return t;
11746 }
11747
11748 static char
11749 peektoken(void)
11750 {
11751         int t;
11752
11753         t = readtoken();
11754         tokpushback = 1;
11755         return tokname_array[t][0];
11756 }
11757
11758 /*
11759  * Read and parse a command.  Returns NODE_EOF on end of file.
11760  * (NULL is a valid parse tree indicating a blank line.)
11761  */
11762 static union node *
11763 parsecmd(int interact)
11764 {
11765         int t;
11766
11767         tokpushback = 0;
11768         doprompt = interact;
11769         if (doprompt)
11770                 setprompt(doprompt);
11771         needprompt = 0;
11772         t = readtoken();
11773         if (t == TEOF)
11774                 return NODE_EOF;
11775         if (t == TNL)
11776                 return NULL;
11777         tokpushback = 1;
11778         return list(1);
11779 }
11780
11781 /*
11782  * Input any here documents.
11783  */
11784 static void
11785 parseheredoc(void)
11786 {
11787         struct heredoc *here;
11788         union node *n;
11789
11790         here = heredoclist;
11791         heredoclist = NULL;
11792
11793         while (here) {
11794                 if (needprompt) {
11795                         setprompt(2);
11796                 }
11797                 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11798                                 here->eofmark, here->striptabs);
11799                 n = stzalloc(sizeof(struct narg));
11800                 n->narg.type = NARG;
11801                 /*n->narg.next = NULL; - stzalloc did it */
11802                 n->narg.text = wordtext;
11803                 n->narg.backquote = backquotelist;
11804                 here->here->nhere.doc = n;
11805                 here = here->next;
11806         }
11807 }
11808
11809
11810 /*
11811  * called by editline -- any expansions to the prompt should be added here.
11812  */
11813 #if ENABLE_ASH_EXPAND_PRMT
11814 static const char *
11815 expandstr(const char *ps)
11816 {
11817         union node n;
11818
11819         /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11820          * and token processing _can_ alter it (delete NULs etc). */
11821         setinputstring((char *)ps);
11822         readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11823         popfile();
11824
11825         n.narg.type = NARG;
11826         n.narg.next = NULL;
11827         n.narg.text = wordtext;
11828         n.narg.backquote = backquotelist;
11829
11830         expandarg(&n, NULL, 0);
11831         return stackblock();
11832 }
11833 #endif
11834
11835 /*
11836  * Execute a command or commands contained in a string.
11837  */
11838 static int
11839 evalstring(char *s, int mask)
11840 {
11841         union node *n;
11842         struct stackmark smark;
11843         int skip;
11844
11845         setinputstring(s);
11846         setstackmark(&smark);
11847
11848         skip = 0;
11849         while ((n = parsecmd(0)) != NODE_EOF) {
11850                 evaltree(n, 0);
11851                 popstackmark(&smark);
11852                 skip = evalskip;
11853                 if (skip)
11854                         break;
11855         }
11856         popfile();
11857
11858         skip &= mask;
11859         evalskip = skip;
11860         return skip;
11861 }
11862
11863 /*
11864  * The eval command.
11865  */
11866 static int FAST_FUNC
11867 evalcmd(int argc UNUSED_PARAM, char **argv)
11868 {
11869         char *p;
11870         char *concat;
11871
11872         if (argv[1]) {
11873                 p = argv[1];
11874                 argv += 2;
11875                 if (argv[0]) {
11876                         STARTSTACKSTR(concat);
11877                         for (;;) {
11878                                 concat = stack_putstr(p, concat);
11879                                 p = *argv++;
11880                                 if (p == NULL)
11881                                         break;
11882                                 STPUTC(' ', concat);
11883                         }
11884                         STPUTC('\0', concat);
11885                         p = grabstackstr(concat);
11886                 }
11887                 evalstring(p, ~SKIPEVAL);
11888
11889         }
11890         return exitstatus;
11891 }
11892
11893 /*
11894  * Read and execute commands.  "Top" is nonzero for the top level command
11895  * loop; it turns on prompting if the shell is interactive.
11896  */
11897 static int
11898 cmdloop(int top)
11899 {
11900         union node *n;
11901         struct stackmark smark;
11902         int inter;
11903         int numeof = 0;
11904
11905         TRACE(("cmdloop(%d) called\n", top));
11906         for (;;) {
11907                 int skip;
11908
11909                 setstackmark(&smark);
11910 #if JOBS
11911                 if (doing_jobctl)
11912                         showjobs(stderr, SHOW_CHANGED);
11913 #endif
11914                 inter = 0;
11915                 if (iflag && top) {
11916                         inter++;
11917 #if ENABLE_ASH_MAIL
11918                         chkmail();
11919 #endif
11920                 }
11921                 n = parsecmd(inter);
11922 #if DEBUG
11923                 if (DEBUG > 2 && debug && (n != NODE_EOF))
11924                         showtree(n);
11925 #endif
11926                 if (n == NODE_EOF) {
11927                         if (!top || numeof >= 50)
11928                                 break;
11929                         if (!stoppedjobs()) {
11930                                 if (!Iflag)
11931                                         break;
11932                                 out2str("\nUse \"exit\" to leave shell.\n");
11933                         }
11934                         numeof++;
11935                 } else if (nflag == 0) {
11936                         /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11937                         job_warning >>= 1;
11938                         numeof = 0;
11939                         evaltree(n, 0);
11940                 }
11941                 popstackmark(&smark);
11942                 skip = evalskip;
11943
11944                 if (skip) {
11945                         evalskip = 0;
11946                         return skip & SKIPEVAL;
11947                 }
11948         }
11949         return 0;
11950 }
11951
11952 /*
11953  * Take commands from a file.  To be compatible we should do a path
11954  * search for the file, which is necessary to find sub-commands.
11955  */
11956 static char *
11957 find_dot_file(char *name)
11958 {
11959         char *fullname;
11960         const char *path = pathval();
11961         struct stat statb;
11962
11963         /* don't try this for absolute or relative paths */
11964         if (strchr(name, '/'))
11965                 return name;
11966
11967         /* IIRC standards do not say whether . is to be searched.
11968          * And it is even smaller this way, making it unconditional for now:
11969          */
11970         if (1) { /* ENABLE_ASH_BASH_COMPAT */
11971                 fullname = name;
11972                 goto try_cur_dir;
11973         }
11974
11975         while ((fullname = path_advance(&path, name)) != NULL) {
11976  try_cur_dir:
11977                 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11978                         /*
11979                          * Don't bother freeing here, since it will
11980                          * be freed by the caller.
11981                          */
11982                         return fullname;
11983                 }
11984                 if (fullname != name)
11985                         stunalloc(fullname);
11986         }
11987
11988         /* not found in the PATH */
11989         ash_msg_and_raise_error("%s: not found", name);
11990         /* NOTREACHED */
11991 }
11992
11993 static int FAST_FUNC
11994 dotcmd(int argc, char **argv)
11995 {
11996         struct strlist *sp;
11997         volatile struct shparam saveparam;
11998         int status = 0;
11999
12000         for (sp = cmdenviron; sp; sp = sp->next)
12001                 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12002
12003         if (argv[1]) {        /* That's what SVR2 does */
12004                 char *fullname = find_dot_file(argv[1]);
12005                 argv += 2;
12006                 argc -= 2;
12007                 if (argc) { /* argc > 0, argv[0] != NULL */
12008                         saveparam = shellparam;
12009                         shellparam.malloced = 0;
12010                         shellparam.nparam = argc;
12011                         shellparam.p = argv;
12012                 };
12013
12014                 setinputfile(fullname, INPUT_PUSH_FILE);
12015                 commandname = fullname;
12016                 cmdloop(0);
12017                 popfile();
12018
12019                 if (argc) {
12020                         freeparam(&shellparam);
12021                         shellparam = saveparam;
12022                 };
12023                 status = exitstatus;
12024         }
12025         return status;
12026 }
12027
12028 static int FAST_FUNC
12029 exitcmd(int argc UNUSED_PARAM, char **argv)
12030 {
12031         if (stoppedjobs())
12032                 return 0;
12033         if (argv[1])
12034                 exitstatus = number(argv[1]);
12035         raise_exception(EXEXIT);
12036         /* NOTREACHED */
12037 }
12038
12039 /*
12040  * Read a file containing shell functions.
12041  */
12042 static void
12043 readcmdfile(char *name)
12044 {
12045         setinputfile(name, INPUT_PUSH_FILE);
12046         cmdloop(0);
12047         popfile();
12048 }
12049
12050
12051 /* ============ find_command inplementation */
12052
12053 /*
12054  * Resolve a command name.  If you change this routine, you may have to
12055  * change the shellexec routine as well.
12056  */
12057 static void
12058 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12059 {
12060         struct tblentry *cmdp;
12061         int idx;
12062         int prev;
12063         char *fullname;
12064         struct stat statb;
12065         int e;
12066         int updatetbl;
12067         struct builtincmd *bcmd;
12068
12069         /* If name contains a slash, don't use PATH or hash table */
12070         if (strchr(name, '/') != NULL) {
12071                 entry->u.index = -1;
12072                 if (act & DO_ABS) {
12073                         while (stat(name, &statb) < 0) {
12074 #ifdef SYSV
12075                                 if (errno == EINTR)
12076                                         continue;
12077 #endif
12078                                 entry->cmdtype = CMDUNKNOWN;
12079                                 return;
12080                         }
12081                 }
12082                 entry->cmdtype = CMDNORMAL;
12083                 return;
12084         }
12085
12086 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12087
12088         updatetbl = (path == pathval());
12089         if (!updatetbl) {
12090                 act |= DO_ALTPATH;
12091                 if (strstr(path, "%builtin") != NULL)
12092                         act |= DO_ALTBLTIN;
12093         }
12094
12095         /* If name is in the table, check answer will be ok */
12096         cmdp = cmdlookup(name, 0);
12097         if (cmdp != NULL) {
12098                 int bit;
12099
12100                 switch (cmdp->cmdtype) {
12101                 default:
12102 #if DEBUG
12103                         abort();
12104 #endif
12105                 case CMDNORMAL:
12106                         bit = DO_ALTPATH;
12107                         break;
12108                 case CMDFUNCTION:
12109                         bit = DO_NOFUNC;
12110                         break;
12111                 case CMDBUILTIN:
12112                         bit = DO_ALTBLTIN;
12113                         break;
12114                 }
12115                 if (act & bit) {
12116                         updatetbl = 0;
12117                         cmdp = NULL;
12118                 } else if (cmdp->rehash == 0)
12119                         /* if not invalidated by cd, we're done */
12120                         goto success;
12121         }
12122
12123         /* If %builtin not in path, check for builtin next */
12124         bcmd = find_builtin(name);
12125         if (bcmd) {
12126                 if (IS_BUILTIN_REGULAR(bcmd))
12127                         goto builtin_success;
12128                 if (act & DO_ALTPATH) {
12129                         if (!(act & DO_ALTBLTIN))
12130                                 goto builtin_success;
12131                 } else if (builtinloc <= 0) {
12132                         goto builtin_success;
12133                 }
12134         }
12135
12136 #if ENABLE_FEATURE_SH_STANDALONE
12137         {
12138                 int applet_no = find_applet_by_name(name);
12139                 if (applet_no >= 0) {
12140                         entry->cmdtype = CMDNORMAL;
12141                         entry->u.index = -2 - applet_no;
12142                         return;
12143                 }
12144         }
12145 #endif
12146
12147         /* We have to search path. */
12148         prev = -1;              /* where to start */
12149         if (cmdp && cmdp->rehash) {     /* doing a rehash */
12150                 if (cmdp->cmdtype == CMDBUILTIN)
12151                         prev = builtinloc;
12152                 else
12153                         prev = cmdp->param.index;
12154         }
12155
12156         e = ENOENT;
12157         idx = -1;
12158  loop:
12159         while ((fullname = path_advance(&path, name)) != NULL) {
12160                 stunalloc(fullname);
12161                 /* NB: code below will still use fullname
12162                  * despite it being "unallocated" */
12163                 idx++;
12164                 if (pathopt) {
12165                         if (prefix(pathopt, "builtin")) {
12166                                 if (bcmd)
12167                                         goto builtin_success;
12168                                 continue;
12169                         }
12170                         if ((act & DO_NOFUNC)
12171                          || !prefix(pathopt, "func")
12172                         ) {     /* ignore unimplemented options */
12173                                 continue;
12174                         }
12175                 }
12176                 /* if rehash, don't redo absolute path names */
12177                 if (fullname[0] == '/' && idx <= prev) {
12178                         if (idx < prev)
12179                                 continue;
12180                         TRACE(("searchexec \"%s\": no change\n", name));
12181                         goto success;
12182                 }
12183                 while (stat(fullname, &statb) < 0) {
12184 #ifdef SYSV
12185                         if (errno == EINTR)
12186                                 continue;
12187 #endif
12188                         if (errno != ENOENT && errno != ENOTDIR)
12189                                 e = errno;
12190                         goto loop;
12191                 }
12192                 e = EACCES;     /* if we fail, this will be the error */
12193                 if (!S_ISREG(statb.st_mode))
12194                         continue;
12195                 if (pathopt) {          /* this is a %func directory */
12196                         stalloc(strlen(fullname) + 1);
12197                         /* NB: stalloc will return space pointed by fullname
12198                          * (because we don't have any intervening allocations
12199                          * between stunalloc above and this stalloc) */
12200                         readcmdfile(fullname);
12201                         cmdp = cmdlookup(name, 0);
12202                         if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12203                                 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12204                         stunalloc(fullname);
12205                         goto success;
12206                 }
12207                 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12208                 if (!updatetbl) {
12209                         entry->cmdtype = CMDNORMAL;
12210                         entry->u.index = idx;
12211                         return;
12212                 }
12213                 INT_OFF;
12214                 cmdp = cmdlookup(name, 1);
12215                 cmdp->cmdtype = CMDNORMAL;
12216                 cmdp->param.index = idx;
12217                 INT_ON;
12218                 goto success;
12219         }
12220
12221         /* We failed.  If there was an entry for this command, delete it */
12222         if (cmdp && updatetbl)
12223                 delete_cmd_entry();
12224         if (act & DO_ERR)
12225                 ash_msg("%s: %s", name, errmsg(e, "not found"));
12226         entry->cmdtype = CMDUNKNOWN;
12227         return;
12228
12229  builtin_success:
12230         if (!updatetbl) {
12231                 entry->cmdtype = CMDBUILTIN;
12232                 entry->u.cmd = bcmd;
12233                 return;
12234         }
12235         INT_OFF;
12236         cmdp = cmdlookup(name, 1);
12237         cmdp->cmdtype = CMDBUILTIN;
12238         cmdp->param.cmd = bcmd;
12239         INT_ON;
12240  success:
12241         cmdp->rehash = 0;
12242         entry->cmdtype = cmdp->cmdtype;
12243         entry->u = cmdp->param;
12244 }
12245
12246
12247 /* ============ trap.c */
12248
12249 /*
12250  * The trap builtin.
12251  */
12252 static int FAST_FUNC
12253 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12254 {
12255         char *action;
12256         char **ap;
12257         int signo;
12258
12259         nextopt(nullstr);
12260         ap = argptr;
12261         if (!*ap) {
12262                 for (signo = 0; signo < NSIG; signo++) {
12263                         if (trap[signo] != NULL) {
12264                                 out1fmt("trap -- %s %s%s\n",
12265                                                 single_quote(trap[signo]),
12266                                                 (signo == 0 ? "" : "SIG"),
12267                                                 get_signame(signo));
12268                         }
12269                 }
12270                 return 0;
12271         }
12272         action = NULL;
12273         if (ap[1])
12274                 action = *ap++;
12275         while (*ap) {
12276                 signo = get_signum(*ap);
12277                 if (signo < 0)
12278                         ash_msg_and_raise_error("%s: bad trap", *ap);
12279                 INT_OFF;
12280                 if (action) {
12281                         if (LONE_DASH(action))
12282                                 action = NULL;
12283                         else
12284                                 action = ckstrdup(action);
12285                 }
12286                 free(trap[signo]);
12287                 trap[signo] = action;
12288                 if (signo != 0)
12289                         setsignal(signo);
12290                 INT_ON;
12291                 ap++;
12292         }
12293         return 0;
12294 }
12295
12296
12297 /* ============ Builtins */
12298
12299 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12300 /*
12301  * Lists available builtins
12302  */
12303 static int FAST_FUNC
12304 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12305 {
12306         unsigned col;
12307         unsigned i;
12308
12309         out1fmt(
12310                 "Built-in commands:\n"
12311                 "------------------\n");
12312         for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12313                 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12314                                         builtintab[i].name + 1);
12315                 if (col > 60) {
12316                         out1fmt("\n");
12317                         col = 0;
12318                 }
12319         }
12320 #if ENABLE_FEATURE_SH_STANDALONE
12321         {
12322                 const char *a = applet_names;
12323                 while (*a) {
12324                         col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12325                         if (col > 60) {
12326                                 out1fmt("\n");
12327                                 col = 0;
12328                         }
12329                         a += strlen(a) + 1;
12330                 }
12331         }
12332 #endif
12333         out1fmt("\n\n");
12334         return EXIT_SUCCESS;
12335 }
12336 #endif /* FEATURE_SH_EXTRA_QUIET */
12337
12338 /*
12339  * The export and readonly commands.
12340  */
12341 static int FAST_FUNC
12342 exportcmd(int argc UNUSED_PARAM, char **argv)
12343 {
12344         struct var *vp;
12345         char *name;
12346         const char *p;
12347         char **aptr;
12348         int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12349
12350         if (nextopt("p") != 'p') {
12351                 aptr = argptr;
12352                 name = *aptr;
12353                 if (name) {
12354                         do {
12355                                 p = strchr(name, '=');
12356                                 if (p != NULL) {
12357                                         p++;
12358                                 } else {
12359                                         vp = *findvar(hashvar(name), name);
12360                                         if (vp) {
12361                                                 vp->flags |= flag;
12362                                                 continue;
12363                                         }
12364                                 }
12365                                 setvar(name, p, flag);
12366                         } while ((name = *++aptr) != NULL);
12367                         return 0;
12368                 }
12369         }
12370         showvars(argv[0], flag, 0);
12371         return 0;
12372 }
12373
12374 /*
12375  * Delete a function if it exists.
12376  */
12377 static void
12378 unsetfunc(const char *name)
12379 {
12380         struct tblentry *cmdp;
12381
12382         cmdp = cmdlookup(name, 0);
12383         if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12384                 delete_cmd_entry();
12385 }
12386
12387 /*
12388  * The unset builtin command.  We unset the function before we unset the
12389  * variable to allow a function to be unset when there is a readonly variable
12390  * with the same name.
12391  */
12392 static int FAST_FUNC
12393 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12394 {
12395         char **ap;
12396         int i;
12397         int flag = 0;
12398         int ret = 0;
12399
12400         while ((i = nextopt("vf")) != '\0') {
12401                 flag = i;
12402         }
12403
12404         for (ap = argptr; *ap; ap++) {
12405                 if (flag != 'f') {
12406                         i = unsetvar(*ap);
12407                         ret |= i;
12408                         if (!(i & 2))
12409                                 continue;
12410                 }
12411                 if (flag != 'v')
12412                         unsetfunc(*ap);
12413         }
12414         return ret & 1;
12415 }
12416
12417
12418 /*      setmode.c      */
12419
12420 #include <sys/times.h>
12421
12422 static const unsigned char timescmd_str[] ALIGN1 = {
12423         ' ',  offsetof(struct tms, tms_utime),
12424         '\n', offsetof(struct tms, tms_stime),
12425         ' ',  offsetof(struct tms, tms_cutime),
12426         '\n', offsetof(struct tms, tms_cstime),
12427         0
12428 };
12429
12430 static int FAST_FUNC
12431 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12432 {
12433         long clk_tck, s, t;
12434         const unsigned char *p;
12435         struct tms buf;
12436
12437         clk_tck = sysconf(_SC_CLK_TCK);
12438         times(&buf);
12439
12440         p = timescmd_str;
12441         do {
12442                 t = *(clock_t *)(((char *) &buf) + p[1]);
12443                 s = t / clk_tck;
12444                 out1fmt("%ldm%ld.%.3lds%c",
12445                         s/60, s%60,
12446                         ((t - s * clk_tck) * 1000) / clk_tck,
12447                         p[0]);
12448         } while (*(p += 2));
12449
12450         return 0;
12451 }
12452
12453 #if ENABLE_SH_MATH_SUPPORT
12454 /*
12455  * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12456  * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12457  *
12458  * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12459  */
12460 static int FAST_FUNC
12461 letcmd(int argc UNUSED_PARAM, char **argv)
12462 {
12463         arith_t i;
12464
12465         argv++;
12466         if (!*argv)
12467                 ash_msg_and_raise_error("expression expected");
12468         do {
12469                 i = ash_arith(*argv);
12470         } while (*++argv);
12471
12472         return !i;
12473 }
12474 #endif /* SH_MATH_SUPPORT */
12475
12476
12477 /* ============ miscbltin.c
12478  *
12479  * Miscellaneous builtins.
12480  */
12481
12482 #undef rflag
12483
12484 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12485 typedef enum __rlimit_resource rlim_t;
12486 #endif
12487
12488 /*
12489  * The read builtin. Options:
12490  *      -r              Do not interpret '\' specially
12491  *      -s              Turn off echo (tty only)
12492  *      -n NCHARS       Read NCHARS max
12493  *      -p PROMPT       Display PROMPT on stderr (if input is from tty)
12494  *      -t SECONDS      Timeout after SECONDS (tty or pipe only)
12495  *      -u FD           Read from given FD instead of fd 0
12496  * This uses unbuffered input, which may be avoidable in some cases.
12497  * TODO: bash also has:
12498  *      -a ARRAY        Read into array[0],[1],etc
12499  *      -d DELIM        End on DELIM char, not newline
12500  *      -e              Use line editing (tty only)
12501  */
12502 static int FAST_FUNC
12503 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12504 {
12505         static const char *const arg_REPLY[] = { "REPLY", NULL };
12506
12507         char **ap;
12508         int backslash;
12509         char c;
12510         int rflag;
12511         char *prompt;
12512         const char *ifs;
12513         char *p;
12514         int startword;
12515         int status;
12516         int i;
12517         int fd = 0;
12518 #if ENABLE_ASH_READ_NCHARS
12519         int nchars = 0; /* if != 0, -n is in effect */
12520         int silent = 0;
12521         struct termios tty, old_tty;
12522 #endif
12523 #if ENABLE_ASH_READ_TIMEOUT
12524         unsigned end_ms = 0;
12525         unsigned timeout = 0;
12526 #endif
12527
12528         rflag = 0;
12529         prompt = NULL;
12530         while ((i = nextopt("p:u:r"
12531                 IF_ASH_READ_TIMEOUT("t:")
12532                 IF_ASH_READ_NCHARS("n:s")
12533         )) != '\0') {
12534                 switch (i) {
12535                 case 'p':
12536                         prompt = optionarg;
12537                         break;
12538 #if ENABLE_ASH_READ_NCHARS
12539                 case 'n':
12540                         nchars = bb_strtou(optionarg, NULL, 10);
12541                         if (nchars < 0 || errno)
12542                                 ash_msg_and_raise_error("invalid count");
12543                         /* nchars == 0: off (bash 3.2 does this too) */
12544                         break;
12545                 case 's':
12546                         silent = 1;
12547                         break;
12548 #endif
12549 #if ENABLE_ASH_READ_TIMEOUT
12550                 case 't':
12551                         timeout = bb_strtou(optionarg, NULL, 10);
12552                         if (errno || timeout > UINT_MAX / 2048)
12553                                 ash_msg_and_raise_error("invalid timeout");
12554                         timeout *= 1000;
12555 #if 0 /* even bash have no -t N.NNN support */
12556                         ts.tv_sec = bb_strtou(optionarg, &p, 10);
12557                         ts.tv_usec = 0;
12558                         /* EINVAL means number is ok, but not terminated by NUL */
12559                         if (*p == '.' && errno == EINVAL) {
12560                                 char *p2;
12561                                 if (*++p) {
12562                                         int scale;
12563                                         ts.tv_usec = bb_strtou(p, &p2, 10);
12564                                         if (errno)
12565                                                 ash_msg_and_raise_error("invalid timeout");
12566                                         scale = p2 - p;
12567                                         /* normalize to usec */
12568                                         if (scale > 6)
12569                                                 ash_msg_and_raise_error("invalid timeout");
12570                                         while (scale++ < 6)
12571                                                 ts.tv_usec *= 10;
12572                                 }
12573                         } else if (ts.tv_sec < 0 || errno) {
12574                                 ash_msg_and_raise_error("invalid timeout");
12575                         }
12576                         if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12577                                 ash_msg_and_raise_error("invalid timeout");
12578                         }
12579 #endif /* if 0 */
12580                         break;
12581 #endif
12582                 case 'r':
12583                         rflag = 1;
12584                         break;
12585                 case 'u':
12586                         fd = bb_strtou(optionarg, NULL, 10);
12587                         if (fd < 0 || errno)
12588                                 ash_msg_and_raise_error("invalid file descriptor");
12589                         break;
12590                 default:
12591                         break;
12592                 }
12593         }
12594         if (prompt && isatty(fd)) {
12595                 out2str(prompt);
12596         }
12597         ap = argptr;
12598         if (*ap == NULL)
12599                 ap = (char**)arg_REPLY;
12600         ifs = bltinlookup("IFS");
12601         if (ifs == NULL)
12602                 ifs = defifs;
12603 #if ENABLE_ASH_READ_NCHARS
12604         tcgetattr(fd, &tty);
12605         old_tty = tty;
12606         if (nchars || silent) {
12607                 if (nchars) {
12608                         tty.c_lflag &= ~ICANON;
12609                         tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12610                 }
12611                 if (silent) {
12612                         tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12613                 }
12614                 /* if tcgetattr failed, tcsetattr will fail too.
12615                  * Ignoring, it's harmless. */
12616                 tcsetattr(fd, TCSANOW, &tty);
12617         }
12618 #endif
12619
12620         status = 0;
12621         startword = 2;
12622         backslash = 0;
12623 #if ENABLE_ASH_READ_TIMEOUT
12624         if (timeout) /* NB: ensuring end_ms is nonzero */
12625                 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12626 #endif
12627         STARTSTACKSTR(p);
12628         do {
12629                 const char *is_ifs;
12630
12631 #if ENABLE_ASH_READ_TIMEOUT
12632                 if (end_ms) {
12633                         struct pollfd pfd[1];
12634                         pfd[0].fd = fd;
12635                         pfd[0].events = POLLIN;
12636                         timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12637                         if ((int)timeout <= 0 /* already late? */
12638                          || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12639                         ) { /* timed out! */
12640 #if ENABLE_ASH_READ_NCHARS
12641                                 tcsetattr(fd, TCSANOW, &old_tty);
12642 #endif
12643                                 return 1;
12644                         }
12645                 }
12646 #endif
12647                 if (nonblock_safe_read(fd, &c, 1) != 1) {
12648                         status = 1;
12649                         break;
12650                 }
12651                 if (c == '\0')
12652                         continue;
12653                 if (backslash) {
12654                         backslash = 0;
12655                         if (c != '\n')
12656                                 goto put;
12657                         continue;
12658                 }
12659                 if (!rflag && c == '\\') {
12660                         backslash = 1;
12661                         continue;
12662                 }
12663                 if (c == '\n')
12664                         break;
12665                 /* $IFS splitting */
12666 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12667                 is_ifs = strchr(ifs, c);
12668                 if (startword && is_ifs) {
12669                         if (isspace(c))
12670                                 continue;
12671                         /* it is a non-space ifs char */
12672                         startword--;
12673                         if (startword == 1) /* first one? */
12674                                 continue; /* yes, it is not next word yet */
12675                 }
12676                 startword = 0;
12677                 if (ap[1] != NULL && is_ifs) {
12678                         const char *beg;
12679                         STACKSTRNUL(p);
12680                         beg = stackblock();
12681                         setvar(*ap, beg, 0);
12682                         ap++;
12683                         /* can we skip one non-space ifs char? (2: yes) */
12684                         startword = isspace(c) ? 2 : 1;
12685                         STARTSTACKSTR(p);
12686                         continue;
12687                 }
12688  put:
12689                 STPUTC(c, p);
12690         }
12691 /* end of do {} while: */
12692 #if ENABLE_ASH_READ_NCHARS
12693         while (--nchars);
12694 #else
12695         while (1);
12696 #endif
12697
12698 #if ENABLE_ASH_READ_NCHARS
12699         tcsetattr(fd, TCSANOW, &old_tty);
12700 #endif
12701
12702         STACKSTRNUL(p);
12703         /* Remove trailing space ifs chars */
12704         while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12705                 *p = '\0';
12706         setvar(*ap, stackblock(), 0);
12707         while (*++ap != NULL)
12708                 setvar(*ap, nullstr, 0);
12709         return status;
12710 }
12711
12712 static int FAST_FUNC
12713 umaskcmd(int argc UNUSED_PARAM, char **argv)
12714 {
12715         static const char permuser[3] ALIGN1 = "ugo";
12716         static const char permmode[3] ALIGN1 = "rwx";
12717         static const short permmask[] ALIGN2 = {
12718                 S_IRUSR, S_IWUSR, S_IXUSR,
12719                 S_IRGRP, S_IWGRP, S_IXGRP,
12720                 S_IROTH, S_IWOTH, S_IXOTH
12721         };
12722
12723         /* TODO: use bb_parse_mode() instead */
12724
12725         char *ap;
12726         mode_t mask;
12727         int i;
12728         int symbolic_mode = 0;
12729
12730         while (nextopt("S") != '\0') {
12731                 symbolic_mode = 1;
12732         }
12733
12734         INT_OFF;
12735         mask = umask(0);
12736         umask(mask);
12737         INT_ON;
12738
12739         ap = *argptr;
12740         if (ap == NULL) {
12741                 if (symbolic_mode) {
12742                         char buf[18];
12743                         char *p = buf;
12744
12745                         for (i = 0; i < 3; i++) {
12746                                 int j;
12747
12748                                 *p++ = permuser[i];
12749                                 *p++ = '=';
12750                                 for (j = 0; j < 3; j++) {
12751                                         if ((mask & permmask[3 * i + j]) == 0) {
12752                                                 *p++ = permmode[j];
12753                                         }
12754                                 }
12755                                 *p++ = ',';
12756                         }
12757                         *--p = 0;
12758                         puts(buf);
12759                 } else {
12760                         out1fmt("%.4o\n", mask);
12761                 }
12762         } else {
12763                 if (isdigit((unsigned char) *ap)) {
12764                         mask = 0;
12765                         do {
12766                                 if (*ap >= '8' || *ap < '0')
12767                                         ash_msg_and_raise_error(msg_illnum, argv[1]);
12768                                 mask = (mask << 3) + (*ap - '0');
12769                         } while (*++ap != '\0');
12770                         umask(mask);
12771                 } else {
12772                         mask = ~mask & 0777;
12773                         if (!bb_parse_mode(ap, &mask)) {
12774                                 ash_msg_and_raise_error("illegal mode: %s", ap);
12775                         }
12776                         umask(~mask & 0777);
12777                 }
12778         }
12779         return 0;
12780 }
12781
12782 /*
12783  * ulimit builtin
12784  *
12785  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12786  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12787  * ash by J.T. Conklin.
12788  *
12789  * Public domain.
12790  */
12791 struct limits {
12792         uint8_t cmd;          /* RLIMIT_xxx fit into it */
12793         uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12794         char    option;
12795 };
12796
12797 static const struct limits limits_tbl[] = {
12798 #ifdef RLIMIT_CPU
12799         { RLIMIT_CPU,        0, 't' },
12800 #endif
12801 #ifdef RLIMIT_FSIZE
12802         { RLIMIT_FSIZE,      9, 'f' },
12803 #endif
12804 #ifdef RLIMIT_DATA
12805         { RLIMIT_DATA,      10, 'd' },
12806 #endif
12807 #ifdef RLIMIT_STACK
12808         { RLIMIT_STACK,     10, 's' },
12809 #endif
12810 #ifdef RLIMIT_CORE
12811         { RLIMIT_CORE,       9, 'c' },
12812 #endif
12813 #ifdef RLIMIT_RSS
12814         { RLIMIT_RSS,       10, 'm' },
12815 #endif
12816 #ifdef RLIMIT_MEMLOCK
12817         { RLIMIT_MEMLOCK,   10, 'l' },
12818 #endif
12819 #ifdef RLIMIT_NPROC
12820         { RLIMIT_NPROC,      0, 'p' },
12821 #endif
12822 #ifdef RLIMIT_NOFILE
12823         { RLIMIT_NOFILE,     0, 'n' },
12824 #endif
12825 #ifdef RLIMIT_AS
12826         { RLIMIT_AS,        10, 'v' },
12827 #endif
12828 #ifdef RLIMIT_LOCKS
12829         { RLIMIT_LOCKS,      0, 'w' },
12830 #endif
12831 };
12832 static const char limits_name[] =
12833 #ifdef RLIMIT_CPU
12834         "time(seconds)" "\0"
12835 #endif
12836 #ifdef RLIMIT_FSIZE
12837         "file(blocks)" "\0"
12838 #endif
12839 #ifdef RLIMIT_DATA
12840         "data(kb)" "\0"
12841 #endif
12842 #ifdef RLIMIT_STACK
12843         "stack(kb)" "\0"
12844 #endif
12845 #ifdef RLIMIT_CORE
12846         "coredump(blocks)" "\0"
12847 #endif
12848 #ifdef RLIMIT_RSS
12849         "memory(kb)" "\0"
12850 #endif
12851 #ifdef RLIMIT_MEMLOCK
12852         "locked memory(kb)" "\0"
12853 #endif
12854 #ifdef RLIMIT_NPROC
12855         "process" "\0"
12856 #endif
12857 #ifdef RLIMIT_NOFILE
12858         "nofiles" "\0"
12859 #endif
12860 #ifdef RLIMIT_AS
12861         "vmemory(kb)" "\0"
12862 #endif
12863 #ifdef RLIMIT_LOCKS
12864         "locks" "\0"
12865 #endif
12866 ;
12867
12868 enum limtype { SOFT = 0x1, HARD = 0x2 };
12869
12870 static void
12871 printlim(enum limtype how, const struct rlimit *limit,
12872                         const struct limits *l)
12873 {
12874         rlim_t val;
12875
12876         val = limit->rlim_max;
12877         if (how & SOFT)
12878                 val = limit->rlim_cur;
12879
12880         if (val == RLIM_INFINITY)
12881                 out1fmt("unlimited\n");
12882         else {
12883                 val >>= l->factor_shift;
12884                 out1fmt("%lld\n", (long long) val);
12885         }
12886 }
12887
12888 static int FAST_FUNC
12889 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12890 {
12891         int c;
12892         rlim_t val = 0;
12893         enum limtype how = SOFT | HARD;
12894         const struct limits *l;
12895         int set, all = 0;
12896         int optc, what;
12897         struct rlimit limit;
12898
12899         what = 'f';
12900         while ((optc = nextopt("HSa"
12901 #ifdef RLIMIT_CPU
12902                                 "t"
12903 #endif
12904 #ifdef RLIMIT_FSIZE
12905                                 "f"
12906 #endif
12907 #ifdef RLIMIT_DATA
12908                                 "d"
12909 #endif
12910 #ifdef RLIMIT_STACK
12911                                 "s"
12912 #endif
12913 #ifdef RLIMIT_CORE
12914                                 "c"
12915 #endif
12916 #ifdef RLIMIT_RSS
12917                                 "m"
12918 #endif
12919 #ifdef RLIMIT_MEMLOCK
12920                                 "l"
12921 #endif
12922 #ifdef RLIMIT_NPROC
12923                                 "p"
12924 #endif
12925 #ifdef RLIMIT_NOFILE
12926                                 "n"
12927 #endif
12928 #ifdef RLIMIT_AS
12929                                 "v"
12930 #endif
12931 #ifdef RLIMIT_LOCKS
12932                                 "w"
12933 #endif
12934                                         )) != '\0')
12935                 switch (optc) {
12936                 case 'H':
12937                         how = HARD;
12938                         break;
12939                 case 'S':
12940                         how = SOFT;
12941                         break;
12942                 case 'a':
12943                         all = 1;
12944                         break;
12945                 default:
12946                         what = optc;
12947                 }
12948
12949         for (l = limits_tbl; l->option != what; l++)
12950                 continue;
12951
12952         set = *argptr ? 1 : 0;
12953         if (set) {
12954                 char *p = *argptr;
12955
12956                 if (all || argptr[1])
12957                         ash_msg_and_raise_error("too many arguments");
12958                 if (strncmp(p, "unlimited\n", 9) == 0)
12959                         val = RLIM_INFINITY;
12960                 else {
12961                         val = (rlim_t) 0;
12962
12963                         while ((c = *p++) >= '0' && c <= '9') {
12964                                 val = (val * 10) + (long)(c - '0');
12965                                 // val is actually 'unsigned long int' and can't get < 0
12966                                 if (val < (rlim_t) 0)
12967                                         break;
12968                         }
12969                         if (c)
12970                                 ash_msg_and_raise_error("bad number");
12971                         val <<= l->factor_shift;
12972                 }
12973         }
12974         if (all) {
12975                 const char *lname = limits_name;
12976                 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12977                         getrlimit(l->cmd, &limit);
12978                         out1fmt("%-20s ", lname);
12979                         lname += strlen(lname) + 1;
12980                         printlim(how, &limit, l);
12981                 }
12982                 return 0;
12983         }
12984
12985         getrlimit(l->cmd, &limit);
12986         if (set) {
12987                 if (how & HARD)
12988                         limit.rlim_max = val;
12989                 if (how & SOFT)
12990                         limit.rlim_cur = val;
12991                 if (setrlimit(l->cmd, &limit) < 0)
12992                         ash_msg_and_raise_error("error setting limit (%m)");
12993         } else {
12994                 printlim(how, &limit, l);
12995         }
12996         return 0;
12997 }
12998
12999 /* ============ main() and helpers */
13000
13001 /*
13002  * Called to exit the shell.
13003  */
13004 static void exitshell(void) NORETURN;
13005 static void
13006 exitshell(void)
13007 {
13008         struct jmploc loc;
13009         char *p;
13010         int status;
13011
13012         status = exitstatus;
13013         TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13014         if (setjmp(loc.loc)) {
13015                 if (exception_type == EXEXIT)
13016 /* dash bug: it just does _exit(exitstatus) here
13017  * but we have to do setjobctl(0) first!
13018  * (bug is still not fixed in dash-0.5.3 - if you run dash
13019  * under Midnight Commander, on exit from dash MC is backgrounded) */
13020                         status = exitstatus;
13021                 goto out;
13022         }
13023         exception_handler = &loc;
13024         p = trap[0];
13025         if (p) {
13026                 trap[0] = NULL;
13027                 evalstring(p, 0);
13028                 free(p);
13029         }
13030         flush_stdout_stderr();
13031  out:
13032         setjobctl(0);
13033         _exit(status);
13034         /* NOTREACHED */
13035 }
13036
13037 static void
13038 init(void)
13039 {
13040         /* from input.c: */
13041         basepf.next_to_pgetc = basepf.buf = basebuf;
13042
13043         /* from trap.c: */
13044         signal(SIGCHLD, SIG_DFL);
13045
13046         /* from var.c: */
13047         {
13048                 char **envp;
13049                 char ppid[sizeof(int)*3 + 2];
13050                 const char *p;
13051                 struct stat st1, st2;
13052
13053                 initvar();
13054                 for (envp = environ; envp && *envp; envp++) {
13055                         if (strchr(*envp, '=')) {
13056                                 setvareq(*envp, VEXPORT|VTEXTFIXED);
13057                         }
13058                 }
13059
13060                 sprintf(ppid, "%u", (unsigned) getppid());
13061                 setvar("PPID", ppid, 0);
13062
13063                 p = lookupvar("PWD");
13064                 if (p)
13065                         if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13066                          || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13067                                 p = '\0';
13068                 setpwd(p, 0);
13069         }
13070 }
13071
13072 /*
13073  * Process the shell command line arguments.
13074  */
13075 static void
13076 procargs(char **argv)
13077 {
13078         int i;
13079         const char *xminusc;
13080         char **xargv;
13081
13082         xargv = argv;
13083         arg0 = xargv[0];
13084         /* if (xargv[0]) - mmm, this is always true! */
13085                 xargv++;
13086         for (i = 0; i < NOPTS; i++)
13087                 optlist[i] = 2;
13088         argptr = xargv;
13089         if (options(1)) {
13090                 /* it already printed err message */
13091                 raise_exception(EXERROR);
13092         }
13093         xargv = argptr;
13094         xminusc = minusc;
13095         if (*xargv == NULL) {
13096                 if (xminusc)
13097                         ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13098                 sflag = 1;
13099         }
13100         if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13101                 iflag = 1;
13102         if (mflag == 2)
13103                 mflag = iflag;
13104         for (i = 0; i < NOPTS; i++)
13105                 if (optlist[i] == 2)
13106                         optlist[i] = 0;
13107 #if DEBUG == 2
13108         debug = 1;
13109 #endif
13110         /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13111         if (xminusc) {
13112                 minusc = *xargv++;
13113                 if (*xargv)
13114                         goto setarg0;
13115         } else if (!sflag) {
13116                 setinputfile(*xargv, 0);
13117  setarg0:
13118                 arg0 = *xargv++;
13119                 commandname = arg0;
13120         }
13121
13122         shellparam.p = xargv;
13123 #if ENABLE_ASH_GETOPTS
13124         shellparam.optind = 1;
13125         shellparam.optoff = -1;
13126 #endif
13127         /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13128         while (*xargv) {
13129                 shellparam.nparam++;
13130                 xargv++;
13131         }
13132         optschanged();
13133 }
13134
13135 /*
13136  * Read /etc/profile or .profile.
13137  */
13138 static void
13139 read_profile(const char *name)
13140 {
13141         int skip;
13142
13143         if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13144                 return;
13145         skip = cmdloop(0);
13146         popfile();
13147         if (skip)
13148                 exitshell();
13149 }
13150
13151 /*
13152  * This routine is called when an error or an interrupt occurs in an
13153  * interactive shell and control is returned to the main command loop.
13154  */
13155 static void
13156 reset(void)
13157 {
13158         /* from eval.c: */
13159         evalskip = 0;
13160         loopnest = 0;
13161         /* from input.c: */
13162         g_parsefile->left_in_buffer = 0;
13163         g_parsefile->left_in_line = 0;      /* clear input buffer */
13164         popallfiles();
13165         /* from parser.c: */
13166         tokpushback = 0;
13167         checkkwd = 0;
13168         /* from redir.c: */
13169         clearredir(/*drop:*/ 0);
13170 }
13171
13172 #if PROFILE
13173 static short profile_buf[16384];
13174 extern int etext();
13175 #endif
13176
13177 /*
13178  * Main routine.  We initialize things, parse the arguments, execute
13179  * profiles if we're a login shell, and then call cmdloop to execute
13180  * commands.  The setjmp call sets up the location to jump to when an
13181  * exception occurs.  When an exception occurs the variable "state"
13182  * is used to figure out how far we had gotten.
13183  */
13184 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13185 int ash_main(int argc UNUSED_PARAM, char **argv)
13186 {
13187         const char *shinit;
13188         volatile smallint state;
13189         struct jmploc jmploc;
13190         struct stackmark smark;
13191
13192         /* Initialize global data */
13193         INIT_G_misc();
13194         INIT_G_memstack();
13195         INIT_G_var();
13196 #if ENABLE_ASH_ALIAS
13197         INIT_G_alias();
13198 #endif
13199         INIT_G_cmdtable();
13200
13201 #if PROFILE
13202         monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13203 #endif
13204
13205 #if ENABLE_FEATURE_EDITING
13206         line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13207 #endif
13208         state = 0;
13209         if (setjmp(jmploc.loc)) {
13210                 smallint e;
13211                 smallint s;
13212
13213                 reset();
13214
13215                 e = exception_type;
13216                 if (e == EXERROR)
13217                         exitstatus = 2;
13218                 s = state;
13219                 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13220                         exitshell();
13221                 if (e == EXINT)
13222                         outcslow('\n', stderr);
13223
13224                 popstackmark(&smark);
13225                 FORCE_INT_ON; /* enable interrupts */
13226                 if (s == 1)
13227                         goto state1;
13228                 if (s == 2)
13229                         goto state2;
13230                 if (s == 3)
13231                         goto state3;
13232                 goto state4;
13233         }
13234         exception_handler = &jmploc;
13235 #if DEBUG
13236         opentrace();
13237         TRACE(("Shell args: "));
13238         trace_puts_args(argv);
13239 #endif
13240         rootpid = getpid();
13241
13242 #if ENABLE_ASH_RANDOM_SUPPORT
13243         /* Can use monotonic_ns() for better randomness but for now it is
13244          * not used anywhere else in busybox... so avoid bloat */
13245         random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13246 #endif
13247         init();
13248         setstackmark(&smark);
13249         procargs(argv);
13250
13251 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13252         if (iflag) {
13253                 const char *hp = lookupvar("HISTFILE");
13254
13255                 if (hp == NULL) {
13256                         hp = lookupvar("HOME");
13257                         if (hp != NULL) {
13258                                 char *defhp = concat_path_file(hp, ".ash_history");
13259                                 setvar("HISTFILE", defhp, 0);
13260                                 free(defhp);
13261                         }
13262                 }
13263         }
13264 #endif
13265         if (/* argv[0] && */ argv[0][0] == '-')
13266                 isloginsh = 1;
13267         if (isloginsh) {
13268                 state = 1;
13269                 read_profile("/etc/profile");
13270  state1:
13271                 state = 2;
13272                 read_profile(".profile");
13273         }
13274  state2:
13275         state = 3;
13276         if (
13277 #ifndef linux
13278          getuid() == geteuid() && getgid() == getegid() &&
13279 #endif
13280          iflag
13281         ) {
13282                 shinit = lookupvar("ENV");
13283                 if (shinit != NULL && *shinit != '\0') {
13284                         read_profile(shinit);
13285                 }
13286         }
13287  state3:
13288         state = 4;
13289         if (minusc) {
13290                 /* evalstring pushes parsefile stack.
13291                  * Ensure we don't falsely claim that 0 (stdin)
13292                  * is one of stacked source fds.
13293                  * Testcase: ash -c 'exec 1>&0' must not complain. */
13294                 if (!sflag)
13295                         g_parsefile->fd = -1;
13296                 evalstring(minusc, 0);
13297         }
13298
13299         if (sflag || minusc == NULL) {
13300 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13301                 if (iflag) {
13302                         const char *hp = lookupvar("HISTFILE");
13303                         if (hp)
13304                                 line_input_state->hist_file = hp;
13305                 }
13306 #endif
13307  state4: /* XXX ??? - why isn't this before the "if" statement */
13308                 cmdloop(1);
13309         }
13310 #if PROFILE
13311         monitor(0);
13312 #endif
13313 #ifdef GPROF
13314         {
13315                 extern void _mcleanup(void);
13316                 _mcleanup();
13317         }
13318 #endif
13319         exitshell();
13320         /* NOTREACHED */
13321 }
13322
13323
13324 /*-
13325  * Copyright (c) 1989, 1991, 1993, 1994
13326  *      The Regents of the University of California.  All rights reserved.
13327  *
13328  * This code is derived from software contributed to Berkeley by
13329  * Kenneth Almquist.
13330  *
13331  * Redistribution and use in source and binary forms, with or without
13332  * modification, are permitted provided that the following conditions
13333  * are met:
13334  * 1. Redistributions of source code must retain the above copyright
13335  *    notice, this list of conditions and the following disclaimer.
13336  * 2. Redistributions in binary form must reproduce the above copyright
13337  *    notice, this list of conditions and the following disclaimer in the
13338  *    documentation and/or other materials provided with the distribution.
13339  * 3. Neither the name of the University nor the names of its contributors
13340  *    may be used to endorse or promote products derived from this software
13341  *    without specific prior written permission.
13342  *
13343  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13344  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13345  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13346  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13347  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13348  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13349  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13350  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13351  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13352  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13353  * SUCH DAMAGE.
13354  */