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