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