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