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