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