ash: fix debug machinery a bit
[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 say: "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                         shcmd(lp->n, 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_PGID       0x01    /* only show pgid - for jobs -p */
3244 #define SHOW_PID        0x04    /* include process pid */
3245 #define SHOW_CHANGED    0x08    /* 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
3254 struct procstat {
3255         pid_t   pid;            /* process id */
3256         int     status;         /* last process status from wait() */
3257         char    *cmd;           /* text of command being run */
3258 };
3259
3260 struct job {
3261         struct procstat ps0;    /* status of process */
3262         struct procstat *ps;    /* status or processes when more than one */
3263 #if JOBS
3264         int stopstatus;         /* status of a stopped job */
3265 #endif
3266         uint32_t
3267                 nprocs: 16,     /* number of processes */
3268                 state: 8,
3269 #define JOBRUNNING      0       /* at least one proc running */
3270 #define JOBSTOPPED      1       /* all procs are stopped */
3271 #define JOBDONE         2       /* all procs are completed */
3272 #if JOBS
3273                 sigint: 1,      /* job was killed by SIGINT */
3274                 jobctl: 1,      /* job running under job control */
3275 #endif
3276                 waited: 1,      /* true if this entry has been waited for */
3277                 used: 1,        /* true if this entry is in used */
3278                 changed: 1;     /* true if status has changed */
3279         struct job *prev_job;   /* previous job */
3280 };
3281
3282 static struct job *makejob(/*union node *,*/ int);
3283 #if !JOBS
3284 #define forkshell(job, node, mode) forkshell(job, mode)
3285 #endif
3286 static int forkshell(struct job *, union node *, int);
3287 static int waitforjob(struct job *);
3288
3289 #if !JOBS
3290 enum { doing_jobctl = 0 };
3291 #define setjobctl(on) do {} while (0)
3292 #else
3293 static smallint doing_jobctl; //references:8
3294 static void setjobctl(int);
3295 #endif
3296
3297 /*
3298  * Ignore a signal.
3299  */
3300 static void
3301 ignoresig(int signo)
3302 {
3303         /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3304         if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3305                 /* No, need to do it */
3306                 signal(signo, SIG_IGN);
3307         }
3308         sigmode[signo - 1] = S_HARD_IGN;
3309 }
3310
3311 /*
3312  * Signal handler. Only one usage site - in setsignal()
3313  */
3314 static void
3315 onsig(int signo)
3316 {
3317         gotsig[signo - 1] = 1;
3318
3319         if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
3320                 if (!suppressint) {
3321                         pendingsig = 0;
3322                         raise_interrupt(); /* does not return */
3323                 }
3324                 intpending = 1;
3325         } else {
3326                 pendingsig = signo;
3327         }
3328 }
3329
3330 /*
3331  * Set the signal handler for the specified signal.  The routine figures
3332  * out what it should be set to.
3333  */
3334 static void
3335 setsignal(int signo)
3336 {
3337         char *t;
3338         char cur_act, new_act;
3339         struct sigaction act;
3340
3341         t = trap[signo];
3342         new_act = S_DFL;
3343         if (t != NULL) { /* trap for this sig is set */
3344                 new_act = S_CATCH;
3345                 if (t[0] == '\0') /* trap is "": ignore this sig */
3346                         new_act = S_IGN;
3347         }
3348
3349         if (rootshell && new_act == S_DFL) {
3350                 switch (signo) {
3351                 case SIGINT:
3352                         if (iflag || minusc || sflag == 0)
3353                                 new_act = S_CATCH;
3354                         break;
3355                 case SIGQUIT:
3356 #if DEBUG
3357                         if (debug)
3358                                 break;
3359 #endif
3360                         /* man bash:
3361                          * "In all cases, bash ignores SIGQUIT. Non-builtin
3362                          * commands run by bash have signal handlers
3363                          * set to the values inherited by the shell
3364                          * from its parent". */
3365                         new_act = S_IGN;
3366                         break;
3367                 case SIGTERM:
3368                         if (iflag)
3369                                 new_act = S_IGN;
3370                         break;
3371 #if JOBS
3372                 case SIGTSTP:
3373                 case SIGTTOU:
3374                         if (mflag)
3375                                 new_act = S_IGN;
3376                         break;
3377 #endif
3378                 }
3379         }
3380 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3381 //whereas we have to restore it to what shell got on entry
3382 //from the parent. See comment above
3383
3384         t = &sigmode[signo - 1];
3385         cur_act = *t;
3386         if (cur_act == 0) {
3387                 /* current setting is not yet known */
3388                 if (sigaction(signo, NULL, &act)) {
3389                         /* pretend it worked; maybe we should give a warning,
3390                          * but other shells don't. We don't alter sigmode,
3391                          * so we retry every time.
3392                          * btw, in Linux it never fails. --vda */
3393                         return;
3394                 }
3395                 if (act.sa_handler == SIG_IGN) {
3396                         cur_act = S_HARD_IGN;
3397                         if (mflag
3398                          && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3399                         ) {
3400                                 cur_act = S_IGN;   /* don't hard ignore these */
3401                         }
3402                 }
3403         }
3404         if (cur_act == S_HARD_IGN || cur_act == new_act)
3405                 return;
3406
3407         act.sa_handler = SIG_DFL;
3408         switch (new_act) {
3409         case S_CATCH:
3410                 act.sa_handler = onsig;
3411                 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3412                 sigfillset(&act.sa_mask); /* ditto */
3413                 break;
3414         case S_IGN:
3415                 act.sa_handler = SIG_IGN;
3416                 break;
3417         }
3418         sigaction_set(signo, &act);
3419
3420         *t = new_act;
3421 }
3422
3423 /* mode flags for set_curjob */
3424 #define CUR_DELETE 2
3425 #define CUR_RUNNING 1
3426 #define CUR_STOPPED 0
3427
3428 /* mode flags for dowait */
3429 #define DOWAIT_NONBLOCK WNOHANG
3430 #define DOWAIT_BLOCK    0
3431
3432 #if JOBS
3433 /* pgrp of shell on invocation */
3434 static int initialpgrp; //references:2
3435 static int ttyfd = -1; //5
3436 #endif
3437 /* array of jobs */
3438 static struct job *jobtab; //5
3439 /* size of array */
3440 static unsigned njobs; //4
3441 /* current job */
3442 static struct job *curjob; //lots
3443 /* number of presumed living untracked jobs */
3444 static int jobless; //4
3445
3446 static void
3447 set_curjob(struct job *jp, unsigned mode)
3448 {
3449         struct job *jp1;
3450         struct job **jpp, **curp;
3451
3452         /* first remove from list */
3453         jpp = curp = &curjob;
3454         do {
3455                 jp1 = *jpp;
3456                 if (jp1 == jp)
3457                         break;
3458                 jpp = &jp1->prev_job;
3459         } while (1);
3460         *jpp = jp1->prev_job;
3461
3462         /* Then re-insert in correct position */
3463         jpp = curp;
3464         switch (mode) {
3465         default:
3466 #if DEBUG
3467                 abort();
3468 #endif
3469         case CUR_DELETE:
3470                 /* job being deleted */
3471                 break;
3472         case CUR_RUNNING:
3473                 /* newly created job or backgrounded job,
3474                    put after all stopped jobs. */
3475                 do {
3476                         jp1 = *jpp;
3477 #if JOBS
3478                         if (!jp1 || jp1->state != JOBSTOPPED)
3479 #endif
3480                                 break;
3481                         jpp = &jp1->prev_job;
3482                 } while (1);
3483                 /* FALLTHROUGH */
3484 #if JOBS
3485         case CUR_STOPPED:
3486 #endif
3487                 /* newly stopped job - becomes curjob */
3488                 jp->prev_job = *jpp;
3489                 *jpp = jp;
3490                 break;
3491         }
3492 }
3493
3494 #if JOBS || DEBUG
3495 static int
3496 jobno(const struct job *jp)
3497 {
3498         return jp - jobtab + 1;
3499 }
3500 #endif
3501
3502 /*
3503  * Convert a job name to a job structure.
3504  */
3505 #if !JOBS
3506 #define getjob(name, getctl) getjob(name)
3507 #endif
3508 static struct job *
3509 getjob(const char *name, int getctl)
3510 {
3511         struct job *jp;
3512         struct job *found;
3513         const char *err_msg = "No such job: %s";
3514         unsigned num;
3515         int c;
3516         const char *p;
3517         char *(*match)(const char *, const char *);
3518
3519         jp = curjob;
3520         p = name;
3521         if (!p)
3522                 goto currentjob;
3523
3524         if (*p != '%')
3525                 goto err;
3526
3527         c = *++p;
3528         if (!c)
3529                 goto currentjob;
3530
3531         if (!p[1]) {
3532                 if (c == '+' || c == '%') {
3533  currentjob:
3534                         err_msg = "No current job";
3535                         goto check;
3536                 }
3537                 if (c == '-') {
3538                         if (jp)
3539                                 jp = jp->prev_job;
3540                         err_msg = "No previous job";
3541  check:
3542                         if (!jp)
3543                                 goto err;
3544                         goto gotit;
3545                 }
3546         }
3547
3548         if (is_number(p)) {
3549 // TODO: number() instead? It does error checking...
3550                 num = atoi(p);
3551                 if (num < njobs) {
3552                         jp = jobtab + num - 1;
3553                         if (jp->used)
3554                                 goto gotit;
3555                         goto err;
3556                 }
3557         }
3558
3559         match = prefix;
3560         if (*p == '?') {
3561                 match = strstr;
3562                 p++;
3563         }
3564
3565         found = 0;
3566         while (1) {
3567                 if (!jp)
3568                         goto err;
3569                 if (match(jp->ps[0].cmd, p)) {
3570                         if (found)
3571                                 goto err;
3572                         found = jp;
3573                         err_msg = "%s: ambiguous";
3574                 }
3575                 jp = jp->prev_job;
3576         }
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_PGID) {
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 - 2] = '+';
3948         else if (curjob && jp == curjob->prev_job)
3949                 s[col - 2] = '-';
3950
3951         if (mode & SHOW_PID)
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
3966         goto start;
3967
3968         do {
3969                 /* for each process */
3970                 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
3971  start:
3972                 fprintf(out, "%s%*c%s",
3973                         s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3974                 );
3975                 if (!(mode & SHOW_PID)) {
3976                         showpipe(jp, out);
3977                         break;
3978                 }
3979                 if (++ps == psend) {
3980                         outcslow('\n', out);
3981                         break;
3982                 }
3983         } while (1);
3984
3985         jp->changed = 0;
3986
3987         if (jp->state == JOBDONE) {
3988                 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3989                 freejob(jp);
3990         }
3991 }
3992
3993 /*
3994  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
3995  * statuses have changed since the last call to showjobs.
3996  */
3997 static void
3998 showjobs(FILE *out, int mode)
3999 {
4000         struct job *jp;
4001
4002         TRACE(("showjobs(0x%x) called\n", mode));
4003
4004         /* Handle all finished jobs */
4005         while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4006                 continue;
4007
4008         for (jp = curjob; jp; jp = jp->prev_job) {
4009                 if (!(mode & SHOW_CHANGED) || jp->changed) {
4010                         showjob(out, jp, mode);
4011                 }
4012         }
4013 }
4014
4015 static int FAST_FUNC
4016 jobscmd(int argc UNUSED_PARAM, char **argv)
4017 {
4018         int mode, m;
4019
4020         mode = 0;
4021         while ((m = nextopt("lp"))) {
4022                 if (m == 'l')
4023                         mode = SHOW_PID;
4024                 else
4025                         mode = SHOW_PGID;
4026         }
4027
4028         argv = argptr;
4029         if (*argv) {
4030                 do
4031                         showjob(stdout, getjob(*argv,0), mode);
4032                 while (*++argv);
4033         } else
4034                 showjobs(stdout, mode);
4035
4036         return 0;
4037 }
4038 #endif /* JOBS */
4039
4040 static int
4041 getstatus(struct job *job)
4042 {
4043         int status;
4044         int retval;
4045
4046         status = job->ps[job->nprocs - 1].status;
4047         retval = WEXITSTATUS(status);
4048         if (!WIFEXITED(status)) {
4049 #if JOBS
4050                 retval = WSTOPSIG(status);
4051                 if (!WIFSTOPPED(status))
4052 #endif
4053                 {
4054                         /* XXX: limits number of signals */
4055                         retval = WTERMSIG(status);
4056 #if JOBS
4057                         if (retval == SIGINT)
4058                                 job->sigint = 1;
4059 #endif
4060                 }
4061                 retval += 128;
4062         }
4063         TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4064                 jobno(job), job->nprocs, status, retval));
4065         return retval;
4066 }
4067
4068 static int FAST_FUNC
4069 waitcmd(int argc UNUSED_PARAM, char **argv)
4070 {
4071         struct job *job;
4072         int retval;
4073         struct job *jp;
4074
4075 //      exsig++;
4076 //      xbarrier();
4077         if (pendingsig)
4078                 raise_exception(EXSIG);
4079
4080         nextopt(nullstr);
4081         retval = 0;
4082
4083         argv = argptr;
4084         if (!*argv) {
4085                 /* wait for all jobs */
4086                 for (;;) {
4087                         jp = curjob;
4088                         while (1) {
4089                                 if (!jp) /* no running procs */
4090                                         goto ret;
4091                                 if (jp->state == JOBRUNNING)
4092                                         break;
4093                                 jp->waited = 1;
4094                                 jp = jp->prev_job;
4095                         }
4096         /* man bash:
4097          * "When bash is waiting for an asynchronous command via
4098          * the wait builtin, the reception of a signal for which a trap
4099          * has been set will cause the wait builtin to return immediately
4100          * with an exit status greater than 128, immediately after which
4101          * the trap is executed."
4102          * Do we do it that way? */
4103                         blocking_wait_with_raise_on_sig(NULL);
4104                 }
4105         }
4106
4107         retval = 127;
4108         do {
4109                 if (**argv != '%') {
4110                         pid_t pid = number(*argv);
4111                         job = curjob;
4112                         while (1) {
4113                                 if (!job)
4114                                         goto repeat;
4115                                 if (job->ps[job->nprocs - 1].pid == pid)
4116                                         break;
4117                                 job = job->prev_job;
4118                         }
4119                 } else
4120                         job = getjob(*argv, 0);
4121                 /* loop until process terminated or stopped */
4122                 while (job->state == JOBRUNNING)
4123                         blocking_wait_with_raise_on_sig(NULL);
4124                 job->waited = 1;
4125                 retval = getstatus(job);
4126  repeat: ;
4127         } while (*++argv);
4128
4129  ret:
4130         return retval;
4131 }
4132
4133 static struct job *
4134 growjobtab(void)
4135 {
4136         size_t len;
4137         ptrdiff_t offset;
4138         struct job *jp, *jq;
4139
4140         len = njobs * sizeof(*jp);
4141         jq = jobtab;
4142         jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4143
4144         offset = (char *)jp - (char *)jq;
4145         if (offset) {
4146                 /* Relocate pointers */
4147                 size_t l = len;
4148
4149                 jq = (struct job *)((char *)jq + l);
4150                 while (l) {
4151                         l -= sizeof(*jp);
4152                         jq--;
4153 #define joff(p) ((struct job *)((char *)(p) + l))
4154 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4155                         if (joff(jp)->ps == &jq->ps0)
4156                                 jmove(joff(jp)->ps);
4157                         if (joff(jp)->prev_job)
4158                                 jmove(joff(jp)->prev_job);
4159                 }
4160                 if (curjob)
4161                         jmove(curjob);
4162 #undef joff
4163 #undef jmove
4164         }
4165
4166         njobs += 4;
4167         jobtab = jp;
4168         jp = (struct job *)((char *)jp + len);
4169         jq = jp + 3;
4170         do {
4171                 jq->used = 0;
4172         } while (--jq >= jp);
4173         return jp;
4174 }
4175
4176 /*
4177  * Return a new job structure.
4178  * Called with interrupts off.
4179  */
4180 static struct job *
4181 makejob(/*union node *node,*/ int nprocs)
4182 {
4183         int i;
4184         struct job *jp;
4185
4186         for (i = njobs, jp = jobtab; ; jp++) {
4187                 if (--i < 0) {
4188                         jp = growjobtab();
4189                         break;
4190                 }
4191                 if (jp->used == 0)
4192                         break;
4193                 if (jp->state != JOBDONE || !jp->waited)
4194                         continue;
4195 #if JOBS
4196                 if (doing_jobctl)
4197                         continue;
4198 #endif
4199                 freejob(jp);
4200                 break;
4201         }
4202         memset(jp, 0, sizeof(*jp));
4203 #if JOBS
4204         /* jp->jobctl is a bitfield.
4205          * "jp->jobctl |= jobctl" likely to give awful code */
4206         if (doing_jobctl)
4207                 jp->jobctl = 1;
4208 #endif
4209         jp->prev_job = curjob;
4210         curjob = jp;
4211         jp->used = 1;
4212         jp->ps = &jp->ps0;
4213         if (nprocs > 1) {
4214                 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4215         }
4216         TRACE(("makejob(%d) returns %%%d\n", nprocs,
4217                                 jobno(jp)));
4218         return jp;
4219 }
4220
4221 #if JOBS
4222 /*
4223  * Return a string identifying a command (to be printed by the
4224  * jobs command).
4225  */
4226 static char *cmdnextc;
4227
4228 static void
4229 cmdputs(const char *s)
4230 {
4231         static const char vstype[VSTYPE + 1][3] = {
4232                 "", "}", "-", "+", "?", "=",
4233                 "%", "%%", "#", "##"
4234                 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4235         };
4236
4237         const char *p, *str;
4238         char c, cc[2] = " ";
4239         char *nextc;
4240         int subtype = 0;
4241         int quoted = 0;
4242
4243         nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4244         p = s;
4245         while ((c = *p++) != 0) {
4246                 str = NULL;
4247                 switch (c) {
4248                 case CTLESC:
4249                         c = *p++;
4250                         break;
4251                 case CTLVAR:
4252                         subtype = *p++;
4253                         if ((subtype & VSTYPE) == VSLENGTH)
4254                                 str = "${#";
4255                         else
4256                                 str = "${";
4257                         if (!(subtype & VSQUOTE) == !(quoted & 1))
4258                                 goto dostr;
4259                         quoted ^= 1;
4260                         c = '"';
4261                         break;
4262                 case CTLENDVAR:
4263                         str = "\"}" + !(quoted & 1);
4264                         quoted >>= 1;
4265                         subtype = 0;
4266                         goto dostr;
4267                 case CTLBACKQ:
4268                         str = "$(...)";
4269                         goto dostr;
4270                 case CTLBACKQ+CTLQUOTE:
4271                         str = "\"$(...)\"";
4272                         goto dostr;
4273 #if ENABLE_SH_MATH_SUPPORT
4274                 case CTLARI:
4275                         str = "$((";
4276                         goto dostr;
4277                 case CTLENDARI:
4278                         str = "))";
4279                         goto dostr;
4280 #endif
4281                 case CTLQUOTEMARK:
4282                         quoted ^= 1;
4283                         c = '"';
4284                         break;
4285                 case '=':
4286                         if (subtype == 0)
4287                                 break;
4288                         if ((subtype & VSTYPE) != VSNORMAL)
4289                                 quoted <<= 1;
4290                         str = vstype[subtype & VSTYPE];
4291                         if (subtype & VSNUL)
4292                                 c = ':';
4293                         else
4294                                 goto checkstr;
4295                         break;
4296                 case '\'':
4297                 case '\\':
4298                 case '"':
4299                 case '$':
4300                         /* These can only happen inside quotes */
4301                         cc[0] = c;
4302                         str = cc;
4303                         c = '\\';
4304                         break;
4305                 default:
4306                         break;
4307                 }
4308                 USTPUTC(c, nextc);
4309  checkstr:
4310                 if (!str)
4311                         continue;
4312  dostr:
4313                 while ((c = *str++)) {
4314                         USTPUTC(c, nextc);
4315                 }
4316         }
4317         if (quoted & 1) {
4318                 USTPUTC('"', nextc);
4319         }
4320         *nextc = 0;
4321         cmdnextc = nextc;
4322 }
4323
4324 /* cmdtxt() and cmdlist() call each other */
4325 static void cmdtxt(union node *n);
4326
4327 static void
4328 cmdlist(union node *np, int sep)
4329 {
4330         for (; np; np = np->narg.next) {
4331                 if (!sep)
4332                         cmdputs(" ");
4333                 cmdtxt(np);
4334                 if (sep && np->narg.next)
4335                         cmdputs(" ");
4336         }
4337 }
4338
4339 static void
4340 cmdtxt(union node *n)
4341 {
4342         union node *np;
4343         struct nodelist *lp;
4344         const char *p;
4345
4346         if (!n)
4347                 return;
4348         switch (n->type) {
4349         default:
4350 #if DEBUG
4351                 abort();
4352 #endif
4353         case NPIPE:
4354                 lp = n->npipe.cmdlist;
4355                 for (;;) {
4356                         cmdtxt(lp->n);
4357                         lp = lp->next;
4358                         if (!lp)
4359                                 break;
4360                         cmdputs(" | ");
4361                 }
4362                 break;
4363         case NSEMI:
4364                 p = "; ";
4365                 goto binop;
4366         case NAND:
4367                 p = " && ";
4368                 goto binop;
4369         case NOR:
4370                 p = " || ";
4371  binop:
4372                 cmdtxt(n->nbinary.ch1);
4373                 cmdputs(p);
4374                 n = n->nbinary.ch2;
4375                 goto donode;
4376         case NREDIR:
4377         case NBACKGND:
4378                 n = n->nredir.n;
4379                 goto donode;
4380         case NNOT:
4381                 cmdputs("!");
4382                 n = n->nnot.com;
4383  donode:
4384                 cmdtxt(n);
4385                 break;
4386         case NIF:
4387                 cmdputs("if ");
4388                 cmdtxt(n->nif.test);
4389                 cmdputs("; then ");
4390                 n = n->nif.ifpart;
4391                 if (n->nif.elsepart) {
4392                         cmdtxt(n);
4393                         cmdputs("; else ");
4394                         n = n->nif.elsepart;
4395                 }
4396                 p = "; fi";
4397                 goto dotail;
4398         case NSUBSHELL:
4399                 cmdputs("(");
4400                 n = n->nredir.n;
4401                 p = ")";
4402                 goto dotail;
4403         case NWHILE:
4404                 p = "while ";
4405                 goto until;
4406         case NUNTIL:
4407                 p = "until ";
4408  until:
4409                 cmdputs(p);
4410                 cmdtxt(n->nbinary.ch1);
4411                 n = n->nbinary.ch2;
4412                 p = "; done";
4413  dodo:
4414                 cmdputs("; do ");
4415  dotail:
4416                 cmdtxt(n);
4417                 goto dotail2;
4418         case NFOR:
4419                 cmdputs("for ");
4420                 cmdputs(n->nfor.var);
4421                 cmdputs(" in ");
4422                 cmdlist(n->nfor.args, 1);
4423                 n = n->nfor.body;
4424                 p = "; done";
4425                 goto dodo;
4426         case NDEFUN:
4427                 cmdputs(n->narg.text);
4428                 p = "() { ... }";
4429                 goto dotail2;
4430         case NCMD:
4431                 cmdlist(n->ncmd.args, 1);
4432                 cmdlist(n->ncmd.redirect, 0);
4433                 break;
4434         case NARG:
4435                 p = n->narg.text;
4436  dotail2:
4437                 cmdputs(p);
4438                 break;
4439         case NHERE:
4440         case NXHERE:
4441                 p = "<<...";
4442                 goto dotail2;
4443         case NCASE:
4444                 cmdputs("case ");
4445                 cmdputs(n->ncase.expr->narg.text);
4446                 cmdputs(" in ");
4447                 for (np = n->ncase.cases; np; np = np->nclist.next) {
4448                         cmdtxt(np->nclist.pattern);
4449                         cmdputs(") ");
4450                         cmdtxt(np->nclist.body);
4451                         cmdputs(";; ");
4452                 }
4453                 p = "esac";
4454                 goto dotail2;
4455         case NTO:
4456                 p = ">";
4457                 goto redir;
4458         case NCLOBBER:
4459                 p = ">|";
4460                 goto redir;
4461         case NAPPEND:
4462                 p = ">>";
4463                 goto redir;
4464 #if ENABLE_ASH_BASH_COMPAT
4465         case NTO2:
4466 #endif
4467         case NTOFD:
4468                 p = ">&";
4469                 goto redir;
4470         case NFROM:
4471                 p = "<";
4472                 goto redir;
4473         case NFROMFD:
4474                 p = "<&";
4475                 goto redir;
4476         case NFROMTO:
4477                 p = "<>";
4478  redir:
4479                 cmdputs(utoa(n->nfile.fd));
4480                 cmdputs(p);
4481                 if (n->type == NTOFD || n->type == NFROMFD) {
4482                         cmdputs(utoa(n->ndup.dupfd));
4483                         break;
4484                 }
4485                 n = n->nfile.fname;
4486                 goto donode;
4487         }
4488 }
4489
4490 static char *
4491 commandtext(union node *n)
4492 {
4493         char *name;
4494
4495         STARTSTACKSTR(cmdnextc);
4496         cmdtxt(n);
4497         name = stackblock();
4498         TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4499                         name, cmdnextc, cmdnextc));
4500         return ckstrdup(name);
4501 }
4502 #endif /* JOBS */
4503
4504 /*
4505  * Fork off a subshell.  If we are doing job control, give the subshell its
4506  * own process group.  Jp is a job structure that the job is to be added to.
4507  * N is the command that will be evaluated by the child.  Both jp and n may
4508  * be NULL.  The mode parameter can be one of the following:
4509  *      FORK_FG - Fork off a foreground process.
4510  *      FORK_BG - Fork off a background process.
4511  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
4512  *                   process group even if job control is on.
4513  *
4514  * When job control is turned off, background processes have their standard
4515  * input redirected to /dev/null (except for the second and later processes
4516  * in a pipeline).
4517  *
4518  * Called with interrupts off.
4519  */
4520 /*
4521  * Clear traps on a fork.
4522  */
4523 static void
4524 clear_traps(void)
4525 {
4526         char **tp;
4527
4528         for (tp = trap; tp < &trap[NSIG]; tp++) {
4529                 if (*tp && **tp) {      /* trap not NULL or "" (SIG_IGN) */
4530                         INT_OFF;
4531                         free(*tp);
4532                         *tp = NULL;
4533                         if (tp != &trap[0])
4534                                 setsignal(tp - trap);
4535                         INT_ON;
4536                 }
4537         }
4538 }
4539
4540 /* Lives far away from here, needed for forkchild */
4541 static void closescript(void);
4542
4543 /* Called after fork(), in child */
4544 static void
4545 forkchild(struct job *jp, /*union node *n,*/ int mode)
4546 {
4547         int oldlvl;
4548
4549         TRACE(("Child shell %d\n", getpid()));
4550         oldlvl = shlvl;
4551         shlvl++;
4552
4553         /* man bash: "Non-builtin commands run by bash have signal handlers
4554          * set to the values inherited by the shell from its parent".
4555          * Do we do it correctly? */
4556
4557         closescript();
4558         clear_traps();
4559 #if JOBS
4560         /* do job control only in root shell */
4561         doing_jobctl = 0;
4562         if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4563                 pid_t pgrp;
4564
4565                 if (jp->nprocs == 0)
4566                         pgrp = getpid();
4567                 else
4568                         pgrp = jp->ps[0].pid;
4569                 /* this can fail because we are doing it in the parent also */
4570                 setpgid(0, pgrp);
4571                 if (mode == FORK_FG)
4572                         xtcsetpgrp(ttyfd, pgrp);
4573                 setsignal(SIGTSTP);
4574                 setsignal(SIGTTOU);
4575         } else
4576 #endif
4577         if (mode == FORK_BG) {
4578                 /* man bash: "When job control is not in effect,
4579                  * asynchronous commands ignore SIGINT and SIGQUIT" */
4580                 ignoresig(SIGINT);
4581                 ignoresig(SIGQUIT);
4582                 if (jp->nprocs == 0) {
4583                         close(0);
4584                         if (open(bb_dev_null, O_RDONLY) != 0)
4585                                 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4586                 }
4587         }
4588         if (!oldlvl) {
4589                 if (iflag) { /* why if iflag only? */
4590                         setsignal(SIGINT);
4591                         setsignal(SIGTERM);
4592                 }
4593                 /* man bash:
4594                  * "In all cases, bash ignores SIGQUIT. Non-builtin
4595                  * commands run by bash have signal handlers
4596                  * set to the values inherited by the shell
4597                  * from its parent".
4598                  * Take care of the second rule: */
4599                 setsignal(SIGQUIT);
4600         }
4601         for (jp = curjob; jp; jp = jp->prev_job)
4602                 freejob(jp);
4603         jobless = 0;
4604 }
4605
4606 /* Called after fork(), in parent */
4607 #if !JOBS
4608 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4609 #endif
4610 static void
4611 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4612 {
4613         TRACE(("In parent shell: child = %d\n", pid));
4614         if (!jp) {
4615                 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4616                         continue;
4617                 jobless++;
4618                 return;
4619         }
4620 #if JOBS
4621         if (mode != FORK_NOJOB && jp->jobctl) {
4622                 int pgrp;
4623
4624                 if (jp->nprocs == 0)
4625                         pgrp = pid;
4626                 else
4627                         pgrp = jp->ps[0].pid;
4628                 /* This can fail because we are doing it in the child also */
4629                 setpgid(pid, pgrp);
4630         }
4631 #endif
4632         if (mode == FORK_BG) {
4633                 backgndpid = pid;               /* set $! */
4634                 set_curjob(jp, CUR_RUNNING);
4635         }
4636         if (jp) {
4637                 struct procstat *ps = &jp->ps[jp->nprocs++];
4638                 ps->pid = pid;
4639                 ps->status = -1;
4640                 ps->cmd = nullstr;
4641 #if JOBS
4642                 if (doing_jobctl && n)
4643                         ps->cmd = commandtext(n);
4644 #endif
4645         }
4646 }
4647
4648 static int
4649 forkshell(struct job *jp, union node *n, int mode)
4650 {
4651         int pid;
4652
4653         TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4654         pid = fork();
4655         if (pid < 0) {
4656                 TRACE(("Fork failed, errno=%d", errno));
4657                 if (jp)
4658                         freejob(jp);
4659                 ash_msg_and_raise_error("can't fork");
4660         }
4661         if (pid == 0)
4662                 forkchild(jp, /*n,*/ mode);
4663         else
4664                 forkparent(jp, n, mode, pid);
4665         return pid;
4666 }
4667
4668 /*
4669  * Wait for job to finish.
4670  *
4671  * Under job control we have the problem that while a child process
4672  * is running interrupts generated by the user are sent to the child
4673  * but not to the shell.  This means that an infinite loop started by
4674  * an interactive user may be hard to kill.  With job control turned off,
4675  * an interactive user may place an interactive program inside a loop.
4676  * If the interactive program catches interrupts, the user doesn't want
4677  * these interrupts to also abort the loop.  The approach we take here
4678  * is to have the shell ignore interrupt signals while waiting for a
4679  * foreground process to terminate, and then send itself an interrupt
4680  * signal if the child process was terminated by an interrupt signal.
4681  * Unfortunately, some programs want to do a bit of cleanup and then
4682  * exit on interrupt; unless these processes terminate themselves by
4683  * sending a signal to themselves (instead of calling exit) they will
4684  * confuse this approach.
4685  *
4686  * Called with interrupts off.
4687  */
4688 static int
4689 waitforjob(struct job *jp)
4690 {
4691         int st;
4692
4693         TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4694
4695         INT_OFF;
4696         while (jp->state == JOBRUNNING) {
4697                 /* In non-interactive shells, we _can_ get
4698                  * a keyboard signal here and be EINTRed,
4699                  * but we just loop back, waiting for command to complete.
4700                  *
4701                  * man bash:
4702                  * "If bash is waiting for a command to complete and receives
4703                  * a signal for which a trap has been set, the trap
4704                  * will not be executed until the command completes."
4705                  *
4706                  * Reality is that even if trap is not set, bash
4707                  * will not act on the signal until command completes.
4708                  * Try this. sleep5intoff.c:
4709                  * #include <signal.h>
4710                  * #include <unistd.h>
4711                  * int main() {
4712                  *         sigset_t set;
4713                  *         sigemptyset(&set);
4714                  *         sigaddset(&set, SIGINT);
4715                  *         sigaddset(&set, SIGQUIT);
4716                  *         sigprocmask(SIG_BLOCK, &set, NULL);
4717                  *         sleep(5);
4718                  *         return 0;
4719                  * }
4720                  * $ bash -c './sleep5intoff; echo hi'
4721                  * ^C^C^C^C <--- pressing ^C once a second
4722                  * $ _
4723                  * $ bash -c './sleep5intoff; echo hi'
4724                  * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4725                  * $ _
4726                  */
4727                 dowait(DOWAIT_BLOCK, jp);
4728         }
4729         INT_ON;
4730
4731         st = getstatus(jp);
4732 #if JOBS
4733         if (jp->jobctl) {
4734                 xtcsetpgrp(ttyfd, rootpid);
4735                 /*
4736                  * This is truly gross.
4737                  * If we're doing job control, then we did a TIOCSPGRP which
4738                  * caused us (the shell) to no longer be in the controlling
4739                  * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
4740                  * intuit from the subprocess exit status whether a SIGINT
4741                  * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
4742                  */
4743                 if (jp->sigint) /* TODO: do the same with all signals */
4744                         raise(SIGINT); /* ... by raise(jp->sig) instead? */
4745         }
4746         if (jp->state == JOBDONE)
4747 #endif
4748                 freejob(jp);
4749         return st;
4750 }
4751
4752 /*
4753  * return 1 if there are stopped jobs, otherwise 0
4754  */
4755 static int
4756 stoppedjobs(void)
4757 {
4758         struct job *jp;
4759         int retval;
4760
4761         retval = 0;
4762         if (job_warning)
4763                 goto out;
4764         jp = curjob;
4765         if (jp && jp->state == JOBSTOPPED) {
4766                 out2str("You have stopped jobs.\n");
4767                 job_warning = 2;
4768                 retval++;
4769         }
4770  out:
4771         return retval;
4772 }
4773
4774
4775 /* ============ redir.c
4776  *
4777  * Code for dealing with input/output redirection.
4778  */
4779
4780 #define EMPTY -2                /* marks an unused slot in redirtab */
4781 #define CLOSED -3               /* marks a slot of previously-closed fd */
4782
4783 /*
4784  * Open a file in noclobber mode.
4785  * The code was copied from bash.
4786  */
4787 static int
4788 noclobberopen(const char *fname)
4789 {
4790         int r, fd;
4791         struct stat finfo, finfo2;
4792
4793         /*
4794          * If the file exists and is a regular file, return an error
4795          * immediately.
4796          */
4797         r = stat(fname, &finfo);
4798         if (r == 0 && S_ISREG(finfo.st_mode)) {
4799                 errno = EEXIST;
4800                 return -1;
4801         }
4802
4803         /*
4804          * If the file was not present (r != 0), make sure we open it
4805          * exclusively so that if it is created before we open it, our open
4806          * will fail.  Make sure that we do not truncate an existing file.
4807          * Note that we don't turn on O_EXCL unless the stat failed -- if the
4808          * file was not a regular file, we leave O_EXCL off.
4809          */
4810         if (r != 0)
4811                 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4812         fd = open(fname, O_WRONLY|O_CREAT, 0666);
4813
4814         /* If the open failed, return the file descriptor right away. */
4815         if (fd < 0)
4816                 return fd;
4817
4818         /*
4819          * OK, the open succeeded, but the file may have been changed from a
4820          * non-regular file to a regular file between the stat and the open.
4821          * We are assuming that the O_EXCL open handles the case where FILENAME
4822          * did not exist and is symlinked to an existing file between the stat
4823          * and open.
4824          */
4825
4826         /*
4827          * If we can open it and fstat the file descriptor, and neither check
4828          * revealed that it was a regular file, and the file has not been
4829          * replaced, return the file descriptor.
4830          */
4831         if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4832          && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4833                 return fd;
4834
4835         /* The file has been replaced.  badness. */
4836         close(fd);
4837         errno = EEXIST;
4838         return -1;
4839 }
4840
4841 /*
4842  * Handle here documents.  Normally we fork off a process to write the
4843  * data to a pipe.  If the document is short, we can stuff the data in
4844  * the pipe without forking.
4845  */
4846 /* openhere needs this forward reference */
4847 static void expandhere(union node *arg, int fd);
4848 static int
4849 openhere(union node *redir)
4850 {
4851         int pip[2];
4852         size_t len = 0;
4853
4854         if (pipe(pip) < 0)
4855                 ash_msg_and_raise_error("pipe call failed");
4856         if (redir->type == NHERE) {
4857                 len = strlen(redir->nhere.doc->narg.text);
4858                 if (len <= PIPE_BUF) {
4859                         full_write(pip[1], redir->nhere.doc->narg.text, len);
4860                         goto out;
4861                 }
4862         }
4863         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4864                 /* child */
4865                 close(pip[0]);
4866                 ignoresig(SIGINT);  //signal(SIGINT, SIG_IGN);
4867                 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4868                 ignoresig(SIGHUP);  //signal(SIGHUP, SIG_IGN);
4869                 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4870                 signal(SIGPIPE, SIG_DFL);
4871                 if (redir->type == NHERE)
4872                         full_write(pip[1], redir->nhere.doc->narg.text, len);
4873                 else /* NXHERE */
4874                         expandhere(redir->nhere.doc, pip[1]);
4875                 _exit(EXIT_SUCCESS);
4876         }
4877  out:
4878         close(pip[1]);
4879         return pip[0];
4880 }
4881
4882 static int
4883 openredirect(union node *redir)
4884 {
4885         char *fname;
4886         int f;
4887
4888         switch (redir->nfile.type) {
4889         case NFROM:
4890                 fname = redir->nfile.expfname;
4891                 f = open(fname, O_RDONLY);
4892                 if (f < 0)
4893                         goto eopen;
4894                 break;
4895         case NFROMTO:
4896                 fname = redir->nfile.expfname;
4897                 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4898                 if (f < 0)
4899                         goto ecreate;
4900                 break;
4901         case NTO:
4902 #if ENABLE_ASH_BASH_COMPAT
4903         case NTO2:
4904 #endif
4905                 /* Take care of noclobber mode. */
4906                 if (Cflag) {
4907                         fname = redir->nfile.expfname;
4908                         f = noclobberopen(fname);
4909                         if (f < 0)
4910                                 goto ecreate;
4911                         break;
4912                 }
4913                 /* FALLTHROUGH */
4914         case NCLOBBER:
4915                 fname = redir->nfile.expfname;
4916                 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4917                 if (f < 0)
4918                         goto ecreate;
4919                 break;
4920         case NAPPEND:
4921                 fname = redir->nfile.expfname;
4922                 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4923                 if (f < 0)
4924                         goto ecreate;
4925                 break;
4926         default:
4927 #if DEBUG
4928                 abort();
4929 #endif
4930                 /* Fall through to eliminate warning. */
4931 /* Our single caller does this itself */
4932 //      case NTOFD:
4933 //      case NFROMFD:
4934 //              f = -1;
4935 //              break;
4936         case NHERE:
4937         case NXHERE:
4938                 f = openhere(redir);
4939                 break;
4940         }
4941
4942         return f;
4943  ecreate:
4944         ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4945  eopen:
4946         ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4947 }
4948
4949 /*
4950  * Copy a file descriptor to be >= to.  Returns -1
4951  * if the source file descriptor is closed, EMPTY if there are no unused
4952  * file descriptors left.
4953  */
4954 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4955  * old code was doing close(to) prior to copyfd() to achieve the same */
4956 enum {
4957         COPYFD_EXACT   = (int)~(INT_MAX),
4958         COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4959 };
4960 static int
4961 copyfd(int from, int to)
4962 {
4963         int newfd;
4964
4965         if (to & COPYFD_EXACT) {
4966                 to &= ~COPYFD_EXACT;
4967                 /*if (from != to)*/
4968                         newfd = dup2(from, to);
4969         } else {
4970                 newfd = fcntl(from, F_DUPFD, to);
4971         }
4972         if (newfd < 0) {
4973                 if (errno == EMFILE)
4974                         return EMPTY;
4975                 /* Happens when source fd is not open: try "echo >&99" */
4976                 ash_msg_and_raise_error("%d: %m", from);
4977         }
4978         return newfd;
4979 }
4980
4981 /* Struct def and variable are moved down to the first usage site */
4982 struct two_fd_t {
4983         int orig, copy;
4984 };
4985 struct redirtab {
4986         struct redirtab *next;
4987         int nullredirs;
4988         int pair_count;
4989         struct two_fd_t two_fd[0];
4990 };
4991 #define redirlist (G_var.redirlist)
4992
4993 static int need_to_remember(struct redirtab *rp, int fd)
4994 {
4995         int i;
4996
4997         if (!rp) /* remembering was not requested */
4998                 return 0;
4999
5000         for (i = 0; i < rp->pair_count; i++) {
5001                 if (rp->two_fd[i].orig == fd) {
5002                         /* already remembered */
5003                         return 0;
5004                 }
5005         }
5006         return 1;
5007 }
5008
5009 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5010 static int is_hidden_fd(struct redirtab *rp, int fd)
5011 {
5012         int i;
5013         struct parsefile *pf;
5014
5015         if (fd == -1)
5016                 return 0;
5017         pf = g_parsefile;
5018         while (pf) {
5019                 if (fd == pf->fd) {
5020                         return 1;
5021                 }
5022                 pf = pf->prev;
5023         }
5024         if (!rp)
5025                 return 0;
5026         fd |= COPYFD_RESTORE;
5027         for (i = 0; i < rp->pair_count; i++) {
5028                 if (rp->two_fd[i].copy == fd) {
5029                         return 1;
5030                 }
5031         }
5032         return 0;
5033 }
5034
5035 /*
5036  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
5037  * old file descriptors are stashed away so that the redirection can be
5038  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
5039  * standard output, and the standard error if it becomes a duplicate of
5040  * stdout, is saved in memory.
5041  */
5042 /* flags passed to redirect */
5043 #define REDIR_PUSH    01        /* save previous values of file descriptors */
5044 #define REDIR_SAVEFD2 03        /* set preverrout */
5045 static void
5046 redirect(union node *redir, int flags)
5047 {
5048         struct redirtab *sv;
5049         int sv_pos;
5050         int i;
5051         int fd;
5052         int newfd;
5053         int copied_fd2 = -1;
5054
5055         g_nullredirs++;
5056         if (!redir) {
5057                 return;
5058         }
5059
5060         sv = NULL;
5061         sv_pos = 0;
5062         INT_OFF;
5063         if (flags & REDIR_PUSH) {
5064                 union node *tmp = redir;
5065                 do {
5066                         sv_pos++;
5067 #if ENABLE_ASH_BASH_COMPAT
5068                         if (redir->nfile.type == NTO2)
5069                                 sv_pos++;
5070 #endif
5071                         tmp = tmp->nfile.next;
5072                 } while (tmp);
5073                 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5074                 sv->next = redirlist;
5075                 sv->pair_count = sv_pos;
5076                 redirlist = sv;
5077                 sv->nullredirs = g_nullredirs - 1;
5078                 g_nullredirs = 0;
5079                 while (sv_pos > 0) {
5080                         sv_pos--;
5081                         sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5082                 }
5083         }
5084
5085         do {
5086                 fd = redir->nfile.fd;
5087                 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5088                         int right_fd = redir->ndup.dupfd;
5089                         /* redirect from/to same file descriptor? */
5090                         if (right_fd == fd)
5091                                 continue;
5092                         /* echo >&10 and 10 is a fd opened to the sh script? */
5093                         if (is_hidden_fd(sv, right_fd)) {
5094                                 errno = EBADF; /* as if it is closed */
5095                                 ash_msg_and_raise_error("%d: %m", right_fd);
5096                         }
5097                         newfd = -1;
5098                 } else {
5099                         newfd = openredirect(redir); /* always >= 0 */
5100                         if (fd == newfd) {
5101                                 /* Descriptor wasn't open before redirect.
5102                                  * Mark it for close in the future */
5103                                 if (need_to_remember(sv, fd)) {
5104                                         goto remember_to_close;
5105                                 }
5106                                 continue;
5107                         }
5108                 }
5109 #if ENABLE_ASH_BASH_COMPAT
5110  redirect_more:
5111 #endif
5112                 if (need_to_remember(sv, fd)) {
5113                         /* Copy old descriptor */
5114                         i = fcntl(fd, F_DUPFD, 10);
5115 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5116  * are closed in popredir() in the child, preventing them from leaking
5117  * into child. (popredir() also cleans up the mess in case of failures)
5118  */
5119                         if (i == -1) {
5120                                 i = errno;
5121                                 if (i != EBADF) {
5122                                         /* Strange error (e.g. "too many files" EMFILE?) */
5123                                         if (newfd >= 0)
5124                                                 close(newfd);
5125                                         errno = i;
5126                                         ash_msg_and_raise_error("%d: %m", fd);
5127                                         /* NOTREACHED */
5128                                 }
5129                                 /* EBADF: it is not open - good, remember to close it */
5130  remember_to_close:
5131                                 i = CLOSED;
5132                         } else { /* fd is open, save its copy */
5133                                 /* "exec fd>&-" should not close fds
5134                                  * which point to script file(s).
5135                                  * Force them to be restored afterwards */
5136                                 if (is_hidden_fd(sv, fd))
5137                                         i |= COPYFD_RESTORE;
5138                         }
5139                         if (fd == 2)
5140                                 copied_fd2 = i;
5141                         sv->two_fd[sv_pos].orig = fd;
5142                         sv->two_fd[sv_pos].copy = i;
5143                         sv_pos++;
5144                 }
5145                 if (newfd < 0) {
5146                         /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5147                         if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5148                                 /* Don't want to trigger debugging */
5149                                 if (fd != -1)
5150                                         close(fd);
5151                         } else {
5152                                 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5153                         }
5154                 } else if (fd != newfd) { /* move newfd to fd */
5155                         copyfd(newfd, fd | COPYFD_EXACT);
5156 #if ENABLE_ASH_BASH_COMPAT
5157                         if (!(redir->nfile.type == NTO2 && fd == 2))
5158 #endif
5159                                 close(newfd);
5160                 }
5161 #if ENABLE_ASH_BASH_COMPAT
5162                 if (redir->nfile.type == NTO2 && fd == 1) {
5163                         /* We already redirected it to fd 1, now copy it to 2 */
5164                         newfd = 1;
5165                         fd = 2;
5166                         goto redirect_more;
5167                 }
5168 #endif
5169         } while ((redir = redir->nfile.next) != NULL);
5170
5171         INT_ON;
5172         if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5173                 preverrout_fd = copied_fd2;
5174 }
5175
5176 /*
5177  * Undo the effects of the last redirection.
5178  */
5179 static void
5180 popredir(int drop, int restore)
5181 {
5182         struct redirtab *rp;
5183         int i;
5184
5185         if (--g_nullredirs >= 0)
5186                 return;
5187         INT_OFF;
5188         rp = redirlist;
5189         for (i = 0; i < rp->pair_count; i++) {
5190                 int fd = rp->two_fd[i].orig;
5191                 int copy = rp->two_fd[i].copy;
5192                 if (copy == CLOSED) {
5193                         if (!drop)
5194                                 close(fd);
5195                         continue;
5196                 }
5197                 if (copy != EMPTY) {
5198                         if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5199                                 copy &= ~COPYFD_RESTORE;
5200                                 /*close(fd);*/
5201                                 copyfd(copy, fd | COPYFD_EXACT);
5202                         }
5203                         close(copy & ~COPYFD_RESTORE);
5204                 }
5205         }
5206         redirlist = rp->next;
5207         g_nullredirs = rp->nullredirs;
5208         free(rp);
5209         INT_ON;
5210 }
5211
5212 /*
5213  * Undo all redirections.  Called on error or interrupt.
5214  */
5215
5216 /*
5217  * Discard all saved file descriptors.
5218  */
5219 static void
5220 clearredir(int drop)
5221 {
5222         for (;;) {
5223                 g_nullredirs = 0;
5224                 if (!redirlist)
5225                         break;
5226                 popredir(drop, /*restore:*/ 0);
5227         }
5228 }
5229
5230 static int
5231 redirectsafe(union node *redir, int flags)
5232 {
5233         int err;
5234         volatile int saveint;
5235         struct jmploc *volatile savehandler = exception_handler;
5236         struct jmploc jmploc;
5237
5238         SAVE_INT(saveint);
5239         /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5240         err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5241         if (!err) {
5242                 exception_handler = &jmploc;
5243                 redirect(redir, flags);
5244         }
5245         exception_handler = savehandler;
5246         if (err && exception_type != EXERROR)
5247                 longjmp(exception_handler->loc, 1);
5248         RESTORE_INT(saveint);
5249         return err;
5250 }
5251
5252
5253 /* ============ Routines to expand arguments to commands
5254  *
5255  * We have to deal with backquotes, shell variables, and file metacharacters.
5256  */
5257
5258 #if ENABLE_SH_MATH_SUPPORT
5259 static arith_t
5260 ash_arith(const char *s)
5261 {
5262         arith_eval_hooks_t math_hooks;
5263         arith_t result;
5264         int errcode = 0;
5265
5266         math_hooks.lookupvar = lookupvar;
5267         math_hooks.setvar = setvar;
5268         math_hooks.endofname = endofname;
5269
5270         INT_OFF;
5271         result = arith(s, &errcode, &math_hooks);
5272         if (errcode < 0) {
5273                 if (errcode == -3)
5274                         ash_msg_and_raise_error("exponent less than 0");
5275                 if (errcode == -2)
5276                         ash_msg_and_raise_error("divide by zero");
5277                 if (errcode == -5)
5278                         ash_msg_and_raise_error("expression recursion loop detected");
5279                 raise_error_syntax(s);
5280         }
5281         INT_ON;
5282
5283         return result;
5284 }
5285 #endif
5286
5287 /*
5288  * expandarg flags
5289  */
5290 #define EXP_FULL        0x1     /* perform word splitting & file globbing */
5291 #define EXP_TILDE       0x2     /* do normal tilde expansion */
5292 #define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
5293 #define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
5294 #define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
5295 #define EXP_RECORD      0x20    /* need to record arguments for ifs breakup */
5296 #define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
5297 #define EXP_WORD        0x80    /* expand word in parameter expansion */
5298 #define EXP_QWORD       0x100   /* expand word in quoted parameter expansion */
5299 /*
5300  * _rmescape() flags
5301  */
5302 #define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
5303 #define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
5304 #define RMESCAPE_QUOTED 0x4     /* Remove CTLESC unless in quotes */
5305 #define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
5306 #define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
5307
5308 /*
5309  * Structure specifying which parts of the string should be searched
5310  * for IFS characters.
5311  */
5312 struct ifsregion {
5313         struct ifsregion *next; /* next region in list */
5314         int begoff;             /* offset of start of region */
5315         int endoff;             /* offset of end of region */
5316         int nulonly;            /* search for nul bytes only */
5317 };
5318
5319 struct arglist {
5320         struct strlist *list;
5321         struct strlist **lastp;
5322 };
5323
5324 /* output of current string */
5325 static char *expdest;
5326 /* list of back quote expressions */
5327 static struct nodelist *argbackq;
5328 /* first struct in list of ifs regions */
5329 static struct ifsregion ifsfirst;
5330 /* last struct in list */
5331 static struct ifsregion *ifslastp;
5332 /* holds expanded arg list */
5333 static struct arglist exparg;
5334
5335 /*
5336  * Our own itoa().
5337  */
5338 static int
5339 cvtnum(arith_t num)
5340 {
5341         int len;
5342
5343         expdest = makestrspace(32, expdest);
5344         len = fmtstr(expdest, 32, arith_t_fmt, num);
5345         STADJUST(len, expdest);
5346         return len;
5347 }
5348
5349 static size_t
5350 esclen(const char *start, const char *p)
5351 {
5352         size_t esc = 0;
5353
5354         while (p > start && *--p == CTLESC) {
5355                 esc++;
5356         }
5357         return esc;
5358 }
5359
5360 /*
5361  * Remove any CTLESC characters from a string.
5362  */
5363 static char *
5364 _rmescapes(char *str, int flag)
5365 {
5366         static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5367
5368         char *p, *q, *r;
5369         unsigned inquotes;
5370         int notescaped;
5371         int globbing;
5372
5373         p = strpbrk(str, qchars);
5374         if (!p) {
5375                 return str;
5376         }
5377         q = p;
5378         r = str;
5379         if (flag & RMESCAPE_ALLOC) {
5380                 size_t len = p - str;
5381                 size_t fulllen = len + strlen(p) + 1;
5382
5383                 if (flag & RMESCAPE_GROW) {
5384                         r = makestrspace(fulllen, expdest);
5385                 } else if (flag & RMESCAPE_HEAP) {
5386                         r = ckmalloc(fulllen);
5387                 } else {
5388                         r = stalloc(fulllen);
5389                 }
5390                 q = r;
5391                 if (len > 0) {
5392                         q = (char *)memcpy(q, str, len) + len;
5393                 }
5394         }
5395         inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5396         globbing = flag & RMESCAPE_GLOB;
5397         notescaped = globbing;
5398         while (*p) {
5399                 if (*p == CTLQUOTEMARK) {
5400                         inquotes = ~inquotes;
5401                         p++;
5402                         notescaped = globbing;
5403                         continue;
5404                 }
5405                 if (*p == '\\') {
5406                         /* naked back slash */
5407                         notescaped = 0;
5408                         goto copy;
5409                 }
5410                 if (*p == CTLESC) {
5411                         p++;
5412                         if (notescaped && inquotes && *p != '/') {
5413                                 *q++ = '\\';
5414                         }
5415                 }
5416                 notescaped = globbing;
5417  copy:
5418                 *q++ = *p++;
5419         }
5420         *q = '\0';
5421         if (flag & RMESCAPE_GROW) {
5422                 expdest = r;
5423                 STADJUST(q - r + 1, expdest);
5424         }
5425         return r;
5426 }
5427 #define rmescapes(p) _rmescapes((p), 0)
5428
5429 #define pmatch(a, b) !fnmatch((a), (b), 0)
5430
5431 /*
5432  * Prepare a pattern for a expmeta (internal glob(3)) call.
5433  *
5434  * Returns an stalloced string.
5435  */
5436 static char *
5437 preglob(const char *pattern, int quoted, int flag)
5438 {
5439         flag |= RMESCAPE_GLOB;
5440         if (quoted) {
5441                 flag |= RMESCAPE_QUOTED;
5442         }
5443         return _rmescapes((char *)pattern, flag);
5444 }
5445
5446 /*
5447  * Put a string on the stack.
5448  */
5449 static void
5450 memtodest(const char *p, size_t len, int syntax, int quotes)
5451 {
5452         char *q = expdest;
5453
5454         q = makestrspace(len * 2, q);
5455
5456         while (len--) {
5457                 int c = signed_char2int(*p++);
5458                 if (!c)
5459                         continue;
5460                 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5461                         USTPUTC(CTLESC, q);
5462                 USTPUTC(c, q);
5463         }
5464
5465         expdest = q;
5466 }
5467
5468 static void
5469 strtodest(const char *p, int syntax, int quotes)
5470 {
5471         memtodest(p, strlen(p), syntax, quotes);
5472 }
5473
5474 /*
5475  * Record the fact that we have to scan this region of the
5476  * string for IFS characters.
5477  */
5478 static void
5479 recordregion(int start, int end, int nulonly)
5480 {
5481         struct ifsregion *ifsp;
5482
5483         if (ifslastp == NULL) {
5484                 ifsp = &ifsfirst;
5485         } else {
5486                 INT_OFF;
5487                 ifsp = ckzalloc(sizeof(*ifsp));
5488                 /*ifsp->next = NULL; - ckzalloc did it */
5489                 ifslastp->next = ifsp;
5490                 INT_ON;
5491         }
5492         ifslastp = ifsp;
5493         ifslastp->begoff = start;
5494         ifslastp->endoff = end;
5495         ifslastp->nulonly = nulonly;
5496 }
5497
5498 static void
5499 removerecordregions(int endoff)
5500 {
5501         if (ifslastp == NULL)
5502                 return;
5503
5504         if (ifsfirst.endoff > endoff) {
5505                 while (ifsfirst.next != NULL) {
5506                         struct ifsregion *ifsp;
5507                         INT_OFF;
5508                         ifsp = ifsfirst.next->next;
5509                         free(ifsfirst.next);
5510                         ifsfirst.next = ifsp;
5511                         INT_ON;
5512                 }
5513                 if (ifsfirst.begoff > endoff)
5514                         ifslastp = NULL;
5515                 else {
5516                         ifslastp = &ifsfirst;
5517                         ifsfirst.endoff = endoff;
5518                 }
5519                 return;
5520         }
5521
5522         ifslastp = &ifsfirst;
5523         while (ifslastp->next && ifslastp->next->begoff < endoff)
5524                 ifslastp=ifslastp->next;
5525         while (ifslastp->next != NULL) {
5526                 struct ifsregion *ifsp;
5527                 INT_OFF;
5528                 ifsp = ifslastp->next->next;
5529                 free(ifslastp->next);
5530                 ifslastp->next = ifsp;
5531                 INT_ON;
5532         }
5533         if (ifslastp->endoff > endoff)
5534                 ifslastp->endoff = endoff;
5535 }
5536
5537 static char *
5538 exptilde(char *startp, char *p, int flag)
5539 {
5540         char c;
5541         char *name;
5542         struct passwd *pw;
5543         const char *home;
5544         int quotes = flag & (EXP_FULL | EXP_CASE);
5545         int startloc;
5546
5547         name = p + 1;
5548
5549         while ((c = *++p) != '\0') {
5550                 switch (c) {
5551                 case CTLESC:
5552                         return startp;
5553                 case CTLQUOTEMARK:
5554                         return startp;
5555                 case ':':
5556                         if (flag & EXP_VARTILDE)
5557                                 goto done;
5558                         break;
5559                 case '/':
5560                 case CTLENDVAR:
5561                         goto done;
5562                 }
5563         }
5564  done:
5565         *p = '\0';
5566         if (*name == '\0') {
5567                 home = lookupvar(homestr);
5568         } else {
5569                 pw = getpwnam(name);
5570                 if (pw == NULL)
5571                         goto lose;
5572                 home = pw->pw_dir;
5573         }
5574         if (!home || !*home)
5575                 goto lose;
5576         *p = c;
5577         startloc = expdest - (char *)stackblock();
5578         strtodest(home, SQSYNTAX, quotes);
5579         recordregion(startloc, expdest - (char *)stackblock(), 0);
5580         return p;
5581  lose:
5582         *p = c;
5583         return startp;
5584 }
5585
5586 /*
5587  * Execute a command inside back quotes.  If it's a builtin command, we
5588  * want to save its output in a block obtained from malloc.  Otherwise
5589  * we fork off a subprocess and get the output of the command via a pipe.
5590  * Should be called with interrupts off.
5591  */
5592 struct backcmd {                /* result of evalbackcmd */
5593         int fd;                 /* file descriptor to read from */
5594         int nleft;              /* number of chars in buffer */
5595         char *buf;              /* buffer */
5596         struct job *jp;         /* job structure for command */
5597 };
5598
5599 /* These forward decls are needed to use "eval" code for backticks handling: */
5600 static uint8_t back_exitstatus; /* exit status of backquoted command */
5601 #define EV_EXIT 01              /* exit after evaluating tree */
5602 static void evaltree(union node *, int);
5603
5604 static void FAST_FUNC
5605 evalbackcmd(union node *n, struct backcmd *result)
5606 {
5607         int saveherefd;
5608
5609         result->fd = -1;
5610         result->buf = NULL;
5611         result->nleft = 0;
5612         result->jp = NULL;
5613         if (n == NULL)
5614                 goto out;
5615
5616         saveherefd = herefd;
5617         herefd = -1;
5618
5619         {
5620                 int pip[2];
5621                 struct job *jp;
5622
5623                 if (pipe(pip) < 0)
5624                         ash_msg_and_raise_error("pipe call failed");
5625                 jp = makejob(/*n,*/ 1);
5626                 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5627                         FORCE_INT_ON;
5628                         close(pip[0]);
5629                         if (pip[1] != 1) {
5630                                 /*close(1);*/
5631                                 copyfd(pip[1], 1 | COPYFD_EXACT);
5632                                 close(pip[1]);
5633                         }
5634                         eflag = 0;
5635                         evaltree(n, EV_EXIT); /* actually evaltreenr... */
5636                         /* NOTREACHED */
5637                 }
5638                 close(pip[1]);
5639                 result->fd = pip[0];
5640                 result->jp = jp;
5641         }
5642         herefd = saveherefd;
5643  out:
5644         TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5645                 result->fd, result->buf, result->nleft, result->jp));
5646 }
5647
5648 /*
5649  * Expand stuff in backwards quotes.
5650  */
5651 static void
5652 expbackq(union node *cmd, int quoted, int quotes)
5653 {
5654         struct backcmd in;
5655         int i;
5656         char buf[128];
5657         char *p;
5658         char *dest;
5659         int startloc;
5660         int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5661         struct stackmark smark;
5662
5663         INT_OFF;
5664         setstackmark(&smark);
5665         dest = expdest;
5666         startloc = dest - (char *)stackblock();
5667         grabstackstr(dest);
5668         evalbackcmd(cmd, &in);
5669         popstackmark(&smark);
5670
5671         p = in.buf;
5672         i = in.nleft;
5673         if (i == 0)
5674                 goto read;
5675         for (;;) {
5676                 memtodest(p, i, syntax, quotes);
5677  read:
5678                 if (in.fd < 0)
5679                         break;
5680                 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5681                 TRACE(("expbackq: read returns %d\n", i));
5682                 if (i <= 0)
5683                         break;
5684                 p = buf;
5685         }
5686
5687         free(in.buf);
5688         if (in.fd >= 0) {
5689                 close(in.fd);
5690                 back_exitstatus = waitforjob(in.jp);
5691         }
5692         INT_ON;
5693
5694         /* Eat all trailing newlines */
5695         dest = expdest;
5696         for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5697                 STUNPUTC(dest);
5698         expdest = dest;
5699
5700         if (quoted == 0)
5701                 recordregion(startloc, dest - (char *)stackblock(), 0);
5702         TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5703                 (dest - (char *)stackblock()) - startloc,
5704                 (dest - (char *)stackblock()) - startloc,
5705                 stackblock() + startloc));
5706 }
5707
5708 #if ENABLE_SH_MATH_SUPPORT
5709 /*
5710  * Expand arithmetic expression.  Backup to start of expression,
5711  * evaluate, place result in (backed up) result, adjust string position.
5712  */
5713 static void
5714 expari(int quotes)
5715 {
5716         char *p, *start;
5717         int begoff;
5718         int flag;
5719         int len;
5720
5721         /* ifsfree(); */
5722
5723         /*
5724          * This routine is slightly over-complicated for
5725          * efficiency.  Next we scan backwards looking for the
5726          * start of arithmetic.
5727          */
5728         start = stackblock();
5729         p = expdest - 1;
5730         *p = '\0';
5731         p--;
5732         do {
5733                 int esc;
5734
5735                 while (*p != CTLARI) {
5736                         p--;
5737 #if DEBUG
5738                         if (p < start) {
5739                                 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5740                         }
5741 #endif
5742                 }
5743
5744                 esc = esclen(start, p);
5745                 if (!(esc % 2)) {
5746                         break;
5747                 }
5748
5749                 p -= esc + 1;
5750         } while (1);
5751
5752         begoff = p - start;
5753
5754         removerecordregions(begoff);
5755
5756         flag = p[1];
5757
5758         expdest = p;
5759
5760         if (quotes)
5761                 rmescapes(p + 2);
5762
5763         len = cvtnum(ash_arith(p + 2));
5764
5765         if (flag != '"')
5766                 recordregion(begoff, begoff + len, 0);
5767 }
5768 #endif
5769
5770 /* argstr needs it */
5771 static char *evalvar(char *p, int flag, struct strlist *var_str_list);
5772
5773 /*
5774  * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
5775  * characters to allow for further processing.  Otherwise treat
5776  * $@ like $* since no splitting will be performed.
5777  *
5778  * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5779  * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5780  * for correct expansion of "B=$A" word.
5781  */
5782 static void
5783 argstr(char *p, int flag, struct strlist *var_str_list)
5784 {
5785         static const char spclchars[] ALIGN1 = {
5786                 '=',
5787                 ':',
5788                 CTLQUOTEMARK,
5789                 CTLENDVAR,
5790                 CTLESC,
5791                 CTLVAR,
5792                 CTLBACKQ,
5793                 CTLBACKQ | CTLQUOTE,
5794 #if ENABLE_SH_MATH_SUPPORT
5795                 CTLENDARI,
5796 #endif
5797                 0
5798         };
5799         const char *reject = spclchars;
5800         int c;
5801         int quotes = flag & (EXP_FULL | EXP_CASE);      /* do CTLESC */
5802         int breakall = flag & EXP_WORD;
5803         int inquotes;
5804         size_t length;
5805         int startloc;
5806
5807         if (!(flag & EXP_VARTILDE)) {
5808                 reject += 2;
5809         } else if (flag & EXP_VARTILDE2) {
5810                 reject++;
5811         }
5812         inquotes = 0;
5813         length = 0;
5814         if (flag & EXP_TILDE) {
5815                 char *q;
5816
5817                 flag &= ~EXP_TILDE;
5818  tilde:
5819                 q = p;
5820                 if (*q == CTLESC && (flag & EXP_QWORD))
5821                         q++;
5822                 if (*q == '~')
5823                         p = exptilde(p, q, flag);
5824         }
5825  start:
5826         startloc = expdest - (char *)stackblock();
5827         for (;;) {
5828                 length += strcspn(p + length, reject);
5829                 c = p[length];
5830                 if (c && (!(c & 0x80)
5831 #if ENABLE_SH_MATH_SUPPORT
5832                                         || c == CTLENDARI
5833 #endif
5834                    )) {
5835                         /* c == '=' || c == ':' || c == CTLENDARI */
5836                         length++;
5837                 }
5838                 if (length > 0) {
5839                         int newloc;
5840                         expdest = stack_nputstr(p, length, expdest);
5841                         newloc = expdest - (char *)stackblock();
5842                         if (breakall && !inquotes && newloc > startloc) {
5843                                 recordregion(startloc, newloc, 0);
5844                         }
5845                         startloc = newloc;
5846                 }
5847                 p += length + 1;
5848                 length = 0;
5849
5850                 switch (c) {
5851                 case '\0':
5852                         goto breakloop;
5853                 case '=':
5854                         if (flag & EXP_VARTILDE2) {
5855                                 p--;
5856                                 continue;
5857                         }
5858                         flag |= EXP_VARTILDE2;
5859                         reject++;
5860                         /* fall through */
5861                 case ':':
5862                         /*
5863                          * sort of a hack - expand tildes in variable
5864                          * assignments (after the first '=' and after ':'s).
5865                          */
5866                         if (*--p == '~') {
5867                                 goto tilde;
5868                         }
5869                         continue;
5870                 }
5871
5872                 switch (c) {
5873                 case CTLENDVAR: /* ??? */
5874                         goto breakloop;
5875                 case CTLQUOTEMARK:
5876                         /* "$@" syntax adherence hack */
5877                         if (
5878                                 !inquotes &&
5879                                 !memcmp(p, dolatstr, 4) &&
5880                                 (p[4] == CTLQUOTEMARK || (
5881                                         p[4] == CTLENDVAR &&
5882                                         p[5] == CTLQUOTEMARK
5883                                 ))
5884                         ) {
5885                                 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
5886                                 goto start;
5887                         }
5888                         inquotes = !inquotes;
5889  addquote:
5890                         if (quotes) {
5891                                 p--;
5892                                 length++;
5893                                 startloc++;
5894                         }
5895                         break;
5896                 case CTLESC:
5897                         startloc++;
5898                         length++;
5899                         goto addquote;
5900                 case CTLVAR:
5901                         p = evalvar(p, flag, var_str_list);
5902                         goto start;
5903                 case CTLBACKQ:
5904                         c = 0;
5905                 case CTLBACKQ|CTLQUOTE:
5906                         expbackq(argbackq->n, c, quotes);
5907                         argbackq = argbackq->next;
5908                         goto start;
5909 #if ENABLE_SH_MATH_SUPPORT
5910                 case CTLENDARI:
5911                         p--;
5912                         expari(quotes);
5913                         goto start;
5914 #endif
5915                 }
5916         }
5917  breakloop:
5918         ;
5919 }
5920
5921 static char *
5922 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5923         int zero)
5924 {
5925 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5926 // as part of a larger change when he added support for ${var/a/b}.
5927 // However, it broke # and % operators:
5928 //
5929 //var=ababcdcd
5930 //                 ok       bad
5931 //echo ${var#ab}   abcdcd   abcdcd
5932 //echo ${var##ab}  abcdcd   abcdcd
5933 //echo ${var#a*b}  abcdcd   ababcdcd  (!)
5934 //echo ${var##a*b} cdcd     cdcd
5935 //echo ${var#?}    babcdcd  ababcdcd  (!)
5936 //echo ${var##?}   babcdcd  babcdcd
5937 //echo ${var#*}    ababcdcd babcdcd   (!)
5938 //echo ${var##*}
5939 //echo ${var%cd}   ababcd   ababcd
5940 //echo ${var%%cd}  ababcd   abab      (!)
5941 //echo ${var%c*d}  ababcd   ababcd
5942 //echo ${var%%c*d} abab     ababcdcd  (!)
5943 //echo ${var%?}    ababcdc  ababcdc
5944 //echo ${var%%?}   ababcdc  ababcdcd  (!)
5945 //echo ${var%*}    ababcdcd ababcdcd
5946 //echo ${var%%*}
5947 //
5948 // Commenting it back out helped. Remove it completely if it really
5949 // is not needed.
5950
5951         char *loc, *loc2; //, *full;
5952         char c;
5953
5954         loc = startp;
5955         loc2 = rmesc;
5956         do {
5957                 int match; // = strlen(str);
5958                 const char *s = loc2;
5959
5960                 c = *loc2;
5961                 if (zero) {
5962                         *loc2 = '\0';
5963                         s = rmesc;
5964                 }
5965                 match = pmatch(str, s); // this line was deleted
5966
5967 //              // chop off end if its '*'
5968 //              full = strrchr(str, '*');
5969 //              if (full && full != str)
5970 //                      match--;
5971 //
5972 //              // If str starts with '*' replace with s.
5973 //              if ((*str == '*') && strlen(s) >= match) {
5974 //                      full = xstrdup(s);
5975 //                      strncpy(full+strlen(s)-match+1, str+1, match-1);
5976 //              } else
5977 //                      full = xstrndup(str, match);
5978 //              match = strncmp(s, full, strlen(full));
5979 //              free(full);
5980 //
5981                 *loc2 = c;
5982                 if (match) // if (!match)
5983                         return loc;
5984                 if (quotes && *loc == CTLESC)
5985                         loc++;
5986                 loc++;
5987                 loc2++;
5988         } while (c);
5989         return 0;
5990 }
5991
5992 static char *
5993 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5994         int zero)
5995 {
5996         int esc = 0;
5997         char *loc;
5998         char *loc2;
5999
6000         for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6001                 int match;
6002                 char c = *loc2;
6003                 const char *s = loc2;
6004                 if (zero) {
6005                         *loc2 = '\0';
6006                         s = rmesc;
6007                 }
6008                 match = pmatch(str, s);
6009                 *loc2 = c;
6010                 if (match)
6011                         return loc;
6012                 loc--;
6013                 if (quotes) {
6014                         if (--esc < 0) {
6015                                 esc = esclen(startp, loc);
6016                         }
6017                         if (esc % 2) {
6018                                 esc--;
6019                                 loc--;
6020                         }
6021                 }
6022         }
6023         return 0;
6024 }
6025
6026 static void varunset(const char *, const char *, const char *, int) NORETURN;
6027 static void
6028 varunset(const char *end, const char *var, const char *umsg, int varflags)
6029 {
6030         const char *msg;
6031         const char *tail;
6032
6033         tail = nullstr;
6034         msg = "parameter not set";
6035         if (umsg) {
6036                 if (*end == CTLENDVAR) {
6037                         if (varflags & VSNUL)
6038                                 tail = " or null";
6039                 } else {
6040                         msg = umsg;
6041                 }
6042         }
6043         ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6044 }
6045
6046 #if ENABLE_ASH_BASH_COMPAT
6047 static char *
6048 parse_sub_pattern(char *arg, int inquotes)
6049 {
6050         char *idx, *repl = NULL;
6051         unsigned char c;
6052
6053         idx = arg;
6054         while (1) {
6055                 c = *arg;
6056                 if (!c)
6057                         break;
6058                 if (c == '/') {
6059                         /* Only the first '/' seen is our separator */
6060                         if (!repl) {
6061                                 repl = idx + 1;
6062                                 c = '\0';
6063                         }
6064                 }
6065                 *idx++ = c;
6066                 if (!inquotes && c == '\\' && arg[1] == '\\')
6067                         arg++; /* skip both \\, not just first one */
6068                 arg++;
6069         }
6070         *idx = c; /* NUL */
6071
6072         return repl;
6073 }
6074 #endif /* ENABLE_ASH_BASH_COMPAT */
6075
6076 static const char *
6077 subevalvar(char *p, char *str, int strloc, int subtype,
6078                 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6079 {
6080         struct nodelist *saveargbackq = argbackq;
6081         char *startp;
6082         char *loc;
6083         char *rmesc, *rmescend;
6084         IF_ASH_BASH_COMPAT(char *repl = NULL;)
6085         IF_ASH_BASH_COMPAT(char null = '\0';)
6086         IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6087         int saveherefd = herefd;
6088         int amount, workloc, resetloc;
6089         int zero;
6090         char *(*scan)(char*, char*, char*, char*, int, int);
6091
6092         herefd = -1;
6093         argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6094                         var_str_list);
6095         STPUTC('\0', expdest);
6096         herefd = saveherefd;
6097         argbackq = saveargbackq;
6098         startp = (char *)stackblock() + startloc;
6099
6100         switch (subtype) {
6101         case VSASSIGN:
6102                 setvar(str, startp, 0);
6103                 amount = startp - expdest;
6104                 STADJUST(amount, expdest);
6105                 return startp;
6106
6107 #if ENABLE_ASH_BASH_COMPAT
6108         case VSSUBSTR:
6109                 loc = str = stackblock() + strloc;
6110 // TODO: number() instead? It does error checking...
6111                 pos = atoi(loc);
6112                 len = str - startp - 1;
6113
6114                 /* *loc != '\0', guaranteed by parser */
6115                 if (quotes) {
6116                         char *ptr;
6117
6118                         /* We must adjust the length by the number of escapes we find. */
6119                         for (ptr = startp; ptr < (str - 1); ptr++) {
6120                                 if (*ptr == CTLESC) {
6121                                         len--;
6122                                         ptr++;
6123                                 }
6124                         }
6125                 }
6126                 orig_len = len;
6127
6128                 if (*loc++ == ':') {
6129 // TODO: number() instead? It does error checking...
6130                         len = atoi(loc);
6131                 } else {
6132                         len = orig_len;
6133                         while (*loc && *loc != ':')
6134                                 loc++;
6135                         if (*loc++ == ':')
6136 // TODO: number() instead? It does error checking...
6137                                 len = atoi(loc);
6138                 }
6139                 if (pos >= orig_len) {
6140                         pos = 0;
6141                         len = 0;
6142                 }
6143                 if (len > (orig_len - pos))
6144                         len = orig_len - pos;
6145
6146                 for (str = startp; pos; str++, pos--) {
6147                         if (quotes && *str == CTLESC)
6148                                 str++;
6149                 }
6150                 for (loc = startp; len; len--) {
6151                         if (quotes && *str == CTLESC)
6152                                 *loc++ = *str++;
6153                         *loc++ = *str++;
6154                 }
6155                 *loc = '\0';
6156                 amount = loc - expdest;
6157                 STADJUST(amount, expdest);
6158                 return loc;
6159 #endif
6160
6161         case VSQUESTION:
6162                 varunset(p, str, startp, varflags);
6163                 /* NOTREACHED */
6164         }
6165         resetloc = expdest - (char *)stackblock();
6166
6167         /* We'll comeback here if we grow the stack while handling
6168          * a VSREPLACE or VSREPLACEALL, since our pointers into the
6169          * stack will need rebasing, and we'll need to remove our work
6170          * areas each time
6171          */
6172  IF_ASH_BASH_COMPAT(restart:)
6173
6174         amount = expdest - ((char *)stackblock() + resetloc);
6175         STADJUST(-amount, expdest);
6176         startp = (char *)stackblock() + startloc;
6177
6178         rmesc = startp;
6179         rmescend = (char *)stackblock() + strloc;
6180         if (quotes) {
6181                 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6182                 if (rmesc != startp) {
6183                         rmescend = expdest;
6184                         startp = (char *)stackblock() + startloc;
6185                 }
6186         }
6187         rmescend--;
6188         str = (char *)stackblock() + strloc;
6189         preglob(str, varflags & VSQUOTE, 0);
6190         workloc = expdest - (char *)stackblock();
6191
6192 #if ENABLE_ASH_BASH_COMPAT
6193         if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6194                 char *idx, *end, *restart_detect;
6195
6196                 if (!repl) {
6197                         repl = parse_sub_pattern(str, varflags & VSQUOTE);
6198                         if (!repl)
6199                                 repl = &null;
6200                 }
6201
6202                 /* If there's no pattern to match, return the expansion unmolested */
6203                 if (*str == '\0')
6204                         return 0;
6205
6206                 len = 0;
6207                 idx = startp;
6208                 end = str - 1;
6209                 while (idx < end) {
6210                         loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6211                         if (!loc) {
6212                                 /* No match, advance */
6213                                 restart_detect = stackblock();
6214                                 STPUTC(*idx, expdest);
6215                                 if (quotes && *idx == CTLESC) {
6216                                         idx++;
6217                                         len++;
6218                                         STPUTC(*idx, expdest);
6219                                 }
6220                                 if (stackblock() != restart_detect)
6221                                         goto restart;
6222                                 idx++;
6223                                 len++;
6224                                 rmesc++;
6225                                 continue;
6226                         }
6227
6228                         if (subtype == VSREPLACEALL) {
6229                                 while (idx < loc) {
6230                                         if (quotes && *idx == CTLESC)
6231                                                 idx++;
6232                                         idx++;
6233                                         rmesc++;
6234                                 }
6235                         } else {
6236                                 idx = loc;
6237                         }
6238
6239                         for (loc = repl; *loc; loc++) {
6240                                 restart_detect = stackblock();
6241                                 STPUTC(*loc, expdest);
6242                                 if (stackblock() != restart_detect)
6243                                         goto restart;
6244                                 len++;
6245                         }
6246
6247                         if (subtype == VSREPLACE) {
6248                                 while (*idx) {
6249                                         restart_detect = stackblock();
6250                                         STPUTC(*idx, expdest);
6251                                         if (stackblock() != restart_detect)
6252                                                 goto restart;
6253                                         len++;
6254                                         idx++;
6255                                 }
6256                                 break;
6257                         }
6258                 }
6259
6260                 /* We've put the replaced text into a buffer at workloc, now
6261                  * move it to the right place and adjust the stack.
6262                  */
6263                 startp = stackblock() + startloc;
6264                 STPUTC('\0', expdest);
6265                 memmove(startp, stackblock() + workloc, len);
6266                 startp[len++] = '\0';
6267                 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6268                 STADJUST(-amount, expdest);
6269                 return startp;
6270         }
6271 #endif /* ENABLE_ASH_BASH_COMPAT */
6272
6273         subtype -= VSTRIMRIGHT;
6274 #if DEBUG
6275         if (subtype < 0 || subtype > 7)
6276                 abort();
6277 #endif
6278         /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6279         zero = subtype >> 1;
6280         /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6281         scan = (subtype & 1) ^ zero ? scanleft : scanright;
6282
6283         loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6284         if (loc) {
6285                 if (zero) {
6286                         memmove(startp, loc, str - loc);
6287                         loc = startp + (str - loc) - 1;
6288                 }
6289                 *loc = '\0';
6290                 amount = loc - expdest;
6291                 STADJUST(amount, expdest);
6292         }
6293         return loc;
6294 }
6295
6296 /*
6297  * Add the value of a specialized variable to the stack string.
6298  */
6299 static ssize_t
6300 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6301 {
6302         int num;
6303         const char *p;
6304         int i;
6305         int sep = 0;
6306         int sepq = 0;
6307         ssize_t len = 0;
6308         char **ap;
6309         int syntax;
6310         int quoted = varflags & VSQUOTE;
6311         int subtype = varflags & VSTYPE;
6312         int quotes = flags & (EXP_FULL | EXP_CASE);
6313
6314         if (quoted && (flags & EXP_FULL))
6315                 sep = 1 << CHAR_BIT;
6316
6317         syntax = quoted ? DQSYNTAX : BASESYNTAX;
6318         switch (*name) {
6319         case '$':
6320                 num = rootpid;
6321                 goto numvar;
6322         case '?':
6323                 num = exitstatus;
6324                 goto numvar;
6325         case '#':
6326                 num = shellparam.nparam;
6327                 goto numvar;
6328         case '!':
6329                 num = backgndpid;
6330                 if (num == 0)
6331                         return -1;
6332  numvar:
6333                 len = cvtnum(num);
6334                 break;
6335         case '-':
6336                 expdest = makestrspace(NOPTS, expdest);
6337                 for (i = NOPTS - 1; i >= 0; i--) {
6338                         if (optlist[i]) {
6339                                 USTPUTC(optletters(i), expdest);
6340                                 len++;
6341                         }
6342                 }
6343                 break;
6344         case '@':
6345                 if (sep)
6346                         goto param;
6347                 /* fall through */
6348         case '*':
6349                 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6350                 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6351                         sepq = 1;
6352  param:
6353                 ap = shellparam.p;
6354                 if (!ap)
6355                         return -1;
6356                 while ((p = *ap++)) {
6357                         size_t partlen;
6358
6359                         partlen = strlen(p);
6360                         len += partlen;
6361
6362                         if (!(subtype == VSPLUS || subtype == VSLENGTH))
6363                                 memtodest(p, partlen, syntax, quotes);
6364
6365                         if (*ap && sep) {
6366                                 char *q;
6367
6368                                 len++;
6369                                 if (subtype == VSPLUS || subtype == VSLENGTH) {
6370                                         continue;
6371                                 }
6372                                 q = expdest;
6373                                 if (sepq)
6374                                         STPUTC(CTLESC, q);
6375                                 STPUTC(sep, q);
6376                                 expdest = q;
6377                         }
6378                 }
6379                 return len;
6380         case '0':
6381         case '1':
6382         case '2':
6383         case '3':
6384         case '4':
6385         case '5':
6386         case '6':
6387         case '7':
6388         case '8':
6389         case '9':
6390 // TODO: number() instead? It does error checking...
6391                 num = atoi(name);
6392                 if (num < 0 || num > shellparam.nparam)
6393                         return -1;
6394                 p = num ? shellparam.p[num - 1] : arg0;
6395                 goto value;
6396         default:
6397                 /* NB: name has form "VAR=..." */
6398
6399                 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6400                  * which should be considered before we check variables. */
6401                 if (var_str_list) {
6402                         unsigned name_len = (strchrnul(name, '=') - name) + 1;
6403                         p = NULL;
6404                         do {
6405                                 char *str, *eq;
6406                                 str = var_str_list->text;
6407                                 eq = strchr(str, '=');
6408                                 if (!eq) /* stop at first non-assignment */
6409                                         break;
6410                                 eq++;
6411                                 if (name_len == (unsigned)(eq - str)
6412                                  && strncmp(str, name, name_len) == 0) {
6413                                         p = eq;
6414                                         /* goto value; - WRONG! */
6415                                         /* think "A=1 A=2 B=$A" */
6416                                 }
6417                                 var_str_list = var_str_list->next;
6418                         } while (var_str_list);
6419                         if (p)
6420                                 goto value;
6421                 }
6422                 p = lookupvar(name);
6423  value:
6424                 if (!p)
6425                         return -1;
6426
6427                 len = strlen(p);
6428                 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6429                         memtodest(p, len, syntax, quotes);
6430                 return len;
6431         }
6432
6433         if (subtype == VSPLUS || subtype == VSLENGTH)
6434                 STADJUST(-len, expdest);
6435         return len;
6436 }
6437
6438 /*
6439  * Expand a variable, and return a pointer to the next character in the
6440  * input string.
6441  */
6442 static char *
6443 evalvar(char *p, int flag, struct strlist *var_str_list)
6444 {
6445         char varflags;
6446         char subtype;
6447         char quoted;
6448         char easy;
6449         char *var;
6450         int patloc;
6451         int startloc;
6452         ssize_t varlen;
6453
6454         varflags = *p++;
6455         subtype = varflags & VSTYPE;
6456         quoted = varflags & VSQUOTE;
6457         var = p;
6458         easy = (!quoted || (*var == '@' && shellparam.nparam));
6459         startloc = expdest - (char *)stackblock();
6460         p = strchr(p, '=') + 1;
6461
6462  again:
6463         varlen = varvalue(var, varflags, flag, var_str_list);
6464         if (varflags & VSNUL)
6465                 varlen--;
6466
6467         if (subtype == VSPLUS) {
6468                 varlen = -1 - varlen;
6469                 goto vsplus;
6470         }
6471
6472         if (subtype == VSMINUS) {
6473  vsplus:
6474                 if (varlen < 0) {
6475                         argstr(
6476                                 p, flag | EXP_TILDE |
6477                                         (quoted ?  EXP_QWORD : EXP_WORD),
6478                                 var_str_list
6479                         );
6480                         goto end;
6481                 }
6482                 if (easy)
6483                         goto record;
6484                 goto end;
6485         }
6486
6487         if (subtype == VSASSIGN || subtype == VSQUESTION) {
6488                 if (varlen < 0) {
6489                         if (subevalvar(p, var, /* strloc: */ 0,
6490                                         subtype, startloc, varflags,
6491                                         /* quotes: */ 0,
6492                                         var_str_list)
6493                         ) {
6494                                 varflags &= ~VSNUL;
6495                                 /*
6496                                  * Remove any recorded regions beyond
6497                                  * start of variable
6498                                  */
6499                                 removerecordregions(startloc);
6500                                 goto again;
6501                         }
6502                         goto end;
6503                 }
6504                 if (easy)
6505                         goto record;
6506                 goto end;
6507         }
6508
6509         if (varlen < 0 && uflag)
6510                 varunset(p, var, 0, 0);
6511
6512         if (subtype == VSLENGTH) {
6513                 cvtnum(varlen > 0 ? varlen : 0);
6514                 goto record;
6515         }
6516
6517         if (subtype == VSNORMAL) {
6518                 if (easy)
6519                         goto record;
6520                 goto end;
6521         }
6522
6523 #if DEBUG
6524         switch (subtype) {
6525         case VSTRIMLEFT:
6526         case VSTRIMLEFTMAX:
6527         case VSTRIMRIGHT:
6528         case VSTRIMRIGHTMAX:
6529 #if ENABLE_ASH_BASH_COMPAT
6530         case VSSUBSTR:
6531         case VSREPLACE:
6532         case VSREPLACEALL:
6533 #endif
6534                 break;
6535         default:
6536                 abort();
6537         }
6538 #endif
6539
6540         if (varlen >= 0) {
6541                 /*
6542                  * Terminate the string and start recording the pattern
6543                  * right after it
6544                  */
6545                 STPUTC('\0', expdest);
6546                 patloc = expdest - (char *)stackblock();
6547                 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6548                                 startloc, varflags,
6549                                 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6550                                 var_str_list)
6551                 ) {
6552                         int amount = expdest - (
6553                                 (char *)stackblock() + patloc - 1
6554                         );
6555                         STADJUST(-amount, expdest);
6556                 }
6557                 /* Remove any recorded regions beyond start of variable */
6558                 removerecordregions(startloc);
6559  record:
6560                 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6561         }
6562
6563  end:
6564         if (subtype != VSNORMAL) {      /* skip to end of alternative */
6565                 int nesting = 1;
6566                 for (;;) {
6567                         char c = *p++;
6568                         if (c == CTLESC)
6569                                 p++;
6570                         else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6571                                 if (varlen >= 0)
6572                                         argbackq = argbackq->next;
6573                         } else if (c == CTLVAR) {
6574                                 if ((*p++ & VSTYPE) != VSNORMAL)
6575                                         nesting++;
6576                         } else if (c == CTLENDVAR) {
6577                                 if (--nesting == 0)
6578                                         break;
6579                         }
6580                 }
6581         }
6582         return p;
6583 }
6584
6585 /*
6586  * Break the argument string into pieces based upon IFS and add the
6587  * strings to the argument list.  The regions of the string to be
6588  * searched for IFS characters have been stored by recordregion.
6589  */
6590 static void
6591 ifsbreakup(char *string, struct arglist *arglist)
6592 {
6593         struct ifsregion *ifsp;
6594         struct strlist *sp;
6595         char *start;
6596         char *p;
6597         char *q;
6598         const char *ifs, *realifs;
6599         int ifsspc;
6600         int nulonly;
6601
6602         start = string;
6603         if (ifslastp != NULL) {
6604                 ifsspc = 0;
6605                 nulonly = 0;
6606                 realifs = ifsset() ? ifsval() : defifs;
6607                 ifsp = &ifsfirst;
6608                 do {
6609                         p = string + ifsp->begoff;
6610                         nulonly = ifsp->nulonly;
6611                         ifs = nulonly ? nullstr : realifs;
6612                         ifsspc = 0;
6613                         while (p < string + ifsp->endoff) {
6614                                 q = p;
6615                                 if (*p == CTLESC)
6616                                         p++;
6617                                 if (!strchr(ifs, *p)) {
6618                                         p++;
6619                                         continue;
6620                                 }
6621                                 if (!nulonly)
6622                                         ifsspc = (strchr(defifs, *p) != NULL);
6623                                 /* Ignore IFS whitespace at start */
6624                                 if (q == start && ifsspc) {
6625                                         p++;
6626                                         start = p;
6627                                         continue;
6628                                 }
6629                                 *q = '\0';
6630                                 sp = stzalloc(sizeof(*sp));
6631                                 sp->text = start;
6632                                 *arglist->lastp = sp;
6633                                 arglist->lastp = &sp->next;
6634                                 p++;
6635                                 if (!nulonly) {
6636                                         for (;;) {
6637                                                 if (p >= string + ifsp->endoff) {
6638                                                         break;
6639                                                 }
6640                                                 q = p;
6641                                                 if (*p == CTLESC)
6642                                                         p++;
6643                                                 if (strchr(ifs, *p) == NULL) {
6644                                                         p = q;
6645                                                         break;
6646                                                 }
6647                                                 if (strchr(defifs, *p) == NULL) {
6648                                                         if (ifsspc) {
6649                                                                 p++;
6650                                                                 ifsspc = 0;
6651                                                         } else {
6652                                                                 p = q;
6653                                                                 break;
6654                                                         }
6655                                                 } else
6656                                                         p++;
6657                                         }
6658                                 }
6659                                 start = p;
6660                         } /* while */
6661                         ifsp = ifsp->next;
6662                 } while (ifsp != NULL);
6663                 if (nulonly)
6664                         goto add;
6665         }
6666
6667         if (!*start)
6668                 return;
6669
6670  add:
6671         sp = stzalloc(sizeof(*sp));
6672         sp->text = start;
6673         *arglist->lastp = sp;
6674         arglist->lastp = &sp->next;
6675 }
6676
6677 static void
6678 ifsfree(void)
6679 {
6680         struct ifsregion *p;
6681
6682         INT_OFF;
6683         p = ifsfirst.next;
6684         do {
6685                 struct ifsregion *ifsp;
6686                 ifsp = p->next;
6687                 free(p);
6688                 p = ifsp;
6689         } while (p);
6690         ifslastp = NULL;
6691         ifsfirst.next = NULL;
6692         INT_ON;
6693 }
6694
6695 /*
6696  * Add a file name to the list.
6697  */
6698 static void
6699 addfname(const char *name)
6700 {
6701         struct strlist *sp;
6702
6703         sp = stzalloc(sizeof(*sp));
6704         sp->text = ststrdup(name);
6705         *exparg.lastp = sp;
6706         exparg.lastp = &sp->next;
6707 }
6708
6709 static char *expdir;
6710
6711 /*
6712  * Do metacharacter (i.e. *, ?, [...]) expansion.
6713  */
6714 static void
6715 expmeta(char *enddir, char *name)
6716 {
6717         char *p;
6718         const char *cp;
6719         char *start;
6720         char *endname;
6721         int metaflag;
6722         struct stat statb;
6723         DIR *dirp;
6724         struct dirent *dp;
6725         int atend;
6726         int matchdot;
6727
6728         metaflag = 0;
6729         start = name;
6730         for (p = name; *p; p++) {
6731                 if (*p == '*' || *p == '?')
6732                         metaflag = 1;
6733                 else if (*p == '[') {
6734                         char *q = p + 1;
6735                         if (*q == '!')
6736                                 q++;
6737                         for (;;) {
6738                                 if (*q == '\\')
6739                                         q++;
6740                                 if (*q == '/' || *q == '\0')
6741                                         break;
6742                                 if (*++q == ']') {
6743                                         metaflag = 1;
6744                                         break;
6745                                 }
6746                         }
6747                 } else if (*p == '\\')
6748                         p++;
6749                 else if (*p == '/') {
6750                         if (metaflag)
6751                                 goto out;
6752                         start = p + 1;
6753                 }
6754         }
6755  out:
6756         if (metaflag == 0) {    /* we've reached the end of the file name */
6757                 if (enddir != expdir)
6758                         metaflag++;
6759                 p = name;
6760                 do {
6761                         if (*p == '\\')
6762                                 p++;
6763                         *enddir++ = *p;
6764                 } while (*p++);
6765                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6766                         addfname(expdir);
6767                 return;
6768         }
6769         endname = p;
6770         if (name < start) {
6771                 p = name;
6772                 do {
6773                         if (*p == '\\')
6774                                 p++;
6775                         *enddir++ = *p++;
6776                 } while (p < start);
6777         }
6778         if (enddir == expdir) {
6779                 cp = ".";
6780         } else if (enddir == expdir + 1 && *expdir == '/') {
6781                 cp = "/";
6782         } else {
6783                 cp = expdir;
6784                 enddir[-1] = '\0';
6785         }
6786         dirp = opendir(cp);
6787         if (dirp == NULL)
6788                 return;
6789         if (enddir != expdir)
6790                 enddir[-1] = '/';
6791         if (*endname == 0) {
6792                 atend = 1;
6793         } else {
6794                 atend = 0;
6795                 *endname++ = '\0';
6796         }
6797         matchdot = 0;
6798         p = start;
6799         if (*p == '\\')
6800                 p++;
6801         if (*p == '.')
6802                 matchdot++;
6803         while (!intpending && (dp = readdir(dirp)) != NULL) {
6804                 if (dp->d_name[0] == '.' && !matchdot)
6805                         continue;
6806                 if (pmatch(start, dp->d_name)) {
6807                         if (atend) {
6808                                 strcpy(enddir, dp->d_name);
6809                                 addfname(expdir);
6810                         } else {
6811                                 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6812                                         continue;
6813                                 p[-1] = '/';
6814                                 expmeta(p, endname);
6815                         }
6816                 }
6817         }
6818         closedir(dirp);
6819         if (!atend)
6820                 endname[-1] = '/';
6821 }
6822
6823 static struct strlist *
6824 msort(struct strlist *list, int len)
6825 {
6826         struct strlist *p, *q = NULL;
6827         struct strlist **lpp;
6828         int half;
6829         int n;
6830
6831         if (len <= 1)
6832                 return list;
6833         half = len >> 1;
6834         p = list;
6835         for (n = half; --n >= 0;) {
6836                 q = p;
6837                 p = p->next;
6838         }
6839         q->next = NULL;                 /* terminate first half of list */
6840         q = msort(list, half);          /* sort first half of list */
6841         p = msort(p, len - half);               /* sort second half */
6842         lpp = &list;
6843         for (;;) {
6844 #if ENABLE_LOCALE_SUPPORT
6845                 if (strcoll(p->text, q->text) < 0)
6846 #else
6847                 if (strcmp(p->text, q->text) < 0)
6848 #endif
6849                                                 {
6850                         *lpp = p;
6851                         lpp = &p->next;
6852                         p = *lpp;
6853                         if (p == NULL) {
6854                                 *lpp = q;
6855                                 break;
6856                         }
6857                 } else {
6858                         *lpp = q;
6859                         lpp = &q->next;
6860                         q = *lpp;
6861                         if (q == NULL) {
6862                                 *lpp = p;
6863                                 break;
6864                         }
6865                 }
6866         }
6867         return list;
6868 }
6869
6870 /*
6871  * Sort the results of file name expansion.  It calculates the number of
6872  * strings to sort and then calls msort (short for merge sort) to do the
6873  * work.
6874  */
6875 static struct strlist *
6876 expsort(struct strlist *str)
6877 {
6878         int len;
6879         struct strlist *sp;
6880
6881         len = 0;
6882         for (sp = str; sp; sp = sp->next)
6883                 len++;
6884         return msort(str, len);
6885 }
6886
6887 static void
6888 expandmeta(struct strlist *str /*, int flag*/)
6889 {
6890         static const char metachars[] ALIGN1 = {
6891                 '*', '?', '[', 0
6892         };
6893         /* TODO - EXP_REDIR */
6894
6895         while (str) {
6896                 struct strlist **savelastp;
6897                 struct strlist *sp;
6898                 char *p;
6899
6900                 if (fflag)
6901                         goto nometa;
6902                 if (!strpbrk(str->text, metachars))
6903                         goto nometa;
6904                 savelastp = exparg.lastp;
6905
6906                 INT_OFF;
6907                 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6908                 {
6909                         int i = strlen(str->text);
6910                         expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6911                 }
6912
6913                 expmeta(expdir, p);
6914                 free(expdir);
6915                 if (p != str->text)
6916                         free(p);
6917                 INT_ON;
6918                 if (exparg.lastp == savelastp) {
6919                         /*
6920                          * no matches
6921                          */
6922  nometa:
6923                         *exparg.lastp = str;
6924                         rmescapes(str->text);
6925                         exparg.lastp = &str->next;
6926                 } else {
6927                         *exparg.lastp = NULL;
6928                         *savelastp = sp = expsort(*savelastp);
6929                         while (sp->next != NULL)
6930                                 sp = sp->next;
6931                         exparg.lastp = &sp->next;
6932                 }
6933                 str = str->next;
6934         }
6935 }
6936
6937 /*
6938  * Perform variable substitution and command substitution on an argument,
6939  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
6940  * perform splitting and file name expansion.  When arglist is NULL, perform
6941  * here document expansion.
6942  */
6943 static void
6944 expandarg(union node *arg, struct arglist *arglist, int flag)
6945 {
6946         struct strlist *sp;
6947         char *p;
6948
6949         argbackq = arg->narg.backquote;
6950         STARTSTACKSTR(expdest);
6951         ifsfirst.next = NULL;
6952         ifslastp = NULL;
6953         argstr(arg->narg.text, flag,
6954                         /* var_str_list: */ arglist ? arglist->list : NULL);
6955         p = _STPUTC('\0', expdest);
6956         expdest = p - 1;
6957         if (arglist == NULL) {
6958                 return;                 /* here document expanded */
6959         }
6960         p = grabstackstr(p);
6961         exparg.lastp = &exparg.list;
6962         /*
6963          * TODO - EXP_REDIR
6964          */
6965         if (flag & EXP_FULL) {
6966                 ifsbreakup(p, &exparg);
6967                 *exparg.lastp = NULL;
6968                 exparg.lastp = &exparg.list;
6969                 expandmeta(exparg.list /*, flag*/);
6970         } else {
6971                 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6972                         rmescapes(p);
6973                 sp = stzalloc(sizeof(*sp));
6974                 sp->text = p;
6975                 *exparg.lastp = sp;
6976                 exparg.lastp = &sp->next;
6977         }
6978         if (ifsfirst.next)
6979                 ifsfree();
6980         *exparg.lastp = NULL;
6981         if (exparg.list) {
6982                 *arglist->lastp = exparg.list;
6983                 arglist->lastp = exparg.lastp;
6984         }
6985 }
6986
6987 /*
6988  * Expand shell variables and backquotes inside a here document.
6989  */
6990 static void
6991 expandhere(union node *arg, int fd)
6992 {
6993         herefd = fd;
6994         expandarg(arg, (struct arglist *)NULL, 0);
6995         full_write(fd, stackblock(), expdest - (char *)stackblock());
6996 }
6997
6998 /*
6999  * Returns true if the pattern matches the string.
7000  */
7001 static int
7002 patmatch(char *pattern, const char *string)
7003 {
7004         return pmatch(preglob(pattern, 0, 0), string);
7005 }
7006
7007 /*
7008  * See if a pattern matches in a case statement.
7009  */
7010 static int
7011 casematch(union node *pattern, char *val)
7012 {
7013         struct stackmark smark;
7014         int result;
7015
7016         setstackmark(&smark);
7017         argbackq = pattern->narg.backquote;
7018         STARTSTACKSTR(expdest);
7019         ifslastp = NULL;
7020         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7021                         /* var_str_list: */ NULL);
7022         STACKSTRNUL(expdest);
7023         result = patmatch(stackblock(), val);
7024         popstackmark(&smark);
7025         return result;
7026 }
7027
7028
7029 /* ============ find_command */
7030
7031 struct builtincmd {
7032         const char *name;
7033         int (*builtin)(int, char **) FAST_FUNC;
7034         /* unsigned flags; */
7035 };
7036 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7037 /* "regular" builtins always take precedence over commands,
7038  * regardless of PATH=....%builtin... position */
7039 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7040 #define IS_BUILTIN_ASSIGN(b)  ((b)->name[0] & 4)
7041
7042 struct cmdentry {
7043         smallint cmdtype;       /* CMDxxx */
7044         union param {
7045                 int index;
7046                 /* index >= 0 for commands without path (slashes) */
7047                 /* (TODO: what exactly does the value mean? PATH position?) */
7048                 /* index == -1 for commands with slashes */
7049                 /* index == (-2 - applet_no) for NOFORK applets */
7050                 const struct builtincmd *cmd;
7051                 struct funcnode *func;
7052         } u;
7053 };
7054 /* values of cmdtype */
7055 #define CMDUNKNOWN      -1      /* no entry in table for command */
7056 #define CMDNORMAL       0       /* command is an executable program */
7057 #define CMDFUNCTION     1       /* command is a shell function */
7058 #define CMDBUILTIN      2       /* command is a shell builtin */
7059
7060 /* action to find_command() */
7061 #define DO_ERR          0x01    /* prints errors */
7062 #define DO_ABS          0x02    /* checks absolute paths */
7063 #define DO_NOFUNC       0x04    /* don't return shell functions, for command */
7064 #define DO_ALTPATH      0x08    /* using alternate path */
7065 #define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
7066
7067 static void find_command(char *, struct cmdentry *, int, const char *);
7068
7069
7070 /* ============ Hashing commands */
7071
7072 /*
7073  * When commands are first encountered, they are entered in a hash table.
7074  * This ensures that a full path search will not have to be done for them
7075  * on each invocation.
7076  *
7077  * We should investigate converting to a linear search, even though that
7078  * would make the command name "hash" a misnomer.
7079  */
7080
7081 struct tblentry {
7082         struct tblentry *next;  /* next entry in hash chain */
7083         union param param;      /* definition of builtin function */
7084         smallint cmdtype;       /* CMDxxx */
7085         char rehash;            /* if set, cd done since entry created */
7086         char cmdname[1];        /* name of command */
7087 };
7088
7089 static struct tblentry **cmdtable;
7090 #define INIT_G_cmdtable() do { \
7091         cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7092 } while (0)
7093
7094 static int builtinloc = -1;     /* index in path of %builtin, or -1 */
7095
7096
7097 static void
7098 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7099 {
7100         int repeated = 0;
7101
7102 #if ENABLE_FEATURE_SH_STANDALONE
7103         if (applet_no >= 0) {
7104                 if (APPLET_IS_NOEXEC(applet_no)) {
7105                         while (*envp)
7106                                 putenv(*envp++);
7107                         run_applet_no_and_exit(applet_no, argv);
7108                 }
7109                 /* re-exec ourselves with the new arguments */
7110                 execve(bb_busybox_exec_path, argv, envp);
7111                 /* If they called chroot or otherwise made the binary no longer
7112                  * executable, fall through */
7113         }
7114 #endif
7115
7116  repeat:
7117 #ifdef SYSV
7118         do {
7119                 execve(cmd, argv, envp);
7120         } while (errno == EINTR);
7121 #else
7122         execve(cmd, argv, envp);
7123 #endif
7124         if (repeated) {
7125                 free(argv);
7126                 return;
7127         }
7128         if (errno == ENOEXEC) {
7129                 char **ap;
7130                 char **new;
7131
7132                 for (ap = argv; *ap; ap++)
7133                         continue;
7134                 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7135                 ap[1] = cmd;
7136                 ap[0] = cmd = (char *)DEFAULT_SHELL;
7137                 ap += 2;
7138                 argv++;
7139                 while ((*ap++ = *argv++) != NULL)
7140                         continue;
7141                 argv = new;
7142                 repeated++;
7143                 goto repeat;
7144         }
7145 }
7146
7147 /*
7148  * Exec a program.  Never returns.  If you change this routine, you may
7149  * have to change the find_command routine as well.
7150  */
7151 static void shellexec(char **, const char *, int) NORETURN;
7152 static void
7153 shellexec(char **argv, const char *path, int idx)
7154 {
7155         char *cmdname;
7156         int e;
7157         char **envp;
7158         int exerrno;
7159 #if ENABLE_FEATURE_SH_STANDALONE
7160         int applet_no = -1;
7161 #endif
7162
7163         clearredir(/*drop:*/ 1);
7164         envp = listvars(VEXPORT, VUNSET, 0);
7165         if (strchr(argv[0], '/') != NULL
7166 #if ENABLE_FEATURE_SH_STANDALONE
7167          || (applet_no = find_applet_by_name(argv[0])) >= 0
7168 #endif
7169         ) {
7170                 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7171                 e = errno;
7172         } else {
7173                 e = ENOENT;
7174                 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7175                         if (--idx < 0 && pathopt == NULL) {
7176                                 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7177                                 if (errno != ENOENT && errno != ENOTDIR)
7178                                         e = errno;
7179                         }
7180                         stunalloc(cmdname);
7181                 }
7182         }
7183
7184         /* Map to POSIX errors */
7185         switch (e) {
7186         case EACCES:
7187                 exerrno = 126;
7188                 break;
7189         case ENOENT:
7190                 exerrno = 127;
7191                 break;
7192         default:
7193                 exerrno = 2;
7194                 break;
7195         }
7196         exitstatus = exerrno;
7197         TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
7198                 argv[0], e, suppressint));
7199         ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7200         /* NOTREACHED */
7201 }
7202
7203 static void
7204 printentry(struct tblentry *cmdp)
7205 {
7206         int idx;
7207         const char *path;
7208         char *name;
7209
7210         idx = cmdp->param.index;
7211         path = pathval();
7212         do {
7213                 name = path_advance(&path, cmdp->cmdname);
7214                 stunalloc(name);
7215         } while (--idx >= 0);
7216         out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7217 }
7218
7219 /*
7220  * Clear out command entries.  The argument specifies the first entry in
7221  * PATH which has changed.
7222  */
7223 static void
7224 clearcmdentry(int firstchange)
7225 {
7226         struct tblentry **tblp;
7227         struct tblentry **pp;
7228         struct tblentry *cmdp;
7229
7230         INT_OFF;
7231         for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7232                 pp = tblp;
7233                 while ((cmdp = *pp) != NULL) {
7234                         if ((cmdp->cmdtype == CMDNORMAL &&
7235                              cmdp->param.index >= firstchange)
7236                          || (cmdp->cmdtype == CMDBUILTIN &&
7237                              builtinloc >= firstchange)
7238                         ) {
7239                                 *pp = cmdp->next;
7240                                 free(cmdp);
7241                         } else {
7242                                 pp = &cmdp->next;
7243                         }
7244                 }
7245         }
7246         INT_ON;
7247 }
7248
7249 /*
7250  * Locate a command in the command hash table.  If "add" is nonzero,
7251  * add the command to the table if it is not already present.  The
7252  * variable "lastcmdentry" is set to point to the address of the link
7253  * pointing to the entry, so that delete_cmd_entry can delete the
7254  * entry.
7255  *
7256  * Interrupts must be off if called with add != 0.
7257  */
7258 static struct tblentry **lastcmdentry;
7259
7260 static struct tblentry *
7261 cmdlookup(const char *name, int add)
7262 {
7263         unsigned int hashval;
7264         const char *p;
7265         struct tblentry *cmdp;
7266         struct tblentry **pp;
7267
7268         p = name;
7269         hashval = (unsigned char)*p << 4;
7270         while (*p)
7271                 hashval += (unsigned char)*p++;
7272         hashval &= 0x7FFF;
7273         pp = &cmdtable[hashval % CMDTABLESIZE];
7274         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7275                 if (strcmp(cmdp->cmdname, name) == 0)
7276                         break;
7277                 pp = &cmdp->next;
7278         }
7279         if (add && cmdp == NULL) {
7280                 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7281                                 + strlen(name)
7282                                 /* + 1 - already done because
7283                                  * tblentry::cmdname is char[1] */);
7284                 /*cmdp->next = NULL; - ckzalloc did it */
7285                 cmdp->cmdtype = CMDUNKNOWN;
7286                 strcpy(cmdp->cmdname, name);
7287         }
7288         lastcmdentry = pp;
7289         return cmdp;
7290 }
7291
7292 /*
7293  * Delete the command entry returned on the last lookup.
7294  */
7295 static void
7296 delete_cmd_entry(void)
7297 {
7298         struct tblentry *cmdp;
7299
7300         INT_OFF;
7301         cmdp = *lastcmdentry;
7302         *lastcmdentry = cmdp->next;
7303         if (cmdp->cmdtype == CMDFUNCTION)
7304                 freefunc(cmdp->param.func);
7305         free(cmdp);
7306         INT_ON;
7307 }
7308
7309 /*
7310  * Add a new command entry, replacing any existing command entry for
7311  * the same name - except special builtins.
7312  */
7313 static void
7314 addcmdentry(char *name, struct cmdentry *entry)
7315 {
7316         struct tblentry *cmdp;
7317
7318         cmdp = cmdlookup(name, 1);
7319         if (cmdp->cmdtype == CMDFUNCTION) {
7320                 freefunc(cmdp->param.func);
7321         }
7322         cmdp->cmdtype = entry->cmdtype;
7323         cmdp->param = entry->u;
7324         cmdp->rehash = 0;
7325 }
7326
7327 static int FAST_FUNC
7328 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7329 {
7330         struct tblentry **pp;
7331         struct tblentry *cmdp;
7332         int c;
7333         struct cmdentry entry;
7334         char *name;
7335
7336         if (nextopt("r") != '\0') {
7337                 clearcmdentry(0);
7338                 return 0;
7339         }
7340
7341         if (*argptr == NULL) {
7342                 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7343                         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7344                                 if (cmdp->cmdtype == CMDNORMAL)
7345                                         printentry(cmdp);
7346                         }
7347                 }
7348                 return 0;
7349         }
7350
7351         c = 0;
7352         while ((name = *argptr) != NULL) {
7353                 cmdp = cmdlookup(name, 0);
7354                 if (cmdp != NULL
7355                  && (cmdp->cmdtype == CMDNORMAL
7356                      || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7357                 ) {
7358                         delete_cmd_entry();
7359                 }
7360                 find_command(name, &entry, DO_ERR, pathval());
7361                 if (entry.cmdtype == CMDUNKNOWN)
7362                         c = 1;
7363                 argptr++;
7364         }
7365         return c;
7366 }
7367
7368 /*
7369  * Called when a cd is done.  Marks all commands so the next time they
7370  * are executed they will be rehashed.
7371  */
7372 static void
7373 hashcd(void)
7374 {
7375         struct tblentry **pp;
7376         struct tblentry *cmdp;
7377
7378         for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7379                 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7380                         if (cmdp->cmdtype == CMDNORMAL
7381                          || (cmdp->cmdtype == CMDBUILTIN
7382                              && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7383                              && builtinloc > 0)
7384                         ) {
7385                                 cmdp->rehash = 1;
7386                         }
7387                 }
7388         }
7389 }
7390
7391 /*
7392  * Fix command hash table when PATH changed.
7393  * Called before PATH is changed.  The argument is the new value of PATH;
7394  * pathval() still returns the old value at this point.
7395  * Called with interrupts off.
7396  */
7397 static void FAST_FUNC
7398 changepath(const char *new)
7399 {
7400         const char *old;
7401         int firstchange;
7402         int idx;
7403         int idx_bltin;
7404
7405         old = pathval();
7406         firstchange = 9999;     /* assume no change */
7407         idx = 0;
7408         idx_bltin = -1;
7409         for (;;) {
7410                 if (*old != *new) {
7411                         firstchange = idx;
7412                         if ((*old == '\0' && *new == ':')
7413                          || (*old == ':' && *new == '\0'))
7414                                 firstchange++;
7415                         old = new;      /* ignore subsequent differences */
7416                 }
7417                 if (*new == '\0')
7418                         break;
7419                 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7420                         idx_bltin = idx;
7421                 if (*new == ':')
7422                         idx++;
7423                 new++, old++;
7424         }
7425         if (builtinloc < 0 && idx_bltin >= 0)
7426                 builtinloc = idx_bltin;             /* zap builtins */
7427         if (builtinloc >= 0 && idx_bltin < 0)
7428                 firstchange = 0;
7429         clearcmdentry(firstchange);
7430         builtinloc = idx_bltin;
7431 }
7432
7433 #define TEOF 0
7434 #define TNL 1
7435 #define TREDIR 2
7436 #define TWORD 3
7437 #define TSEMI 4
7438 #define TBACKGND 5
7439 #define TAND 6
7440 #define TOR 7
7441 #define TPIPE 8
7442 #define TLP 9
7443 #define TRP 10
7444 #define TENDCASE 11
7445 #define TENDBQUOTE 12
7446 #define TNOT 13
7447 #define TCASE 14
7448 #define TDO 15
7449 #define TDONE 16
7450 #define TELIF 17
7451 #define TELSE 18
7452 #define TESAC 19
7453 #define TFI 20
7454 #define TFOR 21
7455 #define TIF 22
7456 #define TIN 23
7457 #define TTHEN 24
7458 #define TUNTIL 25
7459 #define TWHILE 26
7460 #define TBEGIN 27
7461 #define TEND 28
7462 typedef smallint token_id_t;
7463
7464 /* first char is indicating which tokens mark the end of a list */
7465 static const char *const tokname_array[] = {
7466         "\1end of file",
7467         "\0newline",
7468         "\0redirection",
7469         "\0word",
7470         "\0;",
7471         "\0&",
7472         "\0&&",
7473         "\0||",
7474         "\0|",
7475         "\0(",
7476         "\1)",
7477         "\1;;",
7478         "\1`",
7479 #define KWDOFFSET 13
7480         /* the following are keywords */
7481         "\0!",
7482         "\0case",
7483         "\1do",
7484         "\1done",
7485         "\1elif",
7486         "\1else",
7487         "\1esac",
7488         "\1fi",
7489         "\0for",
7490         "\0if",
7491         "\0in",
7492         "\1then",
7493         "\0until",
7494         "\0while",
7495         "\0{",
7496         "\1}",
7497 };
7498
7499 static const char *
7500 tokname(int tok)
7501 {
7502         static char buf[16];
7503
7504 //try this:
7505 //if (tok < TSEMI) return tokname_array[tok] + 1;
7506 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7507 //return buf;
7508
7509         if (tok >= TSEMI)
7510                 buf[0] = '"';
7511         sprintf(buf + (tok >= TSEMI), "%s%c",
7512                         tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7513         return buf;
7514 }
7515
7516 /* Wrapper around strcmp for qsort/bsearch/... */
7517 static int
7518 pstrcmp(const void *a, const void *b)
7519 {
7520         return strcmp((char*) a, (*(char**) b) + 1);
7521 }
7522
7523 static const char *const *
7524 findkwd(const char *s)
7525 {
7526         return bsearch(s, tokname_array + KWDOFFSET,
7527                         ARRAY_SIZE(tokname_array) - KWDOFFSET,
7528                         sizeof(tokname_array[0]), pstrcmp);
7529 }
7530
7531 /*
7532  * Locate and print what a word is...
7533  */
7534 static int
7535 describe_command(char *command, int describe_command_verbose)
7536 {
7537         struct cmdentry entry;
7538         struct tblentry *cmdp;
7539 #if ENABLE_ASH_ALIAS
7540         const struct alias *ap;
7541 #endif
7542         const char *path = pathval();
7543
7544         if (describe_command_verbose) {
7545                 out1str(command);
7546         }
7547
7548         /* First look at the keywords */
7549         if (findkwd(command)) {
7550                 out1str(describe_command_verbose ? " is a shell keyword" : command);
7551                 goto out;
7552         }
7553
7554 #if ENABLE_ASH_ALIAS
7555         /* Then look at the aliases */
7556         ap = lookupalias(command, 0);
7557         if (ap != NULL) {
7558                 if (!describe_command_verbose) {
7559                         out1str("alias ");
7560                         printalias(ap);
7561                         return 0;
7562                 }
7563                 out1fmt(" is an alias for %s", ap->val);
7564                 goto out;
7565         }
7566 #endif
7567         /* Then check if it is a tracked alias */
7568         cmdp = cmdlookup(command, 0);
7569         if (cmdp != NULL) {
7570                 entry.cmdtype = cmdp->cmdtype;
7571                 entry.u = cmdp->param;
7572         } else {
7573                 /* Finally use brute force */
7574                 find_command(command, &entry, DO_ABS, path);
7575         }
7576
7577         switch (entry.cmdtype) {
7578         case CMDNORMAL: {
7579                 int j = entry.u.index;
7580                 char *p;
7581                 if (j < 0) {
7582                         p = command;
7583                 } else {
7584                         do {
7585                                 p = path_advance(&path, command);
7586                                 stunalloc(p);
7587                         } while (--j >= 0);
7588                 }
7589                 if (describe_command_verbose) {
7590                         out1fmt(" is%s %s",
7591                                 (cmdp ? " a tracked alias for" : nullstr), p
7592                         );
7593                 } else {
7594                         out1str(p);
7595                 }
7596                 break;
7597         }
7598
7599         case CMDFUNCTION:
7600                 if (describe_command_verbose) {
7601                         out1str(" is a shell function");
7602                 } else {
7603                         out1str(command);
7604                 }
7605                 break;
7606
7607         case CMDBUILTIN:
7608                 if (describe_command_verbose) {
7609                         out1fmt(" is a %sshell builtin",
7610                                 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7611                                         "special " : nullstr
7612                         );
7613                 } else {
7614                         out1str(command);
7615                 }
7616                 break;
7617
7618         default:
7619                 if (describe_command_verbose) {
7620                         out1str(": not found\n");
7621                 }
7622                 return 127;
7623         }
7624  out:
7625         outstr("\n", stdout);
7626         return 0;
7627 }
7628
7629 static int FAST_FUNC
7630 typecmd(int argc UNUSED_PARAM, char **argv)
7631 {
7632         int i = 1;
7633         int err = 0;
7634         int verbose = 1;
7635
7636         /* type -p ... ? (we don't bother checking for 'p') */
7637         if (argv[1] && argv[1][0] == '-') {
7638                 i++;
7639                 verbose = 0;
7640         }
7641         while (argv[i]) {
7642                 err |= describe_command(argv[i++], verbose);
7643         }
7644         return err;
7645 }
7646
7647 #if ENABLE_ASH_CMDCMD
7648 static int FAST_FUNC
7649 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7650 {
7651         int c;
7652         enum {
7653                 VERIFY_BRIEF = 1,
7654                 VERIFY_VERBOSE = 2,
7655         } verify = 0;
7656
7657         while ((c = nextopt("pvV")) != '\0')
7658                 if (c == 'V')
7659                         verify |= VERIFY_VERBOSE;
7660                 else if (c == 'v')
7661                         verify |= VERIFY_BRIEF;
7662 #if DEBUG
7663                 else if (c != 'p')
7664                         abort();
7665 #endif
7666         /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7667         if (verify && (*argptr != NULL)) {
7668                 return describe_command(*argptr, verify - VERIFY_BRIEF);
7669         }
7670
7671         return 0;
7672 }
7673 #endif
7674
7675
7676 /* ============ eval.c */
7677
7678 static int funcblocksize;       /* size of structures in function */
7679 static int funcstringsize;      /* size of strings in node */
7680 static void *funcblock;         /* block to allocate function from */
7681 static char *funcstring;        /* block to allocate strings from */
7682
7683 /* flags in argument to evaltree */
7684 #define EV_EXIT    01           /* exit after evaluating tree */
7685 #define EV_TESTED  02           /* exit status is checked; ignore -e flag */
7686 #define EV_BACKCMD 04           /* command executing within back quotes */
7687
7688 static const short nodesize[N_NUMBER] = {
7689         [NCMD     ] = SHELL_ALIGN(sizeof(struct ncmd)),
7690         [NPIPE    ] = SHELL_ALIGN(sizeof(struct npipe)),
7691         [NREDIR   ] = SHELL_ALIGN(sizeof(struct nredir)),
7692         [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7693         [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7694         [NAND     ] = SHELL_ALIGN(sizeof(struct nbinary)),
7695         [NOR      ] = SHELL_ALIGN(sizeof(struct nbinary)),
7696         [NSEMI    ] = SHELL_ALIGN(sizeof(struct nbinary)),
7697         [NIF      ] = SHELL_ALIGN(sizeof(struct nif)),
7698         [NWHILE   ] = SHELL_ALIGN(sizeof(struct nbinary)),
7699         [NUNTIL   ] = SHELL_ALIGN(sizeof(struct nbinary)),
7700         [NFOR     ] = SHELL_ALIGN(sizeof(struct nfor)),
7701         [NCASE    ] = SHELL_ALIGN(sizeof(struct ncase)),
7702         [NCLIST   ] = SHELL_ALIGN(sizeof(struct nclist)),
7703         [NDEFUN   ] = SHELL_ALIGN(sizeof(struct narg)),
7704         [NARG     ] = SHELL_ALIGN(sizeof(struct narg)),
7705         [NTO      ] = SHELL_ALIGN(sizeof(struct nfile)),
7706 #if ENABLE_ASH_BASH_COMPAT
7707         [NTO2     ] = SHELL_ALIGN(sizeof(struct nfile)),
7708 #endif
7709         [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7710         [NFROM    ] = SHELL_ALIGN(sizeof(struct nfile)),
7711         [NFROMTO  ] = SHELL_ALIGN(sizeof(struct nfile)),
7712         [NAPPEND  ] = SHELL_ALIGN(sizeof(struct nfile)),
7713         [NTOFD    ] = SHELL_ALIGN(sizeof(struct ndup)),
7714         [NFROMFD  ] = SHELL_ALIGN(sizeof(struct ndup)),
7715         [NHERE    ] = SHELL_ALIGN(sizeof(struct nhere)),
7716         [NXHERE   ] = SHELL_ALIGN(sizeof(struct nhere)),
7717         [NNOT     ] = SHELL_ALIGN(sizeof(struct nnot)),
7718 };
7719
7720 static void calcsize(union node *n);
7721
7722 static void
7723 sizenodelist(struct nodelist *lp)
7724 {
7725         while (lp) {
7726                 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7727                 calcsize(lp->n);
7728                 lp = lp->next;
7729         }
7730 }
7731
7732 static void
7733 calcsize(union node *n)
7734 {
7735         if (n == NULL)
7736                 return;
7737         funcblocksize += nodesize[n->type];
7738         switch (n->type) {
7739         case NCMD:
7740                 calcsize(n->ncmd.redirect);
7741                 calcsize(n->ncmd.args);
7742                 calcsize(n->ncmd.assign);
7743                 break;
7744         case NPIPE:
7745                 sizenodelist(n->npipe.cmdlist);
7746                 break;
7747         case NREDIR:
7748         case NBACKGND:
7749         case NSUBSHELL:
7750                 calcsize(n->nredir.redirect);
7751                 calcsize(n->nredir.n);
7752                 break;
7753         case NAND:
7754         case NOR:
7755         case NSEMI:
7756         case NWHILE:
7757         case NUNTIL:
7758                 calcsize(n->nbinary.ch2);
7759                 calcsize(n->nbinary.ch1);
7760                 break;
7761         case NIF:
7762                 calcsize(n->nif.elsepart);
7763                 calcsize(n->nif.ifpart);
7764                 calcsize(n->nif.test);
7765                 break;
7766         case NFOR:
7767                 funcstringsize += strlen(n->nfor.var) + 1;
7768                 calcsize(n->nfor.body);
7769                 calcsize(n->nfor.args);
7770                 break;
7771         case NCASE:
7772                 calcsize(n->ncase.cases);
7773                 calcsize(n->ncase.expr);
7774                 break;
7775         case NCLIST:
7776                 calcsize(n->nclist.body);
7777                 calcsize(n->nclist.pattern);
7778                 calcsize(n->nclist.next);
7779                 break;
7780         case NDEFUN:
7781         case NARG:
7782                 sizenodelist(n->narg.backquote);
7783                 funcstringsize += strlen(n->narg.text) + 1;
7784                 calcsize(n->narg.next);
7785                 break;
7786         case NTO:
7787 #if ENABLE_ASH_BASH_COMPAT
7788         case NTO2:
7789 #endif
7790         case NCLOBBER:
7791         case NFROM:
7792         case NFROMTO:
7793         case NAPPEND:
7794                 calcsize(n->nfile.fname);
7795                 calcsize(n->nfile.next);
7796                 break;
7797         case NTOFD:
7798         case NFROMFD:
7799                 calcsize(n->ndup.vname);
7800                 calcsize(n->ndup.next);
7801         break;
7802         case NHERE:
7803         case NXHERE:
7804                 calcsize(n->nhere.doc);
7805                 calcsize(n->nhere.next);
7806                 break;
7807         case NNOT:
7808                 calcsize(n->nnot.com);
7809                 break;
7810         };
7811 }
7812
7813 static char *
7814 nodeckstrdup(char *s)
7815 {
7816         char *rtn = funcstring;
7817
7818         strcpy(funcstring, s);
7819         funcstring += strlen(s) + 1;
7820         return rtn;
7821 }
7822
7823 static union node *copynode(union node *);
7824
7825 static struct nodelist *
7826 copynodelist(struct nodelist *lp)
7827 {
7828         struct nodelist *start;
7829         struct nodelist **lpp;
7830
7831         lpp = &start;
7832         while (lp) {
7833                 *lpp = funcblock;
7834                 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7835                 (*lpp)->n = copynode(lp->n);
7836                 lp = lp->next;
7837                 lpp = &(*lpp)->next;
7838         }
7839         *lpp = NULL;
7840         return start;
7841 }
7842
7843 static union node *
7844 copynode(union node *n)
7845 {
7846         union node *new;
7847
7848         if (n == NULL)
7849                 return NULL;
7850         new = funcblock;
7851         funcblock = (char *) funcblock + nodesize[n->type];
7852
7853         switch (n->type) {
7854         case NCMD:
7855                 new->ncmd.redirect = copynode(n->ncmd.redirect);
7856                 new->ncmd.args = copynode(n->ncmd.args);
7857                 new->ncmd.assign = copynode(n->ncmd.assign);
7858                 break;
7859         case NPIPE:
7860                 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7861                 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7862                 break;
7863         case NREDIR:
7864         case NBACKGND:
7865         case NSUBSHELL:
7866                 new->nredir.redirect = copynode(n->nredir.redirect);
7867                 new->nredir.n = copynode(n->nredir.n);
7868                 break;
7869         case NAND:
7870         case NOR:
7871         case NSEMI:
7872         case NWHILE:
7873         case NUNTIL:
7874                 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7875                 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7876                 break;
7877         case NIF:
7878                 new->nif.elsepart = copynode(n->nif.elsepart);
7879                 new->nif.ifpart = copynode(n->nif.ifpart);
7880                 new->nif.test = copynode(n->nif.test);
7881                 break;
7882         case NFOR:
7883                 new->nfor.var = nodeckstrdup(n->nfor.var);
7884                 new->nfor.body = copynode(n->nfor.body);
7885                 new->nfor.args = copynode(n->nfor.args);
7886                 break;
7887         case NCASE:
7888                 new->ncase.cases = copynode(n->ncase.cases);
7889                 new->ncase.expr = copynode(n->ncase.expr);
7890                 break;
7891         case NCLIST:
7892                 new->nclist.body = copynode(n->nclist.body);
7893                 new->nclist.pattern = copynode(n->nclist.pattern);
7894                 new->nclist.next = copynode(n->nclist.next);
7895                 break;
7896         case NDEFUN:
7897         case NARG:
7898                 new->narg.backquote = copynodelist(n->narg.backquote);
7899                 new->narg.text = nodeckstrdup(n->narg.text);
7900                 new->narg.next = copynode(n->narg.next);
7901                 break;
7902         case NTO:
7903 #if ENABLE_ASH_BASH_COMPAT
7904         case NTO2:
7905 #endif
7906         case NCLOBBER:
7907         case NFROM:
7908         case NFROMTO:
7909         case NAPPEND:
7910                 new->nfile.fname = copynode(n->nfile.fname);
7911                 new->nfile.fd = n->nfile.fd;
7912                 new->nfile.next = copynode(n->nfile.next);
7913                 break;
7914         case NTOFD:
7915         case NFROMFD:
7916                 new->ndup.vname = copynode(n->ndup.vname);
7917                 new->ndup.dupfd = n->ndup.dupfd;
7918                 new->ndup.fd = n->ndup.fd;
7919                 new->ndup.next = copynode(n->ndup.next);
7920                 break;
7921         case NHERE:
7922         case NXHERE:
7923                 new->nhere.doc = copynode(n->nhere.doc);
7924                 new->nhere.fd = n->nhere.fd;
7925                 new->nhere.next = copynode(n->nhere.next);
7926                 break;
7927         case NNOT:
7928                 new->nnot.com = copynode(n->nnot.com);
7929                 break;
7930         };
7931         new->type = n->type;
7932         return new;
7933 }
7934
7935 /*
7936  * Make a copy of a parse tree.
7937  */
7938 static struct funcnode *
7939 copyfunc(union node *n)
7940 {
7941         struct funcnode *f;
7942         size_t blocksize;
7943
7944         funcblocksize = offsetof(struct funcnode, n);
7945         funcstringsize = 0;
7946         calcsize(n);
7947         blocksize = funcblocksize;
7948         f = ckmalloc(blocksize + funcstringsize);
7949         funcblock = (char *) f + offsetof(struct funcnode, n);
7950         funcstring = (char *) f + blocksize;
7951         copynode(n);
7952         f->count = 0;
7953         return f;
7954 }
7955
7956 /*
7957  * Define a shell function.
7958  */
7959 static void
7960 defun(char *name, union node *func)
7961 {
7962         struct cmdentry entry;
7963
7964         INT_OFF;
7965         entry.cmdtype = CMDFUNCTION;
7966         entry.u.func = copyfunc(func);
7967         addcmdentry(name, &entry);
7968         INT_ON;
7969 }
7970
7971 /* Reasons for skipping commands (see comment on breakcmd routine) */
7972 #define SKIPBREAK      (1 << 0)
7973 #define SKIPCONT       (1 << 1)
7974 #define SKIPFUNC       (1 << 2)
7975 #define SKIPFILE       (1 << 3)
7976 #define SKIPEVAL       (1 << 4)
7977 static smallint evalskip;       /* set to SKIPxxx if we are skipping commands */
7978 static int skipcount;           /* number of levels to skip */
7979 static int funcnest;            /* depth of function calls */
7980 static int loopnest;            /* current loop nesting level */
7981
7982 /* Forward decl way out to parsing code - dotrap needs it */
7983 static int evalstring(char *s, int mask);
7984
7985 /* Called to execute a trap.
7986  * Single callsite - at the end of evaltree().
7987  * If we return non-zero, exaltree raises EXEXIT exception.
7988  *
7989  * Perhaps we should avoid entering new trap handlers
7990  * while we are executing a trap handler. [is it a TODO?]
7991  */
7992 static int
7993 dotrap(void)
7994 {
7995         uint8_t *g;
7996         int sig;
7997         uint8_t savestatus;
7998
7999         savestatus = exitstatus;
8000         pendingsig = 0;
8001         xbarrier();
8002
8003         TRACE(("dotrap entered\n"));
8004         for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8005                 int want_exexit;
8006                 char *t;
8007
8008                 if (*g == 0)
8009                         continue;
8010                 t = trap[sig];
8011                 /* non-trapped SIGINT is handled separately by raise_interrupt,
8012                  * don't upset it by resetting gotsig[SIGINT-1] */
8013                 if (sig == SIGINT && !t)
8014                         continue;
8015
8016                 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8017                 *g = 0;
8018                 if (!t)
8019                         continue;
8020                 want_exexit = evalstring(t, SKIPEVAL);
8021                 exitstatus = savestatus;
8022                 if (want_exexit) {
8023                         TRACE(("dotrap returns %d\n", want_exexit));
8024                         return want_exexit;
8025                 }
8026         }
8027
8028         TRACE(("dotrap returns 0\n"));
8029         return 0;
8030 }
8031
8032 /* forward declarations - evaluation is fairly recursive business... */
8033 static void evalloop(union node *, int);
8034 static void evalfor(union node *, int);
8035 static void evalcase(union node *, int);
8036 static void evalsubshell(union node *, int);
8037 static void expredir(union node *);
8038 static void evalpipe(union node *, int);
8039 static void evalcommand(union node *, int);
8040 static int evalbltin(const struct builtincmd *, int, char **);
8041 static void prehash(union node *);
8042
8043 /*
8044  * Evaluate a parse tree.  The value is left in the global variable
8045  * exitstatus.
8046  */
8047 static void
8048 evaltree(union node *n, int flags)
8049 {
8050         struct jmploc *volatile savehandler = exception_handler;
8051         struct jmploc jmploc;
8052         int checkexit = 0;
8053         void (*evalfn)(union node *, int);
8054         int status;
8055         int int_level;
8056
8057         SAVE_INT(int_level);
8058
8059         if (n == NULL) {
8060                 TRACE(("evaltree(NULL) called\n"));
8061                 goto out1;
8062         }
8063         TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8064
8065         exception_handler = &jmploc;
8066         {
8067                 int err = setjmp(jmploc.loc);
8068                 if (err) {
8069                         /* if it was a signal, check for trap handlers */
8070                         if (exception_type == EXSIG) {
8071                                 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8072                                                 exception_type, err));
8073                                 goto out;
8074                         }
8075                         /* continue on the way out */
8076                         TRACE(("exception %d in evaltree, propagating err=%d\n",
8077                                         exception_type, err));
8078                         exception_handler = savehandler;
8079                         longjmp(exception_handler->loc, err);
8080                 }
8081         }
8082
8083         switch (n->type) {
8084         default:
8085 #if DEBUG
8086                 out1fmt("Node type = %d\n", n->type);
8087                 fflush(stdout);
8088                 break;
8089 #endif
8090         case NNOT:
8091                 evaltree(n->nnot.com, EV_TESTED);
8092                 status = !exitstatus;
8093                 goto setstatus;
8094         case NREDIR:
8095                 expredir(n->nredir.redirect);
8096                 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8097                 if (!status) {
8098                         evaltree(n->nredir.n, flags & EV_TESTED);
8099                         status = exitstatus;
8100                 }
8101                 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8102                 goto setstatus;
8103         case NCMD:
8104                 evalfn = evalcommand;
8105  checkexit:
8106                 if (eflag && !(flags & EV_TESTED))
8107                         checkexit = ~0;
8108                 goto calleval;
8109         case NFOR:
8110                 evalfn = evalfor;
8111                 goto calleval;
8112         case NWHILE:
8113         case NUNTIL:
8114                 evalfn = evalloop;
8115                 goto calleval;
8116         case NSUBSHELL:
8117         case NBACKGND:
8118                 evalfn = evalsubshell;
8119                 goto calleval;
8120         case NPIPE:
8121                 evalfn = evalpipe;
8122                 goto checkexit;
8123         case NCASE:
8124                 evalfn = evalcase;
8125                 goto calleval;
8126         case NAND:
8127         case NOR:
8128         case NSEMI: {
8129
8130 #if NAND + 1 != NOR
8131 #error NAND + 1 != NOR
8132 #endif
8133 #if NOR + 1 != NSEMI
8134 #error NOR + 1 != NSEMI
8135 #endif
8136                 unsigned is_or = n->type - NAND;
8137                 evaltree(
8138                         n->nbinary.ch1,
8139                         (flags | ((is_or >> 1) - 1)) & EV_TESTED
8140                 );
8141                 if (!exitstatus == is_or)
8142                         break;
8143                 if (!evalskip) {
8144                         n = n->nbinary.ch2;
8145  evaln:
8146                         evalfn = evaltree;
8147  calleval:
8148                         evalfn(n, flags);
8149                         break;
8150                 }
8151                 break;
8152         }
8153         case NIF:
8154                 evaltree(n->nif.test, EV_TESTED);
8155                 if (evalskip)
8156                         break;
8157                 if (exitstatus == 0) {
8158                         n = n->nif.ifpart;
8159                         goto evaln;
8160                 }
8161                 if (n->nif.elsepart) {
8162                         n = n->nif.elsepart;
8163                         goto evaln;
8164                 }
8165                 goto success;
8166         case NDEFUN:
8167                 defun(n->narg.text, n->narg.next);
8168  success:
8169                 status = 0;
8170  setstatus:
8171                 exitstatus = status;
8172                 break;
8173         }
8174
8175  out:
8176         exception_handler = savehandler;
8177  out1:
8178         if (checkexit & exitstatus)
8179                 evalskip |= SKIPEVAL;
8180         else if (pendingsig && dotrap())
8181                 goto exexit;
8182
8183         if (flags & EV_EXIT) {
8184  exexit:
8185                 raise_exception(EXEXIT);
8186         }
8187
8188         RESTORE_INT(int_level);
8189         TRACE(("leaving evaltree (no interrupts)\n"));
8190 }
8191
8192 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8193 static
8194 #endif
8195 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8196
8197 static void
8198 evalloop(union node *n, int flags)
8199 {
8200         int status;
8201
8202         loopnest++;
8203         status = 0;
8204         flags &= EV_TESTED;
8205         for (;;) {
8206                 int i;
8207
8208                 evaltree(n->nbinary.ch1, EV_TESTED);
8209                 if (evalskip) {
8210  skipping:
8211                         if (evalskip == SKIPCONT && --skipcount <= 0) {
8212                                 evalskip = 0;
8213                                 continue;
8214                         }
8215                         if (evalskip == SKIPBREAK && --skipcount <= 0)
8216                                 evalskip = 0;
8217                         break;
8218                 }
8219                 i = exitstatus;
8220                 if (n->type != NWHILE)
8221                         i = !i;
8222                 if (i != 0)
8223                         break;
8224                 evaltree(n->nbinary.ch2, flags);
8225                 status = exitstatus;
8226                 if (evalskip)
8227                         goto skipping;
8228         }
8229         loopnest--;
8230         exitstatus = status;
8231 }
8232
8233 static void
8234 evalfor(union node *n, int flags)
8235 {
8236         struct arglist arglist;
8237         union node *argp;
8238         struct strlist *sp;
8239         struct stackmark smark;
8240
8241         setstackmark(&smark);
8242         arglist.list = NULL;
8243         arglist.lastp = &arglist.list;
8244         for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8245                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8246                 /* XXX */
8247                 if (evalskip)
8248                         goto out;
8249         }
8250         *arglist.lastp = NULL;
8251
8252         exitstatus = 0;
8253         loopnest++;
8254         flags &= EV_TESTED;
8255         for (sp = arglist.list; sp; sp = sp->next) {
8256                 setvar(n->nfor.var, sp->text, 0);
8257                 evaltree(n->nfor.body, flags);
8258                 if (evalskip) {
8259                         if (evalskip == SKIPCONT && --skipcount <= 0) {
8260                                 evalskip = 0;
8261                                 continue;
8262                         }
8263                         if (evalskip == SKIPBREAK && --skipcount <= 0)
8264                                 evalskip = 0;
8265                         break;
8266                 }
8267         }
8268         loopnest--;
8269  out:
8270         popstackmark(&smark);
8271 }
8272
8273 static void
8274 evalcase(union node *n, int flags)
8275 {
8276         union node *cp;
8277         union node *patp;
8278         struct arglist arglist;
8279         struct stackmark smark;
8280
8281         setstackmark(&smark);
8282         arglist.list = NULL;
8283         arglist.lastp = &arglist.list;
8284         expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8285         exitstatus = 0;
8286         for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8287                 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8288                         if (casematch(patp, arglist.list->text)) {
8289                                 if (evalskip == 0) {
8290                                         evaltree(cp->nclist.body, flags);
8291                                 }
8292                                 goto out;
8293                         }
8294                 }
8295         }
8296  out:
8297         popstackmark(&smark);
8298 }
8299
8300 /*
8301  * Kick off a subshell to evaluate a tree.
8302  */
8303 static void
8304 evalsubshell(union node *n, int flags)
8305 {
8306         struct job *jp;
8307         int backgnd = (n->type == NBACKGND);
8308         int status;
8309
8310         expredir(n->nredir.redirect);
8311         if (!backgnd && flags & EV_EXIT && !trap[0])
8312                 goto nofork;
8313         INT_OFF;
8314         jp = makejob(/*n,*/ 1);
8315         if (forkshell(jp, n, backgnd) == 0) {
8316                 INT_ON;
8317                 flags |= EV_EXIT;
8318                 if (backgnd)
8319                         flags &=~ EV_TESTED;
8320  nofork:
8321                 redirect(n->nredir.redirect, 0);
8322                 evaltreenr(n->nredir.n, flags);
8323                 /* never returns */
8324         }
8325         status = 0;
8326         if (!backgnd)
8327                 status = waitforjob(jp);
8328         exitstatus = status;
8329         INT_ON;
8330 }
8331
8332 /*
8333  * Compute the names of the files in a redirection list.
8334  */
8335 static void fixredir(union node *, const char *, int);
8336 static void
8337 expredir(union node *n)
8338 {
8339         union node *redir;
8340
8341         for (redir = n; redir; redir = redir->nfile.next) {
8342                 struct arglist fn;
8343
8344                 fn.list = NULL;
8345                 fn.lastp = &fn.list;
8346                 switch (redir->type) {
8347                 case NFROMTO:
8348                 case NFROM:
8349                 case NTO:
8350 #if ENABLE_ASH_BASH_COMPAT
8351                 case NTO2:
8352 #endif
8353                 case NCLOBBER:
8354                 case NAPPEND:
8355                         expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8356 #if ENABLE_ASH_BASH_COMPAT
8357  store_expfname:
8358 #endif
8359                         redir->nfile.expfname = fn.list->text;
8360                         break;
8361                 case NFROMFD:
8362                 case NTOFD: /* >& */
8363                         if (redir->ndup.vname) {
8364                                 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8365                                 if (fn.list == NULL)
8366                                         ash_msg_and_raise_error("redir error");
8367 #if ENABLE_ASH_BASH_COMPAT
8368 //FIXME: we used expandarg with different args!
8369                                 if (!isdigit_str9(fn.list->text)) {
8370                                         /* >&file, not >&fd */
8371                                         if (redir->nfile.fd != 1) /* 123>&file - BAD */
8372                                                 ash_msg_and_raise_error("redir error");
8373                                         redir->type = NTO2;
8374                                         goto store_expfname;
8375                                 }
8376 #endif
8377                                 fixredir(redir, fn.list->text, 1);
8378                         }
8379                         break;
8380                 }
8381         }
8382 }
8383
8384 /*
8385  * Evaluate a pipeline.  All the processes in the pipeline are children
8386  * of the process creating the pipeline.  (This differs from some versions
8387  * of the shell, which make the last process in a pipeline the parent
8388  * of all the rest.)
8389  */
8390 static void
8391 evalpipe(union node *n, int flags)
8392 {
8393         struct job *jp;
8394         struct nodelist *lp;
8395         int pipelen;
8396         int prevfd;
8397         int pip[2];
8398
8399         TRACE(("evalpipe(0x%lx) called\n", (long)n));
8400         pipelen = 0;
8401         for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8402                 pipelen++;
8403         flags |= EV_EXIT;
8404         INT_OFF;
8405         jp = makejob(/*n,*/ pipelen);
8406         prevfd = -1;
8407         for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8408                 prehash(lp->n);
8409                 pip[1] = -1;
8410                 if (lp->next) {
8411                         if (pipe(pip) < 0) {
8412                                 close(prevfd);
8413                                 ash_msg_and_raise_error("pipe call failed");
8414                         }
8415                 }
8416                 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8417                         INT_ON;
8418                         if (pip[1] >= 0) {
8419                                 close(pip[0]);
8420                         }
8421                         if (prevfd > 0) {
8422                                 dup2(prevfd, 0);
8423                                 close(prevfd);
8424                         }
8425                         if (pip[1] > 1) {
8426                                 dup2(pip[1], 1);
8427                                 close(pip[1]);
8428                         }
8429                         evaltreenr(lp->n, flags);
8430                         /* never returns */
8431                 }
8432                 if (prevfd >= 0)
8433                         close(prevfd);
8434                 prevfd = pip[0];
8435                 /* Don't want to trigger debugging */
8436                 if (pip[1] != -1)
8437                         close(pip[1]);
8438         }
8439         if (n->npipe.pipe_backgnd == 0) {
8440                 exitstatus = waitforjob(jp);
8441                 TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
8442         }
8443         INT_ON;
8444 }
8445
8446 /*
8447  * Controls whether the shell is interactive or not.
8448  */
8449 static void
8450 setinteractive(int on)
8451 {
8452         static smallint is_interactive;
8453
8454         if (++on == is_interactive)
8455                 return;
8456         is_interactive = on;
8457         setsignal(SIGINT);
8458         setsignal(SIGQUIT);
8459         setsignal(SIGTERM);
8460 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8461         if (is_interactive > 1) {
8462                 /* Looks like they want an interactive shell */
8463                 static smallint did_banner;
8464
8465                 if (!did_banner) {
8466                         out1fmt(
8467                                 "\n\n"
8468                                 "%s built-in shell (ash)\n"
8469                                 "Enter 'help' for a list of built-in commands."
8470                                 "\n\n",
8471                                 bb_banner);
8472                         did_banner = 1;
8473                 }
8474         }
8475 #endif
8476 }
8477
8478 static void
8479 optschanged(void)
8480 {
8481 #if DEBUG
8482         opentrace();
8483 #endif
8484         setinteractive(iflag);
8485         setjobctl(mflag);
8486 #if ENABLE_FEATURE_EDITING_VI
8487         if (viflag)
8488                 line_input_state->flags |= VI_MODE;
8489         else
8490                 line_input_state->flags &= ~VI_MODE;
8491 #else
8492         viflag = 0; /* forcibly keep the option off */
8493 #endif
8494 }
8495
8496 static struct localvar *localvars;
8497
8498 /*
8499  * Called after a function returns.
8500  * Interrupts must be off.
8501  */
8502 static void
8503 poplocalvars(void)
8504 {
8505         struct localvar *lvp;
8506         struct var *vp;
8507
8508         while ((lvp = localvars) != NULL) {
8509                 localvars = lvp->next;
8510                 vp = lvp->vp;
8511                 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8512                 if (vp == NULL) {       /* $- saved */
8513                         memcpy(optlist, lvp->text, sizeof(optlist));
8514                         free((char*)lvp->text);
8515                         optschanged();
8516                 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8517                         unsetvar(vp->text);
8518                 } else {
8519                         if (vp->func)
8520                                 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8521                         if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8522                                 free((char*)vp->text);
8523                         vp->flags = lvp->flags;
8524                         vp->text = lvp->text;
8525                 }
8526                 free(lvp);
8527         }
8528 }
8529
8530 static int
8531 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8532 {
8533         volatile struct shparam saveparam;
8534         struct localvar *volatile savelocalvars;
8535         struct jmploc *volatile savehandler;
8536         struct jmploc jmploc;
8537         int e;
8538
8539         saveparam = shellparam;
8540         savelocalvars = localvars;
8541         e = setjmp(jmploc.loc);
8542         if (e) {
8543                 goto funcdone;
8544         }
8545         INT_OFF;
8546         savehandler = exception_handler;
8547         exception_handler = &jmploc;
8548         localvars = NULL;
8549         shellparam.malloced = 0;
8550         func->count++;
8551         funcnest++;
8552         INT_ON;
8553         shellparam.nparam = argc - 1;
8554         shellparam.p = argv + 1;
8555 #if ENABLE_ASH_GETOPTS
8556         shellparam.optind = 1;
8557         shellparam.optoff = -1;
8558 #endif
8559         evaltree(&func->n, flags & EV_TESTED);
8560  funcdone:
8561         INT_OFF;
8562         funcnest--;
8563         freefunc(func);
8564         poplocalvars();
8565         localvars = savelocalvars;
8566         freeparam(&shellparam);
8567         shellparam = saveparam;
8568         exception_handler = savehandler;
8569         INT_ON;
8570         evalskip &= ~SKIPFUNC;
8571         return e;
8572 }
8573
8574 #if ENABLE_ASH_CMDCMD
8575 static char **
8576 parse_command_args(char **argv, const char **path)
8577 {
8578         char *cp, c;
8579
8580         for (;;) {
8581                 cp = *++argv;
8582                 if (!cp)
8583                         return 0;
8584                 if (*cp++ != '-')
8585                         break;
8586                 c = *cp++;
8587                 if (!c)
8588                         break;
8589                 if (c == '-' && !*cp) {
8590                         argv++;
8591                         break;
8592                 }
8593                 do {
8594                         switch (c) {
8595                         case 'p':
8596                                 *path = bb_default_path;
8597                                 break;
8598                         default:
8599                                 /* run 'typecmd' for other options */
8600                                 return 0;
8601                         }
8602                         c = *cp++;
8603                 } while (c);
8604         }
8605         return argv;
8606 }
8607 #endif
8608
8609 /*
8610  * Make a variable a local variable.  When a variable is made local, it's
8611  * value and flags are saved in a localvar structure.  The saved values
8612  * will be restored when the shell function returns.  We handle the name
8613  * "-" as a special case.
8614  */
8615 static void
8616 mklocal(char *name)
8617 {
8618         struct localvar *lvp;
8619         struct var **vpp;
8620         struct var *vp;
8621
8622         INT_OFF;
8623         lvp = ckzalloc(sizeof(struct localvar));
8624         if (LONE_DASH(name)) {
8625                 char *p;
8626                 p = ckmalloc(sizeof(optlist));
8627                 lvp->text = memcpy(p, optlist, sizeof(optlist));
8628                 vp = NULL;
8629         } else {
8630                 char *eq;
8631
8632                 vpp = hashvar(name);
8633                 vp = *findvar(vpp, name);
8634                 eq = strchr(name, '=');
8635                 if (vp == NULL) {
8636                         if (eq)
8637                                 setvareq(name, VSTRFIXED);
8638                         else
8639                                 setvar(name, NULL, VSTRFIXED);
8640                         vp = *vpp;      /* the new variable */
8641                         lvp->flags = VUNSET;
8642                 } else {
8643                         lvp->text = vp->text;
8644                         lvp->flags = vp->flags;
8645                         vp->flags |= VSTRFIXED|VTEXTFIXED;
8646                         if (eq)
8647                                 setvareq(name, 0);
8648                 }
8649         }
8650         lvp->vp = vp;
8651         lvp->next = localvars;
8652         localvars = lvp;
8653         INT_ON;
8654 }
8655
8656 /*
8657  * The "local" command.
8658  */
8659 static int FAST_FUNC
8660 localcmd(int argc UNUSED_PARAM, char **argv)
8661 {
8662         char *name;
8663
8664         argv = argptr;
8665         while ((name = *argv++) != NULL) {
8666                 mklocal(name);
8667         }
8668         return 0;
8669 }
8670
8671 static int FAST_FUNC
8672 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8673 {
8674         return 1;
8675 }
8676
8677 static int FAST_FUNC
8678 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8679 {
8680         return 0;
8681 }
8682
8683 static int FAST_FUNC
8684 execcmd(int argc UNUSED_PARAM, char **argv)
8685 {
8686         if (argv[1]) {
8687                 iflag = 0;              /* exit on error */
8688                 mflag = 0;
8689                 optschanged();
8690                 shellexec(argv + 1, pathval(), 0);
8691         }
8692         return 0;
8693 }
8694
8695 /*
8696  * The return command.
8697  */
8698 static int FAST_FUNC
8699 returncmd(int argc UNUSED_PARAM, char **argv)
8700 {
8701         /*
8702          * If called outside a function, do what ksh does;
8703          * skip the rest of the file.
8704          */
8705         evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8706         return argv[1] ? number(argv[1]) : exitstatus;
8707 }
8708
8709 /* Forward declarations for builtintab[] */
8710 static int breakcmd(int, char **) FAST_FUNC;
8711 static int dotcmd(int, char **) FAST_FUNC;
8712 static int evalcmd(int, char **) FAST_FUNC;
8713 static int exitcmd(int, char **) FAST_FUNC;
8714 static int exportcmd(int, char **) FAST_FUNC;
8715 #if ENABLE_ASH_GETOPTS
8716 static int getoptscmd(int, char **) FAST_FUNC;
8717 #endif
8718 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8719 static int helpcmd(int, char **) FAST_FUNC;
8720 #endif
8721 #if ENABLE_SH_MATH_SUPPORT
8722 static int letcmd(int, char **) FAST_FUNC;
8723 #endif
8724 static int readcmd(int, char **) FAST_FUNC;
8725 static int setcmd(int, char **) FAST_FUNC;
8726 static int shiftcmd(int, char **) FAST_FUNC;
8727 static int timescmd(int, char **) FAST_FUNC;
8728 static int trapcmd(int, char **) FAST_FUNC;
8729 static int umaskcmd(int, char **) FAST_FUNC;
8730 static int unsetcmd(int, char **) FAST_FUNC;
8731 static int ulimitcmd(int, char **) FAST_FUNC;
8732
8733 #define BUILTIN_NOSPEC          "0"
8734 #define BUILTIN_SPECIAL         "1"
8735 #define BUILTIN_REGULAR         "2"
8736 #define BUILTIN_SPEC_REG        "3"
8737 #define BUILTIN_ASSIGN          "4"
8738 #define BUILTIN_SPEC_ASSG       "5"
8739 #define BUILTIN_REG_ASSG        "6"
8740 #define BUILTIN_SPEC_REG_ASSG   "7"
8741
8742 /* Stubs for calling non-FAST_FUNC's */
8743 #if ENABLE_ASH_BUILTIN_ECHO
8744 static int FAST_FUNC echocmd(int argc, char **argv)   { return echo_main(argc, argv); }
8745 #endif
8746 #if ENABLE_ASH_BUILTIN_PRINTF
8747 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8748 #endif
8749 #if ENABLE_ASH_BUILTIN_TEST
8750 static int FAST_FUNC testcmd(int argc, char **argv)   { return test_main(argc, argv); }
8751 #endif
8752
8753 /* Keep these in proper order since it is searched via bsearch() */
8754 static const struct builtincmd builtintab[] = {
8755         { BUILTIN_SPEC_REG      ".", dotcmd },
8756         { BUILTIN_SPEC_REG      ":", truecmd },
8757 #if ENABLE_ASH_BUILTIN_TEST
8758         { BUILTIN_REGULAR       "[", testcmd },
8759 #if ENABLE_ASH_BASH_COMPAT
8760         { BUILTIN_REGULAR       "[[", testcmd },
8761 #endif
8762 #endif
8763 #if ENABLE_ASH_ALIAS
8764         { BUILTIN_REG_ASSG      "alias", aliascmd },
8765 #endif
8766 #if JOBS
8767         { BUILTIN_REGULAR       "bg", fg_bgcmd },
8768 #endif
8769         { BUILTIN_SPEC_REG      "break", breakcmd },
8770         { BUILTIN_REGULAR       "cd", cdcmd },
8771         { BUILTIN_NOSPEC        "chdir", cdcmd },
8772 #if ENABLE_ASH_CMDCMD
8773         { BUILTIN_REGULAR       "command", commandcmd },
8774 #endif
8775         { BUILTIN_SPEC_REG      "continue", breakcmd },
8776 #if ENABLE_ASH_BUILTIN_ECHO
8777         { BUILTIN_REGULAR       "echo", echocmd },
8778 #endif
8779         { BUILTIN_SPEC_REG      "eval", evalcmd },
8780         { BUILTIN_SPEC_REG      "exec", execcmd },
8781         { BUILTIN_SPEC_REG      "exit", exitcmd },
8782         { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8783         { BUILTIN_REGULAR       "false", falsecmd },
8784 #if JOBS
8785         { BUILTIN_REGULAR       "fg", fg_bgcmd },
8786 #endif
8787 #if ENABLE_ASH_GETOPTS
8788         { BUILTIN_REGULAR       "getopts", getoptscmd },
8789 #endif
8790         { BUILTIN_NOSPEC        "hash", hashcmd },
8791 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8792         { BUILTIN_NOSPEC        "help", helpcmd },
8793 #endif
8794 #if JOBS
8795         { BUILTIN_REGULAR       "jobs", jobscmd },
8796         { BUILTIN_REGULAR       "kill", killcmd },
8797 #endif
8798 #if ENABLE_SH_MATH_SUPPORT
8799         { BUILTIN_NOSPEC        "let", letcmd },
8800 #endif
8801         { BUILTIN_ASSIGN        "local", localcmd },
8802 #if ENABLE_ASH_BUILTIN_PRINTF
8803         { BUILTIN_REGULAR       "printf", printfcmd },
8804 #endif
8805         { BUILTIN_NOSPEC        "pwd", pwdcmd },
8806         { BUILTIN_REGULAR       "read", readcmd },
8807         { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8808         { BUILTIN_SPEC_REG      "return", returncmd },
8809         { BUILTIN_SPEC_REG      "set", setcmd },
8810         { BUILTIN_SPEC_REG      "shift", shiftcmd },
8811         { BUILTIN_SPEC_REG      "source", dotcmd },
8812 #if ENABLE_ASH_BUILTIN_TEST
8813         { BUILTIN_REGULAR       "test", testcmd },
8814 #endif
8815         { BUILTIN_SPEC_REG      "times", timescmd },
8816         { BUILTIN_SPEC_REG      "trap", trapcmd },
8817         { BUILTIN_REGULAR       "true", truecmd },
8818         { BUILTIN_NOSPEC        "type", typecmd },
8819         { BUILTIN_NOSPEC        "ulimit", ulimitcmd },
8820         { BUILTIN_REGULAR       "umask", umaskcmd },
8821 #if ENABLE_ASH_ALIAS
8822         { BUILTIN_REGULAR       "unalias", unaliascmd },
8823 #endif
8824         { BUILTIN_SPEC_REG      "unset", unsetcmd },
8825         { BUILTIN_REGULAR       "wait", waitcmd },
8826 };
8827
8828 /* Should match the above table! */
8829 #define COMMANDCMD (builtintab + \
8830         2 + \
8831         1 * ENABLE_ASH_BUILTIN_TEST + \
8832         1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8833         1 * ENABLE_ASH_ALIAS + \
8834         1 * ENABLE_ASH_JOB_CONTROL + \
8835         3)
8836 #define EXECCMD (builtintab + \
8837         2 + \
8838         1 * ENABLE_ASH_BUILTIN_TEST + \
8839         1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8840         1 * ENABLE_ASH_ALIAS + \
8841         1 * ENABLE_ASH_JOB_CONTROL + \
8842         3 + \
8843         1 * ENABLE_ASH_CMDCMD + \
8844         1 + \
8845         ENABLE_ASH_BUILTIN_ECHO + \
8846         1)
8847
8848 /*
8849  * Search the table of builtin commands.
8850  */
8851 static struct builtincmd *
8852 find_builtin(const char *name)
8853 {
8854         struct builtincmd *bp;
8855
8856         bp = bsearch(
8857                 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8858                 pstrcmp
8859         );
8860         return bp;
8861 }
8862
8863 /*
8864  * Execute a simple command.
8865  */
8866 static int
8867 isassignment(const char *p)
8868 {
8869         const char *q = endofname(p);
8870         if (p == q)
8871                 return 0;
8872         return *q == '=';
8873 }
8874 static int FAST_FUNC
8875 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8876 {
8877         /* Preserve exitstatus of a previous possible redirection
8878          * as POSIX mandates */
8879         return back_exitstatus;
8880 }
8881 static void
8882 evalcommand(union node *cmd, int flags)
8883 {
8884         static const struct builtincmd null_bltin = {
8885                 "\0\0", bltincmd /* why three NULs? */
8886         };
8887         struct stackmark smark;
8888         union node *argp;
8889         struct arglist arglist;
8890         struct arglist varlist;
8891         char **argv;
8892         int argc;
8893         const struct strlist *sp;
8894         struct cmdentry cmdentry;
8895         struct job *jp;
8896         char *lastarg;
8897         const char *path;
8898         int spclbltin;
8899         int status;
8900         char **nargv;
8901         struct builtincmd *bcmd;
8902         smallint cmd_is_exec;
8903         smallint pseudovarflag = 0;
8904
8905         /* First expand the arguments. */
8906         TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8907         setstackmark(&smark);
8908         back_exitstatus = 0;
8909
8910         cmdentry.cmdtype = CMDBUILTIN;
8911         cmdentry.u.cmd = &null_bltin;
8912         varlist.lastp = &varlist.list;
8913         *varlist.lastp = NULL;
8914         arglist.lastp = &arglist.list;
8915         *arglist.lastp = NULL;
8916
8917         argc = 0;
8918         if (cmd->ncmd.args) {
8919                 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8920                 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8921         }
8922
8923         for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8924                 struct strlist **spp;
8925
8926                 spp = arglist.lastp;
8927                 if (pseudovarflag && isassignment(argp->narg.text))
8928                         expandarg(argp, &arglist, EXP_VARTILDE);
8929                 else
8930                         expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8931
8932                 for (sp = *spp; sp; sp = sp->next)
8933                         argc++;
8934         }
8935
8936         argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8937         for (sp = arglist.list; sp; sp = sp->next) {
8938                 TRACE(("evalcommand arg: %s\n", sp->text));
8939                 *nargv++ = sp->text;
8940         }
8941         *nargv = NULL;
8942
8943         lastarg = NULL;
8944         if (iflag && funcnest == 0 && argc > 0)
8945                 lastarg = nargv[-1];
8946
8947         preverrout_fd = 2;
8948         expredir(cmd->ncmd.redirect);
8949         status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
8950
8951         path = vpath.text;
8952         for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8953                 struct strlist **spp;
8954                 char *p;
8955
8956                 spp = varlist.lastp;
8957                 expandarg(argp, &varlist, EXP_VARTILDE);
8958
8959                 /*
8960                  * Modify the command lookup path, if a PATH= assignment
8961                  * is present
8962                  */
8963                 p = (*spp)->text;
8964                 if (varequal(p, path))
8965                         path = p;
8966         }
8967
8968         /* Print the command if xflag is set. */
8969         if (xflag) {
8970                 int n;
8971                 const char *p = " %s";
8972
8973                 p++;
8974                 fdprintf(preverrout_fd, p, expandstr(ps4val()));
8975
8976                 sp = varlist.list;
8977                 for (n = 0; n < 2; n++) {
8978                         while (sp) {
8979                                 fdprintf(preverrout_fd, p, sp->text);
8980                                 sp = sp->next;
8981                                 if (*p == '%') {
8982                                         p--;
8983                                 }
8984                         }
8985                         sp = arglist.list;
8986                 }
8987                 safe_write(preverrout_fd, "\n", 1);
8988         }
8989
8990         cmd_is_exec = 0;
8991         spclbltin = -1;
8992
8993         /* Now locate the command. */
8994         if (argc) {
8995                 const char *oldpath;
8996                 int cmd_flag = DO_ERR;
8997
8998                 path += 5;
8999                 oldpath = path;
9000                 for (;;) {
9001                         find_command(argv[0], &cmdentry, cmd_flag, path);
9002                         if (cmdentry.cmdtype == CMDUNKNOWN) {
9003                                 flush_stderr();
9004                                 status = 127;
9005                                 goto bail;
9006                         }
9007
9008                         /* implement bltin and command here */
9009                         if (cmdentry.cmdtype != CMDBUILTIN)
9010                                 break;
9011                         if (spclbltin < 0)
9012                                 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9013                         if (cmdentry.u.cmd == EXECCMD)
9014                                 cmd_is_exec = 1;
9015 #if ENABLE_ASH_CMDCMD
9016                         if (cmdentry.u.cmd == COMMANDCMD) {
9017                                 path = oldpath;
9018                                 nargv = parse_command_args(argv, &path);
9019                                 if (!nargv)
9020                                         break;
9021                                 argc -= nargv - argv;
9022                                 argv = nargv;
9023                                 cmd_flag |= DO_NOFUNC;
9024                         } else
9025 #endif
9026                                 break;
9027                 }
9028         }
9029
9030         if (status) {
9031                 /* We have a redirection error. */
9032                 if (spclbltin > 0)
9033                         raise_exception(EXERROR);
9034  bail:
9035                 exitstatus = status;
9036                 goto out;
9037         }
9038
9039         /* Execute the command. */
9040         switch (cmdentry.cmdtype) {
9041         default:
9042
9043 #if ENABLE_FEATURE_SH_NOFORK
9044 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9045  * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9046         {
9047                 /* find_command() encodes applet_no as (-2 - applet_no) */
9048                 int applet_no = (- cmdentry.u.index - 2);
9049                 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9050                         listsetvar(varlist.list, VEXPORT|VSTACK);
9051                         /* run <applet>_main() */
9052                         exitstatus = run_nofork_applet(applet_no, argv);
9053                         break;
9054                 }
9055         }
9056 #endif
9057                 /* Fork off a child process if necessary. */
9058                 if (!(flags & EV_EXIT) || trap[0]) {
9059                         INT_OFF;
9060                         jp = makejob(/*cmd,*/ 1);
9061                         if (forkshell(jp, cmd, FORK_FG) != 0) {
9062                                 exitstatus = waitforjob(jp);
9063                                 INT_ON;
9064                                 TRACE(("forked child exited with %d\n", exitstatus));
9065                                 break;
9066                         }
9067                         FORCE_INT_ON;
9068                 }
9069                 listsetvar(varlist.list, VEXPORT|VSTACK);
9070                 shellexec(argv, path, cmdentry.u.index);
9071                 /* NOTREACHED */
9072
9073         case CMDBUILTIN:
9074                 cmdenviron = varlist.list;
9075                 if (cmdenviron) {
9076                         struct strlist *list = cmdenviron;
9077                         int i = VNOSET;
9078                         if (spclbltin > 0 || argc == 0) {
9079                                 i = 0;
9080                                 if (cmd_is_exec && argc > 1)
9081                                         i = VEXPORT;
9082                         }
9083                         listsetvar(list, i);
9084                 }
9085                 /* Tight loop with builtins only:
9086                  * "while kill -0 $child; do true; done"
9087                  * will never exit even if $child died, unless we do this
9088                  * to reap the zombie and make kill detect that it's gone: */
9089                 dowait(DOWAIT_NONBLOCK, NULL);
9090
9091                 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9092                         int exit_status;
9093                         int i = exception_type;
9094                         if (i == EXEXIT)
9095                                 goto raise;
9096                         exit_status = 2;
9097                         if (i == EXINT)
9098                                 exit_status = 128 + SIGINT;
9099                         if (i == EXSIG)
9100                                 exit_status = 128 + pendingsig;
9101                         exitstatus = exit_status;
9102                         if (i == EXINT || spclbltin > 0) {
9103  raise:
9104                                 longjmp(exception_handler->loc, 1);
9105                         }
9106                         FORCE_INT_ON;
9107                 }
9108                 break;
9109
9110         case CMDFUNCTION:
9111                 listsetvar(varlist.list, 0);
9112                 /* See above for the rationale */
9113                 dowait(DOWAIT_NONBLOCK, NULL);
9114                 if (evalfun(cmdentry.u.func, argc, argv, flags))
9115                         goto raise;
9116                 break;
9117         }
9118
9119  out:
9120         popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9121         if (lastarg) {
9122                 /* dsl: I think this is intended to be used to support
9123                  * '_' in 'vi' command mode during line editing...
9124                  * However I implemented that within libedit itself.
9125                  */
9126                 setvar("_", lastarg, 0);
9127         }
9128         popstackmark(&smark);
9129 }
9130
9131 static int
9132 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9133 {
9134         char *volatile savecmdname;
9135         struct jmploc *volatile savehandler;
9136         struct jmploc jmploc;
9137         int i;
9138
9139         savecmdname = commandname;
9140         i = setjmp(jmploc.loc);
9141         if (i)
9142                 goto cmddone;
9143         savehandler = exception_handler;
9144         exception_handler = &jmploc;
9145         commandname = argv[0];
9146         argptr = argv + 1;
9147         optptr = NULL;                  /* initialize nextopt */
9148         exitstatus = (*cmd->builtin)(argc, argv);
9149         flush_stdout_stderr();
9150  cmddone:
9151         exitstatus |= ferror(stdout);
9152         clearerr(stdout);
9153         commandname = savecmdname;
9154 //      exsig = 0;
9155         exception_handler = savehandler;
9156
9157         return i;
9158 }
9159
9160 static int
9161 goodname(const char *p)
9162 {
9163         return !*endofname(p);
9164 }
9165
9166
9167 /*
9168  * Search for a command.  This is called before we fork so that the
9169  * location of the command will be available in the parent as well as
9170  * the child.  The check for "goodname" is an overly conservative
9171  * check that the name will not be subject to expansion.
9172  */
9173 static void
9174 prehash(union node *n)
9175 {
9176         struct cmdentry entry;
9177
9178         if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9179                 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9180 }
9181
9182
9183 /* ============ Builtin commands
9184  *
9185  * Builtin commands whose functions are closely tied to evaluation
9186  * are implemented here.
9187  */
9188
9189 /*
9190  * Handle break and continue commands.  Break, continue, and return are
9191  * all handled by setting the evalskip flag.  The evaluation routines
9192  * above all check this flag, and if it is set they start skipping
9193  * commands rather than executing them.  The variable skipcount is
9194  * the number of loops to break/continue, or the number of function
9195  * levels to return.  (The latter is always 1.)  It should probably
9196  * be an error to break out of more loops than exist, but it isn't
9197  * in the standard shell so we don't make it one here.
9198  */
9199 static int FAST_FUNC
9200 breakcmd(int argc UNUSED_PARAM, char **argv)
9201 {
9202         int n = argv[1] ? number(argv[1]) : 1;
9203
9204         if (n <= 0)
9205                 ash_msg_and_raise_error(illnum, argv[1]);
9206         if (n > loopnest)
9207                 n = loopnest;
9208         if (n > 0) {
9209                 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9210                 skipcount = n;
9211         }
9212         return 0;
9213 }
9214
9215
9216 /* ============ input.c
9217  *
9218  * This implements the input routines used by the parser.
9219  */
9220
9221 enum {
9222         INPUT_PUSH_FILE = 1,
9223         INPUT_NOFILE_OK = 2,
9224 };
9225
9226 static smallint checkkwd;
9227 /* values of checkkwd variable */
9228 #define CHKALIAS        0x1
9229 #define CHKKWD          0x2
9230 #define CHKNL           0x4
9231
9232 /*
9233  * Push a string back onto the input at this current parsefile level.
9234  * We handle aliases this way.
9235  */
9236 #if !ENABLE_ASH_ALIAS
9237 #define pushstring(s, ap) pushstring(s)
9238 #endif
9239 static void
9240 pushstring(char *s, struct alias *ap)
9241 {
9242         struct strpush *sp;
9243         int len;
9244
9245         len = strlen(s);
9246         INT_OFF;
9247         if (g_parsefile->strpush) {
9248                 sp = ckzalloc(sizeof(*sp));
9249                 sp->prev = g_parsefile->strpush;
9250         } else {
9251                 sp = &(g_parsefile->basestrpush);
9252         }
9253         g_parsefile->strpush = sp;
9254         sp->prev_string = g_parsefile->next_to_pgetc;
9255         sp->prev_left_in_line = g_parsefile->left_in_line;
9256 #if ENABLE_ASH_ALIAS
9257         sp->ap = ap;
9258         if (ap) {
9259                 ap->flag |= ALIASINUSE;
9260                 sp->string = s;
9261         }
9262 #endif
9263         g_parsefile->next_to_pgetc = s;
9264         g_parsefile->left_in_line = len;
9265         INT_ON;
9266 }
9267
9268 static void
9269 popstring(void)
9270 {
9271         struct strpush *sp = g_parsefile->strpush;
9272
9273         INT_OFF;
9274 #if ENABLE_ASH_ALIAS
9275         if (sp->ap) {
9276                 if (g_parsefile->next_to_pgetc[-1] == ' '
9277                  || g_parsefile->next_to_pgetc[-1] == '\t'
9278                 ) {
9279                         checkkwd |= CHKALIAS;
9280                 }
9281                 if (sp->string != sp->ap->val) {
9282                         free(sp->string);
9283                 }
9284                 sp->ap->flag &= ~ALIASINUSE;
9285                 if (sp->ap->flag & ALIASDEAD) {
9286                         unalias(sp->ap->name);
9287                 }
9288         }
9289 #endif
9290         g_parsefile->next_to_pgetc = sp->prev_string;
9291         g_parsefile->left_in_line = sp->prev_left_in_line;
9292         g_parsefile->strpush = sp->prev;
9293         if (sp != &(g_parsefile->basestrpush))
9294                 free(sp);
9295         INT_ON;
9296 }
9297
9298 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9299 //it peeks whether it is &>, and then pushes back both chars.
9300 //This function needs to save last *next_to_pgetc to buf[0]
9301 //to make two pungetc() reliable. Currently,
9302 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9303 static int
9304 preadfd(void)
9305 {
9306         int nr;
9307         char *buf = g_parsefile->buf;
9308
9309         g_parsefile->next_to_pgetc = buf;
9310 #if ENABLE_FEATURE_EDITING
9311  retry:
9312         if (!iflag || g_parsefile->fd != STDIN_FILENO)
9313                 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9314         else {
9315 #if ENABLE_FEATURE_TAB_COMPLETION
9316                 line_input_state->path_lookup = pathval();
9317 #endif
9318                 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9319                 if (nr == 0) {
9320                         /* Ctrl+C pressed */
9321                         if (trap[SIGINT]) {
9322                                 buf[0] = '\n';
9323                                 buf[1] = '\0';
9324                                 raise(SIGINT);
9325                                 return 1;
9326                         }
9327                         goto retry;
9328                 }
9329                 if (nr < 0 && errno == 0) {
9330                         /* Ctrl+D pressed */
9331                         nr = 0;
9332                 }
9333         }
9334 #else
9335         nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9336 #endif
9337
9338 #if 0
9339 /* nonblock_safe_read() handles this problem */
9340         if (nr < 0) {
9341                 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9342                         int flags = fcntl(0, F_GETFL);
9343                         if (flags >= 0 && (flags & O_NONBLOCK)) {
9344                                 flags &= ~O_NONBLOCK;
9345                                 if (fcntl(0, F_SETFL, flags) >= 0) {
9346                                         out2str("sh: turning off NDELAY mode\n");
9347                                         goto retry;
9348                                 }
9349                         }
9350                 }
9351         }
9352 #endif
9353         return nr;
9354 }
9355
9356 /*
9357  * Refill the input buffer and return the next input character:
9358  *
9359  * 1) If a string was pushed back on the input, pop it;
9360  * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9361  *    or we are reading from a string so we can't refill the buffer,
9362  *    return EOF.
9363  * 3) If there is more stuff in this buffer, use it else call read to fill it.
9364  * 4) Process input up to the next newline, deleting nul characters.
9365  */
9366 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9367 #define pgetc_debug(...) ((void)0)
9368 /*
9369  * NB: due to SIT(c) internals (syntax_index_table[] vector),
9370  * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9371  * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9372  * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9373  */
9374 static int
9375 preadbuffer(void)
9376 {
9377         char *q;
9378         int more;
9379
9380         while (g_parsefile->strpush) {
9381 #if ENABLE_ASH_ALIAS
9382                 if (g_parsefile->left_in_line == -1
9383                  && g_parsefile->strpush->ap
9384                  && g_parsefile->next_to_pgetc[-1] != ' '
9385                  && g_parsefile->next_to_pgetc[-1] != '\t'
9386                 ) {
9387                         pgetc_debug("preadbuffer PEOA");
9388                         return PEOA;
9389                 }
9390 #endif
9391                 popstring();
9392                 /* try "pgetc" now: */
9393                 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9394                                 g_parsefile->left_in_line,
9395                                 g_parsefile->next_to_pgetc,
9396                                 g_parsefile->next_to_pgetc);
9397                 if (--g_parsefile->left_in_line >= 0)
9398                         return (unsigned char)(*g_parsefile->next_to_pgetc++);
9399         }
9400         /* on both branches above g_parsefile->left_in_line < 0.
9401          * "pgetc" needs refilling.
9402          */
9403
9404         /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9405          * pungetc() may increment it a few times.
9406          * Assuming it won't increment it to less than -90.
9407          */
9408         if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9409                 pgetc_debug("preadbuffer PEOF1");
9410                 /* even in failure keep left_in_line and next_to_pgetc
9411                  * in lock step, for correct multi-layer pungetc.
9412                  * left_in_line was decremented before preadbuffer(),
9413                  * must inc next_to_pgetc: */
9414                 g_parsefile->next_to_pgetc++;
9415                 return PEOF;
9416         }
9417
9418         more = g_parsefile->left_in_buffer;
9419         if (more <= 0) {
9420                 flush_stdout_stderr();
9421  again:
9422                 more = preadfd();
9423                 if (more <= 0) {
9424                         /* don't try reading again */
9425                         g_parsefile->left_in_line = -99;
9426                         pgetc_debug("preadbuffer PEOF2");
9427                         g_parsefile->next_to_pgetc++;
9428                         return PEOF;
9429                 }
9430         }
9431
9432         /* Find out where's the end of line.
9433          * Set g_parsefile->left_in_line
9434          * and g_parsefile->left_in_buffer acordingly.
9435          * NUL chars are deleted.
9436          */
9437         q = g_parsefile->next_to_pgetc;
9438         for (;;) {
9439                 char c;
9440
9441                 more--;
9442
9443                 c = *q;
9444                 if (c == '\0') {
9445                         memmove(q, q + 1, more);
9446                 } else {
9447                         q++;
9448                         if (c == '\n') {
9449                                 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9450                                 break;
9451                         }
9452                 }
9453
9454                 if (more <= 0) {
9455                         g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9456                         if (g_parsefile->left_in_line < 0)
9457                                 goto again;
9458                         break;
9459                 }
9460         }
9461         g_parsefile->left_in_buffer = more;
9462
9463         if (vflag) {
9464                 char save = *q;
9465                 *q = '\0';
9466                 out2str(g_parsefile->next_to_pgetc);
9467                 *q = save;
9468         }
9469
9470         pgetc_debug("preadbuffer at %d:%p'%s'",
9471                         g_parsefile->left_in_line,
9472                         g_parsefile->next_to_pgetc,
9473                         g_parsefile->next_to_pgetc);
9474         return signed_char2int(*g_parsefile->next_to_pgetc++);
9475 }
9476
9477 #define pgetc_as_macro() \
9478         (--g_parsefile->left_in_line >= 0 \
9479         ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9480         : preadbuffer() \
9481         )
9482
9483 static int
9484 pgetc(void)
9485 {
9486         pgetc_debug("pgetc_fast at %d:%p'%s'",
9487                         g_parsefile->left_in_line,
9488                         g_parsefile->next_to_pgetc,
9489                         g_parsefile->next_to_pgetc);
9490         return pgetc_as_macro();
9491 }
9492
9493 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9494 #define pgetc_fast() pgetc()
9495 #else
9496 #define pgetc_fast() pgetc_as_macro()
9497 #endif
9498
9499 /*
9500  * Same as pgetc(), but ignores PEOA.
9501  */
9502 #if ENABLE_ASH_ALIAS
9503 static int
9504 pgetc2(void)
9505 {
9506         int c;
9507         do {
9508                 pgetc_debug("pgetc_fast at %d:%p'%s'",
9509                                 g_parsefile->left_in_line,
9510                                 g_parsefile->next_to_pgetc,
9511                                 g_parsefile->next_to_pgetc);
9512                 c = pgetc_fast();
9513         } while (c == PEOA);
9514         return c;
9515 }
9516 #else
9517 #define pgetc2() pgetc()
9518 #endif
9519
9520 /*
9521  * Read a line from the script.
9522  */
9523 static char *
9524 pfgets(char *line, int len)
9525 {
9526         char *p = line;
9527         int nleft = len;
9528         int c;
9529
9530         while (--nleft > 0) {
9531                 c = pgetc2();
9532                 if (c == PEOF) {
9533                         if (p == line)
9534                                 return NULL;
9535                         break;
9536                 }
9537                 *p++ = c;
9538                 if (c == '\n')
9539                         break;
9540         }
9541         *p = '\0';
9542         return line;
9543 }
9544
9545 /*
9546  * Undo the last call to pgetc.  Only one character may be pushed back.
9547  * PEOF may be pushed back.
9548  */
9549 static void
9550 pungetc(void)
9551 {
9552         g_parsefile->left_in_line++;
9553         g_parsefile->next_to_pgetc--;
9554         pgetc_debug("pushed back to %d:%p'%s'",
9555                         g_parsefile->left_in_line,
9556                         g_parsefile->next_to_pgetc,
9557                         g_parsefile->next_to_pgetc);
9558 }
9559
9560 /*
9561  * To handle the "." command, a stack of input files is used.  Pushfile
9562  * adds a new entry to the stack and popfile restores the previous level.
9563  */
9564 static void
9565 pushfile(void)
9566 {
9567         struct parsefile *pf;
9568
9569         pf = ckzalloc(sizeof(*pf));
9570         pf->prev = g_parsefile;
9571         pf->fd = -1;
9572         /*pf->strpush = NULL; - ckzalloc did it */
9573         /*pf->basestrpush.prev = NULL;*/
9574         g_parsefile = pf;
9575 }
9576
9577 static void
9578 popfile(void)
9579 {
9580         struct parsefile *pf = g_parsefile;
9581
9582         INT_OFF;
9583         if (pf->fd >= 0)
9584                 close(pf->fd);
9585         free(pf->buf);
9586         while (pf->strpush)
9587                 popstring();
9588         g_parsefile = pf->prev;
9589         free(pf);
9590         INT_ON;
9591 }
9592
9593 /*
9594  * Return to top level.
9595  */
9596 static void
9597 popallfiles(void)
9598 {
9599         while (g_parsefile != &basepf)
9600                 popfile();
9601 }
9602
9603 /*
9604  * Close the file(s) that the shell is reading commands from.  Called
9605  * after a fork is done.
9606  */
9607 static void
9608 closescript(void)
9609 {
9610         popallfiles();
9611         if (g_parsefile->fd > 0) {
9612                 close(g_parsefile->fd);
9613                 g_parsefile->fd = 0;
9614         }
9615 }
9616
9617 /*
9618  * Like setinputfile, but takes an open file descriptor.  Call this with
9619  * interrupts off.
9620  */
9621 static void
9622 setinputfd(int fd, int push)
9623 {
9624         close_on_exec_on(fd);
9625         if (push) {
9626                 pushfile();
9627                 g_parsefile->buf = NULL;
9628         }
9629         g_parsefile->fd = fd;
9630         if (g_parsefile->buf == NULL)
9631                 g_parsefile->buf = ckmalloc(IBUFSIZ);
9632         g_parsefile->left_in_buffer = 0;
9633         g_parsefile->left_in_line = 0;
9634         g_parsefile->linno = 1;
9635 }
9636
9637 /*
9638  * Set the input to take input from a file.  If push is set, push the
9639  * old input onto the stack first.
9640  */
9641 static int
9642 setinputfile(const char *fname, int flags)
9643 {
9644         int fd;
9645         int fd2;
9646
9647         INT_OFF;
9648         fd = open(fname, O_RDONLY);
9649         if (fd < 0) {
9650                 if (flags & INPUT_NOFILE_OK)
9651                         goto out;
9652                 ash_msg_and_raise_error("can't open '%s'", fname);
9653         }
9654         if (fd < 10) {
9655                 fd2 = copyfd(fd, 10);
9656                 close(fd);
9657                 if (fd2 < 0)
9658                         ash_msg_and_raise_error("out of file descriptors");
9659                 fd = fd2;
9660         }
9661         setinputfd(fd, flags & INPUT_PUSH_FILE);
9662  out:
9663         INT_ON;
9664         return fd;
9665 }
9666
9667 /*
9668  * Like setinputfile, but takes input from a string.
9669  */
9670 static void
9671 setinputstring(char *string)
9672 {
9673         INT_OFF;
9674         pushfile();
9675         g_parsefile->next_to_pgetc = string;
9676         g_parsefile->left_in_line = strlen(string);
9677         g_parsefile->buf = NULL;
9678         g_parsefile->linno = 1;
9679         INT_ON;
9680 }
9681
9682
9683 /* ============ mail.c
9684  *
9685  * Routines to check for mail.
9686  */
9687
9688 #if ENABLE_ASH_MAIL
9689
9690 #define MAXMBOXES 10
9691
9692 /* times of mailboxes */
9693 static time_t mailtime[MAXMBOXES];
9694 /* Set if MAIL or MAILPATH is changed. */
9695 static smallint mail_var_path_changed;
9696
9697 /*
9698  * Print appropriate message(s) if mail has arrived.
9699  * If mail_var_path_changed is set,
9700  * then the value of MAIL has mail_var_path_changed,
9701  * so we just update the values.
9702  */
9703 static void
9704 chkmail(void)
9705 {
9706         const char *mpath;
9707         char *p;
9708         char *q;
9709         time_t *mtp;
9710         struct stackmark smark;
9711         struct stat statb;
9712
9713         setstackmark(&smark);
9714         mpath = mpathset() ? mpathval() : mailval();
9715         for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9716                 p = path_advance(&mpath, nullstr);
9717                 if (p == NULL)
9718                         break;
9719                 if (*p == '\0')
9720                         continue;
9721                 for (q = p; *q; q++)
9722                         continue;
9723 #if DEBUG
9724                 if (q[-1] != '/')
9725                         abort();
9726 #endif
9727                 q[-1] = '\0';                   /* delete trailing '/' */
9728                 if (stat(p, &statb) < 0) {
9729                         *mtp = 0;
9730                         continue;
9731                 }
9732                 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9733                         fprintf(
9734                                 stderr, snlfmt,
9735                                 pathopt ? pathopt : "you have mail"
9736                         );
9737                 }
9738                 *mtp = statb.st_mtime;
9739         }
9740         mail_var_path_changed = 0;
9741         popstackmark(&smark);
9742 }
9743
9744 static void FAST_FUNC
9745 changemail(const char *val UNUSED_PARAM)
9746 {
9747         mail_var_path_changed = 1;
9748 }
9749
9750 #endif /* ASH_MAIL */
9751
9752
9753 /* ============ ??? */
9754
9755 /*
9756  * Set the shell parameters.
9757  */
9758 static void
9759 setparam(char **argv)
9760 {
9761         char **newparam;
9762         char **ap;
9763         int nparam;
9764
9765         for (nparam = 0; argv[nparam]; nparam++)
9766                 continue;
9767         ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9768         while (*argv) {
9769                 *ap++ = ckstrdup(*argv++);
9770         }
9771         *ap = NULL;
9772         freeparam(&shellparam);
9773         shellparam.malloced = 1;
9774         shellparam.nparam = nparam;
9775         shellparam.p = newparam;
9776 #if ENABLE_ASH_GETOPTS
9777         shellparam.optind = 1;
9778         shellparam.optoff = -1;
9779 #endif
9780 }
9781
9782 /*
9783  * Process shell options.  The global variable argptr contains a pointer
9784  * to the argument list; we advance it past the options.
9785  *
9786  * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9787  * For a non-interactive shell, an error condition encountered
9788  * by a special built-in ... shall cause the shell to write a diagnostic message
9789  * to standard error and exit as shown in the following table:
9790  * Error                                           Special Built-In
9791  * ...
9792  * Utility syntax error (option or operand error)  Shall exit
9793  * ...
9794  * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9795  * we see that bash does not do that (set "finishes" with error code 1 instead,
9796  * and shell continues), and people rely on this behavior!
9797  * Testcase:
9798  * set -o barfoo 2>/dev/null
9799  * echo $?
9800  *
9801  * Oh well. Let's mimic that.
9802  */
9803 static int
9804 plus_minus_o(char *name, int val)
9805 {
9806         int i;
9807
9808         if (name) {
9809                 for (i = 0; i < NOPTS; i++) {
9810                         if (strcmp(name, optnames(i)) == 0) {
9811                                 optlist[i] = val;
9812                                 return 0;
9813                         }
9814                 }
9815                 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9816                 return 1;
9817         }
9818         for (i = 0; i < NOPTS; i++) {
9819                 if (val) {
9820                         out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9821                 } else {
9822                         out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9823                 }
9824         }
9825         return 0;
9826 }
9827 static void
9828 setoption(int flag, int val)
9829 {
9830         int i;
9831
9832         for (i = 0; i < NOPTS; i++) {
9833                 if (optletters(i) == flag) {
9834                         optlist[i] = val;
9835                         return;
9836                 }
9837         }
9838         ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9839         /* NOTREACHED */
9840 }
9841 static int
9842 options(int cmdline)
9843 {
9844         char *p;
9845         int val;
9846         int c;
9847
9848         if (cmdline)
9849                 minusc = NULL;
9850         while ((p = *argptr) != NULL) {
9851                 c = *p++;
9852                 if (c != '-' && c != '+')
9853                         break;
9854                 argptr++;
9855                 val = 0; /* val = 0 if c == '+' */
9856                 if (c == '-') {
9857                         val = 1;
9858                         if (p[0] == '\0' || LONE_DASH(p)) {
9859                                 if (!cmdline) {
9860                                         /* "-" means turn off -x and -v */
9861                                         if (p[0] == '\0')
9862                                                 xflag = vflag = 0;
9863                                         /* "--" means reset params */
9864                                         else if (*argptr == NULL)
9865                                                 setparam(argptr);
9866                                 }
9867                                 break;    /* "-" or  "--" terminates options */
9868                         }
9869                 }
9870                 /* first char was + or - */
9871                 while ((c = *p++) != '\0') {
9872                         /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9873                         if (c == 'c' && cmdline) {
9874                                 minusc = p;     /* command is after shell args */
9875                         } else if (c == 'o') {
9876                                 if (plus_minus_o(*argptr, val)) {
9877                                         /* it already printed err message */
9878                                         return 1; /* error */
9879                                 }
9880                                 if (*argptr)
9881                                         argptr++;
9882                         } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9883                                 isloginsh = 1;
9884                         /* bash does not accept +-login, we also won't */
9885                         } else if (cmdline && val && (c == '-')) { /* long options */
9886                                 if (strcmp(p, "login") == 0)
9887                                         isloginsh = 1;
9888                                 break;
9889                         } else {
9890                                 setoption(c, val);
9891                         }
9892                 }
9893         }
9894         return 0;
9895 }
9896
9897 /*
9898  * The shift builtin command.
9899  */
9900 static int FAST_FUNC
9901 shiftcmd(int argc UNUSED_PARAM, char **argv)
9902 {
9903         int n;
9904         char **ap1, **ap2;
9905
9906         n = 1;
9907         if (argv[1])
9908                 n = number(argv[1]);
9909         if (n > shellparam.nparam)
9910                 n = 0; /* bash compat, was = shellparam.nparam; */
9911         INT_OFF;
9912         shellparam.nparam -= n;
9913         for (ap1 = shellparam.p; --n >= 0; ap1++) {
9914                 if (shellparam.malloced)
9915                         free(*ap1);
9916         }
9917         ap2 = shellparam.p;
9918         while ((*ap2++ = *ap1++) != NULL)
9919                 continue;
9920 #if ENABLE_ASH_GETOPTS
9921         shellparam.optind = 1;
9922         shellparam.optoff = -1;
9923 #endif
9924         INT_ON;
9925         return 0;
9926 }
9927
9928 /*
9929  * POSIX requires that 'set' (but not export or readonly) output the
9930  * variables in lexicographic order - by the locale's collating order (sigh).
9931  * Maybe we could keep them in an ordered balanced binary tree
9932  * instead of hashed lists.
9933  * For now just roll 'em through qsort for printing...
9934  */
9935 static int
9936 showvars(const char *sep_prefix, int on, int off)
9937 {
9938         const char *sep;
9939         char **ep, **epend;
9940
9941         ep = listvars(on, off, &epend);
9942         qsort(ep, epend - ep, sizeof(char *), vpcmp);
9943
9944         sep = *sep_prefix ? " " : sep_prefix;
9945
9946         for (; ep < epend; ep++) {
9947                 const char *p;
9948                 const char *q;
9949
9950                 p = strchrnul(*ep, '=');
9951                 q = nullstr;
9952                 if (*p)
9953                         q = single_quote(++p);
9954                 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9955         }
9956         return 0;
9957 }
9958
9959 /*
9960  * The set command builtin.
9961  */
9962 static int FAST_FUNC
9963 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9964 {
9965         int retval;
9966
9967         if (!argv[1])
9968                 return showvars(nullstr, 0, VUNSET);
9969         INT_OFF;
9970         retval = 1;
9971         if (!options(0)) { /* if no parse error... */
9972                 retval = 0;
9973                 optschanged();
9974                 if (*argptr != NULL) {
9975                         setparam(argptr);
9976                 }
9977         }
9978         INT_ON;
9979         return retval;
9980 }
9981
9982 #if ENABLE_ASH_RANDOM_SUPPORT
9983 static void FAST_FUNC
9984 change_random(const char *value)
9985 {
9986         /* Galois LFSR parameter */
9987         /* Taps at 32 31 29 1: */
9988         enum { MASK = 0x8000000b };
9989         /* Another example - taps at 32 31 30 10: */
9990         /* MASK = 0x00400007 */
9991
9992         if (value == NULL) {
9993                 /* "get", generate */
9994                 uint32_t t;
9995
9996                 /* LCG has period of 2^32 and alternating lowest bit */
9997                 random_LCG = 1664525 * random_LCG + 1013904223;
9998                 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
9999                 t = (random_galois_LFSR << 1);
10000                 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10001                         t ^= MASK;
10002                 random_galois_LFSR = t;
10003                 /* Both are weak, combining them gives better randomness
10004                  * and ~2^64 period. & 0x7fff is probably bash compat
10005                  * for $RANDOM range. Combining with subtraction is
10006                  * just for fun. + and ^ would work equally well. */
10007                 t = (t - random_LCG) & 0x7fff;
10008                 /* set without recursion */
10009                 setvar(vrandom.text, utoa(t), VNOFUNC);
10010                 vrandom.flags &= ~VNOFUNC;
10011         } else {
10012                 /* set/reset */
10013                 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
10014         }
10015 }
10016 #endif
10017
10018 #if ENABLE_ASH_GETOPTS
10019 static int
10020 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10021 {
10022         char *p, *q;
10023         char c = '?';
10024         int done = 0;
10025         int err = 0;
10026         char s[12];
10027         char **optnext;
10028
10029         if (*param_optind < 1)
10030                 return 1;
10031         optnext = optfirst + *param_optind - 1;
10032
10033         if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10034                 p = NULL;
10035         else
10036                 p = optnext[-1] + *optoff;
10037         if (p == NULL || *p == '\0') {
10038                 /* Current word is done, advance */
10039                 p = *optnext;
10040                 if (p == NULL || *p != '-' || *++p == '\0') {
10041  atend:
10042                         p = NULL;
10043                         done = 1;
10044                         goto out;
10045                 }
10046                 optnext++;
10047                 if (LONE_DASH(p))        /* check for "--" */
10048                         goto atend;
10049         }
10050
10051         c = *p++;
10052         for (q = optstr; *q != c;) {
10053                 if (*q == '\0') {
10054                         if (optstr[0] == ':') {
10055                                 s[0] = c;
10056                                 s[1] = '\0';
10057                                 err |= setvarsafe("OPTARG", s, 0);
10058                         } else {
10059                                 fprintf(stderr, "Illegal option -%c\n", c);
10060                                 unsetvar("OPTARG");
10061                         }
10062                         c = '?';
10063                         goto out;
10064                 }
10065                 if (*++q == ':')
10066                         q++;
10067         }
10068
10069         if (*++q == ':') {
10070                 if (*p == '\0' && (p = *optnext) == NULL) {
10071                         if (optstr[0] == ':') {
10072                                 s[0] = c;
10073                                 s[1] = '\0';
10074                                 err |= setvarsafe("OPTARG", s, 0);
10075                                 c = ':';
10076                         } else {
10077                                 fprintf(stderr, "No arg for -%c option\n", c);
10078                                 unsetvar("OPTARG");
10079                                 c = '?';
10080                         }
10081                         goto out;
10082                 }
10083
10084                 if (p == *optnext)
10085                         optnext++;
10086                 err |= setvarsafe("OPTARG", p, 0);
10087                 p = NULL;
10088         } else
10089                 err |= setvarsafe("OPTARG", nullstr, 0);
10090  out:
10091         *optoff = p ? p - *(optnext - 1) : -1;
10092         *param_optind = optnext - optfirst + 1;
10093         fmtstr(s, sizeof(s), "%d", *param_optind);
10094         err |= setvarsafe("OPTIND", s, VNOFUNC);
10095         s[0] = c;
10096         s[1] = '\0';
10097         err |= setvarsafe(optvar, s, 0);
10098         if (err) {
10099                 *param_optind = 1;
10100                 *optoff = -1;
10101                 flush_stdout_stderr();
10102                 raise_exception(EXERROR);
10103         }
10104         return done;
10105 }
10106
10107 /*
10108  * The getopts builtin.  Shellparam.optnext points to the next argument
10109  * to be processed.  Shellparam.optptr points to the next character to
10110  * be processed in the current argument.  If shellparam.optnext is NULL,
10111  * then it's the first time getopts has been called.
10112  */
10113 static int FAST_FUNC
10114 getoptscmd(int argc, char **argv)
10115 {
10116         char **optbase;
10117
10118         if (argc < 3)
10119                 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10120         if (argc == 3) {
10121                 optbase = shellparam.p;
10122                 if (shellparam.optind > shellparam.nparam + 1) {
10123                         shellparam.optind = 1;
10124                         shellparam.optoff = -1;
10125                 }
10126         } else {
10127                 optbase = &argv[3];
10128                 if (shellparam.optind > argc - 2) {
10129                         shellparam.optind = 1;
10130                         shellparam.optoff = -1;
10131                 }
10132         }
10133
10134         return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10135                         &shellparam.optoff);
10136 }
10137 #endif /* ASH_GETOPTS */
10138
10139
10140 /* ============ Shell parser */
10141
10142 struct heredoc {
10143         struct heredoc *next;   /* next here document in list */
10144         union node *here;       /* redirection node */
10145         char *eofmark;          /* string indicating end of input */
10146         smallint striptabs;     /* if set, strip leading tabs */
10147 };
10148
10149 static smallint tokpushback;           /* last token pushed back */
10150 static smallint parsebackquote;        /* nonzero if we are inside backquotes */
10151 static smallint quoteflag;             /* set if (part of) last token was quoted */
10152 static token_id_t lasttoken;           /* last token read (integer id Txxx) */
10153 static struct heredoc *heredoclist;    /* list of here documents to read */
10154 static char *wordtext;                 /* text of last word returned by readtoken */
10155 static struct nodelist *backquotelist;
10156 static union node *redirnode;
10157 static struct heredoc *heredoc;
10158
10159 /*
10160  * Called when an unexpected token is read during the parse.  The argument
10161  * is the token that is expected, or -1 if more than one type of token can
10162  * occur at this point.
10163  */
10164 static void raise_error_unexpected_syntax(int) NORETURN;
10165 static void
10166 raise_error_unexpected_syntax(int token)
10167 {
10168         char msg[64];
10169         int l;
10170
10171         l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10172         if (token >= 0)
10173                 sprintf(msg + l, " (expecting %s)", tokname(token));
10174         raise_error_syntax(msg);
10175         /* NOTREACHED */
10176 }
10177
10178 #define EOFMARKLEN 79
10179
10180 /* parsing is heavily cross-recursive, need these forward decls */
10181 static union node *andor(void);
10182 static union node *pipeline(void);
10183 static union node *parse_command(void);
10184 static void parseheredoc(void);
10185 static char peektoken(void);
10186 static int readtoken(void);
10187
10188 static union node *
10189 list(int nlflag)
10190 {
10191         union node *n1, *n2, *n3;
10192         int tok;
10193
10194         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10195         if (nlflag == 2 && peektoken())
10196                 return NULL;
10197         n1 = NULL;
10198         for (;;) {
10199                 n2 = andor();
10200                 tok = readtoken();
10201                 if (tok == TBACKGND) {
10202                         if (n2->type == NPIPE) {
10203                                 n2->npipe.pipe_backgnd = 1;
10204                         } else {
10205                                 if (n2->type != NREDIR) {
10206                                         n3 = stzalloc(sizeof(struct nredir));
10207                                         n3->nredir.n = n2;
10208                                         /*n3->nredir.redirect = NULL; - stzalloc did it */
10209                                         n2 = n3;
10210                                 }
10211                                 n2->type = NBACKGND;
10212                         }
10213                 }
10214                 if (n1 == NULL) {
10215                         n1 = n2;
10216                 } else {
10217                         n3 = stzalloc(sizeof(struct nbinary));
10218                         n3->type = NSEMI;
10219                         n3->nbinary.ch1 = n1;
10220                         n3->nbinary.ch2 = n2;
10221                         n1 = n3;
10222                 }
10223                 switch (tok) {
10224                 case TBACKGND:
10225                 case TSEMI:
10226                         tok = readtoken();
10227                         /* fall through */
10228                 case TNL:
10229                         if (tok == TNL) {
10230                                 parseheredoc();
10231                                 if (nlflag == 1)
10232                                         return n1;
10233                         } else {
10234                                 tokpushback = 1;
10235                         }
10236                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10237                         if (peektoken())
10238                                 return n1;
10239                         break;
10240                 case TEOF:
10241                         if (heredoclist)
10242                                 parseheredoc();
10243                         else
10244                                 pungetc();              /* push back EOF on input */
10245                         return n1;
10246                 default:
10247                         if (nlflag == 1)
10248                                 raise_error_unexpected_syntax(-1);
10249                         tokpushback = 1;
10250                         return n1;
10251                 }
10252         }
10253 }
10254
10255 static union node *
10256 andor(void)
10257 {
10258         union node *n1, *n2, *n3;
10259         int t;
10260
10261         n1 = pipeline();
10262         for (;;) {
10263                 t = readtoken();
10264                 if (t == TAND) {
10265                         t = NAND;
10266                 } else if (t == TOR) {
10267                         t = NOR;
10268                 } else {
10269                         tokpushback = 1;
10270                         return n1;
10271                 }
10272                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10273                 n2 = pipeline();
10274                 n3 = stzalloc(sizeof(struct nbinary));
10275                 n3->type = t;
10276                 n3->nbinary.ch1 = n1;
10277                 n3->nbinary.ch2 = n2;
10278                 n1 = n3;
10279         }
10280 }
10281
10282 static union node *
10283 pipeline(void)
10284 {
10285         union node *n1, *n2, *pipenode;
10286         struct nodelist *lp, *prev;
10287         int negate;
10288
10289         negate = 0;
10290         TRACE(("pipeline: entered\n"));
10291         if (readtoken() == TNOT) {
10292                 negate = !negate;
10293                 checkkwd = CHKKWD | CHKALIAS;
10294         } else
10295                 tokpushback = 1;
10296         n1 = parse_command();
10297         if (readtoken() == TPIPE) {
10298                 pipenode = stzalloc(sizeof(struct npipe));
10299                 pipenode->type = NPIPE;
10300                 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10301                 lp = stzalloc(sizeof(struct nodelist));
10302                 pipenode->npipe.cmdlist = lp;
10303                 lp->n = n1;
10304                 do {
10305                         prev = lp;
10306                         lp = stzalloc(sizeof(struct nodelist));
10307                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
10308                         lp->n = parse_command();
10309                         prev->next = lp;
10310                 } while (readtoken() == TPIPE);
10311                 lp->next = NULL;
10312                 n1 = pipenode;
10313         }
10314         tokpushback = 1;
10315         if (negate) {
10316                 n2 = stzalloc(sizeof(struct nnot));
10317                 n2->type = NNOT;
10318                 n2->nnot.com = n1;
10319                 return n2;
10320         }
10321         return n1;
10322 }
10323
10324 static union node *
10325 makename(void)
10326 {
10327         union node *n;
10328
10329         n = stzalloc(sizeof(struct narg));
10330         n->type = NARG;
10331         /*n->narg.next = NULL; - stzalloc did it */
10332         n->narg.text = wordtext;
10333         n->narg.backquote = backquotelist;
10334         return n;
10335 }
10336
10337 static void
10338 fixredir(union node *n, const char *text, int err)
10339 {
10340         int fd;
10341
10342         TRACE(("Fix redir %s %d\n", text, err));
10343         if (!err)
10344                 n->ndup.vname = NULL;
10345
10346         fd = bb_strtou(text, NULL, 10);
10347         if (!errno && fd >= 0)
10348                 n->ndup.dupfd = fd;
10349         else if (LONE_DASH(text))
10350                 n->ndup.dupfd = -1;
10351         else {
10352                 if (err)
10353                         raise_error_syntax("bad fd number");
10354                 n->ndup.vname = makename();
10355         }
10356 }
10357
10358 /*
10359  * Returns true if the text contains nothing to expand (no dollar signs
10360  * or backquotes).
10361  */
10362 static int
10363 noexpand(const char *text)
10364 {
10365         const char *p;
10366         char c;
10367
10368         p = text;
10369         while ((c = *p++) != '\0') {
10370                 if (c == CTLQUOTEMARK)
10371                         continue;
10372                 if (c == CTLESC)
10373                         p++;
10374                 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10375                         return 0;
10376         }
10377         return 1;
10378 }
10379
10380 static void
10381 parsefname(void)
10382 {
10383         union node *n = redirnode;
10384
10385         if (readtoken() != TWORD)
10386                 raise_error_unexpected_syntax(-1);
10387         if (n->type == NHERE) {
10388                 struct heredoc *here = heredoc;
10389                 struct heredoc *p;
10390                 int i;
10391
10392                 if (quoteflag == 0)
10393                         n->type = NXHERE;
10394                 TRACE(("Here document %d\n", n->type));
10395                 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10396                         raise_error_syntax("illegal eof marker for << redirection");
10397                 rmescapes(wordtext);
10398                 here->eofmark = wordtext;
10399                 here->next = NULL;
10400                 if (heredoclist == NULL)
10401                         heredoclist = here;
10402                 else {
10403                         for (p = heredoclist; p->next; p = p->next)
10404                                 continue;
10405                         p->next = here;
10406                 }
10407         } else if (n->type == NTOFD || n->type == NFROMFD) {
10408                 fixredir(n, wordtext, 0);
10409         } else {
10410                 n->nfile.fname = makename();
10411         }
10412 }
10413
10414 static union node *
10415 simplecmd(void)
10416 {
10417         union node *args, **app;
10418         union node *n = NULL;
10419         union node *vars, **vpp;
10420         union node **rpp, *redir;
10421         int savecheckkwd;
10422 #if ENABLE_ASH_BASH_COMPAT
10423         smallint double_brackets_flag = 0;
10424 #endif
10425
10426         args = NULL;
10427         app = &args;
10428         vars = NULL;
10429         vpp = &vars;
10430         redir = NULL;
10431         rpp = &redir;
10432
10433         savecheckkwd = CHKALIAS;
10434         for (;;) {
10435                 int t;
10436                 checkkwd = savecheckkwd;
10437                 t = readtoken();
10438                 switch (t) {
10439 #if ENABLE_ASH_BASH_COMPAT
10440                 case TAND: /* "&&" */
10441                 case TOR: /* "||" */
10442                         if (!double_brackets_flag) {
10443                                 tokpushback = 1;
10444                                 goto out;
10445                         }
10446                         wordtext = (char *) (t == TAND ? "-a" : "-o");
10447 #endif
10448                 case TWORD:
10449                         n = stzalloc(sizeof(struct narg));
10450                         n->type = NARG;
10451                         /*n->narg.next = NULL; - stzalloc did it */
10452                         n->narg.text = wordtext;
10453 #if ENABLE_ASH_BASH_COMPAT
10454                         if (strcmp("[[", wordtext) == 0)
10455                                 double_brackets_flag = 1;
10456                         else if (strcmp("]]", wordtext) == 0)
10457                                 double_brackets_flag = 0;
10458 #endif
10459                         n->narg.backquote = backquotelist;
10460                         if (savecheckkwd && isassignment(wordtext)) {
10461                                 *vpp = n;
10462                                 vpp = &n->narg.next;
10463                         } else {
10464                                 *app = n;
10465                                 app = &n->narg.next;
10466                                 savecheckkwd = 0;
10467                         }
10468                         break;
10469                 case TREDIR:
10470                         *rpp = n = redirnode;
10471                         rpp = &n->nfile.next;
10472                         parsefname();   /* read name of redirection file */
10473                         break;
10474                 case TLP:
10475                         if (args && app == &args->narg.next
10476                          && !vars && !redir
10477                         ) {
10478                                 struct builtincmd *bcmd;
10479                                 const char *name;
10480
10481                                 /* We have a function */
10482                                 if (readtoken() != TRP)
10483                                         raise_error_unexpected_syntax(TRP);
10484                                 name = n->narg.text;
10485                                 if (!goodname(name)
10486                                  || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10487                                 ) {
10488                                         raise_error_syntax("bad function name");
10489                                 }
10490                                 n->type = NDEFUN;
10491                                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10492                                 n->narg.next = parse_command();
10493                                 return n;
10494                         }
10495                         /* fall through */
10496                 default:
10497                         tokpushback = 1;
10498                         goto out;
10499                 }
10500         }
10501  out:
10502         *app = NULL;
10503         *vpp = NULL;
10504         *rpp = NULL;
10505         n = stzalloc(sizeof(struct ncmd));
10506         n->type = NCMD;
10507         n->ncmd.args = args;
10508         n->ncmd.assign = vars;
10509         n->ncmd.redirect = redir;
10510         return n;
10511 }
10512
10513 static union node *
10514 parse_command(void)
10515 {
10516         union node *n1, *n2;
10517         union node *ap, **app;
10518         union node *cp, **cpp;
10519         union node *redir, **rpp;
10520         union node **rpp2;
10521         int t;
10522
10523         redir = NULL;
10524         rpp2 = &redir;
10525
10526         switch (readtoken()) {
10527         default:
10528                 raise_error_unexpected_syntax(-1);
10529                 /* NOTREACHED */
10530         case TIF:
10531                 n1 = stzalloc(sizeof(struct nif));
10532                 n1->type = NIF;
10533                 n1->nif.test = list(0);
10534                 if (readtoken() != TTHEN)
10535                         raise_error_unexpected_syntax(TTHEN);
10536                 n1->nif.ifpart = list(0);
10537                 n2 = n1;
10538                 while (readtoken() == TELIF) {
10539                         n2->nif.elsepart = stzalloc(sizeof(struct nif));
10540                         n2 = n2->nif.elsepart;
10541                         n2->type = NIF;
10542                         n2->nif.test = list(0);
10543                         if (readtoken() != TTHEN)
10544                                 raise_error_unexpected_syntax(TTHEN);
10545                         n2->nif.ifpart = list(0);
10546                 }
10547                 if (lasttoken == TELSE)
10548                         n2->nif.elsepart = list(0);
10549                 else {
10550                         n2->nif.elsepart = NULL;
10551                         tokpushback = 1;
10552                 }
10553                 t = TFI;
10554                 break;
10555         case TWHILE:
10556         case TUNTIL: {
10557                 int got;
10558                 n1 = stzalloc(sizeof(struct nbinary));
10559                 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10560                 n1->nbinary.ch1 = list(0);
10561                 got = readtoken();
10562                 if (got != TDO) {
10563                         TRACE(("expecting DO got %s %s\n", tokname(got),
10564                                         got == TWORD ? wordtext : ""));
10565                         raise_error_unexpected_syntax(TDO);
10566                 }
10567                 n1->nbinary.ch2 = list(0);
10568                 t = TDONE;
10569                 break;
10570         }
10571         case TFOR:
10572                 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10573                         raise_error_syntax("bad for loop variable");
10574                 n1 = stzalloc(sizeof(struct nfor));
10575                 n1->type = NFOR;
10576                 n1->nfor.var = wordtext;
10577                 checkkwd = CHKKWD | CHKALIAS;
10578                 if (readtoken() == TIN) {
10579                         app = &ap;
10580                         while (readtoken() == TWORD) {
10581                                 n2 = stzalloc(sizeof(struct narg));
10582                                 n2->type = NARG;
10583                                 /*n2->narg.next = NULL; - stzalloc did it */
10584                                 n2->narg.text = wordtext;
10585                                 n2->narg.backquote = backquotelist;
10586                                 *app = n2;
10587                                 app = &n2->narg.next;
10588                         }
10589                         *app = NULL;
10590                         n1->nfor.args = ap;
10591                         if (lasttoken != TNL && lasttoken != TSEMI)
10592                                 raise_error_unexpected_syntax(-1);
10593                 } else {
10594                         n2 = stzalloc(sizeof(struct narg));
10595                         n2->type = NARG;
10596                         /*n2->narg.next = NULL; - stzalloc did it */
10597                         n2->narg.text = (char *)dolatstr;
10598                         /*n2->narg.backquote = NULL;*/
10599                         n1->nfor.args = n2;
10600                         /*
10601                          * Newline or semicolon here is optional (but note
10602                          * that the original Bourne shell only allowed NL).
10603                          */
10604                         if (lasttoken != TNL && lasttoken != TSEMI)
10605                                 tokpushback = 1;
10606                 }
10607                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10608                 if (readtoken() != TDO)
10609                         raise_error_unexpected_syntax(TDO);
10610                 n1->nfor.body = list(0);
10611                 t = TDONE;
10612                 break;
10613         case TCASE:
10614                 n1 = stzalloc(sizeof(struct ncase));
10615                 n1->type = NCASE;
10616                 if (readtoken() != TWORD)
10617                         raise_error_unexpected_syntax(TWORD);
10618                 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10619                 n2->type = NARG;
10620                 /*n2->narg.next = NULL; - stzalloc did it */
10621                 n2->narg.text = wordtext;
10622                 n2->narg.backquote = backquotelist;
10623                 do {
10624                         checkkwd = CHKKWD | CHKALIAS;
10625                 } while (readtoken() == TNL);
10626                 if (lasttoken != TIN)
10627                         raise_error_unexpected_syntax(TIN);
10628                 cpp = &n1->ncase.cases;
10629  next_case:
10630                 checkkwd = CHKNL | CHKKWD;
10631                 t = readtoken();
10632                 while (t != TESAC) {
10633                         if (lasttoken == TLP)
10634                                 readtoken();
10635                         *cpp = cp = stzalloc(sizeof(struct nclist));
10636                         cp->type = NCLIST;
10637                         app = &cp->nclist.pattern;
10638                         for (;;) {
10639                                 *app = ap = stzalloc(sizeof(struct narg));
10640                                 ap->type = NARG;
10641                                 /*ap->narg.next = NULL; - stzalloc did it */
10642                                 ap->narg.text = wordtext;
10643                                 ap->narg.backquote = backquotelist;
10644                                 if (readtoken() != TPIPE)
10645                                         break;
10646                                 app = &ap->narg.next;
10647                                 readtoken();
10648                         }
10649                         //ap->narg.next = NULL;
10650                         if (lasttoken != TRP)
10651                                 raise_error_unexpected_syntax(TRP);
10652                         cp->nclist.body = list(2);
10653
10654                         cpp = &cp->nclist.next;
10655
10656                         checkkwd = CHKNL | CHKKWD;
10657                         t = readtoken();
10658                         if (t != TESAC) {
10659                                 if (t != TENDCASE)
10660                                         raise_error_unexpected_syntax(TENDCASE);
10661                                 goto next_case;
10662                         }
10663                 }
10664                 *cpp = NULL;
10665                 goto redir;
10666         case TLP:
10667                 n1 = stzalloc(sizeof(struct nredir));
10668                 n1->type = NSUBSHELL;
10669                 n1->nredir.n = list(0);
10670                 /*n1->nredir.redirect = NULL; - stzalloc did it */
10671                 t = TRP;
10672                 break;
10673         case TBEGIN:
10674                 n1 = list(0);
10675                 t = TEND;
10676                 break;
10677         case TWORD:
10678         case TREDIR:
10679                 tokpushback = 1;
10680                 return simplecmd();
10681         }
10682
10683         if (readtoken() != t)
10684                 raise_error_unexpected_syntax(t);
10685
10686  redir:
10687         /* Now check for redirection which may follow command */
10688         checkkwd = CHKKWD | CHKALIAS;
10689         rpp = rpp2;
10690         while (readtoken() == TREDIR) {
10691                 *rpp = n2 = redirnode;
10692                 rpp = &n2->nfile.next;
10693                 parsefname();
10694         }
10695         tokpushback = 1;
10696         *rpp = NULL;
10697         if (redir) {
10698                 if (n1->type != NSUBSHELL) {
10699                         n2 = stzalloc(sizeof(struct nredir));
10700                         n2->type = NREDIR;
10701                         n2->nredir.n = n1;
10702                         n1 = n2;
10703                 }
10704                 n1->nredir.redirect = redir;
10705         }
10706         return n1;
10707 }
10708
10709 #if ENABLE_ASH_BASH_COMPAT
10710 static int decode_dollar_squote(void)
10711 {
10712         static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10713         int c, cnt;
10714         char *p;
10715         char buf[4];
10716
10717         c = pgetc();
10718         p = strchr(C_escapes, c);
10719         if (p) {
10720                 buf[0] = c;
10721                 p = buf;
10722                 cnt = 3;
10723                 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10724                         do {
10725                                 c = pgetc();
10726                                 *++p = c;
10727                         } while ((unsigned char)(c - '0') <= 7 && --cnt);
10728                         pungetc();
10729                 } else if (c == 'x') { /* \xHH */
10730                         do {
10731                                 c = pgetc();
10732                                 *++p = c;
10733                         } while (isxdigit(c) && --cnt);
10734                         pungetc();
10735                         if (cnt == 3) { /* \x but next char is "bad" */
10736                                 c = 'x';
10737                                 goto unrecognized;
10738                         }
10739                 } else { /* simple seq like \\ or \t */
10740                         p++;
10741                 }
10742                 *p = '\0';
10743                 p = buf;
10744                 c = bb_process_escape_sequence((void*)&p);
10745         } else { /* unrecognized "\z": print both chars unless ' or " */
10746                 if (c != '\'' && c != '"') {
10747  unrecognized:
10748                         c |= 0x100; /* "please encode \, then me" */
10749                 }
10750         }
10751         return c;
10752 }
10753 #endif
10754
10755 /*
10756  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
10757  * is not NULL, read a here document.  In the latter case, eofmark is the
10758  * word which marks the end of the document and striptabs is true if
10759  * leading tabs should be stripped from the document.  The argument firstc
10760  * is the first character of the input token or document.
10761  *
10762  * Because C does not have internal subroutines, I have simulated them
10763  * using goto's to implement the subroutine linkage.  The following macros
10764  * will run code that appears at the end of readtoken1.
10765  */
10766 #define CHECKEND()      {goto checkend; checkend_return:;}
10767 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
10768 #define PARSESUB()      {goto parsesub; parsesub_return:;}
10769 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10770 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10771 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
10772 static int
10773 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10774 {
10775         /* NB: syntax parameter fits into smallint */
10776         int c = firstc;
10777         char *out;
10778         int len;
10779         char line[EOFMARKLEN + 1];
10780         struct nodelist *bqlist;
10781         smallint quotef;
10782         smallint dblquote;
10783         smallint oldstyle;
10784         smallint prevsyntax; /* syntax before arithmetic */
10785 #if ENABLE_ASH_EXPAND_PRMT
10786         smallint pssyntax;   /* we are expanding a prompt string */
10787 #endif
10788         int varnest;         /* levels of variables expansion */
10789         int arinest;         /* levels of arithmetic expansion */
10790         int parenlevel;      /* levels of parens in arithmetic */
10791         int dqvarnest;       /* levels of variables expansion within double quotes */
10792
10793         IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10794
10795 #if __GNUC__
10796         /* Avoid longjmp clobbering */
10797         (void) &out;
10798         (void) &quotef;
10799         (void) &dblquote;
10800         (void) &varnest;
10801         (void) &arinest;
10802         (void) &parenlevel;
10803         (void) &dqvarnest;
10804         (void) &oldstyle;
10805         (void) &prevsyntax;
10806         (void) &syntax;
10807 #endif
10808         startlinno = g_parsefile->linno;
10809         bqlist = NULL;
10810         quotef = 0;
10811         oldstyle = 0;
10812         prevsyntax = 0;
10813 #if ENABLE_ASH_EXPAND_PRMT
10814         pssyntax = (syntax == PSSYNTAX);
10815         if (pssyntax)
10816                 syntax = DQSYNTAX;
10817 #endif
10818         dblquote = (syntax == DQSYNTAX);
10819         varnest = 0;
10820         arinest = 0;
10821         parenlevel = 0;
10822         dqvarnest = 0;
10823
10824         STARTSTACKSTR(out);
10825  loop:
10826         /* For each line, until end of word */
10827         {
10828                 CHECKEND();     /* set c to PEOF if at end of here document */
10829                 for (;;) {      /* until end of line or end of word */
10830                         CHECKSTRSPACE(4, out);  /* permit 4 calls to USTPUTC */
10831                         switch (SIT(c, syntax)) {
10832                         case CNL:       /* '\n' */
10833                                 if (syntax == BASESYNTAX)
10834                                         goto endword;   /* exit outer loop */
10835                                 USTPUTC(c, out);
10836                                 g_parsefile->linno++;
10837                                 if (doprompt)
10838                                         setprompt(2);
10839                                 c = pgetc();
10840                                 goto loop;              /* continue outer loop */
10841                         case CWORD:
10842                                 USTPUTC(c, out);
10843                                 break;
10844                         case CCTL:
10845                                 if (eofmark == NULL || dblquote)
10846                                         USTPUTC(CTLESC, out);
10847 #if ENABLE_ASH_BASH_COMPAT
10848                                 if (c == '\\' && bash_dollar_squote) {
10849                                         c = decode_dollar_squote();
10850                                         if (c & 0x100) {
10851                                                 USTPUTC('\\', out);
10852                                                 c = (unsigned char)c;
10853                                         }
10854                                 }
10855 #endif
10856                                 USTPUTC(c, out);
10857                                 break;
10858                         case CBACK:     /* backslash */
10859                                 c = pgetc2();
10860                                 if (c == PEOF) {
10861                                         USTPUTC(CTLESC, out);
10862                                         USTPUTC('\\', out);
10863                                         pungetc();
10864                                 } else if (c == '\n') {
10865                                         if (doprompt)
10866                                                 setprompt(2);
10867                                 } else {
10868 #if ENABLE_ASH_EXPAND_PRMT
10869                                         if (c == '$' && pssyntax) {
10870                                                 USTPUTC(CTLESC, out);
10871                                                 USTPUTC('\\', out);
10872                                         }
10873 #endif
10874                                         if (dblquote && c != '\\'
10875                                          && c != '`' && c != '$'
10876                                          && (c != '"' || eofmark != NULL)
10877                                         ) {
10878                                                 USTPUTC(CTLESC, out);
10879                                                 USTPUTC('\\', out);
10880                                         }
10881                                         if (SIT(c, SQSYNTAX) == CCTL)
10882                                                 USTPUTC(CTLESC, out);
10883                                         USTPUTC(c, out);
10884                                         quotef = 1;
10885                                 }
10886                                 break;
10887                         case CSQUOTE:
10888                                 syntax = SQSYNTAX;
10889  quotemark:
10890                                 if (eofmark == NULL) {
10891                                         USTPUTC(CTLQUOTEMARK, out);
10892                                 }
10893                                 break;
10894                         case CDQUOTE:
10895                                 syntax = DQSYNTAX;
10896                                 dblquote = 1;
10897                                 goto quotemark;
10898                         case CENDQUOTE:
10899                                 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10900                                 if (eofmark != NULL && arinest == 0
10901                                  && varnest == 0
10902                                 ) {
10903                                         USTPUTC(c, out);
10904                                 } else {
10905                                         if (dqvarnest == 0) {
10906                                                 syntax = BASESYNTAX;
10907                                                 dblquote = 0;
10908                                         }
10909                                         quotef = 1;
10910                                         goto quotemark;
10911                                 }
10912                                 break;
10913                         case CVAR:      /* '$' */
10914                                 PARSESUB();             /* parse substitution */
10915                                 break;
10916                         case CENDVAR:   /* '}' */
10917                                 if (varnest > 0) {
10918                                         varnest--;
10919                                         if (dqvarnest > 0) {
10920                                                 dqvarnest--;
10921                                         }
10922                                         USTPUTC(CTLENDVAR, out);
10923                                 } else {
10924                                         USTPUTC(c, out);
10925                                 }
10926                                 break;
10927 #if ENABLE_SH_MATH_SUPPORT
10928                         case CLP:       /* '(' in arithmetic */
10929                                 parenlevel++;
10930                                 USTPUTC(c, out);
10931                                 break;
10932                         case CRP:       /* ')' in arithmetic */
10933                                 if (parenlevel > 0) {
10934                                         USTPUTC(c, out);
10935                                         --parenlevel;
10936                                 } else {
10937                                         if (pgetc() == ')') {
10938                                                 if (--arinest == 0) {
10939                                                         USTPUTC(CTLENDARI, out);
10940                                                         syntax = prevsyntax;
10941                                                         dblquote = (syntax == DQSYNTAX);
10942                                                 } else
10943                                                         USTPUTC(')', out);
10944                                         } else {
10945                                                 /*
10946                                                  * unbalanced parens
10947                                                  *  (don't 2nd guess - no error)
10948                                                  */
10949                                                 pungetc();
10950                                                 USTPUTC(')', out);
10951                                         }
10952                                 }
10953                                 break;
10954 #endif
10955                         case CBQUOTE:   /* '`' */
10956                                 PARSEBACKQOLD();
10957                                 break;
10958                         case CENDFILE:
10959                                 goto endword;           /* exit outer loop */
10960                         case CIGN:
10961                                 break;
10962                         default:
10963                                 if (varnest == 0) {
10964 #if ENABLE_ASH_BASH_COMPAT
10965                                         if (c == '&') {
10966                                                 if (pgetc() == '>')
10967                                                         c = 0x100 + '>'; /* flag &> */
10968                                                 pungetc();
10969                                         }
10970 #endif
10971                                         goto endword;   /* exit outer loop */
10972                                 }
10973 #if ENABLE_ASH_ALIAS
10974                                 if (c != PEOA)
10975 #endif
10976                                         USTPUTC(c, out);
10977
10978                         }
10979                         c = pgetc_fast();
10980                 } /* for (;;) */
10981         }
10982  endword:
10983 #if ENABLE_SH_MATH_SUPPORT
10984         if (syntax == ARISYNTAX)
10985                 raise_error_syntax("missing '))'");
10986 #endif
10987         if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10988                 raise_error_syntax("unterminated quoted string");
10989         if (varnest != 0) {
10990                 startlinno = g_parsefile->linno;
10991                 /* { */
10992                 raise_error_syntax("missing '}'");
10993         }
10994         USTPUTC('\0', out);
10995         len = out - (char *)stackblock();
10996         out = stackblock();
10997         if (eofmark == NULL) {
10998                 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
10999                  && quotef == 0
11000                 ) {
11001                         if (isdigit_str9(out)) {
11002                                 PARSEREDIR(); /* passed as params: out, c */
11003                                 lasttoken = TREDIR;
11004                                 return lasttoken;
11005                         }
11006                         /* else: non-number X seen, interpret it
11007                          * as "NNNX>file" = "NNNX >file" */
11008                 }
11009                 pungetc();
11010         }
11011         quoteflag = quotef;
11012         backquotelist = bqlist;
11013         grabstackblock(len);
11014         wordtext = out;
11015         lasttoken = TWORD;
11016         return lasttoken;
11017 /* end of readtoken routine */
11018
11019 /*
11020  * Check to see whether we are at the end of the here document.  When this
11021  * is called, c is set to the first character of the next input line.  If
11022  * we are at the end of the here document, this routine sets the c to PEOF.
11023  */
11024 checkend: {
11025         if (eofmark) {
11026 #if ENABLE_ASH_ALIAS
11027                 if (c == PEOA) {
11028                         c = pgetc2();
11029                 }
11030 #endif
11031                 if (striptabs) {
11032                         while (c == '\t') {
11033                                 c = pgetc2();
11034                         }
11035                 }
11036                 if (c == *eofmark) {
11037                         if (pfgets(line, sizeof(line)) != NULL) {
11038                                 char *p, *q;
11039
11040                                 p = line;
11041                                 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11042                                         continue;
11043                                 if (*p == '\n' && *q == '\0') {
11044                                         c = PEOF;
11045                                         g_parsefile->linno++;
11046                                         needprompt = doprompt;
11047                                 } else {
11048                                         pushstring(line, NULL);
11049                                 }
11050                         }
11051                 }
11052         }
11053         goto checkend_return;
11054 }
11055
11056 /*
11057  * Parse a redirection operator.  The variable "out" points to a string
11058  * specifying the fd to be redirected.  The variable "c" contains the
11059  * first character of the redirection operator.
11060  */
11061 parseredir: {
11062         /* out is already checked to be a valid number or "" */
11063         int fd = (*out == '\0' ? -1 : atoi(out));
11064         union node *np;
11065
11066         np = stzalloc(sizeof(struct nfile));
11067         if (c == '>') {
11068                 np->nfile.fd = 1;
11069                 c = pgetc();
11070                 if (c == '>')
11071                         np->type = NAPPEND;
11072                 else if (c == '|')
11073                         np->type = NCLOBBER;
11074                 else if (c == '&')
11075                         np->type = NTOFD;
11076                         /* it also can be NTO2 (>&file), but we can't figure it out yet */
11077                 else {
11078                         np->type = NTO;
11079                         pungetc();
11080                 }
11081         }
11082 #if ENABLE_ASH_BASH_COMPAT
11083         else if (c == 0x100 + '>') { /* this flags &> redirection */
11084                 np->nfile.fd = 1;
11085                 pgetc(); /* this is '>', no need to check */
11086                 np->type = NTO2;
11087         }
11088 #endif
11089         else { /* c == '<' */
11090                 /*np->nfile.fd = 0; - stzalloc did it */
11091                 c = pgetc();
11092                 switch (c) {
11093                 case '<':
11094                         if (sizeof(struct nfile) != sizeof(struct nhere)) {
11095                                 np = stzalloc(sizeof(struct nhere));
11096                                 /*np->nfile.fd = 0; - stzalloc did it */
11097                         }
11098                         np->type = NHERE;
11099                         heredoc = stzalloc(sizeof(struct heredoc));
11100                         heredoc->here = np;
11101                         c = pgetc();
11102                         if (c == '-') {
11103                                 heredoc->striptabs = 1;
11104                         } else {
11105                                 /*heredoc->striptabs = 0; - stzalloc did it */
11106                                 pungetc();
11107                         }
11108                         break;
11109
11110                 case '&':
11111                         np->type = NFROMFD;
11112                         break;
11113
11114                 case '>':
11115                         np->type = NFROMTO;
11116                         break;
11117
11118                 default:
11119                         np->type = NFROM;
11120                         pungetc();
11121                         break;
11122                 }
11123         }
11124         if (fd >= 0)
11125                 np->nfile.fd = fd;
11126         redirnode = np;
11127         goto parseredir_return;
11128 }
11129
11130 /*
11131  * Parse a substitution.  At this point, we have read the dollar sign
11132  * and nothing else.
11133  */
11134
11135 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11136  * (assuming ascii char codes, as the original implementation did) */
11137 #define is_special(c) \
11138         (((unsigned)(c) - 33 < 32) \
11139                         && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11140 parsesub: {
11141         int subtype;
11142         int typeloc;
11143         int flags;
11144         char *p;
11145         static const char types[] ALIGN1 = "}-+?=";
11146
11147         c = pgetc();
11148         if (c <= PEOA_OR_PEOF
11149          || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11150         ) {
11151 #if ENABLE_ASH_BASH_COMPAT
11152                 if (c == '\'')
11153                         bash_dollar_squote = 1;
11154                 else
11155 #endif
11156                         USTPUTC('$', out);
11157                 pungetc();
11158         } else if (c == '(') {  /* $(command) or $((arith)) */
11159                 if (pgetc() == '(') {
11160 #if ENABLE_SH_MATH_SUPPORT
11161                         PARSEARITH();
11162 #else
11163                         raise_error_syntax("you disabled math support for $((arith)) syntax");
11164 #endif
11165                 } else {
11166                         pungetc();
11167                         PARSEBACKQNEW();
11168                 }
11169         } else {
11170                 USTPUTC(CTLVAR, out);
11171                 typeloc = out - (char *)stackblock();
11172                 USTPUTC(VSNORMAL, out);
11173                 subtype = VSNORMAL;
11174                 if (c == '{') {
11175                         c = pgetc();
11176                         if (c == '#') {
11177                                 c = pgetc();
11178                                 if (c == '}')
11179                                         c = '#';
11180                                 else
11181                                         subtype = VSLENGTH;
11182                         } else
11183                                 subtype = 0;
11184                 }
11185                 if (c > PEOA_OR_PEOF && is_name(c)) {
11186                         do {
11187                                 STPUTC(c, out);
11188                                 c = pgetc();
11189                         } while (c > PEOA_OR_PEOF && is_in_name(c));
11190                 } else if (isdigit(c)) {
11191                         do {
11192                                 STPUTC(c, out);
11193                                 c = pgetc();
11194                         } while (isdigit(c));
11195                 } else if (is_special(c)) {
11196                         USTPUTC(c, out);
11197                         c = pgetc();
11198                 } else {
11199  badsub:
11200                         raise_error_syntax("bad substitution");
11201                 }
11202
11203                 STPUTC('=', out);
11204                 flags = 0;
11205                 if (subtype == 0) {
11206                         switch (c) {
11207                         case ':':
11208                                 c = pgetc();
11209 #if ENABLE_ASH_BASH_COMPAT
11210                                 if (c == ':' || c == '$' || isdigit(c)) {
11211                                         pungetc();
11212                                         subtype = VSSUBSTR;
11213                                         break;
11214                                 }
11215 #endif
11216                                 flags = VSNUL;
11217                                 /*FALLTHROUGH*/
11218                         default:
11219                                 p = strchr(types, c);
11220                                 if (p == NULL)
11221                                         goto badsub;
11222                                 subtype = p - types + VSNORMAL;
11223                                 break;
11224                         case '%':
11225                         case '#': {
11226                                 int cc = c;
11227                                 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11228                                 c = pgetc();
11229                                 if (c == cc)
11230                                         subtype++;
11231                                 else
11232                                         pungetc();
11233                                 break;
11234                         }
11235 #if ENABLE_ASH_BASH_COMPAT
11236                         case '/':
11237                                 subtype = VSREPLACE;
11238                                 c = pgetc();
11239                                 if (c == '/')
11240                                         subtype++; /* VSREPLACEALL */
11241                                 else
11242                                         pungetc();
11243                                 break;
11244 #endif
11245                         }
11246                 } else {
11247                         pungetc();
11248                 }
11249                 if (dblquote || arinest)
11250                         flags |= VSQUOTE;
11251                 *((char *)stackblock() + typeloc) = subtype | flags;
11252                 if (subtype != VSNORMAL) {
11253                         varnest++;
11254                         if (dblquote || arinest) {
11255                                 dqvarnest++;
11256                         }
11257                 }
11258         }
11259         goto parsesub_return;
11260 }
11261
11262 /*
11263  * Called to parse command substitutions.  Newstyle is set if the command
11264  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11265  * list of commands (passed by reference), and savelen is the number of
11266  * characters on the top of the stack which must be preserved.
11267  */
11268 parsebackq: {
11269         struct nodelist **nlpp;
11270         smallint savepbq;
11271         union node *n;
11272         char *volatile str;
11273         struct jmploc jmploc;
11274         struct jmploc *volatile savehandler;
11275         size_t savelen;
11276         smallint saveprompt = 0;
11277
11278 #ifdef __GNUC__
11279         (void) &saveprompt;
11280 #endif
11281         savepbq = parsebackquote;
11282         if (setjmp(jmploc.loc)) {
11283                 free(str);
11284                 parsebackquote = 0;
11285                 exception_handler = savehandler;
11286                 longjmp(exception_handler->loc, 1);
11287         }
11288         INT_OFF;
11289         str = NULL;
11290         savelen = out - (char *)stackblock();
11291         if (savelen > 0) {
11292                 str = ckmalloc(savelen);
11293                 memcpy(str, stackblock(), savelen);
11294         }
11295         savehandler = exception_handler;
11296         exception_handler = &jmploc;
11297         INT_ON;
11298         if (oldstyle) {
11299                 /* We must read until the closing backquote, giving special
11300                    treatment to some slashes, and then push the string and
11301                    reread it as input, interpreting it normally.  */
11302                 char *pout;
11303                 int pc;
11304                 size_t psavelen;
11305                 char *pstr;
11306
11307
11308                 STARTSTACKSTR(pout);
11309                 for (;;) {
11310                         if (needprompt) {
11311                                 setprompt(2);
11312                         }
11313                         pc = pgetc();
11314                         switch (pc) {
11315                         case '`':
11316                                 goto done;
11317
11318                         case '\\':
11319                                 pc = pgetc();
11320                                 if (pc == '\n') {
11321                                         g_parsefile->linno++;
11322                                         if (doprompt)
11323                                                 setprompt(2);
11324                                         /*
11325                                          * If eating a newline, avoid putting
11326                                          * the newline into the new character
11327                                          * stream (via the STPUTC after the
11328                                          * switch).
11329                                          */
11330                                         continue;
11331                                 }
11332                                 if (pc != '\\' && pc != '`' && pc != '$'
11333                                  && (!dblquote || pc != '"'))
11334                                         STPUTC('\\', pout);
11335                                 if (pc > PEOA_OR_PEOF) {
11336                                         break;
11337                                 }
11338                                 /* fall through */
11339
11340                         case PEOF:
11341 #if ENABLE_ASH_ALIAS
11342                         case PEOA:
11343 #endif
11344                                 startlinno = g_parsefile->linno;
11345                                 raise_error_syntax("EOF in backquote substitution");
11346
11347                         case '\n':
11348                                 g_parsefile->linno++;
11349                                 needprompt = doprompt;
11350                                 break;
11351
11352                         default:
11353                                 break;
11354                         }
11355                         STPUTC(pc, pout);
11356                 }
11357  done:
11358                 STPUTC('\0', pout);
11359                 psavelen = pout - (char *)stackblock();
11360                 if (psavelen > 0) {
11361                         pstr = grabstackstr(pout);
11362                         setinputstring(pstr);
11363                 }
11364         }
11365         nlpp = &bqlist;
11366         while (*nlpp)
11367                 nlpp = &(*nlpp)->next;
11368         *nlpp = stzalloc(sizeof(**nlpp));
11369         /* (*nlpp)->next = NULL; - stzalloc did it */
11370         parsebackquote = oldstyle;
11371
11372         if (oldstyle) {
11373                 saveprompt = doprompt;
11374                 doprompt = 0;
11375         }
11376
11377         n = list(2);
11378
11379         if (oldstyle)
11380                 doprompt = saveprompt;
11381         else if (readtoken() != TRP)
11382                 raise_error_unexpected_syntax(TRP);
11383
11384         (*nlpp)->n = n;
11385         if (oldstyle) {
11386                 /*
11387                  * Start reading from old file again, ignoring any pushed back
11388                  * tokens left from the backquote parsing
11389                  */
11390                 popfile();
11391                 tokpushback = 0;
11392         }
11393         while (stackblocksize() <= savelen)
11394                 growstackblock();
11395         STARTSTACKSTR(out);
11396         if (str) {
11397                 memcpy(out, str, savelen);
11398                 STADJUST(savelen, out);
11399                 INT_OFF;
11400                 free(str);
11401                 str = NULL;
11402                 INT_ON;
11403         }
11404         parsebackquote = savepbq;
11405         exception_handler = savehandler;
11406         if (arinest || dblquote)
11407                 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11408         else
11409                 USTPUTC(CTLBACKQ, out);
11410         if (oldstyle)
11411                 goto parsebackq_oldreturn;
11412         goto parsebackq_newreturn;
11413 }
11414
11415 #if ENABLE_SH_MATH_SUPPORT
11416 /*
11417  * Parse an arithmetic expansion (indicate start of one and set state)
11418  */
11419 parsearith: {
11420         if (++arinest == 1) {
11421                 prevsyntax = syntax;
11422                 syntax = ARISYNTAX;
11423                 USTPUTC(CTLARI, out);
11424                 if (dblquote)
11425                         USTPUTC('"', out);
11426                 else
11427                         USTPUTC(' ', out);
11428         } else {
11429                 /*
11430                  * we collapse embedded arithmetic expansion to
11431                  * parenthesis, which should be equivalent
11432                  */
11433                 USTPUTC('(', out);
11434         }
11435         goto parsearith_return;
11436 }
11437 #endif
11438
11439 } /* end of readtoken */
11440
11441 /*
11442  * Read the next input token.
11443  * If the token is a word, we set backquotelist to the list of cmds in
11444  *      backquotes.  We set quoteflag to true if any part of the word was
11445  *      quoted.
11446  * If the token is TREDIR, then we set redirnode to a structure containing
11447  *      the redirection.
11448  * In all cases, the variable startlinno is set to the number of the line
11449  *      on which the token starts.
11450  *
11451  * [Change comment:  here documents and internal procedures]
11452  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
11453  *  word parsing code into a separate routine.  In this case, readtoken
11454  *  doesn't need to have any internal procedures, but parseword does.
11455  *  We could also make parseoperator in essence the main routine, and
11456  *  have parseword (readtoken1?) handle both words and redirection.]
11457  */
11458 #define NEW_xxreadtoken
11459 #ifdef NEW_xxreadtoken
11460 /* singles must be first! */
11461 static const char xxreadtoken_chars[7] ALIGN1 = {
11462         '\n', '(', ')', /* singles */
11463         '&', '|', ';',  /* doubles */
11464         0
11465 };
11466
11467 #define xxreadtoken_singles 3
11468 #define xxreadtoken_doubles 3
11469
11470 static const char xxreadtoken_tokens[] ALIGN1 = {
11471         TNL, TLP, TRP,          /* only single occurrence allowed */
11472         TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11473         TEOF,                   /* corresponds to trailing nul */
11474         TAND, TOR, TENDCASE     /* if double occurrence */
11475 };
11476
11477 static int
11478 xxreadtoken(void)
11479 {
11480         int c;
11481
11482         if (tokpushback) {
11483                 tokpushback = 0;
11484                 return lasttoken;
11485         }
11486         if (needprompt) {
11487                 setprompt(2);
11488         }
11489         startlinno = g_parsefile->linno;
11490         for (;;) {                      /* until token or start of word found */
11491                 c = pgetc_fast();
11492                 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11493                         continue;
11494
11495                 if (c == '#') {
11496                         while ((c = pgetc()) != '\n' && c != PEOF)
11497                                 continue;
11498                         pungetc();
11499                 } else if (c == '\\') {
11500                         if (pgetc() != '\n') {
11501                                 pungetc();
11502                                 break; /* return readtoken1(...) */
11503                         }
11504                         startlinno = ++g_parsefile->linno;
11505                         if (doprompt)
11506                                 setprompt(2);
11507                 } else {
11508                         const char *p;
11509
11510                         p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11511                         if (c != PEOF) {
11512                                 if (c == '\n') {
11513                                         g_parsefile->linno++;
11514                                         needprompt = doprompt;
11515                                 }
11516
11517                                 p = strchr(xxreadtoken_chars, c);
11518                                 if (p == NULL)
11519                                         break; /* return readtoken1(...) */
11520
11521                                 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11522                                         int cc = pgetc();
11523                                         if (cc == c) {    /* double occurrence? */
11524                                                 p += xxreadtoken_doubles + 1;
11525                                         } else {
11526                                                 pungetc();
11527 #if ENABLE_ASH_BASH_COMPAT
11528                                                 if (c == '&' && cc == '>') /* &> */
11529                                                         break; /* return readtoken1(...) */
11530 #endif
11531                                         }
11532                                 }
11533                         }
11534                         lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11535                         return lasttoken;
11536                 }
11537         } /* for (;;) */
11538
11539         return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11540 }
11541 #else /* old xxreadtoken */
11542 #define RETURN(token)   return lasttoken = token
11543 static int
11544 xxreadtoken(void)
11545 {
11546         int c;
11547
11548         if (tokpushback) {
11549                 tokpushback = 0;
11550                 return lasttoken;
11551         }
11552         if (needprompt) {
11553                 setprompt(2);
11554         }
11555         startlinno = g_parsefile->linno;
11556         for (;;) {      /* until token or start of word found */
11557                 c = pgetc_fast();
11558                 switch (c) {
11559                 case ' ': case '\t':
11560 #if ENABLE_ASH_ALIAS
11561                 case PEOA:
11562 #endif
11563                         continue;
11564                 case '#':
11565                         while ((c = pgetc()) != '\n' && c != PEOF)
11566                                 continue;
11567                         pungetc();
11568                         continue;
11569                 case '\\':
11570                         if (pgetc() == '\n') {
11571                                 startlinno = ++g_parsefile->linno;
11572                                 if (doprompt)
11573                                         setprompt(2);
11574                                 continue;
11575                         }
11576                         pungetc();
11577                         goto breakloop;
11578                 case '\n':
11579                         g_parsefile->linno++;
11580                         needprompt = doprompt;
11581                         RETURN(TNL);
11582                 case PEOF:
11583                         RETURN(TEOF);
11584                 case '&':
11585                         if (pgetc() == '&')
11586                                 RETURN(TAND);
11587                         pungetc();
11588                         RETURN(TBACKGND);
11589                 case '|':
11590                         if (pgetc() == '|')
11591                                 RETURN(TOR);
11592                         pungetc();
11593                         RETURN(TPIPE);
11594                 case ';':
11595                         if (pgetc() == ';')
11596                                 RETURN(TENDCASE);
11597                         pungetc();
11598                         RETURN(TSEMI);
11599                 case '(':
11600                         RETURN(TLP);
11601                 case ')':
11602                         RETURN(TRP);
11603                 default:
11604                         goto breakloop;
11605                 }
11606         }
11607  breakloop:
11608         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11609 #undef RETURN
11610 }
11611 #endif /* old xxreadtoken */
11612
11613 static int
11614 readtoken(void)
11615 {
11616         int t;
11617 #if DEBUG
11618         smallint alreadyseen = tokpushback;
11619 #endif
11620
11621 #if ENABLE_ASH_ALIAS
11622  top:
11623 #endif
11624
11625         t = xxreadtoken();
11626
11627         /*
11628          * eat newlines
11629          */
11630         if (checkkwd & CHKNL) {
11631                 while (t == TNL) {
11632                         parseheredoc();
11633                         t = xxreadtoken();
11634                 }
11635         }
11636
11637         if (t != TWORD || quoteflag) {
11638                 goto out;
11639         }
11640
11641         /*
11642          * check for keywords
11643          */
11644         if (checkkwd & CHKKWD) {
11645                 const char *const *pp;
11646
11647                 pp = findkwd(wordtext);
11648                 if (pp) {
11649                         lasttoken = t = pp - tokname_array;
11650                         TRACE(("keyword %s recognized\n", tokname(t)));
11651                         goto out;
11652                 }
11653         }
11654
11655         if (checkkwd & CHKALIAS) {
11656 #if ENABLE_ASH_ALIAS
11657                 struct alias *ap;
11658                 ap = lookupalias(wordtext, 1);
11659                 if (ap != NULL) {
11660                         if (*ap->val) {
11661                                 pushstring(ap->val, ap);
11662                         }
11663                         goto top;
11664                 }
11665 #endif
11666         }
11667  out:
11668         checkkwd = 0;
11669 #if DEBUG
11670         if (!alreadyseen)
11671                 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11672         else
11673                 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11674 #endif
11675         return t;
11676 }
11677
11678 static char
11679 peektoken(void)
11680 {
11681         int t;
11682
11683         t = readtoken();
11684         tokpushback = 1;
11685         return tokname_array[t][0];
11686 }
11687
11688 /*
11689  * Read and parse a command.  Returns NODE_EOF on end of file.
11690  * (NULL is a valid parse tree indicating a blank line.)
11691  */
11692 static union node *
11693 parsecmd(int interact)
11694 {
11695         int t;
11696
11697         tokpushback = 0;
11698         doprompt = interact;
11699         if (doprompt)
11700                 setprompt(doprompt);
11701         needprompt = 0;
11702         t = readtoken();
11703         if (t == TEOF)
11704                 return NODE_EOF;
11705         if (t == TNL)
11706                 return NULL;
11707         tokpushback = 1;
11708         return list(1);
11709 }
11710
11711 /*
11712  * Input any here documents.
11713  */
11714 static void
11715 parseheredoc(void)
11716 {
11717         struct heredoc *here;
11718         union node *n;
11719
11720         here = heredoclist;
11721         heredoclist = NULL;
11722
11723         while (here) {
11724                 if (needprompt) {
11725                         setprompt(2);
11726                 }
11727                 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11728                                 here->eofmark, here->striptabs);
11729                 n = stzalloc(sizeof(struct narg));
11730                 n->narg.type = NARG;
11731                 /*n->narg.next = NULL; - stzalloc did it */
11732                 n->narg.text = wordtext;
11733                 n->narg.backquote = backquotelist;
11734                 here->here->nhere.doc = n;
11735                 here = here->next;
11736         }
11737 }
11738
11739
11740 /*
11741  * called by editline -- any expansions to the prompt should be added here.
11742  */
11743 #if ENABLE_ASH_EXPAND_PRMT
11744 static const char *
11745 expandstr(const char *ps)
11746 {
11747         union node n;
11748
11749         /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11750          * and token processing _can_ alter it (delete NULs etc). */
11751         setinputstring((char *)ps);
11752         readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11753         popfile();
11754
11755         n.narg.type = NARG;
11756         n.narg.next = NULL;
11757         n.narg.text = wordtext;
11758         n.narg.backquote = backquotelist;
11759
11760         expandarg(&n, NULL, 0);
11761         return stackblock();
11762 }
11763 #endif
11764
11765 /*
11766  * Execute a command or commands contained in a string.
11767  */
11768 static int
11769 evalstring(char *s, int mask)
11770 {
11771         union node *n;
11772         struct stackmark smark;
11773         int skip;
11774
11775         setinputstring(s);
11776         setstackmark(&smark);
11777
11778         skip = 0;
11779         while ((n = parsecmd(0)) != NODE_EOF) {
11780                 evaltree(n, 0);
11781                 popstackmark(&smark);
11782                 skip = evalskip;
11783                 if (skip)
11784                         break;
11785         }
11786         popfile();
11787
11788         skip &= mask;
11789         evalskip = skip;
11790         return skip;
11791 }
11792
11793 /*
11794  * The eval command.
11795  */
11796 static int FAST_FUNC
11797 evalcmd(int argc UNUSED_PARAM, char **argv)
11798 {
11799         char *p;
11800         char *concat;
11801
11802         if (argv[1]) {
11803                 p = argv[1];
11804                 argv += 2;
11805                 if (argv[0]) {
11806                         STARTSTACKSTR(concat);
11807                         for (;;) {
11808                                 concat = stack_putstr(p, concat);
11809                                 p = *argv++;
11810                                 if (p == NULL)
11811                                         break;
11812                                 STPUTC(' ', concat);
11813                         }
11814                         STPUTC('\0', concat);
11815                         p = grabstackstr(concat);
11816                 }
11817                 evalstring(p, ~SKIPEVAL);
11818
11819         }
11820         return exitstatus;
11821 }
11822
11823 /*
11824  * Read and execute commands.  "Top" is nonzero for the top level command
11825  * loop; it turns on prompting if the shell is interactive.
11826  */
11827 static int
11828 cmdloop(int top)
11829 {
11830         union node *n;
11831         struct stackmark smark;
11832         int inter;
11833         int numeof = 0;
11834
11835         TRACE(("cmdloop(%d) called\n", top));
11836         for (;;) {
11837                 int skip;
11838
11839                 setstackmark(&smark);
11840 #if JOBS
11841                 if (doing_jobctl)
11842                         showjobs(stderr, SHOW_CHANGED);
11843 #endif
11844                 inter = 0;
11845                 if (iflag && top) {
11846                         inter++;
11847 #if ENABLE_ASH_MAIL
11848                         chkmail();
11849 #endif
11850                 }
11851                 n = parsecmd(inter);
11852 #if DEBUG > 2
11853                 if (debug && (n != NODE_EOF))
11854                         showtree(n);
11855 #endif
11856                 if (n == NODE_EOF) {
11857                         if (!top || numeof >= 50)
11858                                 break;
11859                         if (!stoppedjobs()) {
11860                                 if (!Iflag)
11861                                         break;
11862                                 out2str("\nUse \"exit\" to leave shell.\n");
11863                         }
11864                         numeof++;
11865                 } else if (nflag == 0) {
11866                         /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11867                         job_warning >>= 1;
11868                         numeof = 0;
11869                         evaltree(n, 0);
11870                 }
11871                 popstackmark(&smark);
11872                 skip = evalskip;
11873
11874                 if (skip) {
11875                         evalskip = 0;
11876                         return skip & SKIPEVAL;
11877                 }
11878         }
11879         return 0;
11880 }
11881
11882 /*
11883  * Take commands from a file.  To be compatible we should do a path
11884  * search for the file, which is necessary to find sub-commands.
11885  */
11886 static char *
11887 find_dot_file(char *name)
11888 {
11889         char *fullname;
11890         const char *path = pathval();
11891         struct stat statb;
11892
11893         /* don't try this for absolute or relative paths */
11894         if (strchr(name, '/'))
11895                 return name;
11896
11897         /* IIRC standards do not say whether . is to be searched.
11898          * And it is even smaller this way, making it unconditional for now:
11899          */
11900         if (1) { /* ENABLE_ASH_BASH_COMPAT */
11901                 fullname = name;
11902                 goto try_cur_dir;
11903         }
11904
11905         while ((fullname = path_advance(&path, name)) != NULL) {
11906  try_cur_dir:
11907                 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11908                         /*
11909                          * Don't bother freeing here, since it will
11910                          * be freed by the caller.
11911                          */
11912                         return fullname;
11913                 }
11914                 if (fullname != name)
11915                         stunalloc(fullname);
11916         }
11917
11918         /* not found in the PATH */
11919         ash_msg_and_raise_error("%s: not found", name);
11920         /* NOTREACHED */
11921 }
11922
11923 static int FAST_FUNC
11924 dotcmd(int argc, char **argv)
11925 {
11926         struct strlist *sp;
11927         volatile struct shparam saveparam;
11928         int status = 0;
11929
11930         for (sp = cmdenviron; sp; sp = sp->next)
11931                 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11932
11933         if (argv[1]) {        /* That's what SVR2 does */
11934                 char *fullname = find_dot_file(argv[1]);
11935                 argv += 2;
11936                 argc -= 2;
11937                 if (argc) { /* argc > 0, argv[0] != NULL */
11938                         saveparam = shellparam;
11939                         shellparam.malloced = 0;
11940                         shellparam.nparam = argc;
11941                         shellparam.p = argv;
11942                 };
11943
11944                 setinputfile(fullname, INPUT_PUSH_FILE);
11945                 commandname = fullname;
11946                 cmdloop(0);
11947                 popfile();
11948
11949                 if (argc) {
11950                         freeparam(&shellparam);
11951                         shellparam = saveparam;
11952                 };
11953                 status = exitstatus;
11954         }
11955         return status;
11956 }
11957
11958 static int FAST_FUNC
11959 exitcmd(int argc UNUSED_PARAM, char **argv)
11960 {
11961         if (stoppedjobs())
11962                 return 0;
11963         if (argv[1])
11964                 exitstatus = number(argv[1]);
11965         raise_exception(EXEXIT);
11966         /* NOTREACHED */
11967 }
11968
11969 /*
11970  * Read a file containing shell functions.
11971  */
11972 static void
11973 readcmdfile(char *name)
11974 {
11975         setinputfile(name, INPUT_PUSH_FILE);
11976         cmdloop(0);
11977         popfile();
11978 }
11979
11980
11981 /* ============ find_command inplementation */
11982
11983 /*
11984  * Resolve a command name.  If you change this routine, you may have to
11985  * change the shellexec routine as well.
11986  */
11987 static void
11988 find_command(char *name, struct cmdentry *entry, int act, const char *path)
11989 {
11990         struct tblentry *cmdp;
11991         int idx;
11992         int prev;
11993         char *fullname;
11994         struct stat statb;
11995         int e;
11996         int updatetbl;
11997         struct builtincmd *bcmd;
11998
11999         /* If name contains a slash, don't use PATH or hash table */
12000         if (strchr(name, '/') != NULL) {
12001                 entry->u.index = -1;
12002                 if (act & DO_ABS) {
12003                         while (stat(name, &statb) < 0) {
12004 #ifdef SYSV
12005                                 if (errno == EINTR)
12006                                         continue;
12007 #endif
12008                                 entry->cmdtype = CMDUNKNOWN;
12009                                 return;
12010                         }
12011                 }
12012                 entry->cmdtype = CMDNORMAL;
12013                 return;
12014         }
12015
12016 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12017
12018         updatetbl = (path == pathval());
12019         if (!updatetbl) {
12020                 act |= DO_ALTPATH;
12021                 if (strstr(path, "%builtin") != NULL)
12022                         act |= DO_ALTBLTIN;
12023         }
12024
12025         /* If name is in the table, check answer will be ok */
12026         cmdp = cmdlookup(name, 0);
12027         if (cmdp != NULL) {
12028                 int bit;
12029
12030                 switch (cmdp->cmdtype) {
12031                 default:
12032 #if DEBUG
12033                         abort();
12034 #endif
12035                 case CMDNORMAL:
12036                         bit = DO_ALTPATH;
12037                         break;
12038                 case CMDFUNCTION:
12039                         bit = DO_NOFUNC;
12040                         break;
12041                 case CMDBUILTIN:
12042                         bit = DO_ALTBLTIN;
12043                         break;
12044                 }
12045                 if (act & bit) {
12046                         updatetbl = 0;
12047                         cmdp = NULL;
12048                 } else if (cmdp->rehash == 0)
12049                         /* if not invalidated by cd, we're done */
12050                         goto success;
12051         }
12052
12053         /* If %builtin not in path, check for builtin next */
12054         bcmd = find_builtin(name);
12055         if (bcmd) {
12056                 if (IS_BUILTIN_REGULAR(bcmd))
12057                         goto builtin_success;
12058                 if (act & DO_ALTPATH) {
12059                         if (!(act & DO_ALTBLTIN))
12060                                 goto builtin_success;
12061                 } else if (builtinloc <= 0) {
12062                         goto builtin_success;
12063                 }
12064         }
12065
12066 #if ENABLE_FEATURE_SH_STANDALONE
12067         {
12068                 int applet_no = find_applet_by_name(name);
12069                 if (applet_no >= 0) {
12070                         entry->cmdtype = CMDNORMAL;
12071                         entry->u.index = -2 - applet_no;
12072                         return;
12073                 }
12074         }
12075 #endif
12076
12077         /* We have to search path. */
12078         prev = -1;              /* where to start */
12079         if (cmdp && cmdp->rehash) {     /* doing a rehash */
12080                 if (cmdp->cmdtype == CMDBUILTIN)
12081                         prev = builtinloc;
12082                 else
12083                         prev = cmdp->param.index;
12084         }
12085
12086         e = ENOENT;
12087         idx = -1;
12088  loop:
12089         while ((fullname = path_advance(&path, name)) != NULL) {
12090                 stunalloc(fullname);
12091                 /* NB: code below will still use fullname
12092                  * despite it being "unallocated" */
12093                 idx++;
12094                 if (pathopt) {
12095                         if (prefix(pathopt, "builtin")) {
12096                                 if (bcmd)
12097                                         goto builtin_success;
12098                                 continue;
12099                         }
12100                         if ((act & DO_NOFUNC)
12101                          || !prefix(pathopt, "func")
12102                         ) {     /* ignore unimplemented options */
12103                                 continue;
12104                         }
12105                 }
12106                 /* if rehash, don't redo absolute path names */
12107                 if (fullname[0] == '/' && idx <= prev) {
12108                         if (idx < prev)
12109                                 continue;
12110                         TRACE(("searchexec \"%s\": no change\n", name));
12111                         goto success;
12112                 }
12113                 while (stat(fullname, &statb) < 0) {
12114 #ifdef SYSV
12115                         if (errno == EINTR)
12116                                 continue;
12117 #endif
12118                         if (errno != ENOENT && errno != ENOTDIR)
12119                                 e = errno;
12120                         goto loop;
12121                 }
12122                 e = EACCES;     /* if we fail, this will be the error */
12123                 if (!S_ISREG(statb.st_mode))
12124                         continue;
12125                 if (pathopt) {          /* this is a %func directory */
12126                         stalloc(strlen(fullname) + 1);
12127                         /* NB: stalloc will return space pointed by fullname
12128                          * (because we don't have any intervening allocations
12129                          * between stunalloc above and this stalloc) */
12130                         readcmdfile(fullname);
12131                         cmdp = cmdlookup(name, 0);
12132                         if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12133                                 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12134                         stunalloc(fullname);
12135                         goto success;
12136                 }
12137                 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12138                 if (!updatetbl) {
12139                         entry->cmdtype = CMDNORMAL;
12140                         entry->u.index = idx;
12141                         return;
12142                 }
12143                 INT_OFF;
12144                 cmdp = cmdlookup(name, 1);
12145                 cmdp->cmdtype = CMDNORMAL;
12146                 cmdp->param.index = idx;
12147                 INT_ON;
12148                 goto success;
12149         }
12150
12151         /* We failed.  If there was an entry for this command, delete it */
12152         if (cmdp && updatetbl)
12153                 delete_cmd_entry();
12154         if (act & DO_ERR)
12155                 ash_msg("%s: %s", name, errmsg(e, "not found"));
12156         entry->cmdtype = CMDUNKNOWN;
12157         return;
12158
12159  builtin_success:
12160         if (!updatetbl) {
12161                 entry->cmdtype = CMDBUILTIN;
12162                 entry->u.cmd = bcmd;
12163                 return;
12164         }
12165         INT_OFF;
12166         cmdp = cmdlookup(name, 1);
12167         cmdp->cmdtype = CMDBUILTIN;
12168         cmdp->param.cmd = bcmd;
12169         INT_ON;
12170  success:
12171         cmdp->rehash = 0;
12172         entry->cmdtype = cmdp->cmdtype;
12173         entry->u = cmdp->param;
12174 }
12175
12176
12177 /* ============ trap.c */
12178
12179 /*
12180  * The trap builtin.
12181  */
12182 static int FAST_FUNC
12183 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12184 {
12185         char *action;
12186         char **ap;
12187         int signo;
12188
12189         nextopt(nullstr);
12190         ap = argptr;
12191         if (!*ap) {
12192                 for (signo = 0; signo < NSIG; signo++) {
12193                         if (trap[signo] != NULL) {
12194                                 out1fmt("trap -- %s %s\n",
12195                                                 single_quote(trap[signo]),
12196                                                 get_signame(signo));
12197                         }
12198                 }
12199                 return 0;
12200         }
12201         action = NULL;
12202         if (ap[1])
12203                 action = *ap++;
12204         while (*ap) {
12205                 signo = get_signum(*ap);
12206                 if (signo < 0)
12207                         ash_msg_and_raise_error("%s: bad trap", *ap);
12208                 INT_OFF;
12209                 if (action) {
12210                         if (LONE_DASH(action))
12211                                 action = NULL;
12212                         else
12213                                 action = ckstrdup(action);
12214                 }
12215                 free(trap[signo]);
12216                 trap[signo] = action;
12217                 if (signo != 0)
12218                         setsignal(signo);
12219                 INT_ON;
12220                 ap++;
12221         }
12222         return 0;
12223 }
12224
12225
12226 /* ============ Builtins */
12227
12228 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12229 /*
12230  * Lists available builtins
12231  */
12232 static int FAST_FUNC
12233 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12234 {
12235         unsigned col;
12236         unsigned i;
12237
12238         out1fmt(
12239                 "Built-in commands:\n"
12240                 "------------------\n");
12241         for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12242                 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12243                                         builtintab[i].name + 1);
12244                 if (col > 60) {
12245                         out1fmt("\n");
12246                         col = 0;
12247                 }
12248         }
12249 #if ENABLE_FEATURE_SH_STANDALONE
12250         {
12251                 const char *a = applet_names;
12252                 while (*a) {
12253                         col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12254                         if (col > 60) {
12255                                 out1fmt("\n");
12256                                 col = 0;
12257                         }
12258                         a += strlen(a) + 1;
12259                 }
12260         }
12261 #endif
12262         out1fmt("\n\n");
12263         return EXIT_SUCCESS;
12264 }
12265 #endif /* FEATURE_SH_EXTRA_QUIET */
12266
12267 /*
12268  * The export and readonly commands.
12269  */
12270 static int FAST_FUNC
12271 exportcmd(int argc UNUSED_PARAM, char **argv)
12272 {
12273         struct var *vp;
12274         char *name;
12275         const char *p;
12276         char **aptr;
12277         int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12278
12279         if (nextopt("p") != 'p') {
12280                 aptr = argptr;
12281                 name = *aptr;
12282                 if (name) {
12283                         do {
12284                                 p = strchr(name, '=');
12285                                 if (p != NULL) {
12286                                         p++;
12287                                 } else {
12288                                         vp = *findvar(hashvar(name), name);
12289                                         if (vp) {
12290                                                 vp->flags |= flag;
12291                                                 continue;
12292                                         }
12293                                 }
12294                                 setvar(name, p, flag);
12295                         } while ((name = *++aptr) != NULL);
12296                         return 0;
12297                 }
12298         }
12299         showvars(argv[0], flag, 0);
12300         return 0;
12301 }
12302
12303 /*
12304  * Delete a function if it exists.
12305  */
12306 static void
12307 unsetfunc(const char *name)
12308 {
12309         struct tblentry *cmdp;
12310
12311         cmdp = cmdlookup(name, 0);
12312         if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12313                 delete_cmd_entry();
12314 }
12315
12316 /*
12317  * The unset builtin command.  We unset the function before we unset the
12318  * variable to allow a function to be unset when there is a readonly variable
12319  * with the same name.
12320  */
12321 static int FAST_FUNC
12322 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12323 {
12324         char **ap;
12325         int i;
12326         int flag = 0;
12327         int ret = 0;
12328
12329         while ((i = nextopt("vf")) != '\0') {
12330                 flag = i;
12331         }
12332
12333         for (ap = argptr; *ap; ap++) {
12334                 if (flag != 'f') {
12335                         i = unsetvar(*ap);
12336                         ret |= i;
12337                         if (!(i & 2))
12338                                 continue;
12339                 }
12340                 if (flag != 'v')
12341                         unsetfunc(*ap);
12342         }
12343         return ret & 1;
12344 }
12345
12346
12347 /*      setmode.c      */
12348
12349 #include <sys/times.h>
12350
12351 static const unsigned char timescmd_str[] ALIGN1 = {
12352         ' ',  offsetof(struct tms, tms_utime),
12353         '\n', offsetof(struct tms, tms_stime),
12354         ' ',  offsetof(struct tms, tms_cutime),
12355         '\n', offsetof(struct tms, tms_cstime),
12356         0
12357 };
12358
12359 static int FAST_FUNC
12360 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12361 {
12362         long clk_tck, s, t;
12363         const unsigned char *p;
12364         struct tms buf;
12365
12366         clk_tck = sysconf(_SC_CLK_TCK);
12367         times(&buf);
12368
12369         p = timescmd_str;
12370         do {
12371                 t = *(clock_t *)(((char *) &buf) + p[1]);
12372                 s = t / clk_tck;
12373                 out1fmt("%ldm%ld.%.3lds%c",
12374                         s/60, s%60,
12375                         ((t - s * clk_tck) * 1000) / clk_tck,
12376                         p[0]);
12377         } while (*(p += 2));
12378
12379         return 0;
12380 }
12381
12382 #if ENABLE_SH_MATH_SUPPORT
12383 /*
12384  * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12385  * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12386  *
12387  * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12388  */
12389 static int FAST_FUNC
12390 letcmd(int argc UNUSED_PARAM, char **argv)
12391 {
12392         arith_t i;
12393
12394         argv++;
12395         if (!*argv)
12396                 ash_msg_and_raise_error("expression expected");
12397         do {
12398                 i = ash_arith(*argv);
12399         } while (*++argv);
12400
12401         return !i;
12402 }
12403 #endif /* SH_MATH_SUPPORT */
12404
12405
12406 /* ============ miscbltin.c
12407  *
12408  * Miscellaneous builtins.
12409  */
12410
12411 #undef rflag
12412
12413 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12414 typedef enum __rlimit_resource rlim_t;
12415 #endif
12416
12417 /*
12418  * The read builtin. Options:
12419  *      -r              Do not interpret '\' specially
12420  *      -s              Turn off echo (tty only)
12421  *      -n NCHARS       Read NCHARS max
12422  *      -p PROMPT       Display PROMPT on stderr (if input is from tty)
12423  *      -t SECONDS      Timeout after SECONDS (tty or pipe only)
12424  *      -u FD           Read from given FD instead of fd 0
12425  * This uses unbuffered input, which may be avoidable in some cases.
12426  * TODO: bash also has:
12427  *      -a ARRAY        Read into array[0],[1],etc
12428  *      -d DELIM        End on DELIM char, not newline
12429  *      -e              Use line editing (tty only)
12430  */
12431 static int FAST_FUNC
12432 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12433 {
12434         static const char *const arg_REPLY[] = { "REPLY", NULL };
12435
12436         char **ap;
12437         int backslash;
12438         char c;
12439         int rflag;
12440         char *prompt;
12441         const char *ifs;
12442         char *p;
12443         int startword;
12444         int status;
12445         int i;
12446         int fd = 0;
12447 #if ENABLE_ASH_READ_NCHARS
12448         int nchars = 0; /* if != 0, -n is in effect */
12449         int silent = 0;
12450         struct termios tty, old_tty;
12451 #endif
12452 #if ENABLE_ASH_READ_TIMEOUT
12453         unsigned end_ms = 0;
12454         unsigned timeout = 0;
12455 #endif
12456
12457         rflag = 0;
12458         prompt = NULL;
12459         while ((i = nextopt("p:u:r"
12460                 IF_ASH_READ_TIMEOUT("t:")
12461                 IF_ASH_READ_NCHARS("n:s")
12462         )) != '\0') {
12463                 switch (i) {
12464                 case 'p':
12465                         prompt = optionarg;
12466                         break;
12467 #if ENABLE_ASH_READ_NCHARS
12468                 case 'n':
12469                         nchars = bb_strtou(optionarg, NULL, 10);
12470                         if (nchars < 0 || errno)
12471                                 ash_msg_and_raise_error("invalid count");
12472                         /* nchars == 0: off (bash 3.2 does this too) */
12473                         break;
12474                 case 's':
12475                         silent = 1;
12476                         break;
12477 #endif
12478 #if ENABLE_ASH_READ_TIMEOUT
12479                 case 't':
12480                         timeout = bb_strtou(optionarg, NULL, 10);
12481                         if (errno || timeout > UINT_MAX / 2048)
12482                                 ash_msg_and_raise_error("invalid timeout");
12483                         timeout *= 1000;
12484 #if 0 /* even bash have no -t N.NNN support */
12485                         ts.tv_sec = bb_strtou(optionarg, &p, 10);
12486                         ts.tv_usec = 0;
12487                         /* EINVAL means number is ok, but not terminated by NUL */
12488                         if (*p == '.' && errno == EINVAL) {
12489                                 char *p2;
12490                                 if (*++p) {
12491                                         int scale;
12492                                         ts.tv_usec = bb_strtou(p, &p2, 10);
12493                                         if (errno)
12494                                                 ash_msg_and_raise_error("invalid timeout");
12495                                         scale = p2 - p;
12496                                         /* normalize to usec */
12497                                         if (scale > 6)
12498                                                 ash_msg_and_raise_error("invalid timeout");
12499                                         while (scale++ < 6)
12500                                                 ts.tv_usec *= 10;
12501                                 }
12502                         } else if (ts.tv_sec < 0 || errno) {
12503                                 ash_msg_and_raise_error("invalid timeout");
12504                         }
12505                         if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12506                                 ash_msg_and_raise_error("invalid timeout");
12507                         }
12508 #endif /* if 0 */
12509                         break;
12510 #endif
12511                 case 'r':
12512                         rflag = 1;
12513                         break;
12514                 case 'u':
12515                         fd = bb_strtou(optionarg, NULL, 10);
12516                         if (fd < 0 || errno)
12517                                 ash_msg_and_raise_error("invalid file descriptor");
12518                         break;
12519                 default:
12520                         break;
12521                 }
12522         }
12523         if (prompt && isatty(fd)) {
12524                 out2str(prompt);
12525         }
12526         ap = argptr;
12527         if (*ap == NULL)
12528                 ap = (char**)arg_REPLY;
12529         ifs = bltinlookup("IFS");
12530         if (ifs == NULL)
12531                 ifs = defifs;
12532 #if ENABLE_ASH_READ_NCHARS
12533         tcgetattr(fd, &tty);
12534         old_tty = tty;
12535         if (nchars || silent) {
12536                 if (nchars) {
12537                         tty.c_lflag &= ~ICANON;
12538                         tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12539                 }
12540                 if (silent) {
12541                         tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12542                 }
12543                 /* if tcgetattr failed, tcsetattr will fail too.
12544                  * Ignoring, it's harmless. */
12545                 tcsetattr(fd, TCSANOW, &tty);
12546         }
12547 #endif
12548
12549         status = 0;
12550         startword = 2;
12551         backslash = 0;
12552 #if ENABLE_ASH_READ_TIMEOUT
12553         if (timeout) /* NB: ensuring end_ms is nonzero */
12554                 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12555 #endif
12556         STARTSTACKSTR(p);
12557         do {
12558                 const char *is_ifs;
12559
12560 #if ENABLE_ASH_READ_TIMEOUT
12561                 if (end_ms) {
12562                         struct pollfd pfd[1];
12563                         pfd[0].fd = fd;
12564                         pfd[0].events = POLLIN;
12565                         timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12566                         if ((int)timeout <= 0 /* already late? */
12567                          || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12568                         ) { /* timed out! */
12569 #if ENABLE_ASH_READ_NCHARS
12570                                 tcsetattr(fd, TCSANOW, &old_tty);
12571 #endif
12572                                 return 1;
12573                         }
12574                 }
12575 #endif
12576                 if (nonblock_safe_read(fd, &c, 1) != 1) {
12577                         status = 1;
12578                         break;
12579                 }
12580                 if (c == '\0')
12581                         continue;
12582                 if (backslash) {
12583                         backslash = 0;
12584                         if (c != '\n')
12585                                 goto put;
12586                         continue;
12587                 }
12588                 if (!rflag && c == '\\') {
12589                         backslash = 1;
12590                         continue;
12591                 }
12592                 if (c == '\n')
12593                         break;
12594                 /* $IFS splitting */
12595 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12596                 is_ifs = strchr(ifs, c);
12597                 if (startword && is_ifs) {
12598                         if (isspace(c))
12599                                 continue;
12600                         /* it is a non-space ifs char */
12601                         startword--;
12602                         if (startword == 1) /* first one? */
12603                                 continue; /* yes, it is not next word yet */
12604                 }
12605                 startword = 0;
12606                 if (ap[1] != NULL && is_ifs) {
12607                         const char *beg;
12608                         STACKSTRNUL(p);
12609                         beg = stackblock();
12610                         setvar(*ap, beg, 0);
12611                         ap++;
12612                         /* can we skip one non-space ifs char? (2: yes) */
12613                         startword = isspace(c) ? 2 : 1;
12614                         STARTSTACKSTR(p);
12615                         continue;
12616                 }
12617  put:
12618                 STPUTC(c, p);
12619         }
12620 /* end of do {} while: */
12621 #if ENABLE_ASH_READ_NCHARS
12622         while (--nchars);
12623 #else
12624         while (1);
12625 #endif
12626
12627 #if ENABLE_ASH_READ_NCHARS
12628         tcsetattr(fd, TCSANOW, &old_tty);
12629 #endif
12630
12631         STACKSTRNUL(p);
12632         /* Remove trailing space ifs chars */
12633         while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12634                 *p = '\0';
12635         setvar(*ap, stackblock(), 0);
12636         while (*++ap != NULL)
12637                 setvar(*ap, nullstr, 0);
12638         return status;
12639 }
12640
12641 static int FAST_FUNC
12642 umaskcmd(int argc UNUSED_PARAM, char **argv)
12643 {
12644         static const char permuser[3] ALIGN1 = "ugo";
12645         static const char permmode[3] ALIGN1 = "rwx";
12646         static const short permmask[] ALIGN2 = {
12647                 S_IRUSR, S_IWUSR, S_IXUSR,
12648                 S_IRGRP, S_IWGRP, S_IXGRP,
12649                 S_IROTH, S_IWOTH, S_IXOTH
12650         };
12651
12652         /* TODO: use bb_parse_mode() instead */
12653
12654         char *ap;
12655         mode_t mask;
12656         int i;
12657         int symbolic_mode = 0;
12658
12659         while (nextopt("S") != '\0') {
12660                 symbolic_mode = 1;
12661         }
12662
12663         INT_OFF;
12664         mask = umask(0);
12665         umask(mask);
12666         INT_ON;
12667
12668         ap = *argptr;
12669         if (ap == NULL) {
12670                 if (symbolic_mode) {
12671                         char buf[18];
12672                         char *p = buf;
12673
12674                         for (i = 0; i < 3; i++) {
12675                                 int j;
12676
12677                                 *p++ = permuser[i];
12678                                 *p++ = '=';
12679                                 for (j = 0; j < 3; j++) {
12680                                         if ((mask & permmask[3 * i + j]) == 0) {
12681                                                 *p++ = permmode[j];
12682                                         }
12683                                 }
12684                                 *p++ = ',';
12685                         }
12686                         *--p = 0;
12687                         puts(buf);
12688                 } else {
12689                         out1fmt("%.4o\n", mask);
12690                 }
12691         } else {
12692                 if (isdigit((unsigned char) *ap)) {
12693                         mask = 0;
12694                         do {
12695                                 if (*ap >= '8' || *ap < '0')
12696                                         ash_msg_and_raise_error(illnum, argv[1]);
12697                                 mask = (mask << 3) + (*ap - '0');
12698                         } while (*++ap != '\0');
12699                         umask(mask);
12700                 } else {
12701                         mask = ~mask & 0777;
12702                         if (!bb_parse_mode(ap, &mask)) {
12703                                 ash_msg_and_raise_error("illegal mode: %s", ap);
12704                         }
12705                         umask(~mask & 0777);
12706                 }
12707         }
12708         return 0;
12709 }
12710
12711 /*
12712  * ulimit builtin
12713  *
12714  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12715  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12716  * ash by J.T. Conklin.
12717  *
12718  * Public domain.
12719  */
12720 struct limits {
12721         uint8_t cmd;          /* RLIMIT_xxx fit into it */
12722         uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12723         char    option;
12724 };
12725
12726 static const struct limits limits_tbl[] = {
12727 #ifdef RLIMIT_CPU
12728         { RLIMIT_CPU,        0, 't' },
12729 #endif
12730 #ifdef RLIMIT_FSIZE
12731         { RLIMIT_FSIZE,      9, 'f' },
12732 #endif
12733 #ifdef RLIMIT_DATA
12734         { RLIMIT_DATA,      10, 'd' },
12735 #endif
12736 #ifdef RLIMIT_STACK
12737         { RLIMIT_STACK,     10, 's' },
12738 #endif
12739 #ifdef RLIMIT_CORE
12740         { RLIMIT_CORE,       9, 'c' },
12741 #endif
12742 #ifdef RLIMIT_RSS
12743         { RLIMIT_RSS,       10, 'm' },
12744 #endif
12745 #ifdef RLIMIT_MEMLOCK
12746         { RLIMIT_MEMLOCK,   10, 'l' },
12747 #endif
12748 #ifdef RLIMIT_NPROC
12749         { RLIMIT_NPROC,      0, 'p' },
12750 #endif
12751 #ifdef RLIMIT_NOFILE
12752         { RLIMIT_NOFILE,     0, 'n' },
12753 #endif
12754 #ifdef RLIMIT_AS
12755         { RLIMIT_AS,        10, 'v' },
12756 #endif
12757 #ifdef RLIMIT_LOCKS
12758         { RLIMIT_LOCKS,      0, 'w' },
12759 #endif
12760 };
12761 static const char limits_name[] =
12762 #ifdef RLIMIT_CPU
12763         "time(seconds)" "\0"
12764 #endif
12765 #ifdef RLIMIT_FSIZE
12766         "file(blocks)" "\0"
12767 #endif
12768 #ifdef RLIMIT_DATA
12769         "data(kb)" "\0"
12770 #endif
12771 #ifdef RLIMIT_STACK
12772         "stack(kb)" "\0"
12773 #endif
12774 #ifdef RLIMIT_CORE
12775         "coredump(blocks)" "\0"
12776 #endif
12777 #ifdef RLIMIT_RSS
12778         "memory(kb)" "\0"
12779 #endif
12780 #ifdef RLIMIT_MEMLOCK
12781         "locked memory(kb)" "\0"
12782 #endif
12783 #ifdef RLIMIT_NPROC
12784         "process" "\0"
12785 #endif
12786 #ifdef RLIMIT_NOFILE
12787         "nofiles" "\0"
12788 #endif
12789 #ifdef RLIMIT_AS
12790         "vmemory(kb)" "\0"
12791 #endif
12792 #ifdef RLIMIT_LOCKS
12793         "locks" "\0"
12794 #endif
12795 ;
12796
12797 enum limtype { SOFT = 0x1, HARD = 0x2 };
12798
12799 static void
12800 printlim(enum limtype how, const struct rlimit *limit,
12801                         const struct limits *l)
12802 {
12803         rlim_t val;
12804
12805         val = limit->rlim_max;
12806         if (how & SOFT)
12807                 val = limit->rlim_cur;
12808
12809         if (val == RLIM_INFINITY)
12810                 out1fmt("unlimited\n");
12811         else {
12812                 val >>= l->factor_shift;
12813                 out1fmt("%lld\n", (long long) val);
12814         }
12815 }
12816
12817 static int FAST_FUNC
12818 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12819 {
12820         int c;
12821         rlim_t val = 0;
12822         enum limtype how = SOFT | HARD;
12823         const struct limits *l;
12824         int set, all = 0;
12825         int optc, what;
12826         struct rlimit limit;
12827
12828         what = 'f';
12829         while ((optc = nextopt("HSa"
12830 #ifdef RLIMIT_CPU
12831                                 "t"
12832 #endif
12833 #ifdef RLIMIT_FSIZE
12834                                 "f"
12835 #endif
12836 #ifdef RLIMIT_DATA
12837                                 "d"
12838 #endif
12839 #ifdef RLIMIT_STACK
12840                                 "s"
12841 #endif
12842 #ifdef RLIMIT_CORE
12843                                 "c"
12844 #endif
12845 #ifdef RLIMIT_RSS
12846                                 "m"
12847 #endif
12848 #ifdef RLIMIT_MEMLOCK
12849                                 "l"
12850 #endif
12851 #ifdef RLIMIT_NPROC
12852                                 "p"
12853 #endif
12854 #ifdef RLIMIT_NOFILE
12855                                 "n"
12856 #endif
12857 #ifdef RLIMIT_AS
12858                                 "v"
12859 #endif
12860 #ifdef RLIMIT_LOCKS
12861                                 "w"
12862 #endif
12863                                         )) != '\0')
12864                 switch (optc) {
12865                 case 'H':
12866                         how = HARD;
12867                         break;
12868                 case 'S':
12869                         how = SOFT;
12870                         break;
12871                 case 'a':
12872                         all = 1;
12873                         break;
12874                 default:
12875                         what = optc;
12876                 }
12877
12878         for (l = limits_tbl; l->option != what; l++)
12879                 continue;
12880
12881         set = *argptr ? 1 : 0;
12882         if (set) {
12883                 char *p = *argptr;
12884
12885                 if (all || argptr[1])
12886                         ash_msg_and_raise_error("too many arguments");
12887                 if (strncmp(p, "unlimited\n", 9) == 0)
12888                         val = RLIM_INFINITY;
12889                 else {
12890                         val = (rlim_t) 0;
12891
12892                         while ((c = *p++) >= '0' && c <= '9') {
12893                                 val = (val * 10) + (long)(c - '0');
12894                                 // val is actually 'unsigned long int' and can't get < 0
12895                                 if (val < (rlim_t) 0)
12896                                         break;
12897                         }
12898                         if (c)
12899                                 ash_msg_and_raise_error("bad number");
12900                         val <<= l->factor_shift;
12901                 }
12902         }
12903         if (all) {
12904                 const char *lname = limits_name;
12905                 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12906                         getrlimit(l->cmd, &limit);
12907                         out1fmt("%-20s ", lname);
12908                         lname += strlen(lname) + 1;
12909                         printlim(how, &limit, l);
12910                 }
12911                 return 0;
12912         }
12913
12914         getrlimit(l->cmd, &limit);
12915         if (set) {
12916                 if (how & HARD)
12917                         limit.rlim_max = val;
12918                 if (how & SOFT)
12919                         limit.rlim_cur = val;
12920                 if (setrlimit(l->cmd, &limit) < 0)
12921                         ash_msg_and_raise_error("error setting limit (%m)");
12922         } else {
12923                 printlim(how, &limit, l);
12924         }
12925         return 0;
12926 }
12927
12928 /* ============ main() and helpers */
12929
12930 /*
12931  * Called to exit the shell.
12932  */
12933 static void exitshell(void) NORETURN;
12934 static void
12935 exitshell(void)
12936 {
12937         struct jmploc loc;
12938         char *p;
12939         int status;
12940
12941         status = exitstatus;
12942         TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12943         if (setjmp(loc.loc)) {
12944                 if (exception_type == EXEXIT)
12945 /* dash bug: it just does _exit(exitstatus) here
12946  * but we have to do setjobctl(0) first!
12947  * (bug is still not fixed in dash-0.5.3 - if you run dash
12948  * under Midnight Commander, on exit from dash MC is backgrounded) */
12949                         status = exitstatus;
12950                 goto out;
12951         }
12952         exception_handler = &loc;
12953         p = trap[0];
12954         if (p) {
12955                 trap[0] = NULL;
12956                 evalstring(p, 0);
12957         }
12958         flush_stdout_stderr();
12959  out:
12960         setjobctl(0);
12961         _exit(status);
12962         /* NOTREACHED */
12963 }
12964
12965 static void
12966 init(void)
12967 {
12968         /* from input.c: */
12969         basepf.next_to_pgetc = basepf.buf = basebuf;
12970
12971         /* from trap.c: */
12972         signal(SIGCHLD, SIG_DFL);
12973
12974         /* from var.c: */
12975         {
12976                 char **envp;
12977                 char ppid[sizeof(int)*3 + 1];
12978                 const char *p;
12979                 struct stat st1, st2;
12980
12981                 initvar();
12982                 for (envp = environ; envp && *envp; envp++) {
12983                         if (strchr(*envp, '=')) {
12984                                 setvareq(*envp, VEXPORT|VTEXTFIXED);
12985                         }
12986                 }
12987
12988                 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
12989                 setvar("PPID", ppid, 0);
12990
12991                 p = lookupvar("PWD");
12992                 if (p)
12993                         if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12994                          || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12995                                 p = '\0';
12996                 setpwd(p, 0);
12997         }
12998 }
12999
13000 /*
13001  * Process the shell command line arguments.
13002  */
13003 static void
13004 procargs(char **argv)
13005 {
13006         int i;
13007         const char *xminusc;
13008         char **xargv;
13009
13010         xargv = argv;
13011         arg0 = xargv[0];
13012         /* if (xargv[0]) - mmm, this is always true! */
13013                 xargv++;
13014         for (i = 0; i < NOPTS; i++)
13015                 optlist[i] = 2;
13016         argptr = xargv;
13017         if (options(1)) {
13018                 /* it already printed err message */
13019                 raise_exception(EXERROR);
13020         }
13021         xargv = argptr;
13022         xminusc = minusc;
13023         if (*xargv == NULL) {
13024                 if (xminusc)
13025                         ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13026                 sflag = 1;
13027         }
13028         if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13029                 iflag = 1;
13030         if (mflag == 2)
13031                 mflag = iflag;
13032         for (i = 0; i < NOPTS; i++)
13033                 if (optlist[i] == 2)
13034                         optlist[i] = 0;
13035 #if DEBUG == 2
13036         debug = 1;
13037 #endif
13038         /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13039         if (xminusc) {
13040                 minusc = *xargv++;
13041                 if (*xargv)
13042                         goto setarg0;
13043         } else if (!sflag) {
13044                 setinputfile(*xargv, 0);
13045  setarg0:
13046                 arg0 = *xargv++;
13047                 commandname = arg0;
13048         }
13049
13050         shellparam.p = xargv;
13051 #if ENABLE_ASH_GETOPTS
13052         shellparam.optind = 1;
13053         shellparam.optoff = -1;
13054 #endif
13055         /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13056         while (*xargv) {
13057                 shellparam.nparam++;
13058                 xargv++;
13059         }
13060         optschanged();
13061 }
13062
13063 /*
13064  * Read /etc/profile or .profile.
13065  */
13066 static void
13067 read_profile(const char *name)
13068 {
13069         int skip;
13070
13071         if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13072                 return;
13073         skip = cmdloop(0);
13074         popfile();
13075         if (skip)
13076                 exitshell();
13077 }
13078
13079 /*
13080  * This routine is called when an error or an interrupt occurs in an
13081  * interactive shell and control is returned to the main command loop.
13082  */
13083 static void
13084 reset(void)
13085 {
13086         /* from eval.c: */
13087         evalskip = 0;
13088         loopnest = 0;
13089         /* from input.c: */
13090         g_parsefile->left_in_buffer = 0;
13091         g_parsefile->left_in_line = 0;      /* clear input buffer */
13092         popallfiles();
13093         /* from parser.c: */
13094         tokpushback = 0;
13095         checkkwd = 0;
13096         /* from redir.c: */
13097         clearredir(/*drop:*/ 0);
13098 }
13099
13100 #if PROFILE
13101 static short profile_buf[16384];
13102 extern int etext();
13103 #endif
13104
13105 /*
13106  * Main routine.  We initialize things, parse the arguments, execute
13107  * profiles if we're a login shell, and then call cmdloop to execute
13108  * commands.  The setjmp call sets up the location to jump to when an
13109  * exception occurs.  When an exception occurs the variable "state"
13110  * is used to figure out how far we had gotten.
13111  */
13112 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13113 int ash_main(int argc UNUSED_PARAM, char **argv)
13114 {
13115         const char *shinit;
13116         volatile smallint state;
13117         struct jmploc jmploc;
13118         struct stackmark smark;
13119
13120         /* Initialize global data */
13121         INIT_G_misc();
13122         INIT_G_memstack();
13123         INIT_G_var();
13124 #if ENABLE_ASH_ALIAS
13125         INIT_G_alias();
13126 #endif
13127         INIT_G_cmdtable();
13128
13129 #if PROFILE
13130         monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13131 #endif
13132
13133 #if ENABLE_FEATURE_EDITING
13134         line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13135 #endif
13136         state = 0;
13137         if (setjmp(jmploc.loc)) {
13138                 smallint e;
13139                 smallint s;
13140
13141                 reset();
13142
13143                 e = exception_type;
13144                 if (e == EXERROR)
13145                         exitstatus = 2;
13146                 s = state;
13147                 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13148                         exitshell();
13149                 if (e == EXINT)
13150                         outcslow('\n', stderr);
13151
13152                 popstackmark(&smark);
13153                 FORCE_INT_ON; /* enable interrupts */
13154                 if (s == 1)
13155                         goto state1;
13156                 if (s == 2)
13157                         goto state2;
13158                 if (s == 3)
13159                         goto state3;
13160                 goto state4;
13161         }
13162         exception_handler = &jmploc;
13163 #if DEBUG
13164         opentrace();
13165         TRACE(("Shell args: "));
13166         trace_puts_args(argv);
13167 #endif
13168         rootpid = getpid();
13169
13170 #if ENABLE_ASH_RANDOM_SUPPORT
13171         /* Can use monotonic_ns() for better randomness but for now it is
13172          * not used anywhere else in busybox... so avoid bloat */
13173         random_galois_LFSR = random_LCG = rootpid + monotonic_us();
13174 #endif
13175         init();
13176         setstackmark(&smark);
13177         procargs(argv);
13178
13179 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13180         if (iflag) {
13181                 const char *hp = lookupvar("HISTFILE");
13182
13183                 if (hp == NULL) {
13184                         hp = lookupvar("HOME");
13185                         if (hp != NULL) {
13186                                 char *defhp = concat_path_file(hp, ".ash_history");
13187                                 setvar("HISTFILE", defhp, 0);
13188                                 free(defhp);
13189                         }
13190                 }
13191         }
13192 #endif
13193         if (/* argv[0] && */ argv[0][0] == '-')
13194                 isloginsh = 1;
13195         if (isloginsh) {
13196                 state = 1;
13197                 read_profile("/etc/profile");
13198  state1:
13199                 state = 2;
13200                 read_profile(".profile");
13201         }
13202  state2:
13203         state = 3;
13204         if (
13205 #ifndef linux
13206          getuid() == geteuid() && getgid() == getegid() &&
13207 #endif
13208          iflag
13209         ) {
13210                 shinit = lookupvar("ENV");
13211                 if (shinit != NULL && *shinit != '\0') {
13212                         read_profile(shinit);
13213                 }
13214         }
13215  state3:
13216         state = 4;
13217         if (minusc) {
13218                 /* evalstring pushes parsefile stack.
13219                  * Ensure we don't falsely claim that 0 (stdin)
13220                  * is one of stacked source fds.
13221                  * Testcase: ash -c 'exec 1>&0' must not complain. */
13222                 if (!sflag)
13223                         g_parsefile->fd = -1;
13224                 evalstring(minusc, 0);
13225         }
13226
13227         if (sflag || minusc == NULL) {
13228 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13229                 if (iflag) {
13230                         const char *hp = lookupvar("HISTFILE");
13231                         if (hp)
13232                                 line_input_state->hist_file = hp;
13233                 }
13234 #endif
13235  state4: /* XXX ??? - why isn't this before the "if" statement */
13236                 cmdloop(1);
13237         }
13238 #if PROFILE
13239         monitor(0);
13240 #endif
13241 #ifdef GPROF
13242         {
13243                 extern void _mcleanup(void);
13244                 _mcleanup();
13245         }
13246 #endif
13247         exitshell();
13248         /* NOTREACHED */
13249 }
13250
13251
13252 /*-
13253  * Copyright (c) 1989, 1991, 1993, 1994
13254  *      The Regents of the University of California.  All rights reserved.
13255  *
13256  * This code is derived from software contributed to Berkeley by
13257  * Kenneth Almquist.
13258  *
13259  * Redistribution and use in source and binary forms, with or without
13260  * modification, are permitted provided that the following conditions
13261  * are met:
13262  * 1. Redistributions of source code must retain the above copyright
13263  *    notice, this list of conditions and the following disclaimer.
13264  * 2. Redistributions in binary form must reproduce the above copyright
13265  *    notice, this list of conditions and the following disclaimer in the
13266  *    documentation and/or other materials provided with the distribution.
13267  * 3. Neither the name of the University nor the names of its contributors
13268  *    may be used to endorse or promote products derived from this software
13269  *    without specific prior written permission.
13270  *
13271  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13272  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13273  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13274  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13275  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13276  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13277  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13278  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13279  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13280  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13281  * SUCH DAMAGE.
13282  */