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