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