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