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