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