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