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