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