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