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