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