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