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