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