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