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