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