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