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