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