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