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