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