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