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