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