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