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