c9962e33be672a3a9b8fb81c50ea0ca383e8bc88
[oweals/busybox.git] / shell / hush.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A prototype Bourne shell grammar parser.
4  * Intended to follow the original Thompson and Ritchie
5  * "small and simple is beautiful" philosophy, which
6  * incidentally is a good match to today's BusyBox.
7  *
8  * Copyright (C) 2000,2001  Larry Doolittle <larry@doolittle.boa.org>
9  * Copyright (C) 2008,2009  Denys Vlasenko <vda.linux@googlemail.com>
10  *
11  * Credits:
12  *      The parser routines proper are all original material, first
13  *      written Dec 2000 and Jan 2001 by Larry Doolittle.  The
14  *      execution engine, the builtins, and much of the underlying
15  *      support has been adapted from busybox-0.49pre's lash, which is
16  *      Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17  *      written by Erik Andersen <andersen@codepoet.org>.  That, in turn,
18  *      is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19  *      Troan, which they placed in the public domain.  I don't know
20  *      how much of the Johnson/Troan code has survived the repeated
21  *      rewrites.
22  *
23  * Other credits:
24  *      o_addchr derived from similar w_addchar function in glibc-2.2.
25  *      parse_redirect, redirect_opt_num, and big chunks of main
26  *      and many builtins derived from contributions by Erik Andersen.
27  *      Miscellaneous bugfixes from Matt Kraai.
28  *
29  * There are two big (and related) architecture differences between
30  * this parser and the lash parser.  One is that this version is
31  * actually designed from the ground up to understand nearly all
32  * of the Bourne grammar.  The second, consequential change is that
33  * the parser and input reader have been turned inside out.  Now,
34  * the parser is in control, and asks for input as needed.  The old
35  * way had the input reader in control, and it asked for parsing to
36  * take place as needed.  The new way makes it much easier to properly
37  * handle the recursion implicit in the various substitutions, especially
38  * across continuation lines.
39  *
40  * POSIX syntax not implemented:
41  *      aliases
42  *      <(list) and >(list) Process Substitution
43  *      Tilde Expansion
44  *
45  * Bash stuff (maybe optionally enable?):
46  *      &> and >& redirection of stdout+stderr
47  *      Brace Expansion
48  *      reserved words: [[ ]] function select
49  *      substrings ${var:1:5}
50  *
51  * TODOs:
52  *      grep for "TODO" and fix (some of them are easy)
53  *      builtins: ulimit
54  *      follow IFS rules more precisely, including update semantics
55  *      export builtin should be special, its arguments are assignments
56  *          and therefore expansion of them should be "one-word" expansion:
57  *              $ export i=`echo 'a  b'` # export has one arg: "i=a  b"
58  *          compare with:
59  *              $ ls i=`echo 'a  b'`     # ls has two args: "i=a" and "b"
60  *              ls: cannot access i=a: No such file or directory
61  *              ls: cannot access b: No such file or directory
62  *          Note1: same applies to local builtin when we'll have it.
63  *          Note2: bash 3.2.33(1) does this only if export word itself
64  *          is not quoted:
65  *              $ export i=`echo 'aaa  bbb'`; echo "$i"
66  *              aaa  bbb
67  *              $ "export" i=`echo 'aaa  bbb'`; echo "$i"
68  *              aaa
69  *
70  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
71  */
72 #include "busybox.h"  /* for APPLET_IS_NOFORK/NOEXEC */
73 #include <glob.h>
74 /* #include <dmalloc.h> */
75 #if ENABLE_HUSH_CASE
76 # include <fnmatch.h>
77 #endif
78 #include "math.h"
79 #include "match.h"
80 #ifndef PIPE_BUF
81 # define PIPE_BUF 4096  /* amount of buffering in a pipe */
82 #endif
83
84
85 /* Build knobs */
86 #define LEAK_HUNTING 0
87 #define BUILD_AS_NOMMU 0
88 /* Enable/disable sanity checks. Ok to enable in production,
89  * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
90  * Keeping 1 for now even in released versions.
91  */
92 #define HUSH_DEBUG 1
93 /* Slightly bigger (+200 bytes), but faster hush.
94  * So far it only enables a trick with counting SIGCHLDs and forks,
95  * which allows us to do fewer waitpid's.
96  * (we can detect a case where neither forks were done nor SIGCHLDs happened
97  * and therefore waitpid will return the same result as last time)
98  */
99 #define ENABLE_HUSH_FAST 0
100
101
102 #if BUILD_AS_NOMMU
103 # undef BB_MMU
104 # undef USE_FOR_NOMMU
105 # undef USE_FOR_MMU
106 # define BB_MMU 0
107 # define USE_FOR_NOMMU(...) __VA_ARGS__
108 # define USE_FOR_MMU(...)
109 #endif
110
111 #if defined SINGLE_APPLET_MAIN
112 /* STANDALONE does not make sense, and won't compile */
113 # undef CONFIG_FEATURE_SH_STANDALONE
114 # undef ENABLE_FEATURE_SH_STANDALONE
115 # undef IF_FEATURE_SH_STANDALONE
116 # define IF_FEATURE_SH_STANDALONE(...)
117 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
118 # define ENABLE_FEATURE_SH_STANDALONE 0
119 #endif
120
121 #if !ENABLE_HUSH_INTERACTIVE
122 # undef ENABLE_FEATURE_EDITING
123 # define ENABLE_FEATURE_EDITING 0
124 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
125 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
126 #endif
127
128 /* Do we support ANY keywords? */
129 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
130 # define HAS_KEYWORDS 1
131 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
132 # define IF_HAS_NO_KEYWORDS(...)
133 #else
134 # define HAS_KEYWORDS 0
135 # define IF_HAS_KEYWORDS(...)
136 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
137 #endif
138
139 /* If you comment out one of these below, it will be #defined later
140  * to perform debug printfs to stderr: */
141 #define debug_printf(...)        do {} while (0)
142 /* Finer-grained debug switches */
143 #define debug_printf_parse(...)  do {} while (0)
144 #define debug_print_tree(a, b)   do {} while (0)
145 #define debug_printf_exec(...)   do {} while (0)
146 #define debug_printf_env(...)    do {} while (0)
147 #define debug_printf_jobs(...)   do {} while (0)
148 #define debug_printf_expand(...) do {} while (0)
149 #define debug_printf_glob(...)   do {} while (0)
150 #define debug_printf_list(...)   do {} while (0)
151 #define debug_printf_subst(...)  do {} while (0)
152 #define debug_printf_clean(...)  do {} while (0)
153
154 #define ERR_PTR ((void*)(long)1)
155
156 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
157
158 #define SPECIAL_VAR_SYMBOL 3
159
160 struct variable;
161
162 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
163
164 /* This supports saving pointers malloced in vfork child,
165  * to be freed in the parent.
166  */
167 #if !BB_MMU
168 typedef struct nommu_save_t {
169         char **new_env;
170         struct variable *old_vars;
171         char **argv;
172         char **argv_from_re_execing;
173 } nommu_save_t;
174 #endif
175
176 typedef enum reserved_style {
177         RES_NONE  = 0,
178 #if ENABLE_HUSH_IF
179         RES_IF    ,
180         RES_THEN  ,
181         RES_ELIF  ,
182         RES_ELSE  ,
183         RES_FI    ,
184 #endif
185 #if ENABLE_HUSH_LOOPS
186         RES_FOR   ,
187         RES_WHILE ,
188         RES_UNTIL ,
189         RES_DO    ,
190         RES_DONE  ,
191 #endif
192 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
193         RES_IN    ,
194 #endif
195 #if ENABLE_HUSH_CASE
196         RES_CASE  ,
197         /* three pseudo-keywords support contrived "case" syntax: */
198         RES_CASE_IN,   /* "case ... IN", turns into RES_MATCH when IN is observed */
199         RES_MATCH ,    /* "word)" */
200         RES_CASE_BODY, /* "this command is inside CASE" */
201         RES_ESAC  ,
202 #endif
203         RES_XXXX  ,
204         RES_SNTX
205 } reserved_style;
206
207 typedef struct o_string {
208         char *data;
209         int length; /* position where data is appended */
210         int maxlen;
211         /* Protect newly added chars against globbing
212          * (by prepending \ to *, ?, [, \) */
213         smallint o_escape;
214         smallint o_glob;
215         /* At least some part of the string was inside '' or "",
216          * possibly empty one: word"", wo''rd etc. */
217         smallint o_quoted;
218         smallint has_empty_slot;
219         smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
220 } o_string;
221 enum {
222         MAYBE_ASSIGNMENT = 0,
223         DEFINITELY_ASSIGNMENT = 1,
224         NOT_ASSIGNMENT = 2,
225         WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
226 };
227 /* Used for initialization: o_string foo = NULL_O_STRING; */
228 #define NULL_O_STRING { NULL }
229
230 /* I can almost use ordinary FILE*.  Is open_memstream() universally
231  * available?  Where is it documented? */
232 typedef struct in_str {
233         const char *p;
234         /* eof_flag=1: last char in ->p is really an EOF */
235         char eof_flag; /* meaningless if ->p == NULL */
236         char peek_buf[2];
237 #if ENABLE_HUSH_INTERACTIVE
238         smallint promptme;
239         smallint promptmode; /* 0: PS1, 1: PS2 */
240 #endif
241         FILE *file;
242         int (*get) (struct in_str *) FAST_FUNC;
243         int (*peek) (struct in_str *) FAST_FUNC;
244 } in_str;
245 #define i_getch(input) ((input)->get(input))
246 #define i_peek(input) ((input)->peek(input))
247
248 /* The descrip member of this structure is only used to make
249  * debugging output pretty */
250 static const struct {
251         int mode;
252         signed char default_fd;
253         char descrip[3];
254 } redir_table[] = {
255         { O_RDONLY,                  0, "<"  },
256         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
257         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
258         { O_CREAT|O_RDWR,            1, "<>" },
259         { O_RDONLY,                  0, "<<" },
260 /* Should not be needed. Bogus default_fd helps in debugging */
261 /*      { O_RDONLY,                 77, "<<" }, */
262 };
263
264 struct redir_struct {
265         struct redir_struct *next;
266         char *rd_filename;          /* filename */
267         int rd_fd;                  /* fd to redirect */
268         /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
269         int rd_dup;
270         smallint rd_type;           /* (enum redir_type) */
271         /* note: for heredocs, rd_filename contains heredoc delimiter,
272          * and subsequently heredoc itself; and rd_dup is a bitmask:
273          * bit 0: do we need to trim leading tabs?
274          * bit 1: is heredoc quoted (<<'delim' syntax) ?
275          */
276 };
277 typedef enum redir_type {
278         REDIRECT_INPUT     = 0,
279         REDIRECT_OVERWRITE = 1,
280         REDIRECT_APPEND    = 2,
281         REDIRECT_IO        = 3,
282         REDIRECT_HEREDOC   = 4,
283         REDIRECT_HEREDOC2  = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
284
285         REDIRFD_CLOSE      = -3,
286         REDIRFD_SYNTAX_ERR = -2,
287         REDIRFD_TO_FILE    = -1,
288         /* otherwise, rd_fd is redirected to rd_dup */
289
290         HEREDOC_SKIPTABS = 1,
291         HEREDOC_QUOTED   = 2,
292 } redir_type;
293
294
295 struct command {
296         pid_t pid;                  /* 0 if exited */
297         int assignment_cnt;         /* how many argv[i] are assignments? */
298         smallint is_stopped;        /* is the command currently running? */
299         smallint cmd_type;          /* CMD_xxx */
300 #define CMD_NORMAL   0
301 #define CMD_SUBSHELL 1
302 /* used for "[[ EXPR ]]" */
303 #define CMD_SINGLEWORD_NOGLOB 2
304 /* used for "export noglob=* glob* a=`echo a b`" */
305 /* #define CMD_SINGLEWORD_NOGLOB_COND 3 */
306 // It is hard to implement correctly, adds significant amounts of tricky code,
307 // and all this only useful for really obscure export statements
308 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
309 // guard the code which implement it, but I have doubts it works
310 // in all cases (especially with mixed globbed/non-globbed arguments)
311 #if ENABLE_HUSH_FUNCTIONS
312 # define CMD_FUNCDEF 4
313 #endif
314 //TODO
315 //#define CMD_ARITH - let EXPR, ((EXPR))
316 //let EXPR [EXPR...]
317 // Each EXPR is an arithmetic expression to be evaluated (ARITHMETIC EVALUATION)
318 // If the last arg evaluates to 0, let returns 1; 0 is returned otherwise.
319 // NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
320 //((EXPR))
321 // The EXPR is evaluated according to ARITHMETIC EVALUATION.
322 // This is exactly equivalent to let "expression".
323 //[[ EXPR ]]
324 // Basically, word splitting and pathname expansion should NOT be performed
325 // Examples:
326 // no word splitting:     a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
327 // no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
328 // Additional operators:
329 // || and && should work as -o and -a
330 // =~ regexp match
331 // Apart from the above, [[ expr ]] should work as [ expr ]
332
333         /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
334         struct pipe *group;
335 #if !BB_MMU
336         char *group_as_string;
337 #endif
338 #if ENABLE_HUSH_FUNCTIONS
339         struct function *child_func;
340 /* This field is used to prevent a bug here:
341  * while...do f1() {a;}; f1; f1() {b;}; f1; done
342  * When we execute "f1() {a;}" cmd, we create new function and clear
343  * cmd->group, cmd->group_as_string, cmd->argv[0].
344  * When we execute "f1() {b;}", we notice that f1 exists,
345  * and that its "parent cmd" struct is still "alive",
346  * we put those fields back into cmd->xxx
347  * (struct function has ->parent_cmd ptr to facilitate that).
348  * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
349  * Without this trick, loop would execute a;b;b;b;...
350  * instead of correct sequence a;b;a;b;...
351  * When command is freed, it severs the link
352  * (sets ->child_func->parent_cmd to NULL).
353  */
354 #endif
355         char **argv;                /* command name and arguments */
356 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
357  * and on execution these are substituted with their values.
358  * Substitution can make _several_ words out of one argv[n]!
359  * Example: argv[0]=='.^C*^C.' here: echo .$*.
360  * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
361  */
362         struct redir_struct *redirects; /* I/O redirections */
363 };
364 /* Is there anything in this command at all? */
365 #define IS_NULL_CMD(cmd) \
366         (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
367
368
369 struct pipe {
370         struct pipe *next;
371         int num_cmds;               /* total number of commands in pipe */
372         int alive_cmds;             /* number of commands running (not exited) */
373         int stopped_cmds;           /* number of commands alive, but stopped */
374 #if ENABLE_HUSH_JOB
375         int jobid;                  /* job number */
376         pid_t pgrp;                 /* process group ID for the job */
377         char *cmdtext;              /* name of job */
378 #endif
379         struct command *cmds;       /* array of commands in pipe */
380         smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
381         IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
382         IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
383 };
384 typedef enum pipe_style {
385         PIPE_SEQ = 1,
386         PIPE_AND = 2,
387         PIPE_OR  = 3,
388         PIPE_BG  = 4,
389 } pipe_style;
390 /* Is there anything in this pipe at all? */
391 #define IS_NULL_PIPE(pi) \
392         ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
393
394 /* This holds pointers to the various results of parsing */
395 struct parse_context {
396         /* linked list of pipes */
397         struct pipe *list_head;
398         /* last pipe (being constructed right now) */
399         struct pipe *pipe;
400         /* last command in pipe (being constructed right now) */
401         struct command *command;
402         /* last redirect in command->redirects list */
403         struct redir_struct *pending_redirect;
404 #if !BB_MMU
405         o_string as_string;
406 #endif
407 #if HAS_KEYWORDS
408         smallint ctx_res_w;
409         smallint ctx_inverted; /* "! cmd | cmd" */
410 #if ENABLE_HUSH_CASE
411         smallint ctx_dsemicolon; /* ";;" seen */
412 #endif
413         /* bitmask of FLAG_xxx, for figuring out valid reserved words */
414         int old_flag;
415         /* group we are enclosed in:
416          * example: "if pipe1; pipe2; then pipe3; fi"
417          * when we see "if" or "then", we malloc and copy current context,
418          * and make ->stack point to it. then we parse pipeN.
419          * when closing "then" / fi" / whatever is found,
420          * we move list_head into ->stack->command->group,
421          * copy ->stack into current context, and delete ->stack.
422          * (parsing of { list } and ( list ) doesn't use this method)
423          */
424         struct parse_context *stack;
425 #endif
426 };
427
428 /* On program start, environ points to initial environment.
429  * putenv adds new pointers into it, unsetenv removes them.
430  * Neither of these (de)allocates the strings.
431  * setenv allocates new strings in malloc space and does putenv,
432  * and thus setenv is unusable (leaky) for shell's purposes */
433 #define setenv(...) setenv_is_leaky_dont_use()
434 struct variable {
435         struct variable *next;
436         char *varstr;        /* points to "name=" portion */
437 #if ENABLE_HUSH_LOCAL
438         unsigned func_nest_level;
439 #endif
440         int max_len;         /* if > 0, name is part of initial env; else name is malloced */
441         smallint flg_export; /* putenv should be done on this var */
442         smallint flg_read_only;
443 };
444
445 enum {
446         BC_BREAK = 1,
447         BC_CONTINUE = 2,
448 };
449
450 #if ENABLE_HUSH_FUNCTIONS
451 struct function {
452         struct function *next;
453         char *name;
454         struct command *parent_cmd;
455         struct pipe *body;
456 #if !BB_MMU
457         char *body_as_string;
458 #endif
459 };
460 #endif
461
462
463 /* "Globals" within this file */
464 /* Sorted roughly by size (smaller offsets == smaller code) */
465 struct globals {
466         /* interactive_fd != 0 means we are an interactive shell.
467          * If we are, then saved_tty_pgrp can also be != 0, meaning
468          * that controlling tty is available. With saved_tty_pgrp == 0,
469          * job control still works, but terminal signals
470          * (^C, ^Z, ^Y, ^\) won't work at all, and background
471          * process groups can only be created with "cmd &".
472          * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
473          * to give tty to the foreground process group,
474          * and will take it back when the group is stopped (^Z)
475          * or killed (^C).
476          */
477 #if ENABLE_HUSH_INTERACTIVE
478         /* 'interactive_fd' is a fd# open to ctty, if we have one
479          * _AND_ if we decided to act interactively */
480         int interactive_fd;
481         const char *PS1;
482         const char *PS2;
483 # define G_interactive_fd (G.interactive_fd)
484 #else
485 # define G_interactive_fd 0
486 #endif
487 #if ENABLE_FEATURE_EDITING
488         line_input_t *line_input_state;
489 #endif
490         pid_t root_pid;
491         pid_t last_bg_pid;
492 #if ENABLE_HUSH_JOB
493         int run_list_level;
494         int last_jobid;
495         pid_t saved_tty_pgrp;
496         struct pipe *job_list;
497 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
498 #else
499 # define G_saved_tty_pgrp 0
500 #endif
501         smallint flag_SIGINT;
502 #if ENABLE_HUSH_LOOPS
503         smallint flag_break_continue;
504 #endif
505 #if ENABLE_HUSH_FUNCTIONS
506         /* 0: outside of a function (or sourced file)
507          * -1: inside of a function, ok to use return builtin
508          * 1: return is invoked, skip all till end of func
509          */
510         smallint flag_return_in_progress;
511 #endif
512         smallint fake_mode;
513         smallint exiting; /* used to prevent EXIT trap recursion */
514         /* These four support $?, $#, and $1 */
515         smalluint last_exitcode;
516         /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
517         smalluint global_args_malloced;
518         /* how many non-NULL argv's we have. NB: $# + 1 */
519         int global_argc;
520         char **global_argv;
521 #if !BB_MMU
522         char *argv0_for_re_execing;
523 #endif
524 #if ENABLE_HUSH_LOOPS
525         unsigned depth_break_continue;
526         unsigned depth_of_loop;
527 #endif
528         const char *ifs;
529         const char *cwd;
530         struct variable *top_var; /* = &G.shell_ver (set in main()) */
531         struct variable shell_ver;
532 #if ENABLE_HUSH_FUNCTIONS
533         struct function *top_func;
534 # if ENABLE_HUSH_LOCAL
535         struct variable **shadowed_vars_pp;
536         unsigned func_nest_level;
537 # endif
538 #endif
539         /* Signal and trap handling */
540 #if ENABLE_HUSH_FAST
541         unsigned count_SIGCHLD;
542         unsigned handled_SIGCHLD;
543         smallint we_have_children;
544 #endif
545         /* which signals have non-DFL handler (even with no traps set)? */
546         unsigned non_DFL_mask;
547         char **traps; /* char *traps[NSIG] */
548         sigset_t blocked_set;
549         sigset_t inherited_set;
550 #if HUSH_DEBUG
551         unsigned long memleak_value;
552         int debug_indent;
553 #endif
554         char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
555 };
556 #define G (*ptr_to_globals)
557 /* Not #defining name to G.name - this quickly gets unwieldy
558  * (too many defines). Also, I actually prefer to see when a variable
559  * is global, thus "G." prefix is a useful hint */
560 #define INIT_G() do { \
561         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
562 } while (0)
563
564
565 /* Function prototypes for builtins */
566 static int builtin_cd(char **argv) FAST_FUNC;
567 static int builtin_echo(char **argv) FAST_FUNC;
568 static int builtin_eval(char **argv) FAST_FUNC;
569 static int builtin_exec(char **argv) FAST_FUNC;
570 static int builtin_exit(char **argv) FAST_FUNC;
571 static int builtin_export(char **argv) FAST_FUNC;
572 #if ENABLE_HUSH_JOB
573 static int builtin_fg_bg(char **argv) FAST_FUNC;
574 static int builtin_jobs(char **argv) FAST_FUNC;
575 #endif
576 #if ENABLE_HUSH_HELP
577 static int builtin_help(char **argv) FAST_FUNC;
578 #endif
579 #if ENABLE_HUSH_LOCAL
580 static int builtin_local(char **argv) FAST_FUNC;
581 #endif
582 #if HUSH_DEBUG
583 static int builtin_memleak(char **argv) FAST_FUNC;
584 #endif
585 static int builtin_pwd(char **argv) FAST_FUNC;
586 static int builtin_read(char **argv) FAST_FUNC;
587 static int builtin_set(char **argv) FAST_FUNC;
588 static int builtin_shift(char **argv) FAST_FUNC;
589 static int builtin_source(char **argv) FAST_FUNC;
590 static int builtin_test(char **argv) FAST_FUNC;
591 static int builtin_trap(char **argv) FAST_FUNC;
592 static int builtin_type(char **argv) FAST_FUNC;
593 static int builtin_true(char **argv) FAST_FUNC;
594 static int builtin_umask(char **argv) FAST_FUNC;
595 static int builtin_unset(char **argv) FAST_FUNC;
596 static int builtin_wait(char **argv) FAST_FUNC;
597 #if ENABLE_HUSH_LOOPS
598 static int builtin_break(char **argv) FAST_FUNC;
599 static int builtin_continue(char **argv) FAST_FUNC;
600 #endif
601 #if ENABLE_HUSH_FUNCTIONS
602 static int builtin_return(char **argv) FAST_FUNC;
603 #endif
604
605 /* Table of built-in functions.  They can be forked or not, depending on
606  * context: within pipes, they fork.  As simple commands, they do not.
607  * When used in non-forking context, they can change global variables
608  * in the parent shell process.  If forked, of course they cannot.
609  * For example, 'unset foo | whatever' will parse and run, but foo will
610  * still be set at the end. */
611 struct built_in_command {
612         const char *cmd;
613         int (*function)(char **argv) FAST_FUNC;
614 #if ENABLE_HUSH_HELP
615         const char *descr;
616 # define BLTIN(cmd, func, help) { cmd, func, help }
617 #else
618 # define BLTIN(cmd, func, help) { cmd, func }
619 #endif
620 };
621
622 static const struct built_in_command bltins1[] = {
623         BLTIN("."        , builtin_source  , "Run commands in a file"),
624         BLTIN(":"        , builtin_true    , NULL),
625 #if ENABLE_HUSH_JOB
626         BLTIN("bg"       , builtin_fg_bg   , "Resume a job in the background"),
627 #endif
628 #if ENABLE_HUSH_LOOPS
629         BLTIN("break"    , builtin_break   , "Exit from a loop"),
630 #endif
631         BLTIN("cd"       , builtin_cd      , "Change directory"),
632 #if ENABLE_HUSH_LOOPS
633         BLTIN("continue" , builtin_continue, "Start new loop iteration"),
634 #endif
635         BLTIN("eval"     , builtin_eval    , "Construct and run shell command"),
636         BLTIN("exec"     , builtin_exec    , "Execute command, don't return to shell"),
637         BLTIN("exit"     , builtin_exit    , "Exit"),
638         BLTIN("export"   , builtin_export  , "Set environment variables"),
639 #if ENABLE_HUSH_JOB
640         BLTIN("fg"       , builtin_fg_bg   , "Bring job into the foreground"),
641 #endif
642 #if ENABLE_HUSH_HELP
643         BLTIN("help"     , builtin_help    , NULL),
644 #endif
645 #if ENABLE_HUSH_JOB
646         BLTIN("jobs"     , builtin_jobs    , "List jobs"),
647 #endif
648 #if ENABLE_HUSH_LOCAL
649         BLTIN("local"    , builtin_local   , "Set local variables"),
650 #endif
651 #if HUSH_DEBUG
652         BLTIN("memleak"  , builtin_memleak , NULL),
653 #endif
654         BLTIN("read"     , builtin_read    , "Input into variable"),
655 #if ENABLE_HUSH_FUNCTIONS
656         BLTIN("return"   , builtin_return  , "Return from a function"),
657 #endif
658         BLTIN("set"      , builtin_set     , "Set/unset positional parameters"),
659         BLTIN("shift"    , builtin_shift   , "Shift positional parameters"),
660         BLTIN("trap"     , builtin_trap    , "Trap signals"),
661         BLTIN("type"     , builtin_type    , "Write a description of command type"),
662 //      BLTIN("ulimit"   , builtin_ulimit  , "Control resource limits"),
663         BLTIN("umask"    , builtin_umask   , "Set file creation mask"),
664         BLTIN("unset"    , builtin_unset   , "Unset variables"),
665         BLTIN("wait"     , builtin_wait    , "Wait for process"),
666 };
667 /* For now, echo and test are unconditionally enabled.
668  * Maybe make it configurable? */
669 static const struct built_in_command bltins2[] = {
670         BLTIN("["        , builtin_test    , NULL),
671         BLTIN("echo"     , builtin_echo    , NULL),
672         BLTIN("pwd"      , builtin_pwd     , NULL),
673         BLTIN("test"     , builtin_test    , NULL),
674 };
675
676
677 /* Debug printouts.
678  */
679 #if HUSH_DEBUG
680 /* prevent disasters with G.debug_indent < 0 */
681 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
682 # define debug_enter() (G.debug_indent++)
683 # define debug_leave() (G.debug_indent--)
684 #else
685 # define indent()      ((void)0)
686 # define debug_enter() ((void)0)
687 # define debug_leave() ((void)0)
688 #endif
689
690 #ifndef debug_printf
691 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
692 #endif
693
694 #ifndef debug_printf_parse
695 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
696 #endif
697
698 #ifndef debug_printf_exec
699 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
700 #endif
701
702 #ifndef debug_printf_env
703 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
704 #endif
705
706 #ifndef debug_printf_jobs
707 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
708 # define DEBUG_JOBS 1
709 #else
710 # define DEBUG_JOBS 0
711 #endif
712
713 #ifndef debug_printf_expand
714 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
715 # define DEBUG_EXPAND 1
716 #else
717 # define DEBUG_EXPAND 0
718 #endif
719
720 #ifndef debug_printf_glob
721 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
722 # define DEBUG_GLOB 1
723 #else
724 # define DEBUG_GLOB 0
725 #endif
726
727 #ifndef debug_printf_list
728 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
729 #endif
730
731 #ifndef debug_printf_subst
732 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
733 #endif
734
735 #ifndef debug_printf_clean
736 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
737 # define DEBUG_CLEAN 1
738 #else
739 # define DEBUG_CLEAN 0
740 #endif
741
742 #if DEBUG_EXPAND
743 static void debug_print_strings(const char *prefix, char **vv)
744 {
745         indent();
746         fprintf(stderr, "%s:\n", prefix);
747         while (*vv)
748                 fprintf(stderr, " '%s'\n", *vv++);
749 }
750 #else
751 # define debug_print_strings(prefix, vv) ((void)0)
752 #endif
753
754
755 /* Leak hunting. Use hush_leaktool.sh for post-processing.
756  */
757 #if LEAK_HUNTING
758 static void *xxmalloc(int lineno, size_t size)
759 {
760         void *ptr = xmalloc((size + 0xff) & ~0xff);
761         fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
762         return ptr;
763 }
764 static void *xxrealloc(int lineno, void *ptr, size_t size)
765 {
766         ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
767         fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
768         return ptr;
769 }
770 static char *xxstrdup(int lineno, const char *str)
771 {
772         char *ptr = xstrdup(str);
773         fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
774         return ptr;
775 }
776 static void xxfree(void *ptr)
777 {
778         fdprintf(2, "free %p\n", ptr);
779         free(ptr);
780 }
781 #define xmalloc(s)     xxmalloc(__LINE__, s)
782 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
783 #define xstrdup(s)     xxstrdup(__LINE__, s)
784 #define free(p)        xxfree(p)
785 #endif
786
787
788 /* Syntax and runtime errors. They always abort scripts.
789  * In interactive use they usually discard unparsed and/or unexecuted commands
790  * and return to the prompt.
791  * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
792  */
793 #if HUSH_DEBUG < 2
794 # define die_if_script(lineno, fmt...)          die_if_script(fmt)
795 # define syntax_error(lineno, msg)              syntax_error(msg)
796 # define syntax_error_at(lineno, msg)           syntax_error_at(msg)
797 # define syntax_error_unterm_ch(lineno, ch)     syntax_error_unterm_ch(ch)
798 # define syntax_error_unterm_str(lineno, s)     syntax_error_unterm_str(s)
799 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
800 #endif
801
802 static void die_if_script(unsigned lineno, const char *fmt, ...)
803 {
804         va_list p;
805
806 #if HUSH_DEBUG >= 2
807         bb_error_msg("hush.c:%u", lineno);
808 #endif
809         va_start(p, fmt);
810         bb_verror_msg(fmt, p, NULL);
811         va_end(p);
812         if (!G_interactive_fd)
813                 xfunc_die();
814 }
815
816 static void syntax_error(unsigned lineno, const char *msg)
817 {
818         if (msg)
819                 die_if_script(lineno, "syntax error: %s", msg);
820         else
821                 die_if_script(lineno, "syntax error", NULL);
822 }
823
824 static void syntax_error_at(unsigned lineno, const char *msg)
825 {
826         die_if_script(lineno, "syntax error at '%s'", msg);
827 }
828
829 static void syntax_error_unterm_str(unsigned lineno, const char *s)
830 {
831         die_if_script(lineno, "syntax error: unterminated %s", s);
832 }
833
834 /* It so happens that all such cases are totally fatal
835  * even if shell is interactive: EOF while looking for closing
836  * delimiter. There is nowhere to read stuff from after that,
837  * it's EOF! The only choice is to terminate.
838  */
839 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
840 static void syntax_error_unterm_ch(unsigned lineno, char ch)
841 {
842         char msg[2] = { ch, '\0' };
843         syntax_error_unterm_str(lineno, msg);
844         xfunc_die();
845 }
846
847 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
848 {
849         char msg[2];
850         msg[0] = ch;
851         msg[1] = '\0';
852         die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
853 }
854
855 #if HUSH_DEBUG < 2
856 # undef die_if_script
857 # undef syntax_error
858 # undef syntax_error_at
859 # undef syntax_error_unterm_ch
860 # undef syntax_error_unterm_str
861 # undef syntax_error_unexpected_ch
862 #else
863 # define die_if_script(fmt...)          die_if_script(__LINE__, fmt)
864 # define syntax_error(msg)              syntax_error(__LINE__, msg)
865 # define syntax_error_at(msg)           syntax_error_at(__LINE__, msg)
866 # define syntax_error_unterm_ch(ch)     syntax_error_unterm_ch(__LINE__, ch)
867 # define syntax_error_unterm_str(s)     syntax_error_unterm_str(__LINE__, s)
868 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
869 #endif
870
871
872 #if ENABLE_HUSH_INTERACTIVE
873 static void cmdedit_update_prompt(void);
874 #else
875 # define cmdedit_update_prompt() ((void)0)
876 #endif
877
878
879 /* Utility functions
880  */
881 static int glob_needed(const char *s)
882 {
883         while (*s) {
884                 if (*s == '\\')
885                         s++;
886                 if (*s == '*' || *s == '[' || *s == '?')
887                         return 1;
888                 s++;
889         }
890         return 0;
891 }
892
893 static int is_well_formed_var_name(const char *s, char terminator)
894 {
895         if (!s || !(isalpha(*s) || *s == '_'))
896                 return 0;
897         s++;
898         while (isalnum(*s) || *s == '_')
899                 s++;
900         return *s == terminator;
901 }
902
903 /* Replace each \x with x in place, return ptr past NUL. */
904 static char *unbackslash(char *src)
905 {
906         char *dst = src;
907         while (1) {
908                 if (*src == '\\')
909                         src++;
910                 if ((*dst++ = *src++) == '\0')
911                         break;
912         }
913         return dst;
914 }
915
916 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
917 {
918         int i;
919         unsigned count1;
920         unsigned count2;
921         char **v;
922
923         v = strings;
924         count1 = 0;
925         if (v) {
926                 while (*v) {
927                         count1++;
928                         v++;
929                 }
930         }
931         count2 = 0;
932         v = add;
933         while (*v) {
934                 count2++;
935                 v++;
936         }
937         v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
938         v[count1 + count2] = NULL;
939         i = count2;
940         while (--i >= 0)
941                 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
942         return v;
943 }
944 #if LEAK_HUNTING
945 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
946 {
947         char **ptr = add_strings_to_strings(strings, add, need_to_dup);
948         fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
949         return ptr;
950 }
951 #define add_strings_to_strings(strings, add, need_to_dup) \
952         xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
953 #endif
954
955 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
956 static char **add_string_to_strings(char **strings, char *add)
957 {
958         char *v[2];
959         v[0] = add;
960         v[1] = NULL;
961         return add_strings_to_strings(strings, v, /*dup:*/ 0);
962 }
963 #if LEAK_HUNTING
964 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
965 {
966         char **ptr = add_string_to_strings(strings, add);
967         fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
968         return ptr;
969 }
970 #define add_string_to_strings(strings, add) \
971         xx_add_string_to_strings(__LINE__, strings, add)
972 #endif
973
974 static void free_strings(char **strings)
975 {
976         char **v;
977
978         if (!strings)
979                 return;
980         v = strings;
981         while (*v) {
982                 free(*v);
983                 v++;
984         }
985         free(strings);
986 }
987
988
989 /* Helpers for setting new $n and restoring them back
990  */
991 typedef struct save_arg_t {
992         char *sv_argv0;
993         char **sv_g_argv;
994         int sv_g_argc;
995         smallint sv_g_malloced;
996 } save_arg_t;
997
998 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
999 {
1000         int n;
1001
1002         sv->sv_argv0 = argv[0];
1003         sv->sv_g_argv = G.global_argv;
1004         sv->sv_g_argc = G.global_argc;
1005         sv->sv_g_malloced = G.global_args_malloced;
1006
1007         argv[0] = G.global_argv[0]; /* retain $0 */
1008         G.global_argv = argv;
1009         G.global_args_malloced = 0;
1010
1011         n = 1;
1012         while (*++argv)
1013                 n++;
1014         G.global_argc = n;
1015 }
1016
1017 static void restore_G_args(save_arg_t *sv, char **argv)
1018 {
1019         char **pp;
1020
1021         if (G.global_args_malloced) {
1022                 /* someone ran "set -- arg1 arg2 ...", undo */
1023                 pp = G.global_argv;
1024                 while (*++pp) /* note: does not free $0 */
1025                         free(*pp);
1026                 free(G.global_argv);
1027         }
1028         argv[0] = sv->sv_argv0;
1029         G.global_argv = sv->sv_g_argv;
1030         G.global_argc = sv->sv_g_argc;
1031         G.global_args_malloced = sv->sv_g_malloced;
1032 }
1033
1034
1035 /* Basic theory of signal handling in shell
1036  * ========================================
1037  * This does not describe what hush does, rather, it is current understanding
1038  * what it _should_ do. If it doesn't, it's a bug.
1039  * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1040  *
1041  * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1042  * is finished or backgrounded. It is the same in interactive and
1043  * non-interactive shells, and is the same regardless of whether
1044  * a user trap handler is installed or a shell special one is in effect.
1045  * ^C or ^Z from keyboard seem to execute "at once" because it usually
1046  * backgrounds (i.e. stops) or kills all members of currently running
1047  * pipe.
1048  *
1049  * Wait builtin in interruptible by signals for which user trap is set
1050  * or by SIGINT in interactive shell.
1051  *
1052  * Trap handlers will execute even within trap handlers. (right?)
1053  *
1054  * User trap handlers are forgotten when subshell ("(cmd)") is entered.
1055  *
1056  * If job control is off, backgrounded commands ("cmd &")
1057  * have SIGINT, SIGQUIT set to SIG_IGN.
1058  *
1059  * Commands which are run in command substitution ("`cmd`")
1060  * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1061  *
1062  * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1063  * by the shell from its parent.
1064  *
1065  * Signals which differ from SIG_DFL action
1066  * (note: child (i.e., [v]forked) shell is not an interactive shell):
1067  *
1068  * SIGQUIT: ignore
1069  * SIGTERM (interactive): ignore
1070  * SIGHUP (interactive):
1071  *    send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1072  * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1073  *    Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1074  *    that all pipe members are stopped. Try this in bash:
1075  *    while :; do :; done - ^Z does not background it
1076  *    (while :; do :; done) - ^Z backgrounds it
1077  * SIGINT (interactive): wait for last pipe, ignore the rest
1078  *    of the command line, show prompt. NB: ^C does not send SIGINT
1079  *    to interactive shell while shell is waiting for a pipe,
1080  *    since shell is bg'ed (is not in foreground process group).
1081  *    Example 1: this waits 5 sec, but does not execute ls:
1082  *    "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1083  *    Example 2: this does not wait and does not execute ls:
1084  *    "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1085  *    Example 3: this does not wait 5 sec, but executes ls:
1086  *    "sleep 5; ls -l" + press ^C
1087  *
1088  * (What happens to signals which are IGN on shell start?)
1089  * (What happens with signal mask on shell start?)
1090  *
1091  * Implementation in hush
1092  * ======================
1093  * We use in-kernel pending signal mask to determine which signals were sent.
1094  * We block all signals which we don't want to take action immediately,
1095  * i.e. we block all signals which need to have special handling as described
1096  * above, and all signals which have traps set.
1097  * After each pipe execution, we extract any pending signals via sigtimedwait()
1098  * and act on them.
1099  *
1100  * unsigned non_DFL_mask: a mask of such "special" signals
1101  * sigset_t blocked_set:  current blocked signal set
1102  *
1103  * "trap - SIGxxx":
1104  *    clear bit in blocked_set unless it is also in non_DFL_mask
1105  * "trap 'cmd' SIGxxx":
1106  *    set bit in blocked_set (even if 'cmd' is '')
1107  * after [v]fork, if we plan to be a shell:
1108  *    unblock signals with special interactive handling
1109  *    (child shell is not interactive),
1110  *    unset all traps (note: regardless of child shell's type - {}, (), etc)
1111  * after [v]fork, if we plan to exec:
1112  *    POSIX says pending signal mask is cleared in child - no need to clear it.
1113  *    Restore blocked signal set to one inherited by shell just prior to exec.
1114  *
1115  * Note: as a result, we do not use signal handlers much. The only uses
1116  * are to count SIGCHLDs
1117  * and to restore tty pgrp on signal-induced exit.
1118  */
1119 enum {
1120         SPECIAL_INTERACTIVE_SIGS = 0
1121                 | (1 << SIGTERM)
1122                 | (1 << SIGINT)
1123                 | (1 << SIGHUP)
1124                 ,
1125         SPECIAL_JOB_SIGS = 0
1126 #if ENABLE_HUSH_JOB
1127                 | (1 << SIGTTIN)
1128                 | (1 << SIGTTOU)
1129                 | (1 << SIGTSTP)
1130 #endif
1131 };
1132
1133 #if ENABLE_HUSH_FAST
1134 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1135 {
1136         G.count_SIGCHLD++;
1137 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1138 }
1139 #endif
1140
1141 #if ENABLE_HUSH_JOB
1142
1143 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1144 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1145 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1146 #define enable_restore_tty_pgrp_on_exit()  (die_sleep = -1)
1147
1148 /* Restores tty foreground process group, and exits.
1149  * May be called as signal handler for fatal signal
1150  * (will resend signal to itself, producing correct exit state)
1151  * or called directly with -EXITCODE.
1152  * We also call it if xfunc is exiting. */
1153 static void sigexit(int sig) NORETURN;
1154 static void sigexit(int sig)
1155 {
1156         /* Disable all signals: job control, SIGPIPE, etc. */
1157         sigprocmask_allsigs(SIG_BLOCK);
1158
1159         /* Careful: we can end up here after [v]fork. Do not restore
1160          * tty pgrp then, only top-level shell process does that */
1161         if (G_saved_tty_pgrp && getpid() == G.root_pid)
1162                 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1163
1164         /* Not a signal, just exit */
1165         if (sig <= 0)
1166                 _exit(- sig);
1167
1168         kill_myself_with_sig(sig); /* does not return */
1169 }
1170 #else
1171
1172 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1173 #define enable_restore_tty_pgrp_on_exit()  ((void)0)
1174
1175 #endif
1176
1177 /* Restores tty foreground process group, and exits. */
1178 static void hush_exit(int exitcode) NORETURN;
1179 static void hush_exit(int exitcode)
1180 {
1181         if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1182                 /* Prevent recursion:
1183                  * trap "echo Hi; exit" EXIT; exit
1184                  */
1185                 char *argv[] = { NULL, G.traps[0], NULL };
1186                 G.traps[0] = NULL;
1187                 G.exiting = 1;
1188                 builtin_eval(argv);
1189                 free(argv[1]);
1190         }
1191
1192 #if ENABLE_HUSH_JOB
1193         fflush(NULL); /* flush all streams */
1194         sigexit(- (exitcode & 0xff));
1195 #else
1196         exit(exitcode);
1197 #endif
1198 }
1199
1200 static int check_and_run_traps(int sig)
1201 {
1202         static const struct timespec zero_timespec = { 0, 0 };
1203         smalluint save_rcode;
1204         int last_sig = 0;
1205
1206         if (sig)
1207                 goto jump_in;
1208         while (1) {
1209                 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1210                 if (sig <= 0)
1211                         break;
1212  jump_in:
1213                 last_sig = sig;
1214                 if (G.traps && G.traps[sig]) {
1215                         if (G.traps[sig][0]) {
1216                                 /* We have user-defined handler */
1217                                 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1218                                 save_rcode = G.last_exitcode;
1219                                 builtin_eval(argv);
1220                                 free(argv[1]);
1221                                 G.last_exitcode = save_rcode;
1222                         } /* else: "" trap, ignoring signal */
1223                         continue;
1224                 }
1225                 /* not a trap: special action */
1226                 switch (sig) {
1227 #if ENABLE_HUSH_FAST
1228                 case SIGCHLD:
1229                         G.count_SIGCHLD++;
1230 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1231                         break;
1232 #endif
1233                 case SIGINT:
1234                         /* Builtin was ^C'ed, make it look prettier: */
1235                         bb_putchar('\n');
1236                         G.flag_SIGINT = 1;
1237                         break;
1238 #if ENABLE_HUSH_JOB
1239                 case SIGHUP: {
1240                         struct pipe *job;
1241                         /* bash is observed to signal whole process groups,
1242                          * not individual processes */
1243                         for (job = G.job_list; job; job = job->next) {
1244                                 if (job->pgrp <= 0)
1245                                         continue;
1246                                 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1247                                 if (kill(- job->pgrp, SIGHUP) == 0)
1248                                         kill(- job->pgrp, SIGCONT);
1249                         }
1250                         sigexit(SIGHUP);
1251                 }
1252 #endif
1253                 default: /* ignored: */
1254                         /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1255                         break;
1256                 }
1257         }
1258         return last_sig;
1259 }
1260
1261
1262 static const char *get_cwd(int force)
1263 {
1264         if (force || G.cwd == NULL) {
1265                 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1266                  * we must not try to free(bb_msg_unknown) */
1267                 if (G.cwd == bb_msg_unknown)
1268                         G.cwd = NULL;
1269                 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1270                 if (!G.cwd)
1271                         G.cwd = bb_msg_unknown;
1272         }
1273         return G.cwd;
1274 }
1275
1276
1277 /*
1278  * Shell and environment variable support
1279  */
1280 static struct variable **get_ptr_to_local_var(const char *name)
1281 {
1282         struct variable **pp;
1283         struct variable *cur;
1284         int len;
1285
1286         len = strlen(name);
1287         pp = &G.top_var;
1288         while ((cur = *pp) != NULL) {
1289                 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1290                         return pp;
1291                 pp = &cur->next;
1292         }
1293         return NULL;
1294 }
1295
1296 static struct variable *get_local_var(const char *name)
1297 {
1298         struct variable **pp = get_ptr_to_local_var(name);
1299         if (pp)
1300                 return *pp;
1301         return NULL;
1302 }
1303
1304 static const char *get_local_var_value(const char *name)
1305 {
1306         struct variable **pp = get_ptr_to_local_var(name);
1307         if (pp)
1308                 return strchr((*pp)->varstr, '=') + 1;
1309         return NULL;
1310 }
1311
1312 /* str holds "NAME=VAL" and is expected to be malloced.
1313  * We take ownership of it.
1314  * flg_export:
1315  *  0: do not change export flag
1316  *     (if creating new variable, flag will be 0)
1317  *  1: set export flag and putenv the variable
1318  * -1: clear export flag and unsetenv the variable
1319  * flg_read_only is set only when we handle -R var=val
1320  */
1321 #if !BB_MMU && ENABLE_HUSH_LOCAL
1322 /* all params are used */
1323 #elif BB_MMU && ENABLE_HUSH_LOCAL
1324 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1325         set_local_var(str, flg_export, local_lvl)
1326 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1327 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1328         set_local_var(str, flg_export)
1329 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1330 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1331         set_local_var(str, flg_export, flg_read_only)
1332 #endif
1333 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1334 {
1335         struct variable **var_pp;
1336         struct variable *cur;
1337         char *eq_sign;
1338         int name_len;
1339
1340         eq_sign = strchr(str, '=');
1341         if (!eq_sign) { /* not expected to ever happen? */
1342                 free(str);
1343                 return -1;
1344         }
1345
1346         name_len = eq_sign - str + 1; /* including '=' */
1347         var_pp = &G.top_var;
1348         while ((cur = *var_pp) != NULL) {
1349                 if (strncmp(cur->varstr, str, name_len) != 0) {
1350                         var_pp = &cur->next;
1351                         continue;
1352                 }
1353                 /* We found an existing var with this name */
1354                 if (cur->flg_read_only) {
1355 #if !BB_MMU
1356                         if (!flg_read_only)
1357 #endif
1358                                 bb_error_msg("%s: readonly variable", str);
1359                         free(str);
1360                         return -1;
1361                 }
1362                 if (flg_export == -1) { // "&& cur->flg_export" ?
1363                         debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1364                         *eq_sign = '\0';
1365                         unsetenv(str);
1366                         *eq_sign = '=';
1367                 }
1368 #if ENABLE_HUSH_LOCAL
1369                 if (cur->func_nest_level < local_lvl) {
1370                         /* New variable is declared as local,
1371                          * and existing one is global, or local
1372                          * from enclosing function.
1373                          * Remove and save old one: */
1374                         *var_pp = cur->next;
1375                         cur->next = *G.shadowed_vars_pp;
1376                         *G.shadowed_vars_pp = cur;
1377                         /* bash 3.2.33(1) and exported vars:
1378                          * # export z=z
1379                          * # f() { local z=a; env | grep ^z; }
1380                          * # f
1381                          * z=a
1382                          * # env | grep ^z
1383                          * z=z
1384                          */
1385                         if (cur->flg_export)
1386                                 flg_export = 1;
1387                         break;
1388                 }
1389 #endif
1390                 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1391  free_and_exp:
1392                         free(str);
1393                         goto exp;
1394                 }
1395                 if (cur->max_len != 0) {
1396                         if (cur->max_len >= strlen(str)) {
1397                                 /* This one is from startup env, reuse space */
1398                                 strcpy(cur->varstr, str);
1399                                 goto free_and_exp;
1400                         }
1401                 } else {
1402                         /* max_len == 0 signifies "malloced" var, which we can
1403                          * (and has to) free */
1404                         free(cur->varstr);
1405                 }
1406                 cur->max_len = 0;
1407                 goto set_str_and_exp;
1408         }
1409
1410         /* Not found - create new variable struct */
1411         cur = xzalloc(sizeof(*cur));
1412 #if ENABLE_HUSH_LOCAL
1413         cur->func_nest_level = local_lvl;
1414 #endif
1415         cur->next = *var_pp;
1416         *var_pp = cur;
1417
1418  set_str_and_exp:
1419         cur->varstr = str;
1420 #if !BB_MMU
1421         cur->flg_read_only = flg_read_only;
1422 #endif
1423  exp:
1424         if (flg_export == 1)
1425                 cur->flg_export = 1;
1426         if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1427                 cmdedit_update_prompt();
1428         if (cur->flg_export) {
1429                 if (flg_export == -1) {
1430                         cur->flg_export = 0;
1431                         /* unsetenv was already done */
1432                 } else {
1433                         debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1434                         return putenv(cur->varstr);
1435                 }
1436         }
1437         return 0;
1438 }
1439
1440 static int unset_local_var_len(const char *name, int name_len)
1441 {
1442         struct variable *cur;
1443         struct variable **var_pp;
1444
1445         if (!name)
1446                 return EXIT_SUCCESS;
1447         var_pp = &G.top_var;
1448         while ((cur = *var_pp) != NULL) {
1449                 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1450                         if (cur->flg_read_only) {
1451                                 bb_error_msg("%s: readonly variable", name);
1452                                 return EXIT_FAILURE;
1453                         }
1454                         *var_pp = cur->next;
1455                         debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1456                         bb_unsetenv(cur->varstr);
1457                         if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1458                                 cmdedit_update_prompt();
1459                         if (!cur->max_len)
1460                                 free(cur->varstr);
1461                         free(cur);
1462                         return EXIT_SUCCESS;
1463                 }
1464                 var_pp = &cur->next;
1465         }
1466         return EXIT_SUCCESS;
1467 }
1468
1469 static int unset_local_var(const char *name)
1470 {
1471         return unset_local_var_len(name, strlen(name));
1472 }
1473
1474 static void unset_vars(char **strings)
1475 {
1476         char **v;
1477
1478         if (!strings)
1479                 return;
1480         v = strings;
1481         while (*v) {
1482                 const char *eq = strchrnul(*v, '=');
1483                 unset_local_var_len(*v, (int)(eq - *v));
1484                 v++;
1485         }
1486         free(strings);
1487 }
1488
1489 #if ENABLE_SH_MATH_SUPPORT
1490 #define is_name(c)      ((c) == '_' || isalpha((unsigned char)(c)))
1491 #define is_in_name(c)   ((c) == '_' || isalnum((unsigned char)(c)))
1492 static char *endofname(const char *name)
1493 {
1494         char *p;
1495
1496         p = (char *) name;
1497         if (!is_name(*p))
1498                 return p;
1499         while (*++p) {
1500                 if (!is_in_name(*p))
1501                         break;
1502         }
1503         return p;
1504 }
1505
1506 static void arith_set_local_var(const char *name, const char *val, int flags)
1507 {
1508         /* arith code doesnt malloc space, so do it for it */
1509         char *var = xasprintf("%s=%s", name, val);
1510         set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
1511 }
1512 #endif
1513
1514
1515 /*
1516  * Helpers for "var1=val1 var2=val2 cmd" feature
1517  */
1518 static void add_vars(struct variable *var)
1519 {
1520         struct variable *next;
1521
1522         while (var) {
1523                 next = var->next;
1524                 var->next = G.top_var;
1525                 G.top_var = var;
1526                 if (var->flg_export) {
1527                         debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1528                         putenv(var->varstr);
1529                 } else {
1530                         debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1531                 }
1532                 var = next;
1533         }
1534 }
1535
1536 static struct variable *set_vars_and_save_old(char **strings)
1537 {
1538         char **s;
1539         struct variable *old = NULL;
1540
1541         if (!strings)
1542                 return old;
1543         s = strings;
1544         while (*s) {
1545                 struct variable *var_p;
1546                 struct variable **var_pp;
1547                 char *eq;
1548
1549                 eq = strchr(*s, '=');
1550                 if (eq) {
1551                         *eq = '\0';
1552                         var_pp = get_ptr_to_local_var(*s);
1553                         *eq = '=';
1554                         if (var_pp) {
1555                                 /* Remove variable from global linked list */
1556                                 var_p = *var_pp;
1557                                 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1558                                 *var_pp = var_p->next;
1559                                 /* Add it to returned list */
1560                                 var_p->next = old;
1561                                 old = var_p;
1562                         }
1563                         set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1564                 }
1565                 s++;
1566         }
1567         return old;
1568 }
1569
1570
1571 /*
1572  * in_str support
1573  */
1574 static int FAST_FUNC static_get(struct in_str *i)
1575 {
1576         int ch = *i->p++;
1577         if (ch != '\0')
1578                 return ch;
1579         i->p--;
1580         return EOF;
1581 }
1582
1583 static int FAST_FUNC static_peek(struct in_str *i)
1584 {
1585         return *i->p;
1586 }
1587
1588 #if ENABLE_HUSH_INTERACTIVE
1589
1590 static void cmdedit_update_prompt(void)
1591 {
1592         if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1593                 G.PS1 = get_local_var_value("PS1");
1594                 if (G.PS1 == NULL)
1595                         G.PS1 = "\\w \\$ ";
1596                 G.PS2 = get_local_var_value("PS2");
1597         } else {
1598                 G.PS1 = NULL;
1599         }
1600         if (G.PS2 == NULL)
1601                 G.PS2 = "> ";
1602 }
1603
1604 static const char* setup_prompt_string(int promptmode)
1605 {
1606         const char *prompt_str;
1607         debug_printf("setup_prompt_string %d ", promptmode);
1608         if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1609                 /* Set up the prompt */
1610                 if (promptmode == 0) { /* PS1 */
1611                         free((char*)G.PS1);
1612                         G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1613                         prompt_str = G.PS1;
1614                 } else
1615                         prompt_str = G.PS2;
1616         } else
1617                 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1618         debug_printf("result '%s'\n", prompt_str);
1619         return prompt_str;
1620 }
1621
1622 static void get_user_input(struct in_str *i)
1623 {
1624         int r;
1625         const char *prompt_str;
1626
1627         prompt_str = setup_prompt_string(i->promptmode);
1628 #if ENABLE_FEATURE_EDITING
1629         /* Enable command line editing only while a command line
1630          * is actually being read */
1631         do {
1632                 G.flag_SIGINT = 0;
1633                 /* buglet: SIGINT will not make new prompt to appear _at once_,
1634                  * only after <Enter>. (^C will work) */
1635                 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1636                 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1637                 check_and_run_traps(0);
1638         } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1639         i->eof_flag = (r < 0);
1640         if (i->eof_flag) { /* EOF/error detected */
1641                 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1642                 G.user_input_buf[1] = '\0';
1643         }
1644 #else
1645         do {
1646                 G.flag_SIGINT = 0;
1647                 fputs(prompt_str, stdout);
1648                 fflush(stdout);
1649                 G.user_input_buf[0] = r = fgetc(i->file);
1650                 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1651 //do we need check_and_run_traps(0)? (maybe only if stdin)
1652         } while (G.flag_SIGINT);
1653         i->eof_flag = (r == EOF);
1654 #endif
1655         i->p = G.user_input_buf;
1656 }
1657
1658 #endif  /* INTERACTIVE */
1659
1660 /* This is the magic location that prints prompts
1661  * and gets data back from the user */
1662 static int FAST_FUNC file_get(struct in_str *i)
1663 {
1664         int ch;
1665
1666         /* If there is data waiting, eat it up */
1667         if (i->p && *i->p) {
1668 #if ENABLE_HUSH_INTERACTIVE
1669  take_cached:
1670 #endif
1671                 ch = *i->p++;
1672                 if (i->eof_flag && !*i->p)
1673                         ch = EOF;
1674                 /* note: ch is never NUL */
1675         } else {
1676                 /* need to double check i->file because we might be doing something
1677                  * more complicated by now, like sourcing or substituting. */
1678 #if ENABLE_HUSH_INTERACTIVE
1679                 if (G_interactive_fd && i->promptme && i->file == stdin) {
1680                         do {
1681                                 get_user_input(i);
1682                         } while (!*i->p); /* need non-empty line */
1683                         i->promptmode = 1; /* PS2 */
1684                         i->promptme = 0;
1685                         goto take_cached;
1686                 }
1687 #endif
1688                 do ch = fgetc(i->file); while (ch == '\0');
1689         }
1690         debug_printf("file_get: got '%c' %d\n", ch, ch);
1691 #if ENABLE_HUSH_INTERACTIVE
1692         if (ch == '\n')
1693                 i->promptme = 1;
1694 #endif
1695         return ch;
1696 }
1697
1698 /* All callers guarantee this routine will never
1699  * be used right after a newline, so prompting is not needed.
1700  */
1701 static int FAST_FUNC file_peek(struct in_str *i)
1702 {
1703         int ch;
1704         if (i->p && *i->p) {
1705                 if (i->eof_flag && !i->p[1])
1706                         return EOF;
1707                 return *i->p;
1708                 /* note: ch is never NUL */
1709         }
1710         do ch = fgetc(i->file); while (ch == '\0');
1711         i->eof_flag = (ch == EOF);
1712         i->peek_buf[0] = ch;
1713         i->peek_buf[1] = '\0';
1714         i->p = i->peek_buf;
1715         debug_printf("file_peek: got '%c' %d\n", ch, ch);
1716         return ch;
1717 }
1718
1719 static void setup_file_in_str(struct in_str *i, FILE *f)
1720 {
1721         i->peek = file_peek;
1722         i->get = file_get;
1723 #if ENABLE_HUSH_INTERACTIVE
1724         i->promptme = 1;
1725         i->promptmode = 0; /* PS1 */
1726 #endif
1727         i->file = f;
1728         i->p = NULL;
1729 }
1730
1731 static void setup_string_in_str(struct in_str *i, const char *s)
1732 {
1733         i->peek = static_peek;
1734         i->get = static_get;
1735 #if ENABLE_HUSH_INTERACTIVE
1736         i->promptme = 1;
1737         i->promptmode = 0; /* PS1 */
1738 #endif
1739         i->p = s;
1740         i->eof_flag = 0;
1741 }
1742
1743
1744 /*
1745  * o_string support
1746  */
1747 #define B_CHUNK  (32 * sizeof(char*))
1748
1749 static void o_reset_to_empty_unquoted(o_string *o)
1750 {
1751         o->length = 0;
1752         o->o_quoted = 0;
1753         if (o->data)
1754                 o->data[0] = '\0';
1755 }
1756
1757 static void o_free(o_string *o)
1758 {
1759         free(o->data);
1760         memset(o, 0, sizeof(*o));
1761 }
1762
1763 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1764 {
1765         free(o->data);
1766 }
1767
1768 static void o_grow_by(o_string *o, int len)
1769 {
1770         if (o->length + len > o->maxlen) {
1771                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1772                 o->data = xrealloc(o->data, 1 + o->maxlen);
1773         }
1774 }
1775
1776 static void o_addchr(o_string *o, int ch)
1777 {
1778         debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1779         o_grow_by(o, 1);
1780         o->data[o->length] = ch;
1781         o->length++;
1782         o->data[o->length] = '\0';
1783 }
1784
1785 static void o_addblock(o_string *o, const char *str, int len)
1786 {
1787         o_grow_by(o, len);
1788         memcpy(&o->data[o->length], str, len);
1789         o->length += len;
1790         o->data[o->length] = '\0';
1791 }
1792
1793 #if !BB_MMU
1794 static void o_addstr(o_string *o, const char *str)
1795 {
1796         o_addblock(o, str, strlen(str));
1797 }
1798 static void nommu_addchr(o_string *o, int ch)
1799 {
1800         if (o)
1801                 o_addchr(o, ch);
1802 }
1803 #else
1804 # define nommu_addchr(o, str) ((void)0)
1805 #endif
1806
1807 static void o_addstr_with_NUL(o_string *o, const char *str)
1808 {
1809         o_addblock(o, str, strlen(str) + 1);
1810 }
1811
1812 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1813 {
1814         while (len) {
1815                 o_addchr(o, *str);
1816                 if (*str++ == '\\'
1817                  && (*str != '*' && *str != '?' && *str != '[')
1818                 ) {
1819                         o_addchr(o, '\\');
1820                 }
1821                 len--;
1822         }
1823 }
1824
1825 /* My analysis of quoting semantics tells me that state information
1826  * is associated with a destination, not a source.
1827  */
1828 static void o_addqchr(o_string *o, int ch)
1829 {
1830         int sz = 1;
1831         char *found = strchr("*?[\\", ch);
1832         if (found)
1833                 sz++;
1834         o_grow_by(o, sz);
1835         if (found) {
1836                 o->data[o->length] = '\\';
1837                 o->length++;
1838         }
1839         o->data[o->length] = ch;
1840         o->length++;
1841         o->data[o->length] = '\0';
1842 }
1843
1844 static void o_addQchr(o_string *o, int ch)
1845 {
1846         int sz = 1;
1847         if (o->o_escape && strchr("*?[\\", ch)) {
1848                 sz++;
1849                 o->data[o->length] = '\\';
1850                 o->length++;
1851         }
1852         o_grow_by(o, sz);
1853         o->data[o->length] = ch;
1854         o->length++;
1855         o->data[o->length] = '\0';
1856 }
1857
1858 static void o_addQstr(o_string *o, const char *str, int len)
1859 {
1860         if (!o->o_escape) {
1861                 o_addblock(o, str, len);
1862                 return;
1863         }
1864         while (len) {
1865                 char ch;
1866                 int sz;
1867                 int ordinary_cnt = strcspn(str, "*?[\\");
1868                 if (ordinary_cnt > len) /* paranoia */
1869                         ordinary_cnt = len;
1870                 o_addblock(o, str, ordinary_cnt);
1871                 if (ordinary_cnt == len)
1872                         return;
1873                 str += ordinary_cnt;
1874                 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1875
1876                 ch = *str++;
1877                 sz = 1;
1878                 if (ch) { /* it is necessarily one of "*?[\\" */
1879                         sz++;
1880                         o->data[o->length] = '\\';
1881                         o->length++;
1882                 }
1883                 o_grow_by(o, sz);
1884                 o->data[o->length] = ch;
1885                 o->length++;
1886                 o->data[o->length] = '\0';
1887         }
1888 }
1889
1890 /* A special kind of o_string for $VAR and `cmd` expansion.
1891  * It contains char* list[] at the beginning, which is grown in 16 element
1892  * increments. Actual string data starts at the next multiple of 16 * (char*).
1893  * list[i] contains an INDEX (int!) into this string data.
1894  * It means that if list[] needs to grow, data needs to be moved higher up
1895  * but list[i]'s need not be modified.
1896  * NB: remembering how many list[i]'s you have there is crucial.
1897  * o_finalize_list() operation post-processes this structure - calculates
1898  * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1899  */
1900 #if DEBUG_EXPAND || DEBUG_GLOB
1901 static void debug_print_list(const char *prefix, o_string *o, int n)
1902 {
1903         char **list = (char**)o->data;
1904         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1905         int i = 0;
1906
1907         indent();
1908         fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1909                         prefix, list, n, string_start, o->length, o->maxlen);
1910         while (i < n) {
1911                 indent();
1912                 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1913                                 o->data + (int)list[i] + string_start,
1914                                 o->data + (int)list[i] + string_start);
1915                 i++;
1916         }
1917         if (n) {
1918                 const char *p = o->data + (int)list[n - 1] + string_start;
1919                 indent();
1920                 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1921         }
1922 }
1923 #else
1924 # define debug_print_list(prefix, o, n) ((void)0)
1925 #endif
1926
1927 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1928  * in list[n] so that it points past last stored byte so far.
1929  * It returns n+1. */
1930 static int o_save_ptr_helper(o_string *o, int n)
1931 {
1932         char **list = (char**)o->data;
1933         int string_start;
1934         int string_len;
1935
1936         if (!o->has_empty_slot) {
1937                 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1938                 string_len = o->length - string_start;
1939                 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1940                         debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1941                         /* list[n] points to string_start, make space for 16 more pointers */
1942                         o->maxlen += 0x10 * sizeof(list[0]);
1943                         o->data = xrealloc(o->data, o->maxlen + 1);
1944                         list = (char**)o->data;
1945                         memmove(list + n + 0x10, list + n, string_len);
1946                         o->length += 0x10 * sizeof(list[0]);
1947                 } else {
1948                         debug_printf_list("list[%d]=%d string_start=%d\n",
1949                                         n, string_len, string_start);
1950                 }
1951         } else {
1952                 /* We have empty slot at list[n], reuse without growth */
1953                 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1954                 string_len = o->length - string_start;
1955                 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1956                                 n, string_len, string_start);
1957                 o->has_empty_slot = 0;
1958         }
1959         list[n] = (char*)(ptrdiff_t)string_len;
1960         return n + 1;
1961 }
1962
1963 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1964 static int o_get_last_ptr(o_string *o, int n)
1965 {
1966         char **list = (char**)o->data;
1967         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1968
1969         return ((int)(ptrdiff_t)list[n-1]) + string_start;
1970 }
1971
1972 /* o_glob performs globbing on last list[], saving each result
1973  * as a new list[]. */
1974 static int o_glob(o_string *o, int n)
1975 {
1976         glob_t globdata;
1977         int gr;
1978         char *pattern;
1979
1980         debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1981         if (!o->data)
1982                 return o_save_ptr_helper(o, n);
1983         pattern = o->data + o_get_last_ptr(o, n);
1984         debug_printf_glob("glob pattern '%s'\n", pattern);
1985         if (!glob_needed(pattern)) {
1986  literal:
1987                 o->length = unbackslash(pattern) - o->data;
1988                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1989                 return o_save_ptr_helper(o, n);
1990         }
1991
1992         memset(&globdata, 0, sizeof(globdata));
1993         gr = glob(pattern, 0, NULL, &globdata);
1994         debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1995         if (gr == GLOB_NOSPACE)
1996                 bb_error_msg_and_die("out of memory during glob");
1997         if (gr == GLOB_NOMATCH) {
1998                 globfree(&globdata);
1999                 goto literal;
2000         }
2001         if (gr != 0) { /* GLOB_ABORTED ? */
2002                 /* TODO: testcase for bad glob pattern behavior */
2003                 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2004         }
2005         if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2006                 char **argv = globdata.gl_pathv;
2007                 o->length = pattern - o->data; /* "forget" pattern */
2008                 while (1) {
2009                         o_addstr_with_NUL(o, *argv);
2010                         n = o_save_ptr_helper(o, n);
2011                         argv++;
2012                         if (!*argv)
2013                                 break;
2014                 }
2015         }
2016         globfree(&globdata);
2017         if (DEBUG_GLOB)
2018                 debug_print_list("o_glob returning", o, n);
2019         return n;
2020 }
2021
2022 /* If o->o_glob == 1, glob the string so far remembered.
2023  * Otherwise, just finish current list[] and start new */
2024 static int o_save_ptr(o_string *o, int n)
2025 {
2026         if (o->o_glob) { /* if globbing is requested */
2027                 /* If o->has_empty_slot, list[n] was already globbed
2028                  * (if it was requested back then when it was filled)
2029                  * so don't do that again! */
2030                 if (!o->has_empty_slot)
2031                         return o_glob(o, n); /* o_save_ptr_helper is inside */
2032         }
2033         return o_save_ptr_helper(o, n);
2034 }
2035
2036 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2037 static char **o_finalize_list(o_string *o, int n)
2038 {
2039         char **list;
2040         int string_start;
2041
2042         n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2043         if (DEBUG_EXPAND)
2044                 debug_print_list("finalized", o, n);
2045         debug_printf_expand("finalized n:%d\n", n);
2046         list = (char**)o->data;
2047         string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2048         list[--n] = NULL;
2049         while (n) {
2050                 n--;
2051                 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2052         }
2053         return list;
2054 }
2055
2056
2057 /* Expansion can recurse */
2058 #if ENABLE_HUSH_TICK
2059 static int process_command_subs(o_string *dest, const char *s);
2060 #endif
2061 static char *expand_string_to_string(const char *str);
2062 #if BB_MMU
2063 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2064         parse_stream_dquoted(dest, input, dquote_end)
2065 #endif
2066 static int parse_stream_dquoted(o_string *as_string,
2067                 o_string *dest,
2068                 struct in_str *input,
2069                 int dquote_end);
2070
2071 /* expand_strvec_to_strvec() takes a list of strings, expands
2072  * all variable references within and returns a pointer to
2073  * a list of expanded strings, possibly with larger number
2074  * of strings. (Think VAR="a b"; echo $VAR).
2075  * This new list is allocated as a single malloc block.
2076  * NULL-terminated list of char* pointers is at the beginning of it,
2077  * followed by strings themself.
2078  * Caller can deallocate entire list by single free(list). */
2079
2080 /* Store given string, finalizing the word and starting new one whenever
2081  * we encounter IFS char(s). This is used for expanding variable values.
2082  * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2083 static int expand_on_ifs(o_string *output, int n, const char *str)
2084 {
2085         while (1) {
2086                 int word_len = strcspn(str, G.ifs);
2087                 if (word_len) {
2088                         if (output->o_escape || !output->o_glob)
2089                                 o_addQstr(output, str, word_len);
2090                         else /* protect backslashes against globbing up :) */
2091                                 o_addblock_duplicate_backslash(output, str, word_len);
2092                         str += word_len;
2093                 }
2094                 if (!*str)  /* EOL - do not finalize word */
2095                         break;
2096                 o_addchr(output, '\0');
2097                 debug_print_list("expand_on_ifs", output, n);
2098                 n = o_save_ptr(output, n);
2099                 str += strspn(str, G.ifs); /* skip ifs chars */
2100         }
2101         debug_print_list("expand_on_ifs[1]", output, n);
2102         return n;
2103 }
2104
2105 /* Helper to expand $((...)) and heredoc body. These act as if
2106  * they are in double quotes, with the exception that they are not :).
2107  * Just the rules are similar: "expand only $var and `cmd`"
2108  *
2109  * Returns malloced string.
2110  * As an optimization, we return NULL if expansion is not needed.
2111  */
2112 static char *expand_pseudo_dquoted(const char *str)
2113 {
2114         char *exp_str;
2115         struct in_str input;
2116         o_string dest = NULL_O_STRING;
2117
2118         if (strchr(str, '$') == NULL
2119 #if ENABLE_HUSH_TICK
2120          && strchr(str, '`') == NULL
2121 #endif
2122         ) {
2123                 return NULL;
2124         }
2125
2126         /* We need to expand. Example:
2127          * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2128          */
2129         setup_string_in_str(&input, str);
2130         parse_stream_dquoted(NULL, &dest, &input, EOF);
2131         //bb_error_msg("'%s' -> '%s'", str, dest.data);
2132         exp_str = expand_string_to_string(dest.data);
2133         //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2134         o_free_unsafe(&dest);
2135         return exp_str;
2136 }
2137
2138 /* Expand all variable references in given string, adding words to list[]
2139  * at n, n+1,... positions. Return updated n (so that list[n] is next one
2140  * to be filled). This routine is extremely tricky: has to deal with
2141  * variables/parameters with whitespace, $* and $@, and constructs like
2142  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2143 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2144 {
2145         /* or_mask is either 0 (normal case) or 0x80 -
2146          * expansion of right-hand side of assignment == 1-element expand.
2147          * It will also do no globbing, and thus we must not backslash-quote!
2148          */
2149         char ored_ch;
2150         char *p;
2151
2152         ored_ch = 0;
2153
2154         debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2155         debug_print_list("expand_vars_to_list", output, n);
2156         n = o_save_ptr(output, n);
2157         debug_print_list("expand_vars_to_list[0]", output, n);
2158
2159         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2160                 char first_ch;
2161                 int i;
2162                 char *dyn_val = NULL;
2163                 const char *val = NULL;
2164 #if ENABLE_HUSH_TICK
2165                 o_string subst_result = NULL_O_STRING;
2166 #endif
2167 #if ENABLE_SH_MATH_SUPPORT
2168                 char arith_buf[sizeof(arith_t)*3 + 2];
2169 #endif
2170                 o_addblock(output, arg, p - arg);
2171                 debug_print_list("expand_vars_to_list[1]", output, n);
2172                 arg = ++p;
2173                 p = strchr(p, SPECIAL_VAR_SYMBOL);
2174
2175                 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2176                 /* "$@" is special. Even if quoted, it can still
2177                  * expand to nothing (not even an empty string) */
2178                 if ((first_ch & 0x7f) != '@')
2179                         ored_ch |= first_ch;
2180
2181                 switch (first_ch & 0x7f) {
2182                 /* Highest bit in first_ch indicates that var is double-quoted */
2183                 case '$': /* pid */
2184                         val = utoa(G.root_pid);
2185                         break;
2186                 case '!': /* bg pid */
2187                         val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2188                         break;
2189                 case '?': /* exitcode */
2190                         val = utoa(G.last_exitcode);
2191                         break;
2192                 case '#': /* argc */
2193                         if (arg[1] != SPECIAL_VAR_SYMBOL)
2194                                 /* actually, it's a ${#var} */
2195                                 goto case_default;
2196                         val = utoa(G.global_argc ? G.global_argc-1 : 0);
2197                         break;
2198                 case '*':
2199                 case '@':
2200                         i = 1;
2201                         if (!G.global_argv[i])
2202                                 break;
2203                         ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2204                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2205                                 smallint sv = output->o_escape;
2206                                 /* unquoted var's contents should be globbed, so don't escape */
2207                                 output->o_escape = 0;
2208                                 while (G.global_argv[i]) {
2209                                         n = expand_on_ifs(output, n, G.global_argv[i]);
2210                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2211                                         if (G.global_argv[i++][0] && G.global_argv[i]) {
2212                                                 /* this argv[] is not empty and not last:
2213                                                  * put terminating NUL, start new word */
2214                                                 o_addchr(output, '\0');
2215                                                 debug_print_list("expand_vars_to_list[2]", output, n);
2216                                                 n = o_save_ptr(output, n);
2217                                                 debug_print_list("expand_vars_to_list[3]", output, n);
2218                                         }
2219                                 }
2220                                 output->o_escape = sv;
2221                         } else
2222                         /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2223                          * and in this case should treat it like '$*' - see 'else...' below */
2224                         if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2225                                 while (1) {
2226                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2227                                         if (++i >= G.global_argc)
2228                                                 break;
2229                                         o_addchr(output, '\0');
2230                                         debug_print_list("expand_vars_to_list[4]", output, n);
2231                                         n = o_save_ptr(output, n);
2232                                 }
2233                         } else { /* quoted $*: add as one word */
2234                                 while (1) {
2235                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2236                                         if (!G.global_argv[++i])
2237                                                 break;
2238                                         if (G.ifs[0])
2239                                                 o_addchr(output, G.ifs[0]);
2240                                 }
2241                         }
2242                         break;
2243                 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2244                         /* "Empty variable", used to make "" etc to not disappear */
2245                         arg++;
2246                         ored_ch = 0x80;
2247                         break;
2248 #if ENABLE_HUSH_TICK
2249                 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2250                         *p = '\0';
2251                         arg++;
2252                         /* Can't just stuff it into output o_string,
2253                          * expanded result may need to be globbed
2254                          * and $IFS-splitted */
2255                         debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2256                         process_command_subs(&subst_result, arg);
2257                         debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2258                         val = subst_result.data;
2259                         goto store_val;
2260 #endif
2261 #if ENABLE_SH_MATH_SUPPORT
2262                 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2263                         arith_eval_hooks_t hooks;
2264                         arith_t res;
2265                         int errcode;
2266                         char *exp_str;
2267
2268                         arg++; /* skip '+' */
2269                         *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2270                         debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2271
2272                         exp_str = expand_pseudo_dquoted(arg);
2273                         hooks.lookupvar = get_local_var_value;
2274                         hooks.setvar = arith_set_local_var;
2275                         hooks.endofname = endofname;
2276                         res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2277                         free(exp_str);
2278
2279                         if (errcode < 0) {
2280                                 const char *msg = "error in arithmetic";
2281                                 switch (errcode) {
2282                                 case -3:
2283                                         msg = "exponent less than 0";
2284                                         break;
2285                                 case -2:
2286                                         msg = "divide by 0";
2287                                         break;
2288                                 case -5:
2289                                         msg = "expression recursion loop detected";
2290                                         break;
2291                                 }
2292                                 die_if_script(msg);
2293                         }
2294                         debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2295                         sprintf(arith_buf, arith_t_fmt, res);
2296                         val = arith_buf;
2297                         break;
2298                 }
2299 #endif
2300                 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2301                 case_default: {
2302                         bool exp_len = false;
2303                         bool exp_null = false;
2304                         char *var = arg;
2305                         char exp_save = exp_save; /* for compiler */
2306                         char exp_op = exp_op; /* for compiler */
2307                         char *exp_word = exp_word; /* for compiler */
2308                         size_t exp_off = 0;
2309
2310                         *p = '\0';
2311                         arg[0] = first_ch & 0x7f;
2312
2313                         /* prepare for expansions */
2314                         if (var[0] == '#') {
2315                                 /* handle length expansion ${#var} */
2316                                 exp_len = true;
2317                                 ++var;
2318                         } else {
2319                                 /* maybe handle parameter expansion */
2320                                 exp_off = strcspn(var, ":-=+?%#");
2321                                 if (!var[exp_off])
2322                                         exp_off = 0;
2323                                 if (exp_off) {
2324                                         exp_save = var[exp_off];
2325                                         exp_null = exp_save == ':';
2326                                         exp_word = var + exp_off;
2327                                         if (exp_null)
2328                                                 ++exp_word;
2329                                         exp_op = *exp_word++;
2330                                         var[exp_off] = '\0';
2331                                 }
2332                         }
2333
2334                         /* lookup the variable in question */
2335                         if (isdigit(var[0])) {
2336                                 /* handle_dollar() should have vetted var for us */
2337                                 i = xatoi_u(var);
2338                                 if (i < G.global_argc)
2339                                         val = G.global_argv[i];
2340                                 /* else val remains NULL: $N with too big N */
2341                         } else
2342                                 val = get_local_var_value(var);
2343
2344                         /* handle any expansions */
2345                         if (exp_len) {
2346                                 debug_printf_expand("expand: length of '%s' = ", val);
2347                                 val = utoa(val ? strlen(val) : 0);
2348                                 debug_printf_expand("%s\n", val);
2349                         } else if (exp_off) {
2350                                 if (exp_op == '%' || exp_op == '#') {
2351                                         if (val) {
2352                                                 /* we need to do a pattern match */
2353                                                 bool match_at_left;
2354                                                 char *loc;
2355                                                 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2356                                                 if (exp_op == *exp_word)        /* ## or %% */
2357                                                         ++exp_word;
2358                                                 val = dyn_val = xstrdup(val);
2359                                                 loc = scan(dyn_val, exp_word, match_at_left);
2360                                                 if (match_at_left) /* # or ## */
2361                                                         val = loc;
2362                                                 else if (loc) /* % or %% and match was found */
2363                                                         *loc = '\0';
2364                                         }
2365                                 } else {
2366                                         /* we need to do an expansion */
2367                                         int exp_test = (!val || (exp_null && !val[0]));
2368                                         if (exp_op == '+')
2369                                                 exp_test = !exp_test;
2370                                         debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2371                                                 exp_null ? "true" : "false", exp_test);
2372                                         if (exp_test) {
2373                                                 if (exp_op == '?') {
2374 //TODO: how interactive bash aborts expansion mid-command?
2375                                                         /* ${var?[error_msg_if_unset]} */
2376                                                         /* ${var:?[error_msg_if_unset_or_null]} */
2377                                                         /* mimic bash message */
2378                                                         die_if_script("%s: %s",
2379                                                                 var,
2380                                                                 exp_word[0] ? exp_word : "parameter null or not set"
2381                                                         );
2382                                                 } else {
2383                                                         val = exp_word;
2384                                                 }
2385
2386                                                 if (exp_op == '=') {
2387                                                         /* ${var=[word]} or ${var:=[word]} */
2388                                                         if (isdigit(var[0]) || var[0] == '#') {
2389                                                                 /* mimic bash message */
2390                                                                 die_if_script("$%s: cannot assign in this way", var);
2391                                                                 val = NULL;
2392                                                         } else {
2393                                                                 char *new_var = xasprintf("%s=%s", var, val);
2394                                                                 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2395                                                         }
2396                                                 }
2397                                         }
2398                                 }
2399
2400                                 var[exp_off] = exp_save;
2401                         }
2402
2403                         arg[0] = first_ch;
2404 #if ENABLE_HUSH_TICK
2405  store_val:
2406 #endif
2407                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
2408                                 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2409                                 if (val) {
2410                                         /* unquoted var's contents should be globbed, so don't escape */
2411                                         smallint sv = output->o_escape;
2412                                         output->o_escape = 0;
2413                                         n = expand_on_ifs(output, n, val);
2414                                         val = NULL;
2415                                         output->o_escape = sv;
2416                                 }
2417                         } else { /* quoted $VAR, val will be appended below */
2418                                 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2419                         }
2420                 } /* default: */
2421                 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2422
2423                 if (val) {
2424                         o_addQstr(output, val, strlen(val));
2425                 }
2426                 free(dyn_val);
2427                 /* Do the check to avoid writing to a const string */
2428                 if (*p != SPECIAL_VAR_SYMBOL)
2429                         *p = SPECIAL_VAR_SYMBOL;
2430
2431 #if ENABLE_HUSH_TICK
2432                 o_free(&subst_result);
2433 #endif
2434                 arg = ++p;
2435         } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2436
2437         if (arg[0]) {
2438                 debug_print_list("expand_vars_to_list[a]", output, n);
2439                 /* this part is literal, and it was already pre-quoted
2440                  * if needed (much earlier), do not use o_addQstr here! */
2441                 o_addstr_with_NUL(output, arg);
2442                 debug_print_list("expand_vars_to_list[b]", output, n);
2443         } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2444          && !(ored_ch & 0x80) /* and all vars were not quoted. */
2445         ) {
2446                 n--;
2447                 /* allow to reuse list[n] later without re-growth */
2448                 output->has_empty_slot = 1;
2449         } else {
2450                 o_addchr(output, '\0');
2451         }
2452         return n;
2453 }
2454
2455 static char **expand_variables(char **argv, int or_mask)
2456 {
2457         int n;
2458         char **list;
2459         char **v;
2460         o_string output = NULL_O_STRING;
2461
2462         if (or_mask & 0x100) {
2463                 output.o_escape = 1; /* protect against globbing for "$var" */
2464                 /* (unquoted $var will temporarily switch it off) */
2465                 output.o_glob = 1;
2466         }
2467
2468         n = 0;
2469         v = argv;
2470         while (*v) {
2471                 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2472                 v++;
2473         }
2474         debug_print_list("expand_variables", &output, n);
2475
2476         /* output.data (malloced in one block) gets returned in "list" */
2477         list = o_finalize_list(&output, n);
2478         debug_print_strings("expand_variables[1]", list);
2479         return list;
2480 }
2481
2482 static char **expand_strvec_to_strvec(char **argv)
2483 {
2484         return expand_variables(argv, 0x100);
2485 }
2486
2487 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2488 {
2489         return expand_variables(argv, 0x80);
2490 }
2491
2492 #ifdef CMD_SINGLEWORD_NOGLOB_COND
2493 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2494 {
2495         int n;
2496         char **list;
2497         char **v;
2498         o_string output = NULL_O_STRING;
2499
2500         n = 0;
2501         v = argv;
2502         while (*v) {
2503                 int is_var = is_well_formed_var_name(*v, '=');
2504                 /* is_var * 0x80: singleword expansion for vars */
2505                 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2506
2507                 /* Subtle! expand_vars_to_list did not glob last word yet.
2508                  * It does this only when fed with further data.
2509                  * Therefore we set globbing flags AFTER it, not before:
2510                  */
2511
2512                 /* if it is not recognizably abc=...; then: */
2513                 output.o_escape = !is_var; /* protect against globbing for "$var" */
2514                 /* (unquoted $var will temporarily switch it off) */
2515                 output.o_glob = !is_var; /* and indeed do globbing */
2516                 v++;
2517         }
2518         debug_print_list("expand_cond", &output, n);
2519
2520         /* output.data (malloced in one block) gets returned in "list" */
2521         list = o_finalize_list(&output, n);
2522         debug_print_strings("expand_cond[1]", list);
2523         return list;
2524 }
2525 #endif
2526
2527 /* Used for expansion of right hand of assignments */
2528 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2529  * "v=/bin/c*" */
2530 static char *expand_string_to_string(const char *str)
2531 {
2532         char *argv[2], **list;
2533
2534         argv[0] = (char*)str;
2535         argv[1] = NULL;
2536         list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
2537         if (HUSH_DEBUG)
2538                 if (!list[0] || list[1])
2539                         bb_error_msg_and_die("BUG in varexp2");
2540         /* actually, just move string 2*sizeof(char*) bytes back */
2541         overlapping_strcpy((char*)list, list[0]);
2542         unbackslash((char*)list);
2543         debug_printf_expand("string_to_string='%s'\n", (char*)list);
2544         return (char*)list;
2545 }
2546
2547 /* Used for "eval" builtin */
2548 static char* expand_strvec_to_string(char **argv)
2549 {
2550         char **list;
2551
2552         list = expand_variables(argv, 0x80);
2553         /* Convert all NULs to spaces */
2554         if (list[0]) {
2555                 int n = 1;
2556                 while (list[n]) {
2557                         if (HUSH_DEBUG)
2558                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2559                                         bb_error_msg_and_die("BUG in varexp3");
2560                         /* bash uses ' ' regardless of $IFS contents */
2561                         list[n][-1] = ' ';
2562                         n++;
2563                 }
2564         }
2565         overlapping_strcpy((char*)list, list[0]);
2566         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2567         return (char*)list;
2568 }
2569
2570 static char **expand_assignments(char **argv, int count)
2571 {
2572         int i;
2573         char **p = NULL;
2574         /* Expand assignments into one string each */
2575         for (i = 0; i < count; i++) {
2576                 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2577         }
2578         return p;
2579 }
2580
2581
2582 #if BB_MMU
2583 /* never called */
2584 void re_execute_shell(char ***to_free, const char *s,
2585                 char *g_argv0, char **g_argv,
2586                 char **builtin_argv) NORETURN;
2587
2588 static void reset_traps_to_defaults(void)
2589 {
2590         /* This function is always called in a child shell
2591          * after fork (not vfork, NOMMU doesn't use this function).
2592          * Child shells are not interactive.
2593          * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2594          * Testcase: (while :; do :; done) + ^Z should background.
2595          * Same goes for SIGTERM, SIGHUP, SIGINT.
2596          */
2597         unsigned sig;
2598         unsigned mask;
2599
2600         if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2601                 return;
2602
2603         /* Stupid. It can be done with *single* &= op, but we can't use
2604          * the fact that G.blocked_set is implemented as a bitmask... */
2605         mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2606         sig = 1;
2607         while (1) {
2608                 if (mask & 1)
2609                         sigdelset(&G.blocked_set, sig);
2610                 mask >>= 1;
2611                 if (!mask)
2612                         break;
2613                 sig++;
2614         }
2615
2616         G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2617         mask = G.non_DFL_mask;
2618         if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2619                 if (!G.traps[sig])
2620                         continue;
2621                 free(G.traps[sig]);
2622                 G.traps[sig] = NULL;
2623                 /* There is no signal for 0 (EXIT) */
2624                 if (sig == 0)
2625                         continue;
2626                 /* There was a trap handler, we are removing it.
2627                  * But if sig still has non-DFL handling,
2628                  * we should not unblock it. */
2629                 if (mask & 1)
2630                         continue;
2631                 sigdelset(&G.blocked_set, sig);
2632         }
2633         sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2634 }
2635
2636 #else /* !BB_MMU */
2637
2638 static void re_execute_shell(char ***to_free, const char *s,
2639                 char *g_argv0, char **g_argv,
2640                 char **builtin_argv) NORETURN;
2641 static void re_execute_shell(char ***to_free, const char *s,
2642                 char *g_argv0, char **g_argv,
2643                 char **builtin_argv)
2644 {
2645         char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
2646         char *heredoc_argv[4];
2647         struct variable *cur;
2648 #if ENABLE_HUSH_FUNCTIONS
2649         struct function *funcp;
2650 #endif
2651         char **argv, **pp;
2652         unsigned cnt;
2653
2654         if (!g_argv0) { /* heredoc */
2655                 argv = heredoc_argv;
2656                 argv[0] = (char *) G.argv0_for_re_execing;
2657                 argv[1] = (char *) "-<";
2658                 argv[2] = (char *) s;
2659                 argv[3] = NULL;
2660                 pp = &argv[3]; /* used as pointer to empty environment */
2661                 goto do_exec;
2662         }
2663
2664         cnt = 0;
2665         pp = builtin_argv;
2666         if (pp) while (*pp++)
2667                 cnt++;
2668
2669         sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
2670                         , (unsigned) G.root_pid
2671                         , (unsigned) G.last_bg_pid
2672                         , (unsigned) G.last_exitcode
2673                         , cnt
2674                         IF_HUSH_LOOPS(, G.depth_of_loop)
2675                         );
2676         /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
2677          * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2678          */
2679         cnt += 6;
2680         for (cur = G.top_var; cur; cur = cur->next) {
2681                 if (!cur->flg_export || cur->flg_read_only)
2682                         cnt += 2;
2683         }
2684 #if ENABLE_HUSH_FUNCTIONS
2685         for (funcp = G.top_func; funcp; funcp = funcp->next)
2686                 cnt += 3;
2687 #endif
2688         pp = g_argv;
2689         while (*pp++)
2690                 cnt++;
2691         *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2692         *pp++ = (char *) G.argv0_for_re_execing;
2693         *pp++ = param_buf;
2694         for (cur = G.top_var; cur; cur = cur->next) {
2695                 if (cur->varstr == hush_version_str)
2696                         continue;
2697                 if (cur->flg_read_only) {
2698                         *pp++ = (char *) "-R";
2699                         *pp++ = cur->varstr;
2700                 } else if (!cur->flg_export) {
2701                         *pp++ = (char *) "-V";
2702                         *pp++ = cur->varstr;
2703                 }
2704         }
2705 #if ENABLE_HUSH_FUNCTIONS
2706         for (funcp = G.top_func; funcp; funcp = funcp->next) {
2707                 *pp++ = (char *) "-F";
2708                 *pp++ = funcp->name;
2709                 *pp++ = funcp->body_as_string;
2710         }
2711 #endif
2712         /* We can pass activated traps here. Say, -Tnn:trap_string
2713          *
2714          * However, POSIX says that subshells reset signals with traps
2715          * to SIG_DFL.
2716          * I tested bash-3.2 and it not only does that with true subshells
2717          * of the form ( list ), but with any forked children shells.
2718          * I set trap "echo W" WINCH; and then tried:
2719          *
2720          * { echo 1; sleep 20; echo 2; } &
2721          * while true; do echo 1; sleep 20; echo 2; break; done &
2722          * true | { echo 1; sleep 20; echo 2; } | cat
2723          *
2724          * In all these cases sending SIGWINCH to the child shell
2725          * did not run the trap. If I add trap "echo V" WINCH;
2726          * _inside_ group (just before echo 1), it works.
2727          *
2728          * I conclude it means we don't need to pass active traps here.
2729          * exec syscall below resets them to SIG_DFL for us.
2730          */
2731         *pp++ = (char *) "-c";
2732         *pp++ = (char *) s;
2733         if (builtin_argv) {
2734                 while (*++builtin_argv)
2735                         *pp++ = *builtin_argv;
2736                 *pp++ = (char *) "";
2737         }
2738         *pp++ = g_argv0;
2739         while (*g_argv)
2740                 *pp++ = *g_argv++;
2741         /* *pp = NULL; - is already there */
2742         pp = environ;
2743
2744  do_exec:
2745         debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2746         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2747         execve(bb_busybox_exec_path, argv, pp);
2748         /* Fallback. Useful for init=/bin/hush usage etc */
2749         if (argv[0][0] == '/')
2750                 execve(argv[0], argv, pp);
2751         xfunc_error_retval = 127;
2752         bb_error_msg_and_die("can't re-execute the shell");
2753 }
2754 #endif  /* !BB_MMU */
2755
2756
2757 static void setup_heredoc(struct redir_struct *redir)
2758 {
2759         struct fd_pair pair;
2760         pid_t pid;
2761         int len, written;
2762         /* the _body_ of heredoc (misleading field name) */
2763         const char *heredoc = redir->rd_filename;
2764         char *expanded;
2765 #if !BB_MMU
2766         char **to_free;
2767 #endif
2768
2769         expanded = NULL;
2770         if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2771                 expanded = expand_pseudo_dquoted(heredoc);
2772                 if (expanded)
2773                         heredoc = expanded;
2774         }
2775         len = strlen(heredoc);
2776
2777         close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2778         xpiped_pair(pair);
2779         xmove_fd(pair.rd, redir->rd_fd);
2780
2781         /* Try writing without forking. Newer kernels have
2782          * dynamically growing pipes. Must use non-blocking write! */
2783         ndelay_on(pair.wr);
2784         while (1) {
2785                 written = write(pair.wr, heredoc, len);
2786                 if (written <= 0)
2787                         break;
2788                 len -= written;
2789                 if (len == 0) {
2790                         close(pair.wr);
2791                         free(expanded);
2792                         return;
2793                 }
2794                 heredoc += written;
2795         }
2796         ndelay_off(pair.wr);
2797
2798         /* Okay, pipe buffer was not big enough */
2799         /* Note: we must not create a stray child (bastard? :)
2800          * for the unsuspecting parent process. Child creates a grandchild
2801          * and exits before parent execs the process which consumes heredoc
2802          * (that exec happens after we return from this function) */
2803 #if !BB_MMU
2804         to_free = NULL;
2805 #endif
2806         pid = vfork();
2807         if (pid < 0)
2808                 bb_perror_msg_and_die("vfork");
2809         if (pid == 0) {
2810                 /* child */
2811                 disable_restore_tty_pgrp_on_exit();
2812                 pid = BB_MMU ? fork() : vfork();
2813                 if (pid < 0)
2814                         bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2815                 if (pid != 0)
2816                         _exit(0);
2817                 /* grandchild */
2818                 close(redir->rd_fd); /* read side of the pipe */
2819 #if BB_MMU
2820                 full_write(pair.wr, heredoc, len); /* may loop or block */
2821                 _exit(0);
2822 #else
2823                 /* Delegate blocking writes to another process */
2824                 xmove_fd(pair.wr, STDOUT_FILENO);
2825                 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
2826 #endif
2827         }
2828         /* parent */
2829 #if ENABLE_HUSH_FAST
2830         G.count_SIGCHLD++;
2831 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2832 #endif
2833         enable_restore_tty_pgrp_on_exit();
2834 #if !BB_MMU
2835         free(to_free);
2836 #endif
2837         close(pair.wr);
2838         free(expanded);
2839         wait(NULL); /* wait till child has died */
2840 }
2841
2842 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2843  * and stderr if they are redirected. */
2844 static int setup_redirects(struct command *prog, int squirrel[])
2845 {
2846         int openfd, mode;
2847         struct redir_struct *redir;
2848
2849         for (redir = prog->redirects; redir; redir = redir->next) {
2850                 if (redir->rd_type == REDIRECT_HEREDOC2) {
2851                         /* rd_fd<<HERE case */
2852                         if (squirrel && redir->rd_fd < 3
2853                          && squirrel[redir->rd_fd] < 0
2854                         ) {
2855                                 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2856                         }
2857                         /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2858                          * of the heredoc */
2859                         debug_printf_parse("set heredoc '%s'\n",
2860                                         redir->rd_filename);
2861                         setup_heredoc(redir);
2862                         continue;
2863                 }
2864
2865                 if (redir->rd_dup == REDIRFD_TO_FILE) {
2866                         /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2867                         char *p;
2868                         if (redir->rd_filename == NULL) {
2869                                 /* Something went wrong in the parse.
2870                                  * Pretend it didn't happen */
2871                                 bb_error_msg("bug in redirect parse");
2872                                 continue;
2873                         }
2874                         mode = redir_table[redir->rd_type].mode;
2875                         p = expand_string_to_string(redir->rd_filename);
2876                         openfd = open_or_warn(p, mode);
2877                         free(p);
2878                         if (openfd < 0) {
2879                         /* this could get lost if stderr has been redirected, but
2880                          * bash and ash both lose it as well (though zsh doesn't!) */
2881 //what the above comment tries to say?
2882                                 return 1;
2883                         }
2884                 } else {
2885                         /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2886                         openfd = redir->rd_dup;
2887                 }
2888
2889                 if (openfd != redir->rd_fd) {
2890                         if (squirrel && redir->rd_fd < 3
2891                          && squirrel[redir->rd_fd] < 0
2892                         ) {
2893                                 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2894                         }
2895                         if (openfd == REDIRFD_CLOSE) {
2896                                 /* "n>-" means "close me" */
2897                                 close(redir->rd_fd);
2898                         } else {
2899                                 xdup2(openfd, redir->rd_fd);
2900                                 if (redir->rd_dup == REDIRFD_TO_FILE)
2901                                         close(openfd);
2902                         }
2903                 }
2904         }
2905         return 0;
2906 }
2907
2908 static void restore_redirects(int squirrel[])
2909 {
2910         int i, fd;
2911         for (i = 0; i < 3; i++) {
2912                 fd = squirrel[i];
2913                 if (fd != -1) {
2914                         /* We simply die on error */
2915                         xmove_fd(fd, i);
2916                 }
2917         }
2918 }
2919
2920
2921 static void free_pipe_list(struct pipe *head);
2922
2923 /* Return code is the exit status of the pipe */
2924 static void free_pipe(struct pipe *pi)
2925 {
2926         char **p;
2927         struct command *command;
2928         struct redir_struct *r, *rnext;
2929         int a, i;
2930
2931         if (pi->stopped_cmds > 0) /* why? */
2932                 return;
2933         debug_printf_clean("run pipe: (pid %d)\n", getpid());
2934         for (i = 0; i < pi->num_cmds; i++) {
2935                 command = &pi->cmds[i];
2936                 debug_printf_clean("  command %d:\n", i);
2937                 if (command->argv) {
2938                         for (a = 0, p = command->argv; *p; a++, p++) {
2939                                 debug_printf_clean("   argv[%d] = %s\n", a, *p);
2940                         }
2941                         free_strings(command->argv);
2942                         command->argv = NULL;
2943                 }
2944                 /* not "else if": on syntax error, we may have both! */
2945                 if (command->group) {
2946                         debug_printf_clean("   begin group (cmd_type:%d)\n",
2947                                         command->cmd_type);
2948                         free_pipe_list(command->group);
2949                         debug_printf_clean("   end group\n");
2950                         command->group = NULL;
2951                 }
2952                 /* else is crucial here.
2953                  * If group != NULL, child_func is meaningless */
2954 #if ENABLE_HUSH_FUNCTIONS
2955                 else if (command->child_func) {
2956                         debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2957                         command->child_func->parent_cmd = NULL;
2958                 }
2959 #endif
2960 #if !BB_MMU
2961                 free(command->group_as_string);
2962                 command->group_as_string = NULL;
2963 #endif
2964                 for (r = command->redirects; r; r = rnext) {
2965                         debug_printf_clean("   redirect %d%s",
2966                                         r->rd_fd, redir_table[r->rd_type].descrip);
2967                         /* guard against the case >$FOO, where foo is unset or blank */
2968                         if (r->rd_filename) {
2969                                 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2970                                 free(r->rd_filename);
2971                                 r->rd_filename = NULL;
2972                         }
2973                         debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2974                         rnext = r->next;
2975                         free(r);
2976                 }
2977                 command->redirects = NULL;
2978         }
2979         free(pi->cmds);   /* children are an array, they get freed all at once */
2980         pi->cmds = NULL;
2981 #if ENABLE_HUSH_JOB
2982         free(pi->cmdtext);
2983         pi->cmdtext = NULL;
2984 #endif
2985 }
2986
2987 static void free_pipe_list(struct pipe *head)
2988 {
2989         struct pipe *pi, *next;
2990
2991         for (pi = head; pi; pi = next) {
2992 #if HAS_KEYWORDS
2993                 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2994 #endif
2995                 free_pipe(pi);
2996                 debug_printf_clean("pipe followup code %d\n", pi->followup);
2997                 next = pi->next;
2998                 /*pi->next = NULL;*/
2999                 free(pi);
3000         }
3001 }
3002
3003
3004 static int run_list(struct pipe *pi);
3005 #if BB_MMU
3006 #define parse_stream(pstring, input, end_trigger) \
3007         parse_stream(input, end_trigger)
3008 #endif
3009 static struct pipe *parse_stream(char **pstring,
3010                 struct in_str *input,
3011                 int end_trigger);
3012 static void parse_and_run_string(const char *s);
3013
3014
3015 static char *find_in_path(const char *arg)
3016 {
3017         char *ret = NULL;
3018         const char *PATH = get_local_var_value("PATH");
3019
3020         if (!PATH)
3021                 return NULL;
3022
3023         while (1) {
3024                 const char *end = strchrnul(PATH, ':');
3025                 int sz = end - PATH; /* must be int! */
3026
3027                 free(ret);
3028                 if (sz != 0) {
3029                         ret = xasprintf("%.*s/%s", sz, PATH, arg);
3030                 } else {
3031                         /* We have xxx::yyyy in $PATH,
3032                          * it means "use current dir" */
3033                         ret = xstrdup(arg);
3034                 }
3035                 if (access(ret, F_OK) == 0)
3036                         break;
3037
3038                 if (*end == '\0') {
3039                         free(ret);
3040                         return NULL;
3041                 }
3042                 PATH = end + 1;
3043         }
3044
3045         return ret;
3046 }
3047
3048 static const struct built_in_command* find_builtin_helper(const char *name,
3049                 const struct built_in_command *x,
3050                 const struct built_in_command *end)
3051 {
3052         while (x != end) {
3053                 if (strcmp(name, x->cmd) != 0) {
3054                         x++;
3055                         continue;
3056                 }
3057                 debug_printf_exec("found builtin '%s'\n", name);
3058                 return x;
3059         }
3060         return NULL;
3061 }
3062 static const struct built_in_command* find_builtin1(const char *name)
3063 {
3064         return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3065 }
3066 static const struct built_in_command* find_builtin(const char *name)
3067 {
3068         const struct built_in_command *x = find_builtin1(name);
3069         if (x)
3070                 return x;
3071         return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3072 }
3073
3074 #if ENABLE_HUSH_FUNCTIONS
3075 static const struct function *find_function(const char *name)
3076 {
3077         const struct function *funcp = G.top_func;
3078         while (funcp) {
3079                 if (strcmp(name, funcp->name) == 0) {
3080                         break;
3081                 }
3082                 funcp = funcp->next;
3083         }
3084         if (funcp)
3085                 debug_printf_exec("found function '%s'\n", name);
3086         return funcp;
3087 }
3088
3089 /* Note: takes ownership on name ptr */
3090 static struct function *new_function(char *name)
3091 {
3092         struct function *funcp;
3093         struct function **funcpp = &G.top_func;
3094
3095         while ((funcp = *funcpp) != NULL) {
3096                 struct command *cmd;
3097
3098                 if (strcmp(funcp->name, name) != 0) {
3099                         funcpp = &funcp->next;
3100                         continue;
3101                 }
3102
3103                 cmd = funcp->parent_cmd;
3104                 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3105                 if (!cmd) {
3106                         debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3107                         free(funcp->name);
3108                         /* Note: if !funcp->body, do not free body_as_string!
3109                          * This is a special case of "-F name body" function:
3110                          * body_as_string was not malloced! */
3111                         if (funcp->body) {
3112                                 free_pipe_list(funcp->body);
3113 # if !BB_MMU
3114                                 free(funcp->body_as_string);
3115 # endif
3116                         }
3117                 } else {
3118                         debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3119                         cmd->argv[0] = funcp->name;
3120                         cmd->group = funcp->body;
3121 # if !BB_MMU
3122                         cmd->group_as_string = funcp->body_as_string;
3123 # endif
3124                 }
3125                 goto skip;
3126         }
3127         debug_printf_exec("remembering new function '%s'\n", name);
3128         funcp = *funcpp = xzalloc(sizeof(*funcp));
3129         /*funcp->next = NULL;*/
3130  skip:
3131         funcp->name = name;
3132         return funcp;
3133 }
3134
3135 static void unset_func(const char *name)
3136 {
3137         struct function *funcp;
3138         struct function **funcpp = &G.top_func;
3139
3140         while ((funcp = *funcpp) != NULL) {
3141                 if (strcmp(funcp->name, name) == 0) {
3142                         *funcpp = funcp->next;
3143                         /* funcp is unlinked now, deleting it.
3144                          * Note: if !funcp->body, the function was created by
3145                          * "-F name body", do not free ->body_as_string
3146                          * and ->name as they were not malloced. */
3147                         if (funcp->body) {
3148                                 free_pipe_list(funcp->body);
3149                                 free(funcp->name);
3150 # if !BB_MMU
3151                                 free(funcp->body_as_string);
3152 # endif
3153                         }
3154                         free(funcp);
3155                         break;
3156                 }
3157                 funcpp = &funcp->next;
3158         }
3159 }
3160
3161 # if BB_MMU
3162 #define exec_function(to_free, funcp, argv) \
3163         exec_function(funcp, argv)
3164 # endif
3165 static void exec_function(char ***to_free,
3166                 const struct function *funcp,
3167                 char **argv) NORETURN;
3168 static void exec_function(char ***to_free,
3169                 const struct function *funcp,
3170                 char **argv)
3171 {
3172 # if BB_MMU
3173         int n = 1;
3174
3175         argv[0] = G.global_argv[0];
3176         G.global_argv = argv;
3177         while (*++argv)
3178                 n++;
3179         G.global_argc = n;
3180         /* On MMU, funcp->body is always non-NULL */
3181         n = run_list(funcp->body);
3182         fflush(NULL);
3183         _exit(n);
3184 # else
3185         re_execute_shell(to_free,
3186                         funcp->body_as_string,
3187                         G.global_argv[0],
3188                         argv + 1,
3189                         NULL);
3190 # endif
3191 }
3192
3193 static int run_function(const struct function *funcp, char **argv)
3194 {
3195         int rc;
3196         save_arg_t sv;
3197         smallint sv_flg;
3198
3199         save_and_replace_G_args(&sv, argv);
3200
3201         /* "we are in function, ok to use return" */
3202         sv_flg = G.flag_return_in_progress;
3203         G.flag_return_in_progress = -1;
3204 #if ENABLE_HUSH_LOCAL
3205         G.func_nest_level++;
3206 #endif
3207
3208         /* On MMU, funcp->body is always non-NULL */
3209 # if !BB_MMU
3210         if (!funcp->body) {
3211                 /* Function defined by -F */
3212                 parse_and_run_string(funcp->body_as_string);
3213                 rc = G.last_exitcode;
3214         } else
3215 # endif
3216         {
3217                 rc = run_list(funcp->body);
3218         }
3219
3220 #if ENABLE_HUSH_LOCAL
3221         {
3222                 struct variable *var;
3223                 struct variable **var_pp;
3224
3225                 var_pp = &G.top_var;
3226                 while ((var = *var_pp) != NULL) {
3227                         if (var->func_nest_level < G.func_nest_level) {
3228                                 var_pp = &var->next;
3229                                 continue;
3230                         }
3231                         /* Unexport */
3232                         if (var->flg_export)
3233                                 bb_unsetenv(var->varstr);
3234                         /* Remove from global list */
3235                         *var_pp = var->next;
3236                         /* Free */
3237                         if (!var->max_len)
3238                                 free(var->varstr);
3239                         free(var);
3240                 }
3241                 G.func_nest_level--;
3242         }
3243 #endif
3244         G.flag_return_in_progress = sv_flg;
3245
3246         restore_G_args(&sv, argv);
3247
3248         return rc;
3249 }
3250 #endif /* ENABLE_HUSH_FUNCTIONS */
3251
3252
3253 # if BB_MMU
3254 #define exec_builtin(to_free, x, argv) \
3255         exec_builtin(x, argv)
3256 # else
3257 #define exec_builtin(to_free, x, argv) \
3258         exec_builtin(to_free, argv)
3259 # endif
3260 static void exec_builtin(char ***to_free,
3261                 const struct built_in_command *x,
3262                 char **argv) NORETURN;
3263 static void exec_builtin(char ***to_free,
3264                 const struct built_in_command *x,
3265                 char **argv)
3266 {
3267 # if BB_MMU
3268         int rcode = x->function(argv);
3269         fflush(NULL);
3270         _exit(rcode);
3271 # else
3272         /* On NOMMU, we must never block!
3273          * Example: { sleep 99 | read line; } & echo Ok
3274          */
3275         re_execute_shell(to_free,
3276                         argv[0],
3277                         G.global_argv[0],
3278                         G.global_argv + 1,
3279                         argv);
3280 # endif
3281 }
3282
3283
3284 #if BB_MMU
3285 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3286         pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3287 #define pseudo_exec(nommu_save, command, argv_expanded) \
3288         pseudo_exec(command, argv_expanded)
3289 #endif
3290
3291 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3292  * Never returns.
3293  * Don't exit() here.  If you don't exec, use _exit instead.
3294  * The at_exit handlers apparently confuse the calling process,
3295  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
3296 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3297                 char **argv, int assignment_cnt,
3298                 char **argv_expanded) NORETURN;
3299 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3300                 char **argv, int assignment_cnt,
3301                 char **argv_expanded)
3302 {
3303         char **new_env;
3304
3305         /* Case when we are here: ... | var=val | ... */
3306         if (!argv[assignment_cnt])
3307                 _exit(EXIT_SUCCESS);
3308
3309         new_env = expand_assignments(argv, assignment_cnt);
3310 #if BB_MMU
3311         set_vars_and_save_old(new_env);
3312         free(new_env); /* optional */
3313         /* we can also destroy set_vars_and_save_old's return value,
3314          * to save memory */
3315 #else
3316         nommu_save->new_env = new_env;
3317         nommu_save->old_vars = set_vars_and_save_old(new_env);
3318 #endif
3319         if (argv_expanded) {
3320                 argv = argv_expanded;
3321         } else {
3322                 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3323 #if !BB_MMU
3324                 nommu_save->argv = argv;
3325 #endif
3326         }
3327
3328 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3329         if (strchr(argv[0], '/') != NULL)
3330                 goto skip;
3331 #endif
3332
3333         /* Check if the command matches any of the builtins.
3334          * Depending on context, this might be redundant.  But it's
3335          * easier to waste a few CPU cycles than it is to figure out
3336          * if this is one of those cases.
3337          */
3338         {
3339                 /* On NOMMU, it is more expensive to re-execute shell
3340                  * just in order to run echo or test builtin.
3341                  * It's better to skip it here and run corresponding
3342                  * non-builtin later. */
3343                 const struct built_in_command *x;
3344                 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3345                 if (x) {
3346                         exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3347                 }
3348         }
3349 #if ENABLE_HUSH_FUNCTIONS
3350         /* Check if the command matches any functions */
3351         {
3352                 const struct function *funcp = find_function(argv[0]);
3353                 if (funcp) {
3354                         exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3355                 }
3356         }
3357 #endif
3358
3359 #if ENABLE_FEATURE_SH_STANDALONE
3360         /* Check if the command matches any busybox applets */
3361         {
3362                 int a = find_applet_by_name(argv[0]);
3363                 if (a >= 0) {
3364 # if BB_MMU /* see above why on NOMMU it is not allowed */
3365                         if (APPLET_IS_NOEXEC(a)) {
3366                                 debug_printf_exec("running applet '%s'\n", argv[0]);
3367                                 run_applet_no_and_exit(a, argv);
3368                         }
3369 # endif
3370                         /* Re-exec ourselves */
3371                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3372                         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3373                         execv(bb_busybox_exec_path, argv);
3374                         /* If they called chroot or otherwise made the binary no longer
3375                          * executable, fall through */
3376                 }
3377         }
3378 #endif
3379
3380 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3381  skip:
3382 #endif
3383         debug_printf_exec("execing '%s'\n", argv[0]);
3384         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3385         execvp(argv[0], argv);
3386         bb_perror_msg("can't execute '%s'", argv[0]);
3387         _exit(EXIT_FAILURE);
3388 }
3389
3390 /* Called after [v]fork() in run_pipe
3391  */
3392 static void pseudo_exec(nommu_save_t *nommu_save,
3393                 struct command *command,
3394                 char **argv_expanded) NORETURN;
3395 static void pseudo_exec(nommu_save_t *nommu_save,
3396                 struct command *command,
3397                 char **argv_expanded)
3398 {
3399         if (command->argv) {
3400                 pseudo_exec_argv(nommu_save, command->argv,
3401                                 command->assignment_cnt, argv_expanded);
3402         }
3403
3404         if (command->group) {
3405                 /* Cases when we are here:
3406                  * ( list )
3407                  * { list } &
3408                  * ... | ( list ) | ...
3409                  * ... | { list } | ...
3410                  */
3411 #if BB_MMU
3412                 int rcode;
3413                 debug_printf_exec("pseudo_exec: run_list\n");
3414                 reset_traps_to_defaults();
3415                 rcode = run_list(command->group);
3416                 /* OK to leak memory by not calling free_pipe_list,
3417                  * since this process is about to exit */
3418                 _exit(rcode);
3419 #else
3420                 re_execute_shell(&nommu_save->argv_from_re_execing,
3421                                 command->group_as_string,
3422                                 G.global_argv[0],
3423                                 G.global_argv + 1,
3424                                 NULL);
3425 #endif
3426         }
3427
3428         /* Case when we are here: ... | >file */
3429         debug_printf_exec("pseudo_exec'ed null command\n");
3430         _exit(EXIT_SUCCESS);
3431 }
3432
3433 #if ENABLE_HUSH_JOB
3434 static const char *get_cmdtext(struct pipe *pi)
3435 {
3436         char **argv;
3437         char *p;
3438         int len;
3439
3440         /* This is subtle. ->cmdtext is created only on first backgrounding.
3441          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
3442          * On subsequent bg argv is trashed, but we won't use it */
3443         if (pi->cmdtext)
3444                 return pi->cmdtext;
3445         argv = pi->cmds[0].argv;
3446         if (!argv || !argv[0]) {
3447                 pi->cmdtext = xzalloc(1);
3448                 return pi->cmdtext;
3449         }
3450
3451         len = 0;
3452         do {
3453                 len += strlen(*argv) + 1;
3454         } while (*++argv);
3455         p = xmalloc(len);
3456         pi->cmdtext = p;
3457         argv = pi->cmds[0].argv;
3458         do {
3459                 len = strlen(*argv);
3460                 memcpy(p, *argv, len);
3461                 p += len;
3462                 *p++ = ' ';
3463         } while (*++argv);
3464         p[-1] = '\0';
3465         return pi->cmdtext;
3466 }
3467
3468 static void insert_bg_job(struct pipe *pi)
3469 {
3470         struct pipe *job, **jobp;
3471         int i;
3472
3473         /* Linear search for the ID of the job to use */
3474         pi->jobid = 1;
3475         for (job = G.job_list; job; job = job->next)
3476                 if (job->jobid >= pi->jobid)
3477                         pi->jobid = job->jobid + 1;
3478
3479         /* Add job to the list of running jobs */
3480         jobp = &G.job_list;
3481         while ((job = *jobp) != NULL)
3482                 jobp = &job->next;
3483         job = *jobp = xmalloc(sizeof(*job));
3484
3485         *job = *pi; /* physical copy */
3486         job->next = NULL;
3487         job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3488         /* Cannot copy entire pi->cmds[] vector! This causes double frees */
3489         for (i = 0; i < pi->num_cmds; i++) {
3490                 job->cmds[i].pid = pi->cmds[i].pid;
3491                 /* all other fields are not used and stay zero */
3492         }
3493         job->cmdtext = xstrdup(get_cmdtext(pi));
3494
3495         if (G_interactive_fd)
3496                 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3497         /* Last command's pid goes to $! */
3498         G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3499         G.last_jobid = job->jobid;
3500 }
3501
3502 static void remove_bg_job(struct pipe *pi)
3503 {
3504         struct pipe *prev_pipe;
3505
3506         if (pi == G.job_list) {
3507                 G.job_list = pi->next;
3508         } else {
3509                 prev_pipe = G.job_list;
3510                 while (prev_pipe->next != pi)
3511                         prev_pipe = prev_pipe->next;
3512                 prev_pipe->next = pi->next;
3513         }
3514         if (G.job_list)
3515                 G.last_jobid = G.job_list->jobid;
3516         else
3517                 G.last_jobid = 0;
3518 }
3519
3520 /* Remove a backgrounded job */
3521 static void delete_finished_bg_job(struct pipe *pi)
3522 {
3523         remove_bg_job(pi);
3524         pi->stopped_cmds = 0;
3525         free_pipe(pi);
3526         free(pi);
3527 }
3528 #endif /* JOB */
3529
3530 /* Check to see if any processes have exited -- if they
3531  * have, figure out why and see if a job has completed */
3532 static int checkjobs(struct pipe* fg_pipe)
3533 {
3534         int attributes;
3535         int status;
3536 #if ENABLE_HUSH_JOB
3537         struct pipe *pi;
3538 #endif
3539         pid_t childpid;
3540         int rcode = 0;
3541
3542         debug_printf_jobs("checkjobs %p\n", fg_pipe);
3543
3544         attributes = WUNTRACED;
3545         if (fg_pipe == NULL)
3546                 attributes |= WNOHANG;
3547
3548         errno = 0;
3549 #if ENABLE_HUSH_FAST
3550         if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3551 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3552 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
3553                 /* There was neither fork nor SIGCHLD since last waitpid */
3554                 /* Avoid doing waitpid syscall if possible */
3555                 if (!G.we_have_children) {
3556                         errno = ECHILD;
3557                         return -1;
3558                 }
3559                 if (fg_pipe == NULL) { /* is WNOHANG set? */
3560                         /* We have children, but they did not exit
3561                          * or stop yet (we saw no SIGCHLD) */
3562                         return 0;
3563                 }
3564                 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3565         }
3566 #endif
3567
3568 /* Do we do this right?
3569  * bash-3.00# sleep 20 | false
3570  * <ctrl-Z pressed>
3571  * [3]+  Stopped          sleep 20 | false
3572  * bash-3.00# echo $?
3573  * 1   <========== bg pipe is not fully done, but exitcode is already known!
3574  * [hush 1.14.0: yes we do it right]
3575  */
3576  wait_more:
3577         while (1) {
3578                 int i;
3579                 int dead;
3580
3581 #if ENABLE_HUSH_FAST
3582                 i = G.count_SIGCHLD;
3583 #endif
3584                 childpid = waitpid(-1, &status, attributes);
3585                 if (childpid <= 0) {
3586                         if (childpid && errno != ECHILD)
3587                                 bb_perror_msg("waitpid");
3588 #if ENABLE_HUSH_FAST
3589                         else { /* Until next SIGCHLD, waitpid's are useless */
3590                                 G.we_have_children = (childpid == 0);
3591                                 G.handled_SIGCHLD = i;
3592 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3593                         }
3594 #endif
3595                         break;
3596                 }
3597                 dead = WIFEXITED(status) || WIFSIGNALED(status);
3598
3599 #if DEBUG_JOBS
3600                 if (WIFSTOPPED(status))
3601                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3602                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
3603                 if (WIFSIGNALED(status))
3604                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3605                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
3606                 if (WIFEXITED(status))
3607                         debug_printf_jobs("pid %d exited, exitcode %d\n",
3608                                         childpid, WEXITSTATUS(status));
3609 #endif
3610                 /* Were we asked to wait for fg pipe? */
3611                 if (fg_pipe) {
3612                         for (i = 0; i < fg_pipe->num_cmds; i++) {
3613                                 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3614                                 if (fg_pipe->cmds[i].pid != childpid)
3615                                         continue;
3616                                 if (dead) {
3617                                         fg_pipe->cmds[i].pid = 0;
3618                                         fg_pipe->alive_cmds--;
3619                                         if (i == fg_pipe->num_cmds - 1) {
3620                                                 /* last process gives overall exitstatus */
3621                                                 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
3622                                                 rcode = WEXITSTATUS(status);
3623                                                 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3624                                                 /* bash prints killing signal's name for *last*
3625                                                  * process in pipe (prints just newline for SIGINT).
3626                                                  * Mimic this. Example: "sleep 5" + ^\
3627                                                  */
3628                                                 if (WIFSIGNALED(status)) {
3629                                                         int sig = WTERMSIG(status);
3630                                                         printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
3631                                                 }
3632                                         }
3633                                 } else {
3634                                         fg_pipe->cmds[i].is_stopped = 1;
3635                                         fg_pipe->stopped_cmds++;
3636                                 }
3637                                 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3638                                                 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3639                                 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3640                                         /* All processes in fg pipe have exited or stopped */
3641 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
3642  * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3643  * and "killall -STOP cat" */
3644                                         if (G_interactive_fd) {
3645 #if ENABLE_HUSH_JOB
3646                                                 if (fg_pipe->alive_cmds)
3647                                                         insert_bg_job(fg_pipe);
3648 #endif
3649                                                 return rcode;
3650                                         }
3651                                         if (!fg_pipe->alive_cmds)
3652                                                 return rcode;
3653                                 }
3654                                 /* There are still running processes in the fg pipe */
3655                                 goto wait_more; /* do waitpid again */
3656                         }
3657                         /* it wasnt fg_pipe, look for process in bg pipes */
3658                 }
3659
3660 #if ENABLE_HUSH_JOB
3661                 /* We asked to wait for bg or orphaned children */
3662                 /* No need to remember exitcode in this case */
3663                 for (pi = G.job_list; pi; pi = pi->next) {
3664                         for (i = 0; i < pi->num_cmds; i++) {
3665                                 if (pi->cmds[i].pid == childpid)
3666                                         goto found_pi_and_prognum;
3667                         }
3668                 }
3669                 /* Happens when shell is used as init process (init=/bin/sh) */
3670                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3671                 continue; /* do waitpid again */
3672
3673  found_pi_and_prognum:
3674                 if (dead) {
3675                         /* child exited */
3676                         pi->cmds[i].pid = 0;
3677                         pi->alive_cmds--;
3678                         if (!pi->alive_cmds) {
3679                                 if (G_interactive_fd)
3680                                         printf(JOB_STATUS_FORMAT, pi->jobid,
3681                                                         "Done", pi->cmdtext);
3682                                 delete_finished_bg_job(pi);
3683                         }
3684                 } else {
3685                         /* child stopped */
3686                         pi->cmds[i].is_stopped = 1;
3687                         pi->stopped_cmds++;
3688                 }
3689 #endif
3690         } /* while (waitpid succeeds)... */
3691
3692         return rcode;
3693 }
3694
3695 #if ENABLE_HUSH_JOB
3696 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3697 {
3698         pid_t p;
3699         int rcode = checkjobs(fg_pipe);
3700         if (G_saved_tty_pgrp) {
3701                 /* Job finished, move the shell to the foreground */
3702                 p = getpgrp(); /* our process group id */
3703                 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3704                 tcsetpgrp(G_interactive_fd, p);
3705         }
3706         return rcode;
3707 }
3708 #endif
3709
3710 /* Start all the jobs, but don't wait for anything to finish.
3711  * See checkjobs().
3712  *
3713  * Return code is normally -1, when the caller has to wait for children
3714  * to finish to determine the exit status of the pipe.  If the pipe
3715  * is a simple builtin command, however, the action is done by the
3716  * time run_pipe returns, and the exit code is provided as the
3717  * return value.
3718  *
3719  * Returns -1 only if started some children. IOW: we have to
3720  * mask out retvals of builtins etc with 0xff!
3721  *
3722  * The only case when we do not need to [v]fork is when the pipe
3723  * is single, non-backgrounded, non-subshell command. Examples:
3724  * cmd ; ...   { list } ; ...
3725  * cmd && ...  { list } && ...
3726  * cmd || ...  { list } || ...
3727  * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3728  * or (if SH_STANDALONE) an applet, and we can run the { list }
3729  * with run_list. If it isn't one of these, we fork and exec cmd.
3730  *
3731  * Cases when we must fork:
3732  * non-single:   cmd | cmd
3733  * backgrounded: cmd &     { list } &
3734  * subshell:     ( list ) [&]
3735  */
3736 static int run_pipe(struct pipe *pi)
3737 {
3738         static const char *const null_ptr = NULL;
3739         int i;
3740         int nextin;
3741         struct command *command;
3742         char **argv_expanded;
3743         char **argv;
3744         char *p;
3745         /* it is not always needed, but we aim to smaller code */
3746         int squirrel[] = { -1, -1, -1 };
3747         int rcode;
3748
3749         debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3750         debug_enter();
3751
3752         IF_HUSH_JOB(pi->pgrp = -1;)
3753         pi->stopped_cmds = 0;
3754         command = &(pi->cmds[0]);
3755         argv_expanded = NULL;
3756
3757         if (pi->num_cmds != 1
3758          || pi->followup == PIPE_BG
3759          || command->cmd_type == CMD_SUBSHELL
3760         ) {
3761                 goto must_fork;
3762         }
3763
3764         pi->alive_cmds = 1;
3765
3766         debug_printf_exec(": group:%p argv:'%s'\n",
3767                 command->group, command->argv ? command->argv[0] : "NONE");
3768
3769         if (command->group) {
3770 #if ENABLE_HUSH_FUNCTIONS
3771                 if (command->cmd_type == CMD_FUNCDEF) {
3772                         /* "executing" func () { list } */
3773                         struct function *funcp;
3774
3775                         funcp = new_function(command->argv[0]);
3776                         /* funcp->name is already set to argv[0] */
3777                         funcp->body = command->group;
3778 # if !BB_MMU
3779                         funcp->body_as_string = command->group_as_string;
3780                         command->group_as_string = NULL;
3781 # endif
3782                         command->group = NULL;
3783                         command->argv[0] = NULL;
3784                         debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3785                         funcp->parent_cmd = command;
3786                         command->child_func = funcp;
3787
3788                         debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3789                         debug_leave();
3790                         return EXIT_SUCCESS;
3791                 }
3792 #endif
3793                 /* { list } */
3794                 debug_printf("non-subshell group\n");
3795                 rcode = 1; /* exitcode if redir failed */
3796                 if (setup_redirects(command, squirrel) == 0) {
3797                         debug_printf_exec(": run_list\n");
3798                         rcode = run_list(command->group) & 0xff;
3799                 }
3800                 restore_redirects(squirrel);
3801                 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3802                 debug_leave();
3803                 debug_printf_exec("run_pipe: return %d\n", rcode);
3804                 return rcode;
3805         }
3806
3807         argv = command->argv ? command->argv : (char **) &null_ptr;
3808         {
3809                 const struct built_in_command *x;
3810 #if ENABLE_HUSH_FUNCTIONS
3811                 const struct function *funcp;
3812 #else
3813                 enum { funcp = 0 };
3814 #endif
3815                 char **new_env = NULL;
3816                 struct variable *old_vars = NULL;
3817
3818                 if (argv[command->assignment_cnt] == NULL) {
3819                         /* Assignments, but no command */
3820                         /* Ensure redirects take effect. Try "a=t >file" */
3821                         rcode = setup_redirects(command, squirrel);
3822                         restore_redirects(squirrel);
3823                         /* Set shell variables */
3824                         while (*argv) {
3825                                 p = expand_string_to_string(*argv);
3826                                 debug_printf_exec("set shell var:'%s'->'%s'\n",
3827                                                 *argv, p);
3828                                 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
3829                                 argv++;
3830                         }
3831                         /* Do we need to flag set_local_var() errors?
3832                          * "assignment to readonly var" and "putenv error"
3833                          */
3834                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3835                         debug_leave();
3836                         debug_printf_exec("run_pipe: return %d\n", rcode);
3837                         return rcode;
3838                 }
3839
3840                 /* Expand the rest into (possibly) many strings each */
3841                 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
3842                         argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3843                 }
3844 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3845                 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3846                         argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3847
3848                 }
3849 #endif
3850                 else {
3851                         argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3852                 }
3853
3854                 x = find_builtin(argv_expanded[0]);
3855 #if ENABLE_HUSH_FUNCTIONS
3856                 funcp = NULL;
3857                 if (!x)
3858                         funcp = find_function(argv_expanded[0]);
3859 #endif
3860                 if (x || funcp) {
3861                         if (!funcp) {
3862                                 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3863                                         debug_printf("exec with redirects only\n");
3864                                         rcode = setup_redirects(command, NULL);
3865                                         goto clean_up_and_ret1;
3866                                 }
3867                         }
3868                         /* setup_redirects acts on file descriptors, not FILEs.
3869                          * This is perfect for work that comes after exec().
3870                          * Is it really safe for inline use?  Experimentally,
3871                          * things seem to work. */
3872                         rcode = setup_redirects(command, squirrel);
3873                         if (rcode == 0) {
3874                                 new_env = expand_assignments(argv, command->assignment_cnt);
3875                                 old_vars = set_vars_and_save_old(new_env);
3876                                 if (!funcp) {
3877                                         debug_printf_exec(": builtin '%s' '%s'...\n",
3878                                                 x->cmd, argv_expanded[1]);
3879                                         rcode = x->function(argv_expanded) & 0xff;
3880                                         fflush(NULL);
3881                                 }
3882 #if ENABLE_HUSH_FUNCTIONS
3883                                 else {
3884 # if ENABLE_HUSH_LOCAL
3885                                         struct variable **sv;
3886                                         sv = G.shadowed_vars_pp;
3887                                         G.shadowed_vars_pp = &old_vars;
3888 # endif
3889                                         debug_printf_exec(": function '%s' '%s'...\n",
3890                                                 funcp->name, argv_expanded[1]);
3891                                         rcode = run_function(funcp, argv_expanded) & 0xff;
3892 # if ENABLE_HUSH_LOCAL
3893                                         G.shadowed_vars_pp = sv;
3894 # endif
3895                                 }
3896 #endif
3897                         }
3898 #if ENABLE_FEATURE_SH_STANDALONE
3899  clean_up_and_ret:
3900 #endif
3901                         restore_redirects(squirrel);
3902                         unset_vars(new_env);
3903                         add_vars(old_vars);
3904  clean_up_and_ret1:
3905                         free(argv_expanded);
3906                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3907                         debug_leave();
3908                         debug_printf_exec("run_pipe return %d\n", rcode);
3909                         return rcode;
3910                 }
3911
3912 #if ENABLE_FEATURE_SH_STANDALONE
3913                 i = find_applet_by_name(argv_expanded[0]);
3914                 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3915                         rcode = setup_redirects(command, squirrel);
3916                         if (rcode == 0) {
3917                                 new_env = expand_assignments(argv, command->assignment_cnt);
3918                                 old_vars = set_vars_and_save_old(new_env);
3919                                 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3920                                         argv_expanded[0], argv_expanded[1]);
3921                                 rcode = run_nofork_applet(i, argv_expanded);
3922                         }
3923                         goto clean_up_and_ret;
3924                 }
3925 #endif
3926                 /* It is neither builtin nor applet. We must fork. */
3927         }
3928
3929  must_fork:
3930         /* NB: argv_expanded may already be created, and that
3931          * might include `cmd` runs! Do not rerun it! We *must*
3932          * use argv_expanded if it's non-NULL */
3933
3934         /* Going to fork a child per each pipe member */
3935         pi->alive_cmds = 0;
3936         nextin = 0;
3937
3938         for (i = 0; i < pi->num_cmds; i++) {
3939                 struct fd_pair pipefds;
3940 #if !BB_MMU
3941                 volatile nommu_save_t nommu_save;
3942                 nommu_save.new_env = NULL;
3943                 nommu_save.old_vars = NULL;
3944                 nommu_save.argv = NULL;
3945                 nommu_save.argv_from_re_execing = NULL;
3946 #endif
3947                 command = &(pi->cmds[i]);
3948                 if (command->argv) {
3949                         debug_printf_exec(": pipe member '%s' '%s'...\n",
3950                                         command->argv[0], command->argv[1]);
3951                 } else {
3952                         debug_printf_exec(": pipe member with no argv\n");
3953                 }
3954
3955                 /* pipes are inserted between pairs of commands */
3956                 pipefds.rd = 0;
3957                 pipefds.wr = 1;
3958                 if ((i + 1) < pi->num_cmds)
3959                         xpiped_pair(pipefds);
3960
3961                 command->pid = BB_MMU ? fork() : vfork();
3962                 if (!command->pid) { /* child */
3963 #if ENABLE_HUSH_JOB
3964                         disable_restore_tty_pgrp_on_exit();
3965
3966                         /* Every child adds itself to new process group
3967                          * with pgid == pid_of_first_child_in_pipe */
3968                         if (G.run_list_level == 1 && G_interactive_fd) {
3969                                 pid_t pgrp;
3970                                 pgrp = pi->pgrp;
3971                                 if (pgrp < 0) /* true for 1st process only */
3972                                         pgrp = getpid();
3973                                 if (setpgid(0, pgrp) == 0
3974                                  && pi->followup != PIPE_BG
3975                                  && G_saved_tty_pgrp /* we have ctty */
3976                                 ) {
3977                                         /* We do it in *every* child, not just first,
3978                                          * to avoid races */
3979                                         tcsetpgrp(G_interactive_fd, pgrp);
3980                                 }
3981                         }
3982 #endif
3983                         if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3984                                 /* 1st cmd in backgrounded pipe
3985                                  * should have its stdin /dev/null'ed */
3986                                 close(0);
3987                                 if (open(bb_dev_null, O_RDONLY))
3988                                         xopen("/", O_RDONLY);
3989                         } else {
3990                                 xmove_fd(nextin, 0);
3991                         }
3992                         xmove_fd(pipefds.wr, 1);
3993                         if (pipefds.rd > 1)
3994                                 close(pipefds.rd);
3995                         /* Like bash, explicit redirects override pipes,
3996                          * and the pipe fd is available for dup'ing. */
3997                         if (setup_redirects(command, NULL))
3998                                 _exit(1);
3999
4000                         /* Restore default handlers just prior to exec */
4001                         /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4002
4003                         /* Stores to nommu_save list of env vars putenv'ed
4004                          * (NOMMU, on MMU we don't need that) */
4005                         /* cast away volatility... */
4006                         pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4007                         /* pseudo_exec() does not return */
4008                 }
4009
4010                 /* parent or error */
4011 #if ENABLE_HUSH_FAST
4012                 G.count_SIGCHLD++;
4013 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4014 #endif
4015                 enable_restore_tty_pgrp_on_exit();
4016 #if !BB_MMU
4017                 /* Clean up after vforked child */
4018                 free(nommu_save.argv);
4019                 free(nommu_save.argv_from_re_execing);
4020                 unset_vars(nommu_save.new_env);
4021                 add_vars(nommu_save.old_vars);
4022 #endif
4023                 free(argv_expanded);
4024                 argv_expanded = NULL;
4025                 if (command->pid < 0) { /* [v]fork failed */
4026                         /* Clearly indicate, was it fork or vfork */
4027                         bb_perror_msg(BB_MMU ? "fork" : "vfork");
4028                 } else {
4029                         pi->alive_cmds++;
4030 #if ENABLE_HUSH_JOB
4031                         /* Second and next children need to know pid of first one */
4032                         if (pi->pgrp < 0)
4033                                 pi->pgrp = command->pid;
4034 #endif
4035                 }
4036
4037                 if (i)
4038                         close(nextin);
4039                 if ((i + 1) < pi->num_cmds)
4040                         close(pipefds.wr);
4041                 /* Pass read (output) pipe end to next iteration */
4042                 nextin = pipefds.rd;
4043         }
4044
4045         if (!pi->alive_cmds) {
4046                 debug_leave();
4047                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4048                 return 1;
4049         }
4050
4051         debug_leave();
4052         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4053         return -1;
4054 }
4055
4056 #ifndef debug_print_tree
4057 static void debug_print_tree(struct pipe *pi, int lvl)
4058 {
4059         static const char *const PIPE[] = {
4060                 [PIPE_SEQ] = "SEQ",
4061                 [PIPE_AND] = "AND",
4062                 [PIPE_OR ] = "OR" ,
4063                 [PIPE_BG ] = "BG" ,
4064         };
4065         static const char *RES[] = {
4066                 [RES_NONE ] = "NONE" ,
4067 #if ENABLE_HUSH_IF
4068                 [RES_IF   ] = "IF"   ,
4069                 [RES_THEN ] = "THEN" ,
4070                 [RES_ELIF ] = "ELIF" ,
4071                 [RES_ELSE ] = "ELSE" ,
4072                 [RES_FI   ] = "FI"   ,
4073 #endif
4074 #if ENABLE_HUSH_LOOPS
4075                 [RES_FOR  ] = "FOR"  ,
4076                 [RES_WHILE] = "WHILE",
4077                 [RES_UNTIL] = "UNTIL",
4078                 [RES_DO   ] = "DO"   ,
4079                 [RES_DONE ] = "DONE" ,
4080 #endif
4081 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4082                 [RES_IN   ] = "IN"   ,
4083 #endif
4084 #if ENABLE_HUSH_CASE
4085                 [RES_CASE ] = "CASE" ,
4086                 [RES_CASE_IN ] = "CASE_IN" ,
4087                 [RES_MATCH] = "MATCH",
4088                 [RES_CASE_BODY] = "CASE_BODY",
4089                 [RES_ESAC ] = "ESAC" ,
4090 #endif
4091                 [RES_XXXX ] = "XXXX" ,
4092                 [RES_SNTX ] = "SNTX" ,
4093         };
4094         static const char *const CMDTYPE[] = {
4095                 "{}",
4096                 "()",
4097 #if ENABLE_HUSH_FUNCTIONS
4098                 "func()",
4099 #endif
4100         };
4101
4102         int pin, prn;
4103
4104         pin = 0;
4105         while (pi) {
4106                 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4107                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4108                 prn = 0;
4109                 while (prn < pi->num_cmds) {
4110                         struct command *command = &pi->cmds[prn];
4111                         char **argv = command->argv;
4112
4113                         fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4114                                         lvl*2, "", prn,
4115                                         command->assignment_cnt);
4116                         if (command->group) {
4117                                 fprintf(stderr, " group %s: (argv=%p)\n",
4118                                                 CMDTYPE[command->cmd_type],
4119                                                 argv);
4120                                 debug_print_tree(command->group, lvl+1);
4121                                 prn++;
4122                                 continue;
4123                         }
4124                         if (argv) while (*argv) {
4125                                 fprintf(stderr, " '%s'", *argv);
4126                                 argv++;
4127                         }
4128                         fprintf(stderr, "\n");
4129                         prn++;
4130                 }
4131                 pi = pi->next;
4132                 pin++;
4133         }
4134 }
4135 #endif
4136
4137 /* NB: called by pseudo_exec, and therefore must not modify any
4138  * global data until exec/_exit (we can be a child after vfork!) */
4139 static int run_list(struct pipe *pi)
4140 {
4141 #if ENABLE_HUSH_CASE
4142         char *case_word = NULL;
4143 #endif
4144 #if ENABLE_HUSH_LOOPS
4145         struct pipe *loop_top = NULL;
4146         char **for_lcur = NULL;
4147         char **for_list = NULL;
4148 #endif
4149         smallint last_followup;
4150         smalluint rcode;
4151 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4152         smalluint cond_code = 0;
4153 #else
4154         enum { cond_code = 0 };
4155 #endif
4156 #if HAS_KEYWORDS
4157         smallint rword; /* enum reserved_style */
4158         smallint last_rword; /* ditto */
4159 #endif
4160
4161         debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4162         debug_enter();
4163
4164 #if ENABLE_HUSH_LOOPS
4165         /* Check syntax for "for" */
4166         for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4167                 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4168                         continue;
4169                 /* current word is FOR or IN (BOLD in comments below) */
4170                 if (cpipe->next == NULL) {
4171                         syntax_error("malformed for");
4172                         debug_leave();
4173                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4174                         return 1;
4175                 }
4176                 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4177                 if (cpipe->next->res_word == RES_DO)
4178                         continue;
4179                 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4180                 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4181                  || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4182                 ) {
4183                         syntax_error("malformed for");
4184                         debug_leave();
4185                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4186                         return 1;
4187                 }
4188         }
4189 #endif
4190
4191         /* Past this point, all code paths should jump to ret: label
4192          * in order to return, no direct "return" statements please.
4193          * This helps to ensure that no memory is leaked. */
4194
4195 #if ENABLE_HUSH_JOB
4196         G.run_list_level++;
4197 #endif
4198
4199 #if HAS_KEYWORDS
4200         rword = RES_NONE;
4201         last_rword = RES_XXXX;
4202 #endif
4203         last_followup = PIPE_SEQ;
4204         rcode = G.last_exitcode;
4205
4206         /* Go through list of pipes, (maybe) executing them. */
4207         for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4208                 if (G.flag_SIGINT)
4209                         break;
4210
4211                 IF_HAS_KEYWORDS(rword = pi->res_word;)
4212                 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4213                                 rword, cond_code, last_rword);
4214 #if ENABLE_HUSH_LOOPS
4215                 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4216                  && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4217                 ) {
4218                         /* start of a loop: remember where loop starts */
4219                         loop_top = pi;
4220                         G.depth_of_loop++;
4221                 }
4222 #endif
4223                 /* Still in the same "if...", "then..." or "do..." branch? */
4224                 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4225                         if ((rcode == 0 && last_followup == PIPE_OR)
4226                          || (rcode != 0 && last_followup == PIPE_AND)
4227                         ) {
4228                                 /* It is "<true> || CMD" or "<false> && CMD"
4229                                  * and we should not execute CMD */
4230                                 debug_printf_exec("skipped cmd because of || or &&\n");
4231                                 last_followup = pi->followup;
4232                                 continue;
4233                         }
4234                 }
4235                 last_followup = pi->followup;
4236                 IF_HAS_KEYWORDS(last_rword = rword;)
4237 #if ENABLE_HUSH_IF
4238                 if (cond_code) {
4239                         if (rword == RES_THEN) {
4240                                 /* if false; then ... fi has exitcode 0! */
4241                                 G.last_exitcode = rcode = EXIT_SUCCESS;
4242                                 /* "if <false> THEN cmd": skip cmd */
4243                                 continue;
4244                         }
4245                 } else {
4246                         if (rword == RES_ELSE || rword == RES_ELIF) {
4247                                 /* "if <true> then ... ELSE/ELIF cmd":
4248                                  * skip cmd and all following ones */
4249                                 break;
4250                         }
4251                 }
4252 #endif
4253 #if ENABLE_HUSH_LOOPS
4254                 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4255                         if (!for_lcur) {
4256                                 /* first loop through for */
4257
4258                                 static const char encoded_dollar_at[] ALIGN1 = {
4259                                         SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4260                                 }; /* encoded representation of "$@" */
4261                                 static const char *const encoded_dollar_at_argv[] = {
4262                                         encoded_dollar_at, NULL
4263                                 }; /* argv list with one element: "$@" */
4264                                 char **vals;
4265
4266                                 vals = (char**)encoded_dollar_at_argv;
4267                                 if (pi->next->res_word == RES_IN) {
4268                                         /* if no variable values after "in" we skip "for" */
4269                                         if (!pi->next->cmds[0].argv) {
4270                                                 G.last_exitcode = rcode = EXIT_SUCCESS;
4271                                                 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4272                                                 break;
4273                                         }
4274                                         vals = pi->next->cmds[0].argv;
4275                                 } /* else: "for var; do..." -> assume "$@" list */
4276                                 /* create list of variable values */
4277                                 debug_print_strings("for_list made from", vals);
4278                                 for_list = expand_strvec_to_strvec(vals);
4279                                 for_lcur = for_list;
4280                                 debug_print_strings("for_list", for_list);
4281                         }
4282                         if (!*for_lcur) {
4283                                 /* "for" loop is over, clean up */
4284                                 free(for_list);
4285                                 for_list = NULL;
4286                                 for_lcur = NULL;
4287                                 break;
4288                         }
4289                         /* Insert next value from for_lcur */
4290                         /* note: *for_lcur already has quotes removed, $var expanded, etc */
4291                         set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4292                         continue;
4293                 }
4294                 if (rword == RES_IN) {
4295                         continue; /* "for v IN list;..." - "in" has no cmds anyway */
4296                 }
4297                 if (rword == RES_DONE) {
4298                         continue; /* "done" has no cmds too */
4299                 }
4300 #endif
4301 #if ENABLE_HUSH_CASE
4302                 if (rword == RES_CASE) {
4303                         case_word = expand_strvec_to_string(pi->cmds->argv);
4304                         continue;
4305                 }
4306                 if (rword == RES_MATCH) {
4307                         char **argv;
4308
4309                         if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4310                                 break;
4311                         /* all prev words didn't match, does this one match? */
4312                         argv = pi->cmds->argv;
4313                         while (*argv) {
4314                                 char *pattern = expand_string_to_string(*argv);
4315                                 /* TODO: which FNM_xxx flags to use? */
4316                                 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4317                                 free(pattern);
4318                                 if (cond_code == 0) { /* match! we will execute this branch */
4319                                         free(case_word); /* make future "word)" stop */
4320                                         case_word = NULL;
4321                                         break;
4322                                 }
4323                                 argv++;
4324                         }
4325                         continue;
4326                 }
4327                 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4328                         if (cond_code != 0)
4329                                 continue; /* not matched yet, skip this pipe */
4330                 }
4331 #endif
4332                 /* Just pressing <enter> in shell should check for jobs.
4333                  * OTOH, in non-interactive shell this is useless
4334                  * and only leads to extra job checks */
4335                 if (pi->num_cmds == 0) {
4336                         if (G_interactive_fd)
4337                                 goto check_jobs_and_continue;
4338                         continue;
4339                 }
4340
4341                 /* After analyzing all keywords and conditions, we decided
4342                  * to execute this pipe. NB: have to do checkjobs(NULL)
4343                  * after run_pipe to collect any background children,
4344                  * even if list execution is to be stopped. */
4345                 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4346                 {
4347                         int r;
4348 #if ENABLE_HUSH_LOOPS
4349                         G.flag_break_continue = 0;
4350 #endif
4351                         rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4352                         if (r != -1) {
4353                                 /* We ran a builtin, function, or group.
4354                                  * rcode is already known
4355                                  * and we don't need to wait for anything. */
4356                                 G.last_exitcode = rcode;
4357                                 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4358                                 check_and_run_traps(0);
4359 #if ENABLE_HUSH_LOOPS
4360                                 /* Was it "break" or "continue"? */
4361                                 if (G.flag_break_continue) {
4362                                         smallint fbc = G.flag_break_continue;
4363                                         /* We might fall into outer *loop*,
4364                                          * don't want to break it too */
4365                                         if (loop_top) {
4366                                                 G.depth_break_continue--;
4367                                                 if (G.depth_break_continue == 0)
4368                                                         G.flag_break_continue = 0;
4369                                                 /* else: e.g. "continue 2" should *break* once, *then* continue */
4370                                         } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4371                                         if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4372                                                 goto check_jobs_and_break;
4373                                         /* "continue": simulate end of loop */
4374                                         rword = RES_DONE;
4375                                         continue;
4376                                 }
4377 #endif
4378 #if ENABLE_HUSH_FUNCTIONS
4379                                 if (G.flag_return_in_progress == 1) {
4380                                         /* same as "goto check_jobs_and_break" */
4381                                         checkjobs(NULL);
4382                                         break;
4383                                 }
4384 #endif
4385                         } else if (pi->followup == PIPE_BG) {
4386                                 /* What does bash do with attempts to background builtins? */
4387                                 /* even bash 3.2 doesn't do that well with nested bg:
4388                                  * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4389                                  * I'm NOT treating inner &'s as jobs */
4390                                 check_and_run_traps(0);
4391 #if ENABLE_HUSH_JOB
4392                                 if (G.run_list_level == 1)
4393                                         insert_bg_job(pi);
4394 #endif
4395                                 G.last_exitcode = rcode = EXIT_SUCCESS;
4396                                 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
4397                         } else {
4398 #if ENABLE_HUSH_JOB
4399                                 if (G.run_list_level == 1 && G_interactive_fd) {
4400                                         /* Waits for completion, then fg's main shell */
4401                                         rcode = checkjobs_and_fg_shell(pi);
4402                                         debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
4403                                         check_and_run_traps(0);
4404                                 } else
4405 #endif
4406                                 { /* This one just waits for completion */
4407                                         rcode = checkjobs(pi);
4408                                         debug_printf_exec(": checkjobs exitcode %d\n", rcode);
4409                                         check_and_run_traps(0);
4410                                 }
4411                                 G.last_exitcode = rcode;
4412                         }
4413                 }
4414
4415                 /* Analyze how result affects subsequent commands */
4416 #if ENABLE_HUSH_IF
4417                 if (rword == RES_IF || rword == RES_ELIF)
4418                         cond_code = rcode;
4419 #endif
4420 #if ENABLE_HUSH_LOOPS
4421                 /* Beware of "while false; true; do ..."! */
4422                 if (pi->next && pi->next->res_word == RES_DO) {
4423                         if (rword == RES_WHILE) {
4424                                 if (rcode) {
4425                                         /* "while false; do...done" - exitcode 0 */
4426                                         G.last_exitcode = rcode = EXIT_SUCCESS;
4427                                         debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4428                                         goto check_jobs_and_break;
4429                                 }
4430                         }
4431                         if (rword == RES_UNTIL) {
4432                                 if (!rcode) {
4433                                         debug_printf_exec(": until expr is true: breaking\n");
4434  check_jobs_and_break:
4435                                         checkjobs(NULL);
4436                                         break;
4437                                 }
4438                         }
4439                 }
4440 #endif
4441
4442  check_jobs_and_continue:
4443                 checkjobs(NULL);
4444         } /* for (pi) */
4445
4446 #if ENABLE_HUSH_JOB
4447         G.run_list_level--;
4448 #endif
4449 #if ENABLE_HUSH_LOOPS
4450         if (loop_top)
4451                 G.depth_of_loop--;
4452         free(for_list);
4453 #endif
4454 #if ENABLE_HUSH_CASE
4455         free(case_word);
4456 #endif
4457         debug_leave();
4458         debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
4459         return rcode;
4460 }
4461
4462 /* Select which version we will use */
4463 static int run_and_free_list(struct pipe *pi)
4464 {
4465         int rcode = 0;
4466         debug_printf_exec("run_and_free_list entered\n");
4467         if (!G.fake_mode) {
4468                 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
4469                 rcode = run_list(pi);
4470         }
4471         /* free_pipe_list has the side effect of clearing memory.
4472          * In the long run that function can be merged with run_list,
4473          * but doing that now would hobble the debugging effort. */
4474         free_pipe_list(pi);
4475         debug_printf_exec("run_and_free_list return %d\n", rcode);
4476         return rcode;
4477 }
4478
4479
4480 static struct pipe *new_pipe(void)
4481 {
4482         struct pipe *pi;
4483         pi = xzalloc(sizeof(struct pipe));
4484         /*pi->followup = 0; - deliberately invalid value */
4485         /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
4486         return pi;
4487 }
4488
4489 /* Command (member of a pipe) is complete, or we start a new pipe
4490  * if ctx->command is NULL.
4491  * No errors possible here.
4492  */
4493 static int done_command(struct parse_context *ctx)
4494 {
4495         /* The command is really already in the pipe structure, so
4496          * advance the pipe counter and make a new, null command. */
4497         struct pipe *pi = ctx->pipe;
4498         struct command *command = ctx->command;
4499
4500         if (command) {
4501                 if (IS_NULL_CMD(command)) {
4502                         debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
4503                         goto clear_and_ret;
4504                 }
4505                 pi->num_cmds++;
4506                 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
4507                 //debug_print_tree(ctx->list_head, 20);
4508         } else {
4509                 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4510         }
4511
4512         /* Only real trickiness here is that the uncommitted
4513          * command structure is not counted in pi->num_cmds. */
4514         pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4515         ctx->command = command = &pi->cmds[pi->num_cmds];
4516  clear_and_ret:
4517         memset(command, 0, sizeof(*command));
4518         return pi->num_cmds; /* used only for 0/nonzero check */
4519 }
4520
4521 static void done_pipe(struct parse_context *ctx, pipe_style type)
4522 {
4523         int not_null;
4524
4525         debug_printf_parse("done_pipe entered, followup %d\n", type);
4526         /* Close previous command */
4527         not_null = done_command(ctx);
4528         ctx->pipe->followup = type;
4529 #if HAS_KEYWORDS
4530         ctx->pipe->pi_inverted = ctx->ctx_inverted;
4531         ctx->ctx_inverted = 0;
4532         ctx->pipe->res_word = ctx->ctx_res_w;
4533 #endif
4534
4535         /* Without this check, even just <enter> on command line generates
4536          * tree of three NOPs (!). Which is harmless but annoying.
4537          * IOW: it is safe to do it unconditionally. */
4538         if (not_null
4539 #if ENABLE_HUSH_IF
4540          || ctx->ctx_res_w == RES_FI
4541 #endif
4542 #if ENABLE_HUSH_LOOPS
4543          || ctx->ctx_res_w == RES_DONE
4544          || ctx->ctx_res_w == RES_FOR
4545          || ctx->ctx_res_w == RES_IN
4546 #endif
4547 #if ENABLE_HUSH_CASE
4548          || ctx->ctx_res_w == RES_ESAC
4549 #endif
4550         ) {
4551                 struct pipe *new_p;
4552                 debug_printf_parse("done_pipe: adding new pipe: "
4553                                 "not_null:%d ctx->ctx_res_w:%d\n",
4554                                 not_null, ctx->ctx_res_w);
4555                 new_p = new_pipe();
4556                 ctx->pipe->next = new_p;
4557                 ctx->pipe = new_p;
4558                 /* RES_THEN, RES_DO etc are "sticky" -
4559                  * they remain set for pipes inside if/while.
4560                  * This is used to control execution.
4561                  * RES_FOR and RES_IN are NOT sticky (needed to support
4562                  * cases where variable or value happens to match a keyword):
4563                  */
4564 #if ENABLE_HUSH_LOOPS
4565                 if (ctx->ctx_res_w == RES_FOR
4566                  || ctx->ctx_res_w == RES_IN)
4567                         ctx->ctx_res_w = RES_NONE;
4568 #endif
4569 #if ENABLE_HUSH_CASE
4570                 if (ctx->ctx_res_w == RES_MATCH)
4571                         ctx->ctx_res_w = RES_CASE_BODY;
4572                 if (ctx->ctx_res_w == RES_CASE)
4573                         ctx->ctx_res_w = RES_CASE_IN;
4574 #endif
4575                 ctx->command = NULL; /* trick done_command below */
4576                 /* Create the memory for command, roughly:
4577                  * ctx->pipe->cmds = new struct command;
4578                  * ctx->command = &ctx->pipe->cmds[0];
4579                  */
4580                 done_command(ctx);
4581                 //debug_print_tree(ctx->list_head, 10);
4582         }
4583         debug_printf_parse("done_pipe return\n");
4584 }
4585
4586 static void initialize_context(struct parse_context *ctx)
4587 {
4588         memset(ctx, 0, sizeof(*ctx));
4589         ctx->pipe = ctx->list_head = new_pipe();
4590         /* Create the memory for command, roughly:
4591          * ctx->pipe->cmds = new struct command;
4592          * ctx->command = &ctx->pipe->cmds[0];
4593          */
4594         done_command(ctx);
4595 }
4596
4597 /* If a reserved word is found and processed, parse context is modified
4598  * and 1 is returned.
4599  */
4600 #if HAS_KEYWORDS
4601 struct reserved_combo {
4602         char literal[6];
4603         unsigned char res;
4604         unsigned char assignment_flag;
4605         int flag;
4606 };
4607 enum {
4608         FLAG_END   = (1 << RES_NONE ),
4609 #if ENABLE_HUSH_IF
4610         FLAG_IF    = (1 << RES_IF   ),
4611         FLAG_THEN  = (1 << RES_THEN ),
4612         FLAG_ELIF  = (1 << RES_ELIF ),
4613         FLAG_ELSE  = (1 << RES_ELSE ),
4614         FLAG_FI    = (1 << RES_FI   ),
4615 #endif
4616 #if ENABLE_HUSH_LOOPS
4617         FLAG_FOR   = (1 << RES_FOR  ),
4618         FLAG_WHILE = (1 << RES_WHILE),
4619         FLAG_UNTIL = (1 << RES_UNTIL),
4620         FLAG_DO    = (1 << RES_DO   ),
4621         FLAG_DONE  = (1 << RES_DONE ),
4622         FLAG_IN    = (1 << RES_IN   ),
4623 #endif
4624 #if ENABLE_HUSH_CASE
4625         FLAG_MATCH = (1 << RES_MATCH),
4626         FLAG_ESAC  = (1 << RES_ESAC ),
4627 #endif
4628         FLAG_START = (1 << RES_XXXX ),
4629 };
4630
4631 static const struct reserved_combo* match_reserved_word(o_string *word)
4632 {
4633         /* Mostly a list of accepted follow-up reserved words.
4634          * FLAG_END means we are done with the sequence, and are ready
4635          * to turn the compound list into a command.
4636          * FLAG_START means the word must start a new compound list.
4637          */
4638         static const struct reserved_combo reserved_list[] = {
4639 #if ENABLE_HUSH_IF
4640                 { "!",     RES_NONE,  NOT_ASSIGNMENT , 0 },
4641                 { "if",    RES_IF,    WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4642                 { "then",  RES_THEN,  WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4643                 { "elif",  RES_ELIF,  WORD_IS_KEYWORD, FLAG_THEN },
4644                 { "else",  RES_ELSE,  WORD_IS_KEYWORD, FLAG_FI   },
4645                 { "fi",    RES_FI,    NOT_ASSIGNMENT , FLAG_END  },
4646 #endif
4647 #if ENABLE_HUSH_LOOPS
4648                 { "for",   RES_FOR,   NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4649                 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4650                 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4651                 { "in",    RES_IN,    NOT_ASSIGNMENT , FLAG_DO   },
4652                 { "do",    RES_DO,    WORD_IS_KEYWORD, FLAG_DONE },
4653                 { "done",  RES_DONE,  NOT_ASSIGNMENT , FLAG_END  },
4654 #endif
4655 #if ENABLE_HUSH_CASE
4656                 { "case",  RES_CASE,  NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4657                 { "esac",  RES_ESAC,  NOT_ASSIGNMENT , FLAG_END  },
4658 #endif
4659         };
4660         const struct reserved_combo *r;
4661
4662         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4663                 if (strcmp(word->data, r->literal) == 0)
4664                         return r;
4665         }
4666         return NULL;
4667 }
4668 /* Return 0: not a keyword, 1: keyword
4669  */
4670 static int reserved_word(o_string *word, struct parse_context *ctx)
4671 {
4672 #if ENABLE_HUSH_CASE
4673         static const struct reserved_combo reserved_match = {
4674                 "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4675         };
4676 #endif
4677         const struct reserved_combo *r;
4678
4679         if (word->o_quoted)
4680                 return 0;
4681         r = match_reserved_word(word);
4682         if (!r)
4683                 return 0;
4684
4685         debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4686 #if ENABLE_HUSH_CASE
4687         if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4688                 /* "case word IN ..." - IN part starts first MATCH part */
4689                 r = &reserved_match;
4690         } else
4691 #endif
4692         if (r->flag == 0) { /* '!' */
4693                 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4694                         syntax_error("! ! command");
4695                         ctx->ctx_res_w = RES_SNTX;
4696                 }
4697                 ctx->ctx_inverted = 1;
4698                 return 1;
4699         }
4700         if (r->flag & FLAG_START) {
4701                 struct parse_context *old;
4702
4703                 old = xmalloc(sizeof(*old));
4704                 debug_printf_parse("push stack %p\n", old);
4705                 *old = *ctx;   /* physical copy */
4706                 initialize_context(ctx);
4707                 ctx->stack = old;
4708         } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4709                 syntax_error_at(word->data);
4710                 ctx->ctx_res_w = RES_SNTX;
4711                 return 1;
4712         } else {
4713                 /* "{...} fi" is ok. "{...} if" is not
4714                  * Example:
4715                  * if { echo foo; } then { echo bar; } fi */
4716                 if (ctx->command->group)
4717                         done_pipe(ctx, PIPE_SEQ);
4718         }
4719
4720         ctx->ctx_res_w = r->res;
4721         ctx->old_flag = r->flag;
4722         word->o_assignment = r->assignment_flag;
4723
4724         if (ctx->old_flag & FLAG_END) {
4725                 struct parse_context *old;
4726
4727                 done_pipe(ctx, PIPE_SEQ);
4728                 debug_printf_parse("pop stack %p\n", ctx->stack);
4729                 old = ctx->stack;
4730                 old->command->group = ctx->list_head;
4731                 old->command->cmd_type = CMD_NORMAL;
4732 #if !BB_MMU
4733                 o_addstr(&old->as_string, ctx->as_string.data);
4734                 o_free_unsafe(&ctx->as_string);
4735                 old->command->group_as_string = xstrdup(old->as_string.data);
4736                 debug_printf_parse("pop, remembering as:'%s'\n",
4737                                 old->command->group_as_string);
4738 #endif
4739                 *ctx = *old;   /* physical copy */
4740                 free(old);
4741         }
4742         return 1;
4743 }
4744 #endif
4745
4746 /* Word is complete, look at it and update parsing context.
4747  * Normal return is 0. Syntax errors return 1.
4748  * Note: on return, word is reset, but not o_free'd!
4749  */
4750 static int done_word(o_string *word, struct parse_context *ctx)
4751 {
4752         struct command *command = ctx->command;
4753
4754         debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4755         if (word->length == 0 && word->o_quoted == 0) {
4756                 debug_printf_parse("done_word return 0: true null, ignored\n");
4757                 return 0;
4758         }
4759
4760         if (ctx->pending_redirect) {
4761                 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4762                  * only if run as "bash", not "sh" */
4763                 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4764                  * "2.7 Redirection
4765                  * ...the word that follows the redirection operator
4766                  * shall be subjected to tilde expansion, parameter expansion,
4767                  * command substitution, arithmetic expansion, and quote
4768                  * removal. Pathname expansion shall not be performed
4769                  * on the word by a non-interactive shell; an interactive
4770                  * shell may perform it, but shall do so only when
4771                  * the expansion would result in one word."
4772                  */
4773                 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4774                 /* Cater for >\file case:
4775                  * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4776                  * Same with heredocs:
4777                  * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4778                  */
4779                 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4780                         unbackslash(ctx->pending_redirect->rd_filename);
4781                         /* Is it <<"HEREDOC"? */
4782                         if (word->o_quoted) {
4783                                 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4784                         }
4785                 }
4786                 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4787                 ctx->pending_redirect = NULL;
4788         } else {
4789                 /* If this word wasn't an assignment, next ones definitely
4790                  * can't be assignments. Even if they look like ones. */
4791                 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4792                  && word->o_assignment != WORD_IS_KEYWORD
4793                 ) {
4794                         word->o_assignment = NOT_ASSIGNMENT;
4795                 } else {
4796                         if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4797                                 command->assignment_cnt++;
4798                         word->o_assignment = MAYBE_ASSIGNMENT;
4799                 }
4800
4801 #if HAS_KEYWORDS
4802 # if ENABLE_HUSH_CASE
4803                 if (ctx->ctx_dsemicolon
4804                  && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4805                 ) {
4806                         /* already done when ctx_dsemicolon was set to 1: */
4807                         /* ctx->ctx_res_w = RES_MATCH; */
4808                         ctx->ctx_dsemicolon = 0;
4809                 } else
4810 # endif
4811                 if (!command->argv /* if it's the first word... */
4812 # if ENABLE_HUSH_LOOPS
4813                  && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4814                  && ctx->ctx_res_w != RES_IN
4815 # endif
4816 # if ENABLE_HUSH_CASE
4817                  && ctx->ctx_res_w != RES_CASE
4818 # endif
4819                 ) {
4820                         debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
4821                         if (reserved_word(word, ctx)) {
4822                                 o_reset_to_empty_unquoted(word);
4823                                 debug_printf_parse("done_word return %d\n",
4824                                                 (ctx->ctx_res_w == RES_SNTX));
4825                                 return (ctx->ctx_res_w == RES_SNTX);
4826                         }
4827 # ifdef CMD_SINGLEWORD_NOGLOB_COND
4828                         if (strcmp(word->data, "export") == 0
4829 #  if ENABLE_HUSH_LOCAL
4830                          || strcmp(word->data, "local") == 0
4831 #  endif
4832                         ) {
4833                                 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4834                         } else
4835 # endif
4836                         if (strcmp(word->data, "[[") == 0) {
4837                                 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4838                         }
4839                         /* fall through */
4840                 }
4841 #endif
4842                 if (command->group) {
4843                         /* "{ echo foo; } echo bar" - bad */
4844                         syntax_error_at(word->data);
4845                         debug_printf_parse("done_word return 1: syntax error, "
4846                                         "groups and arglists don't mix\n");
4847                         return 1;
4848                 }
4849                 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4850                  /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4851                  && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4852                  /* (otherwise it's known to be not empty and is already safe) */
4853                 ) {
4854                         /* exclude "$@" - it can expand to no word despite "" */
4855                         char *p = word->data;
4856                         while (p[0] == SPECIAL_VAR_SYMBOL
4857                             && (p[1] & 0x7f) == '@'
4858                             && p[2] == SPECIAL_VAR_SYMBOL
4859                         ) {
4860                                 p += 3;
4861                         }
4862                         if (p == word->data || p[0] != '\0') {
4863                                 /* saw no "$@", or not only "$@" but some
4864                                  * real text is there too */
4865                                 /* insert "empty variable" reference, this makes
4866                                  * e.g. "", $empty"" etc to not disappear */
4867                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
4868                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
4869                         }
4870                 }
4871                 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4872                 debug_print_strings("word appended to argv", command->argv);
4873         }
4874
4875 #if ENABLE_HUSH_LOOPS
4876         if (ctx->ctx_res_w == RES_FOR) {
4877                 if (word->o_quoted
4878                  || !is_well_formed_var_name(command->argv[0], '\0')
4879                 ) {
4880                         /* bash says just "not a valid identifier" */
4881                         syntax_error("not a valid identifier in for");
4882                         return 1;
4883                 }
4884                 /* Force FOR to have just one word (variable name) */
4885                 /* NB: basically, this makes hush see "for v in ..."
4886                  * syntax as if it is "for v; in ...". FOR and IN become
4887                  * two pipe structs in parse tree. */
4888                 done_pipe(ctx, PIPE_SEQ);
4889         }
4890 #endif
4891 #if ENABLE_HUSH_CASE
4892         /* Force CASE to have just one word */
4893         if (ctx->ctx_res_w == RES_CASE) {
4894                 done_pipe(ctx, PIPE_SEQ);
4895         }
4896 #endif
4897
4898         o_reset_to_empty_unquoted(word);
4899
4900         debug_printf_parse("done_word return 0\n");
4901         return 0;
4902 }
4903
4904
4905 /* Peek ahead in the input to find out if we have a "&n" construct,
4906  * as in "2>&1", that represents duplicating a file descriptor.
4907  * Return:
4908  * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4909  * REDIRFD_SYNTAX_ERR if syntax error,
4910  * REDIRFD_TO_FILE if no & was seen,
4911  * or the number found.
4912  */
4913 #if BB_MMU
4914 #define parse_redir_right_fd(as_string, input) \
4915         parse_redir_right_fd(input)
4916 #endif
4917 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4918 {
4919         int ch, d, ok;
4920
4921         ch = i_peek(input);
4922         if (ch != '&')
4923                 return REDIRFD_TO_FILE;
4924
4925         ch = i_getch(input);  /* get the & */
4926         nommu_addchr(as_string, ch);
4927         ch = i_peek(input);
4928         if (ch == '-') {
4929                 ch = i_getch(input);
4930                 nommu_addchr(as_string, ch);
4931                 return REDIRFD_CLOSE;
4932         }
4933         d = 0;
4934         ok = 0;
4935         while (ch != EOF && isdigit(ch)) {
4936                 d = d*10 + (ch-'0');
4937                 ok = 1;
4938                 ch = i_getch(input);
4939                 nommu_addchr(as_string, ch);
4940                 ch = i_peek(input);
4941         }
4942         if (ok) return d;
4943
4944 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4945
4946         bb_error_msg("ambiguous redirect");
4947         return REDIRFD_SYNTAX_ERR;
4948 }
4949
4950 /* Return code is 0 normal, 1 if a syntax error is detected
4951  */
4952 static int parse_redirect(struct parse_context *ctx,
4953                 int fd,
4954                 redir_type style,
4955                 struct in_str *input)
4956 {
4957         struct command *command = ctx->command;
4958         struct redir_struct *redir;
4959         struct redir_struct **redirp;
4960         int dup_num;
4961
4962         dup_num = REDIRFD_TO_FILE;
4963         if (style != REDIRECT_HEREDOC) {
4964                 /* Check for a '>&1' type redirect */
4965                 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4966                 if (dup_num == REDIRFD_SYNTAX_ERR)
4967                         return 1;
4968         } else {
4969                 int ch = i_peek(input);
4970                 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4971                 if (dup_num) { /* <<-... */
4972                         ch = i_getch(input);
4973                         nommu_addchr(&ctx->as_string, ch);
4974                         ch = i_peek(input);
4975                 }
4976         }
4977
4978         if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4979                 int ch = i_peek(input);
4980                 if (ch == '|') {
4981                         /* >|FILE redirect ("clobbering" >).
4982                          * Since we do not support "set -o noclobber" yet,
4983                          * >| and > are the same for now. Just eat |.
4984                          */
4985                         ch = i_getch(input);
4986                         nommu_addchr(&ctx->as_string, ch);
4987                 }
4988         }
4989
4990         /* Create a new redir_struct and append it to the linked list */
4991         redirp = &command->redirects;
4992         while ((redir = *redirp) != NULL) {
4993                 redirp = &(redir->next);
4994         }
4995         *redirp = redir = xzalloc(sizeof(*redir));
4996         /* redir->next = NULL; */
4997         /* redir->rd_filename = NULL; */
4998         redir->rd_type = style;
4999         redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5000
5001         debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5002                                 redir_table[style].descrip);
5003
5004         redir->rd_dup = dup_num;
5005         if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5006                 /* Erik had a check here that the file descriptor in question
5007                  * is legit; I postpone that to "run time"
5008                  * A "-" representation of "close me" shows up as a -3 here */
5009                 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5010                                 redir->rd_fd, redir->rd_dup);
5011         } else {
5012                 /* Set ctx->pending_redirect, so we know what to do at the
5013                  * end of the next parsed word. */
5014                 ctx->pending_redirect = redir;
5015         }
5016         return 0;
5017 }
5018
5019 /* If a redirect is immediately preceded by a number, that number is
5020  * supposed to tell which file descriptor to redirect.  This routine
5021  * looks for such preceding numbers.  In an ideal world this routine
5022  * needs to handle all the following classes of redirects...
5023  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
5024  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
5025  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
5026  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
5027  *
5028  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5029  * "2.7 Redirection
5030  * ... If n is quoted, the number shall not be recognized as part of
5031  * the redirection expression. For example:
5032  * echo \2>a
5033  * writes the character 2 into file a"
5034  * We are getting it right by setting ->o_quoted on any \<char>
5035  *
5036  * A -1 return means no valid number was found,
5037  * the caller should use the appropriate default for this redirection.
5038  */
5039 static int redirect_opt_num(o_string *o)
5040 {
5041         int num;
5042
5043         if (o->data == NULL)
5044                 return -1;
5045         num = bb_strtou(o->data, NULL, 10);
5046         if (errno || num < 0)
5047                 return -1;
5048         o_reset_to_empty_unquoted(o);
5049         return num;
5050 }
5051
5052 #if BB_MMU
5053 #define fetch_till_str(as_string, input, word, skip_tabs) \
5054         fetch_till_str(input, word, skip_tabs)
5055 #endif
5056 static char *fetch_till_str(o_string *as_string,
5057                 struct in_str *input,
5058                 const char *word,
5059                 int skip_tabs)
5060 {
5061         o_string heredoc = NULL_O_STRING;
5062         int past_EOL = 0;
5063         int ch;
5064
5065         goto jump_in;
5066         while (1) {
5067                 ch = i_getch(input);
5068                 nommu_addchr(as_string, ch);
5069                 if (ch == '\n') {
5070                         if (strcmp(heredoc.data + past_EOL, word) == 0) {
5071                                 heredoc.data[past_EOL] = '\0';
5072                                 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5073                                 return heredoc.data;
5074                         }
5075                         do {
5076                                 o_addchr(&heredoc, ch);
5077                                 past_EOL = heredoc.length;
5078  jump_in:
5079                                 do {
5080                                         ch = i_getch(input);
5081                                         nommu_addchr(as_string, ch);
5082                                 } while (skip_tabs && ch == '\t');
5083                         } while (ch == '\n');
5084                 }
5085                 if (ch == EOF) {
5086                         o_free_unsafe(&heredoc);
5087                         return NULL;
5088                 }
5089                 o_addchr(&heredoc, ch);
5090                 nommu_addchr(as_string, ch);
5091         }
5092 }
5093
5094 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5095  * and load them all. There should be exactly heredoc_cnt of them.
5096  */
5097 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5098 {
5099         struct pipe *pi = ctx->list_head;
5100
5101         while (pi && heredoc_cnt) {
5102                 int i;
5103                 struct command *cmd = pi->cmds;
5104
5105                 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5106                                 pi->num_cmds,
5107                                 cmd->argv ? cmd->argv[0] : "NONE");
5108                 for (i = 0; i < pi->num_cmds; i++) {
5109                         struct redir_struct *redir = cmd->redirects;
5110
5111                         debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5112                                         i, cmd->argv ? cmd->argv[0] : "NONE");
5113                         while (redir) {
5114                                 if (redir->rd_type == REDIRECT_HEREDOC) {
5115                                         char *p;
5116
5117                                         redir->rd_type = REDIRECT_HEREDOC2;
5118                                         /* redir->rd_dup is (ab)used to indicate <<- */
5119                                         p = fetch_till_str(&ctx->as_string, input,
5120                                                 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5121                                         if (!p) {
5122                                                 syntax_error("unexpected EOF in here document");
5123                                                 return 1;
5124                                         }
5125                                         free(redir->rd_filename);
5126                                         redir->rd_filename = p;
5127                                         heredoc_cnt--;
5128                                 }
5129                                 redir = redir->next;
5130                         }
5131                         cmd++;
5132                 }
5133                 pi = pi->next;
5134         }
5135 #if 0
5136         /* Should be 0. If it isn't, it's a parse error */
5137         if (heredoc_cnt)
5138                 bb_error_msg_and_die("heredoc BUG 2");
5139 #endif
5140         return 0;
5141 }
5142
5143
5144 #if ENABLE_HUSH_TICK
5145 static FILE *generate_stream_from_string(const char *s)
5146 {
5147         FILE *pf;
5148         int pid, channel[2];
5149 #if !BB_MMU
5150         char **to_free;
5151 #endif
5152
5153         xpipe(channel);
5154         pid = BB_MMU ? fork() : vfork();
5155         if (pid < 0)
5156                 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
5157
5158         if (pid == 0) { /* child */
5159                 disable_restore_tty_pgrp_on_exit();
5160                 /* Process substitution is not considered to be usual
5161                  * 'command execution'.
5162                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5163                  */
5164                 bb_signals(0
5165                         + (1 << SIGTSTP)
5166                         + (1 << SIGTTIN)
5167                         + (1 << SIGTTOU)
5168                         , SIG_IGN);
5169                 close(channel[0]); /* NB: close _first_, then move fd! */
5170                 xmove_fd(channel[1], 1);
5171                 /* Prevent it from trying to handle ctrl-z etc */
5172                 IF_HUSH_JOB(G.run_list_level = 1;)
5173 #if BB_MMU
5174                 reset_traps_to_defaults();
5175                 parse_and_run_string(s);
5176                 _exit(G.last_exitcode);
5177 #else
5178         /* We re-execute after vfork on NOMMU. This makes this script safe:
5179          * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5180          * huge=`cat BIG` # was blocking here forever
5181          * echo OK
5182          */
5183                 re_execute_shell(&to_free,
5184                                 s,
5185                                 G.global_argv[0],
5186                                 G.global_argv + 1,
5187                                 NULL);
5188 #endif
5189         }
5190
5191         /* parent */
5192 #if ENABLE_HUSH_FAST
5193         G.count_SIGCHLD++;
5194 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5195 #endif
5196         enable_restore_tty_pgrp_on_exit();
5197 #if !BB_MMU
5198         free(to_free);
5199 #endif
5200         close(channel[1]);
5201         pf = fdopen(channel[0], "r");
5202         return pf;
5203 }
5204
5205 /* Return code is exit status of the process that is run. */
5206 static int process_command_subs(o_string *dest, const char *s)
5207 {
5208         FILE *pf;
5209         struct in_str pipe_str;
5210         int ch, eol_cnt;
5211
5212         pf = generate_stream_from_string(s);
5213         if (pf == NULL)
5214                 return 1;
5215         close_on_exec_on(fileno(pf));
5216
5217         /* Now send results of command back into original context */
5218         setup_file_in_str(&pipe_str, pf);
5219         eol_cnt = 0;
5220         while ((ch = i_getch(&pipe_str)) != EOF) {
5221                 if (ch == '\n') {
5222                         eol_cnt++;
5223                         continue;
5224                 }
5225                 while (eol_cnt) {
5226                         o_addchr(dest, '\n');
5227                         eol_cnt--;
5228                 }
5229                 o_addQchr(dest, ch);
5230         }
5231
5232         debug_printf("done reading from pipe, pclose()ing\n");
5233         /* Note: we got EOF, and we just close the read end of the pipe.
5234          * We do not wait for the `cmd` child to terminate. bash and ash do.
5235          * Try these:
5236          * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5237          * `false`; echo $? - bash outputs "1"
5238          */
5239         fclose(pf);
5240         debug_printf("closed FILE from child. return 0\n");
5241         return 0;
5242 }
5243 #endif
5244
5245 static int parse_group(o_string *dest, struct parse_context *ctx,
5246         struct in_str *input, int ch)
5247 {
5248         /* dest contains characters seen prior to ( or {.
5249          * Typically it's empty, but for function defs,
5250          * it contains function name (without '()'). */
5251         struct pipe *pipe_list;
5252         int endch;
5253         struct command *command = ctx->command;
5254
5255         debug_printf_parse("parse_group entered\n");
5256 #if ENABLE_HUSH_FUNCTIONS
5257         if (ch == '(' && !dest->o_quoted) {
5258                 if (dest->length)
5259                         if (done_word(dest, ctx))
5260                                 return 1;
5261                 if (!command->argv)
5262                         goto skip; /* (... */
5263                 if (command->argv[1]) { /* word word ... (... */
5264                         syntax_error_unexpected_ch('(');
5265                         return 1;
5266                 }
5267                 /* it is "word(..." or "word (..." */
5268                 do
5269                         ch = i_getch(input);
5270                 while (ch == ' ' || ch == '\t');
5271                 if (ch != ')') {
5272                         syntax_error_unexpected_ch(ch);
5273                         return 1;
5274                 }
5275                 nommu_addchr(&ctx->as_string, ch);
5276                 do
5277                         ch = i_getch(input);
5278                 while (ch == ' ' || ch == '\t' || ch == '\n');
5279                 if (ch != '{') {
5280                         syntax_error_unexpected_ch(ch);
5281                         return 1;
5282                 }
5283                 nommu_addchr(&ctx->as_string, ch);
5284                 command->cmd_type = CMD_FUNCDEF;
5285                 goto skip;
5286         }
5287 #endif
5288         if (command->argv /* word [word]{... */
5289          || dest->length /* word{... */
5290          || dest->o_quoted /* ""{... */
5291         ) {
5292                 syntax_error(NULL);
5293                 debug_printf_parse("parse_group return 1: "
5294                         "syntax error, groups and arglists don't mix\n");
5295                 return 1;
5296         }
5297
5298 #if ENABLE_HUSH_FUNCTIONS
5299  skip:
5300 #endif
5301         endch = '}';
5302         if (ch == '(') {
5303                 endch = ')';
5304                 command->cmd_type = CMD_SUBSHELL;
5305         } else {
5306                 /* bash does not allow "{echo...", requires whitespace */
5307                 ch = i_getch(input);
5308                 if (ch != ' ' && ch != '\t' && ch != '\n') {
5309                         syntax_error_unexpected_ch(ch);
5310                         return 1;
5311                 }
5312                 nommu_addchr(&ctx->as_string, ch);
5313         }
5314
5315         {
5316 #if !BB_MMU
5317                 char *as_string = NULL;
5318 #endif
5319                 pipe_list = parse_stream(&as_string, input, endch);
5320 #if !BB_MMU
5321                 if (as_string)
5322                         o_addstr(&ctx->as_string, as_string);
5323 #endif
5324                 /* empty ()/{} or parse error? */
5325                 if (!pipe_list || pipe_list == ERR_PTR) {
5326                         /* parse_stream already emitted error msg */
5327 #if !BB_MMU
5328                         free(as_string);
5329 #endif
5330                         debug_printf_parse("parse_group return 1: "
5331                                 "parse_stream returned %p\n", pipe_list);
5332                         return 1;
5333                 }
5334                 command->group = pipe_list;
5335 #if !BB_MMU
5336                 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5337                 command->group_as_string = as_string;
5338                 debug_printf_parse("end of group, remembering as:'%s'\n",
5339                                 command->group_as_string);
5340 #endif
5341         }
5342         debug_printf_parse("parse_group return 0\n");
5343         return 0;
5344         /* command remains "open", available for possible redirects */
5345 }
5346
5347 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
5348 /* Subroutines for copying $(...) and `...` things */
5349 static void add_till_backquote(o_string *dest, struct in_str *input);
5350 /* '...' */
5351 static void add_till_single_quote(o_string *dest, struct in_str *input)
5352 {
5353         while (1) {
5354                 int ch = i_getch(input);
5355                 if (ch == EOF) {
5356                         syntax_error_unterm_ch('\'');
5357                         /*xfunc_die(); - redundant */
5358                 }
5359                 if (ch == '\'')
5360                         return;
5361                 o_addchr(dest, ch);
5362         }
5363 }
5364 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
5365 static void add_till_double_quote(o_string *dest, struct in_str *input)
5366 {
5367         while (1) {
5368                 int ch = i_getch(input);
5369                 if (ch == EOF) {
5370                         syntax_error_unterm_ch('"');
5371                         /*xfunc_die(); - redundant */
5372                 }
5373                 if (ch == '"')
5374                         return;
5375                 if (ch == '\\') {  /* \x. Copy both chars. */
5376                         o_addchr(dest, ch);
5377                         ch = i_getch(input);
5378                 }
5379                 o_addchr(dest, ch);
5380                 if (ch == '`') {
5381                         add_till_backquote(dest, input);
5382                         o_addchr(dest, ch);
5383                         continue;
5384                 }
5385                 //if (ch == '$') ...
5386         }
5387 }
5388 /* Process `cmd` - copy contents until "`" is seen. Complicated by
5389  * \` quoting.
5390  * "Within the backquoted style of command substitution, backslash
5391  * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5392  * The search for the matching backquote shall be satisfied by the first
5393  * backquote found without a preceding backslash; during this search,
5394  * if a non-escaped backquote is encountered within a shell comment,
5395  * a here-document, an embedded command substitution of the $(command)
5396  * form, or a quoted string, undefined results occur. A single-quoted
5397  * or double-quoted string that begins, but does not end, within the
5398  * "`...`" sequence produces undefined results."
5399  * Example                               Output
5400  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
5401  */
5402 static void add_till_backquote(o_string *dest, struct in_str *input)
5403 {
5404         while (1) {
5405                 int ch = i_getch(input);
5406                 if (ch == EOF) {
5407                         syntax_error_unterm_ch('`');
5408                         /*xfunc_die(); - redundant */
5409                 }
5410                 if (ch == '`')
5411                         return;
5412                 if (ch == '\\') {
5413                         /* \x. Copy both chars unless it is \` */
5414                         int ch2 = i_getch(input);
5415                         if (ch2 == EOF) {
5416                                 syntax_error_unterm_ch('`');
5417                                 /*xfunc_die(); - redundant */
5418                         }
5419                         if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
5420                                 o_addchr(dest, ch);
5421                         ch = ch2;
5422                 }
5423                 o_addchr(dest, ch);
5424         }
5425 }
5426 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
5427  * quoting and nested ()s.
5428  * "With the $(command) style of command substitution, all characters
5429  * following the open parenthesis to the matching closing parenthesis
5430  * constitute the command. Any valid shell script can be used for command,
5431  * except a script consisting solely of redirections which produces
5432  * unspecified results."
5433  * Example                              Output
5434  * echo $(echo '(TEST)' BEST)           (TEST) BEST
5435  * echo $(echo 'TEST)' BEST)            TEST) BEST
5436  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
5437  */
5438 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
5439 {
5440         int count = 0;
5441         while (1) {
5442                 int ch = i_getch(input);
5443                 if (ch == EOF) {
5444                         syntax_error_unterm_ch(')');
5445                         /*xfunc_die(); - redundant */
5446                 }
5447                 if (ch == '(')
5448                         count++;
5449                 if (ch == ')') {
5450                         if (--count < 0) {
5451                                 if (!dbl)
5452                                         break;
5453                                 if (i_peek(input) == ')') {
5454                                         i_getch(input);
5455                                         break;
5456                                 }
5457                         }
5458                 }
5459                 o_addchr(dest, ch);
5460                 if (ch == '\'') {
5461                         add_till_single_quote(dest, input);
5462                         o_addchr(dest, ch);
5463                         continue;
5464                 }
5465                 if (ch == '"') {
5466                         add_till_double_quote(dest, input);
5467                         o_addchr(dest, ch);
5468                         continue;
5469                 }
5470                 if (ch == '\\') {
5471                         /* \x. Copy verbatim. Important for  \(, \) */
5472                         ch = i_getch(input);
5473                         if (ch == EOF) {
5474                                 syntax_error_unterm_ch(')');
5475                                 /*xfunc_die(); - redundant */
5476                         }
5477                         o_addchr(dest, ch);
5478                         continue;
5479                 }
5480         }
5481 }
5482 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
5483
5484 /* Return code: 0 for OK, 1 for syntax error */
5485 #if BB_MMU
5486 #define handle_dollar(as_string, dest, input) \
5487         handle_dollar(dest, input)
5488 #endif
5489 static int handle_dollar(o_string *as_string,
5490                 o_string *dest,
5491                 struct in_str *input)
5492 {
5493         int ch = i_peek(input);  /* first character after the $ */
5494         unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
5495
5496         debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
5497         if (isalpha(ch)) {
5498                 ch = i_getch(input);
5499                 nommu_addchr(as_string, ch);
5500  make_var:
5501                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5502                 while (1) {
5503                         debug_printf_parse(": '%c'\n", ch);
5504                         o_addchr(dest, ch | quote_mask);
5505                         quote_mask = 0;
5506                         ch = i_peek(input);
5507                         if (!isalnum(ch) && ch != '_')
5508                                 break;
5509                         ch = i_getch(input);
5510                         nommu_addchr(as_string, ch);
5511                 }
5512                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5513         } else if (isdigit(ch)) {
5514  make_one_char_var:
5515                 ch = i_getch(input);
5516                 nommu_addchr(as_string, ch);
5517                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5518                 debug_printf_parse(": '%c'\n", ch);
5519                 o_addchr(dest, ch | quote_mask);
5520                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5521         } else switch (ch) {
5522         case '$': /* pid */
5523         case '!': /* last bg pid */
5524         case '?': /* last exit code */
5525         case '#': /* number of args */
5526         case '*': /* args */
5527         case '@': /* args */
5528                 goto make_one_char_var;
5529         case '{': {
5530                 bool first_char, all_digits;
5531                 int expansion;
5532
5533                 ch = i_getch(input);
5534                 nommu_addchr(as_string, ch);
5535                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5536
5537                 /* TODO: maybe someone will try to escape the '}' */
5538                 expansion = 0;
5539                 first_char = true;
5540                 all_digits = false;
5541                 while (1) {
5542                         ch = i_getch(input);
5543                         nommu_addchr(as_string, ch);
5544                         if (ch == '}') {
5545                                 break;
5546                         }
5547
5548                         if (first_char) {
5549                                 if (ch == '#') {
5550                                         /* ${#var}: length of var contents */
5551                                         goto char_ok;
5552                                 }
5553                                 if (isdigit(ch)) {
5554                                         all_digits = true;
5555                                         goto char_ok;
5556                                 }
5557                                 /* They're being verbose and doing ${?} */
5558                                 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5559                                         goto char_ok;
5560                         }
5561
5562                         if (expansion < 2
5563                          && (  (all_digits && !isdigit(ch))
5564                             || (!all_digits && !isalnum(ch) && ch != '_')
5565                             )
5566                         ) {
5567                                 /* handle parameter expansions
5568                                  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5569                                  */
5570                                 if (first_char)
5571                                         goto case_default;
5572                                 switch (ch) {
5573                                 case ':': /* null modifier */
5574                                         if (expansion == 0) {
5575                                                 debug_printf_parse(": null modifier\n");
5576                                                 ++expansion;
5577                                                 break;
5578                                         }
5579                                         goto case_default;
5580                                 case '#': /* remove prefix */
5581                                 case '%': /* remove suffix */
5582                                         if (expansion == 0) {
5583                                                 debug_printf_parse(": remove suffix/prefix\n");
5584                                                 expansion = 2;
5585                                                 break;
5586                                         }
5587                                         goto case_default;
5588                                 case '-': /* default value */
5589                                 case '=': /* assign default */
5590                                 case '+': /* alternative */
5591                                 case '?': /* error indicate */
5592                                         debug_printf_parse(": parameter expansion\n");
5593                                         expansion = 2;
5594                                         break;
5595                                 default:
5596                                 case_default:
5597                                         syntax_error_unterm_str("${name}");
5598                                         debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5599                                         return 1;
5600                                 }
5601                         }
5602  char_ok:
5603                         debug_printf_parse(": '%c'\n", ch);
5604                         o_addchr(dest, ch | quote_mask);
5605                         quote_mask = 0;
5606                         first_char = false;
5607                 } /* while (1) */
5608                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5609                 break;
5610         }
5611 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5612         case '(': {
5613 # if !BB_MMU
5614                 int pos;
5615 # endif
5616                 ch = i_getch(input);
5617                 nommu_addchr(as_string, ch);
5618 # if ENABLE_SH_MATH_SUPPORT
5619                 if (i_peek(input) == '(') {
5620                         ch = i_getch(input);
5621                         nommu_addchr(as_string, ch);
5622                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
5623                         o_addchr(dest, /*quote_mask |*/ '+');
5624 #  if !BB_MMU
5625                         pos = dest->length;
5626 #  endif
5627                         add_till_closing_paren(dest, input, true);
5628 #  if !BB_MMU
5629                         if (as_string) {
5630                                 o_addstr(as_string, dest->data + pos);
5631                                 o_addchr(as_string, ')');
5632                                 o_addchr(as_string, ')');
5633                         }
5634 #  endif
5635                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
5636                         break;
5637                 }
5638 # endif
5639 # if ENABLE_HUSH_TICK
5640                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5641                 o_addchr(dest, quote_mask | '`');
5642 #  if !BB_MMU
5643                 pos = dest->length;
5644 #  endif
5645                 add_till_closing_paren(dest, input, false);
5646 #  if !BB_MMU
5647                 if (as_string) {
5648                         o_addstr(as_string, dest->data + pos);
5649                         o_addchr(as_string, '`');
5650                 }
5651 #  endif
5652                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5653 # endif
5654                 break;
5655         }
5656 #endif
5657         case '_':
5658                 ch = i_getch(input);
5659                 nommu_addchr(as_string, ch);
5660                 ch = i_peek(input);
5661                 if (isalnum(ch)) { /* it's $_name or $_123 */
5662                         ch = '_';
5663                         goto make_var;
5664                 }
5665                 /* else: it's $_ */
5666         /* TODO: */
5667         /* $_ Shell or shell script name; or last cmd name */
5668         /* $- Option flags set by set builtin or shell options (-i etc) */
5669         default:
5670                 o_addQchr(dest, '$');
5671         }
5672         debug_printf_parse("handle_dollar return 0\n");
5673         return 0;
5674 }
5675
5676 #if BB_MMU
5677 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5678         parse_stream_dquoted(dest, input, dquote_end)
5679 #endif
5680 static int parse_stream_dquoted(o_string *as_string,
5681                 o_string *dest,
5682                 struct in_str *input,
5683                 int dquote_end)
5684 {
5685         int ch;
5686         int next;
5687
5688  again:
5689         ch = i_getch(input);
5690         if (ch != EOF)
5691                 nommu_addchr(as_string, ch);
5692         if (ch == dquote_end) { /* may be only '"' or EOF */
5693                 if (dest->o_assignment == NOT_ASSIGNMENT)
5694                         dest->o_escape ^= 1;
5695                 debug_printf_parse("parse_stream_dquoted return 0\n");
5696                 return 0;
5697         }
5698         /* note: can't move it above ch == dquote_end check! */
5699         if (ch == EOF) {
5700                 syntax_error_unterm_ch('"');
5701                 /*xfunc_die(); - redundant */
5702         }
5703         next = '\0';
5704         if (ch != '\n') {
5705                 next = i_peek(input);
5706         }
5707         debug_printf_parse(": ch=%c (%d) escape=%d\n",
5708                                         ch, ch, dest->o_escape);
5709         if (ch == '\\') {
5710                 if (next == EOF) {
5711                         syntax_error("\\<eof>");
5712                         xfunc_die();
5713                 }
5714                 /* bash:
5715                  * "The backslash retains its special meaning [in "..."]
5716                  * only when followed by one of the following characters:
5717                  * $, `, ", \, or <newline>.  A double quote may be quoted
5718                  * within double quotes by preceding it with a backslash."
5719                  */
5720                 if (strchr("$`\"\\\n", next) != NULL) {
5721                         ch = i_getch(input);
5722                         if (ch != '\n') {
5723                                 o_addqchr(dest, ch);
5724                                 nommu_addchr(as_string, ch);
5725                         }
5726                 } else {
5727                         o_addqchr(dest, '\\');
5728                         nommu_addchr(as_string, '\\');
5729                 }
5730                 goto again;
5731         }
5732         if (ch == '$') {
5733                 if (handle_dollar(as_string, dest, input) != 0) {
5734                         debug_printf_parse("parse_stream_dquoted return 1: "
5735                                         "handle_dollar returned non-0\n");
5736                         return 1;
5737                 }
5738                 goto again;
5739         }
5740 #if ENABLE_HUSH_TICK
5741         if (ch == '`') {
5742                 //int pos = dest->length;
5743                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5744                 o_addchr(dest, 0x80 | '`');
5745                 add_till_backquote(dest, input);
5746                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5747                 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5748                 goto again;
5749         }
5750 #endif
5751         o_addQchr(dest, ch);
5752         if (ch == '='
5753          && (dest->o_assignment == MAYBE_ASSIGNMENT
5754             || dest->o_assignment == WORD_IS_KEYWORD)
5755          && is_well_formed_var_name(dest->data, '=')
5756         ) {
5757                 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5758         }
5759         goto again;
5760 }
5761
5762 /*
5763  * Scan input until EOF or end_trigger char.
5764  * Return a list of pipes to execute, or NULL on EOF
5765  * or if end_trigger character is met.
5766  * On syntax error, exit is shell is not interactive,
5767  * reset parsing machinery and start parsing anew,
5768  * or return ERR_PTR.
5769  */
5770 static struct pipe *parse_stream(char **pstring,
5771                 struct in_str *input,
5772                 int end_trigger)
5773 {
5774         struct parse_context ctx;
5775         o_string dest = NULL_O_STRING;
5776         int is_in_dquote;
5777         int heredoc_cnt;
5778
5779         /* Double-quote state is handled in the state variable is_in_dquote.
5780          * A single-quote triggers a bypass of the main loop until its mate is
5781          * found.  When recursing, quote state is passed in via dest->o_escape.
5782          */
5783         debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5784                         end_trigger ? : 'X');
5785         debug_enter();
5786
5787         G.ifs = get_local_var_value("IFS");
5788         if (G.ifs == NULL)
5789                 G.ifs = " \t\n";
5790
5791  reset:
5792 #if ENABLE_HUSH_INTERACTIVE
5793         input->promptmode = 0; /* PS1 */
5794 #endif
5795         /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5796         initialize_context(&ctx);
5797         is_in_dquote = 0;
5798         heredoc_cnt = 0;
5799         while (1) {
5800                 const char *is_ifs;
5801                 const char *is_special;
5802                 int ch;
5803                 int next;
5804                 int redir_fd;
5805                 redir_type redir_style;
5806
5807                 if (is_in_dquote) {
5808                         /* dest.o_quoted = 1; - already is (see below) */
5809                         if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5810                                 goto parse_error;
5811                         }
5812                         /* We reached closing '"' */
5813                         is_in_dquote = 0;
5814                 }
5815                 ch = i_getch(input);
5816                 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5817                                                 ch, ch, dest.o_escape);
5818                 if (ch == EOF) {
5819                         struct pipe *pi;
5820
5821                         if (heredoc_cnt) {
5822                                 syntax_error_unterm_str("here document");
5823                                 goto parse_error;
5824                         }
5825                         /* end_trigger == '}' case errors out earlier,
5826                          * checking only ')' */
5827                         if (end_trigger == ')') {
5828                                 syntax_error_unterm_ch('('); /* exits */
5829                                 /* goto parse_error; */
5830                         }
5831
5832                         if (done_word(&dest, &ctx)) {
5833                                 goto parse_error;
5834                         }
5835                         o_free(&dest);
5836                         done_pipe(&ctx, PIPE_SEQ);
5837                         pi = ctx.list_head;
5838                         /* If we got nothing... */
5839                         /* (this makes bare "&" cmd a no-op.
5840                          * bash says: "syntax error near unexpected token '&'") */
5841                         if (pi->num_cmds == 0
5842                             IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5843                         ) {
5844                                 free_pipe_list(pi);
5845                                 pi = NULL;
5846                         }
5847 #if !BB_MMU
5848                         debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5849                         if (pstring)
5850                                 *pstring = ctx.as_string.data;
5851                         else
5852                                 o_free_unsafe(&ctx.as_string);
5853 #endif
5854                         debug_leave();
5855                         debug_printf_parse("parse_stream return %p\n", pi);
5856                         return pi;
5857                 }
5858                 nommu_addchr(&ctx.as_string, ch);
5859                 is_ifs = strchr(G.ifs, ch);
5860                 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5861                                 "\\$\"" IF_HUSH_TICK("`") /* always special */
5862                                 , ch);
5863
5864                 if (!is_special && !is_ifs) { /* ordinary char */
5865  ordinary_char:
5866                         o_addQchr(&dest, ch);
5867                         if ((dest.o_assignment == MAYBE_ASSIGNMENT
5868                             || dest.o_assignment == WORD_IS_KEYWORD)
5869                          && ch == '='
5870                          && is_well_formed_var_name(dest.data, '=')
5871                         ) {
5872                                 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5873                         }
5874                         continue;
5875                 }
5876
5877                 if (is_ifs) {
5878                         if (done_word(&dest, &ctx)) {
5879                                 goto parse_error;
5880                         }
5881                         if (ch == '\n') {
5882 #if ENABLE_HUSH_CASE
5883                                 /* "case ... in <newline> word) ..." -
5884                                  * newlines are ignored (but ';' wouldn't be) */
5885                                 if (ctx.command->argv == NULL
5886                                  && ctx.ctx_res_w == RES_MATCH
5887                                 ) {
5888                                         continue;
5889                                 }
5890 #endif
5891                                 /* Treat newline as a command separator. */
5892                                 done_pipe(&ctx, PIPE_SEQ);
5893                                 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5894                                 if (heredoc_cnt) {
5895                                         if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5896                                                 goto parse_error;
5897                                         }
5898                                         heredoc_cnt = 0;
5899                                 }
5900                                 dest.o_assignment = MAYBE_ASSIGNMENT;
5901                                 ch = ';';
5902                                 /* note: if (is_ifs) continue;
5903                                  * will still trigger for us */
5904                         }
5905                 }
5906
5907                 /* "cmd}" or "cmd }..." without semicolon or &:
5908                  * } is an ordinary char in this case, even inside { cmd; }
5909                  * Pathological example: { ""}; } should exec "}" cmd
5910                  */
5911                 if (ch == '}') {
5912                         if (!IS_NULL_CMD(ctx.command) /* cmd } */
5913                          || dest.length != 0 /* word} */
5914                          || dest.o_quoted    /* ""} */
5915                         ) {
5916                                 goto ordinary_char;
5917                         }
5918                         if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5919                                 goto skip_end_trigger;
5920                         /* else: } does terminate a group */
5921                 }
5922
5923                 if (end_trigger && end_trigger == ch
5924                  && (ch != ';' || heredoc_cnt == 0)
5925 #if ENABLE_HUSH_CASE
5926                  && (ch != ')'
5927                     || ctx.ctx_res_w != RES_MATCH
5928                     || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5929                     )
5930 #endif
5931                 ) {
5932                         if (heredoc_cnt) {
5933                                 /* This is technically valid:
5934                                  * { cat <<HERE; }; echo Ok
5935                                  * heredoc
5936                                  * heredoc
5937                                  * HERE
5938                                  * but we don't support this.
5939                                  * We require heredoc to be in enclosing {}/(),
5940                                  * if any.
5941                                  */
5942                                 syntax_error_unterm_str("here document");
5943                                 goto parse_error;
5944                         }
5945                         if (done_word(&dest, &ctx)) {
5946                                 goto parse_error;
5947                         }
5948                         done_pipe(&ctx, PIPE_SEQ);
5949                         dest.o_assignment = MAYBE_ASSIGNMENT;
5950                         /* Do we sit outside of any if's, loops or case's? */
5951                         if (!HAS_KEYWORDS
5952                          IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5953                         ) {
5954                                 o_free(&dest);
5955 #if !BB_MMU
5956                                 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5957                                 if (pstring)
5958                                         *pstring = ctx.as_string.data;
5959                                 else
5960                                         o_free_unsafe(&ctx.as_string);
5961 #endif
5962                                 debug_leave();
5963                                 debug_printf_parse("parse_stream return %p: "
5964                                                 "end_trigger char found\n",
5965                                                 ctx.list_head);
5966                                 return ctx.list_head;
5967                         }
5968                 }
5969  skip_end_trigger:
5970                 if (is_ifs)
5971                         continue;
5972
5973                 next = '\0';
5974                 if (ch != '\n') {
5975                         next = i_peek(input);
5976                 }
5977
5978                 /* Catch <, > before deciding whether this word is
5979                  * an assignment. a=1 2>z b=2: b=2 is still assignment */
5980                 switch (ch) {
5981                 case '>':
5982                         redir_fd = redirect_opt_num(&dest);
5983                         if (done_word(&dest, &ctx)) {
5984                                 goto parse_error;
5985                         }
5986                         redir_style = REDIRECT_OVERWRITE;
5987                         if (next == '>') {
5988                                 redir_style = REDIRECT_APPEND;
5989                                 ch = i_getch(input);
5990                                 nommu_addchr(&ctx.as_string, ch);
5991                         }
5992 #if 0
5993                         else if (next == '(') {
5994                                 syntax_error(">(process) not supported");
5995                                 goto parse_error;
5996                         }
5997 #endif
5998                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
5999                                 goto parse_error;
6000                         continue; /* back to top of while (1) */
6001                 case '<':
6002                         redir_fd = redirect_opt_num(&dest);
6003                         if (done_word(&dest, &ctx)) {
6004                                 goto parse_error;
6005                         }
6006                         redir_style = REDIRECT_INPUT;
6007                         if (next == '<') {
6008                                 redir_style = REDIRECT_HEREDOC;
6009                                 heredoc_cnt++;
6010                                 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6011                                 ch = i_getch(input);
6012                                 nommu_addchr(&ctx.as_string, ch);
6013                         } else if (next == '>') {
6014                                 redir_style = REDIRECT_IO;
6015                                 ch = i_getch(input);
6016                                 nommu_addchr(&ctx.as_string, ch);
6017                         }
6018 #if 0
6019                         else if (next == '(') {
6020                                 syntax_error("<(process) not supported");
6021                                 goto parse_error;
6022                         }
6023 #endif
6024                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
6025                                 goto parse_error;
6026                         continue; /* back to top of while (1) */
6027                 }
6028
6029                 if (dest.o_assignment == MAYBE_ASSIGNMENT
6030                  /* check that we are not in word in "a=1 2>word b=1": */
6031                  && !ctx.pending_redirect
6032                 ) {
6033                         /* ch is a special char and thus this word
6034                          * cannot be an assignment */
6035                         dest.o_assignment = NOT_ASSIGNMENT;
6036                 }
6037
6038                 switch (ch) {
6039                 case '#':
6040                         if (dest.length == 0) {
6041                                 while (1) {
6042                                         ch = i_peek(input);
6043                                         if (ch == EOF || ch == '\n')
6044                                                 break;
6045                                         i_getch(input);
6046                                         /* note: we do not add it to &ctx.as_string */
6047                                 }
6048                                 nommu_addchr(&ctx.as_string, '\n');
6049                         } else {
6050                                 o_addQchr(&dest, ch);
6051                         }
6052                         break;
6053                 case '\\':
6054                         if (next == EOF) {
6055                                 syntax_error("\\<eof>");
6056                                 xfunc_die();
6057                         }
6058                         ch = i_getch(input);
6059                         if (ch != '\n') {
6060                                 o_addchr(&dest, '\\');
6061                                 nommu_addchr(&ctx.as_string, '\\');
6062                                 o_addchr(&dest, ch);
6063                                 nommu_addchr(&ctx.as_string, ch);
6064                                 /* Example: echo Hello \2>file
6065                                  * we need to know that word 2 is quoted */
6066                                 dest.o_quoted = 1;
6067                         }
6068                         break;
6069                 case '$':
6070                         if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
6071                                 debug_printf_parse("parse_stream parse error: "
6072                                         "handle_dollar returned non-0\n");
6073                                 goto parse_error;
6074                         }
6075                         break;
6076                 case '\'':
6077                         dest.o_quoted = 1;
6078                         while (1) {
6079                                 ch = i_getch(input);
6080                                 if (ch == EOF) {
6081                                         syntax_error_unterm_ch('\'');
6082                                         /*xfunc_die(); - redundant */
6083                                 }
6084                                 nommu_addchr(&ctx.as_string, ch);
6085                                 if (ch == '\'')
6086                                         break;
6087                                 o_addqchr(&dest, ch);
6088                         }
6089                         break;
6090                 case '"':
6091                         dest.o_quoted = 1;
6092                         is_in_dquote ^= 1; /* invert */
6093                         if (dest.o_assignment == NOT_ASSIGNMENT)
6094                                 dest.o_escape ^= 1;
6095                         break;
6096 #if ENABLE_HUSH_TICK
6097                 case '`': {
6098 #if !BB_MMU
6099                         int pos;
6100 #endif
6101                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6102                         o_addchr(&dest, '`');
6103 #if !BB_MMU
6104                         pos = dest.length;
6105 #endif
6106                         add_till_backquote(&dest, input);
6107 #if !BB_MMU
6108                         o_addstr(&ctx.as_string, dest.data + pos);
6109                         o_addchr(&ctx.as_string, '`');
6110 #endif
6111                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6112                         //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6113                         break;
6114                 }
6115 #endif
6116                 case ';':
6117 #if ENABLE_HUSH_CASE
6118  case_semi:
6119 #endif
6120                         if (done_word(&dest, &ctx)) {
6121                                 goto parse_error;
6122                         }
6123                         done_pipe(&ctx, PIPE_SEQ);
6124 #if ENABLE_HUSH_CASE
6125                         /* Eat multiple semicolons, detect
6126                          * whether it means something special */
6127                         while (1) {
6128                                 ch = i_peek(input);
6129                                 if (ch != ';')
6130                                         break;
6131                                 ch = i_getch(input);
6132                                 nommu_addchr(&ctx.as_string, ch);
6133                                 if (ctx.ctx_res_w == RES_CASE_BODY) {
6134                                         ctx.ctx_dsemicolon = 1;
6135                                         ctx.ctx_res_w = RES_MATCH;
6136                                         break;
6137                                 }
6138                         }
6139 #endif
6140  new_cmd:
6141                         /* We just finished a cmd. New one may start
6142                          * with an assignment */
6143                         dest.o_assignment = MAYBE_ASSIGNMENT;
6144                         break;
6145                 case '&':
6146                         if (done_word(&dest, &ctx)) {
6147                                 goto parse_error;
6148                         }
6149                         if (next == '&') {
6150                                 ch = i_getch(input);
6151                                 nommu_addchr(&ctx.as_string, ch);
6152                                 done_pipe(&ctx, PIPE_AND);
6153                         } else {
6154                                 done_pipe(&ctx, PIPE_BG);
6155                         }
6156                         goto new_cmd;
6157                 case '|':
6158                         if (done_word(&dest, &ctx)) {
6159                                 goto parse_error;
6160                         }
6161 #if ENABLE_HUSH_CASE
6162                         if (ctx.ctx_res_w == RES_MATCH)
6163                                 break; /* we are in case's "word | word)" */
6164 #endif
6165                         if (next == '|') { /* || */
6166                                 ch = i_getch(input);
6167                                 nommu_addchr(&ctx.as_string, ch);
6168                                 done_pipe(&ctx, PIPE_OR);
6169                         } else {
6170                                 /* we could pick up a file descriptor choice here
6171                                  * with redirect_opt_num(), but bash doesn't do it.
6172                                  * "echo foo 2| cat" yields "foo 2". */
6173                                 done_command(&ctx);
6174                         }
6175                         goto new_cmd;
6176                 case '(':
6177 #if ENABLE_HUSH_CASE
6178                         /* "case... in [(]word)..." - skip '(' */
6179                         if (ctx.ctx_res_w == RES_MATCH
6180                          && ctx.command->argv == NULL /* not (word|(... */
6181                          && dest.length == 0 /* not word(... */
6182                          && dest.o_quoted == 0 /* not ""(... */
6183                         ) {
6184                                 continue;
6185                         }
6186 #endif
6187                 case '{':
6188                         if (parse_group(&dest, &ctx, input, ch) != 0) {
6189                                 goto parse_error;
6190                         }
6191                         goto new_cmd;
6192                 case ')':
6193 #if ENABLE_HUSH_CASE
6194                         if (ctx.ctx_res_w == RES_MATCH)
6195                                 goto case_semi;
6196 #endif
6197                 case '}':
6198                         /* proper use of this character is caught by end_trigger:
6199                          * if we see {, we call parse_group(..., end_trigger='}')
6200                          * and it will match } earlier (not here). */
6201                         syntax_error_unexpected_ch(ch);
6202                         goto parse_error;
6203                 default:
6204                         if (HUSH_DEBUG)
6205                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6206                 }
6207         } /* while (1) */
6208
6209  parse_error:
6210         {
6211                 struct parse_context *pctx;
6212                 IF_HAS_KEYWORDS(struct parse_context *p2;)
6213
6214                 /* Clean up allocated tree.
6215                  * Sample for finding leaks on syntax error recovery path.
6216                  * Run it from interactive shell, watch pmap `pidof hush`.
6217                  * while if false; then false; fi; do break; fi
6218                  * Samples to catch leaks at execution:
6219                  * while if (true | {true;}); then echo ok; fi; do break; done
6220                  * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6221                  */
6222                 pctx = &ctx;
6223                 do {
6224                         /* Update pipe/command counts,
6225                          * otherwise freeing may miss some */
6226                         done_pipe(pctx, PIPE_SEQ);
6227                         debug_printf_clean("freeing list %p from ctx %p\n",
6228                                         pctx->list_head, pctx);
6229                         debug_print_tree(pctx->list_head, 0);
6230                         free_pipe_list(pctx->list_head);
6231                         debug_printf_clean("freed list %p\n", pctx->list_head);
6232 #if !BB_MMU
6233                         o_free_unsafe(&pctx->as_string);
6234 #endif
6235                         IF_HAS_KEYWORDS(p2 = pctx->stack;)
6236                         if (pctx != &ctx) {
6237                                 free(pctx);
6238                         }
6239                         IF_HAS_KEYWORDS(pctx = p2;)
6240                 } while (HAS_KEYWORDS && pctx);
6241                 /* Free text, clear all dest fields */
6242                 o_free(&dest);
6243                 /* If we are not in top-level parse, we return,
6244                  * our caller will propagate error.
6245                  */
6246                 if (end_trigger != ';') {
6247 #if !BB_MMU
6248                         if (pstring)
6249                                 *pstring = NULL;
6250 #endif
6251                         debug_leave();
6252                         return ERR_PTR;
6253                 }
6254                 /* Discard cached input, force prompt */
6255                 input->p = NULL;
6256                 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6257                 goto reset;
6258         }
6259 }
6260
6261 /* Executing from string: eval, sh -c '...'
6262  *          or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6263  * end_trigger controls how often we stop parsing
6264  * NUL: parse all, execute, return
6265  * ';': parse till ';' or newline, execute, repeat till EOF
6266  */
6267 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6268 {
6269         while (1) {
6270                 struct pipe *pipe_list;
6271
6272                 pipe_list = parse_stream(NULL, inp, end_trigger);
6273                 if (!pipe_list) /* EOF */
6274                         break;
6275                 debug_print_tree(pipe_list, 0);
6276                 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6277                 run_and_free_list(pipe_list);
6278         }
6279 }
6280
6281 static void parse_and_run_string(const char *s)
6282 {
6283         struct in_str input;
6284         setup_string_in_str(&input, s);
6285         parse_and_run_stream(&input, '\0');
6286 }
6287
6288 static void parse_and_run_file(FILE *f)
6289 {
6290         struct in_str input;
6291         setup_file_in_str(&input, f);
6292         parse_and_run_stream(&input, ';');
6293 }
6294
6295 /* Called a few times only (or even once if "sh -c") */
6296 static void block_signals(int second_time)
6297 {
6298         unsigned sig;
6299         unsigned mask;
6300
6301         mask = (1 << SIGQUIT);
6302         if (G_interactive_fd) {
6303                 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
6304                 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
6305                         mask |= SPECIAL_JOB_SIGS;
6306         }
6307         G.non_DFL_mask = mask;
6308
6309         if (!second_time)
6310                 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6311         sig = 0;
6312         while (mask) {
6313                 if (mask & 1)
6314                         sigaddset(&G.blocked_set, sig);
6315                 mask >>= 1;
6316                 sig++;
6317         }
6318         sigdelset(&G.blocked_set, SIGCHLD);
6319
6320         sigprocmask(SIG_SETMASK, &G.blocked_set,
6321                         second_time ? NULL : &G.inherited_set);
6322         /* POSIX allows shell to re-enable SIGCHLD
6323          * even if it was SIG_IGN on entry */
6324 #if ENABLE_HUSH_FAST
6325         G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
6326         if (!second_time)
6327                 signal(SIGCHLD, SIGCHLD_handler);
6328 #else
6329         if (!second_time)
6330                 signal(SIGCHLD, SIG_DFL);
6331 #endif
6332 }
6333
6334 #if ENABLE_HUSH_JOB
6335 /* helper */
6336 static void maybe_set_to_sigexit(int sig)
6337 {
6338         void (*handler)(int);
6339         /* non_DFL_mask'ed signals are, well, masked,
6340          * no need to set handler for them.
6341          */
6342         if (!((G.non_DFL_mask >> sig) & 1)) {
6343                 handler = signal(sig, sigexit);
6344                 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6345                         signal(sig, handler);
6346         }
6347 }
6348 /* Set handlers to restore tty pgrp and exit */
6349 static void set_fatal_handlers(void)
6350 {
6351         /* We _must_ restore tty pgrp on fatal signals */
6352         if (HUSH_DEBUG) {
6353                 maybe_set_to_sigexit(SIGILL );
6354                 maybe_set_to_sigexit(SIGFPE );
6355                 maybe_set_to_sigexit(SIGBUS );
6356                 maybe_set_to_sigexit(SIGSEGV);
6357                 maybe_set_to_sigexit(SIGTRAP);
6358         } /* else: hush is perfect. what SEGV? */
6359         maybe_set_to_sigexit(SIGABRT);
6360         /* bash 3.2 seems to handle these just like 'fatal' ones */
6361         maybe_set_to_sigexit(SIGPIPE);
6362         maybe_set_to_sigexit(SIGALRM);
6363         /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
6364          * if we aren't interactive... but in this case
6365          * we never want to restore pgrp on exit, and this fn is not called */
6366         /*maybe_set_to_sigexit(SIGHUP );*/
6367         /*maybe_set_to_sigexit(SIGTERM);*/
6368         /*maybe_set_to_sigexit(SIGINT );*/
6369 }
6370 #endif
6371
6372 static int set_mode(const char cstate, const char mode)
6373 {
6374         int state = (cstate == '-' ? 1 : 0);
6375         switch (mode) {
6376                 case 'n': G.fake_mode = state; break;
6377                 case 'x': /*G.debug_mode = state;*/ break;
6378                 default:  return EXIT_FAILURE;
6379         }
6380         return EXIT_SUCCESS;
6381 }
6382
6383 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6384 int hush_main(int argc, char **argv)
6385 {
6386         static const struct variable const_shell_ver = {
6387                 .next = NULL,
6388                 .varstr = (char*)hush_version_str,
6389                 .max_len = 1, /* 0 can provoke free(name) */
6390                 .flg_export = 1,
6391                 .flg_read_only = 1,
6392         };
6393         int signal_mask_is_inited = 0;
6394         int opt;
6395         unsigned builtin_argc;
6396         char **e;
6397         struct variable *cur_var;
6398
6399         INIT_G();
6400         if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
6401                 G.last_exitcode = EXIT_SUCCESS;
6402 #if !BB_MMU
6403         G.argv0_for_re_execing = argv[0];
6404 #endif
6405         /* Deal with HUSH_VERSION */
6406         G.shell_ver = const_shell_ver; /* copying struct here */
6407         G.top_var = &G.shell_ver;
6408         debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
6409         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6410         /* Initialize our shell local variables with the values
6411          * currently living in the environment */
6412         cur_var = G.top_var;
6413         e = environ;
6414         if (e) while (*e) {
6415                 char *value = strchr(*e, '=');
6416                 if (value) { /* paranoia */
6417                         cur_var->next = xzalloc(sizeof(*cur_var));
6418                         cur_var = cur_var->next;
6419                         cur_var->varstr = *e;
6420                         cur_var->max_len = strlen(*e);
6421                         cur_var->flg_export = 1;
6422                 }
6423                 e++;
6424         }
6425         debug_printf_env("putenv '%s'\n", hush_version_str);
6426         putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
6427 #if ENABLE_FEATURE_EDITING
6428         G.line_input_state = new_line_input_t(FOR_SHELL);
6429 #endif
6430         G.global_argc = argc;
6431         G.global_argv = argv;
6432         /* Initialize some more globals to non-zero values */
6433         cmdedit_update_prompt();
6434
6435         if (setjmp(die_jmp)) {
6436                 /* xfunc has failed! die die die */
6437                 /* no EXIT traps, this is an escape hatch! */
6438                 G.exiting = 1;
6439                 hush_exit(xfunc_error_retval);
6440         }
6441
6442         /* Shell is non-interactive at first. We need to call
6443          * block_signals(0) if we are going to execute "sh <script>",
6444          * "sh -c <cmds>" or login shell's /etc/profile and friends.
6445          * If we later decide that we are interactive, we run block_signals(0)
6446          * (or re-run block_signals(1) if we ran block_signals(0) before)
6447          * in order to intercept (more) signals.
6448          */
6449
6450         /* Parse options */
6451         /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
6452         builtin_argc = 0;
6453         while (1) {
6454                 opt = getopt(argc, argv, "c:xins"
6455 #if !BB_MMU
6456                                 "<:$:R:V:"
6457 # if ENABLE_HUSH_FUNCTIONS
6458                                 "F:"
6459 # endif
6460 #endif
6461                 );
6462                 if (opt <= 0)
6463                         break;
6464                 switch (opt) {
6465                 case 'c':
6466                         /* Possibilities:
6467                          * sh ... -c 'script'
6468                          * sh ... -c 'script' ARG0 [ARG1...]
6469                          * On NOMMU, if builtin_argc != 0,
6470                          * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6471                          * "" needs to be replaced with NULL
6472                          * and BARGV vector fed to builtin function.
6473                          * Note: this form never happens:
6474                          * sh ... -c 'builtin' [BARGV...] ""
6475                          */
6476                         if (!G.root_pid)
6477                                 G.root_pid = getpid();
6478                         G.global_argv = argv + optind;
6479                         G.global_argc = argc - optind;
6480                         if (builtin_argc) {
6481                                 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6482                                 const struct built_in_command *x;
6483
6484                                 block_signals(0); /* 0: called 1st time */
6485                                 x = find_builtin(optarg);
6486                                 if (x) { /* paranoia */
6487                                         G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6488                                         G.global_argv += builtin_argc;
6489                                         G.global_argv[-1] = NULL; /* replace "" */
6490                                         G.last_exitcode = x->function(argv + optind - 1);
6491                                 }
6492                                 goto final_return;
6493                         }
6494                         if (!G.global_argv[0]) {
6495                                 /* -c 'script' (no params): prevent empty $0 */
6496                                 G.global_argv--; /* points to argv[i] of 'script' */
6497                                 G.global_argv[0] = argv[0];
6498                                 G.global_argc--;
6499                         } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
6500                         block_signals(0); /* 0: called 1st time */
6501                         parse_and_run_string(optarg);
6502                         goto final_return;
6503                 case 'i':
6504                         /* Well, we cannot just declare interactiveness,
6505                          * we have to have some stuff (ctty, etc) */
6506                         /* G_interactive_fd++; */
6507                         break;
6508                 case 's':
6509                         /* "-s" means "read from stdin", but this is how we always
6510                          * operate, so simply do nothing here. */
6511                         break;
6512 #if !BB_MMU
6513                 case '<': /* "big heredoc" support */
6514                         full_write(STDOUT_FILENO, optarg, strlen(optarg));
6515                         _exit(0);
6516                 case '$':
6517                         G.root_pid = bb_strtou(optarg, &optarg, 16);
6518                         optarg++;
6519                         G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6520                         optarg++;
6521                         G.last_exitcode = bb_strtou(optarg, &optarg, 16);
6522                         optarg++;
6523                         builtin_argc = bb_strtou(optarg, &optarg, 16);
6524 # if ENABLE_HUSH_LOOPS
6525                         optarg++;
6526                         G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
6527 # endif
6528                         break;
6529                 case 'R':
6530                 case 'V':
6531                         set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
6532                         break;
6533 # if ENABLE_HUSH_FUNCTIONS
6534                 case 'F': {
6535                         struct function *funcp = new_function(optarg);
6536                         /* funcp->name is already set to optarg */
6537                         /* funcp->body is set to NULL. It's a special case. */
6538                         funcp->body_as_string = argv[optind];
6539                         optind++;
6540                         break;
6541                 }
6542 # endif
6543 #endif
6544                 case 'n':
6545                 case 'x':
6546                         if (!set_mode('-', opt))
6547                                 break;
6548                 default:
6549 #ifndef BB_VER
6550                         fprintf(stderr, "Usage: sh [FILE]...\n"
6551                                         "   or: sh -c command [args]...\n\n");
6552                         exit(EXIT_FAILURE);
6553 #else
6554                         bb_show_usage();
6555 #endif
6556                 }
6557         } /* option parsing loop */
6558
6559         if (!G.root_pid)
6560                 G.root_pid = getpid();
6561
6562         /* If we are login shell... */
6563         if (argv[0] && argv[0][0] == '-') {
6564                 FILE *input;
6565                 debug_printf("sourcing /etc/profile\n");
6566                 input = fopen_for_read("/etc/profile");
6567                 if (input != NULL) {
6568                         close_on_exec_on(fileno(input));
6569                         block_signals(0); /* 0: called 1st time */
6570                         signal_mask_is_inited = 1;
6571                         parse_and_run_file(input);
6572                         fclose(input);
6573                 }
6574                 /* bash: after sourcing /etc/profile,
6575                  * tries to source (in the given order):
6576                  * ~/.bash_profile, ~/.bash_login, ~/.profile,
6577                  * stopping on first found. --noprofile turns this off.
6578                  * bash also sources ~/.bash_logout on exit.
6579                  * If called as sh, skips .bash_XXX files.
6580                  */
6581         }
6582
6583         if (argv[optind]) {
6584                 FILE *input;
6585                 /*
6586                  * "bash <script>" (which is never interactive (unless -i?))
6587                  * sources $BASH_ENV here (without scanning $PATH).
6588                  * If called as sh, does the same but with $ENV.
6589                  */
6590                 debug_printf("running script '%s'\n", argv[optind]);
6591                 G.global_argv = argv + optind;
6592                 G.global_argc = argc - optind;
6593                 input = xfopen_for_read(argv[optind]);
6594                 close_on_exec_on(fileno(input));
6595                 if (!signal_mask_is_inited)
6596                         block_signals(0); /* 0: called 1st time */
6597                 parse_and_run_file(input);
6598 #if ENABLE_FEATURE_CLEAN_UP
6599                 fclose(input);
6600 #endif
6601                 goto final_return;
6602         }
6603
6604         /* Up to here, shell was non-interactive. Now it may become one.
6605          * NB: don't forget to (re)run block_signals(0/1) as needed.
6606          */
6607
6608         /* A shell is interactive if the '-i' flag was given,
6609          * or if all of the following conditions are met:
6610          *    no -c command
6611          *    no arguments remaining or the -s flag given
6612          *    standard input is a terminal
6613          *    standard output is a terminal
6614          * Refer to Posix.2, the description of the 'sh' utility.
6615          */
6616 #if ENABLE_HUSH_JOB
6617         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6618                 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6619                 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6620                 if (G_saved_tty_pgrp < 0)
6621                         G_saved_tty_pgrp = 0;
6622
6623                 /* try to dup stdin to high fd#, >= 255 */
6624                 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6625                 if (G_interactive_fd < 0) {
6626                         /* try to dup to any fd */
6627                         G_interactive_fd = dup(STDIN_FILENO);
6628                         if (G_interactive_fd < 0) {
6629                                 /* give up */
6630                                 G_interactive_fd = 0;
6631                                 G_saved_tty_pgrp = 0;
6632                         }
6633                 }
6634 // TODO: track & disallow any attempts of user
6635 // to (inadvertently) close/redirect G_interactive_fd
6636         }
6637         debug_printf("interactive_fd:%d\n", G_interactive_fd);
6638         if (G_interactive_fd) {
6639                 close_on_exec_on(G_interactive_fd);
6640
6641                 if (G_saved_tty_pgrp) {
6642                         /* If we were run as 'hush &', sleep until we are
6643                          * in the foreground (tty pgrp == our pgrp).
6644                          * If we get started under a job aware app (like bash),
6645                          * make sure we are now in charge so we don't fight over
6646                          * who gets the foreground */
6647                         while (1) {
6648                                 pid_t shell_pgrp = getpgrp();
6649                                 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6650                                 if (G_saved_tty_pgrp == shell_pgrp)
6651                                         break;
6652                                 /* send TTIN to ourself (should stop us) */
6653                                 kill(- shell_pgrp, SIGTTIN);
6654                         }
6655                 }
6656
6657                 /* Block some signals */
6658                 block_signals(signal_mask_is_inited);
6659
6660                 if (G_saved_tty_pgrp) {
6661                         /* Set other signals to restore saved_tty_pgrp */
6662                         set_fatal_handlers();
6663                         /* Put ourselves in our own process group
6664                          * (bash, too, does this only if ctty is available) */
6665                         bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6666                         /* Grab control of the terminal */
6667                         tcsetpgrp(G_interactive_fd, getpid());
6668                 }
6669                 /* -1 is special - makes xfuncs longjmp, not exit
6670                  * (we reset die_sleep = 0 whereever we [v]fork) */
6671                 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
6672         } else if (!signal_mask_is_inited) {
6673                 block_signals(0); /* 0: called 1st time */
6674         } /* else: block_signals(0) was done before */
6675 #elif ENABLE_HUSH_INTERACTIVE
6676         /* No job control compiled in, only prompt/line editing */
6677         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
6678                 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6679                 if (G_interactive_fd < 0) {
6680                         /* try to dup to any fd */
6681                         G_interactive_fd = dup(STDIN_FILENO);
6682                         if (G_interactive_fd < 0)
6683                                 /* give up */
6684                                 G_interactive_fd = 0;
6685                 }
6686         }
6687         if (G_interactive_fd) {
6688                 close_on_exec_on(G_interactive_fd);
6689                 block_signals(signal_mask_is_inited);
6690         } else if (!signal_mask_is_inited) {
6691                 block_signals(0);
6692         }
6693 #else
6694         /* We have interactiveness code disabled */
6695         if (!signal_mask_is_inited) {
6696                 block_signals(0);
6697         }
6698 #endif
6699         /* bash:
6700          * if interactive but not a login shell, sources ~/.bashrc
6701          * (--norc turns this off, --rcfile <file> overrides)
6702          */
6703
6704         if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6705                 printf("\n\n%s hush - the humble shell\n", bb_banner);
6706                 if (ENABLE_HUSH_HELP)
6707                         puts("Enter 'help' for a list of built-in commands.");
6708                 puts("");
6709         }
6710
6711         parse_and_run_file(stdin);
6712
6713  final_return:
6714 #if ENABLE_FEATURE_CLEAN_UP
6715         if (G.cwd != bb_msg_unknown)
6716                 free((char*)G.cwd);
6717         cur_var = G.top_var->next;
6718         while (cur_var) {
6719                 struct variable *tmp = cur_var;
6720                 if (!cur_var->max_len)
6721                         free(cur_var->varstr);
6722                 cur_var = cur_var->next;
6723                 free(tmp);
6724         }
6725 #endif
6726         hush_exit(G.last_exitcode);
6727 }
6728
6729
6730 #if ENABLE_LASH
6731 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6732 int lash_main(int argc, char **argv)
6733 {
6734         //bb_error_msg("lash is deprecated, please use hush instead");
6735         return hush_main(argc, argv);
6736 }
6737 #endif
6738
6739
6740 /*
6741  * Built-ins
6742  */
6743 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
6744 {
6745         return 0;
6746 }
6747
6748 static int FAST_FUNC builtin_test(char **argv)
6749 {
6750         int argc = 0;
6751         while (*argv) {
6752                 argc++;
6753                 argv++;
6754         }
6755         return test_main(argc, argv - argc);
6756 }
6757
6758 static int FAST_FUNC builtin_echo(char **argv)
6759 {
6760         int argc = 0;
6761         while (*argv) {
6762                 argc++;
6763                 argv++;
6764         }
6765         return echo_main(argc, argv - argc);
6766 }
6767
6768 static int FAST_FUNC builtin_eval(char **argv)
6769 {
6770         int rcode = EXIT_SUCCESS;
6771
6772         if (*++argv) {
6773                 char *str = expand_strvec_to_string(argv);
6774                 /* bash:
6775                  * eval "echo Hi; done" ("done" is syntax error):
6776                  * "echo Hi" will not execute too.
6777                  */
6778                 parse_and_run_string(str);
6779                 free(str);
6780                 rcode = G.last_exitcode;
6781         }
6782         return rcode;
6783 }
6784
6785 static int FAST_FUNC builtin_cd(char **argv)
6786 {
6787         const char *newdir = argv[1];
6788         if (newdir == NULL) {
6789                 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6790                  * bash says "bash: cd: HOME not set" and does nothing
6791                  * (exitcode 1)
6792                  */
6793                 newdir = get_local_var_value("HOME") ? : "/";
6794         }
6795         if (chdir(newdir)) {
6796                 /* Mimic bash message exactly */
6797                 bb_perror_msg("cd: %s", newdir);
6798                 return EXIT_FAILURE;
6799         }
6800         get_cwd(1);
6801         return EXIT_SUCCESS;
6802 }
6803
6804 static int FAST_FUNC builtin_exec(char **argv)
6805 {
6806         if (*++argv == NULL)
6807                 return EXIT_SUCCESS; /* bash does this */
6808         {
6809 #if !BB_MMU
6810                 nommu_save_t dummy;
6811 #endif
6812                 /* TODO: if exec fails, bash does NOT exit! We do... */
6813                 pseudo_exec_argv(&dummy, argv, 0, NULL);
6814                 /* never returns */
6815         }
6816 }
6817
6818 static int FAST_FUNC builtin_exit(char **argv)
6819 {
6820         debug_printf_exec("%s()\n", __func__);
6821
6822         /* interactive bash:
6823          * # trap "echo EEE" EXIT
6824          * # exit
6825          * exit
6826          * There are stopped jobs.
6827          * (if there are _stopped_ jobs, running ones don't count)
6828          * # exit
6829          * exit
6830          # EEE (then bash exits)
6831          *
6832          * we can use G.exiting = -1 as indicator "last cmd was exit"
6833          */
6834
6835         /* note: EXIT trap is run by hush_exit */
6836         if (*++argv == NULL)
6837                 hush_exit(G.last_exitcode);
6838         /* mimic bash: exit 123abc == exit 255 + error msg */
6839         xfunc_error_retval = 255;
6840         /* bash: exit -2 == exit 254, no error msg */
6841         hush_exit(xatoi(*argv) & 0xff);
6842 }
6843
6844 static void print_escaped(const char *s)
6845 {
6846         if (*s == '\'')
6847                 goto squote;
6848         do {
6849                 const char *p = strchrnul(s, '\'');
6850                 /* print 'xxxx', possibly just '' */
6851                 printf("'%.*s'", (int)(p - s), s);
6852                 if (*p == '\0')
6853                         break;
6854                 s = p;
6855  squote:
6856                 /* s points to '; print "'''...'''" */
6857                 putchar('"');
6858                 do putchar('\''); while (*++s == '\'');
6859                 putchar('"');
6860         } while (*s);
6861 }
6862
6863 #if !ENABLE_HUSH_LOCAL
6864 #define helper_export_local(argv, exp, lvl) \
6865         helper_export_local(argv, exp)
6866 #endif
6867 static void helper_export_local(char **argv, int exp, int lvl)
6868 {
6869         do {
6870                 char *name = *argv;
6871
6872                 /* So far we do not check that name is valid (TODO?) */
6873
6874                 if (strchr(name, '=') == NULL) {
6875                         struct variable *var;
6876
6877                         var = get_local_var(name);
6878                         if (exp == -1) { /* unexporting? */
6879                                 /* export -n NAME (without =VALUE) */
6880                                 if (var) {
6881                                         var->flg_export = 0;
6882                                         debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6883                                         unsetenv(name);
6884                                 } /* else: export -n NOT_EXISTING_VAR: no-op */
6885                                 continue;
6886                         }
6887                         if (exp == 1) { /* exporting? */
6888                                 /* export NAME (without =VALUE) */
6889                                 if (var) {
6890                                         var->flg_export = 1;
6891                                         debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6892                                         putenv(var->varstr);
6893                                         continue;
6894                                 }
6895                         }
6896                         /* Exporting non-existing variable.
6897                          * bash does not put it in environment,
6898                          * but remembers that it is exported,
6899                          * and does put it in env when it is set later.
6900                          * We just set it to "" and export. */
6901                         /* Or, it's "local NAME" (without =VALUE).
6902                          * bash sets the value to "". */
6903                         name = xasprintf("%s=", name);
6904                 } else {
6905                         /* (Un)exporting/making local NAME=VALUE */
6906                         name = xstrdup(name);
6907                 }
6908                 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6909         } while (*++argv);
6910 }
6911
6912 static int FAST_FUNC builtin_export(char **argv)
6913 {
6914         unsigned opt_unexport;
6915
6916 #if ENABLE_HUSH_EXPORT_N
6917         /* "!": do not abort on errors */
6918         opt_unexport = getopt32(argv, "!n");
6919         if (opt_unexport == (uint32_t)-1)
6920                 return EXIT_FAILURE;
6921         argv += optind;
6922 #else
6923         opt_unexport = 0;
6924         argv++;
6925 #endif
6926
6927         if (argv[0] == NULL) {
6928                 char **e = environ;
6929                 if (e) {
6930                         while (*e) {
6931 #if 0
6932                                 puts(*e++);
6933 #else
6934                                 /* ash emits: export VAR='VAL'
6935                                  * bash: declare -x VAR="VAL"
6936                                  * we follow ash example */
6937                                 const char *s = *e++;
6938                                 const char *p = strchr(s, '=');
6939
6940                                 if (!p) /* wtf? take next variable */
6941                                         continue;
6942                                 /* export var= */
6943                                 printf("export %.*s", (int)(p - s) + 1, s);
6944                                 print_escaped(p + 1);
6945                                 putchar('\n');
6946 #endif
6947                         }
6948                         /*fflush(stdout); - done after each builtin anyway */
6949                 }
6950                 return EXIT_SUCCESS;
6951         }
6952
6953         helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
6954
6955         return EXIT_SUCCESS;
6956 }
6957
6958 #if ENABLE_HUSH_LOCAL
6959 static int FAST_FUNC builtin_local(char **argv)
6960 {
6961         if (G.func_nest_level == 0) {
6962                 bb_error_msg("%s: not in a function", argv[0]);
6963                 return EXIT_FAILURE; /* bash compat */
6964         }
6965         helper_export_local(argv, 0, G.func_nest_level);
6966         return EXIT_SUCCESS;
6967 }
6968 #endif
6969
6970 static int FAST_FUNC builtin_trap(char **argv)
6971 {
6972         int sig;
6973         char *new_cmd;
6974
6975         if (!G.traps)
6976                 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6977
6978         argv++;
6979         if (!*argv) {
6980                 int i;
6981                 /* No args: print all trapped */
6982                 for (i = 0; i < NSIG; ++i) {
6983                         if (G.traps[i]) {
6984                                 printf("trap -- ");
6985                                 print_escaped(G.traps[i]);
6986                                 printf(" %s\n", get_signame(i));
6987                         }
6988                 }
6989                 /*fflush(stdout); - done after each builtin anyway */
6990                 return EXIT_SUCCESS;
6991         }
6992
6993         new_cmd = NULL;
6994         /* If first arg is a number: reset all specified signals */
6995         sig = bb_strtou(*argv, NULL, 10);
6996         if (errno == 0) {
6997                 int ret;
6998  process_sig_list:
6999                 ret = EXIT_SUCCESS;
7000                 while (*argv) {
7001                         sig = get_signum(*argv++);
7002                         if (sig < 0 || sig >= NSIG) {
7003                                 ret = EXIT_FAILURE;
7004                                 /* Mimic bash message exactly */
7005                                 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7006                                 continue;
7007                         }
7008
7009                         free(G.traps[sig]);
7010                         G.traps[sig] = xstrdup(new_cmd);
7011
7012                         debug_printf("trap: setting SIG%s (%i) to '%s'",
7013                                 get_signame(sig), sig, G.traps[sig]);
7014
7015                         /* There is no signal for 0 (EXIT) */
7016                         if (sig == 0)
7017                                 continue;
7018
7019                         if (new_cmd) {
7020                                 sigaddset(&G.blocked_set, sig);
7021                         } else {
7022                                 /* There was a trap handler, we are removing it
7023                                  * (if sig has non-DFL handling,
7024                                  * we don't need to do anything) */
7025                                 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7026                                         continue;
7027                                 sigdelset(&G.blocked_set, sig);
7028                         }
7029                 }
7030                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7031                 return ret;
7032         }
7033
7034         if (!argv[1]) { /* no second arg */
7035                 bb_error_msg("trap: invalid arguments");
7036                 return EXIT_FAILURE;
7037         }
7038
7039         /* First arg is "-": reset all specified to default */
7040         /* First arg is "--": skip it, the rest is "handler SIGs..." */
7041         /* Everything else: set arg as signal handler
7042          * (includes "" case, which ignores signal) */
7043         if (argv[0][0] == '-') {
7044                 if (argv[0][1] == '\0') { /* "-" */
7045                         /* new_cmd remains NULL: "reset these sigs" */
7046                         goto reset_traps;
7047                 }
7048                 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7049                         argv++;
7050                 }
7051                 /* else: "-something", no special meaning */
7052         }
7053         new_cmd = *argv;
7054  reset_traps:
7055         argv++;
7056         goto process_sig_list;
7057 }
7058
7059 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7060 static int FAST_FUNC builtin_type(char **argv)
7061 {
7062         int ret = EXIT_SUCCESS;
7063
7064         while (*++argv) {
7065                 const char *type;
7066                 char *path = NULL;
7067
7068                 if (0) {} /* make conditional compile easier below */
7069                 /*else if (find_alias(*argv))
7070                         type = "an alias";*/
7071 #if ENABLE_HUSH_FUNCTIONS
7072                 else if (find_function(*argv))
7073                         type = "a function";
7074 #endif
7075                 else if (find_builtin(*argv))
7076                         type = "a shell builtin";
7077                 else if ((path = find_in_path(*argv)) != NULL)
7078                         type = path;
7079                 else {
7080                         bb_error_msg("type: %s: not found", *argv);
7081                         ret = EXIT_FAILURE;
7082                         continue;
7083                 }
7084
7085                 printf("%s is %s\n", *argv, type);
7086                 free(path);
7087         }
7088
7089         return ret;
7090 }
7091
7092 #if ENABLE_HUSH_JOB
7093 /* built-in 'fg' and 'bg' handler */
7094 static int FAST_FUNC builtin_fg_bg(char **argv)
7095 {
7096         int i, jobnum;
7097         struct pipe *pi;
7098
7099         if (!G_interactive_fd)
7100                 return EXIT_FAILURE;
7101
7102         /* If they gave us no args, assume they want the last backgrounded task */
7103         if (!argv[1]) {
7104                 for (pi = G.job_list; pi; pi = pi->next) {
7105                         if (pi->jobid == G.last_jobid) {
7106                                 goto found;
7107                         }
7108                 }
7109                 bb_error_msg("%s: no current job", argv[0]);
7110                 return EXIT_FAILURE;
7111         }
7112         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7113                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7114                 return EXIT_FAILURE;
7115         }
7116         for (pi = G.job_list; pi; pi = pi->next) {
7117                 if (pi->jobid == jobnum) {
7118                         goto found;
7119                 }
7120         }
7121         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7122         return EXIT_FAILURE;
7123  found:
7124         /* TODO: bash prints a string representation
7125          * of job being foregrounded (like "sleep 1 | cat") */
7126         if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7127                 /* Put the job into the foreground.  */
7128                 tcsetpgrp(G_interactive_fd, pi->pgrp);
7129         }
7130
7131         /* Restart the processes in the job */
7132         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7133         for (i = 0; i < pi->num_cmds; i++) {
7134                 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7135                 pi->cmds[i].is_stopped = 0;
7136         }
7137         pi->stopped_cmds = 0;
7138
7139         i = kill(- pi->pgrp, SIGCONT);
7140         if (i < 0) {
7141                 if (errno == ESRCH) {
7142                         delete_finished_bg_job(pi);
7143                         return EXIT_SUCCESS;
7144                 }
7145                 bb_perror_msg("kill (SIGCONT)");
7146         }
7147
7148         if (argv[0][0] == 'f') {
7149                 remove_bg_job(pi);
7150                 return checkjobs_and_fg_shell(pi);
7151         }
7152         return EXIT_SUCCESS;
7153 }
7154 #endif
7155
7156 #if ENABLE_HUSH_HELP
7157 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7158 {
7159         const struct built_in_command *x;
7160
7161         printf(
7162                 "Built-in commands:\n"
7163                 "------------------\n");
7164         for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7165                 if (x->descr)
7166                         printf("%s\t%s\n", x->cmd, x->descr);
7167         }
7168         bb_putchar('\n');
7169         return EXIT_SUCCESS;
7170 }
7171 #endif
7172
7173 #if ENABLE_HUSH_JOB
7174 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
7175 {
7176         struct pipe *job;
7177         const char *status_string;
7178
7179         for (job = G.job_list; job; job = job->next) {
7180                 if (job->alive_cmds == job->stopped_cmds)
7181                         status_string = "Stopped";
7182                 else
7183                         status_string = "Running";
7184
7185                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7186         }
7187         return EXIT_SUCCESS;
7188 }
7189 #endif
7190
7191 #if HUSH_DEBUG
7192 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
7193 {
7194         void *p;
7195         unsigned long l;
7196
7197         /* Crude attempt to find where "free memory" starts,
7198          * sans fragmentation. */
7199         p = malloc(240);
7200         l = (unsigned long)p;
7201         free(p);
7202         p = malloc(3400);
7203         if (l < (unsigned long)p) l = (unsigned long)p;
7204         free(p);
7205
7206         if (!G.memleak_value)
7207                 G.memleak_value = l;
7208         
7209         l -= G.memleak_value;
7210         if ((long)l < 0)
7211                 l = 0;
7212         l /= 1024;
7213         if (l > 127)
7214                 l = 127;
7215
7216         /* Exitcode is "how many kilobytes we leaked since 1st call" */
7217         return l;
7218 }
7219 #endif
7220
7221 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
7222 {
7223         puts(get_cwd(0));
7224         return EXIT_SUCCESS;
7225 }
7226
7227 static int FAST_FUNC builtin_read(char **argv)
7228 {
7229         char *string;
7230         const char *name = "REPLY";
7231
7232         if (argv[1]) {
7233                 name = argv[1];
7234                 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7235                  * and _after_ that_ it will complain */
7236                 if (!is_well_formed_var_name(name, '\0')) {
7237                         /* Mimic bash message */
7238                         bb_error_msg("read: '%s': not a valid identifier", name);
7239                         return 1;
7240                 }
7241         }
7242
7243 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
7244
7245         string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
7246         return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7247 }
7248
7249 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7250  * built-in 'set' handler
7251  * SUSv3 says:
7252  * set [-abCefhmnuvx] [-o option] [argument...]
7253  * set [+abCefhmnuvx] [+o option] [argument...]
7254  * set -- [argument...]
7255  * set -o
7256  * set +o
7257  * Implementations shall support the options in both their hyphen and
7258  * plus-sign forms. These options can also be specified as options to sh.
7259  * Examples:
7260  * Write out all variables and their values: set
7261  * Set $1, $2, and $3 and set "$#" to 3: set c a b
7262  * Turn on the -x and -v options: set -xv
7263  * Unset all positional parameters: set --
7264  * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7265  * Set the positional parameters to the expansion of x, even if x expands
7266  * with a leading '-' or '+': set -- $x
7267  *
7268  * So far, we only support "set -- [argument...]" and some of the short names.
7269  */
7270 static int FAST_FUNC builtin_set(char **argv)
7271 {
7272         int n;
7273         char **pp, **g_argv;
7274         char *arg = *++argv;
7275
7276         if (arg == NULL) {
7277                 struct variable *e;
7278                 for (e = G.top_var; e; e = e->next)
7279                         puts(e->varstr);
7280                 return EXIT_SUCCESS;
7281         }
7282
7283         do {
7284                 if (!strcmp(arg, "--")) {
7285                         ++argv;
7286                         goto set_argv;
7287                 }
7288                 if (arg[0] != '+' && arg[0] != '-')
7289                         break;
7290                 for (n = 1; arg[n]; ++n)
7291                         if (set_mode(arg[0], arg[n]))
7292                                 goto error;
7293         } while ((arg = *++argv) != NULL);
7294         /* Now argv[0] is 1st argument */
7295
7296         if (arg == NULL)
7297                 return EXIT_SUCCESS;
7298  set_argv:
7299
7300         /* NB: G.global_argv[0] ($0) is never freed/changed */
7301         g_argv = G.global_argv;
7302         if (G.global_args_malloced) {
7303                 pp = g_argv;
7304                 while (*++pp)
7305                         free(*pp);
7306                 g_argv[1] = NULL;
7307         } else {
7308                 G.global_args_malloced = 1;
7309                 pp = xzalloc(sizeof(pp[0]) * 2);
7310                 pp[0] = g_argv[0]; /* retain $0 */
7311                 g_argv = pp;
7312         }
7313         /* This realloc's G.global_argv */
7314         G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7315
7316         n = 1;
7317         while (*++pp)
7318                 n++;
7319         G.global_argc = n;
7320
7321         return EXIT_SUCCESS;
7322
7323         /* Nothing known, so abort */
7324  error:
7325         bb_error_msg("set: %s: invalid option", arg);
7326         return EXIT_FAILURE;
7327 }
7328
7329 static int FAST_FUNC builtin_shift(char **argv)
7330 {
7331         int n = 1;
7332         if (argv[1]) {
7333                 n = atoi(argv[1]);
7334         }
7335         if (n >= 0 && n < G.global_argc) {
7336                 if (G.global_args_malloced) {
7337                         int m = 1;
7338                         while (m <= n)
7339                                 free(G.global_argv[m++]);
7340                 }
7341                 G.global_argc -= n;
7342                 memmove(&G.global_argv[1], &G.global_argv[n+1],
7343                                 G.global_argc * sizeof(G.global_argv[0]));
7344                 return EXIT_SUCCESS;
7345         }
7346         return EXIT_FAILURE;
7347 }
7348
7349 static int FAST_FUNC builtin_source(char **argv)
7350 {
7351         char *arg_path;
7352         FILE *input;
7353         save_arg_t sv;
7354 #if ENABLE_HUSH_FUNCTIONS
7355         smallint sv_flg;
7356 #endif
7357
7358         if (*++argv == NULL)
7359                 return EXIT_FAILURE;
7360
7361         if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7362                 input = fopen_for_read(arg_path);
7363                 free(arg_path);
7364         } else
7365                 input = fopen_or_warn(*argv, "r");
7366         if (!input) {
7367                 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
7368                 return EXIT_FAILURE;
7369         }
7370         close_on_exec_on(fileno(input));
7371
7372 #if ENABLE_HUSH_FUNCTIONS
7373         sv_flg = G.flag_return_in_progress;
7374         /* "we are inside sourced file, ok to use return" */
7375         G.flag_return_in_progress = -1;
7376 #endif
7377         save_and_replace_G_args(&sv, argv);
7378
7379         parse_and_run_file(input);
7380         fclose(input);
7381
7382         restore_G_args(&sv, argv);
7383 #if ENABLE_HUSH_FUNCTIONS
7384         G.flag_return_in_progress = sv_flg;
7385 #endif
7386
7387         return G.last_exitcode;
7388 }
7389
7390 static int FAST_FUNC builtin_umask(char **argv)
7391 {
7392         int rc;
7393         mode_t mask;
7394
7395         mask = umask(0);
7396         if (argv[1]) {
7397                 mode_t old_mask = mask;
7398
7399                 mask ^= 0777;
7400                 rc = bb_parse_mode(argv[1], &mask);
7401                 mask ^= 0777;
7402                 if (rc == 0) {
7403                         mask = old_mask;
7404                         /* bash messages:
7405                          * bash: umask: 'q': invalid symbolic mode operator
7406                          * bash: umask: 999: octal number out of range
7407                          */
7408                         bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
7409                 }
7410         } else {
7411                 rc = 1;
7412                 /* Mimic bash */
7413                 printf("%04o\n", (unsigned) mask);
7414                 /* fall through and restore mask which we set to 0 */
7415         }
7416         umask(mask);
7417
7418         return !rc; /* rc != 0 - success */
7419 }
7420
7421 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
7422 static int FAST_FUNC builtin_unset(char **argv)
7423 {
7424         int ret;
7425         unsigned opts;
7426
7427         /* "!": do not abort on errors */
7428         /* "+": stop at 1st non-option */
7429         opts = getopt32(argv, "!+vf");
7430         if (opts == (unsigned)-1)
7431                 return EXIT_FAILURE;
7432         if (opts == 3) {
7433                 bb_error_msg("unset: -v and -f are exclusive");
7434                 return EXIT_FAILURE;
7435         }
7436         argv += optind;
7437
7438         ret = EXIT_SUCCESS;
7439         while (*argv) {
7440                 if (!(opts & 2)) { /* not -f */
7441                         if (unset_local_var(*argv)) {
7442                                 /* unset <nonexistent_var> doesn't fail.
7443                                  * Error is when one tries to unset RO var.
7444                                  * Message was printed by unset_local_var. */
7445                                 ret = EXIT_FAILURE;
7446                         }
7447                 }
7448 #if ENABLE_HUSH_FUNCTIONS
7449                 else {
7450                         unset_func(*argv);
7451                 }
7452 #endif
7453                 argv++;
7454         }
7455         return ret;
7456 }
7457
7458 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7459 static int FAST_FUNC builtin_wait(char **argv)
7460 {
7461         int ret = EXIT_SUCCESS;
7462         int status, sig;
7463
7464         if (*++argv == NULL) {
7465                 /* Don't care about wait results */
7466                 /* Note 1: must wait until there are no more children */
7467                 /* Note 2: must be interruptible */
7468                 /* Examples:
7469                  * $ sleep 3 & sleep 6 & wait
7470                  * [1] 30934 sleep 3
7471                  * [2] 30935 sleep 6
7472                  * [1] Done                   sleep 3
7473                  * [2] Done                   sleep 6
7474                  * $ sleep 3 & sleep 6 & wait
7475                  * [1] 30936 sleep 3
7476                  * [2] 30937 sleep 6
7477                  * [1] Done                   sleep 3
7478                  * ^C <-- after ~4 sec from keyboard
7479                  * $
7480                  */
7481                 sigaddset(&G.blocked_set, SIGCHLD);
7482                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7483                 while (1) {
7484                         checkjobs(NULL);
7485                         if (errno == ECHILD)
7486                                 break;
7487                         /* Wait for SIGCHLD or any other signal of interest */
7488                         /* sigtimedwait with infinite timeout: */
7489                         sig = sigwaitinfo(&G.blocked_set, NULL);
7490                         if (sig > 0) {
7491                                 sig = check_and_run_traps(sig);
7492                                 if (sig && sig != SIGCHLD) { /* see note 2 */
7493                                         ret = 128 + sig;
7494                                         break;
7495                                 }
7496                         }
7497                 }
7498                 sigdelset(&G.blocked_set, SIGCHLD);
7499                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7500                 return ret;
7501         }
7502
7503         /* This is probably buggy wrt interruptible-ness */
7504         while (*argv) {
7505                 pid_t pid = bb_strtou(*argv, NULL, 10);
7506                 if (errno) {
7507                         /* mimic bash message */
7508                         bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
7509                         return EXIT_FAILURE;
7510                 }
7511                 if (waitpid(pid, &status, 0) == pid) {
7512                         if (WIFSIGNALED(status))
7513                                 ret = 128 + WTERMSIG(status);
7514                         else if (WIFEXITED(status))
7515                                 ret = WEXITSTATUS(status);
7516                         else /* wtf? */
7517                                 ret = EXIT_FAILURE;
7518                 } else {
7519                         bb_perror_msg("wait %s", *argv);
7520                         ret = 127;
7521                 }
7522                 argv++;
7523         }
7524
7525         return ret;
7526 }
7527
7528 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7529 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7530 {
7531         if (argv[1]) {
7532                 def = bb_strtou(argv[1], NULL, 10);
7533                 if (errno || def < def_min || argv[2]) {
7534                         bb_error_msg("%s: bad arguments", argv[0]);
7535                         def = UINT_MAX;
7536                 }
7537         }
7538         return def;
7539 }
7540 #endif
7541
7542 #if ENABLE_HUSH_LOOPS
7543 static int FAST_FUNC builtin_break(char **argv)
7544 {
7545         unsigned depth;
7546         if (G.depth_of_loop == 0) {
7547                 bb_error_msg("%s: only meaningful in a loop", argv[0]);
7548                 return EXIT_SUCCESS; /* bash compat */
7549         }
7550         G.flag_break_continue++; /* BC_BREAK = 1 */
7551
7552         G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7553         if (depth == UINT_MAX)
7554                 G.flag_break_continue = BC_BREAK;
7555         if (G.depth_of_loop < depth)
7556                 G.depth_break_continue = G.depth_of_loop;
7557
7558         return EXIT_SUCCESS;
7559 }
7560
7561 static int FAST_FUNC builtin_continue(char **argv)
7562 {
7563         G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7564         return builtin_break(argv);
7565 }
7566 #endif
7567
7568 #if ENABLE_HUSH_FUNCTIONS
7569 static int FAST_FUNC builtin_return(char **argv)
7570 {
7571         int rc;
7572
7573         if (G.flag_return_in_progress != -1) {
7574                 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7575                 return EXIT_FAILURE; /* bash compat */
7576         }
7577
7578         G.flag_return_in_progress = 1;
7579
7580         /* bash:
7581          * out of range: wraps around at 256, does not error out
7582          * non-numeric param:
7583          * f() { false; return qwe; }; f; echo $?
7584          * bash: return: qwe: numeric argument required  <== we do this
7585          * 255  <== we also do this
7586          */
7587         rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7588         return rc;
7589 }
7590 #endif