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