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