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