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