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