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