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