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