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