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