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