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