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