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