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