ash: fix display of ">&-" redirect in job strings
[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 GPLv2 or later, see file LICENSE in this source tree.
17  */
18 //config:config ASH
19 //config:       bool "ash (77 kb)"
20 //config:       default y
21 //config:       depends on !NOMMU
22 //config:       help
23 //config:       The most complete and most pedantically correct shell included with
24 //config:       busybox. This shell is actually a derivative of the Debian 'dash'
25 //config:       shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config:       (written by Kenneth Almquist) from NetBSD.
27 //config:
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
32 //config:
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config:       bool "Optimize for size instead of speed"
35 //config:       default y
36 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
37 //config:
38 //config:config ASH_INTERNAL_GLOB
39 //config:       bool "Use internal glob() implementation"
40 //config:       default y       # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
42 //config:       help
43 //config:       Do not use glob() function from libc, use internal implementation.
44 //config:       Use this if you are getting "glob.h: No such file or directory"
45 //config:       or similar build errors.
46 //config:       Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config:       which would break ash if you select N here.
48 //config:
49 //config:config ASH_BASH_COMPAT
50 //config:       bool "bash-compatible extensions"
51 //config:       default y
52 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
53 //config:
54 //config:config ASH_JOB_CONTROL
55 //config:       bool "Job control"
56 //config:       default y
57 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
58 //config:
59 //config:config ASH_ALIAS
60 //config:       bool "Alias support"
61 //config:       default y
62 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
63 //config:
64 //config:config ASH_RANDOM_SUPPORT
65 //config:       bool "Pseudorandom generator and $RANDOM variable"
66 //config:       default y
67 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
68 //config:       help
69 //config:       Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config:       Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config:       You can reset the generator by using a specified start value.
72 //config:       After "unset RANDOM" the generator will switch off and this
73 //config:       variable will no longer have special treatment.
74 //config:
75 //config:config ASH_EXPAND_PRMT
76 //config:       bool "Expand prompt string"
77 //config:       default y
78 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
79 //config:       help
80 //config:       $PS# may contain volatile content, such as backquote commands.
81 //config:       This option recreates the prompt string from the environment
82 //config:       variable each time it is displayed.
83 //config:
84 //config:config ASH_IDLE_TIMEOUT
85 //config:       bool "Idle timeout variable $TMOUT"
86 //config:       default y
87 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
88 //config:       help
89 //config:       Enable bash-like auto-logout after $TMOUT seconds of idle time.
90 //config:
91 //config:config ASH_MAIL
92 //config:       bool "Check for new mail in interactive shell"
93 //config:       default y
94 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
95 //config:       help
96 //config:       Enable "check for new mail" function:
97 //config:       if set, $MAIL file and $MAILPATH list of files
98 //config:       are checked for mtime changes, and "you have mail"
99 //config:       message is printed if change is detected.
100 //config:
101 //config:config ASH_ECHO
102 //config:       bool "echo builtin"
103 //config:       default y
104 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config:
106 //config:config ASH_PRINTF
107 //config:       bool "printf builtin"
108 //config:       default y
109 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
110 //config:
111 //config:config ASH_TEST
112 //config:       bool "test builtin"
113 //config:       default y
114 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
115 //config:
116 //config:config ASH_HELP
117 //config:       bool "help builtin"
118 //config:       default y
119 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
120 //config:
121 //config:config ASH_GETOPTS
122 //config:       bool "getopts builtin"
123 //config:       default y
124 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
125 //config:
126 //config:config ASH_CMDCMD
127 //config:       bool "command builtin"
128 //config:       default y
129 //config:       depends on ASH || SH_IS_ASH || BASH_IS_ASH
130 //config:       help
131 //config:       Enable support for the 'command' builtin, which allows
132 //config:       you to run the specified command or builtin,
133 //config:       even when there is a function with the same name.
134 //config:
135 //config:endif # ash options
136
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 //                      APPLET_ODDNAME:name  main location    suid_type     help
139 //applet:IF_SH_IS_ASH(  APPLET_ODDNAME(sh,   ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
141
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
146
147 /*
148  * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149  * DEBUG=2 to compile in and turn on debugging.
150  * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151  * debugging info is written to ./trace, quit signal generates core dump.
152  */
153 #define DEBUG 0
154 /* Tweak debug output verbosity here */
155 #define DEBUG_TIME 0
156 #define DEBUG_PID 1
157 #define DEBUG_SIG 1
158 #define DEBUG_INTONOFF 0
159
160 #define PROFILE 0
161
162 #define JOBS ENABLE_ASH_JOB_CONTROL
163
164 #include <setjmp.h>
165 #include <fnmatch.h>
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
169
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define    BASH_FUNCTION        ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION            IF_ASH_BASH_COMPAT
175 /* &>file */
176 #define    BASH_REDIR_OUTPUT    ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT        IF_ASH_BASH_COMPAT
178 /* $'...' */
179 #define    BASH_DOLLAR_SQUOTE   ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE       IF_ASH_BASH_COMPAT
181 #define    BASH_PATTERN_SUBST   ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST       IF_ASH_BASH_COMPAT
183 #define    BASH_SUBSTR          ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR              IF_ASH_BASH_COMPAT
185 /* [[ EXPR ]] */
186 #define    BASH_TEST2           (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define    BASH_SOURCE          ENABLE_ASH_BASH_COMPAT
188 #define    BASH_PIPEFAIL        ENABLE_ASH_BASH_COMPAT
189 #define    BASH_HOSTNAME_VAR    ENABLE_ASH_BASH_COMPAT
190 #define    BASH_SHLVL_VAR       ENABLE_ASH_BASH_COMPAT
191
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef  ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
196 #endif
197
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
204 // Testcase:
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
207 #endif
208
209 #if !ENABLE_ASH_INTERNAL_GLOB
210 # include <glob.h>
211 #endif
212
213 #include "unicode.h"
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
216 # include "math.h"
217 #else
218 typedef long arith_t;
219 # define ARITH_FMT "%ld"
220 #endif
221 #if ENABLE_ASH_RANDOM_SUPPORT
222 # include "random.h"
223 #else
224 # define CLEAR_RANDOM_T(rnd) ((void)0)
225 #endif
226
227 #include "NUM_APPLETS.h"
228 #if NUM_APPLETS == 1
229 /* STANDALONE does not make sense, and won't compile */
230 # undef CONFIG_FEATURE_SH_STANDALONE
231 # undef ENABLE_FEATURE_SH_STANDALONE
232 # undef IF_FEATURE_SH_STANDALONE
233 # undef IF_NOT_FEATURE_SH_STANDALONE
234 # define ENABLE_FEATURE_SH_STANDALONE 0
235 # define IF_FEATURE_SH_STANDALONE(...)
236 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
237 #endif
238
239 #ifndef PIPE_BUF
240 # define PIPE_BUF 4096           /* amount of buffering in a pipe */
241 #endif
242
243 #if !BB_MMU
244 # error "Do not even bother, ash will not run on NOMMU machine"
245 #endif
246
247
248 /* ============ Hash table sizes. Configurable. */
249
250 #define VTABSIZE 39
251 #define ATABSIZE 39
252 #define CMDTABLESIZE 31         /* should be prime */
253
254
255 /* ============ Shell options */
256
257 static const char *const optletters_optnames[] = {
258         "e"   "errexit",
259         "f"   "noglob",
260         "I"   "ignoreeof",
261         "i"   "interactive",
262         "m"   "monitor",
263         "n"   "noexec",
264         "s"   "stdin",
265         "x"   "xtrace",
266         "v"   "verbose",
267         "C"   "noclobber",
268         "a"   "allexport",
269         "b"   "notify",
270         "u"   "nounset",
271         "\0"  "vi"
272 #if BASH_PIPEFAIL
273         ,"\0"  "pipefail"
274 #endif
275 #if DEBUG
276         ,"\0"  "nolog"
277         ,"\0"  "debug"
278 #endif
279 };
280
281 #define optletters(n)  optletters_optnames[n][0]
282 #define optnames(n)   (optletters_optnames[n] + 1)
283
284 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
285
286
287 /* ============ Misc data */
288
289 #define msg_illnum "Illegal number: %s"
290
291 /*
292  * We enclose jmp_buf in a structure so that we can declare pointers to
293  * jump locations.  The global variable handler contains the location to
294  * jump to when an exception occurs, and the global variable exception_type
295  * contains a code identifying the exception.  To implement nested
296  * exception handlers, the user should save the value of handler on entry
297  * to an inner scope, set handler to point to a jmploc structure for the
298  * inner scope, and restore handler on exit from the scope.
299  */
300 struct jmploc {
301         jmp_buf loc;
302 };
303
304 struct globals_misc {
305         uint8_t exitstatus;     /* exit status of last command */
306         uint8_t back_exitstatus;/* exit status of backquoted command */
307         smallint job_warning;   /* user was warned about stopped jobs (can be 2, 1 or 0). */
308         int rootpid;            /* pid of main shell */
309         /* shell level: 0 for the main shell, 1 for its children, and so on */
310         int shlvl;
311 #define rootshell (!shlvl)
312         char *minusc;  /* argument to -c option */
313
314         char *curdir; // = nullstr;     /* current working directory */
315         char *physdir; // = nullstr;    /* physical working directory */
316
317         char *arg0; /* value of $0 */
318
319         struct jmploc *exception_handler;
320
321         volatile int suppress_int; /* counter */
322         volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
323         volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
324         volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
325         smallint exception_type; /* kind of exception (0..5) */
326         /* exceptions */
327 #define EXINT 0         /* SIGINT received */
328 #define EXERROR 1       /* a generic error */
329 #define EXEXIT 4        /* exit the shell */
330
331         smallint isloginsh;
332         char nullstr[1];        /* zero length string */
333
334         char optlist[NOPTS];
335 #define eflag optlist[0]
336 #define fflag optlist[1]
337 #define Iflag optlist[2]
338 #define iflag optlist[3]
339 #define mflag optlist[4]
340 #define nflag optlist[5]
341 #define sflag optlist[6]
342 #define xflag optlist[7]
343 #define vflag optlist[8]
344 #define Cflag optlist[9]
345 #define aflag optlist[10]
346 #define bflag optlist[11]
347 #define uflag optlist[12]
348 #define viflag optlist[13]
349 #if BASH_PIPEFAIL
350 # define pipefail optlist[14]
351 #else
352 # define pipefail 0
353 #endif
354 #if DEBUG
355 # define nolog optlist[14 + BASH_PIPEFAIL]
356 # define debug optlist[15 + BASH_PIPEFAIL]
357 #endif
358
359         /* trap handler commands */
360         /*
361          * Sigmode records the current value of the signal handlers for the various
362          * modes.  A value of zero means that the current handler is not known.
363          * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
364          */
365         char sigmode[NSIG - 1];
366 #define S_DFL      1            /* default signal handling (SIG_DFL) */
367 #define S_CATCH    2            /* signal is caught */
368 #define S_IGN      3            /* signal is ignored (SIG_IGN) */
369 #define S_HARD_IGN 4            /* signal is ignored permanently */
370
371         /* indicates specified signal received */
372         uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
373         uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
374         char *trap[NSIG];
375         char **trap_ptr;        /* used only by "trap hack" */
376
377         /* Rarely referenced stuff */
378 #if ENABLE_ASH_RANDOM_SUPPORT
379         random_t random_gen;
380 #endif
381         pid_t backgndpid;        /* pid of last background process */
382 };
383 extern struct globals_misc *const ash_ptr_to_globals_misc;
384 #define G_misc (*ash_ptr_to_globals_misc)
385 #define exitstatus        (G_misc.exitstatus )
386 #define back_exitstatus   (G_misc.back_exitstatus )
387 #define job_warning       (G_misc.job_warning)
388 #define rootpid     (G_misc.rootpid    )
389 #define shlvl       (G_misc.shlvl      )
390 #define minusc      (G_misc.minusc     )
391 #define curdir      (G_misc.curdir     )
392 #define physdir     (G_misc.physdir    )
393 #define arg0        (G_misc.arg0       )
394 #define exception_handler (G_misc.exception_handler)
395 #define exception_type    (G_misc.exception_type   )
396 #define suppress_int      (G_misc.suppress_int     )
397 #define pending_int       (G_misc.pending_int      )
398 #define got_sigchld       (G_misc.got_sigchld      )
399 #define pending_sig       (G_misc.pending_sig      )
400 #define isloginsh   (G_misc.isloginsh  )
401 #define nullstr     (G_misc.nullstr    )
402 #define optlist     (G_misc.optlist    )
403 #define sigmode     (G_misc.sigmode    )
404 #define gotsig      (G_misc.gotsig     )
405 #define may_have_traps    (G_misc.may_have_traps   )
406 #define trap        (G_misc.trap       )
407 #define trap_ptr    (G_misc.trap_ptr   )
408 #define random_gen  (G_misc.random_gen )
409 #define backgndpid  (G_misc.backgndpid )
410 #define INIT_G_misc() do { \
411         (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
412         barrier(); \
413         curdir = nullstr; \
414         physdir = nullstr; \
415         trap_ptr = trap; \
416 } while (0)
417
418
419 /* ============ DEBUG */
420 #if DEBUG
421 static void trace_printf(const char *fmt, ...);
422 static void trace_vprintf(const char *fmt, va_list va);
423 # define TRACE(param)    trace_printf param
424 # define TRACEV(param)   trace_vprintf param
425 # define close(fd) do { \
426         int dfd = (fd); \
427         if (close(dfd) < 0) \
428                 bb_error_msg("bug on %d: closing %d(0x%x)", \
429                         __LINE__, dfd, dfd); \
430 } while (0)
431 #else
432 # define TRACE(param)
433 # define TRACEV(param)
434 #endif
435
436
437 /* ============ Utility functions */
438 #define is_name(c)      ((c) == '_' || isalpha((unsigned char)(c)))
439 #define is_in_name(c)   ((c) == '_' || isalnum((unsigned char)(c)))
440
441 static int
442 isdigit_str9(const char *str)
443 {
444         int maxlen = 9 + 1; /* max 9 digits: 999999999 */
445         while (--maxlen && isdigit(*str))
446                 str++;
447         return (*str == '\0');
448 }
449
450 static const char *
451 var_end(const char *var)
452 {
453         while (*var)
454                 if (*var++ == '=')
455                         break;
456         return var;
457 }
458
459
460 /* ============ Interrupts / exceptions */
461
462 static void exitshell(void) NORETURN;
463
464 /*
465  * These macros allow the user to suspend the handling of interrupt signals
466  * over a period of time.  This is similar to SIGHOLD or to sigblock, but
467  * much more efficient and portable.  (But hacking the kernel is so much
468  * more fun than worrying about efficiency and portability. :-))
469  */
470 #if DEBUG_INTONOFF
471 # define INT_OFF do { \
472         TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
473         suppress_int++; \
474         barrier(); \
475 } while (0)
476 #else
477 # define INT_OFF do { \
478         suppress_int++; \
479         barrier(); \
480 } while (0)
481 #endif
482
483 /*
484  * Called to raise an exception.  Since C doesn't include exceptions, we
485  * just do a longjmp to the exception handler.  The type of exception is
486  * stored in the global variable "exception_type".
487  */
488 static void raise_exception(int) NORETURN;
489 static void
490 raise_exception(int e)
491 {
492 #if DEBUG
493         if (exception_handler == NULL)
494                 abort();
495 #endif
496         INT_OFF;
497         exception_type = e;
498         longjmp(exception_handler->loc, 1);
499 }
500 #if DEBUG
501 #define raise_exception(e) do { \
502         TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
503         raise_exception(e); \
504 } while (0)
505 #endif
506
507 /*
508  * Called when a SIGINT is received.  (If the user specifies
509  * that SIGINT is to be trapped or ignored using the trap builtin, then
510  * this routine is not called.)  Suppressint is nonzero when interrupts
511  * are held using the INT_OFF macro.  (The test for iflag is just
512  * defensive programming.)
513  */
514 static void raise_interrupt(void) NORETURN;
515 static void
516 raise_interrupt(void)
517 {
518         pending_int = 0;
519         /* Signal is not automatically unmasked after it is raised,
520          * do it ourself - unmask all signals */
521         sigprocmask_allsigs(SIG_UNBLOCK);
522         /* pending_sig = 0; - now done in signal_handler() */
523
524         if (!(rootshell && iflag)) {
525                 /* Kill ourself with SIGINT */
526                 signal(SIGINT, SIG_DFL);
527                 raise(SIGINT);
528         }
529         /* bash: ^C even on empty command line sets $? */
530         exitstatus = SIGINT + 128;
531         raise_exception(EXINT);
532         /* NOTREACHED */
533 }
534 #if DEBUG
535 #define raise_interrupt() do { \
536         TRACE(("raising interrupt on line %d\n", __LINE__)); \
537         raise_interrupt(); \
538 } while (0)
539 #endif
540
541 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
542 int_on(void)
543 {
544         barrier();
545         if (--suppress_int == 0 && pending_int) {
546                 raise_interrupt();
547         }
548 }
549 #if DEBUG_INTONOFF
550 # define INT_ON do { \
551         TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
552         int_on(); \
553 } while (0)
554 #else
555 # define INT_ON int_on()
556 #endif
557 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
558 force_int_on(void)
559 {
560         barrier();
561         suppress_int = 0;
562         if (pending_int)
563                 raise_interrupt();
564 }
565 #define FORCE_INT_ON force_int_on()
566
567 #define SAVE_INT(v) ((v) = suppress_int)
568
569 #define RESTORE_INT(v) do { \
570         barrier(); \
571         suppress_int = (v); \
572         if (suppress_int == 0 && pending_int) \
573                 raise_interrupt(); \
574 } while (0)
575
576
577 /* ============ Stdout/stderr output */
578
579 static void
580 outstr(const char *p, FILE *file)
581 {
582         INT_OFF;
583         fputs(p, file);
584         INT_ON;
585 }
586
587 static void
588 flush_stdout_stderr(void)
589 {
590         INT_OFF;
591         fflush_all();
592         INT_ON;
593 }
594
595 /* Was called outcslow(c,FILE*), but c was always '\n' */
596 static void
597 newline_and_flush(FILE *dest)
598 {
599         INT_OFF;
600         putc('\n', dest);
601         fflush(dest);
602         INT_ON;
603 }
604
605 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
606 static int
607 out1fmt(const char *fmt, ...)
608 {
609         va_list ap;
610         int r;
611
612         INT_OFF;
613         va_start(ap, fmt);
614         r = vprintf(fmt, ap);
615         va_end(ap);
616         INT_ON;
617         return r;
618 }
619
620 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
621 static int
622 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
623 {
624         va_list ap;
625         int ret;
626
627         INT_OFF;
628         va_start(ap, fmt);
629         ret = vsnprintf(outbuf, length, fmt, ap);
630         va_end(ap);
631         INT_ON;
632         return ret;
633 }
634
635 static void
636 out1str(const char *p)
637 {
638         outstr(p, stdout);
639 }
640
641 static void
642 out2str(const char *p)
643 {
644         outstr(p, stderr);
645         flush_stdout_stderr();
646 }
647
648
649 /* ============ Parser structures */
650
651 /* control characters in argument strings */
652 #define CTL_FIRST CTLESC
653 #define CTLESC       ((unsigned char)'\201')    /* escape next character */
654 #define CTLVAR       ((unsigned char)'\202')    /* variable defn */
655 #define CTLENDVAR    ((unsigned char)'\203')
656 #define CTLBACKQ     ((unsigned char)'\204')
657 #define CTLARI       ((unsigned char)'\206')    /* arithmetic expression */
658 #define CTLENDARI    ((unsigned char)'\207')
659 #define CTLQUOTEMARK ((unsigned char)'\210')
660 #define CTL_LAST CTLQUOTEMARK
661
662 /* variable substitution byte (follows CTLVAR) */
663 #define VSTYPE  0x0f            /* type of variable substitution */
664 #define VSNUL   0x10            /* colon--treat the empty string as unset */
665
666 /* values of VSTYPE field */
667 #define VSNORMAL        0x1     /* normal variable:  $var or ${var} */
668 #define VSMINUS         0x2     /* ${var-text} */
669 #define VSPLUS          0x3     /* ${var+text} */
670 #define VSQUESTION      0x4     /* ${var?message} */
671 #define VSASSIGN        0x5     /* ${var=text} */
672 #define VSTRIMRIGHT     0x6     /* ${var%pattern} */
673 #define VSTRIMRIGHTMAX  0x7     /* ${var%%pattern} */
674 #define VSTRIMLEFT      0x8     /* ${var#pattern} */
675 #define VSTRIMLEFTMAX   0x9     /* ${var##pattern} */
676 #define VSLENGTH        0xa     /* ${#var} */
677 #if BASH_SUBSTR
678 #define VSSUBSTR        0xc     /* ${var:position:length} */
679 #endif
680 #if BASH_PATTERN_SUBST
681 #define VSREPLACE       0xd     /* ${var/pattern/replacement} */
682 #define VSREPLACEALL    0xe     /* ${var//pattern/replacement} */
683 #endif
684
685 static const char dolatstr[] ALIGN1 = {
686         CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
687 };
688 #define DOLATSTRLEN 6
689
690 #define NCMD      0
691 #define NPIPE     1
692 #define NREDIR    2
693 #define NBACKGND  3
694 #define NSUBSHELL 4
695 #define NAND      5
696 #define NOR       6
697 #define NSEMI     7
698 #define NIF       8
699 #define NWHILE    9
700 #define NUNTIL   10
701 #define NFOR     11
702 #define NCASE    12
703 #define NCLIST   13
704 #define NDEFUN   14
705 #define NARG     15
706 #define NTO      16
707 #if BASH_REDIR_OUTPUT
708 #define NTO2     17
709 #endif
710 #define NCLOBBER 18
711 #define NFROM    19
712 #define NFROMTO  20
713 #define NAPPEND  21
714 #define NTOFD    22
715 #define NFROMFD  23
716 #define NHERE    24
717 #define NXHERE   25
718 #define NNOT     26
719 #define N_NUMBER 27
720
721 union node;
722
723 struct ncmd {
724         smallint type; /* Nxxxx */
725         union node *assign;
726         union node *args;
727         union node *redirect;
728 };
729
730 struct npipe {
731         smallint type;
732         smallint pipe_backgnd;
733         struct nodelist *cmdlist;
734 };
735
736 struct nredir {
737         smallint type;
738         union node *n;
739         union node *redirect;
740 };
741
742 struct nbinary {
743         smallint type;
744         union node *ch1;
745         union node *ch2;
746 };
747
748 struct nif {
749         smallint type;
750         union node *test;
751         union node *ifpart;
752         union node *elsepart;
753 };
754
755 struct nfor {
756         smallint type;
757         union node *args;
758         union node *body;
759         char *var;
760 };
761
762 struct ncase {
763         smallint type;
764         union node *expr;
765         union node *cases;
766 };
767
768 struct nclist {
769         smallint type;
770         union node *next;
771         union node *pattern;
772         union node *body;
773 };
774
775 struct narg {
776         smallint type;
777         union node *next;
778         char *text;
779         struct nodelist *backquote;
780 };
781
782 /* nfile and ndup layout must match!
783  * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
784  * that it is actually NTO2 (>&file), and change its type.
785  */
786 struct nfile {
787         smallint type;
788         union node *next;
789         int fd;
790         int _unused_dupfd;
791         union node *fname;
792         char *expfname;
793 };
794
795 struct ndup {
796         smallint type;
797         union node *next;
798         int fd;
799         int dupfd;
800         union node *vname;
801         char *_unused_expfname;
802 };
803
804 struct nhere {
805         smallint type;
806         union node *next;
807         int fd;
808         union node *doc;
809 };
810
811 struct nnot {
812         smallint type;
813         union node *com;
814 };
815
816 union node {
817         smallint type;
818         struct ncmd ncmd;
819         struct npipe npipe;
820         struct nredir nredir;
821         struct nbinary nbinary;
822         struct nif nif;
823         struct nfor nfor;
824         struct ncase ncase;
825         struct nclist nclist;
826         struct narg narg;
827         struct nfile nfile;
828         struct ndup ndup;
829         struct nhere nhere;
830         struct nnot nnot;
831 };
832
833 /*
834  * NODE_EOF is returned by parsecmd when it encounters an end of file.
835  * It must be distinct from NULL.
836  */
837 #define NODE_EOF ((union node *) -1L)
838
839 struct nodelist {
840         struct nodelist *next;
841         union node *n;
842 };
843
844 struct funcnode {
845         int count;
846         union node n;
847 };
848
849 /*
850  * Free a parse tree.
851  */
852 static void
853 freefunc(struct funcnode *f)
854 {
855         if (f && --f->count < 0)
856                 free(f);
857 }
858
859
860 /* ============ Debugging output */
861
862 #if DEBUG
863
864 static FILE *tracefile;
865
866 static void
867 trace_printf(const char *fmt, ...)
868 {
869         va_list va;
870
871         if (debug != 1)
872                 return;
873         if (DEBUG_TIME)
874                 fprintf(tracefile, "%u ", (int) time(NULL));
875         if (DEBUG_PID)
876                 fprintf(tracefile, "[%u] ", (int) getpid());
877         if (DEBUG_SIG)
878                 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
879         va_start(va, fmt);
880         vfprintf(tracefile, fmt, va);
881         va_end(va);
882 }
883
884 static void
885 trace_vprintf(const char *fmt, va_list va)
886 {
887         if (debug != 1)
888                 return;
889         vfprintf(tracefile, fmt, va);
890         fprintf(tracefile, "\n");
891 }
892
893 static void
894 trace_puts(const char *s)
895 {
896         if (debug != 1)
897                 return;
898         fputs(s, tracefile);
899 }
900
901 static void
902 trace_puts_quoted(char *s)
903 {
904         char *p;
905         char c;
906
907         if (debug != 1)
908                 return;
909         putc('"', tracefile);
910         for (p = s; *p; p++) {
911                 switch ((unsigned char)*p) {
912                 case '\n': c = 'n'; goto backslash;
913                 case '\t': c = 't'; goto backslash;
914                 case '\r': c = 'r'; goto backslash;
915                 case '\"': c = '\"'; goto backslash;
916                 case '\\': c = '\\'; goto backslash;
917                 case CTLESC: c = 'e'; goto backslash;
918                 case CTLVAR: c = 'v'; goto backslash;
919                 case CTLBACKQ: c = 'q'; goto backslash;
920  backslash:
921                         putc('\\', tracefile);
922                         putc(c, tracefile);
923                         break;
924                 default:
925                         if (*p >= ' ' && *p <= '~')
926                                 putc(*p, tracefile);
927                         else {
928                                 putc('\\', tracefile);
929                                 putc((*p >> 6) & 03, tracefile);
930                                 putc((*p >> 3) & 07, tracefile);
931                                 putc(*p & 07, tracefile);
932                         }
933                         break;
934                 }
935         }
936         putc('"', tracefile);
937 }
938
939 static void
940 trace_puts_args(char **ap)
941 {
942         if (debug != 1)
943                 return;
944         if (!*ap)
945                 return;
946         while (1) {
947                 trace_puts_quoted(*ap);
948                 if (!*++ap) {
949                         putc('\n', tracefile);
950                         break;
951                 }
952                 putc(' ', tracefile);
953         }
954 }
955
956 static void
957 opentrace(void)
958 {
959         char s[100];
960 #ifdef O_APPEND
961         int flags;
962 #endif
963
964         if (debug != 1) {
965                 if (tracefile)
966                         fflush(tracefile);
967                 /* leave open because libedit might be using it */
968                 return;
969         }
970         strcpy(s, "./trace");
971         if (tracefile) {
972                 if (!freopen(s, "a", tracefile)) {
973                         fprintf(stderr, "Can't re-open %s\n", s);
974                         debug = 0;
975                         return;
976                 }
977         } else {
978                 tracefile = fopen(s, "a");
979                 if (tracefile == NULL) {
980                         fprintf(stderr, "Can't open %s\n", s);
981                         debug = 0;
982                         return;
983                 }
984         }
985 #ifdef O_APPEND
986         flags = fcntl(fileno(tracefile), F_GETFL);
987         if (flags >= 0)
988                 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
989 #endif
990         setlinebuf(tracefile);
991         fputs("\nTracing started.\n", tracefile);
992 }
993
994 static void
995 indent(int amount, char *pfx, FILE *fp)
996 {
997         int i;
998
999         for (i = 0; i < amount; i++) {
1000                 if (pfx && i == amount - 1)
1001                         fputs(pfx, fp);
1002                 putc('\t', fp);
1003         }
1004 }
1005
1006 /* little circular references here... */
1007 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1008
1009 static void
1010 sharg(union node *arg, FILE *fp)
1011 {
1012         char *p;
1013         struct nodelist *bqlist;
1014         unsigned char subtype;
1015
1016         if (arg->type != NARG) {
1017                 out1fmt("<node type %d>\n", arg->type);
1018                 abort();
1019         }
1020         bqlist = arg->narg.backquote;
1021         for (p = arg->narg.text; *p; p++) {
1022                 switch ((unsigned char)*p) {
1023                 case CTLESC:
1024                         p++;
1025                         putc(*p, fp);
1026                         break;
1027                 case CTLVAR:
1028                         putc('$', fp);
1029                         putc('{', fp);
1030                         subtype = *++p;
1031                         if (subtype == VSLENGTH)
1032                                 putc('#', fp);
1033
1034                         while (*p != '=') {
1035                                 putc(*p, fp);
1036                                 p++;
1037                         }
1038
1039                         if (subtype & VSNUL)
1040                                 putc(':', fp);
1041
1042                         switch (subtype & VSTYPE) {
1043                         case VSNORMAL:
1044                                 putc('}', fp);
1045                                 break;
1046                         case VSMINUS:
1047                                 putc('-', fp);
1048                                 break;
1049                         case VSPLUS:
1050                                 putc('+', fp);
1051                                 break;
1052                         case VSQUESTION:
1053                                 putc('?', fp);
1054                                 break;
1055                         case VSASSIGN:
1056                                 putc('=', fp);
1057                                 break;
1058                         case VSTRIMLEFT:
1059                                 putc('#', fp);
1060                                 break;
1061                         case VSTRIMLEFTMAX:
1062                                 putc('#', fp);
1063                                 putc('#', fp);
1064                                 break;
1065                         case VSTRIMRIGHT:
1066                                 putc('%', fp);
1067                                 break;
1068                         case VSTRIMRIGHTMAX:
1069                                 putc('%', fp);
1070                                 putc('%', fp);
1071                                 break;
1072                         case VSLENGTH:
1073                                 break;
1074                         default:
1075                                 out1fmt("<subtype %d>", subtype);
1076                         }
1077                         break;
1078                 case CTLENDVAR:
1079                         putc('}', fp);
1080                         break;
1081                 case CTLBACKQ:
1082                         putc('$', fp);
1083                         putc('(', fp);
1084                         shtree(bqlist->n, -1, NULL, fp);
1085                         putc(')', fp);
1086                         break;
1087                 default:
1088                         putc(*p, fp);
1089                         break;
1090                 }
1091         }
1092 }
1093
1094 static void
1095 shcmd(union node *cmd, FILE *fp)
1096 {
1097         union node *np;
1098         int first;
1099         const char *s;
1100         int dftfd;
1101
1102         first = 1;
1103         for (np = cmd->ncmd.args; np; np = np->narg.next) {
1104                 if (!first)
1105                         putc(' ', fp);
1106                 sharg(np, fp);
1107                 first = 0;
1108         }
1109         for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1110                 if (!first)
1111                         putc(' ', fp);
1112                 dftfd = 0;
1113                 switch (np->nfile.type) {
1114                 case NTO:      s = ">>"+1; dftfd = 1; break;
1115                 case NCLOBBER: s = ">|"; dftfd = 1; break;
1116                 case NAPPEND:  s = ">>"; dftfd = 1; break;
1117 #if BASH_REDIR_OUTPUT
1118                 case NTO2:
1119 #endif
1120                 case NTOFD:    s = ">&"; dftfd = 1; break;
1121                 case NFROM:    s = "<"; break;
1122                 case NFROMFD:  s = "<&"; break;
1123                 case NFROMTO:  s = "<>"; break;
1124                 default:       s = "*error*"; break;
1125                 }
1126                 if (np->nfile.fd != dftfd)
1127                         fprintf(fp, "%d", np->nfile.fd);
1128                 fputs(s, fp);
1129                 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1130                         fprintf(fp, "%d", np->ndup.dupfd);
1131                 } else {
1132                         sharg(np->nfile.fname, fp);
1133                 }
1134                 first = 0;
1135         }
1136 }
1137
1138 static void
1139 shtree(union node *n, int ind, char *pfx, FILE *fp)
1140 {
1141         struct nodelist *lp;
1142         const char *s;
1143
1144         if (n == NULL)
1145                 return;
1146
1147         indent(ind, pfx, fp);
1148
1149         if (n == NODE_EOF) {
1150                 fputs("<EOF>", fp);
1151                 return;
1152         }
1153
1154         switch (n->type) {
1155         case NSEMI:
1156                 s = "; ";
1157                 goto binop;
1158         case NAND:
1159                 s = " && ";
1160                 goto binop;
1161         case NOR:
1162                 s = " || ";
1163  binop:
1164                 shtree(n->nbinary.ch1, ind, NULL, fp);
1165                 /* if (ind < 0) */
1166                         fputs(s, fp);
1167                 shtree(n->nbinary.ch2, ind, NULL, fp);
1168                 break;
1169         case NCMD:
1170                 shcmd(n, fp);
1171                 if (ind >= 0)
1172                         putc('\n', fp);
1173                 break;
1174         case NPIPE:
1175                 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1176                         shtree(lp->n, 0, NULL, fp);
1177                         if (lp->next)
1178                                 fputs(" | ", fp);
1179                 }
1180                 if (n->npipe.pipe_backgnd)
1181                         fputs(" &", fp);
1182                 if (ind >= 0)
1183                         putc('\n', fp);
1184                 break;
1185         default:
1186                 fprintf(fp, "<node type %d>", n->type);
1187                 if (ind >= 0)
1188                         putc('\n', fp);
1189                 break;
1190         }
1191 }
1192
1193 static void
1194 showtree(union node *n)
1195 {
1196         trace_puts("showtree called\n");
1197         shtree(n, 1, NULL, stderr);
1198 }
1199
1200 #endif /* DEBUG */
1201
1202
1203 /* ============ Parser data */
1204
1205 /*
1206  * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1207  */
1208 struct strlist {
1209         struct strlist *next;
1210         char *text;
1211 };
1212
1213 struct alias;
1214
1215 struct strpush {
1216         struct strpush *prev;   /* preceding string on stack */
1217         char *prev_string;
1218         int prev_left_in_line;
1219 #if ENABLE_ASH_ALIAS
1220         struct alias *ap;       /* if push was associated with an alias */
1221 #endif
1222         char *string;           /* remember the string since it may change */
1223
1224         /* Remember last two characters for pungetc. */
1225         int lastc[2];
1226
1227         /* Number of outstanding calls to pungetc. */
1228         int unget;
1229 };
1230
1231 struct parsefile {
1232         struct parsefile *prev; /* preceding file on stack */
1233         int linno;              /* current line */
1234         int pf_fd;              /* file descriptor (or -1 if string) */
1235         int left_in_line;       /* number of chars left in this line */
1236         int left_in_buffer;     /* number of chars left in this buffer past the line */
1237         char *next_to_pgetc;    /* next char in buffer */
1238         char *buf;              /* input buffer */
1239         struct strpush *strpush; /* for pushing strings at this level */
1240         struct strpush basestrpush; /* so pushing one is fast */
1241
1242         /* Remember last two characters for pungetc. */
1243         int lastc[2];
1244
1245         /* Number of outstanding calls to pungetc. */
1246         int unget;
1247 };
1248
1249 static struct parsefile basepf;        /* top level input file */
1250 static struct parsefile *g_parsefile = &basepf;  /* current input file */
1251 static int startlinno;                 /* line # where last token started */
1252 static char *commandname;              /* currently executing command */
1253
1254
1255 /* ============ Message printing */
1256
1257 static void
1258 ash_vmsg(const char *msg, va_list ap)
1259 {
1260         fprintf(stderr, "%s: ", arg0);
1261         if (commandname) {
1262                 if (strcmp(arg0, commandname))
1263                         fprintf(stderr, "%s: ", commandname);
1264                 if (!iflag || g_parsefile->pf_fd > 0)
1265                         fprintf(stderr, "line %d: ", startlinno);
1266         }
1267         vfprintf(stderr, msg, ap);
1268         newline_and_flush(stderr);
1269 }
1270
1271 /*
1272  * Exverror is called to raise the error exception.  If the second argument
1273  * is not NULL then error prints an error message using printf style
1274  * formatting.  It then raises the error exception.
1275  */
1276 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1277 static void
1278 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1279 {
1280 #if DEBUG
1281         if (msg) {
1282                 TRACE(("ash_vmsg_and_raise(%d):", cond));
1283                 TRACEV((msg, ap));
1284         } else
1285                 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1286         if (msg)
1287 #endif
1288                 ash_vmsg(msg, ap);
1289
1290         flush_stdout_stderr();
1291         raise_exception(cond);
1292         /* NOTREACHED */
1293 }
1294
1295 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1296 static void
1297 ash_msg_and_raise_error(const char *msg, ...)
1298 {
1299         va_list ap;
1300
1301         exitstatus = 2;
1302
1303         va_start(ap, msg);
1304         ash_vmsg_and_raise(EXERROR, msg, ap);
1305         /* NOTREACHED */
1306         va_end(ap);
1307 }
1308
1309 /*
1310  * Use '%m' to append error string on platforms that support it, '%s' and
1311  * strerror() on those that don't.
1312  *
1313  * 'fmt' must be a string literal.
1314  */
1315 #ifdef HAVE_PRINTF_PERCENTM
1316 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1317 #else
1318 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1319 #endif
1320
1321 static void raise_error_syntax(const char *) NORETURN;
1322 static void
1323 raise_error_syntax(const char *msg)
1324 {
1325         ash_msg_and_raise_error("syntax error: %s", msg);
1326         /* NOTREACHED */
1327 }
1328
1329 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1330 static void
1331 ash_msg_and_raise(int cond, const char *msg, ...)
1332 {
1333         va_list ap;
1334
1335         va_start(ap, msg);
1336         ash_vmsg_and_raise(cond, msg, ap);
1337         /* NOTREACHED */
1338         va_end(ap);
1339 }
1340
1341 /*
1342  * error/warning routines for external builtins
1343  */
1344 static void
1345 ash_msg(const char *fmt, ...)
1346 {
1347         va_list ap;
1348
1349         va_start(ap, fmt);
1350         ash_vmsg(fmt, ap);
1351         va_end(ap);
1352 }
1353
1354 /*
1355  * Return a string describing an error.  The returned string may be a
1356  * pointer to a static buffer that will be overwritten on the next call.
1357  * Action describes the operation that got the error.
1358  */
1359 static const char *
1360 errmsg(int e, const char *em)
1361 {
1362         if (e == ENOENT || e == ENOTDIR) {
1363                 return em;
1364         }
1365         return strerror(e);
1366 }
1367
1368
1369 /* ============ Memory allocation */
1370
1371 #if 0
1372 /* I consider these wrappers nearly useless:
1373  * ok, they return you to nearest exception handler, but
1374  * how much memory do you leak in the process, making
1375  * memory starvation worse?
1376  */
1377 static void *
1378 ckrealloc(void * p, size_t nbytes)
1379 {
1380         p = realloc(p, nbytes);
1381         if (!p)
1382                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1383         return p;
1384 }
1385
1386 static void *
1387 ckmalloc(size_t nbytes)
1388 {
1389         return ckrealloc(NULL, nbytes);
1390 }
1391
1392 static void *
1393 ckzalloc(size_t nbytes)
1394 {
1395         return memset(ckmalloc(nbytes), 0, nbytes);
1396 }
1397
1398 static char *
1399 ckstrdup(const char *s)
1400 {
1401         char *p = strdup(s);
1402         if (!p)
1403                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1404         return p;
1405 }
1406 #else
1407 /* Using bbox equivalents. They exit if out of memory */
1408 # define ckrealloc xrealloc
1409 # define ckmalloc  xmalloc
1410 # define ckzalloc  xzalloc
1411 # define ckstrdup  xstrdup
1412 #endif
1413
1414 /*
1415  * It appears that grabstackstr() will barf with such alignments
1416  * because stalloc() will return a string allocated in a new stackblock.
1417  */
1418 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1419 enum {
1420         /* Most machines require the value returned from malloc to be aligned
1421          * in some way.  The following macro will get this right
1422          * on many machines.  */
1423         SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1424         /* Minimum size of a block */
1425         MINSIZE = SHELL_ALIGN(504),
1426 };
1427
1428 struct stack_block {
1429         struct stack_block *prev;
1430         char space[MINSIZE];
1431 };
1432
1433 struct stackmark {
1434         struct stack_block *stackp;
1435         char *stacknxt;
1436         size_t stacknleft;
1437 };
1438
1439
1440 struct globals_memstack {
1441         struct stack_block *g_stackp; // = &stackbase;
1442         char *g_stacknxt; // = stackbase.space;
1443         char *sstrend; // = stackbase.space + MINSIZE;
1444         size_t g_stacknleft; // = MINSIZE;
1445         struct stack_block stackbase;
1446 };
1447 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1448 #define G_memstack (*ash_ptr_to_globals_memstack)
1449 #define g_stackp     (G_memstack.g_stackp    )
1450 #define g_stacknxt   (G_memstack.g_stacknxt  )
1451 #define sstrend      (G_memstack.sstrend     )
1452 #define g_stacknleft (G_memstack.g_stacknleft)
1453 #define stackbase    (G_memstack.stackbase   )
1454 #define INIT_G_memstack() do { \
1455         (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1456         barrier(); \
1457         g_stackp = &stackbase; \
1458         g_stacknxt = stackbase.space; \
1459         g_stacknleft = MINSIZE; \
1460         sstrend = stackbase.space + MINSIZE; \
1461 } while (0)
1462
1463
1464 #define stackblock()     ((void *)g_stacknxt)
1465 #define stackblocksize() g_stacknleft
1466
1467 /*
1468  * Parse trees for commands are allocated in lifo order, so we use a stack
1469  * to make this more efficient, and also to avoid all sorts of exception
1470  * handling code to handle interrupts in the middle of a parse.
1471  *
1472  * The size 504 was chosen because the Ultrix malloc handles that size
1473  * well.
1474  */
1475 static void *
1476 stalloc(size_t nbytes)
1477 {
1478         char *p;
1479         size_t aligned;
1480
1481         aligned = SHELL_ALIGN(nbytes);
1482         if (aligned > g_stacknleft) {
1483                 size_t len;
1484                 size_t blocksize;
1485                 struct stack_block *sp;
1486
1487                 blocksize = aligned;
1488                 if (blocksize < MINSIZE)
1489                         blocksize = MINSIZE;
1490                 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1491                 if (len < blocksize)
1492                         ash_msg_and_raise_error(bb_msg_memory_exhausted);
1493                 INT_OFF;
1494                 sp = ckmalloc(len);
1495                 sp->prev = g_stackp;
1496                 g_stacknxt = sp->space;
1497                 g_stacknleft = blocksize;
1498                 sstrend = g_stacknxt + blocksize;
1499                 g_stackp = sp;
1500                 INT_ON;
1501         }
1502         p = g_stacknxt;
1503         g_stacknxt += aligned;
1504         g_stacknleft -= aligned;
1505         return p;
1506 }
1507
1508 static void *
1509 stzalloc(size_t nbytes)
1510 {
1511         return memset(stalloc(nbytes), 0, nbytes);
1512 }
1513
1514 static void
1515 stunalloc(void *p)
1516 {
1517 #if DEBUG
1518         if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1519                 write(STDERR_FILENO, "stunalloc\n", 10);
1520                 abort();
1521         }
1522 #endif
1523         g_stacknleft += g_stacknxt - (char *)p;
1524         g_stacknxt = p;
1525 }
1526
1527 /*
1528  * Like strdup but works with the ash stack.
1529  */
1530 static char *
1531 sstrdup(const char *p)
1532 {
1533         size_t len = strlen(p) + 1;
1534         return memcpy(stalloc(len), p, len);
1535 }
1536
1537 static inline void
1538 grabstackblock(size_t len)
1539 {
1540         stalloc(len);
1541 }
1542
1543 static void
1544 pushstackmark(struct stackmark *mark, size_t len)
1545 {
1546         mark->stackp = g_stackp;
1547         mark->stacknxt = g_stacknxt;
1548         mark->stacknleft = g_stacknleft;
1549         grabstackblock(len);
1550 }
1551
1552 static void
1553 setstackmark(struct stackmark *mark)
1554 {
1555         pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1556 }
1557
1558 static void
1559 popstackmark(struct stackmark *mark)
1560 {
1561         struct stack_block *sp;
1562
1563         if (!mark->stackp)
1564                 return;
1565
1566         INT_OFF;
1567         while (g_stackp != mark->stackp) {
1568                 sp = g_stackp;
1569                 g_stackp = sp->prev;
1570                 free(sp);
1571         }
1572         g_stacknxt = mark->stacknxt;
1573         g_stacknleft = mark->stacknleft;
1574         sstrend = mark->stacknxt + mark->stacknleft;
1575         INT_ON;
1576 }
1577
1578 /*
1579  * When the parser reads in a string, it wants to stick the string on the
1580  * stack and only adjust the stack pointer when it knows how big the
1581  * string is.  Stackblock (defined in stack.h) returns a pointer to a block
1582  * of space on top of the stack and stackblocklen returns the length of
1583  * this block.  Growstackblock will grow this space by at least one byte,
1584  * possibly moving it (like realloc).  Grabstackblock actually allocates the
1585  * part of the block that has been used.
1586  */
1587 static void
1588 growstackblock(void)
1589 {
1590         size_t newlen;
1591
1592         newlen = g_stacknleft * 2;
1593         if (newlen < g_stacknleft)
1594                 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1595         if (newlen < 128)
1596                 newlen += 128;
1597
1598         if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1599                 struct stack_block *sp;
1600                 struct stack_block *prevstackp;
1601                 size_t grosslen;
1602
1603                 INT_OFF;
1604                 sp = g_stackp;
1605                 prevstackp = sp->prev;
1606                 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1607                 sp = ckrealloc(sp, grosslen);
1608                 sp->prev = prevstackp;
1609                 g_stackp = sp;
1610                 g_stacknxt = sp->space;
1611                 g_stacknleft = newlen;
1612                 sstrend = sp->space + newlen;
1613                 INT_ON;
1614         } else {
1615                 char *oldspace = g_stacknxt;
1616                 size_t oldlen = g_stacknleft;
1617                 char *p = stalloc(newlen);
1618
1619                 /* free the space we just allocated */
1620                 g_stacknxt = memcpy(p, oldspace, oldlen);
1621                 g_stacknleft += newlen;
1622         }
1623 }
1624
1625 /*
1626  * The following routines are somewhat easier to use than the above.
1627  * The user declares a variable of type STACKSTR, which may be declared
1628  * to be a register.  The macro STARTSTACKSTR initializes things.  Then
1629  * the user uses the macro STPUTC to add characters to the string.  In
1630  * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1631  * grown as necessary.  When the user is done, she can just leave the
1632  * string there and refer to it using stackblock().  Or she can allocate
1633  * the space for it using grabstackstr().  If it is necessary to allow
1634  * someone else to use the stack temporarily and then continue to grow
1635  * the string, the user should use grabstack to allocate the space, and
1636  * then call ungrabstr(p) to return to the previous mode of operation.
1637  *
1638  * USTPUTC is like STPUTC except that it doesn't check for overflow.
1639  * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1640  * is space for at least one character.
1641  */
1642 static void *
1643 growstackstr(void)
1644 {
1645         size_t len = stackblocksize();
1646         growstackblock();
1647         return (char *)stackblock() + len;
1648 }
1649
1650 /*
1651  * Called from CHECKSTRSPACE.
1652  */
1653 static char *
1654 makestrspace(size_t newlen, char *p)
1655 {
1656         size_t len = p - g_stacknxt;
1657         size_t size;
1658
1659         for (;;) {
1660                 size_t nleft;
1661
1662                 size = stackblocksize();
1663                 nleft = size - len;
1664                 if (nleft >= newlen)
1665                         break;
1666                 growstackblock();
1667         }
1668         return (char *)stackblock() + len;
1669 }
1670
1671 static char *
1672 stack_nputstr(const char *s, size_t n, char *p)
1673 {
1674         p = makestrspace(n, p);
1675         p = (char *)mempcpy(p, s, n);
1676         return p;
1677 }
1678
1679 static char *
1680 stack_putstr(const char *s, char *p)
1681 {
1682         return stack_nputstr(s, strlen(s), p);
1683 }
1684
1685 static char *
1686 _STPUTC(int c, char *p)
1687 {
1688         if (p == sstrend)
1689                 p = growstackstr();
1690         *p++ = c;
1691         return p;
1692 }
1693
1694 #define STARTSTACKSTR(p)        ((p) = stackblock())
1695 #define STPUTC(c, p)            ((p) = _STPUTC((c), (p)))
1696 #define CHECKSTRSPACE(n, p) do { \
1697         char *q = (p); \
1698         size_t l = (n); \
1699         size_t m = sstrend - q; \
1700         if (l > m) \
1701                 (p) = makestrspace(l, q); \
1702 } while (0)
1703 #define USTPUTC(c, p)           (*(p)++ = (c))
1704 #define STACKSTRNUL(p) do { \
1705         if ((p) == sstrend) \
1706                 (p) = growstackstr(); \
1707         *(p) = '\0'; \
1708 } while (0)
1709 #define STUNPUTC(p)             (--(p))
1710 #define STTOPC(p)               ((p)[-1])
1711 #define STADJUST(amount, p)     ((p) += (amount))
1712
1713 #define grabstackstr(p)         stalloc((char *)(p) - (char *)stackblock())
1714 #define ungrabstackstr(s, p)    stunalloc(s)
1715 #define stackstrend()           ((void *)sstrend)
1716
1717
1718 /* ============ String helpers */
1719
1720 /*
1721  * prefix -- see if pfx is a prefix of string.
1722  */
1723 static char *
1724 prefix(const char *string, const char *pfx)
1725 {
1726         while (*pfx) {
1727                 if (*pfx++ != *string++)
1728                         return NULL;
1729         }
1730         return (char *) string;
1731 }
1732
1733 /*
1734  * Check for a valid number.  This should be elsewhere.
1735  */
1736 static int
1737 is_number(const char *p)
1738 {
1739         do {
1740                 if (!isdigit(*p))
1741                         return 0;
1742         } while (*++p != '\0');
1743         return 1;
1744 }
1745
1746 /*
1747  * Convert a string of digits to an integer, printing an error message on
1748  * failure.
1749  */
1750 static int
1751 number(const char *s)
1752 {
1753         if (!is_number(s))
1754                 ash_msg_and_raise_error(msg_illnum, s);
1755         return atoi(s);
1756 }
1757
1758 /*
1759  * Produce a single quoted string suitable as input to the shell.
1760  * The return string is allocated on the stack.
1761  */
1762 static char *
1763 single_quote(const char *s)
1764 {
1765         char *p;
1766
1767         STARTSTACKSTR(p);
1768
1769         do {
1770                 char *q;
1771                 size_t len;
1772
1773                 len = strchrnul(s, '\'') - s;
1774
1775                 q = p = makestrspace(len + 3, p);
1776
1777                 *q++ = '\'';
1778                 q = (char *)mempcpy(q, s, len);
1779                 *q++ = '\'';
1780                 s += len;
1781
1782                 STADJUST(q - p, p);
1783
1784                 if (*s != '\'')
1785                         break;
1786                 len = 0;
1787                 do len++; while (*++s == '\'');
1788
1789                 q = p = makestrspace(len + 3, p);
1790
1791                 *q++ = '"';
1792                 q = (char *)mempcpy(q, s - len, len);
1793                 *q++ = '"';
1794
1795                 STADJUST(q - p, p);
1796         } while (*s);
1797
1798         USTPUTC('\0', p);
1799
1800         return stackblock();
1801 }
1802
1803 /*
1804  * Produce a possibly single quoted string suitable as input to the shell.
1805  * If quoting was done, the return string is allocated on the stack,
1806  * otherwise a pointer to the original string is returned.
1807  */
1808 static const char *
1809 maybe_single_quote(const char *s)
1810 {
1811         const char *p = s;
1812
1813         while (*p) {
1814                 /* Assuming ACSII */
1815                 /* quote ctrl_chars space !"#$%&'()* */
1816                 if (*p < '+')
1817                         goto need_quoting;
1818                 /* quote ;<=>? */
1819                 if (*p >= ';' && *p <= '?')
1820                         goto need_quoting;
1821                 /* quote `[\ */
1822                 if (*p == '`')
1823                         goto need_quoting;
1824                 if (*p == '[')
1825                         goto need_quoting;
1826                 if (*p == '\\')
1827                         goto need_quoting;
1828                 /* quote {|}~ DEL and high bytes */
1829                 if (*p > 'z')
1830                         goto need_quoting;
1831                 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1832                 /* TODO: maybe avoid quoting % */
1833                 p++;
1834         }
1835         return s;
1836
1837  need_quoting:
1838         return single_quote(s);
1839 }
1840
1841
1842 /* ============ nextopt */
1843
1844 static char **argptr;                  /* argument list for builtin commands */
1845 static char *optionarg;                /* set by nextopt (like getopt) */
1846 static char *optptr;                   /* used by nextopt */
1847
1848 /*
1849  * XXX - should get rid of. Have all builtins use getopt(3).
1850  * The library getopt must have the BSD extension static variable
1851  * "optreset", otherwise it can't be used within the shell safely.
1852  *
1853  * Standard option processing (a la getopt) for builtin routines.
1854  * The only argument that is passed to nextopt is the option string;
1855  * the other arguments are unnecessary. It returns the character,
1856  * or '\0' on end of input.
1857  */
1858 static int
1859 nextopt(const char *optstring)
1860 {
1861         char *p;
1862         const char *q;
1863         char c;
1864
1865         p = optptr;
1866         if (p == NULL || *p == '\0') {
1867                 /* We ate entire "-param", take next one */
1868                 p = *argptr;
1869                 if (p == NULL)
1870                         return '\0';
1871                 if (*p != '-')
1872                         return '\0';
1873                 if (*++p == '\0') /* just "-" ? */
1874                         return '\0';
1875                 argptr++;
1876                 if (LONE_DASH(p)) /* "--" ? */
1877                         return '\0';
1878                 /* p => next "-param" */
1879         }
1880         /* p => some option char in the middle of a "-param" */
1881         c = *p++;
1882         for (q = optstring; *q != c;) {
1883                 if (*q == '\0')
1884                         ash_msg_and_raise_error("illegal option -%c", c);
1885                 if (*++q == ':')
1886                         q++;
1887         }
1888         if (*++q == ':') {
1889                 if (*p == '\0') {
1890                         p = *argptr++;
1891                         if (p == NULL)
1892                                 ash_msg_and_raise_error("no arg for -%c option", c);
1893                 }
1894                 optionarg = p;
1895                 p = NULL;
1896         }
1897         optptr = p;
1898         return c;
1899 }
1900
1901
1902 /* ============ Shell variables */
1903
1904 /*
1905  * The parsefile structure pointed to by the global variable parsefile
1906  * contains information about the current file being read.
1907  */
1908 struct shparam {
1909         int nparam;             /* # of positional parameters (without $0) */
1910 #if ENABLE_ASH_GETOPTS
1911         int optind;             /* next parameter to be processed by getopts */
1912         int optoff;             /* used by getopts */
1913 #endif
1914         unsigned char malloced; /* if parameter list dynamically allocated */
1915         char **p;               /* parameter list */
1916 };
1917
1918 /*
1919  * Free the list of positional parameters.
1920  */
1921 static void
1922 freeparam(volatile struct shparam *param)
1923 {
1924         if (param->malloced) {
1925                 char **ap, **ap1;
1926                 ap = ap1 = param->p;
1927                 while (*ap)
1928                         free(*ap++);
1929                 free(ap1);
1930         }
1931 }
1932
1933 #if ENABLE_ASH_GETOPTS
1934 static void FAST_FUNC getoptsreset(const char *value);
1935 #endif
1936
1937 struct var {
1938         struct var *next;               /* next entry in hash list */
1939         int flags;                      /* flags are defined above */
1940         const char *var_text;           /* name=value */
1941         void (*var_func)(const char *) FAST_FUNC; /* function to be called when  */
1942                                         /* the variable gets set/unset */
1943 };
1944
1945 struct localvar {
1946         struct localvar *next;          /* next local variable in list */
1947         struct var *vp;                 /* the variable that was made local */
1948         int flags;                      /* saved flags */
1949         const char *text;               /* saved text */
1950 };
1951
1952 /* flags */
1953 #define VEXPORT         0x01    /* variable is exported */
1954 #define VREADONLY       0x02    /* variable cannot be modified */
1955 #define VSTRFIXED       0x04    /* variable struct is statically allocated */
1956 #define VTEXTFIXED      0x08    /* text is statically allocated */
1957 #define VSTACK          0x10    /* text is allocated on the stack */
1958 #define VUNSET          0x20    /* the variable is not set */
1959 #define VNOFUNC         0x40    /* don't call the callback function */
1960 #define VNOSET          0x80    /* do not set variable - just readonly test */
1961 #define VNOSAVE         0x100   /* when text is on the heap before setvareq */
1962 #if ENABLE_ASH_RANDOM_SUPPORT
1963 # define VDYNAMIC       0x200   /* dynamic variable */
1964 #else
1965 # define VDYNAMIC       0
1966 #endif
1967
1968
1969 /* Need to be before varinit_data[] */
1970 #if ENABLE_LOCALE_SUPPORT
1971 static void FAST_FUNC
1972 change_lc_all(const char *value)
1973 {
1974         if (value && *value != '\0')
1975                 setlocale(LC_ALL, value);
1976 }
1977 static void FAST_FUNC
1978 change_lc_ctype(const char *value)
1979 {
1980         if (value && *value != '\0')
1981                 setlocale(LC_CTYPE, value);
1982 }
1983 #endif
1984 #if ENABLE_ASH_MAIL
1985 static void chkmail(void);
1986 static void changemail(const char *var_value) FAST_FUNC;
1987 #else
1988 # define chkmail()  ((void)0)
1989 #endif
1990 static void changepath(const char *) FAST_FUNC;
1991 #if ENABLE_ASH_RANDOM_SUPPORT
1992 static void change_random(const char *) FAST_FUNC;
1993 #endif
1994
1995 static const struct {
1996         int flags;
1997         const char *var_text;
1998         void (*var_func)(const char *) FAST_FUNC;
1999 } varinit_data[] = {
2000         /*
2001          * Note: VEXPORT would not work correctly here for NOFORK applets:
2002          * some environment strings may be constant.
2003          */
2004         { VSTRFIXED|VTEXTFIXED       , defifsvar   , NULL            },
2005 #if ENABLE_ASH_MAIL
2006         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL"      , changemail      },
2007         { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH"  , changemail      },
2008 #endif
2009         { VSTRFIXED|VTEXTFIXED       , bb_PATH_root_path, changepath },
2010         { VSTRFIXED|VTEXTFIXED       , "PS1=$ "    , NULL            },
2011         { VSTRFIXED|VTEXTFIXED       , "PS2=> "    , NULL            },
2012         { VSTRFIXED|VTEXTFIXED       , "PS4=+ "    , NULL            },
2013 #if ENABLE_ASH_GETOPTS
2014         { VSTRFIXED|VTEXTFIXED       , defoptindvar, getoptsreset    },
2015 #endif
2016 #if ENABLE_ASH_RANDOM_SUPPORT
2017         { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2018 #endif
2019 #if ENABLE_LOCALE_SUPPORT
2020         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL"    , change_lc_all   },
2021         { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE"  , change_lc_ctype },
2022 #endif
2023 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2024         { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE"  , NULL            },
2025 #endif
2026 };
2027
2028 struct redirtab;
2029
2030 struct globals_var {
2031         struct shparam shellparam;      /* $@ current positional parameters */
2032         struct redirtab *redirlist;
2033         int preverrout_fd;   /* stderr fd: usually 2, unless redirect moved it */
2034         struct var *vartab[VTABSIZE];
2035         struct var varinit[ARRAY_SIZE(varinit_data)];
2036 };
2037 extern struct globals_var *const ash_ptr_to_globals_var;
2038 #define G_var (*ash_ptr_to_globals_var)
2039 #define shellparam    (G_var.shellparam   )
2040 //#define redirlist     (G_var.redirlist    )
2041 #define preverrout_fd (G_var.preverrout_fd)
2042 #define vartab        (G_var.vartab       )
2043 #define varinit       (G_var.varinit      )
2044 #define INIT_G_var() do { \
2045         unsigned i; \
2046         (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2047         barrier(); \
2048         for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2049                 varinit[i].flags    = varinit_data[i].flags; \
2050                 varinit[i].var_text = varinit_data[i].var_text; \
2051                 varinit[i].var_func = varinit_data[i].var_func; \
2052         } \
2053 } while (0)
2054
2055 #define vifs      varinit[0]
2056 #if ENABLE_ASH_MAIL
2057 # define vmail    (&vifs)[1]
2058 # define vmpath   (&vmail)[1]
2059 # define vpath    (&vmpath)[1]
2060 #else
2061 # define vpath    (&vifs)[1]
2062 #endif
2063 #define vps1      (&vpath)[1]
2064 #define vps2      (&vps1)[1]
2065 #define vps4      (&vps2)[1]
2066 #if ENABLE_ASH_GETOPTS
2067 # define voptind  (&vps4)[1]
2068 # if ENABLE_ASH_RANDOM_SUPPORT
2069 #  define vrandom (&voptind)[1]
2070 # endif
2071 #else
2072 # if ENABLE_ASH_RANDOM_SUPPORT
2073 #  define vrandom (&vps4)[1]
2074 # endif
2075 #endif
2076
2077 /*
2078  * The following macros access the values of the above variables.
2079  * They have to skip over the name.  They return the null string
2080  * for unset variables.
2081  */
2082 #define ifsval()        (vifs.var_text + 4)
2083 #define ifsset()        ((vifs.flags & VUNSET) == 0)
2084 #if ENABLE_ASH_MAIL
2085 # define mailval()      (vmail.var_text + 5)
2086 # define mpathval()     (vmpath.var_text + 9)
2087 # define mpathset()     ((vmpath.flags & VUNSET) == 0)
2088 #endif
2089 #define pathval()       (vpath.var_text + 5)
2090 #define ps1val()        (vps1.var_text + 4)
2091 #define ps2val()        (vps2.var_text + 4)
2092 #define ps4val()        (vps4.var_text + 4)
2093 #if ENABLE_ASH_GETOPTS
2094 # define optindval()    (voptind.var_text + 7)
2095 #endif
2096
2097 #if ENABLE_ASH_GETOPTS
2098 static void FAST_FUNC
2099 getoptsreset(const char *value)
2100 {
2101         shellparam.optind = number(value) ?: 1;
2102         shellparam.optoff = -1;
2103 }
2104 #endif
2105
2106 /*
2107  * Compares two strings up to the first = or '\0'.  The first
2108  * string must be terminated by '='; the second may be terminated by
2109  * either '=' or '\0'.
2110  */
2111 static int
2112 varcmp(const char *p, const char *q)
2113 {
2114         int c, d;
2115
2116         while ((c = *p) == (d = *q)) {
2117                 if (c == '\0' || c == '=')
2118                         goto out;
2119                 p++;
2120                 q++;
2121         }
2122         if (c == '=')
2123                 c = '\0';
2124         if (d == '=')
2125                 d = '\0';
2126  out:
2127         return c - d;
2128 }
2129
2130 /*
2131  * Find the appropriate entry in the hash table from the name.
2132  */
2133 static struct var **
2134 hashvar(const char *p)
2135 {
2136         unsigned hashval;
2137
2138         hashval = ((unsigned char) *p) << 4;
2139         while (*p && *p != '=')
2140                 hashval += (unsigned char) *p++;
2141         return &vartab[hashval % VTABSIZE];
2142 }
2143
2144 static int
2145 vpcmp(const void *a, const void *b)
2146 {
2147         return varcmp(*(const char **)a, *(const char **)b);
2148 }
2149
2150 /*
2151  * This routine initializes the builtin variables.
2152  */
2153 static void
2154 initvar(void)
2155 {
2156         struct var *vp;
2157         struct var *end;
2158         struct var **vpp;
2159
2160         /*
2161          * PS1 depends on uid
2162          */
2163 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2164         vps1.var_text = "PS1=\\w \\$ ";
2165 #else
2166         if (!geteuid())
2167                 vps1.var_text = "PS1=# ";
2168 #endif
2169         vp = varinit;
2170         end = vp + ARRAY_SIZE(varinit);
2171         do {
2172                 vpp = hashvar(vp->var_text);
2173                 vp->next = *vpp;
2174                 *vpp = vp;
2175         } while (++vp < end);
2176 }
2177
2178 static struct var **
2179 findvar(struct var **vpp, const char *name)
2180 {
2181         for (; *vpp; vpp = &(*vpp)->next) {
2182                 if (varcmp((*vpp)->var_text, name) == 0) {
2183                         break;
2184                 }
2185         }
2186         return vpp;
2187 }
2188
2189 /*
2190  * Find the value of a variable.  Returns NULL if not set.
2191  */
2192 static const char* FAST_FUNC
2193 lookupvar(const char *name)
2194 {
2195         struct var *v;
2196
2197         v = *findvar(hashvar(name), name);
2198         if (v) {
2199 #if ENABLE_ASH_RANDOM_SUPPORT
2200         /*
2201          * Dynamic variables are implemented roughly the same way they are
2202          * in bash. Namely, they're "special" so long as they aren't unset.
2203          * As soon as they're unset, they're no longer dynamic, and dynamic
2204          * lookup will no longer happen at that point. -- PFM.
2205          */
2206                 if (v->flags & VDYNAMIC)
2207                         v->var_func(NULL);
2208 #endif
2209                 if (!(v->flags & VUNSET))
2210                         return var_end(v->var_text);
2211         }
2212         return NULL;
2213 }
2214
2215 #if ENABLE_UNICODE_SUPPORT
2216 static void
2217 reinit_unicode_for_ash(void)
2218 {
2219         /* Unicode support should be activated even if LANG is set
2220          * _during_ shell execution, not only if it was set when
2221          * shell was started. Therefore, re-check LANG every time:
2222          */
2223         if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2224          || ENABLE_UNICODE_USING_LOCALE
2225         ) {
2226                 const char *s = lookupvar("LC_ALL");
2227                 if (!s) s = lookupvar("LC_CTYPE");
2228                 if (!s) s = lookupvar("LANG");
2229                 reinit_unicode(s);
2230         }
2231 }
2232 #else
2233 # define reinit_unicode_for_ash() ((void)0)
2234 #endif
2235
2236 /*
2237  * Search the environment of a builtin command.
2238  */
2239 static ALWAYS_INLINE const char *
2240 bltinlookup(const char *name)
2241 {
2242         return lookupvar(name);
2243 }
2244
2245 /*
2246  * Same as setvar except that the variable and value are passed in
2247  * the first argument as name=value.  Since the first argument will
2248  * be actually stored in the table, it should not be a string that
2249  * will go away.
2250  * Called with interrupts off.
2251  */
2252 static struct var *
2253 setvareq(char *s, int flags)
2254 {
2255         struct var *vp, **vpp;
2256
2257         vpp = hashvar(s);
2258         flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2259         vpp = findvar(vpp, s);
2260         vp = *vpp;
2261         if (vp) {
2262                 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2263                         const char *n;
2264
2265                         if (flags & VNOSAVE)
2266                                 free(s);
2267                         n = vp->var_text;
2268                         exitstatus = 1;
2269                         ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2270                 }
2271
2272                 if (flags & VNOSET)
2273                         goto out;
2274
2275                 if (vp->var_func && !(flags & VNOFUNC))
2276                         vp->var_func(var_end(s));
2277
2278                 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2279                         free((char*)vp->var_text);
2280
2281                 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2282                         *vpp = vp->next;
2283                         free(vp);
2284  out_free:
2285                         if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2286                                 free(s);
2287                         goto out;
2288                 }
2289
2290                 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2291         } else {
2292                 /* variable s is not found */
2293                 if (flags & VNOSET)
2294                         goto out;
2295                 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2296                         goto out_free;
2297                 vp = ckzalloc(sizeof(*vp));
2298                 vp->next = *vpp;
2299                 /*vp->func = NULL; - ckzalloc did it */
2300                 *vpp = vp;
2301         }
2302         if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2303                 s = ckstrdup(s);
2304         vp->var_text = s;
2305         vp->flags = flags;
2306
2307  out:
2308         return vp;
2309 }
2310
2311 /*
2312  * Set the value of a variable.  The flags argument is ored with the
2313  * flags of the variable.  If val is NULL, the variable is unset.
2314  */
2315 static struct var *
2316 setvar(const char *name, const char *val, int flags)
2317 {
2318         const char *q;
2319         char *p;
2320         char *nameeq;
2321         size_t namelen;
2322         size_t vallen;
2323         struct var *vp;
2324
2325         q = endofname(name);
2326         p = strchrnul(q, '=');
2327         namelen = p - name;
2328         if (!namelen || p != q)
2329                 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2330         vallen = 0;
2331         if (val == NULL) {
2332                 flags |= VUNSET;
2333         } else {
2334                 vallen = strlen(val);
2335         }
2336
2337         INT_OFF;
2338         nameeq = ckmalloc(namelen + vallen + 2);
2339         p = mempcpy(nameeq, name, namelen);
2340         if (val) {
2341                 *p++ = '=';
2342                 p = mempcpy(p, val, vallen);
2343         }
2344         *p = '\0';
2345         vp = setvareq(nameeq, flags | VNOSAVE);
2346         INT_ON;
2347
2348         return vp;
2349 }
2350
2351 static void FAST_FUNC
2352 setvar0(const char *name, const char *val)
2353 {
2354         setvar(name, val, 0);
2355 }
2356
2357 /*
2358  * Unset the specified variable.
2359  */
2360 static void
2361 unsetvar(const char *s)
2362 {
2363         setvar(s, NULL, 0);
2364 }
2365
2366 /*
2367  * Process a linked list of variable assignments.
2368  */
2369 static void
2370 listsetvar(struct strlist *list_set_var, int flags)
2371 {
2372         struct strlist *lp = list_set_var;
2373
2374         if (!lp)
2375                 return;
2376         INT_OFF;
2377         do {
2378                 setvareq(lp->text, flags);
2379                 lp = lp->next;
2380         } while (lp);
2381         INT_ON;
2382 }
2383
2384 /*
2385  * Generate a list of variables satisfying the given conditions.
2386  */
2387 static char **
2388 listvars(int on, int off, char ***end)
2389 {
2390         struct var **vpp;
2391         struct var *vp;
2392         char **ep;
2393         int mask;
2394
2395         STARTSTACKSTR(ep);
2396         vpp = vartab;
2397         mask = on | off;
2398         do {
2399                 for (vp = *vpp; vp; vp = vp->next) {
2400                         if ((vp->flags & mask) == on) {
2401                                 if (ep == stackstrend())
2402                                         ep = growstackstr();
2403                                 *ep++ = (char*)vp->var_text;
2404                         }
2405                 }
2406         } while (++vpp < vartab + VTABSIZE);
2407         if (ep == stackstrend())
2408                 ep = growstackstr();
2409         if (end)
2410                 *end = ep;
2411         *ep++ = NULL;
2412         return grabstackstr(ep);
2413 }
2414
2415
2416 /* ============ Path search helper
2417  *
2418  * The variable path (passed by reference) should be set to the start
2419  * of the path before the first call; path_advance will update
2420  * this value as it proceeds.  Successive calls to path_advance will return
2421  * the possible path expansions in sequence.  If an option (indicated by
2422  * a percent sign) appears in the path entry then the global variable
2423  * pathopt will be set to point to it; otherwise pathopt will be set to
2424  * NULL.
2425  */
2426 static const char *pathopt;     /* set by path_advance */
2427
2428 static char *
2429 path_advance(const char **path, const char *name)
2430 {
2431         const char *p;
2432         char *q;
2433         const char *start;
2434         size_t len;
2435
2436         if (*path == NULL)
2437                 return NULL;
2438         start = *path;
2439         for (p = start; *p && *p != ':' && *p != '%'; p++)
2440                 continue;
2441         len = p - start + strlen(name) + 2;     /* "2" is for '/' and '\0' */
2442         while (stackblocksize() < len)
2443                 growstackblock();
2444         q = stackblock();
2445         if (p != start) {
2446                 q = mempcpy(q, start, p - start);
2447                 *q++ = '/';
2448         }
2449         strcpy(q, name);
2450         pathopt = NULL;
2451         if (*p == '%') {
2452                 pathopt = ++p;
2453                 while (*p && *p != ':')
2454                         p++;
2455         }
2456         if (*p == ':')
2457                 *path = p + 1;
2458         else
2459                 *path = NULL;
2460         return stalloc(len);
2461 }
2462
2463
2464 /* ============ Prompt */
2465
2466 static smallint doprompt;                   /* if set, prompt the user */
2467 static smallint needprompt;                 /* true if interactive and at start of line */
2468
2469 #if ENABLE_FEATURE_EDITING
2470 static line_input_t *line_input_state;
2471 static const char *cmdedit_prompt;
2472 static void
2473 putprompt(const char *s)
2474 {
2475         if (ENABLE_ASH_EXPAND_PRMT) {
2476                 free((char*)cmdedit_prompt);
2477                 cmdedit_prompt = ckstrdup(s);
2478                 return;
2479         }
2480         cmdedit_prompt = s;
2481 }
2482 #else
2483 static void
2484 putprompt(const char *s)
2485 {
2486         out2str(s);
2487 }
2488 #endif
2489
2490 /* expandstr() needs parsing machinery, so it is far away ahead... */
2491 static const char *expandstr(const char *ps, int syntax_type);
2492 /* Values for syntax param */
2493 #define BASESYNTAX 0    /* not in quotes */
2494 #define DQSYNTAX   1    /* in double quotes */
2495 #define SQSYNTAX   2    /* in single quotes */
2496 #define ARISYNTAX  3    /* in arithmetic */
2497 #if ENABLE_ASH_EXPAND_PRMT
2498 # define PSSYNTAX  4    /* prompt. never passed to SIT() */
2499 #endif
2500 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2501
2502 /*
2503  * called by editline -- any expansions to the prompt should be added here.
2504  */
2505 static void
2506 setprompt_if(smallint do_set, int whichprompt)
2507 {
2508         const char *prompt;
2509         IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2510
2511         if (!do_set)
2512                 return;
2513
2514         needprompt = 0;
2515
2516         switch (whichprompt) {
2517         case 1:
2518                 prompt = ps1val();
2519                 break;
2520         case 2:
2521                 prompt = ps2val();
2522                 break;
2523         default:                        /* 0 */
2524                 prompt = nullstr;
2525         }
2526 #if ENABLE_ASH_EXPAND_PRMT
2527         pushstackmark(&smark, stackblocksize());
2528         putprompt(expandstr(prompt, PSSYNTAX));
2529         popstackmark(&smark);
2530 #else
2531         putprompt(prompt);
2532 #endif
2533 }
2534
2535
2536 /* ============ The cd and pwd commands */
2537
2538 #define CD_PHYSICAL 1
2539 #define CD_PRINT 2
2540
2541 static int
2542 cdopt(void)
2543 {
2544         int flags = 0;
2545         int i, j;
2546
2547         j = 'L';
2548         while ((i = nextopt("LP")) != '\0') {
2549                 if (i != j) {
2550                         flags ^= CD_PHYSICAL;
2551                         j = i;
2552                 }
2553         }
2554
2555         return flags;
2556 }
2557
2558 /*
2559  * Update curdir (the name of the current directory) in response to a
2560  * cd command.
2561  */
2562 static const char *
2563 updatepwd(const char *dir)
2564 {
2565         char *new;
2566         char *p;
2567         char *cdcomppath;
2568         const char *lim;
2569
2570         cdcomppath = sstrdup(dir);
2571         STARTSTACKSTR(new);
2572         if (*dir != '/') {
2573                 if (curdir == nullstr)
2574                         return 0;
2575                 new = stack_putstr(curdir, new);
2576         }
2577         new = makestrspace(strlen(dir) + 2, new);
2578         lim = (char *)stackblock() + 1;
2579         if (*dir != '/') {
2580                 if (new[-1] != '/')
2581                         USTPUTC('/', new);
2582                 if (new > lim && *lim == '/')
2583                         lim++;
2584         } else {
2585                 USTPUTC('/', new);
2586                 cdcomppath++;
2587                 if (dir[1] == '/' && dir[2] != '/') {
2588                         USTPUTC('/', new);
2589                         cdcomppath++;
2590                         lim++;
2591                 }
2592         }
2593         p = strtok(cdcomppath, "/");
2594         while (p) {
2595                 switch (*p) {
2596                 case '.':
2597                         if (p[1] == '.' && p[2] == '\0') {
2598                                 while (new > lim) {
2599                                         STUNPUTC(new);
2600                                         if (new[-1] == '/')
2601                                                 break;
2602                                 }
2603                                 break;
2604                         }
2605                         if (p[1] == '\0')
2606                                 break;
2607                         /* fall through */
2608                 default:
2609                         new = stack_putstr(p, new);
2610                         USTPUTC('/', new);
2611                 }
2612                 p = strtok(NULL, "/");
2613         }
2614         if (new > lim)
2615                 STUNPUTC(new);
2616         *new = 0;
2617         return stackblock();
2618 }
2619
2620 /*
2621  * Find out what the current directory is. If we already know the current
2622  * directory, this routine returns immediately.
2623  */
2624 static char *
2625 getpwd(void)
2626 {
2627         char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2628         return dir ? dir : nullstr;
2629 }
2630
2631 static void
2632 setpwd(const char *val, int setold)
2633 {
2634         char *oldcur, *dir;
2635
2636         oldcur = dir = curdir;
2637
2638         if (setold) {
2639                 setvar("OLDPWD", oldcur, VEXPORT);
2640         }
2641         INT_OFF;
2642         if (physdir != nullstr) {
2643                 if (physdir != oldcur)
2644                         free(physdir);
2645                 physdir = nullstr;
2646         }
2647         if (oldcur == val || !val) {
2648                 char *s = getpwd();
2649                 physdir = s;
2650                 if (!val)
2651                         dir = s;
2652         } else
2653                 dir = ckstrdup(val);
2654         if (oldcur != dir && oldcur != nullstr) {
2655                 free(oldcur);
2656         }
2657         curdir = dir;
2658         INT_ON;
2659         setvar("PWD", dir, VEXPORT);
2660 }
2661
2662 static void hashcd(void);
2663
2664 /*
2665  * Actually do the chdir.  We also call hashcd to let other routines
2666  * know that the current directory has changed.
2667  */
2668 static int
2669 docd(const char *dest, int flags)
2670 {
2671         const char *dir = NULL;
2672         int err;
2673
2674         TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2675
2676         INT_OFF;
2677         if (!(flags & CD_PHYSICAL)) {
2678                 dir = updatepwd(dest);
2679                 if (dir)
2680                         dest = dir;
2681         }
2682         err = chdir(dest);
2683         if (err)
2684                 goto out;
2685         setpwd(dir, 1);
2686         hashcd();
2687  out:
2688         INT_ON;
2689         return err;
2690 }
2691
2692 static int FAST_FUNC
2693 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2694 {
2695         const char *dest;
2696         const char *path;
2697         const char *p;
2698         char c;
2699         struct stat statb;
2700         int flags;
2701
2702         flags = cdopt();
2703         dest = *argptr;
2704         if (!dest)
2705                 dest = bltinlookup("HOME");
2706         else if (LONE_DASH(dest)) {
2707                 dest = bltinlookup("OLDPWD");
2708                 flags |= CD_PRINT;
2709         }
2710         if (!dest)
2711                 dest = nullstr;
2712         if (*dest == '/')
2713                 goto step6;
2714         if (*dest == '.') {
2715                 c = dest[1];
2716  dotdot:
2717                 switch (c) {
2718                 case '\0':
2719                 case '/':
2720                         goto step6;
2721                 case '.':
2722                         c = dest[2];
2723                         if (c != '.')
2724                                 goto dotdot;
2725                 }
2726         }
2727         if (!*dest)
2728                 dest = ".";
2729         path = bltinlookup("CDPATH");
2730         while (path) {
2731                 c = *path;
2732                 p = path_advance(&path, dest);
2733                 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2734                         if (c && c != ':')
2735                                 flags |= CD_PRINT;
2736  docd:
2737                         if (!docd(p, flags))
2738                                 goto out;
2739                         goto err;
2740                 }
2741         }
2742
2743  step6:
2744         p = dest;
2745         goto docd;
2746
2747  err:
2748         ash_msg_and_raise_error("can't cd to %s", dest);
2749         /* NOTREACHED */
2750  out:
2751         if (flags & CD_PRINT)
2752                 out1fmt("%s\n", curdir);
2753         return 0;
2754 }
2755
2756 static int FAST_FUNC
2757 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2758 {
2759         int flags;
2760         const char *dir = curdir;
2761
2762         flags = cdopt();
2763         if (flags) {
2764                 if (physdir == nullstr)
2765                         setpwd(dir, 0);
2766                 dir = physdir;
2767         }
2768         out1fmt("%s\n", dir);
2769         return 0;
2770 }
2771
2772
2773 /* ============ ... */
2774
2775
2776 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2777
2778 /* Syntax classes */
2779 #define CWORD     0             /* character is nothing special */
2780 #define CNL       1             /* newline character */
2781 #define CBACK     2             /* a backslash character */
2782 #define CSQUOTE   3             /* single quote */
2783 #define CDQUOTE   4             /* double quote */
2784 #define CENDQUOTE 5             /* a terminating quote */
2785 #define CBQUOTE   6             /* backwards single quote */
2786 #define CVAR      7             /* a dollar sign */
2787 #define CENDVAR   8             /* a '}' character */
2788 #define CLP       9             /* a left paren in arithmetic */
2789 #define CRP      10             /* a right paren in arithmetic */
2790 #define CENDFILE 11             /* end of file */
2791 #define CCTL     12             /* like CWORD, except it must be escaped */
2792 #define CSPCL    13             /* these terminate a word */
2793 #define CIGN     14             /* character should be ignored */
2794
2795 #define PEOF     256
2796 #if ENABLE_ASH_ALIAS
2797 # define PEOA    257
2798 #endif
2799
2800 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2801
2802 #if ENABLE_FEATURE_SH_MATH
2803 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2804 #else
2805 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2806 #endif
2807 static const uint16_t S_I_T[] ALIGN2 = {
2808 #if ENABLE_ASH_ALIAS
2809         SIT_ITEM(CSPCL   , CIGN     , CIGN , CIGN   ),    /* 0, PEOA */
2810 #endif
2811         SIT_ITEM(CSPCL   , CWORD    , CWORD, CWORD  ),    /* 1, ' ' */
2812         SIT_ITEM(CNL     , CNL      , CNL  , CNL    ),    /* 2, \n */
2813         SIT_ITEM(CWORD   , CCTL     , CCTL , CWORD  ),    /* 3, !*-/:=?[]~ */
2814         SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD  ),    /* 4, '"' */
2815         SIT_ITEM(CVAR    , CVAR     , CWORD, CVAR   ),    /* 5, $ */
2816         SIT_ITEM(CSQUOTE , CWORD    , CENDQUOTE, CWORD),  /* 6, "'" */
2817         SIT_ITEM(CSPCL   , CWORD    , CWORD, CLP    ),    /* 7, ( */
2818         SIT_ITEM(CSPCL   , CWORD    , CWORD, CRP    ),    /* 8, ) */
2819         SIT_ITEM(CBACK   , CBACK    , CCTL , CBACK  ),    /* 9, \ */
2820         SIT_ITEM(CBQUOTE , CBQUOTE  , CWORD, CBQUOTE),    /* 10, ` */
2821         SIT_ITEM(CENDVAR , CENDVAR  , CWORD, CENDVAR),    /* 11, } */
2822 #if !USE_SIT_FUNCTION
2823         SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2824         SIT_ITEM(CWORD   , CWORD    , CWORD, CWORD  ),    /* 13, 0-9A-Za-z */
2825         SIT_ITEM(CCTL    , CCTL     , CCTL , CCTL   )     /* 14, CTLESC ... */
2826 #endif
2827 #undef SIT_ITEM
2828 };
2829 /* Constants below must match table above */
2830 enum {
2831 #if ENABLE_ASH_ALIAS
2832         CSPCL_CIGN_CIGN_CIGN               , /*  0 */
2833 #endif
2834         CSPCL_CWORD_CWORD_CWORD            , /*  1 */
2835         CNL_CNL_CNL_CNL                    , /*  2 */
2836         CWORD_CCTL_CCTL_CWORD              , /*  3 */
2837         CDQUOTE_CENDQUOTE_CWORD_CWORD      , /*  4 */
2838         CVAR_CVAR_CWORD_CVAR               , /*  5 */
2839         CSQUOTE_CWORD_CENDQUOTE_CWORD      , /*  6 */
2840         CSPCL_CWORD_CWORD_CLP              , /*  7 */
2841         CSPCL_CWORD_CWORD_CRP              , /*  8 */
2842         CBACK_CBACK_CCTL_CBACK             , /*  9 */
2843         CBQUOTE_CBQUOTE_CWORD_CBQUOTE      , /* 10 */
2844         CENDVAR_CENDVAR_CWORD_CENDVAR      , /* 11 */
2845         CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2846         CWORD_CWORD_CWORD_CWORD            , /* 13 */
2847         CCTL_CCTL_CCTL_CCTL                , /* 14 */
2848 };
2849
2850 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2851  * caller must ensure proper cast on it if c is *char_ptr!
2852  */
2853 #if USE_SIT_FUNCTION
2854
2855 static int
2856 SIT(int c, int syntax)
2857 {
2858         /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2859         static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2860         /*
2861          * This causes '/' to be prepended with CTLESC in dquoted string,
2862          * making "./file"* treated incorrectly because we feed
2863          * ".\/file*" string to glob(), confusing it (see expandmeta func).
2864          * The "homegrown" glob implementation is okay with that,
2865          * but glibc one isn't. With '/' always treated as CWORD,
2866          * both work fine.
2867          */
2868 # if ENABLE_ASH_ALIAS
2869         static const uint8_t syntax_index_table[] ALIGN1 = {
2870                 1, 2, 1, 3, 4, 5, 1, 6,         /* "\t\n !\"$&'" */
2871                 7, 8, 3, 3,/*3,*/3, 1, 1,       /* "()*-/:;<" */
2872                 3, 1, 3, 3, 9, 3, 10, 1,        /* "=>?[\\]`|" */
2873                 11, 3                           /* "}~" */
2874         };
2875 # else
2876         static const uint8_t syntax_index_table[] ALIGN1 = {
2877                 0, 1, 0, 2, 3, 4, 0, 5,         /* "\t\n !\"$&'" */
2878                 6, 7, 2, 2,/*2,*/2, 0, 0,       /* "()*-/:;<" */
2879                 2, 0, 2, 2, 8, 2, 9, 0,         /* "=>?[\\]`|" */
2880                 10, 2                           /* "}~" */
2881         };
2882 # endif
2883         const char *s;
2884         int indx;
2885
2886         if (c == PEOF)
2887                 return CENDFILE;
2888 # if ENABLE_ASH_ALIAS
2889         if (c == PEOA)
2890                 indx = 0;
2891         else
2892 # endif
2893         {
2894                 /* Cast is purely for paranoia here,
2895                  * just in case someone passed signed char to us */
2896                 if ((unsigned char)c >= CTL_FIRST
2897                  && (unsigned char)c <= CTL_LAST
2898                 ) {
2899                         return CCTL;
2900                 }
2901                 s = strchrnul(spec_symbls, c);
2902                 if (*s == '\0')
2903                         return CWORD;
2904                 indx = syntax_index_table[s - spec_symbls];
2905         }
2906         return (S_I_T[indx] >> (syntax*4)) & 0xf;
2907 }
2908
2909 #else   /* !USE_SIT_FUNCTION */
2910
2911 static const uint8_t syntax_index_table[] ALIGN1 = {
2912         /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2913         /*   0      */ CWORD_CWORD_CWORD_CWORD,
2914         /*   1      */ CWORD_CWORD_CWORD_CWORD,
2915         /*   2      */ CWORD_CWORD_CWORD_CWORD,
2916         /*   3      */ CWORD_CWORD_CWORD_CWORD,
2917         /*   4      */ CWORD_CWORD_CWORD_CWORD,
2918         /*   5      */ CWORD_CWORD_CWORD_CWORD,
2919         /*   6      */ CWORD_CWORD_CWORD_CWORD,
2920         /*   7      */ CWORD_CWORD_CWORD_CWORD,
2921         /*   8      */ CWORD_CWORD_CWORD_CWORD,
2922         /*   9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2923         /*  10 "\n" */ CNL_CNL_CNL_CNL,
2924         /*  11      */ CWORD_CWORD_CWORD_CWORD,
2925         /*  12      */ CWORD_CWORD_CWORD_CWORD,
2926         /*  13      */ CWORD_CWORD_CWORD_CWORD,
2927         /*  14      */ CWORD_CWORD_CWORD_CWORD,
2928         /*  15      */ CWORD_CWORD_CWORD_CWORD,
2929         /*  16      */ CWORD_CWORD_CWORD_CWORD,
2930         /*  17      */ CWORD_CWORD_CWORD_CWORD,
2931         /*  18      */ CWORD_CWORD_CWORD_CWORD,
2932         /*  19      */ CWORD_CWORD_CWORD_CWORD,
2933         /*  20      */ CWORD_CWORD_CWORD_CWORD,
2934         /*  21      */ CWORD_CWORD_CWORD_CWORD,
2935         /*  22      */ CWORD_CWORD_CWORD_CWORD,
2936         /*  23      */ CWORD_CWORD_CWORD_CWORD,
2937         /*  24      */ CWORD_CWORD_CWORD_CWORD,
2938         /*  25      */ CWORD_CWORD_CWORD_CWORD,
2939         /*  26      */ CWORD_CWORD_CWORD_CWORD,
2940         /*  27      */ CWORD_CWORD_CWORD_CWORD,
2941         /*  28      */ CWORD_CWORD_CWORD_CWORD,
2942         /*  29      */ CWORD_CWORD_CWORD_CWORD,
2943         /*  30      */ CWORD_CWORD_CWORD_CWORD,
2944         /*  31      */ CWORD_CWORD_CWORD_CWORD,
2945         /*  32  " " */ CSPCL_CWORD_CWORD_CWORD,
2946         /*  33  "!" */ CWORD_CCTL_CCTL_CWORD,
2947         /*  34  """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2948         /*  35  "#" */ CWORD_CWORD_CWORD_CWORD,
2949         /*  36  "$" */ CVAR_CVAR_CWORD_CVAR,
2950         /*  37  "%" */ CWORD_CWORD_CWORD_CWORD,
2951         /*  38  "&" */ CSPCL_CWORD_CWORD_CWORD,
2952         /*  39  "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2953         /*  40  "(" */ CSPCL_CWORD_CWORD_CLP,
2954         /*  41  ")" */ CSPCL_CWORD_CWORD_CRP,
2955         /*  42  "*" */ CWORD_CCTL_CCTL_CWORD,
2956         /*  43  "+" */ CWORD_CWORD_CWORD_CWORD,
2957         /*  44  "," */ CWORD_CWORD_CWORD_CWORD,
2958         /*  45  "-" */ CWORD_CCTL_CCTL_CWORD,
2959         /*  46  "." */ CWORD_CWORD_CWORD_CWORD,
2960 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2961         /*  47  "/" */ CWORD_CWORD_CWORD_CWORD,
2962         /*  48  "0" */ CWORD_CWORD_CWORD_CWORD,
2963         /*  49  "1" */ CWORD_CWORD_CWORD_CWORD,
2964         /*  50  "2" */ CWORD_CWORD_CWORD_CWORD,
2965         /*  51  "3" */ CWORD_CWORD_CWORD_CWORD,
2966         /*  52  "4" */ CWORD_CWORD_CWORD_CWORD,
2967         /*  53  "5" */ CWORD_CWORD_CWORD_CWORD,
2968         /*  54  "6" */ CWORD_CWORD_CWORD_CWORD,
2969         /*  55  "7" */ CWORD_CWORD_CWORD_CWORD,
2970         /*  56  "8" */ CWORD_CWORD_CWORD_CWORD,
2971         /*  57  "9" */ CWORD_CWORD_CWORD_CWORD,
2972         /*  58  ":" */ CWORD_CCTL_CCTL_CWORD,
2973         /*  59  ";" */ CSPCL_CWORD_CWORD_CWORD,
2974         /*  60  "<" */ CSPCL_CWORD_CWORD_CWORD,
2975         /*  61  "=" */ CWORD_CCTL_CCTL_CWORD,
2976         /*  62  ">" */ CSPCL_CWORD_CWORD_CWORD,
2977         /*  63  "?" */ CWORD_CCTL_CCTL_CWORD,
2978         /*  64  "@" */ CWORD_CWORD_CWORD_CWORD,
2979         /*  65  "A" */ CWORD_CWORD_CWORD_CWORD,
2980         /*  66  "B" */ CWORD_CWORD_CWORD_CWORD,
2981         /*  67  "C" */ CWORD_CWORD_CWORD_CWORD,
2982         /*  68  "D" */ CWORD_CWORD_CWORD_CWORD,
2983         /*  69  "E" */ CWORD_CWORD_CWORD_CWORD,
2984         /*  70  "F" */ CWORD_CWORD_CWORD_CWORD,
2985         /*  71  "G" */ CWORD_CWORD_CWORD_CWORD,
2986         /*  72  "H" */ CWORD_CWORD_CWORD_CWORD,
2987         /*  73  "I" */ CWORD_CWORD_CWORD_CWORD,
2988         /*  74  "J" */ CWORD_CWORD_CWORD_CWORD,
2989         /*  75  "K" */ CWORD_CWORD_CWORD_CWORD,
2990         /*  76  "L" */ CWORD_CWORD_CWORD_CWORD,
2991         /*  77  "M" */ CWORD_CWORD_CWORD_CWORD,
2992         /*  78  "N" */ CWORD_CWORD_CWORD_CWORD,
2993         /*  79  "O" */ CWORD_CWORD_CWORD_CWORD,
2994         /*  80  "P" */ CWORD_CWORD_CWORD_CWORD,
2995         /*  81  "Q" */ CWORD_CWORD_CWORD_CWORD,
2996         /*  82  "R" */ CWORD_CWORD_CWORD_CWORD,
2997         /*  83  "S" */ CWORD_CWORD_CWORD_CWORD,
2998         /*  84  "T" */ CWORD_CWORD_CWORD_CWORD,
2999         /*  85  "U" */ CWORD_CWORD_CWORD_CWORD,
3000         /*  86  "V" */ CWORD_CWORD_CWORD_CWORD,
3001         /*  87  "W" */ CWORD_CWORD_CWORD_CWORD,
3002         /*  88  "X" */ CWORD_CWORD_CWORD_CWORD,
3003         /*  89  "Y" */ CWORD_CWORD_CWORD_CWORD,
3004         /*  90  "Z" */ CWORD_CWORD_CWORD_CWORD,
3005         /*  91  "[" */ CWORD_CCTL_CCTL_CWORD,
3006         /*  92  "\" */ CBACK_CBACK_CCTL_CBACK,
3007         /*  93  "]" */ CWORD_CCTL_CCTL_CWORD,
3008         /*  94  "^" */ CWORD_CWORD_CWORD_CWORD,
3009         /*  95  "_" */ CWORD_CWORD_CWORD_CWORD,
3010         /*  96  "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3011         /*  97  "a" */ CWORD_CWORD_CWORD_CWORD,
3012         /*  98  "b" */ CWORD_CWORD_CWORD_CWORD,
3013         /*  99  "c" */ CWORD_CWORD_CWORD_CWORD,
3014         /* 100  "d" */ CWORD_CWORD_CWORD_CWORD,
3015         /* 101  "e" */ CWORD_CWORD_CWORD_CWORD,
3016         /* 102  "f" */ CWORD_CWORD_CWORD_CWORD,
3017         /* 103  "g" */ CWORD_CWORD_CWORD_CWORD,
3018         /* 104  "h" */ CWORD_CWORD_CWORD_CWORD,
3019         /* 105  "i" */ CWORD_CWORD_CWORD_CWORD,
3020         /* 106  "j" */ CWORD_CWORD_CWORD_CWORD,
3021         /* 107  "k" */ CWORD_CWORD_CWORD_CWORD,
3022         /* 108  "l" */ CWORD_CWORD_CWORD_CWORD,
3023         /* 109  "m" */ CWORD_CWORD_CWORD_CWORD,
3024         /* 110  "n" */ CWORD_CWORD_CWORD_CWORD,
3025         /* 111  "o" */ CWORD_CWORD_CWORD_CWORD,
3026         /* 112  "p" */ CWORD_CWORD_CWORD_CWORD,
3027         /* 113  "q" */ CWORD_CWORD_CWORD_CWORD,
3028         /* 114  "r" */ CWORD_CWORD_CWORD_CWORD,
3029         /* 115  "s" */ CWORD_CWORD_CWORD_CWORD,
3030         /* 116  "t" */ CWORD_CWORD_CWORD_CWORD,
3031         /* 117  "u" */ CWORD_CWORD_CWORD_CWORD,
3032         /* 118  "v" */ CWORD_CWORD_CWORD_CWORD,
3033         /* 119  "w" */ CWORD_CWORD_CWORD_CWORD,
3034         /* 120  "x" */ CWORD_CWORD_CWORD_CWORD,
3035         /* 121  "y" */ CWORD_CWORD_CWORD_CWORD,
3036         /* 122  "z" */ CWORD_CWORD_CWORD_CWORD,
3037         /* 123  "{" */ CWORD_CWORD_CWORD_CWORD,
3038         /* 124  "|" */ CSPCL_CWORD_CWORD_CWORD,
3039         /* 125  "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3040         /* 126  "~" */ CWORD_CCTL_CCTL_CWORD,
3041         /* 127  del */ CWORD_CWORD_CWORD_CWORD,
3042         /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3043         /* 129 CTLESC       */ CCTL_CCTL_CCTL_CCTL,
3044         /* 130 CTLVAR       */ CCTL_CCTL_CCTL_CCTL,
3045         /* 131 CTLENDVAR    */ CCTL_CCTL_CCTL_CCTL,
3046         /* 132 CTLBACKQ     */ CCTL_CCTL_CCTL_CCTL,
3047         /* 133 CTLQUOTE     */ CCTL_CCTL_CCTL_CCTL,
3048         /* 134 CTLARI       */ CCTL_CCTL_CCTL_CCTL,
3049         /* 135 CTLENDARI    */ CCTL_CCTL_CCTL_CCTL,
3050         /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3051         /* 137      */ CWORD_CWORD_CWORD_CWORD,
3052         /* 138      */ CWORD_CWORD_CWORD_CWORD,
3053         /* 139      */ CWORD_CWORD_CWORD_CWORD,
3054         /* 140      */ CWORD_CWORD_CWORD_CWORD,
3055         /* 141      */ CWORD_CWORD_CWORD_CWORD,
3056         /* 142      */ CWORD_CWORD_CWORD_CWORD,
3057         /* 143      */ CWORD_CWORD_CWORD_CWORD,
3058         /* 144      */ CWORD_CWORD_CWORD_CWORD,
3059         /* 145      */ CWORD_CWORD_CWORD_CWORD,
3060         /* 146      */ CWORD_CWORD_CWORD_CWORD,
3061         /* 147      */ CWORD_CWORD_CWORD_CWORD,
3062         /* 148      */ CWORD_CWORD_CWORD_CWORD,
3063         /* 149      */ CWORD_CWORD_CWORD_CWORD,
3064         /* 150      */ CWORD_CWORD_CWORD_CWORD,
3065         /* 151      */ CWORD_CWORD_CWORD_CWORD,
3066         /* 152      */ CWORD_CWORD_CWORD_CWORD,
3067         /* 153      */ CWORD_CWORD_CWORD_CWORD,
3068         /* 154      */ CWORD_CWORD_CWORD_CWORD,
3069         /* 155      */ CWORD_CWORD_CWORD_CWORD,
3070         /* 156      */ CWORD_CWORD_CWORD_CWORD,
3071         /* 157      */ CWORD_CWORD_CWORD_CWORD,
3072         /* 158      */ CWORD_CWORD_CWORD_CWORD,
3073         /* 159      */ CWORD_CWORD_CWORD_CWORD,
3074         /* 160      */ CWORD_CWORD_CWORD_CWORD,
3075         /* 161      */ CWORD_CWORD_CWORD_CWORD,
3076         /* 162      */ CWORD_CWORD_CWORD_CWORD,
3077         /* 163      */ CWORD_CWORD_CWORD_CWORD,
3078         /* 164      */ CWORD_CWORD_CWORD_CWORD,
3079         /* 165      */ CWORD_CWORD_CWORD_CWORD,
3080         /* 166      */ CWORD_CWORD_CWORD_CWORD,
3081         /* 167      */ CWORD_CWORD_CWORD_CWORD,
3082         /* 168      */ CWORD_CWORD_CWORD_CWORD,
3083         /* 169      */ CWORD_CWORD_CWORD_CWORD,
3084         /* 170      */ CWORD_CWORD_CWORD_CWORD,
3085         /* 171      */ CWORD_CWORD_CWORD_CWORD,
3086         /* 172      */ CWORD_CWORD_CWORD_CWORD,
3087         /* 173      */ CWORD_CWORD_CWORD_CWORD,
3088         /* 174      */ CWORD_CWORD_CWORD_CWORD,
3089         /* 175      */ CWORD_CWORD_CWORD_CWORD,
3090         /* 176      */ CWORD_CWORD_CWORD_CWORD,
3091         /* 177      */ CWORD_CWORD_CWORD_CWORD,
3092         /* 178      */ CWORD_CWORD_CWORD_CWORD,
3093         /* 179      */ CWORD_CWORD_CWORD_CWORD,
3094         /* 180      */ CWORD_CWORD_CWORD_CWORD,
3095         /* 181      */ CWORD_CWORD_CWORD_CWORD,
3096         /* 182      */ CWORD_CWORD_CWORD_CWORD,
3097         /* 183      */ CWORD_CWORD_CWORD_CWORD,
3098         /* 184      */ CWORD_CWORD_CWORD_CWORD,
3099         /* 185      */ CWORD_CWORD_CWORD_CWORD,
3100         /* 186      */ CWORD_CWORD_CWORD_CWORD,
3101         /* 187      */ CWORD_CWORD_CWORD_CWORD,
3102         /* 188      */ CWORD_CWORD_CWORD_CWORD,
3103         /* 189      */ CWORD_CWORD_CWORD_CWORD,
3104         /* 190      */ CWORD_CWORD_CWORD_CWORD,
3105         /* 191      */ CWORD_CWORD_CWORD_CWORD,
3106         /* 192      */ CWORD_CWORD_CWORD_CWORD,
3107         /* 193      */ CWORD_CWORD_CWORD_CWORD,
3108         /* 194      */ CWORD_CWORD_CWORD_CWORD,
3109         /* 195      */ CWORD_CWORD_CWORD_CWORD,
3110         /* 196      */ CWORD_CWORD_CWORD_CWORD,
3111         /* 197      */ CWORD_CWORD_CWORD_CWORD,
3112         /* 198      */ CWORD_CWORD_CWORD_CWORD,
3113         /* 199      */ CWORD_CWORD_CWORD_CWORD,
3114         /* 200      */ CWORD_CWORD_CWORD_CWORD,
3115         /* 201      */ CWORD_CWORD_CWORD_CWORD,
3116         /* 202      */ CWORD_CWORD_CWORD_CWORD,
3117         /* 203      */ CWORD_CWORD_CWORD_CWORD,
3118         /* 204      */ CWORD_CWORD_CWORD_CWORD,
3119         /* 205      */ CWORD_CWORD_CWORD_CWORD,
3120         /* 206      */ CWORD_CWORD_CWORD_CWORD,
3121         /* 207      */ CWORD_CWORD_CWORD_CWORD,
3122         /* 208      */ CWORD_CWORD_CWORD_CWORD,
3123         /* 209      */ CWORD_CWORD_CWORD_CWORD,
3124         /* 210      */ CWORD_CWORD_CWORD_CWORD,
3125         /* 211      */ CWORD_CWORD_CWORD_CWORD,
3126         /* 212      */ CWORD_CWORD_CWORD_CWORD,
3127         /* 213      */ CWORD_CWORD_CWORD_CWORD,
3128         /* 214      */ CWORD_CWORD_CWORD_CWORD,
3129         /* 215      */ CWORD_CWORD_CWORD_CWORD,
3130         /* 216      */ CWORD_CWORD_CWORD_CWORD,
3131         /* 217      */ CWORD_CWORD_CWORD_CWORD,
3132         /* 218      */ CWORD_CWORD_CWORD_CWORD,
3133         /* 219      */ CWORD_CWORD_CWORD_CWORD,
3134         /* 220      */ CWORD_CWORD_CWORD_CWORD,
3135         /* 221      */ CWORD_CWORD_CWORD_CWORD,
3136         /* 222      */ CWORD_CWORD_CWORD_CWORD,
3137         /* 223      */ CWORD_CWORD_CWORD_CWORD,
3138         /* 224      */ CWORD_CWORD_CWORD_CWORD,
3139         /* 225      */ CWORD_CWORD_CWORD_CWORD,
3140         /* 226      */ CWORD_CWORD_CWORD_CWORD,
3141         /* 227      */ CWORD_CWORD_CWORD_CWORD,
3142         /* 228      */ CWORD_CWORD_CWORD_CWORD,
3143         /* 229      */ CWORD_CWORD_CWORD_CWORD,
3144         /* 230      */ CWORD_CWORD_CWORD_CWORD,
3145         /* 231      */ CWORD_CWORD_CWORD_CWORD,
3146         /* 232      */ CWORD_CWORD_CWORD_CWORD,
3147         /* 233      */ CWORD_CWORD_CWORD_CWORD,
3148         /* 234      */ CWORD_CWORD_CWORD_CWORD,
3149         /* 235      */ CWORD_CWORD_CWORD_CWORD,
3150         /* 236      */ CWORD_CWORD_CWORD_CWORD,
3151         /* 237      */ CWORD_CWORD_CWORD_CWORD,
3152         /* 238      */ CWORD_CWORD_CWORD_CWORD,
3153         /* 239      */ CWORD_CWORD_CWORD_CWORD,
3154         /* 230      */ CWORD_CWORD_CWORD_CWORD,
3155         /* 241      */ CWORD_CWORD_CWORD_CWORD,
3156         /* 242      */ CWORD_CWORD_CWORD_CWORD,
3157         /* 243      */ CWORD_CWORD_CWORD_CWORD,
3158         /* 244      */ CWORD_CWORD_CWORD_CWORD,
3159         /* 245      */ CWORD_CWORD_CWORD_CWORD,
3160         /* 246      */ CWORD_CWORD_CWORD_CWORD,
3161         /* 247      */ CWORD_CWORD_CWORD_CWORD,
3162         /* 248      */ CWORD_CWORD_CWORD_CWORD,
3163         /* 249      */ CWORD_CWORD_CWORD_CWORD,
3164         /* 250      */ CWORD_CWORD_CWORD_CWORD,
3165         /* 251      */ CWORD_CWORD_CWORD_CWORD,
3166         /* 252      */ CWORD_CWORD_CWORD_CWORD,
3167         /* 253      */ CWORD_CWORD_CWORD_CWORD,
3168         /* 254      */ CWORD_CWORD_CWORD_CWORD,
3169         /* 255      */ CWORD_CWORD_CWORD_CWORD,
3170         /* PEOF */     CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3171 # if ENABLE_ASH_ALIAS
3172         /* PEOA */     CSPCL_CIGN_CIGN_CIGN,
3173 # endif
3174 };
3175
3176 #if 1
3177 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3178 #else /* debug version, caught one signed char bug */
3179 # define SIT(c, syntax) \
3180         ({ \
3181                 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3182                         bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3183                 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3184                         bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3185                 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3186         })
3187 #endif
3188
3189 #endif  /* !USE_SIT_FUNCTION */
3190
3191
3192 /* ============ Alias handling */
3193
3194 #if ENABLE_ASH_ALIAS
3195
3196 #define ALIASINUSE 1
3197 #define ALIASDEAD  2
3198
3199 struct alias {
3200         struct alias *next;
3201         char *name;
3202         char *val;
3203         int flag;
3204 };
3205
3206
3207 static struct alias **atab; // [ATABSIZE];
3208 #define INIT_G_alias() do { \
3209         atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3210 } while (0)
3211
3212
3213 static struct alias **
3214 __lookupalias(const char *name)
3215 {
3216         unsigned int hashval;
3217         struct alias **app;
3218         const char *p;
3219         unsigned int ch;
3220
3221         p = name;
3222
3223         ch = (unsigned char)*p;
3224         hashval = ch << 4;
3225         while (ch) {
3226                 hashval += ch;
3227                 ch = (unsigned char)*++p;
3228         }
3229         app = &atab[hashval % ATABSIZE];
3230
3231         for (; *app; app = &(*app)->next) {
3232                 if (strcmp(name, (*app)->name) == 0) {
3233                         break;
3234                 }
3235         }
3236
3237         return app;
3238 }
3239
3240 static struct alias *
3241 lookupalias(const char *name, int check)
3242 {
3243         struct alias *ap = *__lookupalias(name);
3244
3245         if (check && ap && (ap->flag & ALIASINUSE))
3246                 return NULL;
3247         return ap;
3248 }
3249
3250 static struct alias *
3251 freealias(struct alias *ap)
3252 {
3253         struct alias *next;
3254
3255         if (ap->flag & ALIASINUSE) {
3256                 ap->flag |= ALIASDEAD;
3257                 return ap;
3258         }
3259
3260         next = ap->next;
3261         free(ap->name);
3262         free(ap->val);
3263         free(ap);
3264         return next;
3265 }
3266
3267 static void
3268 setalias(const char *name, const char *val)
3269 {
3270         struct alias *ap, **app;
3271
3272         app = __lookupalias(name);
3273         ap = *app;
3274         INT_OFF;
3275         if (ap) {
3276                 if (!(ap->flag & ALIASINUSE)) {
3277                         free(ap->val);
3278                 }
3279                 ap->val = ckstrdup(val);
3280                 ap->flag &= ~ALIASDEAD;
3281         } else {
3282                 /* not found */
3283                 ap = ckzalloc(sizeof(struct alias));
3284                 ap->name = ckstrdup(name);
3285                 ap->val = ckstrdup(val);
3286                 /*ap->flag = 0; - ckzalloc did it */
3287                 /*ap->next = NULL;*/
3288                 *app = ap;
3289         }
3290         INT_ON;
3291 }
3292
3293 static int
3294 unalias(const char *name)
3295 {
3296         struct alias **app;
3297
3298         app = __lookupalias(name);
3299
3300         if (*app) {
3301                 INT_OFF;
3302                 *app = freealias(*app);
3303                 INT_ON;
3304                 return 0;
3305         }
3306
3307         return 1;
3308 }
3309
3310 static void
3311 rmaliases(void)
3312 {
3313         struct alias *ap, **app;
3314         int i;
3315
3316         INT_OFF;
3317         for (i = 0; i < ATABSIZE; i++) {
3318                 app = &atab[i];
3319                 for (ap = *app; ap; ap = *app) {
3320                         *app = freealias(*app);
3321                         if (ap == *app) {
3322                                 app = &ap->next;
3323                         }
3324                 }
3325         }
3326         INT_ON;
3327 }
3328
3329 static void
3330 printalias(const struct alias *ap)
3331 {
3332         out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3333 }
3334
3335 /*
3336  * TODO - sort output
3337  */
3338 static int FAST_FUNC
3339 aliascmd(int argc UNUSED_PARAM, char **argv)
3340 {
3341         char *n, *v;
3342         int ret = 0;
3343         struct alias *ap;
3344
3345         if (!argv[1]) {
3346                 int i;
3347
3348                 for (i = 0; i < ATABSIZE; i++) {
3349                         for (ap = atab[i]; ap; ap = ap->next) {
3350                                 printalias(ap);
3351                         }
3352                 }
3353                 return 0;
3354         }
3355         while ((n = *++argv) != NULL) {
3356                 v = strchr(n+1, '=');
3357                 if (v == NULL) { /* n+1: funny ksh stuff */
3358                         ap = *__lookupalias(n);
3359                         if (ap == NULL) {
3360                                 fprintf(stderr, "%s: %s not found\n", "alias", n);
3361                                 ret = 1;
3362                         } else
3363                                 printalias(ap);
3364                 } else {
3365                         *v++ = '\0';
3366                         setalias(n, v);
3367                 }
3368         }
3369
3370         return ret;
3371 }
3372
3373 static int FAST_FUNC
3374 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3375 {
3376         int i;
3377
3378         while (nextopt("a") != '\0') {
3379                 rmaliases();
3380                 return 0;
3381         }
3382         for (i = 0; *argptr; argptr++) {
3383                 if (unalias(*argptr)) {
3384                         fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3385                         i = 1;
3386                 }
3387         }
3388
3389         return i;
3390 }
3391
3392 #endif /* ASH_ALIAS */
3393
3394
3395 /* Mode argument to forkshell.  Don't change FORK_FG or FORK_BG. */
3396 #define FORK_FG    0
3397 #define FORK_BG    1
3398 #define FORK_NOJOB 2
3399
3400 /* mode flags for showjob(s) */
3401 #define SHOW_ONLY_PGID  0x01    /* show only pgid (jobs -p) */
3402 #define SHOW_PIDS       0x02    /* show individual pids, not just one line per job */
3403 #define SHOW_CHANGED    0x04    /* only jobs whose state has changed */
3404 #define SHOW_STDERR     0x08    /* print to stderr (else stdout) */
3405
3406 /*
3407  * A job structure contains information about a job.  A job is either a
3408  * single process or a set of processes contained in a pipeline.  In the
3409  * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3410  * array of pids.
3411  */
3412 struct procstat {
3413         pid_t   ps_pid;         /* process id */
3414         int     ps_status;      /* last process status from wait() */
3415         char    *ps_cmd;        /* text of command being run */
3416 };
3417
3418 struct job {
3419         struct procstat ps0;    /* status of process */
3420         struct procstat *ps;    /* status or processes when more than one */
3421 #if JOBS
3422         int stopstatus;         /* status of a stopped job */
3423 #endif
3424         unsigned nprocs;        /* number of processes */
3425
3426 #define JOBRUNNING      0       /* at least one proc running */
3427 #define JOBSTOPPED      1       /* all procs are stopped */
3428 #define JOBDONE         2       /* all procs are completed */
3429         unsigned
3430                 state: 8,
3431 #if JOBS
3432                 sigint: 1,      /* job was killed by SIGINT */
3433                 jobctl: 1,      /* job running under job control */
3434 #endif
3435                 waited: 1,      /* true if this entry has been waited for */
3436                 used: 1,        /* true if this entry is in used */
3437                 changed: 1;     /* true if status has changed */
3438         struct job *prev_job;   /* previous job */
3439 };
3440
3441 static struct job *makejob(/*union node *,*/ int);
3442 static int forkshell(struct job *, union node *, int);
3443 static int waitforjob(struct job *);
3444
3445 #if !JOBS
3446 enum { doing_jobctl = 0 };
3447 #define setjobctl(on) do {} while (0)
3448 #else
3449 static smallint doing_jobctl; //references:8
3450 static void setjobctl(int);
3451 #endif
3452
3453 /*
3454  * Ignore a signal.
3455  */
3456 static void
3457 ignoresig(int signo)
3458 {
3459         /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3460         if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3461                 /* No, need to do it */
3462                 signal(signo, SIG_IGN);
3463         }
3464         sigmode[signo - 1] = S_HARD_IGN;
3465 }
3466
3467 /*
3468  * Only one usage site - in setsignal()
3469  */
3470 static void
3471 signal_handler(int signo)
3472 {
3473         if (signo == SIGCHLD) {
3474                 got_sigchld = 1;
3475                 if (!trap[SIGCHLD])
3476                         return;
3477         }
3478
3479         gotsig[signo - 1] = 1;
3480         pending_sig = signo;
3481
3482         if (signo == SIGINT && !trap[SIGINT]) {
3483                 if (!suppress_int) {
3484                         pending_sig = 0;
3485                         raise_interrupt(); /* does not return */
3486                 }
3487                 pending_int = 1;
3488         }
3489 }
3490
3491 /*
3492  * Set the signal handler for the specified signal.  The routine figures
3493  * out what it should be set to.
3494  */
3495 static void
3496 setsignal(int signo)
3497 {
3498         char *t;
3499         char cur_act, new_act;
3500         struct sigaction act;
3501
3502         t = trap[signo];
3503         new_act = S_DFL;
3504         if (t != NULL) { /* trap for this sig is set */
3505                 new_act = S_CATCH;
3506                 if (t[0] == '\0') /* trap is "": ignore this sig */
3507                         new_act = S_IGN;
3508         }
3509
3510         if (rootshell && new_act == S_DFL) {
3511                 switch (signo) {
3512                 case SIGINT:
3513                         if (iflag || minusc || sflag == 0)
3514                                 new_act = S_CATCH;
3515                         break;
3516                 case SIGQUIT:
3517 #if DEBUG
3518                         if (debug)
3519                                 break;
3520 #endif
3521                         /* man bash:
3522                          * "In all cases, bash ignores SIGQUIT. Non-builtin
3523                          * commands run by bash have signal handlers
3524                          * set to the values inherited by the shell
3525                          * from its parent". */
3526                         new_act = S_IGN;
3527                         break;
3528                 case SIGTERM:
3529                         if (iflag)
3530                                 new_act = S_IGN;
3531                         break;
3532 #if JOBS
3533                 case SIGTSTP:
3534                 case SIGTTOU:
3535                         if (mflag)
3536                                 new_act = S_IGN;
3537                         break;
3538 #endif
3539                 }
3540         }
3541 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3542 //whereas we have to restore it to what shell got on entry
3543 //from the parent. See comment above
3544
3545         if (signo == SIGCHLD)
3546                 new_act = S_CATCH;
3547
3548         t = &sigmode[signo - 1];
3549         cur_act = *t;
3550         if (cur_act == 0) {
3551                 /* current setting is not yet known */
3552                 if (sigaction(signo, NULL, &act)) {
3553                         /* pretend it worked; maybe we should give a warning,
3554                          * but other shells don't. We don't alter sigmode,
3555                          * so we retry every time.
3556                          * btw, in Linux it never fails. --vda */
3557                         return;
3558                 }
3559                 if (act.sa_handler == SIG_IGN) {
3560                         cur_act = S_HARD_IGN;
3561                         if (mflag
3562                          && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3563                         ) {
3564                                 cur_act = S_IGN;   /* don't hard ignore these */
3565                         }
3566                 }
3567         }
3568         if (cur_act == S_HARD_IGN || cur_act == new_act)
3569                 return;
3570
3571         act.sa_handler = SIG_DFL;
3572         switch (new_act) {
3573         case S_CATCH:
3574                 act.sa_handler = signal_handler;
3575                 break;
3576         case S_IGN:
3577                 act.sa_handler = SIG_IGN;
3578                 break;
3579         }
3580
3581         /* flags and mask matter only if !DFL and !IGN, but we do it
3582          * for all cases for more deterministic behavior:
3583          */
3584         act.sa_flags = 0;
3585         sigfillset(&act.sa_mask);
3586
3587         sigaction_set(signo, &act);
3588
3589         *t = new_act;
3590 }
3591
3592 /* mode flags for set_curjob */
3593 #define CUR_DELETE 2
3594 #define CUR_RUNNING 1
3595 #define CUR_STOPPED 0
3596
3597 #if JOBS
3598 /* pgrp of shell on invocation */
3599 static int initialpgrp; //references:2
3600 static int ttyfd = -1; //5
3601 #endif
3602 /* array of jobs */
3603 static struct job *jobtab; //5
3604 /* size of array */
3605 static unsigned njobs; //4
3606 /* current job */
3607 static struct job *curjob; //lots
3608 /* number of presumed living untracked jobs */
3609 static int jobless; //4
3610
3611 #if 0
3612 /* Bash has a feature: it restores termios after a successful wait for
3613  * a foreground job which had at least one stopped or sigkilled member.
3614  * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3615  * properly restoring tty state. Should we do this too?
3616  * A reproducer: ^Z an interactive python:
3617  *
3618  * # python
3619  * Python 2.7.12 (...)
3620  * >>> ^Z
3621  *      { python leaves tty in -icanon -echo state. We do survive that... }
3622  *  [1]+  Stopped                    python
3623  *      { ...however, next program (python #2) does not survive it well: }
3624  * # python
3625  * Python 2.7.12 (...)
3626  * >>> Traceback (most recent call last):
3627  *      { above, I typed "qwerty<CR>", but -echo state is still in effect }
3628  *   File "<stdin>", line 1, in <module>
3629  * NameError: name 'qwerty' is not defined
3630  *
3631  * The implementation below is modeled on bash code and seems to work.
3632  * However, I'm not sure we should do this. For one: what if I'd fg
3633  * the stopped python instead? It'll be confused by "restored" tty state.
3634  */
3635 static struct termios shell_tty_info;
3636 static void
3637 get_tty_state(void)
3638 {
3639         if (rootshell && ttyfd >= 0)
3640                 tcgetattr(ttyfd, &shell_tty_info);
3641 }
3642 static void
3643 set_tty_state(void)
3644 {
3645         /* if (rootshell) - caller ensures this */
3646         if (ttyfd >= 0)
3647                 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3648 }
3649 static int
3650 job_signal_status(struct job *jp)
3651 {
3652         int status;
3653         unsigned i;
3654         struct procstat *ps = jp->ps;
3655         for (i = 0; i < jp->nprocs; i++) {
3656                 status = ps[i].ps_status;
3657                 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3658                         return status;
3659         }
3660         return 0;
3661 }
3662 static void
3663 restore_tty_if_stopped_or_signaled(struct job *jp)
3664 {
3665 //TODO: check what happens if we come from waitforjob() in expbackq()
3666         if (rootshell) {
3667                 int s = job_signal_status(jp);
3668                 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3669                         set_tty_state();
3670         }
3671 }
3672 #else
3673 # define get_tty_state() ((void)0)
3674 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3675 #endif
3676
3677 static void
3678 set_curjob(struct job *jp, unsigned mode)
3679 {
3680         struct job *jp1;
3681         struct job **jpp, **curp;
3682
3683         /* first remove from list */
3684         jpp = curp = &curjob;
3685         while (1) {
3686                 jp1 = *jpp;
3687                 if (jp1 == jp)
3688                         break;
3689                 jpp = &jp1->prev_job;
3690         }
3691         *jpp = jp1->prev_job;
3692
3693         /* Then re-insert in correct position */
3694         jpp = curp;
3695         switch (mode) {
3696         default:
3697 #if DEBUG
3698                 abort();
3699 #endif
3700         case CUR_DELETE:
3701                 /* job being deleted */
3702                 break;
3703         case CUR_RUNNING:
3704                 /* newly created job or backgrounded job,
3705                  * put after all stopped jobs.
3706                  */
3707                 while (1) {
3708                         jp1 = *jpp;
3709 #if JOBS
3710                         if (!jp1 || jp1->state != JOBSTOPPED)
3711 #endif
3712                                 break;
3713                         jpp = &jp1->prev_job;
3714                 }
3715                 /* FALLTHROUGH */
3716 #if JOBS
3717         case CUR_STOPPED:
3718 #endif
3719                 /* newly stopped job - becomes curjob */
3720                 jp->prev_job = *jpp;
3721                 *jpp = jp;
3722                 break;
3723         }
3724 }
3725
3726 #if JOBS || DEBUG
3727 static int
3728 jobno(const struct job *jp)
3729 {
3730         return jp - jobtab + 1;
3731 }
3732 #endif
3733
3734 /*
3735  * Convert a job name to a job structure.
3736  */
3737 #if !JOBS
3738 #define getjob(name, getctl) getjob(name)
3739 #endif
3740 static struct job *
3741 getjob(const char *name, int getctl)
3742 {
3743         struct job *jp;
3744         struct job *found;
3745         const char *err_msg = "%s: no such job";
3746         unsigned num;
3747         int c;
3748         const char *p;
3749         char *(*match)(const char *, const char *);
3750
3751         jp = curjob;
3752         p = name;
3753         if (!p)
3754                 goto currentjob;
3755
3756         if (*p != '%')
3757                 goto err;
3758
3759         c = *++p;
3760         if (!c)
3761                 goto currentjob;
3762
3763         if (!p[1]) {
3764                 if (c == '+' || c == '%') {
3765  currentjob:
3766                         err_msg = "No current job";
3767                         goto check;
3768                 }
3769                 if (c == '-') {
3770                         if (jp)
3771                                 jp = jp->prev_job;
3772                         err_msg = "No previous job";
3773  check:
3774                         if (!jp)
3775                                 goto err;
3776                         goto gotit;
3777                 }
3778         }
3779
3780         if (is_number(p)) {
3781                 num = atoi(p);
3782                 if (num > 0 && num <= njobs) {
3783                         jp = jobtab + num - 1;
3784                         if (jp->used)
3785                                 goto gotit;
3786                         goto err;
3787                 }
3788         }
3789
3790         match = prefix;
3791         if (*p == '?') {
3792                 match = strstr;
3793                 p++;
3794         }
3795
3796         found = NULL;
3797         while (jp) {
3798                 if (match(jp->ps[0].ps_cmd, p)) {
3799                         if (found)
3800                                 goto err;
3801                         found = jp;
3802                         err_msg = "%s: ambiguous";
3803                 }
3804                 jp = jp->prev_job;
3805         }
3806         if (!found)
3807                 goto err;
3808         jp = found;
3809
3810  gotit:
3811 #if JOBS
3812         err_msg = "job %s not created under job control";
3813         if (getctl && jp->jobctl == 0)
3814                 goto err;
3815 #endif
3816         return jp;
3817  err:
3818         ash_msg_and_raise_error(err_msg, name);
3819 }
3820
3821 /*
3822  * Mark a job structure as unused.
3823  */
3824 static void
3825 freejob(struct job *jp)
3826 {
3827         struct procstat *ps;
3828         int i;
3829
3830         INT_OFF;
3831         for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3832                 if (ps->ps_cmd != nullstr)
3833                         free(ps->ps_cmd);
3834         }
3835         if (jp->ps != &jp->ps0)
3836                 free(jp->ps);
3837         jp->used = 0;
3838         set_curjob(jp, CUR_DELETE);
3839         INT_ON;
3840 }
3841
3842 #if JOBS
3843 static void
3844 xtcsetpgrp(int fd, pid_t pgrp)
3845 {
3846         if (tcsetpgrp(fd, pgrp))
3847                 ash_msg_and_raise_perror("can't set tty process group");
3848 }
3849
3850 /*
3851  * Turn job control on and off.
3852  *
3853  * Note:  This code assumes that the third arg to ioctl is a character
3854  * pointer, which is true on Berkeley systems but not System V.  Since
3855  * System V doesn't have job control yet, this isn't a problem now.
3856  *
3857  * Called with interrupts off.
3858  */
3859 static void
3860 setjobctl(int on)
3861 {
3862         int fd;
3863         int pgrp;
3864
3865         if (on == doing_jobctl || rootshell == 0)
3866                 return;
3867         if (on) {
3868                 int ofd;
3869                 ofd = fd = open(_PATH_TTY, O_RDWR);
3870                 if (fd < 0) {
3871         /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3872          * That sometimes helps to acquire controlling tty.
3873          * Obviously, a workaround for bugs when someone
3874          * failed to provide a controlling tty to bash! :) */
3875                         fd = 2;
3876                         while (!isatty(fd))
3877                                 if (--fd < 0)
3878                                         goto out;
3879                 }
3880                 /* fd is a tty at this point */
3881                 fd = fcntl(fd, F_DUPFD, 10);
3882                 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3883                         close(ofd);
3884                 if (fd < 0)
3885                         goto out; /* F_DUPFD failed */
3886                 close_on_exec_on(fd);
3887                 while (1) { /* while we are in the background */
3888                         pgrp = tcgetpgrp(fd);
3889                         if (pgrp < 0) {
3890  out:
3891                                 ash_msg("can't access tty; job control turned off");
3892                                 mflag = on = 0;
3893                                 goto close;
3894                         }
3895                         if (pgrp == getpgrp())
3896                                 break;
3897                         killpg(0, SIGTTIN);
3898                 }
3899                 initialpgrp = pgrp;
3900
3901                 setsignal(SIGTSTP);
3902                 setsignal(SIGTTOU);
3903                 setsignal(SIGTTIN);
3904                 pgrp = rootpid;
3905                 setpgid(0, pgrp);
3906                 xtcsetpgrp(fd, pgrp);
3907         } else {
3908                 /* turning job control off */
3909                 fd = ttyfd;
3910                 pgrp = initialpgrp;
3911                 /* was xtcsetpgrp, but this can make exiting ash
3912                  * loop forever if pty is already deleted */
3913                 tcsetpgrp(fd, pgrp);
3914                 setpgid(0, pgrp);
3915                 setsignal(SIGTSTP);
3916                 setsignal(SIGTTOU);
3917                 setsignal(SIGTTIN);
3918  close:
3919                 if (fd >= 0)
3920                         close(fd);
3921                 fd = -1;
3922         }
3923         ttyfd = fd;
3924         doing_jobctl = on;
3925 }
3926
3927 static int FAST_FUNC
3928 killcmd(int argc, char **argv)
3929 {
3930         if (argv[1] && strcmp(argv[1], "-l") != 0) {
3931                 int i = 1;
3932                 do {
3933                         if (argv[i][0] == '%') {
3934                                 /*
3935                                  * "kill %N" - job kill
3936                                  * Converting to pgrp / pid kill
3937                                  */
3938                                 struct job *jp;
3939                                 char *dst;
3940                                 int j, n;
3941
3942                                 jp = getjob(argv[i], 0);
3943                                 /*
3944                                  * In jobs started under job control, we signal
3945                                  * entire process group by kill -PGRP_ID.
3946                                  * This happens, f.e., in interactive shell.
3947                                  *
3948                                  * Otherwise, we signal each child via
3949                                  * kill PID1 PID2 PID3.
3950                                  * Testcases:
3951                                  * sh -c 'sleep 1|sleep 1 & kill %1'
3952                                  * sh -c 'true|sleep 2 & sleep 1; kill %1'
3953                                  * sh -c 'true|sleep 1 & sleep 2; kill %1'
3954                                  */
3955                                 n = jp->nprocs; /* can't be 0 (I hope) */
3956                                 if (jp->jobctl)
3957                                         n = 1;
3958                                 dst = alloca(n * sizeof(int)*4);
3959                                 argv[i] = dst;
3960                                 for (j = 0; j < n; j++) {
3961                                         struct procstat *ps = &jp->ps[j];
3962                                         /* Skip non-running and not-stopped members
3963                                          * (i.e. dead members) of the job
3964                                          */
3965                                         if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3966                                                 continue;
3967                                         /*
3968                                          * kill_main has matching code to expect
3969                                          * leading space. Needed to not confuse
3970                                          * negative pids with "kill -SIGNAL_NO" syntax
3971                                          */
3972                                         dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3973                                 }
3974                                 *dst = '\0';
3975                         }
3976                 } while (argv[++i]);
3977         }
3978         return kill_main(argc, argv);
3979 }
3980
3981 static void
3982 showpipe(struct job *jp /*, FILE *out*/)
3983 {
3984         struct procstat *ps;
3985         struct procstat *psend;
3986
3987         psend = jp->ps + jp->nprocs;
3988         for (ps = jp->ps + 1; ps < psend; ps++)
3989                 printf(" | %s", ps->ps_cmd);
3990         newline_and_flush(stdout);
3991         flush_stdout_stderr();
3992 }
3993
3994
3995 static int
3996 restartjob(struct job *jp, int mode)
3997 {
3998         struct procstat *ps;
3999         int i;
4000         int status;
4001         pid_t pgid;
4002
4003         INT_OFF;
4004         if (jp->state == JOBDONE)
4005                 goto out;
4006         jp->state = JOBRUNNING;
4007         pgid = jp->ps[0].ps_pid;
4008         if (mode == FORK_FG) {
4009                 get_tty_state();
4010                 xtcsetpgrp(ttyfd, pgid);
4011         }
4012         killpg(pgid, SIGCONT);
4013         ps = jp->ps;
4014         i = jp->nprocs;
4015         do {
4016                 if (WIFSTOPPED(ps->ps_status)) {
4017                         ps->ps_status = -1;
4018                 }
4019                 ps++;
4020         } while (--i);
4021  out:
4022         status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4023         INT_ON;
4024         return status;
4025 }
4026
4027 static int FAST_FUNC
4028 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4029 {
4030         struct job *jp;
4031         int mode;
4032         int retval;
4033
4034         mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4035         nextopt(nullstr);
4036         argv = argptr;
4037         do {
4038                 jp = getjob(*argv, 1);
4039                 if (mode == FORK_BG) {
4040                         set_curjob(jp, CUR_RUNNING);
4041                         printf("[%d] ", jobno(jp));
4042                 }
4043                 out1str(jp->ps[0].ps_cmd);
4044                 showpipe(jp /*, stdout*/);
4045                 retval = restartjob(jp, mode);
4046         } while (*argv && *++argv);
4047         return retval;
4048 }
4049 #endif
4050
4051 static int
4052 sprint_status48(char *s, int status, int sigonly)
4053 {
4054         int col;
4055         int st;
4056
4057         col = 0;
4058         if (!WIFEXITED(status)) {
4059 #if JOBS
4060                 if (WIFSTOPPED(status))
4061                         st = WSTOPSIG(status);
4062                 else
4063 #endif
4064                         st = WTERMSIG(status);
4065                 if (sigonly) {
4066                         if (st == SIGINT || st == SIGPIPE)
4067                                 goto out;
4068 #if JOBS
4069                         if (WIFSTOPPED(status))
4070                                 goto out;
4071 #endif
4072                 }
4073                 st &= 0x7f;
4074 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4075                 col = fmtstr(s, 32, strsignal(st));
4076                 if (WCOREDUMP(status)) {
4077                         strcpy(s + col, " (core dumped)");
4078                         col += sizeof(" (core dumped)")-1;
4079                 }
4080         } else if (!sigonly) {
4081                 st = WEXITSTATUS(status);
4082                 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4083         }
4084  out:
4085         return col;
4086 }
4087
4088 static int
4089 wait_block_or_sig(int *status)
4090 {
4091         int pid;
4092
4093         do {
4094                 sigset_t mask;
4095
4096                 /* Poll all children for changes in their state */
4097                 got_sigchld = 0;
4098                 /* if job control is active, accept stopped processes too */
4099                 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4100                 if (pid != 0)
4101                         break; /* Error (e.g. EINTR, ECHILD) or pid */
4102
4103                 /* Children exist, but none are ready. Sleep until interesting signal */
4104 #if 1
4105                 sigfillset(&mask);
4106                 sigprocmask(SIG_SETMASK, &mask, &mask);
4107                 while (!got_sigchld && !pending_sig)
4108                         sigsuspend(&mask);
4109                 sigprocmask(SIG_SETMASK, &mask, NULL);
4110 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4111                 while (!got_sigchld && !pending_sig)
4112                         pause();
4113 #endif
4114
4115                 /* If it was SIGCHLD, poll children again */
4116         } while (got_sigchld);
4117
4118         return pid;
4119 }
4120
4121 #define DOWAIT_NONBLOCK 0
4122 #define DOWAIT_BLOCK    1
4123 #define DOWAIT_BLOCK_OR_SIG 2
4124
4125 static int
4126 dowait(int block, struct job *job)
4127 {
4128         int pid;
4129         int status;
4130         struct job *jp;
4131         struct job *thisjob = NULL;
4132
4133         TRACE(("dowait(0x%x) called\n", block));
4134
4135         /* It's wrong to call waitpid() outside of INT_OFF region:
4136          * signal can arrive just after syscall return and handler can
4137          * longjmp away, losing stop/exit notification processing.
4138          * Thus, for "jobs" builtin, and for waiting for a fg job,
4139          * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4140          *
4141          * However, for "wait" builtin it is wrong to simply call waitpid()
4142          * in INT_OFF region: "wait" needs to wait for any running job
4143          * to change state, but should exit on any trap too.
4144          * In INT_OFF region, a signal just before syscall entry can set
4145          * pending_sig variables, but we can't check them, and we would
4146          * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4147          *
4148          * Because of this, we run inside INT_OFF, but use a special routine
4149          * which combines waitpid() and sigsuspend().
4150          * This is the reason why we need to have a handler for SIGCHLD:
4151          * SIG_DFL handler does not wake sigsuspend().
4152          */
4153         INT_OFF;
4154         if (block == DOWAIT_BLOCK_OR_SIG) {
4155                 pid = wait_block_or_sig(&status);
4156         } else {
4157                 int wait_flags = 0;
4158                 if (block == DOWAIT_NONBLOCK)
4159                         wait_flags = WNOHANG;
4160                 /* if job control is active, accept stopped processes too */
4161                 if (doing_jobctl)
4162                         wait_flags |= WUNTRACED;
4163                 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4164                 pid = waitpid(-1, &status, wait_flags);
4165         }
4166         TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4167                                 pid, status, errno, strerror(errno)));
4168         if (pid <= 0)
4169                 goto out;
4170
4171         thisjob = NULL;
4172         for (jp = curjob; jp; jp = jp->prev_job) {
4173                 int jobstate;
4174                 struct procstat *ps;
4175                 struct procstat *psend;
4176                 if (jp->state == JOBDONE)
4177                         continue;
4178                 jobstate = JOBDONE;
4179                 ps = jp->ps;
4180                 psend = ps + jp->nprocs;
4181                 do {
4182                         if (ps->ps_pid == pid) {
4183                                 TRACE(("Job %d: changing status of proc %d "
4184                                         "from 0x%x to 0x%x\n",
4185                                         jobno(jp), pid, ps->ps_status, status));
4186                                 ps->ps_status = status;
4187                                 thisjob = jp;
4188                         }
4189                         if (ps->ps_status == -1)
4190                                 jobstate = JOBRUNNING;
4191 #if JOBS
4192                         if (jobstate == JOBRUNNING)
4193                                 continue;
4194                         if (WIFSTOPPED(ps->ps_status)) {
4195                                 jp->stopstatus = ps->ps_status;
4196                                 jobstate = JOBSTOPPED;
4197                         }
4198 #endif
4199                 } while (++ps < psend);
4200                 if (!thisjob)
4201                         continue;
4202
4203                 /* Found the job where one of its processes changed its state.
4204                  * Is there at least one live and running process in this job? */
4205                 if (jobstate != JOBRUNNING) {
4206                         /* No. All live processes in the job are stopped
4207                          * (JOBSTOPPED) or there are no live processes (JOBDONE)
4208                          */
4209                         thisjob->changed = 1;
4210                         if (thisjob->state != jobstate) {
4211                                 TRACE(("Job %d: changing state from %d to %d\n",
4212                                         jobno(thisjob), thisjob->state, jobstate));
4213                                 thisjob->state = jobstate;
4214 #if JOBS
4215                                 if (jobstate == JOBSTOPPED)
4216                                         set_curjob(thisjob, CUR_STOPPED);
4217 #endif
4218                         }
4219                 }
4220                 goto out;
4221         }
4222         /* The process wasn't found in job list */
4223 #if JOBS
4224         if (!WIFSTOPPED(status))
4225                 jobless--;
4226 #endif
4227  out:
4228         INT_ON;
4229
4230         if (thisjob && thisjob == job) {
4231                 char s[48 + 1];
4232                 int len;
4233
4234                 len = sprint_status48(s, status, 1);
4235                 if (len) {
4236                         s[len] = '\n';
4237                         s[len + 1] = '\0';
4238                         out2str(s);
4239                 }
4240         }
4241         return pid;
4242 }
4243
4244 #if JOBS
4245 static void
4246 showjob(struct job *jp, int mode)
4247 {
4248         struct procstat *ps;
4249         struct procstat *psend;
4250         int col;
4251         int indent_col;
4252         char s[16 + 16 + 48];
4253         FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4254
4255         ps = jp->ps;
4256
4257         if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4258                 /* just output process (group) id of pipeline */
4259                 fprintf(out, "%d\n", ps->ps_pid);
4260                 return;
4261         }
4262
4263         col = fmtstr(s, 16, "[%d]   ", jobno(jp));
4264         indent_col = col;
4265
4266         if (jp == curjob)
4267                 s[col - 3] = '+';
4268         else if (curjob && jp == curjob->prev_job)
4269                 s[col - 3] = '-';
4270
4271         if (mode & SHOW_PIDS)
4272                 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4273
4274         psend = ps + jp->nprocs;
4275
4276         if (jp->state == JOBRUNNING) {
4277                 strcpy(s + col, "Running");
4278                 col += sizeof("Running") - 1;
4279         } else {
4280                 int status = psend[-1].ps_status;
4281                 if (jp->state == JOBSTOPPED)
4282                         status = jp->stopstatus;
4283                 col += sprint_status48(s + col, status, 0);
4284         }
4285         /* By now, "[JOBID]*  [maybe PID] STATUS" is printed */
4286
4287         /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4288          * or prints several "PID             | <cmdN>" lines,
4289          * depending on SHOW_PIDS bit.
4290          * We do not print status of individual processes
4291          * between PID and <cmdN>. bash does it, but not very well:
4292          * first line shows overall job status, not process status,
4293          * making it impossible to know 1st process status.
4294          */
4295         goto start;
4296         do {
4297                 /* for each process */
4298                 s[0] = '\0';
4299                 col = 33;
4300                 if (mode & SHOW_PIDS)
4301                         col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4302  start:
4303                 fprintf(out, "%s%*c%s%s",
4304                                 s,
4305                                 33 - col >= 0 ? 33 - col : 0, ' ',
4306                                 ps == jp->ps ? "" : "| ",
4307                                 ps->ps_cmd
4308                 );
4309         } while (++ps != psend);
4310         newline_and_flush(out);
4311
4312         jp->changed = 0;
4313
4314         if (jp->state == JOBDONE) {
4315                 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4316                 freejob(jp);
4317         }
4318 }
4319
4320 /*
4321  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
4322  * statuses have changed since the last call to showjobs.
4323  */
4324 static void
4325 showjobs(int mode)
4326 {
4327         struct job *jp;
4328
4329         TRACE(("showjobs(0x%x) called\n", mode));
4330
4331         /* Handle all finished jobs */
4332         while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4333                 continue;
4334
4335         for (jp = curjob; jp; jp = jp->prev_job) {
4336                 if (!(mode & SHOW_CHANGED) || jp->changed) {
4337                         showjob(jp, mode);
4338                 }
4339         }
4340 }
4341
4342 static int FAST_FUNC
4343 jobscmd(int argc UNUSED_PARAM, char **argv)
4344 {
4345         int mode, m;
4346
4347         mode = 0;
4348         while ((m = nextopt("lp")) != '\0') {
4349                 if (m == 'l')
4350                         mode |= SHOW_PIDS;
4351                 else
4352                         mode |= SHOW_ONLY_PGID;
4353         }
4354
4355         argv = argptr;
4356         if (*argv) {
4357                 do
4358                         showjob(getjob(*argv, 0), mode);
4359                 while (*++argv);
4360         } else {
4361                 showjobs(mode);
4362         }
4363
4364         return 0;
4365 }
4366 #endif /* JOBS */
4367
4368 /* Called only on finished or stopped jobs (no members are running) */
4369 static int
4370 getstatus(struct job *job)
4371 {
4372         int status;
4373         int retval;
4374         struct procstat *ps;
4375
4376         /* Fetch last member's status */
4377         ps = job->ps + job->nprocs - 1;
4378         status = ps->ps_status;
4379         if (pipefail) {
4380                 /* "set -o pipefail" mode: use last _nonzero_ status */
4381                 while (status == 0 && --ps >= job->ps)
4382                         status = ps->ps_status;
4383         }
4384
4385         retval = WEXITSTATUS(status);
4386         if (!WIFEXITED(status)) {
4387 #if JOBS
4388                 retval = WSTOPSIG(status);
4389                 if (!WIFSTOPPED(status))
4390 #endif
4391                 {
4392                         /* XXX: limits number of signals */
4393                         retval = WTERMSIG(status);
4394 #if JOBS
4395                         if (retval == SIGINT)
4396                                 job->sigint = 1;
4397 #endif
4398                 }
4399                 retval += 128;
4400         }
4401         TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4402                 jobno(job), job->nprocs, status, retval));
4403         return retval;
4404 }
4405
4406 static int FAST_FUNC
4407 waitcmd(int argc UNUSED_PARAM, char **argv)
4408 {
4409         struct job *job;
4410         int retval;
4411         struct job *jp;
4412
4413         nextopt(nullstr);
4414         retval = 0;
4415
4416         argv = argptr;
4417         if (!*argv) {
4418                 /* wait for all jobs */
4419                 for (;;) {
4420                         jp = curjob;
4421                         while (1) {
4422                                 if (!jp) /* no running procs */
4423                                         goto ret;
4424                                 if (jp->state == JOBRUNNING)
4425                                         break;
4426                                 jp->waited = 1;
4427                                 jp = jp->prev_job;
4428                         }
4429         /* man bash:
4430          * "When bash is waiting for an asynchronous command via
4431          * the wait builtin, the reception of a signal for which a trap
4432          * has been set will cause the wait builtin to return immediately
4433          * with an exit status greater than 128, immediately after which
4434          * the trap is executed."
4435          */
4436                         dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4437         /* if child sends us a signal *and immediately exits*,
4438          * dowait() returns pid > 0. Check this case,
4439          * not "if (dowait() < 0)"!
4440          */
4441                         if (pending_sig)
4442                                 goto sigout;
4443                 }
4444         }
4445
4446         retval = 127;
4447         do {
4448                 if (**argv != '%') {
4449                         pid_t pid = number(*argv);
4450                         job = curjob;
4451                         while (1) {
4452                                 if (!job)
4453                                         goto repeat;
4454                                 if (job->ps[job->nprocs - 1].ps_pid == pid)
4455                                         break;
4456                                 job = job->prev_job;
4457                         }
4458                 } else {
4459                         job = getjob(*argv, 0);
4460                 }
4461                 /* loop until process terminated or stopped */
4462                 while (job->state == JOBRUNNING) {
4463                         dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4464                         if (pending_sig)
4465                                 goto sigout;
4466                 }
4467                 job->waited = 1;
4468                 retval = getstatus(job);
4469  repeat: ;
4470         } while (*++argv);
4471
4472  ret:
4473         return retval;
4474  sigout:
4475         retval = 128 + pending_sig;
4476         return retval;
4477 }
4478
4479 static struct job *
4480 growjobtab(void)
4481 {
4482         size_t len;
4483         ptrdiff_t offset;
4484         struct job *jp, *jq;
4485
4486         len = njobs * sizeof(*jp);
4487         jq = jobtab;
4488         jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4489
4490         offset = (char *)jp - (char *)jq;
4491         if (offset) {
4492                 /* Relocate pointers */
4493                 size_t l = len;
4494
4495                 jq = (struct job *)((char *)jq + l);
4496                 while (l) {
4497                         l -= sizeof(*jp);
4498                         jq--;
4499 #define joff(p) ((struct job *)((char *)(p) + l))
4500 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4501                         if (joff(jp)->ps == &jq->ps0)
4502                                 jmove(joff(jp)->ps);
4503                         if (joff(jp)->prev_job)
4504                                 jmove(joff(jp)->prev_job);
4505                 }
4506                 if (curjob)
4507                         jmove(curjob);
4508 #undef joff
4509 #undef jmove
4510         }
4511
4512         njobs += 4;
4513         jobtab = jp;
4514         jp = (struct job *)((char *)jp + len);
4515         jq = jp + 3;
4516         do {
4517                 jq->used = 0;
4518         } while (--jq >= jp);
4519         return jp;
4520 }
4521
4522 /*
4523  * Return a new job structure.
4524  * Called with interrupts off.
4525  */
4526 static struct job *
4527 makejob(/*union node *node,*/ int nprocs)
4528 {
4529         int i;
4530         struct job *jp;
4531
4532         for (i = njobs, jp = jobtab; ; jp++) {
4533                 if (--i < 0) {
4534                         jp = growjobtab();
4535                         break;
4536                 }
4537                 if (jp->used == 0)
4538                         break;
4539                 if (jp->state != JOBDONE || !jp->waited)
4540                         continue;
4541 #if JOBS
4542                 if (doing_jobctl)
4543                         continue;
4544 #endif
4545                 freejob(jp);
4546                 break;
4547         }
4548         memset(jp, 0, sizeof(*jp));
4549 #if JOBS
4550         /* jp->jobctl is a bitfield.
4551          * "jp->jobctl |= doing_jobctl" likely to give awful code */
4552         if (doing_jobctl)
4553                 jp->jobctl = 1;
4554 #endif
4555         jp->prev_job = curjob;
4556         curjob = jp;
4557         jp->used = 1;
4558         jp->ps = &jp->ps0;
4559         if (nprocs > 1) {
4560                 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4561         }
4562         TRACE(("makejob(%d) returns %%%d\n", nprocs,
4563                                 jobno(jp)));
4564         return jp;
4565 }
4566
4567 #if JOBS
4568 /*
4569  * Return a string identifying a command (to be printed by the
4570  * jobs command).
4571  */
4572 static char *cmdnextc;
4573
4574 static void
4575 cmdputs(const char *s)
4576 {
4577         static const char vstype[VSTYPE + 1][3] = {
4578                 "", "}", "-", "+", "?", "=",
4579                 "%", "%%", "#", "##"
4580                 IF_BASH_SUBSTR(, ":")
4581                 IF_BASH_PATTERN_SUBST(, "/", "//")
4582         };
4583
4584         const char *p, *str;
4585         char cc[2];
4586         char *nextc;
4587         unsigned char c;
4588         unsigned char subtype = 0;
4589         int quoted = 0;
4590
4591         cc[1] = '\0';
4592         nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4593         p = s;
4594         while ((c = *p++) != '\0') {
4595                 str = NULL;
4596                 switch (c) {
4597                 case CTLESC:
4598                         c = *p++;
4599                         break;
4600                 case CTLVAR:
4601                         subtype = *p++;
4602                         if ((subtype & VSTYPE) == VSLENGTH)
4603                                 str = "${#";
4604                         else
4605                                 str = "${";
4606                         goto dostr;
4607                 case CTLENDVAR:
4608                         str = "\"}" + !(quoted & 1);
4609                         quoted >>= 1;
4610                         subtype = 0;
4611                         goto dostr;
4612                 case CTLBACKQ:
4613                         str = "$(...)";
4614                         goto dostr;
4615 #if ENABLE_FEATURE_SH_MATH
4616                 case CTLARI:
4617                         str = "$((";
4618                         goto dostr;
4619                 case CTLENDARI:
4620                         str = "))";
4621                         goto dostr;
4622 #endif
4623                 case CTLQUOTEMARK:
4624                         quoted ^= 1;
4625                         c = '"';
4626                         break;
4627                 case '=':
4628                         if (subtype == 0)
4629                                 break;
4630                         if ((subtype & VSTYPE) != VSNORMAL)
4631                                 quoted <<= 1;
4632                         str = vstype[subtype & VSTYPE];
4633                         if (subtype & VSNUL)
4634                                 c = ':';
4635                         else
4636                                 goto checkstr;
4637                         break;
4638                 case '\'':
4639                 case '\\':
4640                 case '"':
4641                 case '$':
4642                         /* These can only happen inside quotes */
4643                         cc[0] = c;
4644                         str = cc;
4645 //FIXME:
4646 // $ true $$ &
4647 // $ <cr>
4648 // [1]+  Done    true ${\$}   <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4649                         c = '\\';
4650                         break;
4651                 default:
4652                         break;
4653                 }
4654                 USTPUTC(c, nextc);
4655  checkstr:
4656                 if (!str)
4657                         continue;
4658  dostr:
4659                 while ((c = *str++) != '\0') {
4660                         USTPUTC(c, nextc);
4661                 }
4662         } /* while *p++ not NUL */
4663
4664         if (quoted & 1) {
4665                 USTPUTC('"', nextc);
4666         }
4667         *nextc = 0;
4668         cmdnextc = nextc;
4669 }
4670
4671 /* cmdtxt() and cmdlist() call each other */
4672 static void cmdtxt(union node *n);
4673
4674 static void
4675 cmdlist(union node *np, int sep)
4676 {
4677         for (; np; np = np->narg.next) {
4678                 if (!sep)
4679                         cmdputs(" ");
4680                 cmdtxt(np);
4681                 if (sep && np->narg.next)
4682                         cmdputs(" ");
4683         }
4684 }
4685
4686 static void
4687 cmdtxt(union node *n)
4688 {
4689         union node *np;
4690         struct nodelist *lp;
4691         const char *p;
4692
4693         if (!n)
4694                 return;
4695         switch (n->type) {
4696         default:
4697 #if DEBUG
4698                 abort();
4699 #endif
4700         case NPIPE:
4701                 lp = n->npipe.cmdlist;
4702                 for (;;) {
4703                         cmdtxt(lp->n);
4704                         lp = lp->next;
4705                         if (!lp)
4706                                 break;
4707                         cmdputs(" | ");
4708                 }
4709                 break;
4710         case NSEMI:
4711                 p = "; ";
4712                 goto binop;
4713         case NAND:
4714                 p = " && ";
4715                 goto binop;
4716         case NOR:
4717                 p = " || ";
4718  binop:
4719                 cmdtxt(n->nbinary.ch1);
4720                 cmdputs(p);
4721                 n = n->nbinary.ch2;
4722                 goto donode;
4723         case NREDIR:
4724         case NBACKGND:
4725                 n = n->nredir.n;
4726                 goto donode;
4727         case NNOT:
4728                 cmdputs("!");
4729                 n = n->nnot.com;
4730  donode:
4731                 cmdtxt(n);
4732                 break;
4733         case NIF:
4734                 cmdputs("if ");
4735                 cmdtxt(n->nif.test);
4736                 cmdputs("; then ");
4737                 if (n->nif.elsepart) {
4738                         cmdtxt(n->nif.ifpart);
4739                         cmdputs("; else ");
4740                         n = n->nif.elsepart;
4741                 } else {
4742                         n = n->nif.ifpart;
4743                 }
4744                 p = "; fi";
4745                 goto dotail;
4746         case NSUBSHELL:
4747                 cmdputs("(");
4748                 n = n->nredir.n;
4749                 p = ")";
4750                 goto dotail;
4751         case NWHILE:
4752                 p = "while ";
4753                 goto until;
4754         case NUNTIL:
4755                 p = "until ";
4756  until:
4757                 cmdputs(p);
4758                 cmdtxt(n->nbinary.ch1);
4759                 n = n->nbinary.ch2;
4760                 p = "; done";
4761  dodo:
4762                 cmdputs("; do ");
4763  dotail:
4764                 cmdtxt(n);
4765                 goto dotail2;
4766         case NFOR:
4767                 cmdputs("for ");
4768                 cmdputs(n->nfor.var);
4769                 cmdputs(" in ");
4770                 cmdlist(n->nfor.args, 1);
4771                 n = n->nfor.body;
4772                 p = "; done";
4773                 goto dodo;
4774         case NDEFUN:
4775                 cmdputs(n->narg.text);
4776                 p = "() { ... }";
4777                 goto dotail2;
4778         case NCMD:
4779                 cmdlist(n->ncmd.args, 1);
4780                 cmdlist(n->ncmd.redirect, 0);
4781                 break;
4782         case NARG:
4783                 p = n->narg.text;
4784  dotail2:
4785                 cmdputs(p);
4786                 break;
4787         case NHERE:
4788         case NXHERE:
4789                 p = "<<...";
4790                 goto dotail2;
4791         case NCASE:
4792                 cmdputs("case ");
4793                 cmdputs(n->ncase.expr->narg.text);
4794                 cmdputs(" in ");
4795                 for (np = n->ncase.cases; np; np = np->nclist.next) {
4796                         cmdtxt(np->nclist.pattern);
4797                         cmdputs(") ");
4798                         cmdtxt(np->nclist.body);
4799                         cmdputs(";; ");
4800                 }
4801                 p = "esac";
4802                 goto dotail2;
4803         case NTO:
4804                 p = ">";
4805                 goto redir;
4806         case NCLOBBER:
4807                 p = ">|";
4808                 goto redir;
4809         case NAPPEND:
4810                 p = ">>";
4811                 goto redir;
4812 #if BASH_REDIR_OUTPUT
4813         case NTO2:
4814 #endif
4815         case NTOFD:
4816                 p = ">&";
4817                 goto redir;
4818         case NFROM:
4819                 p = "<";
4820                 goto redir;
4821         case NFROMFD:
4822                 p = "<&";
4823                 goto redir;
4824         case NFROMTO:
4825                 p = "<>";
4826  redir:
4827                 cmdputs(utoa(n->nfile.fd));
4828                 cmdputs(p);
4829                 if (n->type == NTOFD || n->type == NFROMFD) {
4830                         if (n->ndup.dupfd >= 0)
4831                                 cmdputs(utoa(n->ndup.dupfd));
4832                         else
4833                                 cmdputs("-");
4834                         break;
4835                 }
4836                 n = n->nfile.fname;
4837                 goto donode;
4838         }
4839 }
4840
4841 static char *
4842 commandtext(union node *n)
4843 {
4844         char *name;
4845
4846         STARTSTACKSTR(cmdnextc);
4847         cmdtxt(n);
4848         name = stackblock();
4849         TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4850         return ckstrdup(name);
4851 }
4852 #endif /* JOBS */
4853
4854 /*
4855  * Fork off a subshell.  If we are doing job control, give the subshell its
4856  * own process group.  Jp is a job structure that the job is to be added to.
4857  * N is the command that will be evaluated by the child.  Both jp and n may
4858  * be NULL.  The mode parameter can be one of the following:
4859  *      FORK_FG - Fork off a foreground process.
4860  *      FORK_BG - Fork off a background process.
4861  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
4862  *                   process group even if job control is on.
4863  *
4864  * When job control is turned off, background processes have their standard
4865  * input redirected to /dev/null (except for the second and later processes
4866  * in a pipeline).
4867  *
4868  * Called with interrupts off.
4869  */
4870 /*
4871  * Clear traps on a fork.
4872  */
4873 static void
4874 clear_traps(void)
4875 {
4876         char **tp;
4877
4878         INT_OFF;
4879         for (tp = trap; tp < &trap[NSIG]; tp++) {
4880                 if (*tp && **tp) {      /* trap not NULL or "" (SIG_IGN) */
4881                         if (trap_ptr == trap)
4882                                 free(*tp);
4883                         /* else: it "belongs" to trap_ptr vector, don't free */
4884                         *tp = NULL;
4885                         if ((tp - trap) != 0)
4886                                 setsignal(tp - trap);
4887                 }
4888         }
4889         may_have_traps = 0;
4890         INT_ON;
4891 }
4892
4893 /* Lives far away from here, needed for forkchild */
4894 static void closescript(void);
4895
4896 /* Called after fork(), in child */
4897 /* jp and n are NULL when called by openhere() for heredoc support */
4898 static NOINLINE void
4899 forkchild(struct job *jp, union node *n, int mode)
4900 {
4901         int oldlvl;
4902
4903         TRACE(("Child shell %d\n", getpid()));
4904         oldlvl = shlvl;
4905         shlvl++;
4906
4907         /* man bash: "Non-builtin commands run by bash have signal handlers
4908          * set to the values inherited by the shell from its parent".
4909          * Do we do it correctly? */
4910
4911         closescript();
4912
4913         if (mode == FORK_NOJOB          /* is it `xxx` ? */
4914          && n && n->type == NCMD        /* is it single cmd? */
4915         /* && n->ncmd.args->type == NARG - always true? */
4916          && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4917          && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4918         /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4919         ) {
4920                 TRACE(("Trap hack\n"));
4921                 /* Awful hack for `trap` or $(trap).
4922                  *
4923                  * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4924                  * contains an example where "trap" is executed in a subshell:
4925                  *
4926                  * save_traps=$(trap)
4927                  * ...
4928                  * eval "$save_traps"
4929                  *
4930                  * Standard does not say that "trap" in subshell shall print
4931                  * parent shell's traps. It only says that its output
4932                  * must have suitable form, but then, in the above example
4933                  * (which is not supposed to be normative), it implies that.
4934                  *
4935                  * bash (and probably other shell) does implement it
4936                  * (traps are reset to defaults, but "trap" still shows them),
4937                  * but as a result, "trap" logic is hopelessly messed up:
4938                  *
4939                  * # trap
4940                  * trap -- 'echo Ho' SIGWINCH  <--- we have a handler
4941                  * # (trap)        <--- trap is in subshell - no output (correct, traps are reset)
4942                  * # true | trap   <--- trap is in subshell - no output (ditto)
4943                  * # echo `true | trap`    <--- in subshell - output (but traps are reset!)
4944                  * trap -- 'echo Ho' SIGWINCH
4945                  * # echo `(trap)`         <--- in subshell in subshell - output
4946                  * trap -- 'echo Ho' SIGWINCH
4947                  * # echo `true | (trap)`  <--- in subshell in subshell in subshell - output!
4948                  * trap -- 'echo Ho' SIGWINCH
4949                  *
4950                  * The rules when to forget and when to not forget traps
4951                  * get really complex and nonsensical.
4952                  *
4953                  * Our solution: ONLY bare $(trap) or `trap` is special.
4954                  */
4955                 /* Save trap handler strings for trap builtin to print */
4956                 trap_ptr = xmemdup(trap, sizeof(trap));
4957                 /* Fall through into clearing traps */
4958         }
4959         clear_traps();
4960 #if JOBS
4961         /* do job control only in root shell */
4962         doing_jobctl = 0;
4963         if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4964                 pid_t pgrp;
4965
4966                 if (jp->nprocs == 0)
4967                         pgrp = getpid();
4968                 else
4969                         pgrp = jp->ps[0].ps_pid;
4970                 /* this can fail because we are doing it in the parent also */
4971                 setpgid(0, pgrp);
4972                 if (mode == FORK_FG)
4973                         xtcsetpgrp(ttyfd, pgrp);
4974                 setsignal(SIGTSTP);
4975                 setsignal(SIGTTOU);
4976         } else
4977 #endif
4978         if (mode == FORK_BG) {
4979                 /* man bash: "When job control is not in effect,
4980                  * asynchronous commands ignore SIGINT and SIGQUIT" */
4981                 ignoresig(SIGINT);
4982                 ignoresig(SIGQUIT);
4983                 if (jp->nprocs == 0) {
4984                         close(0);
4985                         if (open(bb_dev_null, O_RDONLY) != 0)
4986                                 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4987                 }
4988         }
4989         if (oldlvl == 0) {
4990                 if (iflag) { /* why if iflag only? */
4991                         setsignal(SIGINT);
4992                         setsignal(SIGTERM);
4993                 }
4994                 /* man bash:
4995                  * "In all cases, bash ignores SIGQUIT. Non-builtin
4996                  * commands run by bash have signal handlers
4997                  * set to the values inherited by the shell
4998                  * from its parent".
4999                  * Take care of the second rule: */
5000                 setsignal(SIGQUIT);
5001         }
5002 #if JOBS
5003         if (n && n->type == NCMD
5004          && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5005         ) {
5006                 TRACE(("Job hack\n"));
5007                 /* "jobs": we do not want to clear job list for it,
5008                  * instead we remove only _its_ own_ job from job list.
5009                  * This makes "jobs .... | cat" more useful.
5010                  */
5011                 freejob(curjob);
5012                 return;
5013         }
5014 #endif
5015         for (jp = curjob; jp; jp = jp->prev_job)
5016                 freejob(jp);
5017         jobless = 0;
5018 }
5019
5020 /* Called after fork(), in parent */
5021 #if !JOBS
5022 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5023 #endif
5024 static void
5025 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5026 {
5027         TRACE(("In parent shell: child = %d\n", pid));
5028         if (!jp) {
5029                 /* jp is NULL when called by openhere() for heredoc support */
5030                 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5031                         continue;
5032                 jobless++;
5033                 return;
5034         }
5035 #if JOBS
5036         if (mode != FORK_NOJOB && jp->jobctl) {
5037                 int pgrp;
5038
5039                 if (jp->nprocs == 0)
5040                         pgrp = pid;
5041                 else
5042                         pgrp = jp->ps[0].ps_pid;
5043                 /* This can fail because we are doing it in the child also */
5044                 setpgid(pid, pgrp);
5045         }
5046 #endif
5047         if (mode == FORK_BG) {
5048                 backgndpid = pid;               /* set $! */
5049                 set_curjob(jp, CUR_RUNNING);
5050         }
5051         if (jp) {
5052                 struct procstat *ps = &jp->ps[jp->nprocs++];
5053                 ps->ps_pid = pid;
5054                 ps->ps_status = -1;
5055                 ps->ps_cmd = nullstr;
5056 #if JOBS
5057                 if (doing_jobctl && n)
5058                         ps->ps_cmd = commandtext(n);
5059 #endif
5060         }
5061 }
5062
5063 /* jp and n are NULL when called by openhere() for heredoc support */
5064 static int
5065 forkshell(struct job *jp, union node *n, int mode)
5066 {
5067         int pid;
5068
5069         TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5070         pid = fork();
5071         if (pid < 0) {
5072                 TRACE(("Fork failed, errno=%d", errno));
5073                 if (jp)
5074                         freejob(jp);
5075                 ash_msg_and_raise_error("can't fork");
5076         }
5077         if (pid == 0) {
5078                 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5079                 forkchild(jp, n, mode);
5080         } else {
5081                 forkparent(jp, n, mode, pid);
5082         }
5083         return pid;
5084 }
5085
5086 /*
5087  * Wait for job to finish.
5088  *
5089  * Under job control we have the problem that while a child process
5090  * is running interrupts generated by the user are sent to the child
5091  * but not to the shell.  This means that an infinite loop started by
5092  * an interactive user may be hard to kill.  With job control turned off,
5093  * an interactive user may place an interactive program inside a loop.
5094  * If the interactive program catches interrupts, the user doesn't want
5095  * these interrupts to also abort the loop.  The approach we take here
5096  * is to have the shell ignore interrupt signals while waiting for a
5097  * foreground process to terminate, and then send itself an interrupt
5098  * signal if the child process was terminated by an interrupt signal.
5099  * Unfortunately, some programs want to do a bit of cleanup and then
5100  * exit on interrupt; unless these processes terminate themselves by
5101  * sending a signal to themselves (instead of calling exit) they will
5102  * confuse this approach.
5103  *
5104  * Called with interrupts off.
5105  */
5106 static int
5107 waitforjob(struct job *jp)
5108 {
5109         int st;
5110
5111         TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5112
5113         INT_OFF;
5114         while (jp->state == JOBRUNNING) {
5115                 /* In non-interactive shells, we _can_ get
5116                  * a keyboard signal here and be EINTRed,
5117                  * but we just loop back, waiting for command to complete.
5118                  *
5119                  * man bash:
5120                  * "If bash is waiting for a command to complete and receives
5121                  * a signal for which a trap has been set, the trap
5122                  * will not be executed until the command completes."
5123                  *
5124                  * Reality is that even if trap is not set, bash
5125                  * will not act on the signal until command completes.
5126                  * Try this. sleep5intoff.c:
5127                  * #include <signal.h>
5128                  * #include <unistd.h>
5129                  * int main() {
5130                  *         sigset_t set;
5131                  *         sigemptyset(&set);
5132                  *         sigaddset(&set, SIGINT);
5133                  *         sigaddset(&set, SIGQUIT);
5134                  *         sigprocmask(SIG_BLOCK, &set, NULL);
5135                  *         sleep(5);
5136                  *         return 0;
5137                  * }
5138                  * $ bash -c './sleep5intoff; echo hi'
5139                  * ^C^C^C^C <--- pressing ^C once a second
5140                  * $ _
5141                  * $ bash -c './sleep5intoff; echo hi'
5142                  * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5143                  * $ _
5144                  */
5145                 dowait(DOWAIT_BLOCK, jp);
5146         }
5147         INT_ON;
5148
5149         st = getstatus(jp);
5150 #if JOBS
5151         if (jp->jobctl) {
5152                 xtcsetpgrp(ttyfd, rootpid);
5153                 restore_tty_if_stopped_or_signaled(jp);
5154
5155                 /*
5156                  * This is truly gross.
5157                  * If we're doing job control, then we did a TIOCSPGRP which
5158                  * caused us (the shell) to no longer be in the controlling
5159                  * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
5160                  * intuit from the subprocess exit status whether a SIGINT
5161                  * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
5162                  */
5163                 if (jp->sigint) /* TODO: do the same with all signals */
5164                         raise(SIGINT); /* ... by raise(jp->sig) instead? */
5165         }
5166         if (jp->state == JOBDONE)
5167 #endif
5168                 freejob(jp);
5169         return st;
5170 }
5171
5172 /*
5173  * return 1 if there are stopped jobs, otherwise 0
5174  */
5175 static int
5176 stoppedjobs(void)
5177 {
5178         struct job *jp;
5179         int retval;
5180
5181         retval = 0;
5182         if (job_warning)
5183                 goto out;
5184         jp = curjob;
5185         if (jp && jp->state == JOBSTOPPED) {
5186                 out2str("You have stopped jobs.\n");
5187                 job_warning = 2;
5188                 retval++;
5189         }
5190  out:
5191         return retval;
5192 }
5193
5194
5195 /*
5196  * Code for dealing with input/output redirection.
5197  */
5198
5199 #undef EMPTY
5200 #undef CLOSED
5201 #define EMPTY -2                /* marks an unused slot in redirtab */
5202 #define CLOSED -1               /* marks a slot of previously-closed fd */
5203
5204 /*
5205  * Handle here documents.  Normally we fork off a process to write the
5206  * data to a pipe.  If the document is short, we can stuff the data in
5207  * the pipe without forking.
5208  */
5209 /* openhere needs this forward reference */
5210 static void expandhere(union node *arg, int fd);
5211 static int
5212 openhere(union node *redir)
5213 {
5214         int pip[2];
5215         size_t len = 0;
5216
5217         if (pipe(pip) < 0)
5218                 ash_msg_and_raise_error("pipe call failed");
5219         if (redir->type == NHERE) {
5220                 len = strlen(redir->nhere.doc->narg.text);
5221                 if (len <= PIPE_BUF) {
5222                         full_write(pip[1], redir->nhere.doc->narg.text, len);
5223                         goto out;
5224                 }
5225         }
5226         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5227                 /* child */
5228                 close(pip[0]);
5229                 ignoresig(SIGINT);  //signal(SIGINT, SIG_IGN);
5230                 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5231                 ignoresig(SIGHUP);  //signal(SIGHUP, SIG_IGN);
5232                 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5233                 signal(SIGPIPE, SIG_DFL);
5234                 if (redir->type == NHERE)
5235                         full_write(pip[1], redir->nhere.doc->narg.text, len);
5236                 else /* NXHERE */
5237                         expandhere(redir->nhere.doc, pip[1]);
5238                 _exit(EXIT_SUCCESS);
5239         }
5240  out:
5241         close(pip[1]);
5242         return pip[0];
5243 }
5244
5245 static int
5246 openredirect(union node *redir)
5247 {
5248         struct stat sb;
5249         char *fname;
5250         int f;
5251
5252         switch (redir->nfile.type) {
5253 /* Can't happen, our single caller does this itself */
5254 //      case NTOFD:
5255 //      case NFROMFD:
5256 //              return -1;
5257         case NHERE:
5258         case NXHERE:
5259                 return openhere(redir);
5260         }
5261
5262         /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5263          * allocated space. Do it only when we know it is safe.
5264          */
5265         fname = redir->nfile.expfname;
5266
5267         switch (redir->nfile.type) {
5268         default:
5269 #if DEBUG
5270                 abort();
5271 #endif
5272         case NFROM:
5273                 f = open(fname, O_RDONLY);
5274                 if (f < 0)
5275                         goto eopen;
5276                 break;
5277         case NFROMTO:
5278                 f = open(fname, O_RDWR|O_CREAT, 0666);
5279                 if (f < 0)
5280                         goto ecreate;
5281                 break;
5282         case NTO:
5283 #if BASH_REDIR_OUTPUT
5284         case NTO2:
5285 #endif
5286                 /* Take care of noclobber mode. */
5287                 if (Cflag) {
5288                         if (stat(fname, &sb) < 0) {
5289                                 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5290                                 if (f < 0)
5291                                         goto ecreate;
5292                         } else if (!S_ISREG(sb.st_mode)) {
5293                                 f = open(fname, O_WRONLY, 0666);
5294                                 if (f < 0)
5295                                         goto ecreate;
5296                                 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5297                                         close(f);
5298                                         errno = EEXIST;
5299                                         goto ecreate;
5300                                 }
5301                         } else {
5302                                 errno = EEXIST;
5303                                 goto ecreate;
5304                         }
5305                         break;
5306                 }
5307                 /* FALLTHROUGH */
5308         case NCLOBBER:
5309                 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5310                 if (f < 0)
5311                         goto ecreate;
5312                 break;
5313         case NAPPEND:
5314                 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5315                 if (f < 0)
5316                         goto ecreate;
5317                 break;
5318         }
5319
5320         return f;
5321  ecreate:
5322         ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5323  eopen:
5324         ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5325 }
5326
5327 /*
5328  * Copy a file descriptor to be >= 10. Throws exception on error.
5329  */
5330 static int
5331 savefd(int from)
5332 {
5333         int newfd;
5334         int err;
5335
5336         newfd = fcntl(from, F_DUPFD, 10);
5337         err = newfd < 0 ? errno : 0;
5338         if (err != EBADF) {
5339                 if (err)
5340                         ash_msg_and_raise_perror("%d", from);
5341                 close(from);
5342                 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5343         }
5344
5345         return newfd;
5346 }
5347 static int
5348 dup2_or_raise(int from, int to)
5349 {
5350         int newfd;
5351
5352         newfd = (from != to) ? dup2(from, to) : to;
5353         if (newfd < 0) {
5354                 /* Happens when source fd is not open: try "echo >&99" */
5355                 ash_msg_and_raise_perror("%d", from);
5356         }
5357         return newfd;
5358 }
5359 static int
5360 fcntl_F_DUPFD(int fd, int avoid_fd)
5361 {
5362         int newfd;
5363  repeat:
5364         newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5365         if (newfd < 0) {
5366                 if (errno == EBUSY)
5367                         goto repeat;
5368                 if (errno == EINTR)
5369                         goto repeat;
5370         }
5371         return newfd;
5372 }
5373 static int
5374 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5375 {
5376         int newfd;
5377  repeat:
5378         newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5379         if (newfd < 0) {
5380                 if (errno == EBUSY)
5381                         goto repeat;
5382                 if (errno == EINTR)
5383                         goto repeat;
5384                 /* fd was not open? */
5385                 if (errno == EBADF)
5386                         return fd;
5387                 ash_msg_and_raise_perror("%d", newfd);
5388         }
5389         fcntl(newfd, F_SETFD, FD_CLOEXEC);
5390         close(fd);
5391         return newfd;
5392 }
5393
5394 /* Struct def and variable are moved down to the first usage site */
5395 struct squirrel {
5396         int orig_fd;
5397         int moved_to;
5398 };
5399 struct redirtab {
5400         struct redirtab *next;
5401         int pair_count;
5402         struct squirrel two_fd[];
5403 };
5404 #define redirlist (G_var.redirlist)
5405
5406 static void
5407 add_squirrel_closed(struct redirtab *sq, int fd)
5408 {
5409         int i;
5410
5411         if (!sq)
5412                 return;
5413
5414         for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5415                 /* If we collide with an already moved fd... */
5416                 if (fd == sq->two_fd[i].orig_fd) {
5417                         /* Examples:
5418                          * "echo 3>FILE 3>&- 3>FILE"
5419                          * "echo 3>&- 3>FILE"
5420                          * No need for last redirect to insert
5421                          * another "need to close 3" indicator.
5422                          */
5423                         TRACE(("redirect_fd %d: already moved or closed\n", fd));
5424                         return;
5425                 }
5426         }
5427         TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5428         sq->two_fd[i].orig_fd = fd;
5429         sq->two_fd[i].moved_to = CLOSED;
5430 }
5431
5432 static int
5433 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5434 {
5435         int i, new_fd;
5436
5437         if (avoid_fd < 9) /* the important case here is that it can be -1 */
5438                 avoid_fd = 9;
5439
5440 #if JOBS
5441         if (fd == ttyfd) {
5442                 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5443                 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5444                 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5445                 return 1; /* "we closed fd" */
5446         }
5447 #endif
5448         /* Are we called from redirect(0)? E.g. redirect
5449          * in a forked child. No need to save fds,
5450          * we aren't going to use them anymore, ok to trash.
5451          */
5452         if (!sq)
5453                 return 0;
5454
5455         /* If this one of script's fds? */
5456         if (fd != 0) {
5457                 struct parsefile *pf = g_parsefile;
5458                 while (pf) {
5459                         /* We skip fd == 0 case because of the following:
5460                          * $ ash  # running ash interactively
5461                          * $ . ./script.sh
5462                          * and in script.sh: "exec 9>&0".
5463                          * Even though top-level pf_fd _is_ 0,
5464                          * it's still ok to use it: "read" builtin uses it,
5465                          * why should we cripple "exec" builtin?
5466                          */
5467                         if (fd == pf->pf_fd) {
5468                                 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5469                                 return 1; /* "we closed fd" */
5470                         }
5471                         pf = pf->prev;
5472                 }
5473         }
5474
5475         /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5476
5477         /* First: do we collide with some already moved fds? */
5478         for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5479                 /* If we collide with an already moved fd... */
5480                 if (fd == sq->two_fd[i].moved_to) {
5481                         new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5482                         sq->two_fd[i].moved_to = new_fd;
5483                         TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5484                         if (new_fd < 0) /* what? */
5485                                 xfunc_die();
5486                         return 0; /* "we did not close fd" */
5487                 }
5488                 if (fd == sq->two_fd[i].orig_fd) {
5489                         /* Example: echo Hello >/dev/null 1>&2 */
5490                         TRACE(("redirect_fd %d: already moved\n", fd));
5491                         return 0; /* "we did not close fd" */
5492                 }
5493         }
5494
5495         /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5496         new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5497         TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5498         if (new_fd < 0) {
5499                 if (errno != EBADF)
5500                         xfunc_die();
5501                 /* new_fd = CLOSED; - already is -1 */
5502         }
5503         sq->two_fd[i].moved_to = new_fd;
5504         sq->two_fd[i].orig_fd = fd;
5505
5506         /* if we move stderr, let "set -x" code know */
5507         if (fd == preverrout_fd)
5508                 preverrout_fd = new_fd;
5509
5510         return 0; /* "we did not close fd" */
5511 }
5512
5513 static int
5514 internally_opened_fd(int fd, struct redirtab *sq)
5515 {
5516         int i;
5517 #if JOBS
5518         if (fd == ttyfd)
5519                 return 1;
5520 #endif
5521         /* If this one of script's fds? */
5522         if (fd != 0) {
5523                 struct parsefile *pf = g_parsefile;
5524                 while (pf) {
5525                         if (fd == pf->pf_fd)
5526                                 return 1;
5527                         pf = pf->prev;
5528                 }
5529         }
5530
5531         if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5532                 if (fd == sq->two_fd[i].moved_to)
5533                         return 1;
5534         }
5535         return 0;
5536 }
5537
5538 /*
5539  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
5540  * old file descriptors are stashed away so that the redirection can be
5541  * undone by calling popredir.
5542  */
5543 /* flags passed to redirect */
5544 #define REDIR_PUSH    01        /* save previous values of file descriptors */
5545 static void
5546 redirect(union node *redir, int flags)
5547 {
5548         struct redirtab *sv;
5549         int sv_pos;
5550
5551         if (!redir)
5552                 return;
5553
5554         sv_pos = 0;
5555         sv = NULL;
5556         INT_OFF;
5557         if (flags & REDIR_PUSH)
5558                 sv = redirlist;
5559         do {
5560                 int fd;
5561                 int newfd;
5562                 int close_fd;
5563                 int closed;
5564
5565                 fd = redir->nfile.fd;
5566                 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5567                         //bb_error_msg("doing %d > %d", fd, newfd);
5568                         newfd = redir->ndup.dupfd;
5569                         close_fd = -1;
5570                 } else {
5571                         newfd = openredirect(redir); /* always >= 0 */
5572                         if (fd == newfd) {
5573                                 /* open() gave us precisely the fd we wanted.
5574                                  * This means that this fd was not busy
5575                                  * (not opened to anywhere).
5576                                  * Remember to close it on restore:
5577                                  */
5578                                 add_squirrel_closed(sv, fd);
5579                                 continue;
5580                         }
5581                         close_fd = newfd;
5582                 }
5583
5584                 if (fd == newfd)
5585                         continue;
5586
5587                 /* if "N>FILE": move newfd to fd */
5588                 /* if "N>&M": dup newfd to fd */
5589                 /* if "N>&-": close fd (newfd is -1) */
5590
5591  IF_BASH_REDIR_OUTPUT(redirect_more:)
5592
5593                 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5594                 if (newfd == -1) {
5595                         /* "N>&-" means "close me" */
5596                         if (!closed) {
5597                                 /* ^^^ optimization: saving may already
5598                                  * have closed it. If not... */
5599                                 close(fd);
5600                         }
5601                 } else {
5602                         /* if newfd is a script fd or saved fd, simulate EBADF */
5603                         if (internally_opened_fd(newfd, sv)) {
5604                                 errno = EBADF;
5605                                 ash_msg_and_raise_perror("%d", newfd);
5606                         }
5607                         dup2_or_raise(newfd, fd);
5608                         if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5609                                 close(close_fd);
5610 #if BASH_REDIR_OUTPUT
5611                         if (redir->nfile.type == NTO2 && fd == 1) {
5612                                 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5613                                 fd = 2;
5614                                 newfd = 1;
5615                                 close_fd = -1;
5616                                 goto redirect_more;
5617                         }
5618 #endif
5619                 }
5620         } while ((redir = redir->nfile.next) != NULL);
5621         INT_ON;
5622
5623 //dash:#define REDIR_SAVEFD2 03        /* set preverrout */
5624 #define REDIR_SAVEFD2 0
5625         // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5626         // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5627         // not only for calls with flags containing REDIR_SAVEFD2.
5628         // We do this unconditionally (see save_fd_on_redirect()).
5629         //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5630         //      preverrout_fd = copied_fd2;
5631 }
5632
5633 static int
5634 redirectsafe(union node *redir, int flags)
5635 {
5636         int err;
5637         volatile int saveint;
5638         struct jmploc *volatile savehandler = exception_handler;
5639         struct jmploc jmploc;
5640
5641         SAVE_INT(saveint);
5642         /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5643         err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5644         if (!err) {
5645                 exception_handler = &jmploc;
5646                 redirect(redir, flags);
5647         }
5648         exception_handler = savehandler;
5649         if (err && exception_type != EXERROR)
5650                 longjmp(exception_handler->loc, 1);
5651         RESTORE_INT(saveint);
5652         return err;
5653 }
5654
5655 static struct redirtab*
5656 pushredir(union node *redir)
5657 {
5658         struct redirtab *sv;
5659         int i;
5660
5661         if (!redir)
5662                 return redirlist;
5663
5664         i = 0;
5665         do {
5666                 i++;
5667 #if BASH_REDIR_OUTPUT
5668                 if (redir->nfile.type == NTO2)
5669                         i++;
5670 #endif
5671                 redir = redir->nfile.next;
5672         } while (redir);
5673
5674         sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5675         sv->pair_count = i;
5676         while (--i >= 0)
5677                 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5678         sv->next = redirlist;
5679         redirlist = sv;
5680         return sv->next;
5681 }
5682
5683 /*
5684  * Undo the effects of the last redirection.
5685  */
5686 static void
5687 popredir(int drop)
5688 {
5689         struct redirtab *rp;
5690         int i;
5691
5692         if (redirlist == NULL)
5693                 return;
5694         INT_OFF;
5695         rp = redirlist;
5696         for (i = 0; i < rp->pair_count; i++) {
5697                 int fd = rp->two_fd[i].orig_fd;
5698                 int copy = rp->two_fd[i].moved_to;
5699                 if (copy == CLOSED) {
5700                         if (!drop)
5701                                 close(fd);
5702                         continue;
5703                 }
5704                 if (copy != EMPTY) {
5705                         if (!drop) {
5706                                 /*close(fd);*/
5707                                 dup2_or_raise(copy, fd);
5708                         }
5709                         close(copy);
5710                 }
5711         }
5712         redirlist = rp->next;
5713         free(rp);
5714         INT_ON;
5715 }
5716
5717 static void
5718 unwindredir(struct redirtab *stop)
5719 {
5720         while (redirlist != stop)
5721                 popredir(/*drop:*/ 0);
5722 }
5723
5724
5725 /* ============ Routines to expand arguments to commands
5726  *
5727  * We have to deal with backquotes, shell variables, and file metacharacters.
5728  */
5729
5730 #if ENABLE_FEATURE_SH_MATH
5731 static arith_t
5732 ash_arith(const char *s)
5733 {
5734         arith_state_t math_state;
5735         arith_t result;
5736
5737         math_state.lookupvar = lookupvar;
5738         math_state.setvar    = setvar0;
5739         //math_state.endofname = endofname;
5740
5741         INT_OFF;
5742         result = arith(&math_state, s);
5743         if (math_state.errmsg)
5744                 ash_msg_and_raise_error(math_state.errmsg);
5745         INT_ON;
5746
5747         return result;
5748 }
5749 #endif
5750
5751 /*
5752  * expandarg flags
5753  */
5754 #define EXP_FULL        0x1     /* perform word splitting & file globbing */
5755 #define EXP_TILDE       0x2     /* do normal tilde expansion */
5756 #define EXP_VARTILDE    0x4     /* expand tildes in an assignment */
5757 #define EXP_REDIR       0x8     /* file glob for a redirection (1 match only) */
5758 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5759  * POSIX says for this case:
5760  *  Pathname expansion shall not be performed on the word by a
5761  *  non-interactive shell; an interactive shell may perform it, but shall
5762  *  do so only when the expansion would result in one word.
5763  * Currently, our code complies to the above rule by never globbing
5764  * redirection filenames.
5765  * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5766  * (this means that on a typical Linux distro, bash almost always
5767  * performs globbing, and thus diverges from what we do).
5768  */
5769 #define EXP_CASE        0x10    /* keeps quotes around for CASE pattern */
5770 #define EXP_QPAT        0x20    /* pattern in quoted parameter expansion */
5771 #define EXP_VARTILDE2   0x40    /* expand tildes after colons only */
5772 #define EXP_WORD        0x80    /* expand word in parameter expansion */
5773 #define EXP_QUOTED      0x100   /* expand word in double quotes */
5774 /*
5775  * rmescape() flags
5776  */
5777 #define RMESCAPE_ALLOC  0x1     /* Allocate a new string */
5778 #define RMESCAPE_GLOB   0x2     /* Add backslashes for glob */
5779 #define RMESCAPE_GROW   0x8     /* Grow strings instead of stalloc */
5780 #define RMESCAPE_HEAP   0x10    /* Malloc strings instead of stalloc */
5781 #define RMESCAPE_SLASH  0x20    /* Stop globbing after slash */
5782
5783 /* Add CTLESC when necessary. */
5784 #define QUOTES_ESC     (EXP_FULL | EXP_CASE | EXP_QPAT)
5785 /* Do not skip NUL characters. */
5786 #define QUOTES_KEEPNUL EXP_TILDE
5787
5788 /*
5789  * Structure specifying which parts of the string should be searched
5790  * for IFS characters.
5791  */
5792 struct ifsregion {
5793         struct ifsregion *next; /* next region in list */
5794         int begoff;             /* offset of start of region */
5795         int endoff;             /* offset of end of region */
5796         int nulonly;            /* search for nul bytes only */
5797 };
5798
5799 struct arglist {
5800         struct strlist *list;
5801         struct strlist **lastp;
5802 };
5803
5804 /* output of current string */
5805 static char *expdest;
5806 /* list of back quote expressions */
5807 static struct nodelist *argbackq;
5808 /* first struct in list of ifs regions */
5809 static struct ifsregion ifsfirst;
5810 /* last struct in list */
5811 static struct ifsregion *ifslastp;
5812 /* holds expanded arg list */
5813 static struct arglist exparg;
5814
5815 /*
5816  * Our own itoa().
5817  * cvtnum() is used even if math support is off (to prepare $? values and such).
5818  */
5819 static int
5820 cvtnum(arith_t num)
5821 {
5822         int len;
5823
5824         /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5825         len = sizeof(arith_t) * 3;
5826         /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5827         if (sizeof(arith_t) < 4) len += 2;
5828
5829         expdest = makestrspace(len, expdest);
5830         len = fmtstr(expdest, len, ARITH_FMT, num);
5831         STADJUST(len, expdest);
5832         return len;
5833 }
5834
5835 /*
5836  * Break the argument string into pieces based upon IFS and add the
5837  * strings to the argument list.  The regions of the string to be
5838  * searched for IFS characters have been stored by recordregion.
5839  */
5840 static void
5841 ifsbreakup(char *string, struct arglist *arglist)
5842 {
5843         struct ifsregion *ifsp;
5844         struct strlist *sp;
5845         char *start;
5846         char *p;
5847         char *q;
5848         const char *ifs, *realifs;
5849         int ifsspc;
5850         int nulonly;
5851
5852         start = string;
5853         if (ifslastp != NULL) {
5854                 ifsspc = 0;
5855                 nulonly = 0;
5856                 realifs = ifsset() ? ifsval() : defifs;
5857                 ifsp = &ifsfirst;
5858                 do {
5859                         p = string + ifsp->begoff;
5860                         nulonly = ifsp->nulonly;
5861                         ifs = nulonly ? nullstr : realifs;
5862                         ifsspc = 0;
5863                         while (p < string + ifsp->endoff) {
5864                                 q = p;
5865                                 if ((unsigned char)*p == CTLESC)
5866                                         p++;
5867                                 if (!strchr(ifs, *p)) {
5868                                         p++;
5869                                         continue;
5870                                 }
5871                                 if (!nulonly)
5872                                         ifsspc = (strchr(defifs, *p) != NULL);
5873                                 /* Ignore IFS whitespace at start */
5874                                 if (q == start && ifsspc) {
5875                                         p++;
5876                                         start = p;
5877                                         continue;
5878                                 }
5879                                 *q = '\0';
5880                                 sp = stzalloc(sizeof(*sp));
5881                                 sp->text = start;
5882                                 *arglist->lastp = sp;
5883                                 arglist->lastp = &sp->next;
5884                                 p++;
5885                                 if (!nulonly) {
5886                                         for (;;) {
5887                                                 if (p >= string + ifsp->endoff) {
5888                                                         break;
5889                                                 }
5890                                                 q = p;
5891                                                 if ((unsigned char)*p == CTLESC)
5892                                                         p++;
5893                                                 if (strchr(ifs, *p) == NULL) {
5894                                                         p = q;
5895                                                         break;
5896                                                 }
5897                                                 if (strchr(defifs, *p) == NULL) {
5898                                                         if (ifsspc) {
5899                                                                 p++;
5900                                                                 ifsspc = 0;
5901                                                         } else {
5902                                                                 p = q;
5903                                                                 break;
5904                                                         }
5905                                                 } else
5906                                                         p++;
5907                                         }
5908                                 }
5909                                 start = p;
5910                         } /* while */
5911                         ifsp = ifsp->next;
5912                 } while (ifsp != NULL);
5913                 if (nulonly)
5914                         goto add;
5915         }
5916
5917         if (!*start)
5918                 return;
5919
5920  add:
5921         sp = stzalloc(sizeof(*sp));
5922         sp->text = start;
5923         *arglist->lastp = sp;
5924         arglist->lastp = &sp->next;
5925 }
5926
5927 static void
5928 ifsfree(void)
5929 {
5930         struct ifsregion *p = ifsfirst.next;
5931
5932         if (!p)
5933                 goto out;
5934
5935         INT_OFF;
5936         do {
5937                 struct ifsregion *ifsp;
5938                 ifsp = p->next;
5939                 free(p);
5940                 p = ifsp;
5941         } while (p);
5942         ifsfirst.next = NULL;
5943         INT_ON;
5944  out:
5945         ifslastp = NULL;
5946 }
5947
5948 static size_t
5949 esclen(const char *start, const char *p)
5950 {
5951         size_t esc = 0;
5952
5953         while (p > start && (unsigned char)*--p == CTLESC) {
5954                 esc++;
5955         }
5956         return esc;
5957 }
5958
5959 /*
5960  * Remove any CTLESC characters from a string.
5961  */
5962 static char *
5963 rmescapes(char *str, int flag)
5964 {
5965         static const char qchars[] ALIGN1 = {
5966                 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5967
5968         char *p, *q, *r;
5969         unsigned inquotes;
5970         unsigned protect_against_glob;
5971         unsigned globbing;
5972         IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5973
5974         p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5975         if (!p)
5976                 return str;
5977
5978         q = p;
5979         r = str;
5980         if (flag & RMESCAPE_ALLOC) {
5981                 size_t len = p - str;
5982                 size_t fulllen = len + strlen(p) + 1;
5983
5984                 if (flag & RMESCAPE_GROW) {
5985                         int strloc = str - (char *)stackblock();
5986                         r = makestrspace(fulllen, expdest);
5987                         /* p and str may be invalidated by makestrspace */
5988                         str = (char *)stackblock() + strloc;
5989                         p = str + len;
5990                 } else if (flag & RMESCAPE_HEAP) {
5991                         r = ckmalloc(fulllen);
5992                 } else {
5993                         r = stalloc(fulllen);
5994                 }
5995                 q = r;
5996                 if (len > 0) {
5997                         q = (char *)mempcpy(q, str, len);
5998                 }
5999         }
6000
6001         inquotes = 0;
6002         globbing = flag & RMESCAPE_GLOB;
6003         protect_against_glob = globbing;
6004         while (*p) {
6005                 if ((unsigned char)*p == CTLQUOTEMARK) {
6006 // Note: both inquotes and protect_against_glob only affect whether
6007 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6008                         inquotes = ~inquotes;
6009                         p++;
6010                         protect_against_glob = globbing;
6011                         continue;
6012                 }
6013                 if ((unsigned char)*p == CTLESC) {
6014                         p++;
6015 #if DEBUG
6016                         if (*p == '\0')
6017                                 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6018 #endif
6019                         if (protect_against_glob) {
6020                                 /*
6021                                  * We used to trust glob() and fnmatch() to eat
6022                                  * superfluous escapes (\z where z has no
6023                                  * special meaning anyway). But this causes
6024                                  * bugs such as string of one greek letter rho
6025                                  * (unicode-encoded as two bytes "cf,81")
6026                                  * getting encoded as "cf,CTLESC,81"
6027                                  * and here, converted to "cf,\,81" -
6028                                  * which does not go well with some flavors
6029                                  * of fnmatch() in unicode locales
6030                                  * (for example, glibc <= 2.22).
6031                                  *
6032                                  * Lets add "\" only on the chars which need it.
6033                                  * Testcases for less obvious chars are shown.
6034                                  */
6035                                 if (*p == '*'
6036                                  || *p == '?'
6037                                  || *p == '['
6038                                  || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6039                                  || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6040                                  || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6041                                  || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6042                                 /* Some libc support [^negate], that's why "^" also needs love */
6043                                  || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6044                                 ) {
6045                                         *q++ = '\\';
6046                                 }
6047                         }
6048                 } else if (*p == '\\' && !inquotes) {
6049                         /* naked back slash */
6050                         protect_against_glob = 0;
6051                         goto copy;
6052                 }
6053 #if BASH_PATTERN_SUBST
6054                 else if (*p == '/' && slash) {
6055                         /* stop handling globbing and mark location of slash */
6056                         globbing = slash = 0;
6057                         *p = CTLESC;
6058                 }
6059 #endif
6060                 protect_against_glob = globbing;
6061  copy:
6062                 *q++ = *p++;
6063         }
6064         *q = '\0';
6065         if (flag & RMESCAPE_GROW) {
6066                 expdest = r;
6067                 STADJUST(q - r + 1, expdest);
6068         }
6069         return r;
6070 }
6071 #define pmatch(a, b) !fnmatch((a), (b), 0)
6072
6073 /*
6074  * Prepare a pattern for a expmeta (internal glob(3)) call.
6075  *
6076  * Returns an stalloced string.
6077  */
6078 static char *
6079 preglob(const char *pattern, int flag)
6080 {
6081         return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6082 }
6083
6084 /*
6085  * Put a string on the stack.
6086  */
6087 static void
6088 memtodest(const char *p, size_t len, int syntax, int quotes)
6089 {
6090         char *q;
6091
6092         if (!len)
6093                 return;
6094
6095         q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6096
6097         do {
6098                 unsigned char c = *p++;
6099                 if (c) {
6100                         if (quotes & QUOTES_ESC) {
6101                                 int n = SIT(c, syntax);
6102                                 if (n == CCTL
6103                                  || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6104                                      && n == CBACK
6105                                     )
6106                                 ) {
6107                                         USTPUTC(CTLESC, q);
6108                                 }
6109                         }
6110                 } else if (!(quotes & QUOTES_KEEPNUL))
6111                         continue;
6112                 USTPUTC(c, q);
6113         } while (--len);
6114
6115         expdest = q;
6116 }
6117
6118 static size_t
6119 strtodest(const char *p, int syntax, int quotes)
6120 {
6121         size_t len = strlen(p);
6122         memtodest(p, len, syntax, quotes);
6123         return len;
6124 }
6125
6126 /*
6127  * Record the fact that we have to scan this region of the
6128  * string for IFS characters.
6129  */
6130 static void
6131 recordregion(int start, int end, int nulonly)
6132 {
6133         struct ifsregion *ifsp;
6134
6135         if (ifslastp == NULL) {
6136                 ifsp = &ifsfirst;
6137         } else {
6138                 INT_OFF;
6139                 ifsp = ckzalloc(sizeof(*ifsp));
6140                 /*ifsp->next = NULL; - ckzalloc did it */
6141                 ifslastp->next = ifsp;
6142                 INT_ON;
6143         }
6144         ifslastp = ifsp;
6145         ifslastp->begoff = start;
6146         ifslastp->endoff = end;
6147         ifslastp->nulonly = nulonly;
6148 }
6149
6150 static void
6151 removerecordregions(int endoff)
6152 {
6153         if (ifslastp == NULL)
6154                 return;
6155
6156         if (ifsfirst.endoff > endoff) {
6157                 while (ifsfirst.next) {
6158                         struct ifsregion *ifsp;
6159                         INT_OFF;
6160                         ifsp = ifsfirst.next->next;
6161                         free(ifsfirst.next);
6162                         ifsfirst.next = ifsp;
6163                         INT_ON;
6164                 }
6165                 if (ifsfirst.begoff > endoff) {
6166                         ifslastp = NULL;
6167                 } else {
6168                         ifslastp = &ifsfirst;
6169                         ifsfirst.endoff = endoff;
6170                 }
6171                 return;
6172         }
6173
6174         ifslastp = &ifsfirst;
6175         while (ifslastp->next && ifslastp->next->begoff < endoff)
6176                 ifslastp = ifslastp->next;
6177         while (ifslastp->next) {
6178                 struct ifsregion *ifsp;
6179                 INT_OFF;
6180                 ifsp = ifslastp->next->next;
6181                 free(ifslastp->next);
6182                 ifslastp->next = ifsp;
6183                 INT_ON;
6184         }
6185         if (ifslastp->endoff > endoff)
6186                 ifslastp->endoff = endoff;
6187 }
6188
6189 static char *
6190 exptilde(char *startp, char *p, int flags)
6191 {
6192         unsigned char c;
6193         char *name;
6194         struct passwd *pw;
6195         const char *home;
6196         int quotes = flags & QUOTES_ESC;
6197
6198         name = p + 1;
6199
6200         while ((c = *++p) != '\0') {
6201                 switch (c) {
6202                 case CTLESC:
6203                         return startp;
6204                 case CTLQUOTEMARK:
6205                         return startp;
6206                 case ':':
6207                         if (flags & EXP_VARTILDE)
6208                                 goto done;
6209                         break;
6210                 case '/':
6211                 case CTLENDVAR:
6212                         goto done;
6213                 }
6214         }
6215  done:
6216         *p = '\0';
6217         if (*name == '\0') {
6218                 home = lookupvar("HOME");
6219         } else {
6220                 pw = getpwnam(name);
6221                 if (pw == NULL)
6222                         goto lose;
6223                 home = pw->pw_dir;
6224         }
6225         if (!home || !*home)
6226                 goto lose;
6227         *p = c;
6228         strtodest(home, SQSYNTAX, quotes);
6229         return p;
6230  lose:
6231         *p = c;
6232         return startp;
6233 }
6234
6235 /*
6236  * Execute a command inside back quotes.  If it's a builtin command, we
6237  * want to save its output in a block obtained from malloc.  Otherwise
6238  * we fork off a subprocess and get the output of the command via a pipe.
6239  * Should be called with interrupts off.
6240  */
6241 struct backcmd {                /* result of evalbackcmd */
6242         int fd;                 /* file descriptor to read from */
6243         int nleft;              /* number of chars in buffer */
6244         char *buf;              /* buffer */
6245         struct job *jp;         /* job structure for command */
6246 };
6247
6248 /* These forward decls are needed to use "eval" code for backticks handling: */
6249 /* flags in argument to evaltree */
6250 #define EV_EXIT    01           /* exit after evaluating tree */
6251 #define EV_TESTED  02           /* exit status is checked; ignore -e flag */
6252 static int evaltree(union node *, int);
6253
6254 /* An evaltree() which is known to never return.
6255  * Used to use an alias:
6256  * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6257  * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6258  */
6259 static ALWAYS_INLINE NORETURN void
6260 evaltreenr(union node *n, int flags)
6261 {
6262         evaltree(n, flags);
6263         bb_unreachable(abort());
6264         /* NOTREACHED */
6265 }
6266
6267 static void FAST_FUNC
6268 evalbackcmd(union node *n, struct backcmd *result)
6269 {
6270         int pip[2];
6271         struct job *jp;
6272
6273         result->fd = -1;
6274         result->buf = NULL;
6275         result->nleft = 0;
6276         result->jp = NULL;
6277         if (n == NULL) {
6278                 goto out;
6279         }
6280
6281         if (pipe(pip) < 0)
6282                 ash_msg_and_raise_error("pipe call failed");
6283         jp = makejob(/*n,*/ 1);
6284         if (forkshell(jp, n, FORK_NOJOB) == 0) {
6285                 /* child */
6286                 FORCE_INT_ON;
6287                 close(pip[0]);
6288                 if (pip[1] != 1) {
6289                         /*close(1);*/
6290                         dup2_or_raise(pip[1], 1);
6291                         close(pip[1]);
6292                 }
6293 /* TODO: eflag clearing makes the following not abort:
6294  *  ash -c 'set -e; z=$(false;echo foo); echo $z'
6295  * which is what bash does (unless it is in POSIX mode).
6296  * dash deleted "eflag = 0" line in the commit
6297  *  Date: Mon, 28 Jun 2010 17:11:58 +1000
6298  *  [EVAL] Don't clear eflag in evalbackcmd
6299  * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6300  */
6301                 eflag = 0;
6302                 ifsfree();
6303                 evaltreenr(n, EV_EXIT);
6304                 /* NOTREACHED */
6305         }
6306         /* parent */
6307         close(pip[1]);
6308         result->fd = pip[0];
6309         result->jp = jp;
6310
6311  out:
6312         TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6313                 result->fd, result->buf, result->nleft, result->jp));
6314 }
6315
6316 /*
6317  * Expand stuff in backwards quotes.
6318  */
6319 static void
6320 expbackq(union node *cmd, int flag)
6321 {
6322         struct backcmd in;
6323         int i;
6324         char buf[128];
6325         char *p;
6326         char *dest;
6327         int startloc;
6328         int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6329         struct stackmark smark;
6330
6331         INT_OFF;
6332         startloc = expdest - (char *)stackblock();
6333         pushstackmark(&smark, startloc);
6334         evalbackcmd(cmd, &in);
6335         popstackmark(&smark);
6336
6337         p = in.buf;
6338         i = in.nleft;
6339         if (i == 0)
6340                 goto read;
6341         for (;;) {
6342                 memtodest(p, i, syntax, flag & QUOTES_ESC);
6343  read:
6344                 if (in.fd < 0)
6345                         break;
6346                 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6347                 TRACE(("expbackq: read returns %d\n", i));
6348                 if (i <= 0)
6349                         break;
6350                 p = buf;
6351         }
6352
6353         free(in.buf);
6354         if (in.fd >= 0) {
6355                 close(in.fd);
6356                 back_exitstatus = waitforjob(in.jp);
6357         }
6358         INT_ON;
6359
6360         /* Eat all trailing newlines */
6361         dest = expdest;
6362         for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6363                 STUNPUTC(dest);
6364         expdest = dest;
6365
6366         if (!(flag & EXP_QUOTED))
6367                 recordregion(startloc, dest - (char *)stackblock(), 0);
6368         TRACE(("evalbackq: size:%d:'%.*s'\n",
6369                 (int)((dest - (char *)stackblock()) - startloc),
6370                 (int)((dest - (char *)stackblock()) - startloc),
6371                 stackblock() + startloc));
6372 }
6373
6374 #if ENABLE_FEATURE_SH_MATH
6375 /*
6376  * Expand arithmetic expression.  Backup to start of expression,
6377  * evaluate, place result in (backed up) result, adjust string position.
6378  */
6379 static void
6380 expari(int flag)
6381 {
6382         char *p, *start;
6383         int begoff;
6384         int len;
6385
6386         /* ifsfree(); */
6387
6388         /*
6389          * This routine is slightly over-complicated for
6390          * efficiency.  Next we scan backwards looking for the
6391          * start of arithmetic.
6392          */
6393         start = stackblock();
6394         p = expdest - 1;
6395         *p = '\0';
6396         p--;
6397         while (1) {
6398                 int esc;
6399
6400                 while ((unsigned char)*p != CTLARI) {
6401                         p--;
6402 #if DEBUG
6403                         if (p < start) {
6404                                 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6405                         }
6406 #endif
6407                 }
6408
6409                 esc = esclen(start, p);
6410                 if (!(esc % 2)) {
6411                         break;
6412                 }
6413
6414                 p -= esc + 1;
6415         }
6416
6417         begoff = p - start;
6418
6419         removerecordregions(begoff);
6420
6421         expdest = p;
6422
6423         if (flag & QUOTES_ESC)
6424                 rmescapes(p + 1, 0);
6425
6426         len = cvtnum(ash_arith(p + 1));
6427
6428         if (!(flag & EXP_QUOTED))
6429                 recordregion(begoff, begoff + len, 0);
6430 }
6431 #endif
6432
6433 /* argstr needs it */
6434 static char *evalvar(char *p, int flags);
6435
6436 /*
6437  * Perform variable and command substitution.  If EXP_FULL is set, output CTLESC
6438  * characters to allow for further processing.  Otherwise treat
6439  * $@ like $* since no splitting will be performed.
6440  */
6441 static void
6442 argstr(char *p, int flags)
6443 {
6444         static const char spclchars[] ALIGN1 = {
6445                 '=',
6446                 ':',
6447                 CTLQUOTEMARK,
6448                 CTLENDVAR,
6449                 CTLESC,
6450                 CTLVAR,
6451                 CTLBACKQ,
6452 #if ENABLE_FEATURE_SH_MATH
6453                 CTLENDARI,
6454 #endif
6455                 '\0'
6456         };
6457         const char *reject = spclchars;
6458         int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6459         int inquotes;
6460         size_t length;
6461         int startloc;
6462
6463         if (!(flags & EXP_VARTILDE)) {
6464                 reject += 2;
6465         } else if (flags & EXP_VARTILDE2) {
6466                 reject++;
6467         }
6468         inquotes = 0;
6469         length = 0;
6470         if (flags & EXP_TILDE) {
6471                 char *q;
6472
6473                 flags &= ~EXP_TILDE;
6474  tilde:
6475                 q = p;
6476                 if (*q == '~')
6477                         p = exptilde(p, q, flags);
6478         }
6479  start:
6480         startloc = expdest - (char *)stackblock();
6481         for (;;) {
6482                 unsigned char c;
6483
6484                 length += strcspn(p + length, reject);
6485                 c = p[length];
6486                 if (c) {
6487                         if (!(c & 0x80)
6488                         IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6489                         ) {
6490                                 /* c == '=' || c == ':' || c == CTLENDARI */
6491                                 length++;
6492                         }
6493                 }
6494                 if (length > 0) {
6495                         int newloc;
6496                         expdest = stack_nputstr(p, length, expdest);
6497                         newloc = expdest - (char *)stackblock();
6498                         if (breakall && !inquotes && newloc > startloc) {
6499                                 recordregion(startloc, newloc, 0);
6500                         }
6501                         startloc = newloc;
6502                 }
6503                 p += length + 1;
6504                 length = 0;
6505
6506                 switch (c) {
6507                 case '\0':
6508                         goto breakloop;
6509                 case '=':
6510                         if (flags & EXP_VARTILDE2) {
6511                                 p--;
6512                                 continue;
6513                         }
6514                         flags |= EXP_VARTILDE2;
6515                         reject++;
6516                         /* fall through */
6517                 case ':':
6518                         /*
6519                          * sort of a hack - expand tildes in variable
6520                          * assignments (after the first '=' and after ':'s).
6521                          */
6522                         if (*--p == '~') {
6523                                 goto tilde;
6524                         }
6525                         continue;
6526                 }
6527
6528                 switch (c) {
6529                 case CTLENDVAR: /* ??? */
6530                         goto breakloop;
6531                 case CTLQUOTEMARK:
6532                         inquotes ^= EXP_QUOTED;
6533                         /* "$@" syntax adherence hack */
6534                         if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6535                                 p = evalvar(p + 1, flags | inquotes) + 1;
6536                                 goto start;
6537                         }
6538  addquote:
6539                         if (flags & QUOTES_ESC) {
6540                                 p--;
6541                                 length++;
6542                                 startloc++;
6543                         }
6544                         break;
6545                 case CTLESC:
6546                         startloc++;
6547                         length++;
6548
6549                         /*
6550                          * Quoted parameter expansion pattern: remove quote
6551                          * unless inside inner quotes or we have a literal
6552                          * backslash.
6553                          */
6554                         if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6555                             EXP_QPAT && *p != '\\')
6556                                 break;
6557
6558                         goto addquote;
6559                 case CTLVAR:
6560                         TRACE(("argstr: evalvar('%s')\n", p));
6561                         p = evalvar(p, flags | inquotes);
6562                         TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6563                         goto start;
6564                 case CTLBACKQ:
6565                         expbackq(argbackq->n, flags | inquotes);
6566                         argbackq = argbackq->next;
6567                         goto start;
6568 #if ENABLE_FEATURE_SH_MATH
6569                 case CTLENDARI:
6570                         p--;
6571                         expari(flags | inquotes);
6572                         goto start;
6573 #endif
6574                 }
6575         }
6576  breakloop: ;
6577 }
6578
6579 static char *
6580 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6581                 char *pattern, int quotes, int zero)
6582 {
6583         char *loc, *loc2;
6584         char c;
6585
6586         loc = startp;
6587         loc2 = rmesc;
6588         do {
6589                 int match;
6590                 const char *s = loc2;
6591
6592                 c = *loc2;
6593                 if (zero) {
6594                         *loc2 = '\0';
6595                         s = rmesc;
6596                 }
6597                 match = pmatch(pattern, s);
6598
6599                 *loc2 = c;
6600                 if (match)
6601                         return loc;
6602                 if (quotes && (unsigned char)*loc == CTLESC)
6603                         loc++;
6604                 loc++;
6605                 loc2++;
6606         } while (c);
6607         return NULL;
6608 }
6609
6610 static char *
6611 scanright(char *startp, char *rmesc, char *rmescend,
6612                 char *pattern, int quotes, int match_at_start)
6613 {
6614 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6615         int try2optimize = match_at_start;
6616 #endif
6617         int esc = 0;
6618         char *loc;
6619         char *loc2;
6620
6621         /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6622          * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6623          * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6624          * Logic:
6625          * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6626          * and on each iteration they go back two/one char until they reach the beginning.
6627          * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6628          */
6629         /* TODO: document in what other circumstances we are called. */
6630
6631         for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6632                 int match;
6633                 char c = *loc2;
6634                 const char *s = loc2;
6635                 if (match_at_start) {
6636                         *loc2 = '\0';
6637                         s = rmesc;
6638                 }
6639                 match = pmatch(pattern, s);
6640                 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6641                 *loc2 = c;
6642                 if (match)
6643                         return loc;
6644 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6645                 if (try2optimize) {
6646                         /* Maybe we can optimize this:
6647                          * if pattern ends with unescaped *, we can avoid checking
6648                          * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6649                          * it won't match truncated "raw_value_of_" strings too.
6650                          */
6651                         unsigned plen = strlen(pattern);
6652                         /* Does it end with "*"? */
6653                         if (plen != 0 && pattern[--plen] == '*') {
6654                                 /* "xxxx*" is not escaped */
6655                                 /* "xxx\*" is escaped */
6656                                 /* "xx\\*" is not escaped */
6657                                 /* "x\\\*" is escaped */
6658                                 int slashes = 0;
6659                                 while (plen != 0 && pattern[--plen] == '\\')
6660                                         slashes++;
6661                                 if (!(slashes & 1))
6662                                         break; /* ends with unescaped "*" */
6663                         }
6664                         try2optimize = 0;
6665                 }
6666 #endif
6667                 loc--;
6668                 if (quotes) {
6669                         if (--esc < 0) {
6670                                 esc = esclen(startp, loc);
6671                         }
6672                         if (esc % 2) {
6673                                 esc--;
6674                                 loc--;
6675                         }
6676                 }
6677         }
6678         return NULL;
6679 }
6680
6681 static void varunset(const char *, const char *, const char *, int) NORETURN;
6682 static void
6683 varunset(const char *end, const char *var, const char *umsg, int varflags)
6684 {
6685         const char *msg;
6686         const char *tail;
6687
6688         tail = nullstr;
6689         msg = "parameter not set";
6690         if (umsg) {
6691                 if ((unsigned char)*end == CTLENDVAR) {
6692                         if (varflags & VSNUL)
6693                                 tail = " or null";
6694                 } else {
6695                         msg = umsg;
6696                 }
6697         }
6698         ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6699 }
6700
6701 static const char *
6702 subevalvar(char *p, char *varname, int strloc, int subtype,
6703                 int startloc, int varflags, int flag)
6704 {
6705         struct nodelist *saveargbackq = argbackq;
6706         int quotes = flag & QUOTES_ESC;
6707         char *startp;
6708         char *loc;
6709         char *rmesc, *rmescend;
6710         char *str;
6711         int amount, resetloc;
6712         IF_BASH_PATTERN_SUBST(int workloc;)
6713         IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6714         int zero;
6715         char *(*scan)(char*, char*, char*, char*, int, int);
6716
6717         //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6718         //              p, varname, strloc, subtype, startloc, varflags, quotes);
6719
6720         argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6721                         (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6722         );
6723         STPUTC('\0', expdest);
6724         argbackq = saveargbackq;
6725         startp = (char *)stackblock() + startloc;
6726
6727         switch (subtype) {
6728         case VSASSIGN:
6729                 setvar0(varname, startp);
6730                 amount = startp - expdest;
6731                 STADJUST(amount, expdest);
6732                 return startp;
6733
6734         case VSQUESTION:
6735                 varunset(p, varname, startp, varflags);
6736                 /* NOTREACHED */
6737
6738 #if BASH_SUBSTR
6739         case VSSUBSTR: {
6740                 int pos, len, orig_len;
6741                 char *colon;
6742
6743                 loc = str = stackblock() + strloc;
6744
6745 # if !ENABLE_FEATURE_SH_MATH
6746 #  define ash_arith number
6747 # endif
6748                 /* Read POS in ${var:POS:LEN} */
6749                 colon = strchr(loc, ':');
6750                 if (colon) *colon = '\0';
6751                 pos = ash_arith(loc);
6752                 if (colon) *colon = ':';
6753
6754                 /* Read LEN in ${var:POS:LEN} */
6755                 len = str - startp - 1;
6756                 /* *loc != '\0', guaranteed by parser */
6757                 if (quotes) {
6758                         char *ptr;
6759
6760                         /* Adjust the length by the number of escapes */
6761                         for (ptr = startp; ptr < (str - 1); ptr++) {
6762                                 if ((unsigned char)*ptr == CTLESC) {
6763                                         len--;
6764                                         ptr++;
6765                                 }
6766                         }
6767                 }
6768                 orig_len = len;
6769                 if (*loc++ == ':') {
6770                         /* ${var::LEN} */
6771                         len = ash_arith(loc);
6772                 } else {
6773                         /* Skip POS in ${var:POS:LEN} */
6774                         len = orig_len;
6775                         while (*loc && *loc != ':') {
6776                                 loc++;
6777                         }
6778                         if (*loc++ == ':') {
6779                                 len = ash_arith(loc);
6780                         }
6781                 }
6782 #  undef ash_arith
6783
6784                 if (pos < 0) {
6785                         /* ${VAR:$((-n)):l} starts n chars from the end */
6786                         pos = orig_len + pos;
6787                 }
6788                 if ((unsigned)pos >= orig_len) {
6789                         /* apart from obvious ${VAR:999999:l},
6790                          * covers ${VAR:$((-9999999)):l} - result is ""
6791                          * (bash compat)
6792                          */
6793                         pos = 0;
6794                         len = 0;
6795                 }
6796                 if (len < 0) {
6797                         /* ${VAR:N:-M} sets LEN to strlen()-M */
6798                         len = (orig_len - pos) + len;
6799                 }
6800                 if ((unsigned)len > (orig_len - pos))
6801                         len = orig_len - pos;
6802
6803                 for (str = startp; pos; str++, pos--) {
6804                         if (quotes && (unsigned char)*str == CTLESC)
6805                                 str++;
6806                 }
6807                 for (loc = startp; len; len--) {
6808                         if (quotes && (unsigned char)*str == CTLESC)
6809                                 *loc++ = *str++;
6810                         *loc++ = *str++;
6811                 }
6812                 *loc = '\0';
6813                 amount = loc - expdest;
6814                 STADJUST(amount, expdest);
6815                 return loc;
6816         }
6817 #endif /* BASH_SUBSTR */
6818         }
6819
6820         resetloc = expdest - (char *)stackblock();
6821
6822 #if BASH_PATTERN_SUBST
6823         /* We'll comeback here if we grow the stack while handling
6824          * a VSREPLACE or VSREPLACEALL, since our pointers into the
6825          * stack will need rebasing, and we'll need to remove our work
6826          * areas each time
6827          */
6828  restart:
6829 #endif
6830
6831         amount = expdest - ((char *)stackblock() + resetloc);
6832         STADJUST(-amount, expdest);
6833         startp = (char *)stackblock() + startloc;
6834
6835         rmesc = startp;
6836         rmescend = (char *)stackblock() + strloc;
6837         if (quotes) {
6838                 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6839                 if (rmesc != startp) {
6840                         rmescend = expdest;
6841                         startp = (char *)stackblock() + startloc;
6842                 }
6843         }
6844         rmescend--;
6845         str = (char *)stackblock() + strloc;
6846         /*
6847          * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6848          * The result is a_\_z_c (not a\_\_z_c)!
6849          *
6850          * The search pattern and replace string treat backslashes differently!
6851          * RMESCAPE_SLASH causes preglob to work differently on the pattern
6852          * and string.  It's only used on the first call.
6853          */
6854         preglob(str, IF_BASH_PATTERN_SUBST(
6855                 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6856                         RMESCAPE_SLASH : ) 0);
6857
6858 #if BASH_PATTERN_SUBST
6859         workloc = expdest - (char *)stackblock();
6860         if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6861                 int len;
6862                 char *idx, *end;
6863
6864                 if (!repl) {
6865                         repl = strchr(str, CTLESC);
6866                         if (repl)
6867                                 *repl++ = '\0';
6868                         else
6869                                 repl = nullstr;
6870                 }
6871                 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6872
6873                 /* If there's no pattern to match, return the expansion unmolested */
6874                 if (str[0] == '\0')
6875                         return NULL;
6876
6877                 len = 0;
6878                 idx = startp;
6879                 end = str - 1;
6880                 while (idx < end) {
6881  try_to_match:
6882                         loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6883                         //bb_error_msg("scanright('%s'):'%s'", str, loc);
6884                         if (!loc) {
6885                                 /* No match, advance */
6886                                 char *restart_detect = stackblock();
6887  skip_matching:
6888                                 STPUTC(*idx, expdest);
6889                                 if (quotes && (unsigned char)*idx == CTLESC) {
6890                                         idx++;
6891                                         len++;
6892                                         STPUTC(*idx, expdest);
6893                                 }
6894                                 if (stackblock() != restart_detect)
6895                                         goto restart;
6896                                 idx++;
6897                                 len++;
6898                                 rmesc++;
6899                                 /* continue; - prone to quadratic behavior, smarter code: */
6900                                 if (idx >= end)
6901                                         break;
6902                                 if (str[0] == '*') {
6903                                         /* Pattern is "*foo". If "*foo" does not match "long_string",
6904                                          * it would never match "ong_string" etc, no point in trying.
6905                                          */
6906                                         goto skip_matching;
6907                                 }
6908                                 goto try_to_match;
6909                         }
6910
6911                         if (subtype == VSREPLACEALL) {
6912                                 while (idx < loc) {
6913                                         if (quotes && (unsigned char)*idx == CTLESC)
6914                                                 idx++;
6915                                         idx++;
6916                                         rmesc++;
6917                                 }
6918                         } else {
6919                                 idx = loc;
6920                         }
6921
6922                         //bb_error_msg("repl:'%s'", repl);
6923                         for (loc = (char*)repl; *loc; loc++) {
6924                                 char *restart_detect = stackblock();
6925                                 if (quotes && *loc == '\\') {
6926                                         STPUTC(CTLESC, expdest);
6927                                         len++;
6928                                 }
6929                                 STPUTC(*loc, expdest);
6930                                 if (stackblock() != restart_detect)
6931                                         goto restart;
6932                                 len++;
6933                         }
6934
6935                         if (subtype == VSREPLACE) {
6936                                 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6937                                 while (*idx) {
6938                                         char *restart_detect = stackblock();
6939                                         STPUTC(*idx, expdest);
6940                                         if (stackblock() != restart_detect)
6941                                                 goto restart;
6942                                         len++;
6943                                         idx++;
6944                                 }
6945                                 break;
6946                         }
6947                 }
6948
6949                 /* We've put the replaced text into a buffer at workloc, now
6950                  * move it to the right place and adjust the stack.
6951                  */
6952                 STPUTC('\0', expdest);
6953                 startp = (char *)stackblock() + startloc;
6954                 memmove(startp, (char *)stackblock() + workloc, len + 1);
6955                 //bb_error_msg("startp:'%s'", startp);
6956                 amount = expdest - (startp + len);
6957                 STADJUST(-amount, expdest);
6958                 return startp;
6959         }
6960 #endif /* BASH_PATTERN_SUBST */
6961
6962         subtype -= VSTRIMRIGHT;
6963 #if DEBUG
6964         if (subtype < 0 || subtype > 7)
6965                 abort();
6966 #endif
6967         /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6968         zero = subtype >> 1;
6969         /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6970         scan = (subtype & 1) ^ zero ? scanleft : scanright;
6971
6972         loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6973         if (loc) {
6974                 if (zero) {
6975                         memmove(startp, loc, str - loc);
6976                         loc = startp + (str - loc) - 1;
6977                 }
6978                 *loc = '\0';
6979                 amount = loc - expdest;
6980                 STADJUST(amount, expdest);
6981         }
6982         return loc;
6983 }
6984
6985 /*
6986  * Add the value of a specialized variable to the stack string.
6987  * name parameter (examples):
6988  * ash -c 'echo $1'      name:'1='
6989  * ash -c 'echo $qwe'    name:'qwe='
6990  * ash -c 'echo $$'      name:'$='
6991  * ash -c 'echo ${$}'    name:'$='
6992  * ash -c 'echo ${$##q}' name:'$=q'
6993  * ash -c 'echo ${#$}'   name:'$='
6994  * note: examples with bad shell syntax:
6995  * ash -c 'echo ${#$1}'  name:'$=1'
6996  * ash -c 'echo ${#1#}'  name:'1=#'
6997  */
6998 static NOINLINE ssize_t
6999 varvalue(char *name, int varflags, int flags, int *quotedp)
7000 {
7001         const char *p;
7002         int num;
7003         int i;
7004         ssize_t len = 0;
7005         int sep;
7006         int quoted = *quotedp;
7007         int subtype = varflags & VSTYPE;
7008         int discard = subtype == VSPLUS || subtype == VSLENGTH;
7009         int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7010         int syntax;
7011
7012         sep = (flags & EXP_FULL) << CHAR_BIT;
7013         syntax = quoted ? DQSYNTAX : BASESYNTAX;
7014
7015         switch (*name) {
7016         case '$':
7017                 num = rootpid;
7018                 goto numvar;
7019         case '?':
7020                 num = exitstatus;
7021                 goto numvar;
7022         case '#':
7023                 num = shellparam.nparam;
7024                 goto numvar;
7025         case '!':
7026                 num = backgndpid;
7027                 if (num == 0)
7028                         return -1;
7029  numvar:
7030                 len = cvtnum(num);
7031                 goto check_1char_name;
7032         case '-':
7033                 expdest = makestrspace(NOPTS, expdest);
7034                 for (i = NOPTS - 1; i >= 0; i--) {
7035                         if (optlist[i]) {
7036                                 USTPUTC(optletters(i), expdest);
7037                                 len++;
7038                         }
7039                 }
7040  check_1char_name:
7041 #if 0
7042                 /* handles cases similar to ${#$1} */
7043                 if (name[2] != '\0')
7044                         raise_error_syntax("bad substitution");
7045 #endif
7046                 break;
7047         case '@':
7048                 if (quoted && sep)
7049                         goto param;
7050                 /* fall through */
7051         case '*': {
7052                 char **ap;
7053                 char sepc;
7054
7055                 if (quoted)
7056                         sep = 0;
7057                 sep |= ifsset() ? ifsval()[0] : ' ';
7058  param:
7059                 sepc = sep;
7060                 *quotedp = !sepc;
7061                 ap = shellparam.p;
7062                 if (!ap)
7063                         return -1;
7064                 while ((p = *ap++) != NULL) {
7065                         len += strtodest(p, syntax, quotes);
7066
7067                         if (*ap && sep) {
7068                                 len++;
7069                                 memtodest(&sepc, 1, syntax, quotes);
7070                         }
7071                 }
7072                 break;
7073         } /* case '*' */
7074         case '0':
7075         case '1':
7076         case '2':
7077         case '3':
7078         case '4':
7079         case '5':
7080         case '6':
7081         case '7':
7082         case '8':
7083         case '9':
7084                 num = atoi(name); /* number(name) fails on ${N#str} etc */
7085                 if (num < 0 || num > shellparam.nparam)
7086                         return -1;
7087                 p = num ? shellparam.p[num - 1] : arg0;
7088                 goto value;
7089         default:
7090                 /* NB: name has form "VAR=..." */
7091                 p = lookupvar(name);
7092  value:
7093                 if (!p)
7094                         return -1;
7095
7096                 len = strtodest(p, syntax, quotes);
7097 #if ENABLE_UNICODE_SUPPORT
7098                 if (subtype == VSLENGTH && len > 0) {
7099                         reinit_unicode_for_ash();
7100                         if (unicode_status == UNICODE_ON) {
7101                                 STADJUST(-len, expdest);
7102                                 discard = 0;
7103                                 len = unicode_strlen(p);
7104                         }
7105                 }
7106 #endif
7107                 break;
7108         }
7109
7110         if (discard)
7111                 STADJUST(-len, expdest);
7112         return len;
7113 }
7114
7115 /*
7116  * Expand a variable, and return a pointer to the next character in the
7117  * input string.
7118  */
7119 static char *
7120 evalvar(char *p, int flag)
7121 {
7122         char varflags;
7123         char subtype;
7124         int quoted;
7125         char easy;
7126         char *var;
7127         int patloc;
7128         int startloc;
7129         ssize_t varlen;
7130
7131         varflags = (unsigned char) *p++;
7132         subtype = varflags & VSTYPE;
7133
7134         if (!subtype)
7135                 raise_error_syntax("bad substitution");
7136
7137         quoted = flag & EXP_QUOTED;
7138         var = p;
7139         easy = (!quoted || (*var == '@' && shellparam.nparam));
7140         startloc = expdest - (char *)stackblock();
7141         p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7142
7143  again:
7144         varlen = varvalue(var, varflags, flag, &quoted);
7145         if (varflags & VSNUL)
7146                 varlen--;
7147
7148         if (subtype == VSPLUS) {
7149                 varlen = -1 - varlen;
7150                 goto vsplus;
7151         }
7152
7153         if (subtype == VSMINUS) {
7154  vsplus:
7155                 if (varlen < 0) {
7156                         argstr(
7157                                 p,
7158                                 flag | EXP_TILDE | EXP_WORD
7159                         );
7160                         goto end;
7161                 }
7162                 goto record;
7163         }
7164
7165         if (subtype == VSASSIGN || subtype == VSQUESTION) {
7166                 if (varlen >= 0)
7167                         goto record;
7168
7169                 subevalvar(p, var, 0, subtype, startloc, varflags,
7170                            flag & ~QUOTES_ESC);
7171                 varflags &= ~VSNUL;
7172                 /*
7173                  * Remove any recorded regions beyond
7174                  * start of variable
7175                  */
7176                 removerecordregions(startloc);
7177                 goto again;
7178         }
7179
7180         if (varlen < 0 && uflag)
7181                 varunset(p, var, 0, 0);
7182
7183         if (subtype == VSLENGTH) {
7184                 cvtnum(varlen > 0 ? varlen : 0);
7185                 goto record;
7186         }
7187
7188         if (subtype == VSNORMAL) {
7189  record:
7190                 if (!easy)
7191                         goto end;
7192                 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7193                 goto end;
7194         }
7195
7196 #if DEBUG
7197         switch (subtype) {
7198         case VSTRIMLEFT:
7199         case VSTRIMLEFTMAX:
7200         case VSTRIMRIGHT:
7201         case VSTRIMRIGHTMAX:
7202 #if BASH_SUBSTR
7203         case VSSUBSTR:
7204 #endif
7205 #if BASH_PATTERN_SUBST
7206         case VSREPLACE:
7207         case VSREPLACEALL:
7208 #endif
7209                 break;
7210         default:
7211                 abort();
7212         }
7213 #endif
7214
7215         if (varlen >= 0) {
7216                 /*
7217                  * Terminate the string and start recording the pattern
7218                  * right after it
7219                  */
7220                 STPUTC('\0', expdest);
7221                 patloc = expdest - (char *)stackblock();
7222                 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7223                                 startloc, varflags, flag)) {
7224                         int amount = expdest - (
7225                                 (char *)stackblock() + patloc - 1
7226                         );
7227                         STADJUST(-amount, expdest);
7228                 }
7229                 /* Remove any recorded regions beyond start of variable */
7230                 removerecordregions(startloc);
7231                 goto record;
7232         }
7233
7234  end:
7235         if (subtype != VSNORMAL) {      /* skip to end of alternative */
7236                 int nesting = 1;
7237                 for (;;) {
7238                         unsigned char c = *p++;
7239                         if (c == CTLESC)
7240                                 p++;
7241                         else if (c == CTLBACKQ) {
7242                                 if (varlen >= 0)
7243                                         argbackq = argbackq->next;
7244                         } else if (c == CTLVAR) {
7245                                 if ((*p++ & VSTYPE) != VSNORMAL)
7246                                         nesting++;
7247                         } else if (c == CTLENDVAR) {
7248                                 if (--nesting == 0)
7249                                         break;
7250                         }
7251                 }
7252         }
7253         return p;
7254 }
7255
7256 /*
7257  * Add a file name to the list.
7258  */
7259 static void
7260 addfname(const char *name)
7261 {
7262         struct strlist *sp;
7263
7264         sp = stzalloc(sizeof(*sp));
7265         sp->text = sstrdup(name);
7266         *exparg.lastp = sp;
7267         exparg.lastp = &sp->next;
7268 }
7269
7270 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7271 static int
7272 hasmeta(const char *p)
7273 {
7274         static const char chars[] ALIGN1 = {
7275                 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7276         };
7277
7278         for (;;) {
7279                 p = strpbrk(p, chars);
7280                 if (!p)
7281                         break;
7282                 switch ((unsigned char) *p) {
7283                 case CTLQUOTEMARK:
7284                         for (;;) {
7285                                 p++;
7286                                 if (*p == CTLQUOTEMARK)
7287                                         break;
7288                                 if (*p == CTLESC)
7289                                         p++;
7290                                 if (*p == '\0') /* huh? */
7291                                         return 0;
7292                         }
7293                         break;
7294                 case '\\':
7295                 case CTLESC:
7296                         p++;
7297                         if (*p == '\0')
7298                                 return 0;
7299                         break;
7300                 case '[':
7301                         if (!strchr(p + 1, ']')) {
7302                                 /* It's not a properly closed [] pattern,
7303                                  * but other metas may follow. Continue checking.
7304                                  * my[file* _is_ globbed by bash
7305                                  * and matches filenames like "my[file1".
7306                                  */
7307                                 break;
7308                         }
7309                         /* fallthrough */
7310                 default:
7311                 /* case '*': */
7312                 /* case '?': */
7313                         return 1;
7314                 }
7315                 p++;
7316         }
7317
7318         return 0;
7319 }
7320
7321 /* If we want to use glob() from libc... */
7322 #if !ENABLE_ASH_INTERNAL_GLOB
7323
7324 /* Add the result of glob() to the list */
7325 static void
7326 addglob(const glob_t *pglob)
7327 {
7328         char **p = pglob->gl_pathv;
7329
7330         do {
7331                 addfname(*p);
7332         } while (*++p);
7333 }
7334 static void
7335 expandmeta(struct strlist *str /*, int flag*/)
7336 {
7337         /* TODO - EXP_REDIR */
7338
7339         while (str) {
7340                 char *p;
7341                 glob_t pglob;
7342                 int i;
7343
7344                 if (fflag)
7345                         goto nometa;
7346
7347                 if (!hasmeta(str->text))
7348                         goto nometa;
7349
7350                 INT_OFF;
7351                 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7352 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7353 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7354 //
7355 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7356 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7357 // Which means you need to unescape the string, right? Not so fast:
7358 // if there _is_ a file named "file\?" (with backslash), it is returned
7359 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7360 // You DON'T KNOW by looking at the result whether you need to unescape it.
7361 //
7362 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7363 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7364 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7365 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7366 //              i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7367 //              i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7368                 i = glob(p, 0, NULL, &pglob);
7369                 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7370                 if (p != str->text)
7371                         free(p);
7372                 switch (i) {
7373                 case 0:
7374 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7375                         /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7376                         if (!(pglob.gl_flags & GLOB_MAGCHAR))
7377                                 goto nometa2;
7378 #endif
7379                         addglob(&pglob);
7380                         globfree(&pglob);
7381                         INT_ON;
7382                         break;
7383                 case GLOB_NOMATCH:
7384  //nometa2:
7385                         globfree(&pglob);
7386                         INT_ON;
7387  nometa:
7388                         *exparg.lastp = str;
7389                         rmescapes(str->text, 0);
7390                         exparg.lastp = &str->next;
7391                         break;
7392                 default:        /* GLOB_NOSPACE */
7393                         globfree(&pglob);
7394                         INT_ON;
7395                         ash_msg_and_raise_error(bb_msg_memory_exhausted);
7396                 }
7397                 str = str->next;
7398         }
7399 }
7400
7401 #else
7402 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7403
7404 /*
7405  * Do metacharacter (i.e. *, ?, [...]) expansion.
7406  */
7407 static void
7408 expmeta(char *expdir, char *enddir, char *name)
7409 {
7410         char *p;
7411         const char *cp;
7412         char *start;
7413         char *endname;
7414         int metaflag;
7415         struct stat statb;
7416         DIR *dirp;
7417         struct dirent *dp;
7418         int atend;
7419         int matchdot;
7420         int esc;
7421
7422         metaflag = 0;
7423         start = name;
7424         for (p = name; esc = 0, *p; p += esc + 1) {
7425                 if (*p == '*' || *p == '?')
7426                         metaflag = 1;
7427                 else if (*p == '[') {
7428                         char *q = p + 1;
7429                         if (*q == '!')
7430                                 q++;
7431                         for (;;) {
7432                                 if (*q == '\\')
7433                                         q++;
7434                                 if (*q == '/' || *q == '\0')
7435                                         break;
7436                                 if (*++q == ']') {
7437                                         metaflag = 1;
7438                                         break;
7439                                 }
7440                         }
7441                 } else {
7442                         if (*p == '\\')
7443                                 esc++;
7444                         if (p[esc] == '/') {
7445                                 if (metaflag)
7446                                         break;
7447                                 start = p + esc + 1;
7448                         }
7449                 }
7450         }
7451         if (metaflag == 0) {    /* we've reached the end of the file name */
7452                 if (enddir != expdir)
7453                         metaflag++;
7454                 p = name;
7455                 do {
7456                         if (*p == '\\')
7457                                 p++;
7458                         *enddir++ = *p;
7459                 } while (*p++);
7460                 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7461                         addfname(expdir);
7462                 return;
7463         }
7464         endname = p;
7465         if (name < start) {
7466                 p = name;
7467                 do {
7468                         if (*p == '\\')
7469                                 p++;
7470                         *enddir++ = *p++;
7471                 } while (p < start);
7472         }
7473         if (enddir == expdir) {
7474                 cp = ".";
7475         } else if (enddir == expdir + 1 && *expdir == '/') {
7476                 cp = "/";
7477         } else {
7478                 cp = expdir;
7479                 enddir[-1] = '\0';
7480         }
7481         dirp = opendir(cp);
7482         if (dirp == NULL)
7483                 return;
7484         if (enddir != expdir)
7485                 enddir[-1] = '/';
7486         if (*endname == 0) {
7487                 atend = 1;
7488         } else {
7489                 atend = 0;
7490                 *endname = '\0';
7491                 endname += esc + 1;
7492         }
7493         matchdot = 0;
7494         p = start;
7495         if (*p == '\\')
7496                 p++;
7497         if (*p == '.')
7498                 matchdot++;
7499         while (!pending_int && (dp = readdir(dirp)) != NULL) {
7500                 if (dp->d_name[0] == '.' && !matchdot)
7501                         continue;
7502                 if (pmatch(start, dp->d_name)) {
7503                         if (atend) {
7504                                 strcpy(enddir, dp->d_name);
7505                                 addfname(expdir);
7506                         } else {
7507                                 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7508                                         continue;
7509                                 p[-1] = '/';
7510                                 expmeta(expdir, p, endname);
7511                         }
7512                 }
7513         }
7514         closedir(dirp);
7515         if (!atend)
7516                 endname[-esc - 1] = esc ? '\\' : '/';
7517 }
7518
7519 static struct strlist *
7520 msort(struct strlist *list, int len)
7521 {
7522         struct strlist *p, *q = NULL;
7523         struct strlist **lpp;
7524         int half;
7525         int n;
7526
7527         if (len <= 1)
7528                 return list;
7529         half = len >> 1;
7530         p = list;
7531         for (n = half; --n >= 0;) {
7532                 q = p;
7533                 p = p->next;
7534         }
7535         q->next = NULL;                 /* terminate first half of list */
7536         q = msort(list, half);          /* sort first half of list */
7537         p = msort(p, len - half);               /* sort second half */
7538         lpp = &list;
7539         for (;;) {
7540 #if ENABLE_LOCALE_SUPPORT
7541                 if (strcoll(p->text, q->text) < 0)
7542 #else
7543                 if (strcmp(p->text, q->text) < 0)
7544 #endif
7545                                                 {
7546                         *lpp = p;
7547                         lpp = &p->next;
7548                         p = *lpp;
7549                         if (p == NULL) {
7550                                 *lpp = q;
7551                                 break;
7552                         }
7553                 } else {
7554                         *lpp = q;
7555                         lpp = &q->next;
7556                         q = *lpp;
7557                         if (q == NULL) {
7558                                 *lpp = p;
7559                                 break;
7560                         }
7561                 }
7562         }
7563         return list;
7564 }
7565
7566 /*
7567  * Sort the results of file name expansion.  It calculates the number of
7568  * strings to sort and then calls msort (short for merge sort) to do the
7569  * work.
7570  */
7571 static struct strlist *
7572 expsort(struct strlist *str)
7573 {
7574         int len;
7575         struct strlist *sp;
7576
7577         len = 0;
7578         for (sp = str; sp; sp = sp->next)
7579                 len++;
7580         return msort(str, len);
7581 }
7582
7583 static void
7584 expandmeta(struct strlist *str /*, int flag*/)
7585 {
7586         /* TODO - EXP_REDIR */
7587
7588         while (str) {
7589                 char *expdir;
7590                 struct strlist **savelastp;
7591                 struct strlist *sp;
7592                 char *p;
7593
7594                 if (fflag)
7595                         goto nometa;
7596                 if (!hasmeta(str->text))
7597                         goto nometa;
7598                 savelastp = exparg.lastp;
7599
7600                 INT_OFF;
7601                 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7602                 {
7603                         int i = strlen(str->text);
7604 //BUGGY estimation of how long expanded name can be
7605                         expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7606                 }
7607                 expmeta(expdir, expdir, p);
7608                 free(expdir);
7609                 if (p != str->text)
7610                         free(p);
7611                 INT_ON;
7612                 if (exparg.lastp == savelastp) {
7613                         /*
7614                          * no matches
7615                          */
7616  nometa:
7617                         *exparg.lastp = str;
7618                         rmescapes(str->text, 0);
7619                         exparg.lastp = &str->next;
7620                 } else {
7621                         *exparg.lastp = NULL;
7622                         *savelastp = sp = expsort(*savelastp);
7623                         while (sp->next != NULL)
7624                                 sp = sp->next;
7625                         exparg.lastp = &sp->next;
7626                 }
7627                 str = str->next;
7628         }
7629 }
7630 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7631
7632 /*
7633  * Perform variable substitution and command substitution on an argument,
7634  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
7635  * perform splitting and file name expansion.  When arglist is NULL, perform
7636  * here document expansion.
7637  */
7638 static void
7639 expandarg(union node *arg, struct arglist *arglist, int flag)
7640 {
7641         struct strlist *sp;
7642         char *p;
7643
7644         argbackq = arg->narg.backquote;
7645         STARTSTACKSTR(expdest);
7646         TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7647         argstr(arg->narg.text, flag);
7648         p = _STPUTC('\0', expdest);
7649         expdest = p - 1;
7650         if (arglist == NULL) {
7651                 /* here document expanded */
7652                 goto out;
7653         }
7654         p = grabstackstr(p);
7655         TRACE(("expandarg: p:'%s'\n", p));
7656         exparg.lastp = &exparg.list;
7657         /*
7658          * TODO - EXP_REDIR
7659          */
7660         if (flag & EXP_FULL) {
7661                 ifsbreakup(p, &exparg);
7662                 *exparg.lastp = NULL;
7663                 exparg.lastp = &exparg.list;
7664                 expandmeta(exparg.list /*, flag*/);
7665         } else {
7666                 sp = stzalloc(sizeof(*sp));
7667                 sp->text = p;
7668                 *exparg.lastp = sp;
7669                 exparg.lastp = &sp->next;
7670         }
7671         *exparg.lastp = NULL;
7672         if (exparg.list) {
7673                 *arglist->lastp = exparg.list;
7674                 arglist->lastp = exparg.lastp;
7675         }
7676
7677  out:
7678         ifsfree();
7679 }
7680
7681 /*
7682  * Expand shell variables and backquotes inside a here document.
7683  */
7684 static void
7685 expandhere(union node *arg, int fd)
7686 {
7687         expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7688         full_write(fd, stackblock(), expdest - (char *)stackblock());
7689 }
7690
7691 /*
7692  * Returns true if the pattern matches the string.
7693  */
7694 static int
7695 patmatch(char *pattern, const char *string)
7696 {
7697         char *p = preglob(pattern, 0);
7698         //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7699         return pmatch(p, string);
7700 }
7701
7702 /*
7703  * See if a pattern matches in a case statement.
7704  */
7705 static int
7706 casematch(union node *pattern, char *val)
7707 {
7708         struct stackmark smark;
7709         int result;
7710
7711         setstackmark(&smark);
7712         argbackq = pattern->narg.backquote;
7713         STARTSTACKSTR(expdest);
7714         argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7715         STACKSTRNUL(expdest);
7716         ifsfree();
7717         result = patmatch(stackblock(), val);
7718         popstackmark(&smark);
7719         return result;
7720 }
7721
7722
7723 /* ============ find_command */
7724
7725 struct builtincmd {
7726         const char *name;
7727         int (*builtin)(int, char **) FAST_FUNC;
7728         /* unsigned flags; */
7729 };
7730 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7731 /* "regular" builtins always take precedence over commands,
7732  * regardless of PATH=....%builtin... position */
7733 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7734 #define IS_BUILTIN_ASSIGN(b)  ((b)->name[0] & 4)
7735
7736 struct cmdentry {
7737         smallint cmdtype;       /* CMDxxx */
7738         union param {
7739                 int index;
7740                 /* index >= 0 for commands without path (slashes) */
7741                 /* (TODO: what exactly does the value mean? PATH position?) */
7742                 /* index == -1 for commands with slashes */
7743                 /* index == (-2 - applet_no) for NOFORK applets */
7744                 const struct builtincmd *cmd;
7745                 struct funcnode *func;
7746         } u;
7747 };
7748 /* values of cmdtype */
7749 #define CMDUNKNOWN      -1      /* no entry in table for command */
7750 #define CMDNORMAL       0       /* command is an executable program */
7751 #define CMDFUNCTION     1       /* command is a shell function */
7752 #define CMDBUILTIN      2       /* command is a shell builtin */
7753
7754 /* action to find_command() */
7755 #define DO_ERR          0x01    /* prints errors */
7756 #define DO_ABS          0x02    /* checks absolute paths */
7757 #define DO_NOFUNC       0x04    /* don't return shell functions, for command */
7758 #define DO_ALTPATH      0x08    /* using alternate path */
7759 #define DO_ALTBLTIN     0x20    /* %builtin in alt. path */
7760
7761 static void find_command(char *, struct cmdentry *, int, const char *);
7762
7763
7764 /* ============ Hashing commands */
7765
7766 /*
7767  * When commands are first encountered, they are entered in a hash table.
7768  * This ensures that a full path search will not have to be done for them
7769  * on each invocation.
7770  *
7771  * We should investigate converting to a linear search, even though that
7772  * would make the command name "hash" a misnomer.
7773  */
7774
7775 struct tblentry {
7776         struct tblentry *next;  /* next entry in hash chain */
7777         union param param;      /* definition of builtin function */
7778         smallint cmdtype;       /* CMDxxx */
7779         char rehash;            /* if set, cd done since entry created */
7780         char cmdname[1];        /* name of command */
7781 };
7782
7783 static struct tblentry **cmdtable;
7784 #define INIT_G_cmdtable() do { \
7785         cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7786 } while (0)
7787
7788 static int builtinloc = -1;     /* index in path of %builtin, or -1 */
7789
7790
7791 static void
7792 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7793 {
7794 #if ENABLE_FEATURE_SH_STANDALONE
7795         if (applet_no >= 0) {
7796                 if (APPLET_IS_NOEXEC(applet_no)) {
7797                         clearenv();
7798                         while (*envp)
7799                                 putenv(*envp++);
7800                         popredir(/*drop:*/ 1);
7801                         run_applet_no_and_exit(applet_no, cmd, argv);
7802                 }
7803                 /* re-exec ourselves with the new arguments */
7804                 execve(bb_busybox_exec_path, argv, envp);
7805                 /* If they called chroot or otherwise made the binary no longer
7806                  * executable, fall through */
7807         }
7808 #endif
7809
7810  repeat:
7811 #ifdef SYSV
7812         do {
7813                 execve(cmd, argv, envp);
7814         } while (errno == EINTR);
7815 #else
7816         execve(cmd, argv, envp);
7817 #endif
7818         if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7819                 /* Run "cmd" as a shell script:
7820                  * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7821                  * "If the execve() function fails with ENOEXEC, the shell
7822                  * shall execute a command equivalent to having a shell invoked
7823                  * with the command name as its first operand,
7824                  * with any remaining arguments passed to the new shell"
7825                  *
7826                  * That is, do not use $SHELL, user's shell, or /bin/sh;
7827                  * just call ourselves.
7828                  *
7829                  * Note that bash reads ~80 chars of the file, and if it sees
7830                  * a zero byte before it sees newline, it doesn't try to
7831                  * interpret it, but fails with "cannot execute binary file"
7832                  * message and exit code 126. For one, this prevents attempts
7833                  * to interpret foreign ELF binaries as shell scripts.
7834                  */
7835                 argv[0] = (char*) cmd;
7836                 cmd = bb_busybox_exec_path;
7837                 /* NB: this is only possible because all callers of shellexec()
7838                  * ensure that the argv[-1] slot exists!
7839                  */
7840                 argv--;
7841                 argv[0] = (char*) "ash";
7842                 goto repeat;
7843         }
7844 }
7845
7846 /*
7847  * Exec a program.  Never returns.  If you change this routine, you may
7848  * have to change the find_command routine as well.
7849  * argv[-1] must exist and be writable! See tryexec() for why.
7850  */
7851 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7852 static void shellexec(char *prog, char **argv, const char *path, int idx)
7853 {
7854         char *cmdname;
7855         int e;
7856         char **envp;
7857         int exerrno;
7858         int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7859
7860         envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7861         if (strchr(prog, '/') != NULL
7862 #if ENABLE_FEATURE_SH_STANDALONE
7863          || (applet_no = find_applet_by_name(prog)) >= 0
7864 #endif
7865         ) {
7866                 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7867                 if (applet_no >= 0) {
7868                         /* We tried execing ourself, but it didn't work.
7869                          * Maybe /proc/self/exe doesn't exist?
7870                          * Try $PATH search.
7871                          */
7872                         goto try_PATH;
7873                 }
7874                 e = errno;
7875         } else {
7876  try_PATH:
7877                 e = ENOENT;
7878                 while ((cmdname = path_advance(&path, prog)) != NULL) {
7879                         if (--idx < 0 && pathopt == NULL) {
7880                                 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7881                                 if (errno != ENOENT && errno != ENOTDIR)
7882                                         e = errno;
7883                         }
7884                         stunalloc(cmdname);
7885                 }
7886         }
7887
7888         /* Map to POSIX errors */
7889         switch (e) {
7890         case EACCES:
7891                 exerrno = 126;
7892                 break;
7893         case ENOENT:
7894                 exerrno = 127;
7895                 break;
7896         default:
7897                 exerrno = 2;
7898                 break;
7899         }
7900         exitstatus = exerrno;
7901         TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7902                 prog, e, suppress_int));
7903         ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7904         /* NOTREACHED */
7905 }
7906
7907 static void
7908 printentry(struct tblentry *cmdp)
7909 {
7910         int idx;
7911         const char *path;
7912         char *name;
7913
7914         idx = cmdp->param.index;
7915         path = pathval();
7916         do {
7917                 name = path_advance(&path, cmdp->cmdname);
7918                 stunalloc(name);
7919         } while (--idx >= 0);
7920         out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7921 }
7922
7923 /*
7924  * Clear out command entries.  The argument specifies the first entry in
7925  * PATH which has changed.
7926  */
7927 static void
7928 clearcmdentry(int firstchange)
7929 {
7930         struct tblentry **tblp;
7931         struct tblentry **pp;
7932         struct tblentry *cmdp;
7933
7934         INT_OFF;
7935         for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7936                 pp = tblp;
7937                 while ((cmdp = *pp) != NULL) {
7938                         if ((cmdp->cmdtype == CMDNORMAL &&
7939                              cmdp->param.index >= firstchange)
7940                          || (cmdp->cmdtype == CMDBUILTIN &&
7941                              builtinloc >= firstchange)
7942                         ) {
7943                                 *pp = cmdp->next;
7944                                 free(cmdp);
7945                         } else {
7946                                 pp = &cmdp->next;
7947                         }
7948                 }
7949         }
7950         INT_ON;
7951 }
7952
7953 /*
7954  * Locate a command in the command hash table.  If "add" is nonzero,
7955  * add the command to the table if it is not already present.  The
7956  * variable "lastcmdentry" is set to point to the address of the link
7957  * pointing to the entry, so that delete_cmd_entry can delete the
7958  * entry.
7959  *
7960  * Interrupts must be off if called with add != 0.
7961  */
7962 static struct tblentry **lastcmdentry;
7963
7964 static struct tblentry *
7965 cmdlookup(const char *name, int add)
7966 {
7967         unsigned int hashval;
7968         const char *p;
7969         struct tblentry *cmdp;
7970         struct tblentry **pp;
7971
7972         p = name;
7973         hashval = (unsigned char)*p << 4;
7974         while (*p)
7975                 hashval += (unsigned char)*p++;
7976         hashval &= 0x7FFF;
7977         pp = &cmdtable[hashval % CMDTABLESIZE];
7978         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7979                 if (strcmp(cmdp->cmdname, name) == 0)
7980                         break;
7981                 pp = &cmdp->next;
7982         }
7983         if (add && cmdp == NULL) {
7984                 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7985                                 + strlen(name)
7986                                 /* + 1 - already done because
7987                                  * tblentry::cmdname is char[1] */);
7988                 /*cmdp->next = NULL; - ckzalloc did it */
7989                 cmdp->cmdtype = CMDUNKNOWN;
7990                 strcpy(cmdp->cmdname, name);
7991         }
7992         lastcmdentry = pp;
7993         return cmdp;
7994 }
7995
7996 /*
7997  * Delete the command entry returned on the last lookup.
7998  */
7999 static void
8000 delete_cmd_entry(void)
8001 {
8002         struct tblentry *cmdp;
8003
8004         INT_OFF;
8005         cmdp = *lastcmdentry;
8006         *lastcmdentry = cmdp->next;
8007         if (cmdp->cmdtype == CMDFUNCTION)
8008                 freefunc(cmdp->param.func);
8009         free(cmdp);
8010         INT_ON;
8011 }
8012
8013 /*
8014  * Add a new command entry, replacing any existing command entry for
8015  * the same name - except special builtins.
8016  */
8017 static void
8018 addcmdentry(char *name, struct cmdentry *entry)
8019 {
8020         struct tblentry *cmdp;
8021
8022         cmdp = cmdlookup(name, 1);
8023         if (cmdp->cmdtype == CMDFUNCTION) {
8024                 freefunc(cmdp->param.func);
8025         }
8026         cmdp->cmdtype = entry->cmdtype;
8027         cmdp->param = entry->u;
8028         cmdp->rehash = 0;
8029 }
8030
8031 static int FAST_FUNC
8032 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8033 {
8034         struct tblentry **pp;
8035         struct tblentry *cmdp;
8036         int c;
8037         struct cmdentry entry;
8038         char *name;
8039
8040         if (nextopt("r") != '\0') {
8041                 clearcmdentry(0);
8042                 return 0;
8043         }
8044
8045         if (*argptr == NULL) {
8046                 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8047                         for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8048                                 if (cmdp->cmdtype == CMDNORMAL)
8049                                         printentry(cmdp);
8050                         }
8051                 }
8052                 return 0;
8053         }
8054
8055         c = 0;
8056         while ((name = *argptr) != NULL) {
8057                 cmdp = cmdlookup(name, 0);
8058                 if (cmdp != NULL
8059                  && (cmdp->cmdtype == CMDNORMAL
8060                      || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8061                 ) {
8062                         delete_cmd_entry();
8063                 }
8064                 find_command(name, &entry, DO_ERR, pathval());
8065                 if (entry.cmdtype == CMDUNKNOWN)
8066                         c = 1;
8067                 argptr++;
8068         }
8069         return c;
8070 }
8071
8072 /*
8073  * Called when a cd is done.  Marks all commands so the next time they
8074  * are executed they will be rehashed.
8075  */
8076 static void
8077 hashcd(void)
8078 {
8079         struct tblentry **pp;
8080         struct tblentry *cmdp;
8081
8082         for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8083                 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8084                         if (cmdp->cmdtype == CMDNORMAL
8085                          || (cmdp->cmdtype == CMDBUILTIN
8086                              && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8087                              && builtinloc > 0)
8088                         ) {
8089                                 cmdp->rehash = 1;
8090                         }
8091                 }
8092         }
8093 }
8094
8095 /*
8096  * Fix command hash table when PATH changed.
8097  * Called before PATH is changed.  The argument is the new value of PATH;
8098  * pathval() still returns the old value at this point.
8099  * Called with interrupts off.
8100  */
8101 static void FAST_FUNC
8102 changepath(const char *new)
8103 {
8104         const char *old;
8105         int firstchange;
8106         int idx;
8107         int idx_bltin;
8108
8109         old = pathval();
8110         firstchange = 9999;     /* assume no change */
8111         idx = 0;
8112         idx_bltin = -1;
8113         for (;;) {
8114                 if (*old != *new) {
8115                         firstchange = idx;
8116                         if ((*old == '\0' && *new == ':')
8117                          || (*old == ':' && *new == '\0')
8118                         ) {
8119                                 firstchange++;
8120                         }
8121                         old = new;      /* ignore subsequent differences */
8122                 }
8123                 if (*new == '\0')
8124                         break;
8125                 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8126                         idx_bltin = idx;
8127                 if (*new == ':')
8128                         idx++;
8129                 new++;
8130                 old++;
8131         }
8132         if (builtinloc < 0 && idx_bltin >= 0)
8133                 builtinloc = idx_bltin;             /* zap builtins */
8134         if (builtinloc >= 0 && idx_bltin < 0)
8135                 firstchange = 0;
8136         clearcmdentry(firstchange);
8137         builtinloc = idx_bltin;
8138 }
8139 enum {
8140         TEOF,
8141         TNL,
8142         TREDIR,
8143         TWORD,
8144         TSEMI,
8145         TBACKGND,
8146         TAND,
8147         TOR,
8148         TPIPE,
8149         TLP,
8150         TRP,
8151         TENDCASE,
8152         TENDBQUOTE,
8153         TNOT,
8154         TCASE,
8155         TDO,
8156         TDONE,
8157         TELIF,
8158         TELSE,
8159         TESAC,
8160         TFI,
8161         TFOR,
8162 #if BASH_FUNCTION
8163         TFUNCTION,
8164 #endif
8165         TIF,
8166         TIN,
8167         TTHEN,
8168         TUNTIL,
8169         TWHILE,
8170         TBEGIN,
8171         TEND
8172 };
8173 typedef smallint token_id_t;
8174
8175 /* Nth bit indicates if token marks the end of a list */
8176 enum {
8177         tokendlist = 0
8178         /*  0 */ | (1u << TEOF)
8179         /*  1 */ | (0u << TNL)
8180         /*  2 */ | (0u << TREDIR)
8181         /*  3 */ | (0u << TWORD)
8182         /*  4 */ | (0u << TSEMI)
8183         /*  5 */ | (0u << TBACKGND)
8184         /*  6 */ | (0u << TAND)
8185         /*  7 */ | (0u << TOR)
8186         /*  8 */ | (0u << TPIPE)
8187         /*  9 */ | (0u << TLP)
8188         /* 10 */ | (1u << TRP)
8189         /* 11 */ | (1u << TENDCASE)
8190         /* 12 */ | (1u << TENDBQUOTE)
8191         /* 13 */ | (0u << TNOT)
8192         /* 14 */ | (0u << TCASE)
8193         /* 15 */ | (1u << TDO)
8194         /* 16 */ | (1u << TDONE)
8195         /* 17 */ | (1u << TELIF)
8196         /* 18 */ | (1u << TELSE)
8197         /* 19 */ | (1u << TESAC)
8198         /* 20 */ | (1u << TFI)
8199         /* 21 */ | (0u << TFOR)
8200 #if BASH_FUNCTION
8201         /* 22 */ | (0u << TFUNCTION)
8202 #endif
8203         /* 23 */ | (0u << TIF)
8204         /* 24 */ | (0u << TIN)
8205         /* 25 */ | (1u << TTHEN)
8206         /* 26 */ | (0u << TUNTIL)
8207         /* 27 */ | (0u << TWHILE)
8208         /* 28 */ | (0u << TBEGIN)
8209         /* 29 */ | (1u << TEND)
8210         , /* thus far 29 bits used */
8211 };
8212
8213 static const char *const tokname_array[] = {
8214         "end of file",
8215         "newline",
8216         "redirection",
8217         "word",
8218         ";",
8219         "&",
8220         "&&",
8221         "||",
8222         "|",
8223         "(",
8224         ")",
8225         ";;",
8226         "`",
8227 #define KWDOFFSET 13
8228         /* the following are keywords */
8229         "!",
8230         "case",
8231         "do",
8232         "done",
8233         "elif",
8234         "else",
8235         "esac",
8236         "fi",
8237         "for",
8238 #if BASH_FUNCTION
8239         "function",
8240 #endif
8241         "if",
8242         "in",
8243         "then",
8244         "until",
8245         "while",
8246         "{",
8247         "}",
8248 };
8249
8250 /* Wrapper around strcmp for qsort/bsearch/... */
8251 static int
8252 pstrcmp(const void *a, const void *b)
8253 {
8254         return strcmp((char*)a, *(char**)b);
8255 }
8256
8257 static const char *const *
8258 findkwd(const char *s)
8259 {
8260         return bsearch(s, tokname_array + KWDOFFSET,
8261                         ARRAY_SIZE(tokname_array) - KWDOFFSET,
8262                         sizeof(tokname_array[0]), pstrcmp);
8263 }
8264
8265 /*
8266  * Locate and print what a word is...
8267  */
8268 static int
8269 describe_command(char *command, const char *path, int describe_command_verbose)
8270 {
8271         struct cmdentry entry;
8272 #if ENABLE_ASH_ALIAS
8273         const struct alias *ap;
8274 #endif
8275
8276         path = path ? path : pathval();
8277
8278         if (describe_command_verbose) {
8279                 out1str(command);
8280         }
8281
8282         /* First look at the keywords */
8283         if (findkwd(command)) {
8284                 out1str(describe_command_verbose ? " is a shell keyword" : command);
8285                 goto out;
8286         }
8287
8288 #if ENABLE_ASH_ALIAS
8289         /* Then look at the aliases */
8290         ap = lookupalias(command, 0);
8291         if (ap != NULL) {
8292                 if (!describe_command_verbose) {
8293                         out1str("alias ");
8294                         printalias(ap);
8295                         return 0;
8296                 }
8297                 out1fmt(" is an alias for %s", ap->val);
8298                 goto out;
8299         }
8300 #endif
8301         /* Brute force */
8302         find_command(command, &entry, DO_ABS, path);
8303
8304         switch (entry.cmdtype) {
8305         case CMDNORMAL: {
8306                 int j = entry.u.index;
8307                 char *p;
8308                 if (j < 0) {
8309                         p = command;
8310                 } else {
8311                         do {
8312                                 p = path_advance(&path, command);
8313                                 stunalloc(p);
8314                         } while (--j >= 0);
8315                 }
8316                 if (describe_command_verbose) {
8317                         out1fmt(" is %s", p);
8318                 } else {
8319                         out1str(p);
8320                 }
8321                 break;
8322         }
8323
8324         case CMDFUNCTION:
8325                 if (describe_command_verbose) {
8326                         out1str(" is a shell function");
8327                 } else {
8328                         out1str(command);
8329                 }
8330                 break;
8331
8332         case CMDBUILTIN:
8333                 if (describe_command_verbose) {
8334                         out1fmt(" is a %sshell builtin",
8335                                 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8336                                         "special " : nullstr
8337                         );
8338                 } else {
8339                         out1str(command);
8340                 }
8341                 break;
8342
8343         default:
8344                 if (describe_command_verbose) {
8345                         out1str(": not found\n");
8346                 }
8347                 return 127;
8348         }
8349  out:
8350         out1str("\n");
8351         return 0;
8352 }
8353
8354 static int FAST_FUNC
8355 typecmd(int argc UNUSED_PARAM, char **argv)
8356 {
8357         int i = 1;
8358         int err = 0;
8359         int verbose = 1;
8360
8361         /* type -p ... ? (we don't bother checking for 'p') */
8362         if (argv[1] && argv[1][0] == '-') {
8363                 i++;
8364                 verbose = 0;
8365         }
8366         while (argv[i]) {
8367                 err |= describe_command(argv[i++], NULL, verbose);
8368         }
8369         return err;
8370 }
8371
8372 #if ENABLE_ASH_CMDCMD
8373 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8374 static char **
8375 parse_command_args(char **argv, const char **path)
8376 {
8377         char *cp, c;
8378
8379         for (;;) {
8380                 cp = *++argv;
8381                 if (!cp)
8382                         return NULL;
8383                 if (*cp++ != '-')
8384                         break;
8385                 c = *cp++;
8386                 if (!c)
8387                         break;
8388                 if (c == '-' && !*cp) {
8389                         if (!*++argv)
8390                                 return NULL;
8391                         break;
8392                 }
8393                 do {
8394                         switch (c) {
8395                         case 'p':
8396                                 *path = bb_default_path;
8397                                 break;
8398                         default:
8399                                 /* run 'typecmd' for other options */
8400                                 return NULL;
8401                         }
8402                         c = *cp++;
8403                 } while (c);
8404         }
8405         return argv;
8406 }
8407
8408 static int FAST_FUNC
8409 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8410 {
8411         char *cmd;
8412         int c;
8413         enum {
8414                 VERIFY_BRIEF = 1,
8415                 VERIFY_VERBOSE = 2,
8416         } verify = 0;
8417         const char *path = NULL;
8418
8419         /* "command [-p] PROG ARGS" (that is, without -V or -v)
8420          * never reaches this function.
8421          */
8422
8423         while ((c = nextopt("pvV")) != '\0')
8424                 if (c == 'V')
8425                         verify |= VERIFY_VERBOSE;
8426                 else if (c == 'v')
8427                         /*verify |= VERIFY_BRIEF*/;
8428 #if DEBUG
8429                 else if (c != 'p')
8430                         abort();
8431 #endif
8432                 else
8433                         path = bb_default_path;
8434
8435         /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8436         cmd = *argptr;
8437         if (/*verify && */ cmd)
8438                 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8439
8440         return 0;
8441 }
8442 #endif
8443
8444
8445 /*static int funcblocksize;     // size of structures in function */
8446 /*static int funcstringsize;    // size of strings in node */
8447 static void *funcblock;         /* block to allocate function from */
8448 static char *funcstring_end;    /* end of block to allocate strings from */
8449
8450 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8451         [NCMD     ] = SHELL_ALIGN(sizeof(struct ncmd)),
8452         [NPIPE    ] = SHELL_ALIGN(sizeof(struct npipe)),
8453         [NREDIR   ] = SHELL_ALIGN(sizeof(struct nredir)),
8454         [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8455         [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8456         [NAND     ] = SHELL_ALIGN(sizeof(struct nbinary)),
8457         [NOR      ] = SHELL_ALIGN(sizeof(struct nbinary)),
8458         [NSEMI    ] = SHELL_ALIGN(sizeof(struct nbinary)),
8459         [NIF      ] = SHELL_ALIGN(sizeof(struct nif)),
8460         [NWHILE   ] = SHELL_ALIGN(sizeof(struct nbinary)),
8461         [NUNTIL   ] = SHELL_ALIGN(sizeof(struct nbinary)),
8462         [NFOR     ] = SHELL_ALIGN(sizeof(struct nfor)),
8463         [NCASE    ] = SHELL_ALIGN(sizeof(struct ncase)),
8464         [NCLIST   ] = SHELL_ALIGN(sizeof(struct nclist)),
8465         [NDEFUN   ] = SHELL_ALIGN(sizeof(struct narg)),
8466         [NARG     ] = SHELL_ALIGN(sizeof(struct narg)),
8467         [NTO      ] = SHELL_ALIGN(sizeof(struct nfile)),
8468 #if BASH_REDIR_OUTPUT
8469         [NTO2     ] = SHELL_ALIGN(sizeof(struct nfile)),
8470 #endif
8471         [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8472         [NFROM    ] = SHELL_ALIGN(sizeof(struct nfile)),
8473         [NFROMTO  ] = SHELL_ALIGN(sizeof(struct nfile)),
8474         [NAPPEND  ] = SHELL_ALIGN(sizeof(struct nfile)),
8475         [NTOFD    ] = SHELL_ALIGN(sizeof(struct ndup)),
8476         [NFROMFD  ] = SHELL_ALIGN(sizeof(struct ndup)),
8477         [NHERE    ] = SHELL_ALIGN(sizeof(struct nhere)),
8478         [NXHERE   ] = SHELL_ALIGN(sizeof(struct nhere)),
8479         [NNOT     ] = SHELL_ALIGN(sizeof(struct nnot)),
8480 };
8481
8482 static int calcsize(int funcblocksize, union node *n);
8483
8484 static int
8485 sizenodelist(int funcblocksize, struct nodelist *lp)
8486 {
8487         while (lp) {
8488                 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8489                 funcblocksize = calcsize(funcblocksize, lp->n);
8490                 lp = lp->next;
8491         }
8492         return funcblocksize;
8493 }
8494
8495 static int
8496 calcsize(int funcblocksize, union node *n)
8497 {
8498         if (n == NULL)
8499                 return funcblocksize;
8500         funcblocksize += nodesize[n->type];
8501         switch (n->type) {
8502         case NCMD:
8503                 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8504                 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8505                 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8506                 break;
8507         case NPIPE:
8508                 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8509                 break;
8510         case NREDIR:
8511         case NBACKGND:
8512         case NSUBSHELL:
8513                 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8514                 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8515                 break;
8516         case NAND:
8517         case NOR:
8518         case NSEMI:
8519         case NWHILE:
8520         case NUNTIL:
8521                 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8522                 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8523                 break;
8524         case NIF:
8525                 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8526                 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8527                 funcblocksize = calcsize(funcblocksize, n->nif.test);
8528                 break;
8529         case NFOR:
8530                 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8531                 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8532                 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8533                 break;
8534         case NCASE:
8535                 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8536                 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8537                 break;
8538         case NCLIST:
8539                 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8540                 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8541                 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8542                 break;
8543         case NDEFUN:
8544         case NARG:
8545                 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8546                 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8547                 funcblocksize = calcsize(funcblocksize, n->narg.next);
8548                 break;
8549         case NTO:
8550 #if BASH_REDIR_OUTPUT
8551         case NTO2:
8552 #endif
8553         case NCLOBBER:
8554         case NFROM:
8555         case NFROMTO:
8556         case NAPPEND:
8557                 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8558                 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8559                 break;
8560         case NTOFD:
8561         case NFROMFD:
8562                 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8563                 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8564         break;
8565         case NHERE:
8566         case NXHERE:
8567                 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8568                 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8569                 break;
8570         case NNOT:
8571                 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8572                 break;
8573         };
8574         return funcblocksize;
8575 }
8576
8577 static char *
8578 nodeckstrdup(char *s)
8579 {
8580         funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8581         return strcpy(funcstring_end, s);
8582 }
8583
8584 static union node *copynode(union node *);
8585
8586 static struct nodelist *
8587 copynodelist(struct nodelist *lp)
8588 {
8589         struct nodelist *start;
8590         struct nodelist **lpp;
8591
8592         lpp = &start;
8593         while (lp) {
8594                 *lpp = funcblock;
8595                 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8596                 (*lpp)->n = copynode(lp->n);
8597                 lp = lp->next;
8598                 lpp = &(*lpp)->next;
8599         }
8600         *lpp = NULL;
8601         return start;
8602 }
8603
8604 static union node *
8605 copynode(union node *n)
8606 {
8607         union node *new;
8608
8609         if (n == NULL)
8610                 return NULL;
8611         new = funcblock;
8612         funcblock = (char *) funcblock + nodesize[n->type];
8613
8614         switch (n->type) {
8615         case NCMD:
8616                 new->ncmd.redirect = copynode(n->ncmd.redirect);
8617                 new->ncmd.args = copynode(n->ncmd.args);
8618                 new->ncmd.assign = copynode(n->ncmd.assign);
8619                 break;
8620         case NPIPE:
8621                 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8622                 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8623                 break;
8624         case NREDIR:
8625         case NBACKGND:
8626         case NSUBSHELL:
8627                 new->nredir.redirect = copynode(n->nredir.redirect);
8628                 new->nredir.n = copynode(n->nredir.n);
8629                 break;
8630         case NAND:
8631         case NOR:
8632         case NSEMI:
8633         case NWHILE:
8634         case NUNTIL:
8635                 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8636                 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8637                 break;
8638         case NIF:
8639                 new->nif.elsepart = copynode(n->nif.elsepart);
8640                 new->nif.ifpart = copynode(n->nif.ifpart);
8641                 new->nif.test = copynode(n->nif.test);
8642                 break;
8643         case NFOR:
8644                 new->nfor.var = nodeckstrdup(n->nfor.var);
8645                 new->nfor.body = copynode(n->nfor.body);
8646                 new->nfor.args = copynode(n->nfor.args);
8647                 break;
8648         case NCASE:
8649                 new->ncase.cases = copynode(n->ncase.cases);
8650                 new->ncase.expr = copynode(n->ncase.expr);
8651                 break;
8652         case NCLIST:
8653                 new->nclist.body = copynode(n->nclist.body);
8654                 new->nclist.pattern = copynode(n->nclist.pattern);
8655                 new->nclist.next = copynode(n->nclist.next);
8656                 break;
8657         case NDEFUN:
8658         case NARG:
8659                 new->narg.backquote = copynodelist(n->narg.backquote);
8660                 new->narg.text = nodeckstrdup(n->narg.text);
8661                 new->narg.next = copynode(n->narg.next);
8662                 break;
8663         case NTO:
8664 #if BASH_REDIR_OUTPUT
8665         case NTO2:
8666 #endif
8667         case NCLOBBER:
8668         case NFROM:
8669         case NFROMTO:
8670         case NAPPEND:
8671                 new->nfile.fname = copynode(n->nfile.fname);
8672                 new->nfile.fd = n->nfile.fd;
8673                 new->nfile.next = copynode(n->nfile.next);
8674                 break;
8675         case NTOFD:
8676         case NFROMFD:
8677                 new->ndup.vname = copynode(n->ndup.vname);
8678                 new->ndup.dupfd = n->ndup.dupfd;
8679                 new->ndup.fd = n->ndup.fd;
8680                 new->ndup.next = copynode(n->ndup.next);
8681                 break;
8682         case NHERE:
8683         case NXHERE:
8684                 new->nhere.doc = copynode(n->nhere.doc);
8685                 new->nhere.fd = n->nhere.fd;
8686                 new->nhere.next = copynode(n->nhere.next);
8687                 break;
8688         case NNOT:
8689                 new->nnot.com = copynode(n->nnot.com);
8690                 break;
8691         };
8692         new->type = n->type;
8693         return new;
8694 }
8695
8696 /*
8697  * Make a copy of a parse tree.
8698  */
8699 static struct funcnode *
8700 copyfunc(union node *n)
8701 {
8702         struct funcnode *f;
8703         size_t blocksize;
8704
8705         /*funcstringsize = 0;*/
8706         blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8707         f = ckzalloc(blocksize /* + funcstringsize */);
8708         funcblock = (char *) f + offsetof(struct funcnode, n);
8709         funcstring_end = (char *) f + blocksize;
8710         copynode(n);
8711         /* f->count = 0; - ckzalloc did it */
8712         return f;
8713 }
8714
8715 /*
8716  * Define a shell function.
8717  */
8718 static void
8719 defun(union node *func)
8720 {
8721         struct cmdentry entry;
8722
8723         INT_OFF;
8724         entry.cmdtype = CMDFUNCTION;
8725         entry.u.func = copyfunc(func);
8726         addcmdentry(func->narg.text, &entry);
8727         INT_ON;
8728 }
8729
8730 /* Reasons for skipping commands (see comment on breakcmd routine) */
8731 #define SKIPBREAK      (1 << 0)
8732 #define SKIPCONT       (1 << 1)
8733 #define SKIPFUNC       (1 << 2)
8734 static smallint evalskip;       /* set to SKIPxxx if we are skipping commands */
8735 static int skipcount;           /* number of levels to skip */
8736 static int funcnest;            /* depth of function calls */
8737 static int loopnest;            /* current loop nesting level */
8738
8739 /* Forward decl way out to parsing code - dotrap needs it */
8740 static int evalstring(char *s, int flags);
8741
8742 /* Called to execute a trap.
8743  * Single callsite - at the end of evaltree().
8744  * If we return non-zero, evaltree raises EXEXIT exception.
8745  *
8746  * Perhaps we should avoid entering new trap handlers
8747  * while we are executing a trap handler. [is it a TODO?]
8748  */
8749 static void
8750 dotrap(void)
8751 {
8752         uint8_t *g;
8753         int sig;
8754         uint8_t last_status;
8755
8756         if (!pending_sig)
8757                 return;
8758
8759         last_status = exitstatus;
8760         pending_sig = 0;
8761         barrier();
8762
8763         TRACE(("dotrap entered\n"));
8764         for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8765                 char *p;
8766
8767                 if (!*g)
8768                         continue;
8769
8770                 if (evalskip) {
8771                         pending_sig = sig;
8772                         break;
8773                 }
8774
8775                 p = trap[sig];
8776                 /* non-trapped SIGINT is handled separately by raise_interrupt,
8777                  * don't upset it by resetting gotsig[SIGINT-1] */
8778                 if (sig == SIGINT && !p)
8779                         continue;
8780
8781                 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8782                 *g = 0;
8783                 if (!p)
8784                         continue;
8785                 evalstring(p, 0);
8786         }
8787         exitstatus = last_status;
8788         TRACE(("dotrap returns\n"));
8789 }
8790
8791 /* forward declarations - evaluation is fairly recursive business... */
8792 static int evalloop(union node *, int);
8793 static int evalfor(union node *, int);
8794 static int evalcase(union node *, int);
8795 static int evalsubshell(union node *, int);
8796 static void expredir(union node *);
8797 static int evalpipe(union node *, int);
8798 static int evalcommand(union node *, int);
8799 static int evalbltin(const struct builtincmd *, int, char **, int);
8800 static void prehash(union node *);
8801
8802 /*
8803  * Evaluate a parse tree.  The value is left in the global variable
8804  * exitstatus.
8805  */
8806 static int
8807 evaltree(union node *n, int flags)
8808 {
8809         int checkexit = 0;
8810         int (*evalfn)(union node *, int);
8811         int status = 0;
8812
8813         if (n == NULL) {
8814                 TRACE(("evaltree(NULL) called\n"));
8815                 goto out;
8816         }
8817         TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8818
8819         dotrap();
8820
8821         switch (n->type) {
8822         default:
8823 #if DEBUG
8824                 out1fmt("Node type = %d\n", n->type);
8825                 fflush_all();
8826                 break;
8827 #endif
8828         case NNOT:
8829                 status = !evaltree(n->nnot.com, EV_TESTED);
8830                 goto setstatus;
8831         case NREDIR:
8832                 expredir(n->nredir.redirect);
8833                 pushredir(n->nredir.redirect);
8834                 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8835                 if (!status) {
8836                         status = evaltree(n->nredir.n, flags & EV_TESTED);
8837                 }
8838                 if (n->nredir.redirect)
8839                         popredir(/*drop:*/ 0);
8840                 goto setstatus;
8841         case NCMD:
8842                 evalfn = evalcommand;
8843  checkexit:
8844                 if (eflag && !(flags & EV_TESTED))
8845                         checkexit = ~0;
8846                 goto calleval;
8847         case NFOR:
8848                 evalfn = evalfor;
8849                 goto calleval;
8850         case NWHILE:
8851         case NUNTIL:
8852                 evalfn = evalloop;
8853                 goto calleval;
8854         case NSUBSHELL:
8855         case NBACKGND:
8856                 evalfn = evalsubshell;
8857                 goto checkexit;
8858         case NPIPE:
8859                 evalfn = evalpipe;
8860                 goto checkexit;
8861         case NCASE:
8862                 evalfn = evalcase;
8863                 goto calleval;
8864         case NAND:
8865         case NOR:
8866         case NSEMI: {
8867
8868 #if NAND + 1 != NOR
8869 #error NAND + 1 != NOR
8870 #endif
8871 #if NOR + 1 != NSEMI
8872 #error NOR + 1 != NSEMI
8873 #endif
8874                 unsigned is_or = n->type - NAND;
8875                 status = evaltree(
8876                         n->nbinary.ch1,
8877                         (flags | ((is_or >> 1) - 1)) & EV_TESTED
8878                 );
8879                 if ((!status) == is_or || evalskip)
8880                         break;
8881                 n = n->nbinary.ch2;
8882  evaln:
8883                 evalfn = evaltree;
8884  calleval:
8885                 status = evalfn(n, flags);
8886                 goto setstatus;
8887         }
8888         case NIF:
8889                 status = evaltree(n->nif.test, EV_TESTED);
8890                 if (evalskip)
8891                         break;
8892                 if (!status) {
8893                         n = n->nif.ifpart;
8894                         goto evaln;
8895                 }
8896                 if (n->nif.elsepart) {
8897                         n = n->nif.elsepart;
8898                         goto evaln;
8899                 }
8900                 status = 0;
8901                 goto setstatus;
8902         case NDEFUN:
8903                 defun(n);
8904                 /* Not necessary. To test it:
8905                  * "false; f() { qwerty; }; echo $?" should print 0.
8906                  */
8907                 /* status = 0; */
8908  setstatus:
8909                 exitstatus = status;
8910                 break;
8911         }
8912  out:
8913         /* Order of checks below is important:
8914          * signal handlers trigger before exit caused by "set -e".
8915          */
8916         dotrap();
8917
8918         if (checkexit & status)
8919                 raise_exception(EXEXIT);
8920         if (flags & EV_EXIT)
8921                 raise_exception(EXEXIT);
8922
8923         TRACE(("leaving evaltree (no interrupts)\n"));
8924         return exitstatus;
8925 }
8926
8927 static int
8928 skiploop(void)
8929 {
8930         int skip = evalskip;
8931
8932         switch (skip) {
8933         case 0:
8934                 break;
8935         case SKIPBREAK:
8936         case SKIPCONT:
8937                 if (--skipcount <= 0) {
8938                         evalskip = 0;
8939                         break;
8940                 }
8941                 skip = SKIPBREAK;
8942                 break;
8943         }
8944         return skip;
8945 }
8946
8947 static int
8948 evalloop(union node *n, int flags)
8949 {
8950         int skip;
8951         int status;
8952
8953         loopnest++;
8954         status = 0;
8955         flags &= EV_TESTED;
8956         do {
8957                 int i;
8958
8959                 i = evaltree(n->nbinary.ch1, EV_TESTED);
8960                 skip = skiploop();
8961                 if (skip == SKIPFUNC)
8962                         status = i;
8963                 if (skip)
8964                         continue;
8965                 if (n->type != NWHILE)
8966                         i = !i;
8967                 if (i != 0)
8968                         break;
8969                 status = evaltree(n->nbinary.ch2, flags);
8970                 skip = skiploop();
8971         } while (!(skip & ~SKIPCONT));
8972         loopnest--;
8973
8974         return status;
8975 }
8976
8977 static int
8978 evalfor(union node *n, int flags)
8979 {
8980         struct arglist arglist;
8981         union node *argp;
8982         struct strlist *sp;
8983         struct stackmark smark;
8984         int status = 0;
8985
8986         setstackmark(&smark);
8987         arglist.list = NULL;
8988         arglist.lastp = &arglist.list;
8989         for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8990                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8991         }
8992         *arglist.lastp = NULL;
8993
8994         loopnest++;
8995         flags &= EV_TESTED;
8996         for (sp = arglist.list; sp; sp = sp->next) {
8997                 setvar0(n->nfor.var, sp->text);
8998                 status = evaltree(n->nfor.body, flags);
8999                 if (skiploop() & ~SKIPCONT)
9000                         break;
9001         }
9002         loopnest--;
9003         popstackmark(&smark);
9004
9005         return status;
9006 }
9007
9008 static int
9009 evalcase(union node *n, int flags)
9010 {
9011         union node *cp;
9012         union node *patp;
9013         struct arglist arglist;
9014         struct stackmark smark;
9015         int status = 0;
9016
9017         setstackmark(&smark);
9018         arglist.list = NULL;
9019         arglist.lastp = &arglist.list;
9020         expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9021         for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9022                 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9023                         if (casematch(patp, arglist.list->text)) {
9024                                 /* Ensure body is non-empty as otherwise
9025                                  * EV_EXIT may prevent us from setting the
9026                                  * exit status.
9027                                  */
9028                                 if (evalskip == 0 && cp->nclist.body) {
9029                                         status = evaltree(cp->nclist.body, flags);
9030                                 }
9031                                 goto out;
9032                         }
9033                 }
9034         }
9035  out:
9036         popstackmark(&smark);
9037
9038         return status;
9039 }
9040
9041 /*
9042  * Kick off a subshell to evaluate a tree.
9043  */
9044 static int
9045 evalsubshell(union node *n, int flags)
9046 {
9047         struct job *jp;
9048         int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9049         int status;
9050
9051         expredir(n->nredir.redirect);
9052         if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9053                 goto nofork;
9054         INT_OFF;
9055         if (backgnd == FORK_FG)
9056                 get_tty_state();
9057         jp = makejob(/*n,*/ 1);
9058         if (forkshell(jp, n, backgnd) == 0) {
9059                 /* child */
9060                 INT_ON;
9061                 flags |= EV_EXIT;
9062                 if (backgnd)
9063                         flags &= ~EV_TESTED;
9064  nofork:
9065                 redirect(n->nredir.redirect, 0);
9066                 evaltreenr(n->nredir.n, flags);
9067                 /* never returns */
9068         }
9069         /* parent */
9070         status = 0;
9071         if (backgnd == FORK_FG)
9072                 status = waitforjob(jp);
9073         INT_ON;
9074         return status;
9075 }
9076
9077 /*
9078  * Compute the names of the files in a redirection list.
9079  */
9080 static void fixredir(union node *, const char *, int);
9081 static void
9082 expredir(union node *n)
9083 {
9084         union node *redir;
9085
9086         for (redir = n; redir; redir = redir->nfile.next) {
9087                 struct arglist fn;
9088
9089                 fn.list = NULL;
9090                 fn.lastp = &fn.list;
9091                 switch (redir->type) {
9092                 case NFROMTO:
9093                 case NFROM:
9094                 case NTO:
9095 #if BASH_REDIR_OUTPUT
9096                 case NTO2:
9097 #endif
9098                 case NCLOBBER:
9099                 case NAPPEND:
9100                         expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9101                         TRACE(("expredir expanded to '%s'\n", fn.list->text));
9102 #if BASH_REDIR_OUTPUT
9103  store_expfname:
9104 #endif
9105 #if 0
9106 // By the design of stack allocator, the loop of this kind:
9107 //      while true; do while true; do break; done </dev/null; done
9108 // will look like a memory leak: ash plans to free expfname's
9109 // of "/dev/null" as soon as it finishes running the loop
9110 // (in this case, never).
9111 // This "fix" is wrong:
9112                         if (redir->nfile.expfname)
9113                                 stunalloc(redir->nfile.expfname);
9114 // It results in corrupted state of stacked allocations.
9115 #endif
9116                         redir->nfile.expfname = fn.list->text;
9117                         break;
9118                 case NFROMFD:
9119                 case NTOFD: /* >& */
9120                         if (redir->ndup.vname) {
9121                                 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9122                                 if (fn.list == NULL)
9123                                         ash_msg_and_raise_error("redir error");
9124 #if BASH_REDIR_OUTPUT
9125 //FIXME: we used expandarg with different args!
9126                                 if (!isdigit_str9(fn.list->text)) {
9127                                         /* >&file, not >&fd */
9128                                         if (redir->nfile.fd != 1) /* 123>&file - BAD */
9129                                                 ash_msg_and_raise_error("redir error");
9130                                         redir->type = NTO2;
9131                                         goto store_expfname;
9132                                 }
9133 #endif
9134                                 fixredir(redir, fn.list->text, 1);
9135                         }
9136                         break;
9137                 }
9138         }
9139 }
9140
9141 /*
9142  * Evaluate a pipeline.  All the processes in the pipeline are children
9143  * of the process creating the pipeline.  (This differs from some versions
9144  * of the shell, which make the last process in a pipeline the parent
9145  * of all the rest.)
9146  */
9147 static int
9148 evalpipe(union node *n, int flags)
9149 {
9150         struct job *jp;
9151         struct nodelist *lp;
9152         int pipelen;
9153         int prevfd;
9154         int pip[2];
9155         int status = 0;
9156
9157         TRACE(("evalpipe(0x%lx) called\n", (long)n));
9158         pipelen = 0;
9159         for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9160                 pipelen++;
9161         flags |= EV_EXIT;
9162         INT_OFF;
9163         if (n->npipe.pipe_backgnd == 0)
9164                 get_tty_state();
9165         jp = makejob(/*n,*/ pipelen);
9166         prevfd = -1;
9167         for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9168                 prehash(lp->n);
9169                 pip[1] = -1;
9170                 if (lp->next) {
9171                         if (pipe(pip) < 0) {
9172                                 close(prevfd);
9173                                 ash_msg_and_raise_error("pipe call failed");
9174                         }
9175                 }
9176                 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9177                         /* child */
9178                         INT_ON;
9179                         if (pip[1] >= 0) {
9180                                 close(pip[0]);
9181                         }
9182                         if (prevfd > 0) {
9183                                 dup2(prevfd, 0);
9184                                 close(prevfd);
9185                         }
9186                         if (pip[1] > 1) {
9187                                 dup2(pip[1], 1);
9188                                 close(pip[1]);
9189                         }
9190                         evaltreenr(lp->n, flags);
9191                         /* never returns */
9192                 }
9193                 /* parent */
9194                 if (prevfd >= 0)
9195                         close(prevfd);
9196                 prevfd = pip[0];
9197                 /* Don't want to trigger debugging */
9198                 if (pip[1] != -1)
9199                         close(pip[1]);
9200         }
9201         if (n->npipe.pipe_backgnd == 0) {
9202                 status = waitforjob(jp);
9203                 TRACE(("evalpipe:  job done exit status %d\n", status));
9204         }
9205         INT_ON;
9206
9207         return status;
9208 }
9209
9210 /*
9211  * Controls whether the shell is interactive or not.
9212  */
9213 static void
9214 setinteractive(int on)
9215 {
9216         static smallint is_interactive;
9217
9218         if (++on == is_interactive)
9219                 return;
9220         is_interactive = on;
9221         setsignal(SIGINT);
9222         setsignal(SIGQUIT);
9223         setsignal(SIGTERM);
9224 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9225         if (is_interactive > 1) {
9226                 /* Looks like they want an interactive shell */
9227                 static smallint did_banner;
9228
9229                 if (!did_banner) {
9230                         /* note: ash and hush share this string */
9231                         out1fmt("\n\n%s %s\n"
9232                                 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9233                                 "\n",
9234                                 bb_banner,
9235                                 "built-in shell (ash)"
9236                         );
9237                         did_banner = 1;
9238                 }
9239         }
9240 #endif
9241 }
9242
9243 static void
9244 optschanged(void)
9245 {
9246 #if DEBUG
9247         opentrace();
9248 #endif
9249         setinteractive(iflag);
9250         setjobctl(mflag);
9251 #if ENABLE_FEATURE_EDITING_VI
9252         if (viflag)
9253                 line_input_state->flags |= VI_MODE;
9254         else
9255                 line_input_state->flags &= ~VI_MODE;
9256 #else
9257         viflag = 0; /* forcibly keep the option off */
9258 #endif
9259 }
9260
9261 struct localvar_list {
9262         struct localvar_list *next;
9263         struct localvar *lv;
9264 };
9265
9266 static struct localvar_list *localvar_stack;
9267
9268 /*
9269  * Called after a function returns.
9270  * Interrupts must be off.
9271  */
9272 static void
9273 poplocalvars(int keep)
9274 {
9275         struct localvar_list *ll;
9276         struct localvar *lvp, *next;
9277         struct var *vp;
9278
9279         INT_OFF;
9280         ll = localvar_stack;
9281         localvar_stack = ll->next;
9282
9283         next = ll->lv;
9284         free(ll);
9285
9286         while ((lvp = next) != NULL) {
9287                 next = lvp->next;
9288                 vp = lvp->vp;
9289                 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9290                 if (keep) {
9291                         int bits = VSTRFIXED;
9292
9293                         if (lvp->flags != VUNSET) {
9294                                 if (vp->var_text == lvp->text)
9295                                         bits |= VTEXTFIXED;
9296                                 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9297                                         free((char*)lvp->text);
9298                         }
9299
9300                         vp->flags &= ~bits;
9301                         vp->flags |= (lvp->flags & bits);
9302
9303                         if ((vp->flags &
9304                              (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9305                                 unsetvar(vp->var_text);
9306                 } else if (vp == NULL) {        /* $- saved */
9307                         memcpy(optlist, lvp->text, sizeof(optlist));
9308                         free((char*)lvp->text);
9309                         optschanged();
9310                 } else if (lvp->flags == VUNSET) {
9311                         vp->flags &= ~(VSTRFIXED|VREADONLY);
9312                         unsetvar(vp->var_text);
9313                 } else {
9314                         if (vp->var_func)
9315                                 vp->var_func(var_end(lvp->text));
9316                         if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9317                                 free((char*)vp->var_text);
9318                         vp->flags = lvp->flags;
9319                         vp->var_text = lvp->text;
9320                 }
9321                 free(lvp);
9322         }
9323         INT_ON;
9324 }
9325
9326 /*
9327  * Create a new localvar environment.
9328  */
9329 static struct localvar_list *
9330 pushlocalvars(void)
9331 {
9332         struct localvar_list *ll;
9333
9334         INT_OFF;
9335         ll = ckzalloc(sizeof(*ll));
9336         /*ll->lv = NULL; - zalloc did it */
9337         ll->next = localvar_stack;
9338         localvar_stack = ll;
9339         INT_ON;
9340
9341         return ll->next;
9342 }
9343
9344 static void
9345 unwindlocalvars(struct localvar_list *stop)
9346 {
9347         while (localvar_stack != stop)
9348                 poplocalvars(0);
9349 }
9350
9351 static int
9352 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9353 {
9354         volatile struct shparam saveparam;
9355         struct jmploc *volatile savehandler;
9356         struct jmploc jmploc;
9357         int e;
9358
9359         saveparam = shellparam;
9360         savehandler = exception_handler;
9361         e = setjmp(jmploc.loc);
9362         if (e) {
9363                 goto funcdone;
9364         }
9365         INT_OFF;
9366         exception_handler = &jmploc;
9367         shellparam.malloced = 0;
9368         func->count++;
9369         funcnest++;
9370         INT_ON;
9371         shellparam.nparam = argc - 1;
9372         shellparam.p = argv + 1;
9373 #if ENABLE_ASH_GETOPTS
9374         shellparam.optind = 1;
9375         shellparam.optoff = -1;
9376 #endif
9377         pushlocalvars();
9378         evaltree(func->n.narg.next, flags & EV_TESTED);
9379         poplocalvars(0);
9380  funcdone:
9381         INT_OFF;
9382         funcnest--;
9383         freefunc(func);
9384         freeparam(&shellparam);
9385         shellparam = saveparam;
9386         exception_handler = savehandler;
9387         INT_ON;
9388         evalskip &= ~SKIPFUNC;
9389         return e;
9390 }
9391
9392 /*
9393  * Make a variable a local variable.  When a variable is made local, it's
9394  * value and flags are saved in a localvar structure.  The saved values
9395  * will be restored when the shell function returns.  We handle the name
9396  * "-" as a special case: it makes changes to "set +-options" local
9397  * (options will be restored on return from the function).
9398  */
9399 static void
9400 mklocal(char *name)
9401 {
9402         struct localvar *lvp;
9403         struct var **vpp;
9404         struct var *vp;
9405         char *eq = strchr(name, '=');
9406
9407         INT_OFF;
9408         /* Cater for duplicate "local". Examples:
9409          * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9410          * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9411          */
9412         lvp = localvar_stack->lv;
9413         while (lvp) {
9414                 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9415                         if (eq)
9416                                 setvareq(name, 0);
9417                         /* else:
9418                          * it's a duplicate "local VAR" declaration, do nothing
9419                          */
9420                         goto ret;
9421                 }
9422                 lvp = lvp->next;
9423         }
9424
9425         lvp = ckzalloc(sizeof(*lvp));
9426         if (LONE_DASH(name)) {
9427                 char *p;
9428                 p = ckmalloc(sizeof(optlist));
9429                 lvp->text = memcpy(p, optlist, sizeof(optlist));
9430                 vp = NULL;
9431         } else {
9432                 vpp = hashvar(name);
9433                 vp = *findvar(vpp, name);
9434                 if (vp == NULL) {
9435                         /* variable did not exist yet */
9436                         if (eq)
9437                                 vp = setvareq(name, VSTRFIXED);
9438                         else
9439                                 vp = setvar(name, NULL, VSTRFIXED);
9440                         lvp->flags = VUNSET;
9441                 } else {
9442                         lvp->text = vp->var_text;
9443                         lvp->flags = vp->flags;
9444                         /* make sure neither "struct var" nor string gets freed
9445                          * during (un)setting:
9446                          */
9447                         vp->flags |= VSTRFIXED|VTEXTFIXED;
9448                         if (eq)
9449                                 setvareq(name, 0);
9450                         else
9451                                 /* "local VAR" unsets VAR: */
9452                                 setvar0(name, NULL);
9453                 }
9454         }
9455         lvp->vp = vp;
9456         lvp->next = localvar_stack->lv;
9457         localvar_stack->lv = lvp;
9458  ret:
9459         INT_ON;
9460 }
9461
9462 /*
9463  * The "local" command.
9464  */
9465 static int FAST_FUNC
9466 localcmd(int argc UNUSED_PARAM, char **argv)
9467 {
9468         char *name;
9469
9470         if (!localvar_stack)
9471                 ash_msg_and_raise_error("not in a function");
9472
9473         argv = argptr;
9474         while ((name = *argv++) != NULL) {
9475                 mklocal(name);
9476         }
9477         return 0;
9478 }
9479
9480 static int FAST_FUNC
9481 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9482 {
9483         return 1;
9484 }
9485
9486 static int FAST_FUNC
9487 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9488 {
9489         return 0;
9490 }
9491
9492 static int FAST_FUNC
9493 execcmd(int argc UNUSED_PARAM, char **argv)
9494 {
9495         optionarg = NULL;
9496         while (nextopt("a:") != '\0')
9497                 /* nextopt() sets optionarg to "-a ARGV0" */;
9498
9499         argv = argptr;
9500         if (argv[0]) {
9501                 char *prog;
9502
9503                 iflag = 0;              /* exit on error */
9504                 mflag = 0;
9505                 optschanged();
9506                 /* We should set up signals for "exec CMD"
9507                  * the same way as for "CMD" without "exec".
9508                  * But optschanged->setinteractive->setsignal
9509                  * still thought we are a root shell. Therefore, for example,
9510                  * SIGQUIT is still set to IGN. Fix it:
9511                  */
9512                 shlvl++;
9513                 setsignal(SIGQUIT);
9514                 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9515                 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9516                 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9517
9518                 prog = argv[0];
9519                 if (optionarg)
9520                         argv[0] = optionarg;
9521                 shellexec(prog, argv, pathval(), 0);
9522                 /* NOTREACHED */
9523         }
9524         return 0;
9525 }
9526
9527 /*
9528  * The return command.
9529  */
9530 static int FAST_FUNC
9531 returncmd(int argc UNUSED_PARAM, char **argv)
9532 {
9533         /*
9534          * If called outside a function, do what ksh does;
9535          * skip the rest of the file.
9536          */
9537         evalskip = SKIPFUNC;
9538         return argv[1] ? number(argv[1]) : exitstatus;
9539 }
9540
9541 /* Forward declarations for builtintab[] */
9542 static int breakcmd(int, char **) FAST_FUNC;
9543 static int dotcmd(int, char **) FAST_FUNC;
9544 static int evalcmd(int, char **, int) FAST_FUNC;
9545 static int exitcmd(int, char **) FAST_FUNC;
9546 static int exportcmd(int, char **) FAST_FUNC;
9547 #if ENABLE_ASH_GETOPTS
9548 static int getoptscmd(int, char **) FAST_FUNC;
9549 #endif
9550 #if ENABLE_ASH_HELP
9551 static int helpcmd(int, char **) FAST_FUNC;
9552 #endif
9553 #if MAX_HISTORY
9554 static int historycmd(int, char **) FAST_FUNC;
9555 #endif
9556 #if ENABLE_FEATURE_SH_MATH
9557 static int letcmd(int, char **) FAST_FUNC;
9558 #endif
9559 static int readcmd(int, char **) FAST_FUNC;
9560 static int setcmd(int, char **) FAST_FUNC;
9561 static int shiftcmd(int, char **) FAST_FUNC;
9562 static int timescmd(int, char **) FAST_FUNC;
9563 static int trapcmd(int, char **) FAST_FUNC;
9564 static int umaskcmd(int, char **) FAST_FUNC;
9565 static int unsetcmd(int, char **) FAST_FUNC;
9566 static int ulimitcmd(int, char **) FAST_FUNC;
9567
9568 #define BUILTIN_NOSPEC          "0"
9569 #define BUILTIN_SPECIAL         "1"
9570 #define BUILTIN_REGULAR         "2"
9571 #define BUILTIN_SPEC_REG        "3"
9572 #define BUILTIN_ASSIGN          "4"
9573 #define BUILTIN_SPEC_ASSG       "5"
9574 #define BUILTIN_REG_ASSG        "6"
9575 #define BUILTIN_SPEC_REG_ASSG   "7"
9576
9577 /* Stubs for calling non-FAST_FUNC's */
9578 #if ENABLE_ASH_ECHO
9579 static int FAST_FUNC echocmd(int argc, char **argv)   { return echo_main(argc, argv); }
9580 #endif
9581 #if ENABLE_ASH_PRINTF
9582 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9583 #endif
9584 #if ENABLE_ASH_TEST || BASH_TEST2
9585 static int FAST_FUNC testcmd(int argc, char **argv)   { return test_main(argc, argv); }
9586 #endif
9587
9588 /* Keep these in proper order since it is searched via bsearch() */
9589 static const struct builtincmd builtintab[] = {
9590         { BUILTIN_SPEC_REG      "."       , dotcmd     },
9591         { BUILTIN_SPEC_REG      ":"       , truecmd    },
9592 #if ENABLE_ASH_TEST
9593         { BUILTIN_REGULAR       "["       , testcmd    },
9594 #endif
9595 #if BASH_TEST2
9596         { BUILTIN_REGULAR       "[["      , testcmd    },
9597 #endif
9598 #if ENABLE_ASH_ALIAS
9599         { BUILTIN_REG_ASSG      "alias"   , aliascmd   },
9600 #endif
9601 #if JOBS
9602         { BUILTIN_REGULAR       "bg"      , fg_bgcmd   },
9603 #endif
9604         { BUILTIN_SPEC_REG      "break"   , breakcmd   },
9605         { BUILTIN_REGULAR       "cd"      , cdcmd      },
9606         { BUILTIN_NOSPEC        "chdir"   , cdcmd      },
9607 #if ENABLE_ASH_CMDCMD
9608         { BUILTIN_REGULAR       "command" , commandcmd },
9609 #endif
9610         { BUILTIN_SPEC_REG      "continue", breakcmd   },
9611 #if ENABLE_ASH_ECHO
9612         { BUILTIN_REGULAR       "echo"    , echocmd    },
9613 #endif
9614         { BUILTIN_SPEC_REG      "eval"    , NULL       }, /*evalcmd() has a differing prototype*/
9615         { BUILTIN_SPEC_REG      "exec"    , execcmd    },
9616         { BUILTIN_SPEC_REG      "exit"    , exitcmd    },
9617         { BUILTIN_SPEC_REG_ASSG "export"  , exportcmd  },
9618         { BUILTIN_REGULAR       "false"   , falsecmd   },
9619 #if JOBS
9620         { BUILTIN_REGULAR       "fg"      , fg_bgcmd   },
9621 #endif
9622 #if ENABLE_ASH_GETOPTS
9623         { BUILTIN_REGULAR       "getopts" , getoptscmd },
9624 #endif
9625         { BUILTIN_NOSPEC        "hash"    , hashcmd    },
9626 #if ENABLE_ASH_HELP
9627         { BUILTIN_NOSPEC        "help"    , helpcmd    },
9628 #endif
9629 #if MAX_HISTORY
9630         { BUILTIN_NOSPEC        "history" , historycmd },
9631 #endif
9632 #if JOBS
9633         { BUILTIN_REGULAR       "jobs"    , jobscmd    },
9634         { BUILTIN_REGULAR       "kill"    , killcmd    },
9635 #endif
9636 #if ENABLE_FEATURE_SH_MATH
9637         { BUILTIN_NOSPEC        "let"     , letcmd     },
9638 #endif
9639         { BUILTIN_SPEC_REG_ASSG "local"   , localcmd   },
9640 #if ENABLE_ASH_PRINTF
9641         { BUILTIN_REGULAR       "printf"  , printfcmd  },
9642 #endif
9643         { BUILTIN_NOSPEC        "pwd"     , pwdcmd     },
9644         { BUILTIN_REGULAR       "read"    , readcmd    },
9645         { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd  },
9646         { BUILTIN_SPEC_REG      "return"  , returncmd  },
9647         { BUILTIN_SPEC_REG      "set"     , setcmd     },
9648         { BUILTIN_SPEC_REG      "shift"   , shiftcmd   },
9649 #if BASH_SOURCE
9650         { BUILTIN_SPEC_REG      "source"  , dotcmd     },
9651 #endif
9652 #if ENABLE_ASH_TEST
9653         { BUILTIN_REGULAR       "test"    , testcmd    },
9654 #endif
9655         { BUILTIN_SPEC_REG      "times"   , timescmd   },
9656         { BUILTIN_SPEC_REG      "trap"    , trapcmd    },
9657         { BUILTIN_REGULAR       "true"    , truecmd    },
9658         { BUILTIN_NOSPEC        "type"    , typecmd    },
9659         { BUILTIN_NOSPEC        "ulimit"  , ulimitcmd  },
9660         { BUILTIN_REGULAR       "umask"   , umaskcmd   },
9661 #if ENABLE_ASH_ALIAS
9662         { BUILTIN_REGULAR       "unalias" , unaliascmd },
9663 #endif
9664         { BUILTIN_SPEC_REG      "unset"   , unsetcmd   },
9665         { BUILTIN_REGULAR       "wait"    , waitcmd    },
9666 };
9667
9668 /* Should match the above table! */
9669 #define COMMANDCMD (builtintab + \
9670         /* . : */       2 + \
9671         /* [ */         1 * ENABLE_ASH_TEST + \
9672         /* [[ */        1 * BASH_TEST2 + \
9673         /* alias */     1 * ENABLE_ASH_ALIAS + \
9674         /* bg */        1 * ENABLE_ASH_JOB_CONTROL + \
9675         /* break cd cddir  */   3)
9676 #define EVALCMD (COMMANDCMD + \
9677         /* command */   1 * ENABLE_ASH_CMDCMD + \
9678         /* continue */  1 + \
9679         /* echo */      1 * ENABLE_ASH_ECHO + \
9680         0)
9681 #define EXECCMD (EVALCMD + \
9682         /* eval */      1)
9683
9684 /*
9685  * Search the table of builtin commands.
9686  */
9687 static int
9688 pstrcmp1(const void *a, const void *b)
9689 {
9690         return strcmp((char*)a, *(char**)b + 1);
9691 }
9692 static struct builtincmd *
9693 find_builtin(const char *name)
9694 {
9695         struct builtincmd *bp;
9696
9697         bp = bsearch(
9698                 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9699                 pstrcmp1
9700         );
9701         return bp;
9702 }
9703
9704 /*
9705  * Execute a simple command.
9706  */
9707 static int
9708 isassignment(const char *p)
9709 {
9710         const char *q = endofname(p);
9711         if (p == q)
9712                 return 0;
9713         return *q == '=';
9714 }
9715 static int FAST_FUNC
9716 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9717 {
9718         /* Preserve exitstatus of a previous possible redirection
9719          * as POSIX mandates */
9720         return back_exitstatus;
9721 }
9722 static int
9723 evalcommand(union node *cmd, int flags)
9724 {
9725         static const struct builtincmd null_bltin = {
9726                 "\0\0", bltincmd /* why three NULs? */
9727         };
9728         struct localvar_list *localvar_stop;
9729         struct redirtab *redir_stop;
9730         struct stackmark smark;
9731         union node *argp;
9732         struct arglist arglist;
9733         struct arglist varlist;
9734         char **argv;
9735         int argc;
9736         const struct strlist *sp;
9737         struct cmdentry cmdentry;
9738         struct job *jp;
9739         char *lastarg;
9740         const char *path;
9741         int spclbltin;
9742         int status;
9743         char **nargv;
9744         smallint cmd_is_exec;
9745
9746         /* First expand the arguments. */
9747         TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9748         setstackmark(&smark);
9749         localvar_stop = pushlocalvars();
9750         back_exitstatus = 0;
9751
9752         cmdentry.cmdtype = CMDBUILTIN;
9753         cmdentry.u.cmd = &null_bltin;
9754         varlist.lastp = &varlist.list;
9755         *varlist.lastp = NULL;
9756         arglist.lastp = &arglist.list;
9757         *arglist.lastp = NULL;
9758
9759         argc = 0;
9760         if (cmd->ncmd.args) {
9761                 struct builtincmd *bcmd;
9762                 smallint pseudovarflag;
9763
9764                 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9765                 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9766
9767                 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9768                         struct strlist **spp;
9769
9770                         spp = arglist.lastp;
9771                         if (pseudovarflag && isassignment(argp->narg.text))
9772                                 expandarg(argp, &arglist, EXP_VARTILDE);
9773                         else
9774                                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9775
9776                         for (sp = *spp; sp; sp = sp->next)
9777                                 argc++;
9778                 }
9779         }
9780
9781         /* Reserve one extra spot at the front for shellexec. */
9782         nargv = stalloc(sizeof(char *) * (argc + 2));
9783         argv = ++nargv;
9784         for (sp = arglist.list; sp; sp = sp->next) {
9785                 TRACE(("evalcommand arg: %s\n", sp->text));
9786                 *nargv++ = sp->text;
9787         }
9788         *nargv = NULL;
9789
9790         lastarg = NULL;
9791         if (iflag && funcnest == 0 && argc > 0)
9792                 lastarg = nargv[-1];
9793
9794         expredir(cmd->ncmd.redirect);
9795         redir_stop = pushredir(cmd->ncmd.redirect);
9796         preverrout_fd = 2;
9797         status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9798
9799         path = vpath.var_text;
9800         for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9801                 struct strlist **spp;
9802                 char *p;
9803
9804                 spp = varlist.lastp;
9805                 expandarg(argp, &varlist, EXP_VARTILDE);
9806
9807                 mklocal((*spp)->text);
9808
9809                 /*
9810                  * Modify the command lookup path, if a PATH= assignment
9811                  * is present
9812                  */
9813                 p = (*spp)->text;
9814                 if (varcmp(p, path) == 0)
9815                         path = p;
9816         }
9817
9818         /* Print the command if xflag is set. */
9819         if (xflag) {
9820                 const char *pfx = "";
9821
9822                 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9823
9824                 sp = varlist.list;
9825                 while (sp) {
9826                         char *varval = sp->text;
9827                         char *eq = strchrnul(varval, '=');
9828                         if (*eq)
9829                                 eq++;
9830                         fdprintf(preverrout_fd, "%s%.*s%s",
9831                                 pfx,
9832                                 (int)(eq - varval), varval,
9833                                 maybe_single_quote(eq)
9834                         );
9835                         sp = sp->next;
9836                         pfx = " ";
9837                 }
9838
9839                 sp = arglist.list;
9840                 while (sp) {
9841                         fdprintf(preverrout_fd, "%s%s",
9842                                 pfx,
9843                                 /* always quote if matches reserved word: */
9844                                 findkwd(sp->text)
9845                                 ? single_quote(sp->text)
9846                                 : maybe_single_quote(sp->text)
9847                         );
9848                         sp = sp->next;
9849                         pfx = " ";
9850                 }
9851                 safe_write(preverrout_fd, "\n", 1);
9852         }
9853
9854         cmd_is_exec = 0;
9855         spclbltin = -1;
9856
9857         /* Now locate the command. */
9858         if (argc) {
9859                 int cmd_flag = DO_ERR;
9860 #if ENABLE_ASH_CMDCMD
9861                 const char *oldpath = path + 5;
9862 #endif
9863                 path += 5;
9864                 for (;;) {
9865                         find_command(argv[0], &cmdentry, cmd_flag, path);
9866                         if (cmdentry.cmdtype == CMDUNKNOWN) {
9867                                 flush_stdout_stderr();
9868                                 status = 127;
9869                                 goto bail;
9870                         }
9871
9872                         /* implement bltin and command here */
9873                         if (cmdentry.cmdtype != CMDBUILTIN)
9874                                 break;
9875                         if (spclbltin < 0)
9876                                 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9877                         if (cmdentry.u.cmd == EXECCMD)
9878                                 cmd_is_exec = 1;
9879 #if ENABLE_ASH_CMDCMD
9880                         if (cmdentry.u.cmd == COMMANDCMD) {
9881                                 path = oldpath;
9882                                 nargv = parse_command_args(argv, &path);
9883                                 if (!nargv)
9884                                         break;
9885                                 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9886                                  * nargv => "PROG". path is updated if -p.
9887                                  */
9888                                 argc -= nargv - argv;
9889                                 argv = nargv;
9890                                 cmd_flag |= DO_NOFUNC;
9891                         } else
9892 #endif
9893                                 break;
9894                 }
9895         }
9896
9897         if (status) {
9898  bail:
9899                 exitstatus = status;
9900
9901                 /* We have a redirection error. */
9902                 if (spclbltin > 0)
9903                         raise_exception(EXERROR);
9904
9905                 goto out;
9906         }
9907
9908         /* Execute the command. */
9909         switch (cmdentry.cmdtype) {
9910         default: {
9911
9912 #if ENABLE_FEATURE_SH_NOFORK
9913 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9914  *     around run_nofork_applet() call.
9915  * (2) Should this check also be done in forkshell()?
9916  *     (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9917  */
9918                 /* find_command() encodes applet_no as (-2 - applet_no) */
9919                 int applet_no = (- cmdentry.u.index - 2);
9920                 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9921                         listsetvar(varlist.list, VEXPORT|VSTACK);
9922                         /* run <applet>_main() */
9923                         status = run_nofork_applet(applet_no, argv);
9924                         break;
9925                 }
9926 #endif
9927                 /* Can we avoid forking off? For example, very last command
9928                  * in a script or a subshell does not need forking,
9929                  * we can just exec it.
9930                  */
9931                 if (!(flags & EV_EXIT) || may_have_traps) {
9932                         /* No, forking off a child is necessary */
9933                         INT_OFF;
9934                         get_tty_state();
9935                         jp = makejob(/*cmd,*/ 1);
9936                         if (forkshell(jp, cmd, FORK_FG) != 0) {
9937                                 /* parent */
9938                                 status = waitforjob(jp);
9939                                 INT_ON;
9940                                 TRACE(("forked child exited with %d\n", status));
9941                                 break;
9942                         }
9943                         /* child */
9944                         FORCE_INT_ON;
9945                         /* fall through to exec'ing external program */
9946                 }
9947                 listsetvar(varlist.list, VEXPORT|VSTACK);
9948                 shellexec(argv[0], argv, path, cmdentry.u.index);
9949                 /* NOTREACHED */
9950         } /* default */
9951         case CMDBUILTIN:
9952                 if (spclbltin > 0 || argc == 0) {
9953                         poplocalvars(1);
9954                         if (cmd_is_exec && argc > 1)
9955                                 listsetvar(varlist.list, VEXPORT);
9956                 }
9957
9958                 /* Tight loop with builtins only:
9959                  * "while kill -0 $child; do true; done"
9960                  * will never exit even if $child died, unless we do this
9961                  * to reap the zombie and make kill detect that it's gone: */
9962                 dowait(DOWAIT_NONBLOCK, NULL);
9963
9964                 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9965                         if (exception_type == EXERROR && spclbltin <= 0) {
9966                                 FORCE_INT_ON;
9967                                 goto readstatus;
9968                         }
9969  raise:
9970                         longjmp(exception_handler->loc, 1);
9971                 }
9972                 goto readstatus;
9973
9974         case CMDFUNCTION:
9975                 poplocalvars(1);
9976                 /* See above for the rationale */
9977                 dowait(DOWAIT_NONBLOCK, NULL);
9978                 if (evalfun(cmdentry.u.func, argc, argv, flags))
9979                         goto raise;
9980  readstatus:
9981                 status = exitstatus;
9982                 break;
9983         } /* switch */
9984
9985  out:
9986         if (cmd->ncmd.redirect)
9987                 popredir(/*drop:*/ cmd_is_exec);
9988         unwindredir(redir_stop);
9989         unwindlocalvars(localvar_stop);
9990         if (lastarg) {
9991                 /* dsl: I think this is intended to be used to support
9992                  * '_' in 'vi' command mode during line editing...
9993                  * However I implemented that within libedit itself.
9994                  */
9995                 setvar0("_", lastarg);
9996         }
9997         popstackmark(&smark);
9998
9999         return status;
10000 }
10001
10002 static int
10003 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10004 {
10005         char *volatile savecmdname;
10006         struct jmploc *volatile savehandler;
10007         struct jmploc jmploc;
10008         int status;
10009         int i;
10010
10011         savecmdname = commandname;
10012         savehandler = exception_handler;
10013         i = setjmp(jmploc.loc);
10014         if (i)
10015                 goto cmddone;
10016         exception_handler = &jmploc;
10017         commandname = argv[0];
10018         argptr = argv + 1;
10019         optptr = NULL;                  /* initialize nextopt */
10020         if (cmd == EVALCMD)
10021                 status = evalcmd(argc, argv, flags);
10022         else
10023                 status = (*cmd->builtin)(argc, argv);
10024         flush_stdout_stderr();
10025         status |= ferror(stdout);
10026         exitstatus = status;
10027  cmddone:
10028         clearerr(stdout);
10029         commandname = savecmdname;
10030         exception_handler = savehandler;
10031
10032         return i;
10033 }
10034
10035 static int
10036 goodname(const char *p)
10037 {
10038         return endofname(p)[0] == '\0';
10039 }
10040
10041
10042 /*
10043  * Search for a command.  This is called before we fork so that the
10044  * location of the command will be available in the parent as well as
10045  * the child.  The check for "goodname" is an overly conservative
10046  * check that the name will not be subject to expansion.
10047  */
10048 static void
10049 prehash(union node *n)
10050 {
10051         struct cmdentry entry;
10052
10053         if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10054                 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10055 }
10056
10057
10058 /* ============ Builtin commands
10059  *
10060  * Builtin commands whose functions are closely tied to evaluation
10061  * are implemented here.
10062  */
10063
10064 /*
10065  * Handle break and continue commands.  Break, continue, and return are
10066  * all handled by setting the evalskip flag.  The evaluation routines
10067  * above all check this flag, and if it is set they start skipping
10068  * commands rather than executing them.  The variable skipcount is
10069  * the number of loops to break/continue, or the number of function
10070  * levels to return.  (The latter is always 1.)  It should probably
10071  * be an error to break out of more loops than exist, but it isn't
10072  * in the standard shell so we don't make it one here.
10073  */
10074 static int FAST_FUNC
10075 breakcmd(int argc UNUSED_PARAM, char **argv)
10076 {
10077         int n = argv[1] ? number(argv[1]) : 1;
10078
10079         if (n <= 0)
10080                 ash_msg_and_raise_error(msg_illnum, argv[1]);
10081         if (n > loopnest)
10082                 n = loopnest;
10083         if (n > 0) {
10084                 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10085                 skipcount = n;
10086         }
10087         return 0;
10088 }
10089
10090
10091 /*
10092  * This implements the input routines used by the parser.
10093  */
10094
10095 enum {
10096         INPUT_PUSH_FILE = 1,
10097         INPUT_NOFILE_OK = 2,
10098 };
10099
10100 static smallint checkkwd;
10101 /* values of checkkwd variable */
10102 #define CHKALIAS        0x1
10103 #define CHKKWD          0x2
10104 #define CHKNL           0x4
10105 #define CHKEOFMARK      0x8
10106
10107 /*
10108  * Push a string back onto the input at this current parsefile level.
10109  * We handle aliases this way.
10110  */
10111 #if !ENABLE_ASH_ALIAS
10112 #define pushstring(s, ap) pushstring(s)
10113 #endif
10114 static void
10115 pushstring(char *s, struct alias *ap)
10116 {
10117         struct strpush *sp;
10118         int len;
10119
10120         len = strlen(s);
10121         INT_OFF;
10122         if (g_parsefile->strpush) {
10123                 sp = ckzalloc(sizeof(*sp));
10124                 sp->prev = g_parsefile->strpush;
10125         } else {
10126                 sp = &(g_parsefile->basestrpush);
10127         }
10128         g_parsefile->strpush = sp;
10129         sp->prev_string = g_parsefile->next_to_pgetc;
10130         sp->prev_left_in_line = g_parsefile->left_in_line;
10131         sp->unget = g_parsefile->unget;
10132         memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10133 #if ENABLE_ASH_ALIAS
10134         sp->ap = ap;
10135         if (ap) {
10136                 ap->flag |= ALIASINUSE;
10137                 sp->string = s;
10138         }
10139 #endif
10140         g_parsefile->next_to_pgetc = s;
10141         g_parsefile->left_in_line = len;
10142         g_parsefile->unget = 0;
10143         INT_ON;
10144 }
10145
10146 static void
10147 popstring(void)
10148 {
10149         struct strpush *sp = g_parsefile->strpush;
10150
10151         INT_OFF;
10152 #if ENABLE_ASH_ALIAS
10153         if (sp->ap) {
10154                 if (g_parsefile->next_to_pgetc[-1] == ' '
10155                  || g_parsefile->next_to_pgetc[-1] == '\t'
10156                 ) {
10157                         checkkwd |= CHKALIAS;
10158                 }
10159                 if (sp->string != sp->ap->val) {
10160                         free(sp->string);
10161                 }
10162                 sp->ap->flag &= ~ALIASINUSE;
10163                 if (sp->ap->flag & ALIASDEAD) {
10164                         unalias(sp->ap->name);
10165                 }
10166         }
10167 #endif
10168         g_parsefile->next_to_pgetc = sp->prev_string;
10169         g_parsefile->left_in_line = sp->prev_left_in_line;
10170         g_parsefile->unget = sp->unget;
10171         memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10172         g_parsefile->strpush = sp->prev;
10173         if (sp != &(g_parsefile->basestrpush))
10174                 free(sp);
10175         INT_ON;
10176 }
10177
10178 static int
10179 preadfd(void)
10180 {
10181         int nr;
10182         char *buf = g_parsefile->buf;
10183
10184         g_parsefile->next_to_pgetc = buf;
10185 #if ENABLE_FEATURE_EDITING
10186  retry:
10187         if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10188                 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10189         else {
10190                 int timeout = -1;
10191 # if ENABLE_ASH_IDLE_TIMEOUT
10192                 if (iflag) {
10193                         const char *tmout_var = lookupvar("TMOUT");
10194                         if (tmout_var) {
10195                                 timeout = atoi(tmout_var) * 1000;
10196                                 if (timeout <= 0)
10197                                         timeout = -1;
10198                         }
10199                 }
10200 # endif
10201 # if ENABLE_FEATURE_TAB_COMPLETION
10202                 line_input_state->path_lookup = pathval();
10203 # endif
10204                 reinit_unicode_for_ash();
10205                 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10206                 if (nr == 0) {
10207                         /* ^C pressed, "convert" to SIGINT */
10208                         write(STDOUT_FILENO, "^C", 2);
10209                         if (trap[SIGINT]) {
10210                                 buf[0] = '\n';
10211                                 buf[1] = '\0';
10212                                 raise(SIGINT);
10213                                 return 1;
10214                         }
10215                         exitstatus = 128 + SIGINT;
10216                         bb_putchar('\n');
10217                         goto retry;
10218                 }
10219                 if (nr < 0) {
10220                         if (errno == 0) {
10221                                 /* Ctrl+D pressed */
10222                                 nr = 0;
10223                         }
10224 # if ENABLE_ASH_IDLE_TIMEOUT
10225                         else if (errno == EAGAIN && timeout > 0) {
10226                                 puts("\007timed out waiting for input: auto-logout");
10227                                 exitshell();
10228                         }
10229 # endif
10230                 }
10231         }
10232 #else
10233         nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10234 #endif
10235
10236 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10237         if (nr < 0) {
10238                 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10239                         int flags = fcntl(0, F_GETFL);
10240                         if (flags >= 0 && (flags & O_NONBLOCK)) {
10241                                 flags &= ~O_NONBLOCK;
10242                                 if (fcntl(0, F_SETFL, flags) >= 0) {
10243                                         out2str("sh: turning off NDELAY mode\n");
10244                                         goto retry;
10245                                 }
10246                         }
10247                 }
10248         }
10249 #endif
10250         return nr;
10251 }
10252
10253 /*
10254  * Refill the input buffer and return the next input character:
10255  *
10256  * 1) If a string was pushed back on the input, pop it;
10257  * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10258  *    or we are reading from a string so we can't refill the buffer,
10259  *    return EOF.
10260  * 3) If there is more stuff in this buffer, use it else call read to fill it.
10261  * 4) Process input up to the next newline, deleting nul characters.
10262  */
10263 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10264 #define pgetc_debug(...) ((void)0)
10265 static int pgetc(void);
10266 static int
10267 preadbuffer(void)
10268 {
10269         char *q;
10270         int more;
10271
10272         if (g_parsefile->strpush) {
10273 #if ENABLE_ASH_ALIAS
10274                 if (g_parsefile->left_in_line == -1
10275                  && g_parsefile->strpush->ap
10276                  && g_parsefile->next_to_pgetc[-1] != ' '
10277                  && g_parsefile->next_to_pgetc[-1] != '\t'
10278                 ) {
10279                         pgetc_debug("preadbuffer PEOA");
10280                         return PEOA;
10281                 }
10282 #endif
10283                 popstring();
10284                 return pgetc();
10285         }
10286         /* on both branches above g_parsefile->left_in_line < 0.
10287          * "pgetc" needs refilling.
10288          */
10289
10290         /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10291          * pungetc() may increment it a few times.
10292          * Assuming it won't increment it to less than -90.
10293          */
10294         if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10295                 pgetc_debug("preadbuffer PEOF1");
10296                 /* even in failure keep left_in_line and next_to_pgetc
10297                  * in lock step, for correct multi-layer pungetc.
10298                  * left_in_line was decremented before preadbuffer(),
10299                  * must inc next_to_pgetc: */
10300                 g_parsefile->next_to_pgetc++;
10301                 return PEOF;
10302         }
10303
10304         more = g_parsefile->left_in_buffer;
10305         if (more <= 0) {
10306                 flush_stdout_stderr();
10307  again:
10308                 more = preadfd();
10309                 if (more <= 0) {
10310                         /* don't try reading again */
10311                         g_parsefile->left_in_line = -99;
10312                         pgetc_debug("preadbuffer PEOF2");
10313                         g_parsefile->next_to_pgetc++;
10314                         return PEOF;
10315                 }
10316         }
10317
10318         /* Find out where's the end of line.
10319          * Set g_parsefile->left_in_line
10320          * and g_parsefile->left_in_buffer acordingly.
10321          * NUL chars are deleted.
10322          */
10323         q = g_parsefile->next_to_pgetc;
10324         for (;;) {
10325                 char c;
10326
10327                 more--;
10328
10329                 c = *q;
10330                 if (c == '\0') {
10331                         memmove(q, q + 1, more);
10332                 } else {
10333                         q++;
10334                         if (c == '\n') {
10335                                 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10336                                 break;
10337                         }
10338                 }
10339
10340                 if (more <= 0) {
10341                         g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10342                         if (g_parsefile->left_in_line < 0)
10343                                 goto again;
10344                         break;
10345                 }
10346         }
10347         g_parsefile->left_in_buffer = more;
10348
10349         if (vflag) {
10350                 char save = *q;
10351                 *q = '\0';
10352                 out2str(g_parsefile->next_to_pgetc);
10353                 *q = save;
10354         }
10355
10356         pgetc_debug("preadbuffer at %d:%p'%s'",
10357                         g_parsefile->left_in_line,
10358                         g_parsefile->next_to_pgetc,
10359                         g_parsefile->next_to_pgetc);
10360         return (unsigned char)*g_parsefile->next_to_pgetc++;
10361 }
10362
10363 static void
10364 nlprompt(void)
10365 {
10366         g_parsefile->linno++;
10367         setprompt_if(doprompt, 2);
10368 }
10369 static void
10370 nlnoprompt(void)
10371 {
10372         g_parsefile->linno++;
10373         needprompt = doprompt;
10374 }
10375
10376 static int
10377 pgetc(void)
10378 {
10379         int c;
10380
10381         pgetc_debug("pgetc at %d:%p'%s'",
10382                         g_parsefile->left_in_line,
10383                         g_parsefile->next_to_pgetc,
10384                         g_parsefile->next_to_pgetc);
10385         if (g_parsefile->unget)
10386                 return g_parsefile->lastc[--g_parsefile->unget];
10387
10388         if (--g_parsefile->left_in_line >= 0)
10389                 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10390         else
10391                 c = preadbuffer();
10392
10393         g_parsefile->lastc[1] = g_parsefile->lastc[0];
10394         g_parsefile->lastc[0] = c;
10395
10396         return c;
10397 }
10398
10399 #if ENABLE_ASH_ALIAS
10400 static int
10401 pgetc_without_PEOA(void)
10402 {
10403         int c;
10404         do {
10405                 pgetc_debug("pgetc at %d:%p'%s'",
10406                                 g_parsefile->left_in_line,
10407                                 g_parsefile->next_to_pgetc,
10408                                 g_parsefile->next_to_pgetc);
10409                 c = pgetc();
10410         } while (c == PEOA);
10411         return c;
10412 }
10413 #else
10414 # define pgetc_without_PEOA() pgetc()
10415 #endif
10416
10417 /*
10418  * Undo a call to pgetc.  Only two characters may be pushed back.
10419  * PEOF may be pushed back.
10420  */
10421 static void
10422 pungetc(void)
10423 {
10424         g_parsefile->unget++;
10425 }
10426
10427 /* This one eats backslash+newline */
10428 static int
10429 pgetc_eatbnl(void)
10430 {
10431         int c;
10432
10433         while ((c = pgetc()) == '\\') {
10434                 if (pgetc() != '\n') {
10435                         pungetc();
10436                         break;
10437                 }
10438
10439                 nlprompt();
10440         }
10441
10442         return c;
10443 }
10444
10445 /*
10446  * To handle the "." command, a stack of input files is used.  Pushfile
10447  * adds a new entry to the stack and popfile restores the previous level.
10448  */
10449 static void
10450 pushfile(void)
10451 {
10452         struct parsefile *pf;
10453
10454         pf = ckzalloc(sizeof(*pf));
10455         pf->prev = g_parsefile;
10456         pf->pf_fd = -1;
10457         /*pf->strpush = NULL; - ckzalloc did it */
10458         /*pf->basestrpush.prev = NULL;*/
10459         /*pf->unget = 0;*/
10460         g_parsefile = pf;
10461 }
10462
10463 static void
10464 popfile(void)
10465 {
10466         struct parsefile *pf = g_parsefile;
10467
10468         if (pf == &basepf)
10469                 return;
10470
10471         INT_OFF;
10472         if (pf->pf_fd >= 0)
10473                 close(pf->pf_fd);
10474         free(pf->buf);
10475         while (pf->strpush)
10476                 popstring();
10477         g_parsefile = pf->prev;
10478         free(pf);
10479         INT_ON;
10480 }
10481
10482 /*
10483  * Return to top level.
10484  */
10485 static void
10486 popallfiles(void)
10487 {
10488         while (g_parsefile != &basepf)
10489                 popfile();
10490 }
10491
10492 /*
10493  * Close the file(s) that the shell is reading commands from.  Called
10494  * after a fork is done.
10495  */
10496 static void
10497 closescript(void)
10498 {
10499         popallfiles();
10500         if (g_parsefile->pf_fd > 0) {
10501                 close(g_parsefile->pf_fd);
10502                 g_parsefile->pf_fd = 0;
10503         }
10504 }
10505
10506 /*
10507  * Like setinputfile, but takes an open file descriptor.  Call this with
10508  * interrupts off.
10509  */
10510 static void
10511 setinputfd(int fd, int push)
10512 {
10513         if (push) {
10514                 pushfile();
10515                 g_parsefile->buf = NULL;
10516         }
10517         g_parsefile->pf_fd = fd;
10518         if (g_parsefile->buf == NULL)
10519                 g_parsefile->buf = ckmalloc(IBUFSIZ);
10520         g_parsefile->left_in_buffer = 0;
10521         g_parsefile->left_in_line = 0;
10522         g_parsefile->linno = 1;
10523 }
10524
10525 /*
10526  * Set the input to take input from a file.  If push is set, push the
10527  * old input onto the stack first.
10528  */
10529 static int
10530 setinputfile(const char *fname, int flags)
10531 {
10532         int fd;
10533
10534         INT_OFF;
10535         fd = open(fname, O_RDONLY);
10536         if (fd < 0) {
10537                 if (flags & INPUT_NOFILE_OK)
10538                         goto out;
10539                 exitstatus = 127;
10540                 ash_msg_and_raise_error("can't open '%s'", fname);
10541         }
10542         if (fd < 10)
10543                 fd = savefd(fd);
10544         else
10545                 close_on_exec_on(fd);
10546         setinputfd(fd, flags & INPUT_PUSH_FILE);
10547  out:
10548         INT_ON;
10549         return fd;
10550 }
10551
10552 /*
10553  * Like setinputfile, but takes input from a string.
10554  */
10555 static void
10556 setinputstring(char *string)
10557 {
10558         INT_OFF;
10559         pushfile();
10560         g_parsefile->next_to_pgetc = string;
10561         g_parsefile->left_in_line = strlen(string);
10562         g_parsefile->buf = NULL;
10563         g_parsefile->linno = 1;
10564         INT_ON;
10565 }
10566
10567
10568 /*
10569  * Routines to check for mail.
10570  */
10571
10572 #if ENABLE_ASH_MAIL
10573
10574 /* Hash of mtimes of mailboxes */
10575 static unsigned mailtime_hash;
10576 /* Set if MAIL or MAILPATH is changed. */
10577 static smallint mail_var_path_changed;
10578
10579 /*
10580  * Print appropriate message(s) if mail has arrived.
10581  * If mail_var_path_changed is set,
10582  * then the value of MAIL has mail_var_path_changed,
10583  * so we just update the values.
10584  */
10585 static void
10586 chkmail(void)
10587 {
10588         const char *mpath;
10589         char *p;
10590         char *q;
10591         unsigned new_hash;
10592         struct stackmark smark;
10593         struct stat statb;
10594
10595         setstackmark(&smark);
10596         mpath = mpathset() ? mpathval() : mailval();
10597         new_hash = 0;
10598         for (;;) {
10599                 p = path_advance(&mpath, nullstr);
10600                 if (p == NULL)
10601                         break;
10602                 if (*p == '\0')
10603                         continue;
10604                 for (q = p; *q; q++)
10605                         continue;
10606 #if DEBUG
10607                 if (q[-1] != '/')
10608                         abort();
10609 #endif
10610                 q[-1] = '\0';                   /* delete trailing '/' */
10611                 if (stat(p, &statb) < 0) {
10612                         continue;
10613                 }
10614                 /* Very simplistic "hash": just a sum of all mtimes */
10615                 new_hash += (unsigned)statb.st_mtime;
10616         }
10617         if (!mail_var_path_changed && mailtime_hash != new_hash) {
10618                 if (mailtime_hash != 0)
10619                         out2str("you have mail\n");
10620                 mailtime_hash = new_hash;
10621         }
10622         mail_var_path_changed = 0;
10623         popstackmark(&smark);
10624 }
10625
10626 static void FAST_FUNC
10627 changemail(const char *val UNUSED_PARAM)
10628 {
10629         mail_var_path_changed = 1;
10630 }
10631
10632 #endif /* ASH_MAIL */
10633
10634
10635 /* ============ ??? */
10636
10637 /*
10638  * Set the shell parameters.
10639  */
10640 static void
10641 setparam(char **argv)
10642 {
10643         char **newparam;
10644         char **ap;
10645         int nparam;
10646
10647         for (nparam = 0; argv[nparam]; nparam++)
10648                 continue;
10649         ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10650         while (*argv) {
10651                 *ap++ = ckstrdup(*argv++);
10652         }
10653         *ap = NULL;
10654         freeparam(&shellparam);
10655         shellparam.malloced = 1;
10656         shellparam.nparam = nparam;
10657         shellparam.p = newparam;
10658 #if ENABLE_ASH_GETOPTS
10659         shellparam.optind = 1;
10660         shellparam.optoff = -1;
10661 #endif
10662 }
10663
10664 /*
10665  * Process shell options.  The global variable argptr contains a pointer
10666  * to the argument list; we advance it past the options.
10667  *
10668  * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10669  * For a non-interactive shell, an error condition encountered
10670  * by a special built-in ... shall cause the shell to write a diagnostic message
10671  * to standard error and exit as shown in the following table:
10672  * Error                                           Special Built-In
10673  * ...
10674  * Utility syntax error (option or operand error)  Shall exit
10675  * ...
10676  * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10677  * we see that bash does not do that (set "finishes" with error code 1 instead,
10678  * and shell continues), and people rely on this behavior!
10679  * Testcase:
10680  * set -o barfoo 2>/dev/null
10681  * echo $?
10682  *
10683  * Oh well. Let's mimic that.
10684  */
10685 static int
10686 plus_minus_o(char *name, int val)
10687 {
10688         int i;
10689
10690         if (name) {
10691                 for (i = 0; i < NOPTS; i++) {
10692                         if (strcmp(name, optnames(i)) == 0) {
10693                                 optlist[i] = val;
10694                                 return 0;
10695                         }
10696                 }
10697                 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10698                 return 1;
10699         }
10700         for (i = 0; i < NOPTS; i++) {
10701                 if (val) {
10702                         out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10703                 } else {
10704                         out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10705                 }
10706         }
10707         return 0;
10708 }
10709 static void
10710 setoption(int flag, int val)
10711 {
10712         int i;
10713
10714         for (i = 0; i < NOPTS; i++) {
10715                 if (optletters(i) == flag) {
10716                         optlist[i] = val;
10717                         return;
10718                 }
10719         }
10720         ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10721         /* NOTREACHED */
10722 }
10723 static int
10724 options(int cmdline)
10725 {
10726         char *p;
10727         int val;
10728         int c;
10729
10730         if (cmdline)
10731                 minusc = NULL;
10732         while ((p = *argptr) != NULL) {
10733                 c = *p++;
10734                 if (c != '-' && c != '+')
10735                         break;
10736                 argptr++;
10737                 val = 0; /* val = 0 if c == '+' */
10738                 if (c == '-') {
10739                         val = 1;
10740                         if (p[0] == '\0' || LONE_DASH(p)) {
10741                                 if (!cmdline) {
10742                                         /* "-" means turn off -x and -v */
10743                                         if (p[0] == '\0')
10744                                                 xflag = vflag = 0;
10745                                         /* "--" means reset params */
10746                                         else if (*argptr == NULL)
10747                                                 setparam(argptr);
10748                                 }
10749                                 break;    /* "-" or "--" terminates options */
10750                         }
10751                 }
10752                 /* first char was + or - */
10753                 while ((c = *p++) != '\0') {
10754                         /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10755                         if (c == 'c' && cmdline) {
10756                                 minusc = p;     /* command is after shell args */
10757                         } else if (c == 'o') {
10758                                 if (plus_minus_o(*argptr, val)) {
10759                                         /* it already printed err message */
10760                                         return 1; /* error */
10761                                 }
10762                                 if (*argptr)
10763                                         argptr++;
10764                         } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10765                                 isloginsh = 1;
10766                         /* bash does not accept +-login, we also won't */
10767                         } else if (cmdline && val && (c == '-')) { /* long options */
10768                                 if (strcmp(p, "login") == 0)
10769                                         isloginsh = 1;
10770                                 break;
10771                         } else {
10772                                 setoption(c, val);
10773                         }
10774                 }
10775         }
10776         return 0;
10777 }
10778
10779 /*
10780  * The shift builtin command.
10781  */
10782 static int FAST_FUNC
10783 shiftcmd(int argc UNUSED_PARAM, char **argv)
10784 {
10785         int n;
10786         char **ap1, **ap2;
10787
10788         n = 1;
10789         if (argv[1])
10790                 n = number(argv[1]);
10791         if (n > shellparam.nparam)
10792                 n = 0; /* bash compat, was = shellparam.nparam; */
10793         INT_OFF;
10794         shellparam.nparam -= n;
10795         for (ap1 = shellparam.p; --n >= 0; ap1++) {
10796                 if (shellparam.malloced)
10797                         free(*ap1);
10798         }
10799         ap2 = shellparam.p;
10800         while ((*ap2++ = *ap1++) != NULL)
10801                 continue;
10802 #if ENABLE_ASH_GETOPTS
10803         shellparam.optind = 1;
10804         shellparam.optoff = -1;
10805 #endif
10806         INT_ON;
10807         return 0;
10808 }
10809
10810 /*
10811  * POSIX requires that 'set' (but not export or readonly) output the
10812  * variables in lexicographic order - by the locale's collating order (sigh).
10813  * Maybe we could keep them in an ordered balanced binary tree
10814  * instead of hashed lists.
10815  * For now just roll 'em through qsort for printing...
10816  */
10817 static int
10818 showvars(const char *sep_prefix, int on, int off)
10819 {
10820         const char *sep;
10821         char **ep, **epend;
10822
10823         ep = listvars(on, off, &epend);
10824         qsort(ep, epend - ep, sizeof(char *), vpcmp);
10825
10826         sep = *sep_prefix ? " " : sep_prefix;
10827
10828         for (; ep < epend; ep++) {
10829                 const char *p;
10830                 const char *q;
10831
10832                 p = strchrnul(*ep, '=');
10833                 q = nullstr;
10834                 if (*p)
10835                         q = single_quote(++p);
10836                 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10837         }
10838         return 0;
10839 }
10840
10841 /*
10842  * The set command builtin.
10843  */
10844 static int FAST_FUNC
10845 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10846 {
10847         int retval;
10848
10849         if (!argv[1])
10850                 return showvars(nullstr, 0, VUNSET);
10851
10852         INT_OFF;
10853         retval = options(/*cmdline:*/ 0);
10854         if (retval == 0) { /* if no parse error... */
10855                 optschanged();
10856                 if (*argptr != NULL) {
10857                         setparam(argptr);
10858                 }
10859         }
10860         INT_ON;
10861         return retval;
10862 }
10863
10864 #if ENABLE_ASH_RANDOM_SUPPORT
10865 static void FAST_FUNC
10866 change_random(const char *value)
10867 {
10868         uint32_t t;
10869
10870         if (value == NULL) {
10871                 /* "get", generate */
10872                 t = next_random(&random_gen);
10873                 /* set without recursion */
10874                 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10875                 vrandom.flags &= ~VNOFUNC;
10876         } else {
10877                 /* set/reset */
10878                 t = strtoul(value, NULL, 10);
10879                 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10880         }
10881 }
10882 #endif
10883
10884 #if ENABLE_ASH_GETOPTS
10885 static int
10886 getopts(char *optstr, char *optvar, char **optfirst)
10887 {
10888         char *p, *q;
10889         char c = '?';
10890         int done = 0;
10891         char sbuf[2];
10892         char **optnext;
10893         int ind = shellparam.optind;
10894         int off = shellparam.optoff;
10895
10896         sbuf[1] = '\0';
10897
10898         shellparam.optind = -1;
10899         optnext = optfirst + ind - 1;
10900
10901         if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10902                 p = NULL;
10903         else
10904                 p = optnext[-1] + off;
10905         if (p == NULL || *p == '\0') {
10906                 /* Current word is done, advance */
10907                 p = *optnext;
10908                 if (p == NULL || *p != '-' || *++p == '\0') {
10909  atend:
10910                         p = NULL;
10911                         done = 1;
10912                         goto out;
10913                 }
10914                 optnext++;
10915                 if (LONE_DASH(p))        /* check for "--" */
10916                         goto atend;
10917         }
10918
10919         c = *p++;
10920         for (q = optstr; *q != c;) {
10921                 if (*q == '\0') {
10922                         if (optstr[0] == ':') {
10923                                 sbuf[0] = c;
10924                                 /*sbuf[1] = '\0'; - already is */
10925                                 setvar0("OPTARG", sbuf);
10926                         } else {
10927                                 fprintf(stderr, "Illegal option -%c\n", c);
10928                                 unsetvar("OPTARG");
10929                         }
10930                         c = '?';
10931                         goto out;
10932                 }
10933                 if (*++q == ':')
10934                         q++;
10935         }
10936
10937         if (*++q == ':') {
10938                 if (*p == '\0' && (p = *optnext) == NULL) {
10939                         if (optstr[0] == ':') {
10940                                 sbuf[0] = c;
10941                                 /*sbuf[1] = '\0'; - already is */
10942                                 setvar0("OPTARG", sbuf);
10943                                 c = ':';
10944                         } else {
10945                                 fprintf(stderr, "No arg for -%c option\n", c);
10946                                 unsetvar("OPTARG");
10947                                 c = '?';
10948                         }
10949                         goto out;
10950                 }
10951
10952                 if (p == *optnext)
10953                         optnext++;
10954                 setvar0("OPTARG", p);
10955                 p = NULL;
10956         } else
10957                 setvar0("OPTARG", nullstr);
10958  out:
10959         ind = optnext - optfirst + 1;
10960         setvar("OPTIND", itoa(ind), VNOFUNC);
10961         sbuf[0] = c;
10962         /*sbuf[1] = '\0'; - already is */
10963         setvar0(optvar, sbuf);
10964
10965         shellparam.optoff = p ? p - *(optnext - 1) : -1;
10966         shellparam.optind = ind;
10967
10968         return done;
10969 }
10970
10971 /*
10972  * The getopts builtin.  Shellparam.optnext points to the next argument
10973  * to be processed.  Shellparam.optptr points to the next character to
10974  * be processed in the current argument.  If shellparam.optnext is NULL,
10975  * then it's the first time getopts has been called.
10976  */
10977 static int FAST_FUNC
10978 getoptscmd(int argc, char **argv)
10979 {
10980         char **optbase;
10981
10982         if (argc < 3)
10983                 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10984         if (argc == 3) {
10985                 optbase = shellparam.p;
10986                 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10987                         shellparam.optind = 1;
10988                         shellparam.optoff = -1;
10989                 }
10990         } else {
10991                 optbase = &argv[3];
10992                 if ((unsigned)shellparam.optind > argc - 2) {
10993                         shellparam.optind = 1;
10994                         shellparam.optoff = -1;
10995                 }
10996         }
10997
10998         return getopts(argv[1], argv[2], optbase);
10999 }
11000 #endif /* ASH_GETOPTS */
11001
11002
11003 /* ============ Shell parser */
11004
11005 struct heredoc {
11006         struct heredoc *next;   /* next here document in list */
11007         union node *here;       /* redirection node */
11008         char *eofmark;          /* string indicating end of input */
11009         smallint striptabs;     /* if set, strip leading tabs */
11010 };
11011
11012 static smallint tokpushback;           /* last token pushed back */
11013 static smallint quoteflag;             /* set if (part of) last token was quoted */
11014 static token_id_t lasttoken;           /* last token read (integer id Txxx) */
11015 static struct heredoc *heredoclist;    /* list of here documents to read */
11016 static char *wordtext;                 /* text of last word returned by readtoken */
11017 static struct nodelist *backquotelist;
11018 static union node *redirnode;
11019 static struct heredoc *heredoc;
11020
11021 static const char *
11022 tokname(char *buf, int tok)
11023 {
11024         if (tok < TSEMI)
11025                 return tokname_array[tok];
11026         sprintf(buf, "\"%s\"", tokname_array[tok]);
11027         return buf;
11028 }
11029
11030 /* raise_error_unexpected_syntax:
11031  * Called when an unexpected token is read during the parse.  The argument
11032  * is the token that is expected, or -1 if more than one type of token can
11033  * occur at this point.
11034  */
11035 static void raise_error_unexpected_syntax(int) NORETURN;
11036 static void
11037 raise_error_unexpected_syntax(int token)
11038 {
11039         char msg[64];
11040         char buf[16];
11041         int l;
11042
11043         l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11044         if (token >= 0)
11045                 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11046         raise_error_syntax(msg);
11047         /* NOTREACHED */
11048 }
11049
11050 /* parsing is heavily cross-recursive, need these forward decls */
11051 static union node *andor(void);
11052 static union node *pipeline(void);
11053 static union node *parse_command(void);
11054 static void parseheredoc(void);
11055 static int peektoken(void);
11056 static int readtoken(void);
11057
11058 static union node *
11059 list(int nlflag)
11060 {
11061         union node *n1, *n2, *n3;
11062         int tok;
11063
11064         n1 = NULL;
11065         for (;;) {
11066                 switch (peektoken()) {
11067                 case TNL:
11068                         if (!(nlflag & 1))
11069                                 break;
11070                         parseheredoc();
11071                         return n1;
11072
11073                 case TEOF:
11074                         if (!n1 && (nlflag & 1))
11075                                 n1 = NODE_EOF;
11076                         parseheredoc();
11077                         return n1;
11078                 }
11079
11080                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11081                 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11082                         return n1;
11083                 nlflag |= 2;
11084
11085                 n2 = andor();
11086                 tok = readtoken();
11087                 if (tok == TBACKGND) {
11088                         if (n2->type == NPIPE) {
11089                                 n2->npipe.pipe_backgnd = 1;
11090                         } else {
11091                                 if (n2->type != NREDIR) {
11092                                         n3 = stzalloc(sizeof(struct nredir));
11093                                         n3->nredir.n = n2;
11094                                         /*n3->nredir.redirect = NULL; - stzalloc did it */
11095                                         n2 = n3;
11096                                 }
11097                                 n2->type = NBACKGND;
11098                         }
11099                 }
11100                 if (n1 == NULL) {
11101                         n1 = n2;
11102                 } else {
11103                         n3 = stzalloc(sizeof(struct nbinary));
11104                         n3->type = NSEMI;
11105                         n3->nbinary.ch1 = n1;
11106                         n3->nbinary.ch2 = n2;
11107                         n1 = n3;
11108                 }
11109                 switch (tok) {
11110                 case TNL:
11111                 case TEOF:
11112                         tokpushback = 1;
11113                         /* fall through */
11114                 case TBACKGND:
11115                 case TSEMI:
11116                         break;
11117                 default:
11118                         if ((nlflag & 1))
11119                                 raise_error_unexpected_syntax(-1);
11120                         tokpushback = 1;
11121                         return n1;
11122                 }
11123         }
11124 }
11125
11126 static union node *
11127 andor(void)
11128 {
11129         union node *n1, *n2, *n3;
11130         int t;
11131
11132         n1 = pipeline();
11133         for (;;) {
11134                 t = readtoken();
11135                 if (t == TAND) {
11136                         t = NAND;
11137                 } else if (t == TOR) {
11138                         t = NOR;
11139                 } else {
11140                         tokpushback = 1;
11141                         return n1;
11142                 }
11143                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11144                 n2 = pipeline();
11145                 n3 = stzalloc(sizeof(struct nbinary));
11146                 n3->type = t;
11147                 n3->nbinary.ch1 = n1;
11148                 n3->nbinary.ch2 = n2;
11149                 n1 = n3;
11150         }
11151 }
11152
11153 static union node *
11154 pipeline(void)
11155 {
11156         union node *n1, *n2, *pipenode;
11157         struct nodelist *lp, *prev;
11158         int negate;
11159
11160         negate = 0;
11161         TRACE(("pipeline: entered\n"));
11162         if (readtoken() == TNOT) {
11163                 negate = !negate;
11164                 checkkwd = CHKKWD | CHKALIAS;
11165         } else
11166                 tokpushback = 1;
11167         n1 = parse_command();
11168         if (readtoken() == TPIPE) {
11169                 pipenode = stzalloc(sizeof(struct npipe));
11170                 pipenode->type = NPIPE;
11171                 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11172                 lp = stzalloc(sizeof(struct nodelist));
11173                 pipenode->npipe.cmdlist = lp;
11174                 lp->n = n1;
11175                 do {
11176                         prev = lp;
11177                         lp = stzalloc(sizeof(struct nodelist));
11178                         checkkwd = CHKNL | CHKKWD | CHKALIAS;
11179                         lp->n = parse_command();
11180                         prev->next = lp;
11181                 } while (readtoken() == TPIPE);
11182                 lp->next = NULL;
11183                 n1 = pipenode;
11184         }
11185         tokpushback = 1;
11186         if (negate) {
11187                 n2 = stzalloc(sizeof(struct nnot));
11188                 n2->type = NNOT;
11189                 n2->nnot.com = n1;
11190                 return n2;
11191         }
11192         return n1;
11193 }
11194
11195 static union node *
11196 makename(void)
11197 {
11198         union node *n;
11199
11200         n = stzalloc(sizeof(struct narg));
11201         n->type = NARG;
11202         /*n->narg.next = NULL; - stzalloc did it */
11203         n->narg.text = wordtext;
11204         n->narg.backquote = backquotelist;
11205         return n;
11206 }
11207
11208 static void
11209 fixredir(union node *n, const char *text, int err)
11210 {
11211         int fd;
11212
11213         TRACE(("Fix redir %s %d\n", text, err));
11214         if (!err)
11215                 n->ndup.vname = NULL;
11216
11217         fd = bb_strtou(text, NULL, 10);
11218         if (!errno && fd >= 0)
11219                 n->ndup.dupfd = fd;
11220         else if (LONE_DASH(text))
11221                 n->ndup.dupfd = -1;
11222         else {
11223                 if (err)
11224                         raise_error_syntax("bad fd number");
11225                 n->ndup.vname = makename();
11226         }
11227 }
11228
11229 static void
11230 parsefname(void)
11231 {
11232         union node *n = redirnode;
11233
11234         if (n->type == NHERE)
11235                 checkkwd = CHKEOFMARK;
11236         if (readtoken() != TWORD)
11237                 raise_error_unexpected_syntax(-1);
11238         if (n->type == NHERE) {
11239                 struct heredoc *here = heredoc;
11240                 struct heredoc *p;
11241
11242                 if (quoteflag == 0)
11243                         n->type = NXHERE;
11244                 TRACE(("Here document %d\n", n->type));
11245                 rmescapes(wordtext, 0);
11246                 here->eofmark = wordtext;
11247                 here->next = NULL;
11248                 if (heredoclist == NULL)
11249                         heredoclist = here;
11250                 else {
11251                         for (p = heredoclist; p->next; p = p->next)
11252                                 continue;
11253                         p->next = here;
11254                 }
11255         } else if (n->type == NTOFD || n->type == NFROMFD) {
11256                 fixredir(n, wordtext, 0);
11257         } else {
11258                 n->nfile.fname = makename();
11259         }
11260 }
11261
11262 static union node *
11263 simplecmd(void)
11264 {
11265         union node *args, **app;
11266         union node *n = NULL;
11267         union node *vars, **vpp;
11268         union node **rpp, *redir;
11269         int savecheckkwd;
11270 #if BASH_TEST2
11271         smallint double_brackets_flag = 0;
11272 #endif
11273         IF_BASH_FUNCTION(smallint function_flag = 0;)
11274
11275         args = NULL;
11276         app = &args;
11277         vars = NULL;
11278         vpp = &vars;
11279         redir = NULL;
11280         rpp = &redir;
11281
11282         savecheckkwd = CHKALIAS;
11283         for (;;) {
11284                 int t;
11285                 checkkwd = savecheckkwd;
11286                 t = readtoken();
11287                 switch (t) {
11288 #if BASH_FUNCTION
11289                 case TFUNCTION:
11290                         if (peektoken() != TWORD)
11291                                 raise_error_unexpected_syntax(TWORD);
11292                         function_flag = 1;
11293                         break;
11294 #endif
11295 #if BASH_TEST2
11296                 case TAND: /* "&&" */
11297                 case TOR: /* "||" */
11298                         if (!double_brackets_flag) {
11299                                 tokpushback = 1;
11300                                 goto out;
11301                         }
11302                         wordtext = (char *) (t == TAND ? "-a" : "-o");
11303 #endif
11304                 case TWORD:
11305                         n = stzalloc(sizeof(struct narg));
11306                         n->type = NARG;
11307                         /*n->narg.next = NULL; - stzalloc did it */
11308                         n->narg.text = wordtext;
11309 #if BASH_TEST2
11310                         if (strcmp("[[", wordtext) == 0)
11311                                 double_brackets_flag = 1;
11312                         else if (strcmp("]]", wordtext) == 0)
11313                                 double_brackets_flag = 0;
11314 #endif
11315                         n->narg.backquote = backquotelist;
11316                         if (savecheckkwd && isassignment(wordtext)) {
11317                                 *vpp = n;
11318                                 vpp = &n->narg.next;
11319                         } else {
11320                                 *app = n;
11321                                 app = &n->narg.next;
11322                                 savecheckkwd = 0;
11323                         }
11324 #if BASH_FUNCTION
11325                         if (function_flag) {
11326                                 checkkwd = CHKNL | CHKKWD;
11327                                 switch (peektoken()) {
11328                                 case TBEGIN:
11329                                 case TIF:
11330                                 case TCASE:
11331                                 case TUNTIL:
11332                                 case TWHILE:
11333                                 case TFOR:
11334                                         goto do_func;
11335                                 case TLP:
11336                                         function_flag = 0;
11337                                         break;
11338                                 case TWORD:
11339                                         if (strcmp("[[", wordtext) == 0)
11340                                                 goto do_func;
11341                                         /* fall through */
11342                                 default:
11343                                         raise_error_unexpected_syntax(-1);
11344                                 }
11345                         }
11346 #endif
11347                         break;
11348                 case TREDIR:
11349                         *rpp = n = redirnode;
11350                         rpp = &n->nfile.next;
11351                         parsefname();   /* read name of redirection file */
11352                         break;
11353                 case TLP:
11354  IF_BASH_FUNCTION(do_func:)
11355                         if (args && app == &args->narg.next
11356                          && !vars && !redir
11357                         ) {
11358                                 struct builtincmd *bcmd;
11359                                 const char *name;
11360
11361                                 /* We have a function */
11362                                 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11363                                         raise_error_unexpected_syntax(TRP);
11364                                 name = n->narg.text;
11365                                 if (!goodname(name)
11366                                  || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11367                                 ) {
11368                                         raise_error_syntax("bad function name");
11369                                 }
11370                                 n->type = NDEFUN;
11371                                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11372                                 n->narg.next = parse_command();
11373                                 return n;
11374                         }
11375                         IF_BASH_FUNCTION(function_flag = 0;)
11376                         /* fall through */
11377                 default:
11378                         tokpushback = 1;
11379                         goto out;
11380                 }
11381         }
11382  out:
11383         *app = NULL;
11384         *vpp = NULL;
11385         *rpp = NULL;
11386         n = stzalloc(sizeof(struct ncmd));
11387         n->type = NCMD;
11388         n->ncmd.args = args;
11389         n->ncmd.assign = vars;
11390         n->ncmd.redirect = redir;
11391         return n;
11392 }
11393
11394 static union node *
11395 parse_command(void)
11396 {
11397         union node *n1, *n2;
11398         union node *ap, **app;
11399         union node *cp, **cpp;
11400         union node *redir, **rpp;
11401         union node **rpp2;
11402         int t;
11403
11404         redir = NULL;
11405         rpp2 = &redir;
11406
11407         switch (readtoken()) {
11408         default:
11409                 raise_error_unexpected_syntax(-1);
11410                 /* NOTREACHED */
11411         case TIF:
11412                 n1 = stzalloc(sizeof(struct nif));
11413                 n1->type = NIF;
11414                 n1->nif.test = list(0);
11415                 if (readtoken() != TTHEN)
11416                         raise_error_unexpected_syntax(TTHEN);
11417                 n1->nif.ifpart = list(0);
11418                 n2 = n1;
11419                 while (readtoken() == TELIF) {
11420                         n2->nif.elsepart = stzalloc(sizeof(struct nif));
11421                         n2 = n2->nif.elsepart;
11422                         n2->type = NIF;
11423                         n2->nif.test = list(0);
11424                         if (readtoken() != TTHEN)
11425                                 raise_error_unexpected_syntax(TTHEN);
11426                         n2->nif.ifpart = list(0);
11427                 }
11428                 if (lasttoken == TELSE)
11429                         n2->nif.elsepart = list(0);
11430                 else {
11431                         n2->nif.elsepart = NULL;
11432                         tokpushback = 1;
11433                 }
11434                 t = TFI;
11435                 break;
11436         case TWHILE:
11437         case TUNTIL: {
11438                 int got;
11439                 n1 = stzalloc(sizeof(struct nbinary));
11440                 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11441                 n1->nbinary.ch1 = list(0);
11442                 got = readtoken();
11443                 if (got != TDO) {
11444                         TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11445                                         got == TWORD ? wordtext : ""));
11446                         raise_error_unexpected_syntax(TDO);
11447                 }
11448                 n1->nbinary.ch2 = list(0);
11449                 t = TDONE;
11450                 break;
11451         }
11452         case TFOR:
11453                 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11454                         raise_error_syntax("bad for loop variable");
11455                 n1 = stzalloc(sizeof(struct nfor));
11456                 n1->type = NFOR;
11457                 n1->nfor.var = wordtext;
11458                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11459                 if (readtoken() == TIN) {
11460                         app = &ap;
11461                         while (readtoken() == TWORD) {
11462                                 n2 = stzalloc(sizeof(struct narg));
11463                                 n2->type = NARG;
11464                                 /*n2->narg.next = NULL; - stzalloc did it */
11465                                 n2->narg.text = wordtext;
11466                                 n2->narg.backquote = backquotelist;
11467                                 *app = n2;
11468                                 app = &n2->narg.next;
11469                         }
11470                         *app = NULL;
11471                         n1->nfor.args = ap;
11472                         if (lasttoken != TNL && lasttoken != TSEMI)
11473                                 raise_error_unexpected_syntax(-1);
11474                 } else {
11475                         n2 = stzalloc(sizeof(struct narg));
11476                         n2->type = NARG;
11477                         /*n2->narg.next = NULL; - stzalloc did it */
11478                         n2->narg.text = (char *)dolatstr;
11479                         /*n2->narg.backquote = NULL;*/
11480                         n1->nfor.args = n2;
11481                         /*
11482                          * Newline or semicolon here is optional (but note
11483                          * that the original Bourne shell only allowed NL).
11484                          */
11485                         if (lasttoken != TSEMI)
11486                                 tokpushback = 1;
11487                 }
11488                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11489                 if (readtoken() != TDO)
11490                         raise_error_unexpected_syntax(TDO);
11491                 n1->nfor.body = list(0);
11492                 t = TDONE;
11493                 break;
11494         case TCASE:
11495                 n1 = stzalloc(sizeof(struct ncase));
11496                 n1->type = NCASE;
11497                 if (readtoken() != TWORD)
11498                         raise_error_unexpected_syntax(TWORD);
11499                 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11500                 n2->type = NARG;
11501                 /*n2->narg.next = NULL; - stzalloc did it */
11502                 n2->narg.text = wordtext;
11503                 n2->narg.backquote = backquotelist;
11504                 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11505                 if (readtoken() != TIN)
11506                         raise_error_unexpected_syntax(TIN);
11507                 cpp = &n1->ncase.cases;
11508  next_case:
11509                 checkkwd = CHKNL | CHKKWD;
11510                 t = readtoken();
11511                 while (t != TESAC) {
11512                         if (lasttoken == TLP)
11513                                 readtoken();
11514                         *cpp = cp = stzalloc(sizeof(struct nclist));
11515                         cp->type = NCLIST;
11516                         app = &cp->nclist.pattern;
11517                         for (;;) {
11518                                 *app = ap = stzalloc(sizeof(struct narg));
11519                                 ap->type = NARG;
11520                                 /*ap->narg.next = NULL; - stzalloc did it */
11521                                 ap->narg.text = wordtext;
11522                                 ap->narg.backquote = backquotelist;
11523                                 if (readtoken() != TPIPE)
11524                                         break;
11525                                 app = &ap->narg.next;
11526                                 readtoken();
11527                         }
11528                         //ap->narg.next = NULL;
11529                         if (lasttoken != TRP)
11530                                 raise_error_unexpected_syntax(TRP);
11531                         cp->nclist.body = list(2);
11532
11533                         cpp = &cp->nclist.next;
11534
11535                         checkkwd = CHKNL | CHKKWD;
11536                         t = readtoken();
11537                         if (t != TESAC) {
11538                                 if (t != TENDCASE)
11539                                         raise_error_unexpected_syntax(TENDCASE);
11540                                 goto next_case;
11541                         }
11542                 }
11543                 *cpp = NULL;
11544                 goto redir;
11545         case TLP:
11546                 n1 = stzalloc(sizeof(struct nredir));
11547                 n1->type = NSUBSHELL;
11548                 n1->nredir.n = list(0);
11549                 /*n1->nredir.redirect = NULL; - stzalloc did it */
11550                 t = TRP;
11551                 break;
11552         case TBEGIN:
11553                 n1 = list(0);
11554                 t = TEND;
11555                 break;
11556         IF_BASH_FUNCTION(case TFUNCTION:)
11557         case TWORD:
11558         case TREDIR:
11559                 tokpushback = 1;
11560                 return simplecmd();
11561         }
11562
11563         if (readtoken() != t)
11564                 raise_error_unexpected_syntax(t);
11565
11566  redir:
11567         /* Now check for redirection which may follow command */
11568         checkkwd = CHKKWD | CHKALIAS;
11569         rpp = rpp2;
11570         while (readtoken() == TREDIR) {
11571                 *rpp = n2 = redirnode;
11572                 rpp = &n2->nfile.next;
11573                 parsefname();
11574         }
11575         tokpushback = 1;
11576         *rpp = NULL;
11577         if (redir) {
11578                 if (n1->type != NSUBSHELL) {
11579                         n2 = stzalloc(sizeof(struct nredir));
11580                         n2->type = NREDIR;
11581                         n2->nredir.n = n1;
11582                         n1 = n2;
11583                 }
11584                 n1->nredir.redirect = redir;
11585         }
11586         return n1;
11587 }
11588
11589 #if BASH_DOLLAR_SQUOTE
11590 static int
11591 decode_dollar_squote(void)
11592 {
11593         static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11594         int c, cnt;
11595         char *p;
11596         char buf[4];
11597
11598         c = pgetc();
11599         p = strchr(C_escapes, c);
11600         if (p) {
11601                 buf[0] = c;
11602                 p = buf;
11603                 cnt = 3;
11604                 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11605                         do {
11606                                 c = pgetc();
11607                                 *++p = c;
11608                         } while ((unsigned char)(c - '0') <= 7 && --cnt);
11609                         pungetc();
11610                 } else if (c == 'x') { /* \xHH */
11611                         do {
11612                                 c = pgetc();
11613                                 *++p = c;
11614                         } while (isxdigit(c) && --cnt);
11615                         pungetc();
11616                         if (cnt == 3) { /* \x but next char is "bad" */
11617                                 c = 'x';
11618                                 goto unrecognized;
11619                         }
11620                 } else { /* simple seq like \\ or \t */
11621                         p++;
11622                 }
11623                 *p = '\0';
11624                 p = buf;
11625                 c = bb_process_escape_sequence((void*)&p);
11626         } else { /* unrecognized "\z": print both chars unless ' or " */
11627                 if (c != '\'' && c != '"') {
11628  unrecognized:
11629                         c |= 0x100; /* "please encode \, then me" */
11630                 }
11631         }
11632         return c;
11633 }
11634 #endif
11635
11636 /* Used by expandstr to get here-doc like behaviour. */
11637 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11638
11639 static ALWAYS_INLINE int
11640 realeofmark(const char *eofmark)
11641 {
11642         return eofmark && eofmark != FAKEEOFMARK;
11643 }
11644
11645 /*
11646  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
11647  * is not NULL, read a here document.  In the latter case, eofmark is the
11648  * word which marks the end of the document and striptabs is true if
11649  * leading tabs should be stripped from the document.  The argument c
11650  * is the first character of the input token or document.
11651  *
11652  * Because C does not have internal subroutines, I have simulated them
11653  * using goto's to implement the subroutine linkage.  The following macros
11654  * will run code that appears at the end of readtoken1.
11655  */
11656 #define CHECKEND()      {goto checkend; checkend_return:;}
11657 #define PARSEREDIR()    {goto parseredir; parseredir_return:;}
11658 #define PARSESUB()      {goto parsesub; parsesub_return:;}
11659 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11660 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11661 #define PARSEARITH()    {goto parsearith; parsearith_return:;}
11662 static int
11663 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11664 {
11665         /* NB: syntax parameter fits into smallint */
11666         /* c parameter is an unsigned char or PEOF or PEOA */
11667         char *out;
11668         size_t len;
11669         struct nodelist *bqlist;
11670         smallint quotef;
11671         smallint dblquote;
11672         smallint oldstyle;
11673         IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11674         smallint pssyntax;   /* we are expanding a prompt string */
11675         int varnest;         /* levels of variables expansion */
11676         IF_FEATURE_SH_MATH(int arinest;)    /* levels of arithmetic expansion */
11677         IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11678         int dqvarnest;       /* levels of variables expansion within double quotes */
11679
11680         IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11681
11682         startlinno = g_parsefile->linno;
11683         bqlist = NULL;
11684         quotef = 0;
11685         IF_FEATURE_SH_MATH(prevsyntax = 0;)
11686 #if ENABLE_ASH_EXPAND_PRMT
11687         pssyntax = (syntax == PSSYNTAX);
11688         if (pssyntax)
11689                 syntax = DQSYNTAX;
11690 #else
11691         pssyntax = 0; /* constant */
11692 #endif
11693         dblquote = (syntax == DQSYNTAX);
11694         varnest = 0;
11695         IF_FEATURE_SH_MATH(arinest = 0;)
11696         IF_FEATURE_SH_MATH(parenlevel = 0;)
11697         dqvarnest = 0;
11698
11699         STARTSTACKSTR(out);
11700  loop:
11701         /* For each line, until end of word */
11702         CHECKEND();     /* set c to PEOF if at end of here document */
11703         for (;;) {      /* until end of line or end of word */
11704                 CHECKSTRSPACE(4, out);  /* permit 4 calls to USTPUTC */
11705                 switch (SIT(c, syntax)) {
11706                 case CNL:       /* '\n' */
11707                         if (syntax == BASESYNTAX)
11708                                 goto endword;   /* exit outer loop */
11709                         USTPUTC(c, out);
11710                         nlprompt();
11711                         c = pgetc();
11712                         goto loop;              /* continue outer loop */
11713                 case CWORD:
11714                         USTPUTC(c, out);
11715                         break;
11716                 case CCTL:
11717 #if BASH_DOLLAR_SQUOTE
11718                         if (c == '\\' && bash_dollar_squote) {
11719                                 c = decode_dollar_squote();
11720                                 if (c == '\0') {
11721                                         /* skip $'\000', $'\x00' (like bash) */
11722                                         break;
11723                                 }
11724                                 if (c & 0x100) {
11725                                         /* Unknown escape. Encode as '\z' */
11726                                         c = (unsigned char)c;
11727                                         if (eofmark == NULL || dblquote)
11728                                                 USTPUTC(CTLESC, out);
11729                                         USTPUTC('\\', out);
11730                                 }
11731                         }
11732 #endif
11733                         if (eofmark == NULL || dblquote)
11734                                 USTPUTC(CTLESC, out);
11735                         USTPUTC(c, out);
11736                         break;
11737                 case CBACK:     /* backslash */
11738                         c = pgetc_without_PEOA();
11739                         if (c == PEOF) {
11740                                 USTPUTC(CTLESC, out);
11741                                 USTPUTC('\\', out);
11742                                 pungetc();
11743                         } else if (c == '\n') {
11744                                 nlprompt();
11745                         } else {
11746                                 if (pssyntax && c == '$') {
11747                                         USTPUTC(CTLESC, out);
11748                                         USTPUTC('\\', out);
11749                                 }
11750                                 /* Backslash is retained if we are in "str" and next char isn't special */
11751                                 if (dblquote
11752                                  && c != '\\'
11753                                  && c != '`'
11754                                  && c != '$'
11755                                  && (c != '"' || eofmark != NULL)
11756                                 ) {
11757                                         USTPUTC('\\', out);
11758                                 }
11759                                 USTPUTC(CTLESC, out);
11760                                 USTPUTC(c, out);
11761                                 quotef = 1;
11762                         }
11763                         break;
11764                 case CSQUOTE:
11765                         syntax = SQSYNTAX;
11766  quotemark:
11767                         if (eofmark == NULL) {
11768                                 USTPUTC(CTLQUOTEMARK, out);
11769                         }
11770                         break;
11771                 case CDQUOTE:
11772                         syntax = DQSYNTAX;
11773                         dblquote = 1;
11774                         goto quotemark;
11775                 case CENDQUOTE:
11776                         IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11777                         if (eofmark != NULL && varnest == 0) {
11778                                 USTPUTC(c, out);
11779                         } else {
11780                                 if (dqvarnest == 0) {
11781                                         syntax = BASESYNTAX;
11782                                         dblquote = 0;
11783                                 }
11784                                 quotef = 1;
11785                                 goto quotemark;
11786                         }
11787                         break;
11788                 case CVAR:      /* '$' */
11789                         PARSESUB();             /* parse substitution */
11790                         break;
11791                 case CENDVAR:   /* '}' */
11792                         if (varnest > 0) {
11793                                 varnest--;
11794                                 if (dqvarnest > 0) {
11795                                         dqvarnest--;
11796                                 }
11797                                 c = CTLENDVAR;
11798                         }
11799                         USTPUTC(c, out);
11800                         break;
11801 #if ENABLE_FEATURE_SH_MATH
11802                 case CLP:       /* '(' in arithmetic */
11803                         parenlevel++;
11804                         USTPUTC(c, out);
11805                         break;
11806                 case CRP:       /* ')' in arithmetic */
11807                         if (parenlevel > 0) {
11808                                 parenlevel--;
11809                         } else {
11810                                 if (pgetc_eatbnl() == ')') {
11811                                         c = CTLENDARI;
11812                                         if (--arinest == 0) {
11813                                                 syntax = prevsyntax;
11814                                         }
11815                                 } else {
11816                                         /*
11817                                          * unbalanced parens
11818                                          * (don't 2nd guess - no error)
11819                                          */
11820                                         pungetc();
11821                                 }
11822                         }
11823                         USTPUTC(c, out);
11824                         break;
11825 #endif
11826                 case CBQUOTE:   /* '`' */
11827                         PARSEBACKQOLD();
11828                         break;
11829                 case CENDFILE:
11830                         goto endword;           /* exit outer loop */
11831                 case CIGN:
11832                         break;
11833                 default:
11834                         if (varnest == 0) {
11835 #if BASH_REDIR_OUTPUT
11836                                 if (c == '&') {
11837 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11838                                         if (pgetc() == '>')
11839                                                 c = 0x100 + '>'; /* flag &> */
11840                                         pungetc();
11841                                 }
11842 #endif
11843                                 goto endword;   /* exit outer loop */
11844                         }
11845                         IF_ASH_ALIAS(if (c != PEOA))
11846                                 USTPUTC(c, out);
11847                 }
11848                 c = pgetc();
11849         } /* for (;;) */
11850  endword:
11851
11852 #if ENABLE_FEATURE_SH_MATH
11853         if (syntax == ARISYNTAX)
11854                 raise_error_syntax("missing '))'");
11855 #endif
11856         if (syntax != BASESYNTAX && eofmark == NULL)
11857                 raise_error_syntax("unterminated quoted string");
11858         if (varnest != 0) {
11859                 startlinno = g_parsefile->linno;
11860                 /* { */
11861                 raise_error_syntax("missing '}'");
11862         }
11863         USTPUTC('\0', out);
11864         len = out - (char *)stackblock();
11865         out = stackblock();
11866         if (eofmark == NULL) {
11867                 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11868                  && quotef == 0
11869                 ) {
11870                         if (isdigit_str9(out)) {
11871                                 PARSEREDIR(); /* passed as params: out, c */
11872                                 lasttoken = TREDIR;
11873                                 return lasttoken;
11874                         }
11875                         /* else: non-number X seen, interpret it
11876                          * as "NNNX>file" = "NNNX >file" */
11877                 }
11878                 pungetc();
11879         }
11880         quoteflag = quotef;
11881         backquotelist = bqlist;
11882         grabstackblock(len);
11883         wordtext = out;
11884         lasttoken = TWORD;
11885         return lasttoken;
11886 /* end of readtoken routine */
11887
11888 /*
11889  * Check to see whether we are at the end of the here document.  When this
11890  * is called, c is set to the first character of the next input line.  If
11891  * we are at the end of the here document, this routine sets the c to PEOF.
11892  */
11893 checkend: {
11894         if (realeofmark(eofmark)) {
11895                 int markloc;
11896                 char *p;
11897
11898 #if ENABLE_ASH_ALIAS
11899                 if (c == PEOA)
11900                         c = pgetc_without_PEOA();
11901 #endif
11902                 if (striptabs) {
11903                         while (c == '\t') {
11904                                 c = pgetc_without_PEOA();
11905                         }
11906                 }
11907
11908                 markloc = out - (char *)stackblock();
11909                 for (p = eofmark; STPUTC(c, out), *p; p++) {
11910                         if (c != *p)
11911                                 goto more_heredoc;
11912
11913                         c = pgetc_without_PEOA();
11914                 }
11915
11916                 if (c == '\n' || c == PEOF) {
11917                         c = PEOF;
11918                         g_parsefile->linno++;
11919                         needprompt = doprompt;
11920                 } else {
11921                         int len_here;
11922
11923  more_heredoc:
11924                         p = (char *)stackblock() + markloc + 1;
11925                         len_here = out - p;
11926
11927                         if (len_here) {
11928                                 len_here -= (c >= PEOF);
11929                                 c = p[-1];
11930
11931                                 if (len_here) {
11932                                         char *str;
11933
11934                                         str = alloca(len_here + 1);
11935                                         *(char *)mempcpy(str, p, len_here) = '\0';
11936
11937                                         pushstring(str, NULL);
11938                                 }
11939                         }
11940                 }
11941
11942                 STADJUST((char *)stackblock() + markloc - out, out);
11943         }
11944         goto checkend_return;
11945 }
11946
11947 /*
11948  * Parse a redirection operator.  The variable "out" points to a string
11949  * specifying the fd to be redirected.  The variable "c" contains the
11950  * first character of the redirection operator.
11951  */
11952 parseredir: {
11953         /* out is already checked to be a valid number or "" */
11954         int fd = (*out == '\0' ? -1 : atoi(out));
11955         union node *np;
11956
11957         np = stzalloc(sizeof(struct nfile));
11958         if (c == '>') {
11959                 np->nfile.fd = 1;
11960                 c = pgetc();
11961                 if (c == '>')
11962                         np->type = NAPPEND;
11963                 else if (c == '|')
11964                         np->type = NCLOBBER;
11965                 else if (c == '&')
11966                         np->type = NTOFD;
11967                         /* it also can be NTO2 (>&file), but we can't figure it out yet */
11968                 else {
11969                         np->type = NTO;
11970                         pungetc();
11971                 }
11972         }
11973 #if BASH_REDIR_OUTPUT
11974         else if (c == 0x100 + '>') { /* this flags &> redirection */
11975                 np->nfile.fd = 1;
11976                 pgetc(); /* this is '>', no need to check */
11977                 np->type = NTO2;
11978         }
11979 #endif
11980         else { /* c == '<' */
11981                 /*np->nfile.fd = 0; - stzalloc did it */
11982                 c = pgetc();
11983                 switch (c) {
11984                 case '<':
11985                         if (sizeof(struct nfile) != sizeof(struct nhere)) {
11986                                 np = stzalloc(sizeof(struct nhere));
11987                                 /*np->nfile.fd = 0; - stzalloc did it */
11988                         }
11989                         np->type = NHERE;
11990                         heredoc = stzalloc(sizeof(struct heredoc));
11991                         heredoc->here = np;
11992                         c = pgetc();
11993                         if (c == '-') {
11994                                 heredoc->striptabs = 1;
11995                         } else {
11996                                 /*heredoc->striptabs = 0; - stzalloc did it */
11997                                 pungetc();
11998                         }
11999                         break;
12000
12001                 case '&':
12002                         np->type = NFROMFD;
12003                         break;
12004
12005                 case '>':
12006                         np->type = NFROMTO;
12007                         break;
12008
12009                 default:
12010                         np->type = NFROM;
12011                         pungetc();
12012                         break;
12013                 }
12014         }
12015         if (fd >= 0)
12016                 np->nfile.fd = fd;
12017         redirnode = np;
12018         goto parseredir_return;
12019 }
12020
12021 /*
12022  * Parse a substitution.  At this point, we have read the dollar sign
12023  * and nothing else.
12024  */
12025
12026 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12027  * (assuming ascii char codes, as the original implementation did) */
12028 #define is_special(c) \
12029         (((unsigned)(c) - 33 < 32) \
12030                         && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12031 parsesub: {
12032         unsigned char subtype;
12033         int typeloc;
12034
12035         c = pgetc_eatbnl();
12036         if ((checkkwd & CHKEOFMARK)
12037          || c > 255 /* PEOA or PEOF */
12038          || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12039         ) {
12040 #if BASH_DOLLAR_SQUOTE
12041                 if (syntax != DQSYNTAX && c == '\'')
12042                         bash_dollar_squote = 1;
12043                 else
12044 #endif
12045                         USTPUTC('$', out);
12046                 pungetc();
12047         } else if (c == '(') {
12048                 /* $(command) or $((arith)) */
12049                 if (pgetc_eatbnl() == '(') {
12050 #if ENABLE_FEATURE_SH_MATH
12051                         PARSEARITH();
12052 #else
12053                         raise_error_syntax("support for $((arith)) is disabled");
12054 #endif
12055                 } else {
12056                         pungetc();
12057                         PARSEBACKQNEW();
12058                 }
12059         } else {
12060                 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12061                 USTPUTC(CTLVAR, out);
12062                 typeloc = out - (char *)stackblock();
12063                 STADJUST(1, out);
12064                 subtype = VSNORMAL;
12065                 if (c == '{') {
12066                         c = pgetc_eatbnl();
12067                         subtype = 0;
12068                 }
12069  varname:
12070                 if (is_name(c)) {
12071                         /* $[{[#]]NAME[}] */
12072                         do {
12073                                 STPUTC(c, out);
12074                                 c = pgetc_eatbnl();
12075                         } while (is_in_name(c));
12076                 } else if (isdigit(c)) {
12077                         /* $[{[#]]NUM[}] */
12078                         do {
12079                                 STPUTC(c, out);
12080                                 c = pgetc_eatbnl();
12081                         } while (isdigit(c));
12082                 } else if (is_special(c)) {
12083                         /* $[{[#]]<specialchar>[}] */
12084                         int cc = c;
12085
12086                         c = pgetc_eatbnl();
12087                         if (!subtype && cc == '#') {
12088                                 subtype = VSLENGTH;
12089                                 if (c == '_' || isalnum(c))
12090                                         goto varname;
12091                                 cc = c;
12092                                 c = pgetc_eatbnl();
12093                                 if (cc == '}' || c != '}') {
12094                                         pungetc();
12095                                         subtype = 0;
12096                                         c = cc;
12097                                         cc = '#';
12098                                 }
12099                         }
12100                         USTPUTC(cc, out);
12101                 } else {
12102                         goto badsub;
12103                 }
12104                 if (c != '}' && subtype == VSLENGTH) {
12105                         /* ${#VAR didn't end with } */
12106                         goto badsub;
12107                 }
12108
12109                 if (subtype == 0) {
12110                         static const char types[] ALIGN1 = "}-+?=";
12111                         /* ${VAR...} but not $VAR or ${#VAR} */
12112                         /* c == first char after VAR */
12113                         switch (c) {
12114                         case ':':
12115                                 c = pgetc_eatbnl();
12116 #if BASH_SUBSTR
12117                                 /* This check is only needed to not misinterpret
12118                                  * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12119                                  * constructs.
12120                                  */
12121                                 if (!strchr(types, c)) {
12122                                         subtype = VSSUBSTR;
12123                                         pungetc();
12124                                         break; /* "goto badsub" is bigger (!) */
12125                                 }
12126 #endif
12127                                 subtype = VSNUL;
12128                                 /*FALLTHROUGH*/
12129                         default: {
12130                                 const char *p = strchr(types, c);
12131                                 if (p == NULL)
12132                                         break;
12133                                 subtype |= p - types + VSNORMAL;
12134                                 break;
12135                         }
12136                         case '%':
12137                         case '#': {
12138                                 int cc = c;
12139                                 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12140                                 c = pgetc_eatbnl();
12141                                 if (c != cc)
12142                                         goto badsub;
12143                                 subtype++;
12144                                 break;
12145                         }
12146 #if BASH_PATTERN_SUBST
12147                         case '/':
12148                                 /* ${v/[/]pattern/repl} */
12149 //TODO: encode pattern and repl separately.
12150 // Currently ${v/$var_with_slash/repl} is horribly broken
12151                                 subtype = VSREPLACE;
12152                                 c = pgetc_eatbnl();
12153                                 if (c != '/')
12154                                         goto badsub;
12155                                 subtype++; /* VSREPLACEALL */
12156                                 break;
12157 #endif
12158                         }
12159                 } else {
12160  badsub:
12161                         pungetc();
12162                 }
12163                 ((unsigned char *)stackblock())[typeloc] = subtype;
12164                 if (subtype != VSNORMAL) {
12165                         varnest++;
12166                         if (dblquote)
12167                                 dqvarnest++;
12168                 }
12169                 STPUTC('=', out);
12170         }
12171         goto parsesub_return;
12172 }
12173
12174 /*
12175  * Called to parse command substitutions.  Newstyle is set if the command
12176  * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12177  * list of commands (passed by reference), and savelen is the number of
12178  * characters on the top of the stack which must be preserved.
12179  */
12180 parsebackq: {
12181         struct nodelist **nlpp;
12182         union node *n;
12183         char *str;
12184         size_t savelen;
12185         smallint saveprompt = 0;
12186
12187         str = NULL;
12188         savelen = out - (char *)stackblock();
12189         if (savelen > 0) {
12190                 /*
12191                  * FIXME: this can allocate very large block on stack and SEGV.
12192                  * Example:
12193                  * echo "..<100kbytes>..`true` $(true) `true` ..."
12194                  * allocates 100kb for every command subst. With about
12195                  * a hundred command substitutions stack overflows.
12196                  * With larger prepended string, SEGV happens sooner.
12197                  */
12198                 str = alloca(savelen);
12199                 memcpy(str, stackblock(), savelen);
12200         }
12201
12202         if (oldstyle) {
12203                 /* We must read until the closing backquote, giving special
12204                  * treatment to some slashes, and then push the string and
12205                  * reread it as input, interpreting it normally.
12206                  */
12207                 char *pout;
12208                 size_t psavelen;
12209                 char *pstr;
12210
12211                 STARTSTACKSTR(pout);
12212                 for (;;) {
12213                         int pc;
12214
12215                         setprompt_if(needprompt, 2);
12216                         pc = pgetc();
12217                         switch (pc) {
12218                         case '`':
12219                                 goto done;
12220
12221                         case '\\':
12222                                 pc = pgetc();
12223                                 if (pc == '\n') {
12224                                         nlprompt();
12225                                         /*
12226                                          * If eating a newline, avoid putting
12227                                          * the newline into the new character
12228                                          * stream (via the STPUTC after the
12229                                          * switch).
12230                                          */
12231                                         continue;
12232                                 }
12233                                 if (pc != '\\' && pc != '`' && pc != '$'
12234                                  && (!dblquote || pc != '"')
12235                                 ) {
12236                                         STPUTC('\\', pout);
12237                                 }
12238                                 if (pc <= 255 /* not PEOA or PEOF */) {
12239                                         break;
12240                                 }
12241                                 /* fall through */
12242
12243                         case PEOF:
12244                         IF_ASH_ALIAS(case PEOA:)
12245                                 startlinno = g_parsefile->linno;
12246                                 raise_error_syntax("EOF in backquote substitution");
12247
12248                         case '\n':
12249                                 nlnoprompt();
12250                                 break;
12251
12252                         default:
12253                                 break;
12254                         }
12255                         STPUTC(pc, pout);
12256                 }
12257  done:
12258                 STPUTC('\0', pout);
12259                 psavelen = pout - (char *)stackblock();
12260                 if (psavelen > 0) {
12261                         pstr = grabstackstr(pout);
12262                         setinputstring(pstr);
12263                 }
12264         }
12265         nlpp = &bqlist;
12266         while (*nlpp)
12267                 nlpp = &(*nlpp)->next;
12268         *nlpp = stzalloc(sizeof(**nlpp));
12269         /* (*nlpp)->next = NULL; - stzalloc did it */
12270
12271         if (oldstyle) {
12272                 saveprompt = doprompt;
12273                 doprompt = 0;
12274         }
12275
12276         n = list(2);
12277
12278         if (oldstyle)
12279                 doprompt = saveprompt;
12280         else if (readtoken() != TRP)
12281                 raise_error_unexpected_syntax(TRP);
12282
12283         (*nlpp)->n = n;
12284         if (oldstyle) {
12285                 /*
12286                  * Start reading from old file again, ignoring any pushed back
12287                  * tokens left from the backquote parsing
12288                  */
12289                 popfile();
12290                 tokpushback = 0;
12291         }
12292         while (stackblocksize() <= savelen)
12293                 growstackblock();
12294         STARTSTACKSTR(out);
12295         if (str) {
12296                 memcpy(out, str, savelen);
12297                 STADJUST(savelen, out);
12298         }
12299         USTPUTC(CTLBACKQ, out);
12300         if (oldstyle)
12301                 goto parsebackq_oldreturn;
12302         goto parsebackq_newreturn;
12303 }
12304
12305 #if ENABLE_FEATURE_SH_MATH
12306 /*
12307  * Parse an arithmetic expansion (indicate start of one and set state)
12308  */
12309 parsearith: {
12310         if (++arinest == 1) {
12311                 prevsyntax = syntax;
12312                 syntax = ARISYNTAX;
12313         }
12314         USTPUTC(CTLARI, out);
12315         goto parsearith_return;
12316 }
12317 #endif
12318 } /* end of readtoken */
12319
12320 /*
12321  * Read the next input token.
12322  * If the token is a word, we set backquotelist to the list of cmds in
12323  *      backquotes.  We set quoteflag to true if any part of the word was
12324  *      quoted.
12325  * If the token is TREDIR, then we set redirnode to a structure containing
12326  *      the redirection.
12327  * In all cases, the variable startlinno is set to the number of the line
12328  *      on which the token starts.
12329  *
12330  * [Change comment:  here documents and internal procedures]
12331  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
12332  *  word parsing code into a separate routine.  In this case, readtoken
12333  *  doesn't need to have any internal procedures, but parseword does.
12334  *  We could also make parseoperator in essence the main routine, and
12335  *  have parseword (readtoken1?) handle both words and redirection.]
12336  */
12337 #define NEW_xxreadtoken
12338 #ifdef NEW_xxreadtoken
12339 /* singles must be first! */
12340 static const char xxreadtoken_chars[7] ALIGN1 = {
12341         '\n', '(', ')', /* singles */
12342         '&', '|', ';',  /* doubles */
12343         0
12344 };
12345
12346 #define xxreadtoken_singles 3
12347 #define xxreadtoken_doubles 3
12348
12349 static const char xxreadtoken_tokens[] ALIGN1 = {
12350         TNL, TLP, TRP,          /* only single occurrence allowed */
12351         TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12352         TEOF,                   /* corresponds to trailing nul */
12353         TAND, TOR, TENDCASE     /* if double occurrence */
12354 };
12355
12356 static int
12357 xxreadtoken(void)
12358 {
12359         int c;
12360
12361         if (tokpushback) {
12362                 tokpushback = 0;
12363                 return lasttoken;
12364         }
12365         setprompt_if(needprompt, 2);
12366         startlinno = g_parsefile->linno;
12367         for (;;) {                      /* until token or start of word found */
12368                 c = pgetc();
12369                 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12370                         continue;
12371
12372                 if (c == '#') {
12373                         while ((c = pgetc()) != '\n' && c != PEOF)
12374                                 continue;
12375                         pungetc();
12376                 } else if (c == '\\') {
12377                         if (pgetc() != '\n') {
12378                                 pungetc();
12379                                 break; /* return readtoken1(...) */
12380                         }
12381                         nlprompt();
12382                 } else {
12383                         const char *p;
12384
12385                         p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12386                         if (c != PEOF) {
12387                                 if (c == '\n') {
12388                                         nlnoprompt();
12389                                 }
12390
12391                                 p = strchr(xxreadtoken_chars, c);
12392                                 if (p == NULL)
12393                                         break; /* return readtoken1(...) */
12394
12395                                 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12396                                         int cc = pgetc();
12397                                         if (cc == c) {    /* double occurrence? */
12398                                                 p += xxreadtoken_doubles + 1;
12399                                         } else {
12400                                                 pungetc();
12401 #if BASH_REDIR_OUTPUT
12402                                                 if (c == '&' && cc == '>') /* &> */
12403                                                         break; /* return readtoken1(...) */
12404 #endif
12405                                         }
12406                                 }
12407                         }
12408                         lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12409                         return lasttoken;
12410                 }
12411         } /* for (;;) */
12412
12413         return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12414 }
12415 #else /* old xxreadtoken */
12416 #define RETURN(token)   return lasttoken = token
12417 static int
12418 xxreadtoken(void)
12419 {
12420         int c;
12421
12422         if (tokpushback) {
12423                 tokpushback = 0;
12424                 return lasttoken;
12425         }
12426         setprompt_if(needprompt, 2);
12427         startlinno = g_parsefile->linno;
12428         for (;;) {      /* until token or start of word found */
12429                 c = pgetc();
12430                 switch (c) {
12431                 case ' ': case '\t':
12432                 IF_ASH_ALIAS(case PEOA:)
12433                         continue;
12434                 case '#':
12435                         while ((c = pgetc()) != '\n' && c != PEOF)
12436                                 continue;
12437                         pungetc();
12438                         continue;
12439                 case '\\':
12440                         if (pgetc() == '\n') {
12441                                 nlprompt();
12442                                 continue;
12443                         }
12444                         pungetc();
12445                         goto breakloop;
12446                 case '\n':
12447                         nlnoprompt();
12448                         RETURN(TNL);
12449                 case PEOF:
12450                         RETURN(TEOF);
12451                 case '&':
12452                         if (pgetc() == '&')
12453                                 RETURN(TAND);
12454                         pungetc();
12455                         RETURN(TBACKGND);
12456                 case '|':
12457                         if (pgetc() == '|')
12458                                 RETURN(TOR);
12459                         pungetc();
12460                         RETURN(TPIPE);
12461                 case ';':
12462                         if (pgetc() == ';')
12463                                 RETURN(TENDCASE);
12464                         pungetc();
12465                         RETURN(TSEMI);
12466                 case '(':
12467                         RETURN(TLP);
12468                 case ')':
12469                         RETURN(TRP);
12470                 default:
12471                         goto breakloop;
12472                 }
12473         }
12474  breakloop:
12475         return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12476 #undef RETURN
12477 }
12478 #endif /* old xxreadtoken */
12479
12480 static int
12481 readtoken(void)
12482 {
12483         int t;
12484         int kwd = checkkwd;
12485 #if DEBUG
12486         smallint alreadyseen = tokpushback;
12487 #endif
12488
12489 #if ENABLE_ASH_ALIAS
12490  top:
12491 #endif
12492
12493         t = xxreadtoken();
12494
12495         /*
12496          * eat newlines
12497          */
12498         if (kwd & CHKNL) {
12499                 while (t == TNL) {
12500                         parseheredoc();
12501                         t = xxreadtoken();
12502                 }
12503         }
12504
12505         if (t != TWORD || quoteflag) {
12506                 goto out;
12507         }
12508
12509         /*
12510          * check for keywords
12511          */
12512         if (kwd & CHKKWD) {
12513                 const char *const *pp;
12514
12515                 pp = findkwd(wordtext);
12516                 if (pp) {
12517                         lasttoken = t = pp - tokname_array;
12518                         TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12519                         goto out;
12520                 }
12521         }
12522
12523         if (checkkwd & CHKALIAS) {
12524 #if ENABLE_ASH_ALIAS
12525                 struct alias *ap;
12526                 ap = lookupalias(wordtext, 1);
12527                 if (ap != NULL) {
12528                         if (*ap->val) {
12529                                 pushstring(ap->val, ap);
12530                         }
12531                         goto top;
12532                 }
12533 #endif
12534         }
12535  out:
12536         checkkwd = 0;
12537 #if DEBUG
12538         if (!alreadyseen)
12539                 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12540         else
12541                 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12542 #endif
12543         return t;
12544 }
12545
12546 static int
12547 peektoken(void)
12548 {
12549         int t;
12550
12551         t = readtoken();
12552         tokpushback = 1;
12553         return t;
12554 }
12555
12556 /*
12557  * Read and parse a command.  Returns NODE_EOF on end of file.
12558  * (NULL is a valid parse tree indicating a blank line.)
12559  */
12560 static union node *
12561 parsecmd(int interact)
12562 {
12563         tokpushback = 0;
12564         checkkwd = 0;
12565         heredoclist = 0;
12566         doprompt = interact;
12567         setprompt_if(doprompt, doprompt);
12568         needprompt = 0;
12569         return list(1);
12570 }
12571
12572 /*
12573  * Input any here documents.
12574  */
12575 static void
12576 parseheredoc(void)
12577 {
12578         struct heredoc *here;
12579         union node *n;
12580
12581         here = heredoclist;
12582         heredoclist = NULL;
12583
12584         while (here) {
12585                 setprompt_if(needprompt, 2);
12586                 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12587                                 here->eofmark, here->striptabs);
12588                 n = stzalloc(sizeof(struct narg));
12589                 n->narg.type = NARG;
12590                 /*n->narg.next = NULL; - stzalloc did it */
12591                 n->narg.text = wordtext;
12592                 n->narg.backquote = backquotelist;
12593                 here->here->nhere.doc = n;
12594                 here = here->next;
12595         }
12596 }
12597
12598
12599 static const char *
12600 expandstr(const char *ps, int syntax_type)
12601 {
12602         union node n;
12603         int saveprompt;
12604
12605         /* XXX Fix (char *) cast. */
12606         setinputstring((char *)ps);
12607
12608         saveprompt = doprompt;
12609         doprompt = 0;
12610         readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12611         doprompt = saveprompt;
12612
12613         popfile();
12614
12615         n.narg.type = NARG;
12616         n.narg.next = NULL;
12617         n.narg.text = wordtext;
12618         n.narg.backquote = backquotelist;
12619
12620         expandarg(&n, NULL, EXP_QUOTED);
12621         return stackblock();
12622 }
12623
12624 static inline int
12625 parser_eof(void)
12626 {
12627         return tokpushback && lasttoken == TEOF;
12628 }
12629
12630 /*
12631  * Execute a command or commands contained in a string.
12632  */
12633 static int
12634 evalstring(char *s, int flags)
12635 {
12636         struct jmploc *volatile savehandler;
12637         struct jmploc jmploc;
12638         int ex;
12639
12640         union node *n;
12641         struct stackmark smark;
12642         int status;
12643
12644         s = sstrdup(s);
12645         setinputstring(s);
12646         setstackmark(&smark);
12647
12648         status = 0;
12649         /* On exception inside execution loop, we must popfile().
12650          * Try interactively:
12651          *      readonly a=a
12652          *      command eval "a=b"  # throws "is read only" error
12653          * "command BLTIN" is not supposed to abort (even in non-interactive use).
12654          * But if we skip popfile(), we hit EOF in eval's string, and exit.
12655          */
12656         savehandler = exception_handler;
12657         ex = setjmp(jmploc.loc);
12658         if (ex)
12659                 goto out;
12660         exception_handler = &jmploc;
12661
12662         while ((n = parsecmd(0)) != NODE_EOF) {
12663                 int i;
12664
12665                 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12666                 if (n)
12667                         status = i;
12668                 popstackmark(&smark);
12669                 if (evalskip)
12670                         break;
12671         }
12672  out:
12673         popstackmark(&smark);
12674         popfile();
12675         stunalloc(s);
12676
12677         exception_handler = savehandler;
12678         if (ex)
12679                 longjmp(exception_handler->loc, ex);
12680
12681         return status;
12682 }
12683
12684 /*
12685  * The eval command.
12686  */
12687 static int FAST_FUNC
12688 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12689 {
12690         char *p;
12691         char *concat;
12692
12693         if (argv[1]) {
12694                 p = argv[1];
12695                 argv += 2;
12696                 if (argv[0]) {
12697                         STARTSTACKSTR(concat);
12698                         for (;;) {
12699                                 concat = stack_putstr(p, concat);
12700                                 p = *argv++;
12701                                 if (p == NULL)
12702                                         break;
12703                                 STPUTC(' ', concat);
12704                         }
12705                         STPUTC('\0', concat);
12706                         p = grabstackstr(concat);
12707                 }
12708                 return evalstring(p, flags & EV_TESTED);
12709         }
12710         return 0;
12711 }
12712
12713 /*
12714  * Read and execute commands.
12715  * "Top" is nonzero for the top level command loop;
12716  * it turns on prompting if the shell is interactive.
12717  */
12718 static int
12719 cmdloop(int top)
12720 {
12721         union node *n;
12722         struct stackmark smark;
12723         int inter;
12724         int status = 0;
12725         int numeof = 0;
12726
12727         TRACE(("cmdloop(%d) called\n", top));
12728         for (;;) {
12729                 int skip;
12730
12731                 setstackmark(&smark);
12732 #if JOBS
12733                 if (doing_jobctl)
12734                         showjobs(SHOW_CHANGED|SHOW_STDERR);
12735 #endif
12736                 inter = 0;
12737                 if (iflag && top) {
12738                         inter++;
12739                         chkmail();
12740                 }
12741                 n = parsecmd(inter);
12742 #if DEBUG
12743                 if (DEBUG > 2 && debug && (n != NODE_EOF))
12744                         showtree(n);
12745 #endif
12746                 if (n == NODE_EOF) {
12747                         if (!top || numeof >= 50)
12748                                 break;
12749                         if (!stoppedjobs()) {
12750                                 if (!Iflag)
12751                                         break;
12752                                 out2str("\nUse \"exit\" to leave shell.\n");
12753                         }
12754                         numeof++;
12755                 } else if (nflag == 0) {
12756                         int i;
12757
12758                         /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12759                         job_warning >>= 1;
12760                         numeof = 0;
12761                         i = evaltree(n, 0);
12762                         if (n)
12763                                 status = i;
12764                 }
12765                 popstackmark(&smark);
12766                 skip = evalskip;
12767
12768                 if (skip) {
12769                         evalskip &= ~SKIPFUNC;
12770                         break;
12771                 }
12772         }
12773         return status;
12774 }
12775
12776 /*
12777  * Take commands from a file.  To be compatible we should do a path
12778  * search for the file, which is necessary to find sub-commands.
12779  */
12780 static char *
12781 find_dot_file(char *name)
12782 {
12783         char *fullname;
12784         const char *path = pathval();
12785         struct stat statb;
12786
12787         /* don't try this for absolute or relative paths */
12788         if (strchr(name, '/'))
12789                 return name;
12790
12791         while ((fullname = path_advance(&path, name)) != NULL) {
12792                 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12793                         /*
12794                          * Don't bother freeing here, since it will
12795                          * be freed by the caller.
12796                          */
12797                         return fullname;
12798                 }
12799                 if (fullname != name)
12800                         stunalloc(fullname);
12801         }
12802
12803         /* not found in the PATH */
12804         ash_msg_and_raise_error("%s: not found", name);
12805         /* NOTREACHED */
12806 }
12807
12808 static int FAST_FUNC
12809 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12810 {
12811         /* "false; . empty_file; echo $?" should print 0, not 1: */
12812         int status = 0;
12813         char *fullname;
12814         char **argv;
12815         char *args_need_save;
12816         volatile struct shparam saveparam;
12817
12818 //???
12819 //      struct strlist *sp;
12820 //      for (sp = cmdenviron; sp; sp = sp->next)
12821 //              setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12822
12823         nextopt(nullstr); /* handle possible "--" */
12824         argv = argptr;
12825
12826         if (!argv[0]) {
12827                 /* bash says: "bash: .: filename argument required" */
12828                 return 2; /* bash compat */
12829         }
12830
12831         /* This aborts if file isn't found, which is POSIXly correct.
12832          * bash returns exitcode 1 instead.
12833          */
12834         fullname = find_dot_file(argv[0]);
12835         argv++;
12836         args_need_save = argv[0];
12837         if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12838                 int argc;
12839                 saveparam = shellparam;
12840                 shellparam.malloced = 0;
12841                 argc = 1;
12842                 while (argv[argc])
12843                         argc++;
12844                 shellparam.nparam = argc;
12845                 shellparam.p = argv;
12846         };
12847
12848         /* This aborts if file can't be opened, which is POSIXly correct.
12849          * bash returns exitcode 1 instead.
12850          */
12851         setinputfile(fullname, INPUT_PUSH_FILE);
12852         commandname = fullname;
12853         status = cmdloop(0);
12854         popfile();
12855
12856         if (args_need_save) {
12857                 freeparam(&shellparam);
12858                 shellparam = saveparam;
12859         };
12860
12861         return status;
12862 }
12863
12864 static int FAST_FUNC
12865 exitcmd(int argc UNUSED_PARAM, char **argv)
12866 {
12867         if (stoppedjobs())
12868                 return 0;
12869         if (argv[1])
12870                 exitstatus = number(argv[1]);
12871         raise_exception(EXEXIT);
12872         /* NOTREACHED */
12873 }
12874
12875 /*
12876  * Read a file containing shell functions.
12877  */
12878 static void
12879 readcmdfile(char *name)
12880 {
12881         setinputfile(name, INPUT_PUSH_FILE);
12882         cmdloop(0);
12883         popfile();
12884 }
12885
12886
12887 /* ============ find_command inplementation */
12888
12889 /*
12890  * Resolve a command name.  If you change this routine, you may have to
12891  * change the shellexec routine as well.
12892  */
12893 static void
12894 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12895 {
12896         struct tblentry *cmdp;
12897         int idx;
12898         int prev;
12899         char *fullname;
12900         struct stat statb;
12901         int e;
12902         int updatetbl;
12903         struct builtincmd *bcmd;
12904
12905         /* If name contains a slash, don't use PATH or hash table */
12906         if (strchr(name, '/') != NULL) {
12907                 entry->u.index = -1;
12908                 if (act & DO_ABS) {
12909                         while (stat(name, &statb) < 0) {
12910 #ifdef SYSV
12911                                 if (errno == EINTR)
12912                                         continue;
12913 #endif
12914                                 entry->cmdtype = CMDUNKNOWN;
12915                                 return;
12916                         }
12917                 }
12918                 entry->cmdtype = CMDNORMAL;
12919                 return;
12920         }
12921
12922 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12923
12924         updatetbl = (path == pathval());
12925         if (!updatetbl) {
12926                 act |= DO_ALTPATH;
12927                 if (strstr(path, "%builtin") != NULL)
12928                         act |= DO_ALTBLTIN;
12929         }
12930
12931         /* If name is in the table, check answer will be ok */
12932         cmdp = cmdlookup(name, 0);
12933         if (cmdp != NULL) {
12934                 int bit;
12935
12936                 switch (cmdp->cmdtype) {
12937                 default:
12938 #if DEBUG
12939                         abort();
12940 #endif
12941                 case CMDNORMAL:
12942                         bit = DO_ALTPATH;
12943                         break;
12944                 case CMDFUNCTION:
12945                         bit = DO_NOFUNC;
12946                         break;
12947                 case CMDBUILTIN:
12948                         bit = DO_ALTBLTIN;
12949                         break;
12950                 }
12951                 if (act & bit) {
12952                         updatetbl = 0;
12953                         cmdp = NULL;
12954                 } else if (cmdp->rehash == 0)
12955                         /* if not invalidated by cd, we're done */
12956                         goto success;
12957         }
12958
12959         /* If %builtin not in path, check for builtin next */
12960         bcmd = find_builtin(name);
12961         if (bcmd) {
12962                 if (IS_BUILTIN_REGULAR(bcmd))
12963                         goto builtin_success;
12964                 if (act & DO_ALTPATH) {
12965                         if (!(act & DO_ALTBLTIN))
12966                                 goto builtin_success;
12967                 } else if (builtinloc <= 0) {
12968                         goto builtin_success;
12969                 }
12970         }
12971
12972 #if ENABLE_FEATURE_SH_STANDALONE
12973         {
12974                 int applet_no = find_applet_by_name(name);
12975                 if (applet_no >= 0) {
12976                         entry->cmdtype = CMDNORMAL;
12977                         entry->u.index = -2 - applet_no;
12978                         return;
12979                 }
12980         }
12981 #endif
12982
12983         /* We have to search path. */
12984         prev = -1;              /* where to start */
12985         if (cmdp && cmdp->rehash) {     /* doing a rehash */
12986                 if (cmdp->cmdtype == CMDBUILTIN)
12987                         prev = builtinloc;
12988                 else
12989                         prev = cmdp->param.index;
12990         }
12991
12992         e = ENOENT;
12993         idx = -1;
12994  loop:
12995         while ((fullname = path_advance(&path, name)) != NULL) {
12996                 stunalloc(fullname);
12997                 /* NB: code below will still use fullname
12998                  * despite it being "unallocated" */
12999                 idx++;
13000                 if (pathopt) {
13001                         if (prefix(pathopt, "builtin")) {
13002                                 if (bcmd)
13003                                         goto builtin_success;
13004                                 continue;
13005                         }
13006                         if ((act & DO_NOFUNC)
13007                          || !prefix(pathopt, "func")
13008                         ) {     /* ignore unimplemented options */
13009                                 continue;
13010                         }
13011                 }
13012                 /* if rehash, don't redo absolute path names */
13013                 if (fullname[0] == '/' && idx <= prev) {
13014                         if (idx < prev)
13015                                 continue;
13016                         TRACE(("searchexec \"%s\": no change\n", name));
13017                         goto success;
13018                 }
13019                 while (stat(fullname, &statb) < 0) {
13020 #ifdef SYSV
13021                         if (errno == EINTR)
13022                                 continue;
13023 #endif
13024                         if (errno != ENOENT && errno != ENOTDIR)
13025                                 e = errno;
13026                         goto loop;
13027                 }
13028                 e = EACCES;     /* if we fail, this will be the error */
13029                 if (!S_ISREG(statb.st_mode))
13030                         continue;
13031                 if (pathopt) {          /* this is a %func directory */
13032                         stalloc(strlen(fullname) + 1);
13033                         /* NB: stalloc will return space pointed by fullname
13034                          * (because we don't have any intervening allocations
13035                          * between stunalloc above and this stalloc) */
13036                         readcmdfile(fullname);
13037                         cmdp = cmdlookup(name, 0);
13038                         if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13039                                 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13040                         stunalloc(fullname);
13041                         goto success;
13042                 }
13043                 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13044                 if (!updatetbl) {
13045                         entry->cmdtype = CMDNORMAL;
13046                         entry->u.index = idx;
13047                         return;
13048                 }
13049                 INT_OFF;
13050                 cmdp = cmdlookup(name, 1);
13051                 cmdp->cmdtype = CMDNORMAL;
13052                 cmdp->param.index = idx;
13053                 INT_ON;
13054                 goto success;
13055         }
13056
13057         /* We failed.  If there was an entry for this command, delete it */
13058         if (cmdp && updatetbl)
13059                 delete_cmd_entry();
13060         if (act & DO_ERR)
13061                 ash_msg("%s: %s", name, errmsg(e, "not found"));
13062         entry->cmdtype = CMDUNKNOWN;
13063         return;
13064
13065  builtin_success:
13066         if (!updatetbl) {
13067                 entry->cmdtype = CMDBUILTIN;
13068                 entry->u.cmd = bcmd;
13069                 return;
13070         }
13071         INT_OFF;
13072         cmdp = cmdlookup(name, 1);
13073         cmdp->cmdtype = CMDBUILTIN;
13074         cmdp->param.cmd = bcmd;
13075         INT_ON;
13076  success:
13077         cmdp->rehash = 0;
13078         entry->cmdtype = cmdp->cmdtype;
13079         entry->u = cmdp->param;
13080 }
13081
13082
13083 /*
13084  * The trap builtin.
13085  */
13086 static int FAST_FUNC
13087 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13088 {
13089         char *action;
13090         char **ap;
13091         int signo, exitcode;
13092
13093         nextopt(nullstr);
13094         ap = argptr;
13095         if (!*ap) {
13096                 for (signo = 0; signo < NSIG; signo++) {
13097                         char *tr = trap_ptr[signo];
13098                         if (tr) {
13099                                 /* note: bash adds "SIG", but only if invoked
13100                                  * as "bash". If called as "sh", or if set -o posix,
13101                                  * then it prints short signal names.
13102                                  * We are printing short names: */
13103                                 out1fmt("trap -- %s %s\n",
13104                                                 single_quote(tr),
13105                                                 get_signame(signo));
13106                 /* trap_ptr != trap only if we are in special-cased `trap` code.
13107                  * In this case, we will exit very soon, no need to free(). */
13108                                 /* if (trap_ptr != trap && tp[0]) */
13109                                 /*      free(tr); */
13110                         }
13111                 }
13112                 /*
13113                 if (trap_ptr != trap) {
13114                         free(trap_ptr);
13115                         trap_ptr = trap;
13116                 }
13117                 */
13118                 return 0;
13119         }
13120
13121         /* Why the second check?
13122          * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13123          * In this case, NUM is signal no, not an action.
13124          */
13125         action = NULL;
13126         if (ap[1] && !is_number(ap[0]))
13127                 action = *ap++;
13128
13129         exitcode = 0;
13130         while (*ap) {
13131                 signo = get_signum(*ap);
13132                 if (signo < 0) {
13133                         /* Mimic bash message exactly */
13134                         ash_msg("%s: invalid signal specification", *ap);
13135                         exitcode = 1;
13136                         goto next;
13137                 }
13138                 INT_OFF;
13139                 if (action) {
13140                         if (LONE_DASH(action))
13141                                 action = NULL;
13142                         else {
13143                                 if (action[0]) /* not NULL and not "" and not "-" */
13144                                         may_have_traps = 1;
13145                                 action = ckstrdup(action);
13146                         }
13147                 }
13148                 free(trap[signo]);
13149                 trap[signo] = action;
13150                 if (signo != 0)
13151                         setsignal(signo);
13152                 INT_ON;
13153  next:
13154                 ap++;
13155         }
13156         return exitcode;
13157 }
13158
13159
13160 /* ============ Builtins */
13161
13162 #if ENABLE_ASH_HELP
13163 static int FAST_FUNC
13164 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13165 {
13166         unsigned col;
13167         unsigned i;
13168
13169         out1fmt(
13170                 "Built-in commands:\n"
13171                 "------------------\n");
13172         for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13173                 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13174                                         builtintab[i].name + 1);
13175                 if (col > 60) {
13176                         out1fmt("\n");
13177                         col = 0;
13178                 }
13179         }
13180 # if ENABLE_FEATURE_SH_STANDALONE
13181         {
13182                 const char *a = applet_names;
13183                 while (*a) {
13184                         col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13185                         if (col > 60) {
13186                                 out1fmt("\n");
13187                                 col = 0;
13188                         }
13189                         while (*a++ != '\0')
13190                                 continue;
13191                 }
13192         }
13193 # endif
13194         newline_and_flush(stdout);
13195         return EXIT_SUCCESS;
13196 }
13197 #endif
13198
13199 #if MAX_HISTORY
13200 static int FAST_FUNC
13201 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13202 {
13203         show_history(line_input_state);
13204         return EXIT_SUCCESS;
13205 }
13206 #endif
13207
13208 /*
13209  * The export and readonly commands.
13210  */
13211 static int FAST_FUNC
13212 exportcmd(int argc UNUSED_PARAM, char **argv)
13213 {
13214         struct var *vp;
13215         char *name;
13216         const char *p;
13217         char **aptr;
13218         char opt;
13219         int flag;
13220         int flag_off;
13221
13222         /* "readonly" in bash accepts, but ignores -n.
13223          * We do the same: it saves a conditional in nextopt's param.
13224          */
13225         flag_off = 0;
13226         while ((opt = nextopt("np")) != '\0') {
13227                 if (opt == 'n')
13228                         flag_off = VEXPORT;
13229         }
13230         flag = VEXPORT;
13231         if (argv[0][0] == 'r') {
13232                 flag = VREADONLY;
13233                 flag_off = 0; /* readonly ignores -n */
13234         }
13235         flag_off = ~flag_off;
13236
13237         /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13238         {
13239                 aptr = argptr;
13240                 name = *aptr;
13241                 if (name) {
13242                         do {
13243                                 p = strchr(name, '=');
13244                                 if (p != NULL) {
13245                                         p++;
13246                                 } else {
13247                                         vp = *findvar(hashvar(name), name);
13248                                         if (vp) {
13249                                                 vp->flags = ((vp->flags | flag) & flag_off);
13250                                                 continue;
13251                                         }
13252                                 }
13253                                 setvar(name, p, (flag & flag_off));
13254                         } while ((name = *++aptr) != NULL);
13255                         return 0;
13256                 }
13257         }
13258
13259         /* No arguments. Show the list of exported or readonly vars.
13260          * -n is ignored.
13261          */
13262         showvars(argv[0], flag, 0);
13263         return 0;
13264 }
13265
13266 /*
13267  * Delete a function if it exists.
13268  */
13269 static void
13270 unsetfunc(const char *name)
13271 {
13272         struct tblentry *cmdp;
13273
13274         cmdp = cmdlookup(name, 0);
13275         if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13276                 delete_cmd_entry();
13277 }
13278
13279 /*
13280  * The unset builtin command.  We unset the function before we unset the
13281  * variable to allow a function to be unset when there is a readonly variable
13282  * with the same name.
13283  */
13284 static int FAST_FUNC
13285 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13286 {
13287         char **ap;
13288         int i;
13289         int flag = 0;
13290
13291         while ((i = nextopt("vf")) != 0) {
13292                 flag = i;
13293         }
13294
13295         for (ap = argptr; *ap; ap++) {
13296                 if (flag != 'f') {
13297                         unsetvar(*ap);
13298                         continue;
13299                 }
13300                 if (flag != 'v')
13301                         unsetfunc(*ap);
13302         }
13303         return 0;
13304 }
13305
13306 static const unsigned char timescmd_str[] ALIGN1 = {
13307         ' ',  offsetof(struct tms, tms_utime),
13308         '\n', offsetof(struct tms, tms_stime),
13309         ' ',  offsetof(struct tms, tms_cutime),
13310         '\n', offsetof(struct tms, tms_cstime),
13311         0
13312 };
13313 static int FAST_FUNC
13314 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13315 {
13316         unsigned long clk_tck, s, t;
13317         const unsigned char *p;
13318         struct tms buf;
13319
13320         clk_tck = bb_clk_tck();
13321         times(&buf);
13322
13323         p = timescmd_str;
13324         do {
13325                 t = *(clock_t *)(((char *) &buf) + p[1]);
13326                 s = t / clk_tck;
13327                 t = t % clk_tck;
13328                 out1fmt("%lum%lu.%03lus%c",
13329                         s / 60, s % 60,
13330                         (t * 1000) / clk_tck,
13331                         p[0]);
13332                 p += 2;
13333         } while (*p);
13334
13335         return 0;
13336 }
13337
13338 #if ENABLE_FEATURE_SH_MATH
13339 /*
13340  * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13341  * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13342  *
13343  * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13344  */
13345 static int FAST_FUNC
13346 letcmd(int argc UNUSED_PARAM, char **argv)
13347 {
13348         arith_t i;
13349
13350         argv++;
13351         if (!*argv)
13352                 ash_msg_and_raise_error("expression expected");
13353         do {
13354                 i = ash_arith(*argv);
13355         } while (*++argv);
13356
13357         return !i;
13358 }
13359 #endif
13360
13361 /*
13362  * The read builtin. Options:
13363  *      -r              Do not interpret '\' specially
13364  *      -s              Turn off echo (tty only)
13365  *      -n NCHARS       Read NCHARS max
13366  *      -p PROMPT       Display PROMPT on stderr (if input is from tty)
13367  *      -t SECONDS      Timeout after SECONDS (tty or pipe only)
13368  *      -u FD           Read from given FD instead of fd 0
13369  * This uses unbuffered input, which may be avoidable in some cases.
13370  * TODO: bash also has:
13371  *      -a ARRAY        Read into array[0],[1],etc
13372  *      -d DELIM        End on DELIM char, not newline
13373  *      -e              Use line editing (tty only)
13374  */
13375 static int FAST_FUNC
13376 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13377 {
13378         char *opt_n = NULL;
13379         char *opt_p = NULL;
13380         char *opt_t = NULL;
13381         char *opt_u = NULL;
13382         int read_flags = 0;
13383         const char *r;
13384         int i;
13385
13386         while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13387                 switch (i) {
13388                 case 'p':
13389                         opt_p = optionarg;
13390                         break;
13391                 case 'n':
13392                         opt_n = optionarg;
13393                         break;
13394                 case 's':
13395                         read_flags |= BUILTIN_READ_SILENT;
13396                         break;
13397                 case 't':
13398                         opt_t = optionarg;
13399                         break;
13400                 case 'r':
13401                         read_flags |= BUILTIN_READ_RAW;
13402                         break;
13403                 case 'u':
13404                         opt_u = optionarg;
13405                         break;
13406                 default:
13407                         break;
13408                 }
13409         }
13410
13411         /* "read -s" needs to save/restore termios, can't allow ^C
13412          * to jump out of it.
13413          */
13414  again:
13415         INT_OFF;
13416         r = shell_builtin_read(setvar0,
13417                 argptr,
13418                 bltinlookup("IFS"), /* can be NULL */
13419                 read_flags,
13420                 opt_n,
13421                 opt_p,
13422                 opt_t,
13423                 opt_u
13424         );
13425         INT_ON;
13426
13427         if ((uintptr_t)r == 1 && errno == EINTR) {
13428                 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13429                 if (pending_sig == 0)
13430                         goto again;
13431         }
13432
13433         if ((uintptr_t)r > 1)
13434                 ash_msg_and_raise_error(r);
13435
13436         return (uintptr_t)r;
13437 }
13438
13439 static int FAST_FUNC
13440 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13441 {
13442         static const char permuser[3] ALIGN1 = "ogu";
13443
13444         mode_t mask;
13445         int symbolic_mode = 0;
13446
13447         while (nextopt("S") != '\0') {
13448                 symbolic_mode = 1;
13449         }
13450
13451         INT_OFF;
13452         mask = umask(0);
13453         umask(mask);
13454         INT_ON;
13455
13456         if (*argptr == NULL) {
13457                 if (symbolic_mode) {
13458                         char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13459                         char *p = buf;
13460                         int i;
13461
13462                         i = 2;
13463                         for (;;) {
13464                                 *p++ = ',';
13465                                 *p++ = permuser[i];
13466                                 *p++ = '=';
13467                                 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13468                                 if (!(mask & 0400)) *p++ = 'r';
13469                                 if (!(mask & 0200)) *p++ = 'w';
13470                                 if (!(mask & 0100)) *p++ = 'x';
13471                                 mask <<= 3;
13472                                 if (--i < 0)
13473                                         break;
13474                         }
13475                         *p = '\0';
13476                         puts(buf + 1);
13477                 } else {
13478                         out1fmt("%04o\n", mask);
13479                 }
13480         } else {
13481                 char *modestr = *argptr;
13482                 /* numeric umasks are taken as-is */
13483                 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13484                 if (!isdigit(modestr[0]))
13485                         mask ^= 0777;
13486                 mask = bb_parse_mode(modestr, mask);
13487                 if ((unsigned)mask > 0777) {
13488                         ash_msg_and_raise_error("illegal mode: %s", modestr);
13489                 }
13490                 if (!isdigit(modestr[0]))
13491                         mask ^= 0777;
13492                 umask(mask);
13493         }
13494         return 0;
13495 }
13496
13497 static int FAST_FUNC
13498 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13499 {
13500         return shell_builtin_ulimit(argv);
13501 }
13502
13503 /* ============ main() and helpers */
13504
13505 /*
13506  * Called to exit the shell.
13507  */
13508 static void
13509 exitshell(void)
13510 {
13511         struct jmploc loc;
13512         char *p;
13513         int status;
13514
13515 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13516         save_history(line_input_state);
13517 #endif
13518         status = exitstatus;
13519         TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13520         if (setjmp(loc.loc)) {
13521                 if (exception_type == EXEXIT)
13522                         status = exitstatus;
13523                 goto out;
13524         }
13525         exception_handler = &loc;
13526         p = trap[0];
13527         if (p) {
13528                 trap[0] = NULL;
13529                 evalskip = 0;
13530                 evalstring(p, 0);
13531                 /*free(p); - we'll exit soon */
13532         }
13533  out:
13534         /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13535          * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13536          */
13537         setjobctl(0);
13538         flush_stdout_stderr();
13539         _exit(status);
13540         /* NOTREACHED */
13541 }
13542
13543 static void
13544 init(void)
13545 {
13546         /* we will never free this */
13547         basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13548
13549         sigmode[SIGCHLD - 1] = S_DFL;
13550         setsignal(SIGCHLD);
13551
13552         /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13553          * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13554          */
13555         signal(SIGHUP, SIG_DFL);
13556
13557         {
13558                 char **envp;
13559                 const char *p;
13560                 struct stat st1, st2;
13561
13562                 initvar();
13563                 for (envp = environ; envp && *envp; envp++) {
13564                         p = endofname(*envp);
13565                         if (p != *envp && *p == '=') {
13566                                 setvareq(*envp, VEXPORT|VTEXTFIXED);
13567                         }
13568                 }
13569
13570                 setvareq((char*)defoptindvar, VTEXTFIXED);
13571
13572                 setvar0("PPID", utoa(getppid()));
13573 #if BASH_SHLVL_VAR
13574                 p = lookupvar("SHLVL");
13575                 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13576 #endif
13577 #if BASH_HOSTNAME_VAR
13578                 if (!lookupvar("HOSTNAME")) {
13579                         struct utsname uts;
13580                         uname(&uts);
13581                         setvar0("HOSTNAME", uts.nodename);
13582                 }
13583 #endif
13584                 p = lookupvar("PWD");
13585                 if (p) {
13586                         if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13587                          || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13588                         ) {
13589                                 p = NULL;
13590                         }
13591                 }
13592                 setpwd(p, 0);
13593         }
13594 }
13595
13596
13597 //usage:#define ash_trivial_usage
13598 //usage:        "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13599 //usage:#define ash_full_usage "\n\n"
13600 //usage:        "Unix shell interpreter"
13601
13602 /*
13603  * Process the shell command line arguments.
13604  */
13605 static void
13606 procargs(char **argv)
13607 {
13608         int i;
13609         const char *xminusc;
13610         char **xargv;
13611
13612         xargv = argv;
13613         arg0 = xargv[0];
13614         /* if (xargv[0]) - mmm, this is always true! */
13615                 xargv++;
13616         for (i = 0; i < NOPTS; i++)
13617                 optlist[i] = 2;
13618         argptr = xargv;
13619         if (options(/*cmdline:*/ 1)) {
13620                 /* it already printed err message */
13621                 raise_exception(EXERROR);
13622         }
13623         xargv = argptr;
13624         xminusc = minusc;
13625         if (*xargv == NULL) {
13626                 if (xminusc)
13627                         ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13628                 sflag = 1;
13629         }
13630         if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13631                 iflag = 1;
13632         if (mflag == 2)
13633                 mflag = iflag;
13634         for (i = 0; i < NOPTS; i++)
13635                 if (optlist[i] == 2)
13636                         optlist[i] = 0;
13637 #if DEBUG == 2
13638         debug = 1;
13639 #endif
13640         /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13641         if (xminusc) {
13642                 minusc = *xargv++;
13643                 if (*xargv)
13644                         goto setarg0;
13645         } else if (!sflag) {
13646                 setinputfile(*xargv, 0);
13647  setarg0:
13648                 arg0 = *xargv++;
13649                 commandname = arg0;
13650         }
13651
13652         shellparam.p = xargv;
13653 #if ENABLE_ASH_GETOPTS
13654         shellparam.optind = 1;
13655         shellparam.optoff = -1;
13656 #endif
13657         /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13658         while (*xargv) {
13659                 shellparam.nparam++;
13660                 xargv++;
13661         }
13662         optschanged();
13663 }
13664
13665 /*
13666  * Read /etc/profile, ~/.profile, $ENV.
13667  */
13668 static void
13669 read_profile(const char *name)
13670 {
13671         name = expandstr(name, DQSYNTAX);
13672         if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13673                 return;
13674         cmdloop(0);
13675         popfile();
13676 }
13677
13678 /*
13679  * This routine is called when an error or an interrupt occurs in an
13680  * interactive shell and control is returned to the main command loop.
13681  * (In dash, this function is auto-generated by build machinery).
13682  */
13683 static void
13684 reset(void)
13685 {
13686         /* from eval.c: */
13687         evalskip = 0;
13688         loopnest = 0;
13689
13690         /* from expand.c: */
13691         ifsfree();
13692
13693         /* from input.c: */
13694         g_parsefile->left_in_buffer = 0;
13695         g_parsefile->left_in_line = 0;      /* clear input buffer */
13696         popallfiles();
13697
13698         /* from redir.c: */
13699         unwindredir(NULL);
13700
13701         /* from var.c: */
13702         unwindlocalvars(NULL);
13703 }
13704
13705 #if PROFILE
13706 static short profile_buf[16384];
13707 extern int etext();
13708 #endif
13709
13710 /*
13711  * Main routine.  We initialize things, parse the arguments, execute
13712  * profiles if we're a login shell, and then call cmdloop to execute
13713  * commands.  The setjmp call sets up the location to jump to when an
13714  * exception occurs.  When an exception occurs the variable "state"
13715  * is used to figure out how far we had gotten.
13716  */
13717 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13718 int ash_main(int argc UNUSED_PARAM, char **argv)
13719 {
13720         volatile smallint state;
13721         struct jmploc jmploc;
13722         struct stackmark smark;
13723
13724         /* Initialize global data */
13725         INIT_G_misc();
13726         INIT_G_memstack();
13727         INIT_G_var();
13728 #if ENABLE_ASH_ALIAS
13729         INIT_G_alias();
13730 #endif
13731         INIT_G_cmdtable();
13732
13733 #if PROFILE
13734         monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13735 #endif
13736
13737 #if ENABLE_FEATURE_EDITING
13738         line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13739 #endif
13740         state = 0;
13741         if (setjmp(jmploc.loc)) {
13742                 smallint e;
13743                 smallint s;
13744
13745                 reset();
13746
13747                 e = exception_type;
13748                 s = state;
13749                 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13750                         exitshell();
13751                 }
13752                 if (e == EXINT) {
13753                         newline_and_flush(stderr);
13754                 }
13755
13756                 popstackmark(&smark);
13757                 FORCE_INT_ON; /* enable interrupts */
13758                 if (s == 1)
13759                         goto state1;
13760                 if (s == 2)
13761                         goto state2;
13762                 if (s == 3)
13763                         goto state3;
13764                 goto state4;
13765         }
13766         exception_handler = &jmploc;
13767         rootpid = getpid();
13768
13769         init();
13770         setstackmark(&smark);
13771         procargs(argv);
13772 #if DEBUG
13773         TRACE(("Shell args: "));
13774         trace_puts_args(argv);
13775 #endif
13776
13777         if (argv[0] && argv[0][0] == '-')
13778                 isloginsh = 1;
13779         if (isloginsh) {
13780                 const char *hp;
13781
13782                 state = 1;
13783                 read_profile("/etc/profile");
13784  state1:
13785                 state = 2;
13786                 hp = lookupvar("HOME");
13787                 if (hp)
13788                         read_profile("$HOME/.profile");
13789         }
13790  state2:
13791         state = 3;
13792         if (
13793 #ifndef linux
13794          getuid() == geteuid() && getgid() == getegid() &&
13795 #endif
13796          iflag
13797         ) {
13798                 const char *shinit = lookupvar("ENV");
13799                 if (shinit != NULL && *shinit != '\0')
13800                         read_profile(shinit);
13801         }
13802         popstackmark(&smark);
13803  state3:
13804         state = 4;
13805         if (minusc) {
13806                 /* evalstring pushes parsefile stack.
13807                  * Ensure we don't falsely claim that 0 (stdin)
13808                  * is one of stacked source fds.
13809                  * Testcase: ash -c 'exec 1>&0' must not complain. */
13810                 // if (!sflag) g_parsefile->pf_fd = -1;
13811                 // ^^ not necessary since now we special-case fd 0
13812                 // in save_fd_on_redirect()
13813                 evalstring(minusc, sflag ? 0 : EV_EXIT);
13814         }
13815
13816         if (sflag || minusc == NULL) {
13817 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13818                 if (iflag) {
13819                         const char *hp = lookupvar("HISTFILE");
13820                         if (!hp) {
13821                                 hp = lookupvar("HOME");
13822                                 if (hp) {
13823                                         INT_OFF;
13824                                         hp = concat_path_file(hp, ".ash_history");
13825                                         setvar0("HISTFILE", hp);
13826                                         free((char*)hp);
13827                                         INT_ON;
13828                                         hp = lookupvar("HISTFILE");
13829                                 }
13830                         }
13831                         if (hp)
13832                                 line_input_state->hist_file = hp;
13833 # if ENABLE_FEATURE_SH_HISTFILESIZE
13834                         hp = lookupvar("HISTFILESIZE");
13835                         line_input_state->max_history = size_from_HISTFILESIZE(hp);
13836 # endif
13837                 }
13838 #endif
13839  state4: /* XXX ??? - why isn't this before the "if" statement */
13840                 cmdloop(1);
13841         }
13842 #if PROFILE
13843         monitor(0);
13844 #endif
13845 #ifdef GPROF
13846         {
13847                 extern void _mcleanup(void);
13848                 _mcleanup();
13849         }
13850 #endif
13851         TRACE(("End of main reached\n"));
13852         exitshell();
13853         /* NOTREACHED */
13854 }
13855
13856
13857 /*-
13858  * Copyright (c) 1989, 1991, 1993, 1994
13859  *      The Regents of the University of California.  All rights reserved.
13860  *
13861  * This code is derived from software contributed to Berkeley by
13862  * Kenneth Almquist.
13863  *
13864  * Redistribution and use in source and binary forms, with or without
13865  * modification, are permitted provided that the following conditions
13866  * are met:
13867  * 1. Redistributions of source code must retain the above copyright
13868  *    notice, this list of conditions and the following disclaimer.
13869  * 2. Redistributions in binary form must reproduce the above copyright
13870  *    notice, this list of conditions and the following disclaimer in the
13871  *    documentation and/or other materials provided with the distribution.
13872  * 3. Neither the name of the University nor the names of its contributors
13873  *    may be used to endorse or promote products derived from this software
13874  *    without specific prior written permission.
13875  *
13876  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13877  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13878  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13879  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13880  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13881  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13882  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13883  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13884  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13885  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13886  * SUCH DAMAGE.
13887  */