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