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