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