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