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