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