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