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