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