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