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