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