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