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