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