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