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