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