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