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