implement support for parameter substitution via #/% operators
[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  *
47  * Bash stuff (maybe optionally enable?):
48  *      &> and >& redirection of stdout+stderr
49  *      Brace expansion
50  *      reserved words: [[ ]] function select
51  *      substrings ${var:1:5}
52  *
53  * TODOs:
54  *      grep for "TODO" and fix (some of them are easy)
55  *      change { and } from special chars to reserved words
56  *      builtins: return, ulimit
57  *      follow IFS rules more precisely, including update semantics
58  *      figure out what to do with backslash-newline
59  *      continuation lines, both explicit and implicit - done?
60  *      SIGHUP handling
61  *      ^Z handling (and explain it in comments for mere humans)
62  *      separate job control from interactiveness
63  *      (testcase: booting with init=/bin/hush does not show prompt (2009-04))
64  *      functions
65  *
66  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
67  */
68
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
72 #include <glob.h>
73 /* #include <dmalloc.h> */
74 #if ENABLE_HUSH_CASE
75 #include <fnmatch.h>
76 #endif
77 #include "math.h"
78 #include "match.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 *dyn_val, *p;
1671
1672         dyn_val = NULL;
1673         ored_ch = 0;
1674
1675         debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1676         debug_print_list("expand_vars_to_list", output, n);
1677         n = o_save_ptr(output, n);
1678         debug_print_list("expand_vars_to_list[0]", output, n);
1679
1680         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1681 #if ENABLE_HUSH_TICK
1682                 o_string subst_result = NULL_O_STRING;
1683 #endif
1684 #if ENABLE_SH_MATH_SUPPORT
1685                 char arith_buf[sizeof(arith_t)*3 + 2];
1686 #endif
1687                 o_addblock(output, arg, p - arg);
1688                 debug_print_list("expand_vars_to_list[1]", output, n);
1689                 arg = ++p;
1690                 p = strchr(p, SPECIAL_VAR_SYMBOL);
1691
1692                 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1693                 /* "$@" is special. Even if quoted, it can still
1694                  * expand to nothing (not even an empty string) */
1695                 if ((first_ch & 0x7f) != '@')
1696                         ored_ch |= first_ch;
1697
1698                 val = NULL;
1699                 switch (first_ch & 0x7f) {
1700                 /* Highest bit in first_ch indicates that var is double-quoted */
1701                 case '$': /* pid */
1702                         val = utoa(G.root_pid);
1703                         break;
1704                 case '!': /* bg pid */
1705                         val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1706                         break;
1707                 case '?': /* exitcode */
1708                         val = utoa(G.last_exitcode);
1709                         break;
1710                 case '#': /* argc */
1711                         if (arg[1] != SPECIAL_VAR_SYMBOL)
1712                                 /* actually, it's a ${#var} */
1713                                 goto case_default;
1714                         val = utoa(G.global_argc ? G.global_argc-1 : 0);
1715                         break;
1716                 case '*':
1717                 case '@':
1718                         i = 1;
1719                         if (!G.global_argv[i])
1720                                 break;
1721                         ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1722                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1723                                 smallint sv = output->o_escape;
1724                                 /* unquoted var's contents should be globbed, so don't escape */
1725                                 output->o_escape = 0;
1726                                 while (G.global_argv[i]) {
1727                                         n = expand_on_ifs(output, n, G.global_argv[i]);
1728                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1729                                         if (G.global_argv[i++][0] && G.global_argv[i]) {
1730                                                 /* this argv[] is not empty and not last:
1731                                                  * put terminating NUL, start new word */
1732                                                 o_addchr(output, '\0');
1733                                                 debug_print_list("expand_vars_to_list[2]", output, n);
1734                                                 n = o_save_ptr(output, n);
1735                                                 debug_print_list("expand_vars_to_list[3]", output, n);
1736                                         }
1737                                 }
1738                                 output->o_escape = sv;
1739                         } else
1740                         /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1741                          * and in this case should treat it like '$*' - see 'else...' below */
1742                         if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1743                                 while (1) {
1744                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1745                                         if (++i >= G.global_argc)
1746                                                 break;
1747                                         o_addchr(output, '\0');
1748                                         debug_print_list("expand_vars_to_list[4]", output, n);
1749                                         n = o_save_ptr(output, n);
1750                                 }
1751                         } else { /* quoted $*: add as one word */
1752                                 while (1) {
1753                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1754                                         if (!G.global_argv[++i])
1755                                                 break;
1756                                         if (G.ifs[0])
1757                                                 o_addchr(output, G.ifs[0]);
1758                                 }
1759                         }
1760                         break;
1761                 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1762                         /* "Empty variable", used to make "" etc to not disappear */
1763                         arg++;
1764                         ored_ch = 0x80;
1765                         break;
1766 #if ENABLE_HUSH_TICK
1767                 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1768                         *p = '\0';
1769                         arg++;
1770 //TODO: can we just stuff it into "output" directly?
1771                         debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1772                         process_command_subs(&subst_result, arg);
1773                         debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1774                         val = subst_result.data;
1775                         goto store_val;
1776 #endif
1777 #if ENABLE_SH_MATH_SUPPORT
1778                 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1779                         arith_eval_hooks_t hooks;
1780                         arith_t res;
1781                         int errcode;
1782                         char *exp_str;
1783
1784                         arg++; /* skip '+' */
1785                         *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1786                         debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1787
1788                         /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1789                         exp_str = NULL;
1790                         if (strchr(arg, '$') != NULL
1791 #if ENABLE_HUSH_TICK
1792                          || strchr(arg, '`') != NULL
1793 #endif
1794                         ) {
1795                                 /* We need to expand. Example:
1796                                  * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1797                                  */
1798                                 struct in_str input;
1799                                 o_string dest = NULL_O_STRING;
1800
1801                                 setup_string_in_str(&input, arg);
1802                                 parse_stream_dquoted(NULL, &dest, &input, EOF);
1803                                 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1804                                 exp_str = expand_string_to_string(dest.data);
1805                                 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1806                                 o_free_unsafe(&dest);
1807                         }
1808                         hooks.lookupvar = get_local_var_value;
1809                         hooks.setvar = arith_set_local_var;
1810                         hooks.endofname = endofname;
1811                         res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1812                         free(exp_str);
1813
1814                         if (errcode < 0) {
1815                                 switch (errcode) {
1816                                 case -3: maybe_die("arith", "exponent less than 0"); break;
1817                                 case -2: maybe_die("arith", "divide by zero"); break;
1818                                 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1819                                 default: maybe_die("arith", "syntax error"); break;
1820                                 }
1821                         }
1822                         debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1823                         sprintf(arith_buf, arith_t_fmt, res);
1824                         val = arith_buf;
1825                         break;
1826                 }
1827 #endif
1828                 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1829                 case_default: {
1830                         bool exp_len = false;
1831                         bool exp_null = false;
1832                         char *var = arg;
1833                         char exp_save = exp_save; /* for compiler */
1834                         char exp_op = exp_op; /* for compiler */
1835                         char *exp_word = exp_word; /* for compiler */
1836                         size_t exp_off = 0;
1837
1838                         *p = '\0';
1839                         arg[0] = first_ch & 0x7f;
1840
1841                         /* prepare for expansions */
1842                         if (var[0] == '#') {
1843                                 /* handle length expansion ${#var} */
1844                                 exp_len = true;
1845                                 ++var;
1846                         } else {
1847                                 /* maybe handle parameter expansion */
1848                                 exp_off = strcspn(var, ":-=+?%#");
1849                                 if (!var[exp_off])
1850                                         exp_off = 0;
1851                                 if (exp_off) {
1852                                         exp_save = var[exp_off];
1853                                         exp_null = exp_save == ':';
1854                                         exp_word = var + exp_off;
1855                                         if (exp_null) ++exp_word;
1856                                         exp_op = *exp_word++;
1857                                         var[exp_off] = '\0';
1858                                 }
1859                         }
1860
1861                         /* lookup the variable in question */
1862                         if (isdigit(var[0])) {
1863                                 /* handle_dollar() should have vetted var for us */
1864                                 i = xatoi_u(var);
1865                                 if (i < G.global_argc)
1866                                         val = G.global_argv[i];
1867                                 /* else val remains NULL: $N with too big N */
1868                         } else
1869                                 val = get_local_var_value(var);
1870
1871                         /* handle any expansions */
1872                         if (exp_len) {
1873                                 debug_printf_expand("expand: length of '%s' = ", val);
1874                                 val = utoa(val ? strlen(val) : 0);
1875                                 debug_printf_expand("%s\n", val);
1876                         } else if (exp_off) {
1877                                 if (exp_op == '%' || exp_op == '#') {
1878                                         /* we need to do a pattern match */
1879                                         bool zero;
1880                                         char *loc;
1881                                         scan_t scan = pick_scan(exp_op, *exp_word, &zero);
1882                                         if (exp_op == *exp_word)        /* ## or %% */
1883                                                 ++exp_word;
1884                                         val = dyn_val = xstrdup(val);
1885                                         loc = scan(dyn_val, exp_word, zero);
1886                                         if (zero)
1887                                                 val = loc;
1888                                         else
1889                                                 *loc = '\0';
1890                                 } else {
1891                                         /* we need to do an expansion */
1892                                         int exp_test = (!val || (exp_null && !val[0]));
1893                                         if (exp_op == '+')
1894                                                 exp_test = !exp_test;
1895                                         debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1896                                                 exp_null ? "true" : "false", exp_test);
1897                                         if (exp_test) {
1898                                                 if (exp_op == '?')
1899                                                         maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1900                                                 else
1901                                                         val = exp_word;
1902
1903                                                 if (exp_op == '=') {
1904                                                         if (isdigit(var[0]) || var[0] == '#') {
1905                                                                 maybe_die(var, "special vars cannot assign in this way");
1906                                                                 val = NULL;
1907                                                         } else {
1908                                                                 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1909                                                                 sprintf(new_var, "%s=%s", var, val);
1910                                                                 set_local_var(new_var, -1, 0);
1911                                                         }
1912                                                 }
1913                                         }
1914                                 }
1915
1916                                 var[exp_off] = exp_save;
1917                         }
1918
1919                         arg[0] = first_ch;
1920 #if ENABLE_HUSH_TICK
1921  store_val:
1922 #endif
1923                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
1924                                 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1925                                 if (val) {
1926                                         /* unquoted var's contents should be globbed, so don't escape */
1927                                         smallint sv = output->o_escape;
1928                                         output->o_escape = 0;
1929                                         n = expand_on_ifs(output, n, val);
1930                                         val = NULL;
1931                                         output->o_escape = sv;
1932                                 }
1933                         } else { /* quoted $VAR, val will be appended below */
1934                                 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1935                         }
1936                 } /* default: */
1937                 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1938                 if (val) {
1939                         o_addQstr(output, val, strlen(val));
1940                 }
1941                 free(dyn_val);
1942                 dyn_val = NULL;
1943                 /* Do the check to avoid writing to a const string */
1944                 if (*p != SPECIAL_VAR_SYMBOL)
1945                         *p = SPECIAL_VAR_SYMBOL;
1946
1947 #if ENABLE_HUSH_TICK
1948                 o_free(&subst_result);
1949 #endif
1950                 arg = ++p;
1951         } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1952
1953         if (arg[0]) {
1954                 debug_print_list("expand_vars_to_list[a]", output, n);
1955                 /* this part is literal, and it was already pre-quoted
1956                  * if needed (much earlier), do not use o_addQstr here! */
1957                 o_addstr_with_NUL(output, arg);
1958                 debug_print_list("expand_vars_to_list[b]", output, n);
1959         } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1960          && !(ored_ch & 0x80) /* and all vars were not quoted. */
1961         ) {
1962                 n--;
1963                 /* allow to reuse list[n] later without re-growth */
1964                 output->has_empty_slot = 1;
1965         } else {
1966                 o_addchr(output, '\0');
1967         }
1968         return n;
1969 }
1970
1971 static char **expand_variables(char **argv, int or_mask)
1972 {
1973         int n;
1974         char **list;
1975         char **v;
1976         o_string output = NULL_O_STRING;
1977
1978         if (or_mask & 0x100) {
1979                 output.o_escape = 1; /* protect against globbing for "$var" */
1980                 /* (unquoted $var will temporarily switch it off) */
1981                 output.o_glob = 1;
1982         }
1983
1984         n = 0;
1985         v = argv;
1986         while (*v) {
1987                 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1988                 v++;
1989         }
1990         debug_print_list("expand_variables", &output, n);
1991
1992         /* output.data (malloced in one block) gets returned in "list" */
1993         list = o_finalize_list(&output, n);
1994         debug_print_strings("expand_variables[1]", list);
1995         return list;
1996 }
1997
1998 static char **expand_strvec_to_strvec(char **argv)
1999 {
2000         return expand_variables(argv, 0x100);
2001 }
2002
2003 /* Used for expansion of right hand of assignments */
2004 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2005  * "v=/bin/c*" */
2006 static char *expand_string_to_string(const char *str)
2007 {
2008         char *argv[2], **list;
2009
2010         argv[0] = (char*)str;
2011         argv[1] = NULL;
2012         list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2013         if (HUSH_DEBUG)
2014                 if (!list[0] || list[1])
2015                         bb_error_msg_and_die("BUG in varexp2");
2016         /* actually, just move string 2*sizeof(char*) bytes back */
2017         overlapping_strcpy((char*)list, list[0]);
2018         debug_printf_expand("string_to_string='%s'\n", (char*)list);
2019         return (char*)list;
2020 }
2021
2022 /* Used for "eval" builtin */
2023 static char* expand_strvec_to_string(char **argv)
2024 {
2025         char **list;
2026
2027         list = expand_variables(argv, 0x80);
2028         /* Convert all NULs to spaces */
2029         if (list[0]) {
2030                 int n = 1;
2031                 while (list[n]) {
2032                         if (HUSH_DEBUG)
2033                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2034                                         bb_error_msg_and_die("BUG in varexp3");
2035                         list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2036                         n++;
2037                 }
2038         }
2039         overlapping_strcpy((char*)list, list[0]);
2040         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2041         return (char*)list;
2042 }
2043
2044 static char **expand_assignments(char **argv, int count)
2045 {
2046         int i;
2047         char **p = NULL;
2048         /* Expand assignments into one string each */
2049         for (i = 0; i < count; i++) {
2050                 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2051         }
2052         return p;
2053 }
2054
2055
2056 //TODO: fix big string case!
2057 static void setup_heredoc(int fd, const char *heredoc)
2058 {
2059         struct fd_pair pair;
2060         pid_t pid;
2061
2062         xpiped_pair(pair);
2063         pid = vfork();
2064         if (pid < 0)
2065                 bb_perror_msg_and_die("vfork");
2066         if (pid == 0) { /* child */
2067                 die_sleep = 0;
2068                 close(pair.rd);
2069                 xwrite_str(pair.wr, heredoc);
2070                 _exit(0);
2071         }
2072         /* parent */
2073         die_sleep = -1;
2074         close(pair.wr);
2075         xmove_fd(pair.rd, fd);
2076 }
2077
2078 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2079  * and stderr if they are redirected. */
2080 static int setup_redirects(struct command *prog, int squirrel[])
2081 {
2082 //TODO: no callers ever check return value - ?!
2083         int openfd, mode;
2084         struct redir_struct *redir;
2085
2086         for (redir = prog->redirects; redir; redir = redir->next) {
2087                 if (redir->rd_type == REDIRECT_HEREDOC2) {
2088                         if (squirrel && redir->fd < 3) {
2089                                 squirrel[redir->fd] = dup(redir->fd);
2090                         }
2091                         /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2092                          * of the heredoc */
2093                         debug_printf_parse("set heredoc '%s'\n",
2094                                         redir->rd_filename);
2095                         setup_heredoc(redir->fd, redir->rd_filename);
2096                         continue;
2097                 }
2098
2099                 if (redir->dup == -1) {
2100                         char *p;
2101                         if (redir->rd_filename == NULL) {
2102                                 /* Something went wrong in the parse.
2103                                  * Pretend it didn't happen */
2104                                 continue;
2105                         }
2106                         mode = redir_table[redir->rd_type].mode;
2107 //TODO: check redir for names like '\\'
2108                         p = expand_string_to_string(redir->rd_filename);
2109                         openfd = open_or_warn(p, mode);
2110                         free(p);
2111                         if (openfd < 0) {
2112                         /* this could get lost if stderr has been redirected, but
2113                          * bash and ash both lose it as well (though zsh doesn't!) */
2114 //what the above comment tries to say?
2115                                 return 1;
2116                         }
2117                 } else {
2118                         openfd = redir->dup;
2119                 }
2120
2121                 if (openfd != redir->fd) {
2122                         if (squirrel && redir->fd < 3) {
2123                                 squirrel[redir->fd] = dup(redir->fd);
2124                         }
2125                         if (openfd == -3) {
2126                                 /* "-" means "close me" and we use -3 for that */
2127                                 close(redir->fd);
2128                         } else {
2129                                 dup2(openfd, redir->fd);
2130                                 if (redir->dup == -1)
2131                                         close(openfd);
2132                         }
2133                 }
2134         }
2135         return 0;
2136 }
2137
2138 static void restore_redirects(int squirrel[])
2139 {
2140         int i, fd;
2141         for (i = 0; i < 3; i++) {
2142                 fd = squirrel[i];
2143                 if (fd != -1) {
2144                         /* We simply die on error */
2145                         xmove_fd(fd, i);
2146                 }
2147         }
2148 }
2149
2150
2151 #if !DEBUG_CLEAN
2152 #define free_pipe_list(head, indent) free_pipe_list(head)
2153 #define free_pipe(pi, indent)        free_pipe(pi)
2154 #endif
2155 static void free_pipe_list(struct pipe *head, int indent);
2156
2157 /* Return code is the exit status of the pipe */
2158 static void free_pipe(struct pipe *pi, int indent)
2159 {
2160         char **p;
2161         struct command *command;
2162         struct redir_struct *r, *rnext;
2163         int a, i;
2164
2165         if (pi->stopped_cmds > 0) /* why? */
2166                 return;
2167         debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2168         for (i = 0; i < pi->num_cmds; i++) {
2169                 command = &pi->cmds[i];
2170                 debug_printf_clean("%s  command %d:\n", indenter(indent), i);
2171                 if (command->argv) {
2172                         for (a = 0, p = command->argv; *p; a++, p++) {
2173                                 debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
2174                         }
2175                         free_strings(command->argv);
2176                         command->argv = NULL;
2177                 }
2178                 /* not "else if": on syntax error, we may have both! */
2179                 if (command->group) {
2180                         debug_printf_clean("%s   begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2181                         free_pipe_list(command->group, indent+3);
2182                         debug_printf_clean("%s   end group\n", indenter(indent));
2183                         command->group = NULL;
2184                 }
2185 #if !BB_MMU
2186                 free(command->group_as_string);
2187                 command->group_as_string = NULL;
2188 #endif
2189                 for (r = command->redirects; r; r = rnext) {
2190                         debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2191                         if (r->dup == -1) {
2192                                 /* guard against the case >$FOO, where foo is unset or blank */
2193                                 if (r->rd_filename) {
2194                                         debug_printf_clean(" %s\n", r->rd_filename);
2195                                         free(r->rd_filename);
2196                                         r->rd_filename = NULL;
2197                                 }
2198                         } else {
2199                                 debug_printf_clean("&%d\n", r->dup);
2200                         }
2201                         rnext = r->next;
2202                         free(r);
2203                 }
2204                 command->redirects = NULL;
2205         }
2206         free(pi->cmds);   /* children are an array, they get freed all at once */
2207         pi->cmds = NULL;
2208 #if ENABLE_HUSH_JOB
2209         free(pi->cmdtext);
2210         pi->cmdtext = NULL;
2211 #endif
2212 }
2213
2214 static void free_pipe_list(struct pipe *head, int indent)
2215 {
2216         struct pipe *pi, *next;
2217
2218         for (pi = head; pi; pi = next) {
2219 #if HAS_KEYWORDS
2220                 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2221 #endif
2222                 free_pipe(pi, indent);
2223                 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2224                 next = pi->next;
2225                 /*pi->next = NULL;*/
2226                 free(pi);
2227         }
2228 }
2229
2230
2231 #if !BB_MMU
2232 typedef struct nommu_save_t {
2233         char **new_env;
2234         char **old_env;
2235         char **argv;
2236 } nommu_save_t;
2237 #else
2238 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2239         pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2240 #define pseudo_exec(nommu_save, command, argv_expanded) \
2241         pseudo_exec(command, argv_expanded)
2242 #endif
2243
2244 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2245  * Never returns.
2246  * XXX no exit() here.  If you don't exec, use _exit instead.
2247  * The at_exit handlers apparently confuse the calling process,
2248  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
2249 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2250                 char **argv, int assignment_cnt,
2251                 char **argv_expanded) NORETURN;
2252 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2253                 char **argv, int assignment_cnt,
2254                 char **argv_expanded)
2255 {
2256         char **new_env;
2257
2258         /* Case when we are here: ... | var=val | ... */
2259         if (!argv[assignment_cnt])
2260                 _exit(EXIT_SUCCESS);
2261
2262         new_env = expand_assignments(argv, assignment_cnt);
2263 #if BB_MMU
2264         putenv_all(new_env);
2265         free(new_env); /* optional */
2266 #else
2267         nommu_save->new_env = new_env;
2268         nommu_save->old_env = putenv_all_and_save_old(new_env);
2269 #endif
2270         if (argv_expanded) {
2271                 argv = argv_expanded;
2272         } else {
2273                 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2274 #if !BB_MMU
2275                 nommu_save->argv = argv;
2276 #endif
2277         }
2278
2279         /* On NOMMU, we must never block!
2280          * Example: { sleep 99999 | read line } & echo Ok
2281          * read builtin will block on read syscall, leaving parent blocked
2282          * in vfork. Therefore we can't do this:
2283          */
2284 #if BB_MMU
2285         /* Check if the command matches any of the builtins.
2286          * Depending on context, this might be redundant.  But it's
2287          * easier to waste a few CPU cycles than it is to figure out
2288          * if this is one of those cases.
2289          */
2290         {
2291                 int rcode;
2292                 const struct built_in_command *x;
2293                 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2294                         if (strcmp(argv[0], x->cmd) == 0) {
2295                                 debug_printf_exec("running builtin '%s'\n",
2296                                                 argv[0]);
2297                                 rcode = x->function(argv);
2298                                 fflush(NULL);
2299                                 _exit(rcode);
2300                         }
2301                 }
2302         }
2303 #endif
2304
2305 #if ENABLE_FEATURE_SH_STANDALONE
2306         /* Check if the command matches any busybox applets */
2307         if (strchr(argv[0], '/') == NULL) {
2308                 int a = find_applet_by_name(argv[0]);
2309                 if (a >= 0) {
2310 #if BB_MMU /* see above why on NOMMU it is not allowed */
2311                         if (APPLET_IS_NOEXEC(a)) {
2312                                 debug_printf_exec("running applet '%s'\n", argv[0]);
2313                                 run_applet_no_and_exit(a, argv);
2314                         }
2315 #endif
2316                         /* Re-exec ourselves */
2317                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2318                         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2319                         execv(bb_busybox_exec_path, argv);
2320                         /* If they called chroot or otherwise made the binary no longer
2321                          * executable, fall through */
2322                 }
2323         }
2324 #endif
2325
2326         debug_printf_exec("execing '%s'\n", argv[0]);
2327         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2328         execvp(argv[0], argv);
2329         bb_perror_msg("can't exec '%s'", argv[0]);
2330         _exit(EXIT_FAILURE);
2331 }
2332
2333 #if BB_MMU
2334 static void reset_traps_to_defaults(void)
2335 {
2336         unsigned sig;
2337         int dirty;
2338
2339         if (!G.traps)
2340                 return;
2341         dirty = 0;
2342         for (sig = 0; sig < NSIG; sig++) {
2343                 if (!G.traps[sig])
2344                         continue;
2345                 free(G.traps[sig]);
2346                 G.traps[sig] = NULL;
2347                 /* There is no signal for 0 (EXIT) */
2348                 if (sig == 0)
2349                         continue;
2350                 /* there was a trap handler, we are removing it
2351                  * (if sig has non-DFL handling,
2352                  * we don't need to do anything) */
2353                 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2354                         continue;
2355                 sigdelset(&G.blocked_set, sig);
2356                 dirty = 1;
2357         }
2358         if (dirty)
2359                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2360 }
2361 #define clean_up_after_re_execute() ((void)0)
2362
2363 #else /* !BB_MMU */
2364
2365 static void re_execute_shell(const char *s) NORETURN;
2366 static void re_execute_shell(const char *s)
2367 {
2368         char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2369         struct variable *cur;
2370         char **argv, **pp, **pp2;
2371         unsigned cnt;
2372
2373         sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2374                         , (unsigned) G.root_pid
2375                         , (unsigned) G.last_bg_pid
2376                         , (unsigned) G.last_exitcode
2377                         USE_HUSH_LOOPS(, G.depth_of_loop)
2378                         );
2379         /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2380          * 3:-c 4:<cmd> <argN...> 5:NULL
2381          */
2382         cnt = 5 + G.global_argc;
2383         for (cur = G.top_var; cur; cur = cur->next) {
2384                 if (!cur->flg_export || cur->flg_read_only)
2385                         cnt += 2;
2386         }
2387         G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2388         *pp++ = (char *) G.argv0_for_re_execing;
2389         *pp++ = param_buf;
2390         for (cur = G.top_var; cur; cur = cur->next) {
2391                 if (cur->varstr == hush_version_str)
2392                         continue;
2393                 if (cur->flg_read_only) {
2394                         *pp++ = (char *) "-R";
2395                         *pp++ = cur->varstr;
2396                 } else if (!cur->flg_export) {
2397                         *pp++ = (char *) "-V";
2398                         *pp++ = cur->varstr;
2399                 }
2400         }
2401 //TODO: pass functions
2402         /* We can pass activated traps here. Say, -Tnn:trap_string
2403          *
2404          * However, POSIX says that subshells reset signals with traps
2405          * to SIG_DFL.
2406          * I tested bash-3.2 and it not only does that with true subshells
2407          * of the form ( list ), but with any forked children shells.
2408          * I set trap "echo W" WINCH; and then tried:
2409          *
2410          * { echo 1; sleep 20; echo 2; } &
2411          * while true; do echo 1; sleep 20; echo 2; break; done &
2412          * true | { echo 1; sleep 20; echo 2; } | cat
2413          *
2414          * In all these cases sending SIGWINCH to the child shell
2415          * did not run the trap. If I add trap "echo V" WINCH;
2416          * _inside_ group (just before echo 1), it works.
2417          *
2418          * I conclude it means we don't need to pass active traps here.
2419          * exec syscall below resets them to SIG_DFL for us.
2420          */
2421         *pp++ = (char *) "-c";
2422         *pp++ = (char *) s;
2423         pp2 = G.global_argv;
2424         while (*pp2)
2425                 *pp++ = *pp2++;
2426         /* *pp = NULL; - is already there */
2427
2428         debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2429         sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2430         execv(bb_busybox_exec_path, G.argv_from_re_execing);
2431         /* Fallback. Useful for init=/bin/hush usage etc */
2432         if (G.argv0_for_re_execing[0] == '/')
2433                 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2434         xfunc_error_retval = 127;
2435         bb_error_msg_and_die("can't re-execute the shell");
2436 }
2437
2438 static void clean_up_after_re_execute(void)
2439 {
2440         char **pp = G.argv_from_re_execing;
2441         if (pp) {
2442                 /* Must match re_execute_shell's allocations (if any) */
2443                 free(pp);
2444                 G.argv_from_re_execing = NULL;
2445         }
2446 }
2447 #endif
2448
2449 static int run_list(struct pipe *pi);
2450
2451 /* Called after [v]fork() in run_pipe
2452  */
2453 static void pseudo_exec(nommu_save_t *nommu_save,
2454                 struct command *command,
2455                 char **argv_expanded) NORETURN;
2456 static void pseudo_exec(nommu_save_t *nommu_save,
2457                 struct command *command,
2458                 char **argv_expanded)
2459 {
2460         if (command->argv) {
2461                 pseudo_exec_argv(nommu_save, command->argv,
2462                                 command->assignment_cnt, argv_expanded);
2463         }
2464
2465         if (command->group) {
2466                 /* Cases when we are here:
2467                  * ( list )
2468                  * { list } &
2469                  * ... | ( list ) | ...
2470                  * ... | { list } | ...
2471                  */
2472 #if BB_MMU
2473                 int rcode;
2474                 debug_printf_exec("pseudo_exec: run_list\n");
2475                 reset_traps_to_defaults();
2476                 rcode = run_list(command->group);
2477                 /* OK to leak memory by not calling free_pipe_list,
2478                  * since this process is about to exit */
2479                 _exit(rcode);
2480 #else
2481                 re_execute_shell(command->group_as_string);
2482 #endif
2483         }
2484
2485         /* Case when we are here: ... | >file */
2486         debug_printf_exec("pseudo_exec'ed null command\n");
2487         _exit(EXIT_SUCCESS);
2488 }
2489
2490 #if ENABLE_HUSH_JOB
2491 static const char *get_cmdtext(struct pipe *pi)
2492 {
2493         char **argv;
2494         char *p;
2495         int len;
2496
2497         /* This is subtle. ->cmdtext is created only on first backgrounding.
2498          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2499          * On subsequent bg argv is trashed, but we won't use it */
2500         if (pi->cmdtext)
2501                 return pi->cmdtext;
2502         argv = pi->cmds[0].argv;
2503         if (!argv || !argv[0]) {
2504                 pi->cmdtext = xzalloc(1);
2505                 return pi->cmdtext;
2506         }
2507
2508         len = 0;
2509         do len += strlen(*argv) + 1; while (*++argv);
2510         pi->cmdtext = p = xmalloc(len);
2511         argv = pi->cmds[0].argv;
2512         do {
2513                 len = strlen(*argv);
2514                 memcpy(p, *argv, len);
2515                 p += len;
2516                 *p++ = ' ';
2517         } while (*++argv);
2518         p[-1] = '\0';
2519         return pi->cmdtext;
2520 }
2521
2522 static void insert_bg_job(struct pipe *pi)
2523 {
2524         struct pipe *thejob;
2525         int i;
2526
2527         /* Linear search for the ID of the job to use */
2528         pi->jobid = 1;
2529         for (thejob = G.job_list; thejob; thejob = thejob->next)
2530                 if (thejob->jobid >= pi->jobid)
2531                         pi->jobid = thejob->jobid + 1;
2532
2533         /* Add thejob to the list of running jobs */
2534         if (!G.job_list) {
2535                 thejob = G.job_list = xmalloc(sizeof(*thejob));
2536         } else {
2537                 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2538                         continue;
2539                 thejob->next = xmalloc(sizeof(*thejob));
2540                 thejob = thejob->next;
2541         }
2542
2543         /* Physically copy the struct job */
2544         memcpy(thejob, pi, sizeof(struct pipe));
2545         thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2546         /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2547         for (i = 0; i < pi->num_cmds; i++) {
2548 // TODO: do we really need to have so many fields which are just dead weight
2549 // at execution stage?
2550                 thejob->cmds[i].pid = pi->cmds[i].pid;
2551                 /* all other fields are not used and stay zero */
2552         }
2553         thejob->next = NULL;
2554         thejob->cmdtext = xstrdup(get_cmdtext(pi));
2555
2556         /* We don't wait for background thejobs to return -- append it
2557            to the list of backgrounded thejobs and leave it alone */
2558         if (G_interactive_fd)
2559                 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2560         G.last_bg_pid = thejob->cmds[0].pid;
2561         G.last_jobid = thejob->jobid;
2562 }
2563
2564 static void remove_bg_job(struct pipe *pi)
2565 {
2566         struct pipe *prev_pipe;
2567
2568         if (pi == G.job_list) {
2569                 G.job_list = pi->next;
2570         } else {
2571                 prev_pipe = G.job_list;
2572                 while (prev_pipe->next != pi)
2573                         prev_pipe = prev_pipe->next;
2574                 prev_pipe->next = pi->next;
2575         }
2576         if (G.job_list)
2577                 G.last_jobid = G.job_list->jobid;
2578         else
2579                 G.last_jobid = 0;
2580 }
2581
2582 /* Remove a backgrounded job */
2583 static void delete_finished_bg_job(struct pipe *pi)
2584 {
2585         remove_bg_job(pi);
2586         pi->stopped_cmds = 0;
2587         free_pipe(pi, 0);
2588         free(pi);
2589 }
2590 #endif /* JOB */
2591
2592 /* Check to see if any processes have exited -- if they
2593  * have, figure out why and see if a job has completed */
2594 static int checkjobs(struct pipe* fg_pipe)
2595 {
2596         int attributes;
2597         int status;
2598 #if ENABLE_HUSH_JOB
2599         struct pipe *pi;
2600 #endif
2601         pid_t childpid;
2602         int rcode = 0;
2603
2604         debug_printf_jobs("checkjobs %p\n", fg_pipe);
2605
2606         errno = 0;
2607 //      if (G.handled_SIGCHLD == G.count_SIGCHLD)
2608 //              /* avoid doing syscall, nothing there anyway */
2609 //              return rcode;
2610
2611         attributes = WUNTRACED;
2612         if (fg_pipe == NULL)
2613                 attributes |= WNOHANG;
2614
2615 /* Do we do this right?
2616  * bash-3.00# sleep 20 | false
2617  * <ctrl-Z pressed>
2618  * [3]+  Stopped          sleep 20 | false
2619  * bash-3.00# echo $?
2620  * 1   <========== bg pipe is not fully done, but exitcode is already known!
2621  */
2622
2623 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2624 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2625 // + killall -STOP cat
2626
2627  wait_more:
2628         while (1) {
2629                 int i;
2630                 int dead;
2631
2632 //              i = G.count_SIGCHLD;
2633                 childpid = waitpid(-1, &status, attributes);
2634                 if (childpid <= 0) {
2635                         if (childpid && errno != ECHILD)
2636                                 bb_perror_msg("waitpid");
2637 //                      else /* Until next SIGCHLD, waitpid's are useless */
2638 //                              G.handled_SIGCHLD = i;
2639                         break;
2640                 }
2641                 dead = WIFEXITED(status) || WIFSIGNALED(status);
2642
2643 #if DEBUG_JOBS
2644                 if (WIFSTOPPED(status))
2645                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2646                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
2647                 if (WIFSIGNALED(status))
2648                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2649                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
2650                 if (WIFEXITED(status))
2651                         debug_printf_jobs("pid %d exited, exitcode %d\n",
2652                                         childpid, WEXITSTATUS(status));
2653 #endif
2654                 /* Were we asked to wait for fg pipe? */
2655                 if (fg_pipe) {
2656                         for (i = 0; i < fg_pipe->num_cmds; i++) {
2657                                 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2658                                 if (fg_pipe->cmds[i].pid != childpid)
2659                                         continue;
2660                                 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2661                                 if (dead) {
2662                                         fg_pipe->cmds[i].pid = 0;
2663                                         fg_pipe->alive_cmds--;
2664                                         if (i == fg_pipe->num_cmds - 1) {
2665                                                 /* last process gives overall exitstatus */
2666                                                 rcode = WEXITSTATUS(status);
2667                                                 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2668                                         }
2669                                 } else {
2670                                         fg_pipe->cmds[i].is_stopped = 1;
2671                                         fg_pipe->stopped_cmds++;
2672                                 }
2673                                 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2674                                                 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2675                                 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2676                                         /* All processes in fg pipe have exited/stopped */
2677 #if ENABLE_HUSH_JOB
2678                                         if (fg_pipe->alive_cmds)
2679                                                 insert_bg_job(fg_pipe);
2680 #endif
2681                                         return rcode;
2682                                 }
2683                                 /* There are still running processes in the fg pipe */
2684                                 goto wait_more; /* do waitpid again */
2685                         }
2686                         /* it wasnt fg_pipe, look for process in bg pipes */
2687                 }
2688
2689 #if ENABLE_HUSH_JOB
2690                 /* We asked to wait for bg or orphaned children */
2691                 /* No need to remember exitcode in this case */
2692                 for (pi = G.job_list; pi; pi = pi->next) {
2693                         for (i = 0; i < pi->num_cmds; i++) {
2694                                 if (pi->cmds[i].pid == childpid)
2695                                         goto found_pi_and_prognum;
2696                         }
2697                 }
2698                 /* Happens when shell is used as init process (init=/bin/sh) */
2699                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2700                 continue; /* do waitpid again */
2701
2702  found_pi_and_prognum:
2703                 if (dead) {
2704                         /* child exited */
2705                         pi->cmds[i].pid = 0;
2706                         pi->alive_cmds--;
2707                         if (!pi->alive_cmds) {
2708                                 if (G_interactive_fd)
2709                                         printf(JOB_STATUS_FORMAT, pi->jobid,
2710                                                         "Done", pi->cmdtext);
2711                                 delete_finished_bg_job(pi);
2712                         }
2713                 } else {
2714                         /* child stopped */
2715                         pi->cmds[i].is_stopped = 1;
2716                         pi->stopped_cmds++;
2717                 }
2718 #endif
2719         } /* while (waitpid succeeds)... */
2720
2721         return rcode;
2722 }
2723
2724 #if ENABLE_HUSH_JOB
2725 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2726 {
2727         pid_t p;
2728         int rcode = checkjobs(fg_pipe);
2729         /* Job finished, move the shell to the foreground */
2730         p = getpgid(0); /* pgid of our process */
2731         debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2732         tcsetpgrp(G_interactive_fd, p);
2733         return rcode;
2734 }
2735 #endif
2736
2737 /* Start all the jobs, but don't wait for anything to finish.
2738  * See checkjobs().
2739  *
2740  * Return code is normally -1, when the caller has to wait for children
2741  * to finish to determine the exit status of the pipe.  If the pipe
2742  * is a simple builtin command, however, the action is done by the
2743  * time run_pipe returns, and the exit code is provided as the
2744  * return value.
2745  *
2746  * Returns -1 only if started some children. IOW: we have to
2747  * mask out retvals of builtins etc with 0xff!
2748  *
2749  * The only case when we do not need to [v]fork is when the pipe
2750  * is single, non-backgrounded, non-subshell command. Examples:
2751  * cmd ; ...   { list } ; ...
2752  * cmd && ...  { list } && ...
2753  * cmd || ...  { list } || ...
2754  * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2755  * or (if SH_STANDALONE) an applet, and we can run the { list }
2756  * with run_list(). If it isn't one of these, we fork and exec cmd.
2757  *
2758  * Cases when we must fork:
2759  * non-single:   cmd | cmd
2760  * backgrounded: cmd &     { list } &
2761  * subshell:     ( list ) [&]
2762  */
2763 static int run_pipe(struct pipe *pi)
2764 {
2765         static const char *const null_ptr = NULL;
2766         int i;
2767         int nextin;
2768         int pipefds[2];         /* pipefds[0] is for reading */
2769         struct command *command;
2770         char **argv_expanded;
2771         char **argv;
2772         char *p;
2773         /* it is not always needed, but we aim to smaller code */
2774         int squirrel[] = { -1, -1, -1 };
2775         int rcode;
2776
2777         debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2778
2779         USE_HUSH_JOB(pi->pgrp = -1;)
2780         pi->stopped_cmds = 0;
2781         command = &(pi->cmds[0]);
2782         argv_expanded = NULL;
2783
2784         if (pi->num_cmds != 1
2785          || pi->followup == PIPE_BG
2786          || command->grp_type == GRP_SUBSHELL
2787         ) {
2788                 goto must_fork;
2789         }
2790
2791         pi->alive_cmds = 1;
2792
2793         debug_printf_exec(": group:%p argv:'%s'\n",
2794                 command->group, command->argv ? command->argv[0] : "NONE");
2795
2796         if (command->group) {
2797 #if ENABLE_HUSH_FUNCTIONS
2798                 if (command->grp_type == GRP_FUNCTION) {
2799                         /* func () { list } */
2800                         bb_error_msg("here we ought to remember function definition, and go on");
2801                         return EXIT_SUCCESS;
2802                 }
2803 #endif
2804                 /* { list } */
2805                 debug_printf("non-subshell group\n");
2806                 setup_redirects(command, squirrel);
2807                 debug_printf_exec(": run_list\n");
2808                 rcode = run_list(command->group) & 0xff;
2809                 restore_redirects(squirrel);
2810                 debug_printf_exec("run_pipe return %d\n", rcode);
2811                 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2812                 return rcode;
2813         }
2814
2815         argv = command->argv ? command->argv : (char **) &null_ptr;
2816         {
2817                 const struct built_in_command *x;
2818                 char **new_env = NULL;
2819                 char **old_env = NULL;
2820
2821                 if (argv[command->assignment_cnt] == NULL) {
2822                         /* Assignments, but no command */
2823                         /* Ensure redirects take effect. Try "a=t >file" */
2824                         setup_redirects(command, squirrel);
2825                         restore_redirects(squirrel);
2826                         /* Set shell variables */
2827                         while (*argv) {
2828                                 p = expand_string_to_string(*argv);
2829                                 debug_printf_exec("set shell var:'%s'->'%s'\n",
2830                                                 *argv, p);
2831                                 set_local_var(p, 0, 0);
2832                                 argv++;
2833                         }
2834                         /* Do we need to flag set_local_var() errors?
2835                          * "assignment to readonly var" and "putenv error"
2836                          */
2837                         return EXIT_SUCCESS;
2838                 }
2839
2840                 /* Expand the rest into (possibly) many strings each */
2841                 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2842
2843                 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2844                         if (strcmp(argv_expanded[0], x->cmd) != 0)
2845                                 continue;
2846                         if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2847                                 debug_printf("exec with redirects only\n");
2848                                 setup_redirects(command, NULL);
2849                                 rcode = EXIT_SUCCESS;
2850                                 goto clean_up_and_ret1;
2851                         }
2852                         debug_printf("builtin inline %s\n", argv_expanded[0]);
2853                         /* XXX setup_redirects acts on file descriptors, not FILEs.
2854                          * This is perfect for work that comes after exec().
2855                          * Is it really safe for inline use?  Experimentally,
2856                          * things seem to work with glibc. */
2857                         setup_redirects(command, squirrel);
2858                         new_env = expand_assignments(argv, command->assignment_cnt);
2859                         old_env = putenv_all_and_save_old(new_env);
2860                         debug_printf_exec(": builtin '%s' '%s'...\n",
2861                                     x->cmd, argv_expanded[1]);
2862                         rcode = x->function(argv_expanded) & 0xff;
2863 #if ENABLE_FEATURE_SH_STANDALONE
2864  clean_up_and_ret:
2865 #endif
2866                         restore_redirects(squirrel);
2867                         free_strings_and_unsetenv(new_env, 1);
2868                         putenv_all(old_env);
2869                         free(old_env); /* not free_strings()! */
2870  clean_up_and_ret1:
2871                         free(argv_expanded);
2872                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2873                         debug_printf_exec("run_pipe return %d\n", rcode);
2874                         return rcode;
2875                 }
2876 #if ENABLE_FEATURE_SH_STANDALONE
2877                 i = find_applet_by_name(argv_expanded[0]);
2878                 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2879                         setup_redirects(command, squirrel);
2880                         save_nofork_data(&G.nofork_save);
2881                         new_env = expand_assignments(argv, command->assignment_cnt);
2882                         old_env = putenv_all_and_save_old(new_env);
2883                         debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2884                                         argv_expanded[0], argv_expanded[1]);
2885                         rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2886                         goto clean_up_and_ret;
2887                 }
2888 #endif
2889                 /* It is neither builtin nor applet. We must fork. */
2890         }
2891
2892  must_fork:
2893         /* NB: argv_expanded may already be created, and that
2894          * might include `cmd` runs! Do not rerun it! We *must*
2895          * use argv_expanded if it's non-NULL */
2896
2897         /* Going to fork a child per each pipe member */
2898         pi->alive_cmds = 0;
2899         nextin = 0;
2900
2901         for (i = 0; i < pi->num_cmds; i++) {
2902 #if !BB_MMU
2903                 volatile nommu_save_t nommu_save;
2904                 nommu_save.new_env = NULL;
2905                 nommu_save.old_env = NULL;
2906                 nommu_save.argv = NULL;
2907 #endif
2908                 command = &(pi->cmds[i]);
2909                 if (command->argv) {
2910                         debug_printf_exec(": pipe member '%s' '%s'...\n",
2911                                         command->argv[0], command->argv[1]);
2912                 } else {
2913                         debug_printf_exec(": pipe member with no argv\n");
2914                 }
2915
2916                 /* pipes are inserted between pairs of commands */
2917                 pipefds[0] = 0;
2918                 pipefds[1] = 1;
2919                 if ((i + 1) < pi->num_cmds)
2920                         xpipe(pipefds);
2921
2922                 command->pid = BB_MMU ? fork() : vfork();
2923                 if (!command->pid) { /* child */
2924 #if ENABLE_HUSH_JOB
2925                         die_sleep = 0; /* do not restore tty pgrp on xfunc death */
2926
2927                         /* Every child adds itself to new process group
2928                          * with pgid == pid_of_first_child_in_pipe */
2929                         if (G.run_list_level == 1 && G_interactive_fd) {
2930                                 pid_t pgrp;
2931                                 pgrp = pi->pgrp;
2932                                 if (pgrp < 0) /* true for 1st process only */
2933                                         pgrp = getpid();
2934                                 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2935                                         /* We do it in *every* child, not just first,
2936                                          * to avoid races */
2937                                         tcsetpgrp(G_interactive_fd, pgrp);
2938                                 }
2939                         }
2940 #endif
2941                         xmove_fd(nextin, 0);
2942                         xmove_fd(pipefds[1], 1); /* write end */
2943                         if (pipefds[0] > 1)
2944                                 close(pipefds[0]); /* read end */
2945                         /* Like bash, explicit redirects override pipes,
2946                          * and the pipe fd is available for dup'ing. */
2947                         setup_redirects(command, NULL);
2948
2949                         /* Restore default handlers just prior to exec */
2950                         /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2951
2952                         /* Stores to nommu_save list of env vars putenv'ed
2953                          * (NOMMU, on MMU we don't need that) */
2954                         /* cast away volatility... */
2955                         pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2956                         /* pseudo_exec() does not return */
2957                 }
2958
2959                 /* parent or error */
2960 #if ENABLE_HUSH_JOB
2961                 die_sleep = -1; /* restore tty pgrp on xfunc death */
2962 #endif
2963 #if !BB_MMU
2964                 /* Clean up after vforked child */
2965                 clean_up_after_re_execute();
2966                 free(nommu_save.argv);
2967                 free_strings_and_unsetenv(nommu_save.new_env, 1);
2968                 putenv_all(nommu_save.old_env);
2969 #endif
2970                 free(argv_expanded);
2971                 argv_expanded = NULL;
2972                 if (command->pid < 0) { /* [v]fork failed */
2973                         /* Clearly indicate, was it fork or vfork */
2974                         bb_perror_msg(BB_MMU ? "fork" : "vfork");
2975                 } else {
2976                         pi->alive_cmds++;
2977 #if ENABLE_HUSH_JOB
2978                         /* Second and next children need to know pid of first one */
2979                         if (pi->pgrp < 0)
2980                                 pi->pgrp = command->pid;
2981 #endif
2982                 }
2983
2984                 if (i)
2985                         close(nextin);
2986                 if ((i + 1) < pi->num_cmds)
2987                         close(pipefds[1]); /* write end */
2988                 /* Pass read (output) pipe end to next iteration */
2989                 nextin = pipefds[0];
2990         }
2991
2992         if (!pi->alive_cmds) {
2993                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2994                 return 1;
2995         }
2996
2997         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2998         return -1;
2999 }
3000
3001 #ifndef debug_print_tree
3002 static void debug_print_tree(struct pipe *pi, int lvl)
3003 {
3004         static const char *const PIPE[] = {
3005                 [PIPE_SEQ] = "SEQ",
3006                 [PIPE_AND] = "AND",
3007                 [PIPE_OR ] = "OR" ,
3008                 [PIPE_BG ] = "BG" ,
3009         };
3010         static const char *RES[] = {
3011                 [RES_NONE ] = "NONE" ,
3012 #if ENABLE_HUSH_IF
3013                 [RES_IF   ] = "IF"   ,
3014                 [RES_THEN ] = "THEN" ,
3015                 [RES_ELIF ] = "ELIF" ,
3016                 [RES_ELSE ] = "ELSE" ,
3017                 [RES_FI   ] = "FI"   ,
3018 #endif
3019 #if ENABLE_HUSH_LOOPS
3020                 [RES_FOR  ] = "FOR"  ,
3021                 [RES_WHILE] = "WHILE",
3022                 [RES_UNTIL] = "UNTIL",
3023                 [RES_DO   ] = "DO"   ,
3024                 [RES_DONE ] = "DONE" ,
3025 #endif
3026 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3027                 [RES_IN   ] = "IN"   ,
3028 #endif
3029 #if ENABLE_HUSH_CASE
3030                 [RES_CASE ] = "CASE" ,
3031                 [RES_MATCH] = "MATCH",
3032                 [RES_CASEI] = "CASEI",
3033                 [RES_ESAC ] = "ESAC" ,
3034 #endif
3035                 [RES_XXXX ] = "XXXX" ,
3036                 [RES_SNTX ] = "SNTX" ,
3037         };
3038         static const char *const GRPTYPE[] = {
3039                 "{}",
3040                 "()",
3041 #if ENABLE_HUSH_FUNCTIONS
3042                 "func()",
3043 #endif
3044         };
3045
3046         int pin, prn;
3047
3048         pin = 0;
3049         while (pi) {
3050                 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3051                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3052                 prn = 0;
3053                 while (prn < pi->num_cmds) {
3054                         struct command *command = &pi->cmds[prn];
3055                         char **argv = command->argv;
3056
3057                         fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3058                                         lvl*2, "", prn,
3059                                         command->assignment_cnt);
3060                         if (command->group) {
3061                                 fprintf(stderr, " group %s: (argv=%p)\n",
3062                                                 GRPTYPE[command->grp_type],
3063                                                 argv);
3064                                 debug_print_tree(command->group, lvl+1);
3065                                 prn++;
3066                                 continue;
3067                         }
3068                         if (argv) while (*argv) {
3069                                 fprintf(stderr, " '%s'", *argv);
3070                                 argv++;
3071                         }
3072                         fprintf(stderr, "\n");
3073                         prn++;
3074                 }
3075                 pi = pi->next;
3076                 pin++;
3077         }
3078 }
3079 #endif
3080
3081 /* NB: called by pseudo_exec, and therefore must not modify any
3082  * global data until exec/_exit (we can be a child after vfork!) */
3083 static int run_list(struct pipe *pi)
3084 {
3085 #if ENABLE_HUSH_CASE
3086         char *case_word = NULL;
3087 #endif
3088 #if ENABLE_HUSH_LOOPS
3089         struct pipe *loop_top = NULL;
3090         char *for_varname = NULL;
3091         char **for_lcur = NULL;
3092         char **for_list = NULL;
3093 #endif
3094         smallint last_followup;
3095         smalluint rcode;
3096 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3097         smalluint cond_code = 0;
3098 #else
3099         enum { cond_code = 0 };
3100 #endif
3101 #if HAS_KEYWORDS
3102         smallint rword; /* enum reserved_style */
3103         smallint last_rword; /* ditto */
3104 #endif
3105
3106         debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3107
3108 #if ENABLE_HUSH_LOOPS
3109         /* Check syntax for "for" */
3110         for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3111                 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3112                         continue;
3113                 /* current word is FOR or IN (BOLD in comments below) */
3114                 if (cpipe->next == NULL) {
3115                         syntax("malformed for");
3116                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3117                         return 1;
3118                 }
3119                 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3120                 if (cpipe->next->res_word == RES_DO)
3121                         continue;
3122                 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3123                 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3124                  || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3125                 ) {
3126                         syntax("malformed for");
3127                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3128                         return 1;
3129                 }
3130         }
3131 #endif
3132
3133         /* Past this point, all code paths should jump to ret: label
3134          * in order to return, no direct "return" statements please.
3135          * This helps to ensure that no memory is leaked. */
3136
3137 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3138
3139 #if ENABLE_HUSH_JOB
3140         /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3141          * We are saving state before entering outermost list ("while...done")
3142          * so that ctrl-Z will correctly background _entire_ outermost list,
3143          * not just a part of it (like "sleep 1 | exit 2") */
3144         if (++G.run_list_level == 1 && G_interactive_fd) {
3145                 if (sigsetjmp(G.toplevel_jb, 1)) {
3146                         /* ctrl-Z forked and we are parent; or ctrl-C.
3147                          * Sighandler has longjmped us here */
3148                         signal(SIGINT, SIG_IGN);
3149                         signal(SIGTSTP, SIG_IGN);
3150                         /* Restore level (we can be coming from deep inside
3151                          * nested levels) */
3152                         G.run_list_level = 1;
3153 #if ENABLE_FEATURE_SH_STANDALONE
3154                         if (G.nofork_save.saved) { /* if save area is valid */
3155                                 debug_printf_jobs("exiting nofork early\n");
3156                                 restore_nofork_data(&G.nofork_save);
3157                         }
3158 #endif
3159 ////                    if (G.ctrl_z_flag) {
3160 ////                            /* ctrl-Z has forked and stored pid of the child in pi->pid.
3161 ////                             * Remember this child as background job */
3162 ////                            insert_bg_job(pi);
3163 ////                    } else {
3164                                 /* ctrl-C. We just stop doing whatever we were doing */
3165                                 bb_putchar('\n');
3166 ////                    }
3167                         USE_HUSH_LOOPS(loop_top = NULL;)
3168                         USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3169                         rcode = 0;
3170                         goto ret;
3171                 }
3172 ////            /* ctrl-Z handler will store pid etc in pi */
3173 ////            G.toplevel_list = pi;
3174 ////            G.ctrl_z_flag = 0;
3175 ////#if ENABLE_FEATURE_SH_STANDALONE
3176 ////            G.nofork_save.saved = 0; /* in case we will run a nofork later */
3177 ////#endif
3178 ////            signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3179 ////            signal(SIGINT, handler_ctrl_c);
3180         }
3181 #endif /* JOB */
3182
3183 #if HAS_KEYWORDS
3184         rword = RES_NONE;
3185         last_rword = RES_XXXX;
3186 #endif
3187         last_followup = PIPE_SEQ;
3188         rcode = G.last_exitcode;
3189
3190         /* Go through list of pipes, (maybe) executing them. */
3191         for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3192                 if (G.flag_SIGINT)
3193                         break;
3194
3195                 IF_HAS_KEYWORDS(rword = pi->res_word;)
3196                 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3197                                 rword, cond_code, last_rword);
3198 #if ENABLE_HUSH_LOOPS
3199                 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3200                  && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3201                 ) {
3202                         /* start of a loop: remember where loop starts */
3203                         loop_top = pi;
3204                         G.depth_of_loop++;
3205                 }
3206 #endif
3207                 /* Still in the same "if...", "then..." or "do..." branch? */
3208                 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3209                         if ((rcode == 0 && last_followup == PIPE_OR)
3210                          || (rcode != 0 && last_followup == PIPE_AND)
3211                         ) {
3212                                 /* It is "<true> || CMD" or "<false> && CMD"
3213                                  * and we should not execute CMD */
3214                                 debug_printf_exec("skipped cmd because of || or &&\n");
3215                                 last_followup = pi->followup;
3216                                 continue;
3217                         }
3218                 }
3219                 last_followup = pi->followup;
3220                 IF_HAS_KEYWORDS(last_rword = rword;)
3221 #if ENABLE_HUSH_IF
3222                 if (cond_code) {
3223                         if (rword == RES_THEN) {
3224                                 /* if false; then ... fi has exitcode 0! */
3225                                 G.last_exitcode = rcode = EXIT_SUCCESS;
3226                                 /* "if <false> THEN cmd": skip cmd */
3227                                 continue;
3228                         }
3229                 } else {
3230                         if (rword == RES_ELSE || rword == RES_ELIF) {
3231                                 /* "if <true> then ... ELSE/ELIF cmd":
3232                                  * skip cmd and all following ones */
3233                                 break;
3234                         }
3235                 }
3236 #endif
3237 #if ENABLE_HUSH_LOOPS
3238                 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3239                         if (!for_lcur) {
3240                                 /* first loop through for */
3241
3242                                 static const char encoded_dollar_at[] ALIGN1 = {
3243                                         SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3244                                 }; /* encoded representation of "$@" */
3245                                 static const char *const encoded_dollar_at_argv[] = {
3246                                         encoded_dollar_at, NULL
3247                                 }; /* argv list with one element: "$@" */
3248                                 char **vals;
3249
3250                                 vals = (char**)encoded_dollar_at_argv;
3251                                 if (pi->next->res_word == RES_IN) {
3252                                         /* if no variable values after "in" we skip "for" */
3253                                         if (!pi->next->cmds[0].argv) {
3254                                                 G.last_exitcode = rcode = EXIT_SUCCESS;
3255                                                 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3256                                                 break;
3257                                         }
3258                                         vals = pi->next->cmds[0].argv;
3259                                 } /* else: "for var; do..." -> assume "$@" list */
3260                                 /* create list of variable values */
3261                                 debug_print_strings("for_list made from", vals);
3262                                 for_list = expand_strvec_to_strvec(vals);
3263                                 for_lcur = for_list;
3264                                 debug_print_strings("for_list", for_list);
3265                                 for_varname = pi->cmds[0].argv[0];
3266                                 pi->cmds[0].argv[0] = NULL;
3267                         }
3268                         free(pi->cmds[0].argv[0]);
3269                         if (!*for_lcur) {
3270                                 /* "for" loop is over, clean up */
3271                                 free(for_list);
3272                                 for_list = NULL;
3273                                 for_lcur = NULL;
3274                                 pi->cmds[0].argv[0] = for_varname;
3275                                 break;
3276                         }
3277                         /* Insert next value from for_lcur */
3278 //TODO: does it need escaping?
3279                         pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3280                         pi->cmds[0].assignment_cnt = 1;
3281                 }
3282                 if (rword == RES_IN) {
3283                         continue; /* "for v IN list;..." - "in" has no cmds anyway */
3284                 }
3285                 if (rword == RES_DONE) {
3286                         continue; /* "done" has no cmds too */
3287                 }
3288 #endif
3289 #if ENABLE_HUSH_CASE
3290                 if (rword == RES_CASE) {
3291                         case_word = expand_strvec_to_string(pi->cmds->argv);
3292                         continue;
3293                 }
3294                 if (rword == RES_MATCH) {
3295                         char **argv;
3296
3297                         if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3298                                 break;
3299                         /* all prev words didn't match, does this one match? */
3300                         argv = pi->cmds->argv;
3301                         while (*argv) {
3302                                 char *pattern = expand_string_to_string(*argv);
3303                                 /* TODO: which FNM_xxx flags to use? */
3304                                 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3305                                 free(pattern);
3306                                 if (cond_code == 0) { /* match! we will execute this branch */
3307                                         free(case_word); /* make future "word)" stop */
3308                                         case_word = NULL;
3309                                         break;
3310                                 }
3311                                 argv++;
3312                         }
3313                         continue;
3314                 }
3315                 if (rword == RES_CASEI) { /* inside of a case branch */
3316                         if (cond_code != 0)
3317                                 continue; /* not matched yet, skip this pipe */
3318                 }
3319 #endif
3320                 /* Just pressing <enter> in shell should check for jobs.
3321                  * OTOH, in non-interactive shell this is useless
3322                  * and only leads to extra job checks */
3323                 if (pi->num_cmds == 0) {
3324                         if (G_interactive_fd)
3325                                 goto check_jobs_and_continue;
3326                         continue;
3327                 }
3328
3329                 /* After analyzing all keywords and conditions, we decided
3330                  * to execute this pipe. NB: have to do checkjobs(NULL)
3331                  * after run_pipe to collect any background children,
3332                  * even if list execution is to be stopped. */
3333                 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3334                 {
3335                         int r;
3336 #if ENABLE_HUSH_LOOPS
3337                         G.flag_break_continue = 0;
3338 #endif
3339                         rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3340                         if (r != -1) {
3341                                 /* We only ran a builtin: rcode is already known
3342                                  * and we don't need to wait for anything. */
3343                                 G.last_exitcode = rcode;
3344                                 debug_printf_exec(": builtin exitcode %d\n", rcode);
3345                                 check_and_run_traps(0);
3346 #if ENABLE_HUSH_LOOPS
3347                                 /* Was it "break" or "continue"? */
3348                                 if (G.flag_break_continue) {
3349                                         smallint fbc = G.flag_break_continue;
3350                                         /* We might fall into outer *loop*,
3351                                          * don't want to break it too */
3352                                         if (loop_top) {
3353                                                 G.depth_break_continue--;
3354                                                 if (G.depth_break_continue == 0)
3355                                                         G.flag_break_continue = 0;
3356                                                 /* else: e.g. "continue 2" should *break* once, *then* continue */
3357                                         } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3358                                         if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3359                                                 goto check_jobs_and_break;
3360                                         /* "continue": simulate end of loop */
3361                                         rword = RES_DONE;
3362                                         continue;
3363                                 }
3364 #endif
3365                         } else if (pi->followup == PIPE_BG) {
3366                                 /* What does bash do with attempts to background builtins? */
3367                                 /* even bash 3.2 doesn't do that well with nested bg:
3368                                  * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3369                                  * I'm NOT treating inner &'s as jobs */
3370                                 check_and_run_traps(0);
3371 #if ENABLE_HUSH_JOB
3372                                 if (G.run_list_level == 1)
3373                                         insert_bg_job(pi);
3374 #endif
3375                                 G.last_exitcode = rcode = EXIT_SUCCESS;
3376                                 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3377                         } else {
3378 #if ENABLE_HUSH_JOB
3379                                 if (G.run_list_level == 1 && G_interactive_fd) {
3380                                         /* Waits for completion, then fg's main shell */
3381                                         rcode = checkjobs_and_fg_shell(pi);
3382                                         debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3383                                         check_and_run_traps(0);
3384                                 } else
3385 #endif
3386                                 { /* This one just waits for completion */
3387                                         rcode = checkjobs(pi);
3388                                         debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3389                                         check_and_run_traps(0);
3390                                 }
3391                                 G.last_exitcode = rcode;
3392                         }
3393                 }
3394
3395                 /* Analyze how result affects subsequent commands */
3396 #if ENABLE_HUSH_IF
3397                 if (rword == RES_IF || rword == RES_ELIF)
3398                         cond_code = rcode;
3399 #endif
3400 #if ENABLE_HUSH_LOOPS
3401                 /* Beware of "while false; true; do ..."! */
3402                 if (pi->next && pi->next->res_word == RES_DO) {
3403                         if (rword == RES_WHILE) {
3404                                 if (rcode) {
3405                                         /* "while false; do...done" - exitcode 0 */
3406                                         G.last_exitcode = rcode = EXIT_SUCCESS;
3407                                         debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3408                                         goto check_jobs_and_break;
3409                                 }
3410                         }
3411                         if (rword == RES_UNTIL) {
3412                                 if (!rcode) {
3413                                         debug_printf_exec(": until expr is true: breaking\n");
3414  check_jobs_and_break:
3415                                         checkjobs(NULL);
3416                                         break;
3417                                 }
3418                         }
3419                 }
3420 #endif
3421
3422  check_jobs_and_continue:
3423                 checkjobs(NULL);
3424         } /* for (pi) */
3425
3426 #if ENABLE_HUSH_JOB
3427 ////    if (G.ctrl_z_flag) {
3428 ////            /* ctrl-Z forked somewhere in the past, we are the child,
3429 ////             * and now we completed running the list. Exit. */
3430 //////TODO: _exit?
3431 ////            exit(rcode);
3432 ////    }
3433  ret:
3434         G.run_list_level--;
3435 ////    if (!G.run_list_level && G_interactive_fd) {
3436 ////            signal(SIGTSTP, SIG_IGN);
3437 ////            signal(SIGINT, SIG_IGN);
3438 ////    }
3439 #endif
3440         debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3441 #if ENABLE_HUSH_LOOPS
3442         if (loop_top)
3443                 G.depth_of_loop--;
3444         free(for_list);
3445 #endif
3446 #if ENABLE_HUSH_CASE
3447         free(case_word);
3448 #endif
3449         return rcode;
3450 }
3451
3452 /* Select which version we will use */
3453 static int run_and_free_list(struct pipe *pi)
3454 {
3455         int rcode = 0;
3456         debug_printf_exec("run_and_free_list entered\n");
3457         if (!G.fake_mode) {
3458                 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3459                 rcode = run_list(pi);
3460         }
3461         /* free_pipe_list has the side effect of clearing memory.
3462          * In the long run that function can be merged with run_list,
3463          * but doing that now would hobble the debugging effort. */
3464         free_pipe_list(pi, /* indent: */ 0);
3465         debug_printf_exec("run_and_free_list return %d\n", rcode);
3466         return rcode;
3467 }
3468
3469
3470 static struct pipe *new_pipe(void)
3471 {
3472         struct pipe *pi;
3473         pi = xzalloc(sizeof(struct pipe));
3474         /*pi->followup = 0; - deliberately invalid value */
3475         /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3476         return pi;
3477 }
3478
3479 /* Command (member of a pipe) is complete. The only possible error here
3480  * is out of memory, in which case xmalloc exits. */
3481 static int done_command(struct parse_context *ctx)
3482 {
3483         /* The command is really already in the pipe structure, so
3484          * advance the pipe counter and make a new, null command. */
3485         struct pipe *pi = ctx->pipe;
3486         struct command *command = ctx->command;
3487
3488         if (command) {
3489                 if (command->group == NULL
3490                  && command->argv == NULL
3491                  && command->redirects == NULL
3492                 ) {
3493                         debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3494                         memset(command, 0, sizeof(*command)); /* paranoia */
3495                         return pi->num_cmds;
3496                 }
3497                 pi->num_cmds++;
3498                 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3499                 //debug_print_tree(ctx->list_head, 20);
3500         } else {
3501                 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3502         }
3503
3504         /* Only real trickiness here is that the uncommitted
3505          * command structure is not counted in pi->num_cmds. */
3506         pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3507         command = &pi->cmds[pi->num_cmds];
3508         memset(command, 0, sizeof(*command));
3509
3510         ctx->command = command;
3511         /* but ctx->pipe and ctx->list_head remain unchanged */
3512
3513         return pi->num_cmds; /* used only for 0/nonzero check */
3514 }
3515
3516 static void done_pipe(struct parse_context *ctx, pipe_style type)
3517 {
3518         int not_null;
3519
3520         debug_printf_parse("done_pipe entered, followup %d\n", type);
3521         /* Close previous command */
3522         not_null = done_command(ctx);
3523         ctx->pipe->followup = type;
3524 #if HAS_KEYWORDS
3525         ctx->pipe->pi_inverted = ctx->ctx_inverted;
3526         ctx->ctx_inverted = 0;
3527         ctx->pipe->res_word = ctx->ctx_res_w;
3528 #endif
3529
3530         /* Without this check, even just <enter> on command line generates
3531          * tree of three NOPs (!). Which is harmless but annoying.
3532          * IOW: it is safe to do it unconditionally.
3533          * RES_NONE case is for "for a in; do ..." (empty IN set)
3534          * and other cases to work. */
3535         if (not_null
3536 #if HAS_KEYWORDS
3537          || ctx->ctx_res_w == RES_FI
3538          || ctx->ctx_res_w == RES_DONE
3539          || ctx->ctx_res_w == RES_FOR
3540          || ctx->ctx_res_w == RES_IN
3541          || ctx->ctx_res_w == RES_ESAC
3542 #endif
3543         ) {
3544                 struct pipe *new_p;
3545                 debug_printf_parse("done_pipe: adding new pipe: "
3546                                 "not_null:%d ctx->ctx_res_w:%d\n",
3547                                 not_null, ctx->ctx_res_w);
3548                 new_p = new_pipe();
3549                 ctx->pipe->next = new_p;
3550                 ctx->pipe = new_p;
3551                 /* RES_THEN, RES_DO etc are "sticky" -
3552                  * they remain set for commands inside if/while.
3553                  * This is used to control execution.
3554                  * RES_FOR and RES_IN are NOT sticky (needed to support
3555                  * cases where variable or value happens to match a keyword):
3556                  */
3557 #if ENABLE_HUSH_LOOPS
3558                 if (ctx->ctx_res_w == RES_FOR
3559                  || ctx->ctx_res_w == RES_IN)
3560                         ctx->ctx_res_w = RES_NONE;
3561 #endif
3562 #if ENABLE_HUSH_CASE
3563                 if (ctx->ctx_res_w == RES_MATCH)
3564                         ctx->ctx_res_w = RES_CASEI;
3565 #endif
3566                 ctx->command = NULL; /* trick done_command below */
3567                 /* Create the memory for command, roughly:
3568                  * ctx->pipe->cmds = new struct command;
3569                  * ctx->command = &ctx->pipe->cmds[0];
3570                  */
3571                 done_command(ctx);
3572                 //debug_print_tree(ctx->list_head, 10);
3573         }
3574         debug_printf_parse("done_pipe return\n");
3575 }
3576
3577 static void initialize_context(struct parse_context *ctx)
3578 {
3579         memset(ctx, 0, sizeof(*ctx));
3580         ctx->pipe = ctx->list_head = new_pipe();
3581         /* Create the memory for command, roughly:
3582          * ctx->pipe->cmds = new struct command;
3583          * ctx->command = &ctx->pipe->cmds[0];
3584          */
3585         done_command(ctx);
3586 }
3587
3588 /* If a reserved word is found and processed, parse context is modified
3589  * and 1 is returned.
3590  */
3591 #if HAS_KEYWORDS
3592 struct reserved_combo {
3593         char literal[6];
3594         unsigned char res;
3595         unsigned char assignment_flag;
3596         int flag;
3597 };
3598 enum {
3599         FLAG_END   = (1 << RES_NONE ),
3600 #if ENABLE_HUSH_IF
3601         FLAG_IF    = (1 << RES_IF   ),
3602         FLAG_THEN  = (1 << RES_THEN ),
3603         FLAG_ELIF  = (1 << RES_ELIF ),
3604         FLAG_ELSE  = (1 << RES_ELSE ),
3605         FLAG_FI    = (1 << RES_FI   ),
3606 #endif
3607 #if ENABLE_HUSH_LOOPS
3608         FLAG_FOR   = (1 << RES_FOR  ),
3609         FLAG_WHILE = (1 << RES_WHILE),
3610         FLAG_UNTIL = (1 << RES_UNTIL),
3611         FLAG_DO    = (1 << RES_DO   ),
3612         FLAG_DONE  = (1 << RES_DONE ),
3613         FLAG_IN    = (1 << RES_IN   ),
3614 #endif
3615 #if ENABLE_HUSH_CASE
3616         FLAG_MATCH = (1 << RES_MATCH),
3617         FLAG_ESAC  = (1 << RES_ESAC ),
3618 #endif
3619         FLAG_START = (1 << RES_XXXX ),
3620 };
3621
3622 static const struct reserved_combo* match_reserved_word(o_string *word)
3623 {
3624         /* Mostly a list of accepted follow-up reserved words.
3625          * FLAG_END means we are done with the sequence, and are ready
3626          * to turn the compound list into a command.
3627          * FLAG_START means the word must start a new compound list.
3628          */
3629         static const struct reserved_combo reserved_list[] = {
3630 #if ENABLE_HUSH_IF
3631                 { "!",     RES_NONE,  NOT_ASSIGNMENT , 0 },
3632                 { "if",    RES_IF,    WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3633                 { "then",  RES_THEN,  WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3634                 { "elif",  RES_ELIF,  WORD_IS_KEYWORD, FLAG_THEN },
3635                 { "else",  RES_ELSE,  WORD_IS_KEYWORD, FLAG_FI   },
3636                 { "fi",    RES_FI,    NOT_ASSIGNMENT , FLAG_END  },
3637 #endif
3638 #if ENABLE_HUSH_LOOPS
3639                 { "for",   RES_FOR,   NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3640                 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3641                 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3642                 { "in",    RES_IN,    NOT_ASSIGNMENT , FLAG_DO   },
3643                 { "do",    RES_DO,    WORD_IS_KEYWORD, FLAG_DONE },
3644                 { "done",  RES_DONE,  NOT_ASSIGNMENT , FLAG_END  },
3645 #endif
3646 #if ENABLE_HUSH_CASE
3647                 { "case",  RES_CASE,  NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3648                 { "esac",  RES_ESAC,  NOT_ASSIGNMENT , FLAG_END  },
3649 #endif
3650         };
3651         const struct reserved_combo *r;
3652
3653         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3654                 if (strcmp(word->data, r->literal) == 0)
3655                         return r;
3656         }
3657         return NULL;
3658 }
3659 static int reserved_word(o_string *word, struct parse_context *ctx)
3660 {
3661 #if ENABLE_HUSH_CASE
3662         static const struct reserved_combo reserved_match = {
3663                 "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3664         };
3665 #endif
3666         const struct reserved_combo *r;
3667
3668         r = match_reserved_word(word);
3669         if (!r)
3670                 return 0;
3671
3672         debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3673 #if ENABLE_HUSH_CASE
3674         if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3675                 /* "case word IN ..." - IN part starts first match part */
3676                 r = &reserved_match;
3677         else
3678 #endif
3679         if (r->flag == 0) { /* '!' */
3680                 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3681                         syntax("! ! command");
3682                         IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3683                 }
3684                 ctx->ctx_inverted = 1;
3685                 return 1;
3686         }
3687         if (r->flag & FLAG_START) {
3688                 struct parse_context *old;
3689                 old = xmalloc(sizeof(*old));
3690                 debug_printf_parse("push stack %p\n", old);
3691                 *old = *ctx;   /* physical copy */
3692                 initialize_context(ctx);
3693                 ctx->stack = old;
3694         } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3695                 syntax(word->data);
3696                 ctx->ctx_res_w = RES_SNTX;
3697                 return 1;
3698         }
3699         ctx->ctx_res_w = r->res;
3700         ctx->old_flag = r->flag;
3701         if (ctx->old_flag & FLAG_END) {
3702                 struct parse_context *old;
3703                 done_pipe(ctx, PIPE_SEQ);
3704                 debug_printf_parse("pop stack %p\n", ctx->stack);
3705                 old = ctx->stack;
3706                 old->command->group = ctx->list_head;
3707                 old->command->grp_type = GRP_NORMAL;
3708 #if !BB_MMU
3709                 o_addstr(&old->as_string, ctx->as_string.data);
3710                 o_free_unsafe(&ctx->as_string);
3711                 old->command->group_as_string = xstrdup(old->as_string.data);
3712                 debug_printf_parse("pop, remembering as:'%s'\n",
3713                                 old->command->group_as_string);
3714 #endif
3715                 *ctx = *old;   /* physical copy */
3716                 free(old);
3717         }
3718         word->o_assignment = r->assignment_flag;
3719         return 1;
3720 }
3721 #endif
3722
3723 /* Word is complete, look at it and update parsing context.
3724  * Normal return is 0. Syntax errors return 1.
3725  * Note: on return, word is reset, but not o_free'd!
3726  */
3727 static int done_word(o_string *word, struct parse_context *ctx)
3728 {
3729         struct command *command = ctx->command;
3730
3731         debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3732         if (word->length == 0 && word->nonnull == 0) {
3733                 debug_printf_parse("done_word return 0: true null, ignored\n");
3734                 return 0;
3735         }
3736         /* If this word wasn't an assignment, next ones definitely
3737          * can't be assignments. Even if they look like ones. */
3738         if (word->o_assignment != DEFINITELY_ASSIGNMENT
3739          && word->o_assignment != WORD_IS_KEYWORD
3740         ) {
3741                 word->o_assignment = NOT_ASSIGNMENT;
3742         } else {
3743                 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3744                         command->assignment_cnt++;
3745                 word->o_assignment = MAYBE_ASSIGNMENT;
3746         }
3747
3748         if (ctx->pending_redirect) {
3749                 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3750                  * only if run as "bash", not "sh" */
3751                 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3752                  * "2.7 Redirection
3753                  * ...the word that follows the redirection operator
3754                  * shall be subjected to tilde expansion, parameter expansion,
3755                  * command substitution, arithmetic expansion, and quote
3756                  * removal. Pathname expansion shall not be performed
3757                  * on the word by a non-interactive shell; an interactive
3758                  * shell may perform it, but shall do so only when
3759                  * the expansion would result in one word."
3760                  */
3761                 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3762                 word->o_assignment = NOT_ASSIGNMENT;
3763                 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3764         } else {
3765                 /* "{ echo foo; } echo bar" - bad */
3766                 /* NB: bash allows e.g.:
3767                  * if true; then { echo foo; } fi
3768                  * while if false; then false; fi do break; done
3769                  * and disallows:
3770                  * while if false; then false; fi; do; break; done
3771                  * TODO? */
3772                 if (command->group) {
3773                         syntax(word->data);
3774                         debug_printf_parse("done_word return 1: syntax error, "
3775                                         "groups and arglists don't mix\n");
3776                         return 1;
3777                 }
3778 #if HAS_KEYWORDS
3779 #if ENABLE_HUSH_CASE
3780                 if (ctx->ctx_dsemicolon
3781                  && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3782                 ) {
3783                         /* already done when ctx_dsemicolon was set to 1: */
3784                         /* ctx->ctx_res_w = RES_MATCH; */
3785                         ctx->ctx_dsemicolon = 0;
3786                 } else
3787 #endif
3788                 if (!command->argv /* if it's the first word... */
3789 #if ENABLE_HUSH_LOOPS
3790                  && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3791                  && ctx->ctx_res_w != RES_IN
3792 #endif
3793                 ) {
3794                         debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3795                         if (reserved_word(word, ctx)) {
3796                                 o_reset(word);
3797                                 debug_printf_parse("done_word return %d\n",
3798                                                 (ctx->ctx_res_w == RES_SNTX));
3799                                 return (ctx->ctx_res_w == RES_SNTX);
3800                         }
3801                 }
3802 #endif
3803                 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3804                  /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3805                  && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3806                  /* (otherwise it's known to be not empty and is already safe) */
3807                 ) {
3808                         /* exclude "$@" - it can expand to no word despite "" */
3809                         char *p = word->data;
3810                         while (p[0] == SPECIAL_VAR_SYMBOL
3811                             && (p[1] & 0x7f) == '@'
3812                             && p[2] == SPECIAL_VAR_SYMBOL
3813                         ) {
3814                                 p += 3;
3815                         }
3816                         if (p == word->data || p[0] != '\0') {
3817                                 /* saw no "$@", or not only "$@" but some
3818                                  * real text is there too */
3819                                 /* insert "empty variable" reference, this makes
3820                                  * e.g. "", $empty"" etc to not disappear */
3821                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3822                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3823                         }
3824                 }
3825                 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3826                 debug_print_strings("word appended to argv", command->argv);
3827         }
3828
3829         o_reset(word);
3830         ctx->pending_redirect = NULL;
3831
3832 #if ENABLE_HUSH_LOOPS
3833         /* Force FOR to have just one word (variable name) */
3834         /* NB: basically, this makes hush see "for v in ..." syntax as if
3835          * as it is "for v; in ...". FOR and IN become two pipe structs
3836          * in parse tree. */
3837         if (ctx->ctx_res_w == RES_FOR) {
3838 //TODO: check that command->argv[0] is a valid variable name!
3839                 done_pipe(ctx, PIPE_SEQ);
3840         }
3841 #endif
3842 #if ENABLE_HUSH_CASE
3843         /* Force CASE to have just one word */
3844         if (ctx->ctx_res_w == RES_CASE) {
3845                 done_pipe(ctx, PIPE_SEQ);
3846         }
3847 #endif
3848         debug_printf_parse("done_word return 0\n");
3849         return 0;
3850 }
3851
3852
3853 /* Peek ahead in the input to find out if we have a "&n" construct,
3854  * as in "2>&1", that represents duplicating a file descriptor.
3855  * Return: -3 if >&- "close fd" construct is seen,
3856  * -2 (syntax error), -1 if no & was seen, or the number found.
3857  */
3858 #if BB_MMU
3859 #define redirect_dup_num(as_string, input) \
3860         redirect_dup_num(input)
3861 #endif
3862 static int redirect_dup_num(o_string *as_string, struct in_str *input)
3863 {
3864         int ch, d, ok;
3865
3866         ch = i_peek(input);
3867         if (ch != '&')
3868                 return -1;
3869
3870         ch = i_getch(input);  /* get the & */
3871 #if !BB_MMU
3872         o_addchr(as_string, ch);
3873 #endif
3874         ch = i_peek(input);
3875         if (ch == '-') {
3876                 ch = i_getch(input);
3877 #if !BB_MMU
3878                 o_addchr(as_string, ch);
3879 #endif
3880                 return -3;  /* "-" represents "close me" */
3881         }
3882         d = 0;
3883         ok = 0;
3884         while (ch != EOF && isdigit(ch)) {
3885                 d = d*10 + (ch-'0');
3886                 ok = 1;
3887                 ch = i_getch(input);
3888 #if !BB_MMU
3889                 o_addchr(as_string, ch);
3890 #endif
3891                 ch = i_peek(input);
3892         }
3893         if (ok) return d;
3894
3895 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3896
3897         bb_error_msg("ambiguous redirect");
3898         return -2;
3899 }
3900
3901 /* Return code is 0 normally, 1 if a syntax error is detected
3902  */
3903 static int parse_redirect(struct parse_context *ctx,
3904                 int fd,
3905                 redir_type style,
3906                 struct in_str *input)
3907 {
3908         struct command *command = ctx->command;
3909         struct redir_struct *redir;
3910         struct redir_struct **redirp;
3911         int dup_num;
3912
3913         dup_num = -1;
3914         if (style != REDIRECT_HEREDOC) {
3915                 /* Check for a '2>&1' type redirect */
3916                 dup_num = redirect_dup_num(&ctx->as_string, input);
3917                 if (dup_num == -2)
3918                         return 1;  /* syntax error */
3919         }
3920 //TODO: else { check for <<-word }
3921
3922         if (style == REDIRECT_OVERWRITE && dup_num == -1) {
3923                 int ch = i_peek(input);
3924                 if (ch == '|') {
3925                         /* >|FILE redirect ("clobbering" >).
3926                          * Since we do not support "set -o noclobber" yet,
3927                          * >| and > are the same for now. Just eat |.
3928                          */
3929                         ch = i_getch(input);
3930 #if !BB_MMU
3931                         o_addchr(&ctx->as_string, ch);
3932 #endif
3933                 }
3934         }
3935
3936         /* Create a new redir_struct and append it to the linked list */
3937         redirp = &command->redirects;
3938         while ((redir = *redirp) != NULL) {
3939                 redirp = &(redir->next);
3940         }
3941         *redirp = redir = xzalloc(sizeof(*redir));
3942         /* redir->next = NULL; */
3943         /* redir->rd_filename = NULL; */
3944         redir->rd_type = style;
3945         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3946
3947         debug_printf_parse("redirect type %d %s\n", redir->fd, redir_table[style].descrip);
3948
3949         redir->dup = dup_num;
3950         if (dup_num != -1) {
3951                 /* Erik had a check here that the file descriptor in question
3952                  * is legit; I postpone that to "run time"
3953                  * A "-" representation of "close me" shows up as a -3 here */
3954                 debug_printf_parse("duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3955         } else {
3956                 /* Set ctx->pending_redirect, so we know what to do at the
3957                  * end of the next parsed word. */
3958                 ctx->pending_redirect = redir;
3959         }
3960         return 0;
3961 }
3962
3963 /* If a redirect is immediately preceded by a number, that number is
3964  * supposed to tell which file descriptor to redirect.  This routine
3965  * looks for such preceding numbers.  In an ideal world this routine
3966  * needs to handle all the following classes of redirects...
3967  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
3968  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
3969  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
3970  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
3971  *
3972  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3973  * "2.7 Redirection
3974  * ... If n is quoted, the number shall not be recognized as part of
3975  * the redirection expression. For example:
3976  * echo \2>a
3977  * writes the character 2 into file a"
3978  * I am not sure we do it right (and not sure we care)
3979  *
3980  * A -1 return means no valid number was found,
3981  * the caller should use the appropriate default for this redirection.
3982  */
3983 static int redirect_opt_num(o_string *o)
3984 {
3985         int num;
3986
3987         if (o->data == NULL)
3988                 return -1;
3989         num = bb_strtou(o->data, NULL, 10);
3990         if (errno || num < 0)
3991                 return -1;
3992         o_reset(o);
3993         return num;
3994 }
3995
3996 //TODO: add NOMMU as_string fill
3997 static char *fetch_till_str(struct in_str *input, const char *word)
3998 {
3999         o_string heredoc = NULL_O_STRING;
4000         int past_EOL = 0;
4001         int ch;
4002
4003         while (1) {
4004                 ch = i_getch(input);
4005                 if (ch == EOF) {
4006                         o_free_unsafe(&heredoc);
4007                         return NULL;
4008                 }
4009                 if (ch == '\n') {
4010                         if (strcmp(heredoc.data + past_EOL, word) == 0) {
4011                                 heredoc.data[past_EOL] = '\0';
4012                                 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4013                                 return heredoc.data;
4014                         }
4015                         past_EOL = heredoc.length + 1;
4016                 }
4017                 o_addchr(&heredoc, ch);
4018         }
4019 }
4020
4021 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4022 {
4023         struct pipe *pi = ctx->list_head;
4024
4025         while (pi) {
4026                 int i;
4027                 struct command *cmd = pi->cmds;
4028
4029                 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4030                                 pi->num_cmds,
4031                                 cmd->argv ? cmd->argv[0] : "NONE");
4032                 for (i = 0; i < pi->num_cmds; i++) {
4033                         struct redir_struct *redirect = cmd->redirects;
4034
4035                         debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4036                                         i, cmd->argv ? cmd->argv[0] : "NONE");
4037                         while (redirect) {
4038                                 if (redirect->rd_type == REDIRECT_HEREDOC) {
4039                                         char *p;
4040
4041                                         if (heredoc_cnt <= 0)
4042                                                 return 1; /* error */
4043                                         redirect->rd_type = REDIRECT_HEREDOC2;
4044                                         p = fetch_till_str(input, redirect->rd_filename);
4045                                         if (!p)
4046                                                 return 1; /* unexpected EOF */
4047                                         free(redirect->rd_filename);
4048                                         redirect->rd_filename = p;
4049                                         heredoc_cnt--;
4050                                 }
4051                                 redirect = redirect->next;
4052                         }
4053                         cmd++;
4054                 }
4055                 pi = pi->next;
4056         }
4057         /* Should be 0. If it isn't, it's a parse error */
4058         return heredoc_cnt;
4059 }
4060
4061
4062 #if BB_MMU
4063 #define parse_stream(pstring, input, end_trigger) \
4064         parse_stream(input, end_trigger)
4065 #endif
4066 static struct pipe *parse_stream(char **pstring,
4067                 struct in_str *input,
4068                 int end_trigger);
4069 static void parse_and_run_string(const char *s);
4070
4071 #if ENABLE_HUSH_TICK
4072 static FILE *generate_stream_from_string(const char *s)
4073 {
4074         FILE *pf;
4075         int pid, channel[2];
4076
4077         xpipe(channel);
4078         pid = BB_MMU ? fork() : vfork();
4079         if (pid < 0)
4080                 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4081
4082         if (pid == 0) { /* child */
4083 #if ENABLE_HUSH_JOB
4084                 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
4085 #endif
4086                 /* Process substitution is not considered to be usual
4087                  * 'command execution'.
4088                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4089                  */
4090                 bb_signals(0
4091                         + (1 << SIGTSTP)
4092                         + (1 << SIGTTIN)
4093                         + (1 << SIGTTOU)
4094                         , SIG_IGN);
4095                 close(channel[0]); /* NB: close _first_, then move fd! */
4096                 xmove_fd(channel[1], 1);
4097                 /* Prevent it from trying to handle ctrl-z etc */
4098                 USE_HUSH_JOB(G.run_list_level = 1;)
4099 #if BB_MMU
4100                 reset_traps_to_defaults();
4101                 parse_and_run_string(s);
4102                 _exit(G.last_exitcode);
4103 #else
4104         /* We re-execute after vfork on NOMMU. This makes this script safe:
4105          * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4106          * huge=`cat BIG` # was blocking here forever
4107          * echo OK
4108          */
4109                 re_execute_shell(s);
4110 #endif
4111         }
4112
4113         /* parent */
4114 #if ENABLE_HUSH_JOB
4115         die_sleep = -1; /* restore tty pgrp on xfunc death */
4116 #endif
4117         clean_up_after_re_execute();
4118         close(channel[1]);
4119         pf = fdopen(channel[0], "r");
4120         return pf;
4121 }
4122
4123 /* Return code is exit status of the process that is run. */
4124 static int process_command_subs(o_string *dest, const char *s)
4125 {
4126         FILE *pf;
4127         struct in_str pipe_str;
4128         int ch, eol_cnt;
4129
4130         pf = generate_stream_from_string(s);
4131         if (pf == NULL)
4132                 return 1;
4133         close_on_exec_on(fileno(pf));
4134
4135         /* Now send results of command back into original context */
4136         setup_file_in_str(&pipe_str, pf);
4137         eol_cnt = 0;
4138         while ((ch = i_getch(&pipe_str)) != EOF) {
4139                 if (ch == '\n') {
4140                         eol_cnt++;
4141                         continue;
4142                 }
4143                 while (eol_cnt) {
4144                         o_addchr(dest, '\n');
4145                         eol_cnt--;
4146                 }
4147                 o_addQchr(dest, ch);
4148         }
4149
4150         debug_printf("done reading from pipe, pclose()ing\n");
4151         /* Note: we got EOF, and we just close the read end of the pipe.
4152          * We do not wait for the `cmd` child to terminate. bash and ash do.
4153          * Try these:
4154          * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4155          * `false`; echo $? - bash outputs "1"
4156          */
4157         fclose(pf);
4158         debug_printf("closed FILE from child. return 0\n");
4159         return 0;
4160 }
4161 #endif
4162
4163 static int parse_group(o_string *dest, struct parse_context *ctx,
4164         struct in_str *input, int ch)
4165 {
4166         /* dest contains characters seen prior to ( or {.
4167          * Typically it's empty, but for function defs,
4168          * it contains function name (without '()'). */
4169         struct pipe *pipe_list;
4170         int endch;
4171         struct command *command = ctx->command;
4172
4173         debug_printf_parse("parse_group entered\n");
4174 #if ENABLE_HUSH_FUNCTIONS
4175         if (ch == 'F') { /* function definition? */
4176                 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4177                 //command->fname = dest->data;
4178                 command->grp_type = GRP_FUNCTION;
4179 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4180                 memset(dest, 0, sizeof(*dest));
4181         }
4182 #endif
4183         if (command->argv /* word [word](... */
4184          || dest->length /* word(... */
4185          || dest->nonnull /* ""(... */
4186         ) {
4187                 syntax(NULL);
4188                 debug_printf_parse("parse_group return 1: "
4189                         "syntax error, groups and arglists don't mix\n");
4190                 return 1;
4191         }
4192         endch = '}';
4193         if (ch == '(') {
4194                 endch = ')';
4195                 command->grp_type = GRP_SUBSHELL;
4196         }
4197         {
4198 #if !BB_MMU
4199                 char *as_string = NULL;
4200 #endif
4201                 pipe_list = parse_stream(&as_string, input, endch);
4202 #if !BB_MMU
4203                 if (as_string)
4204                         o_addstr(&ctx->as_string, as_string);
4205 #endif
4206                 /* empty ()/{} or parse error? */
4207                 if (!pipe_list || pipe_list == ERR_PTR) {
4208 #if !BB_MMU
4209                         free(as_string);
4210 #endif
4211                         syntax(NULL);
4212                         debug_printf_parse("parse_group return 1: "
4213                                 "parse_stream returned %p\n", pipe_list);
4214                         return 1;
4215                 }
4216                 command->group = pipe_list;
4217 #if !BB_MMU
4218                 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4219                 command->group_as_string = as_string;
4220                 debug_printf_parse("end of group, remembering as:'%s'\n",
4221                                 command->group_as_string);
4222 #endif
4223         }
4224         debug_printf_parse("parse_group return 0\n");
4225         return 0;
4226         /* command remains "open", available for possible redirects */
4227 }
4228
4229 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4230 /* Subroutines for copying $(...) and `...` things */
4231 static void add_till_backquote(o_string *dest, struct in_str *input);
4232 /* '...' */
4233 static void add_till_single_quote(o_string *dest, struct in_str *input)
4234 {
4235         while (1) {
4236                 int ch = i_getch(input);
4237                 if (ch == EOF)
4238                         break;
4239                 if (ch == '\'')
4240                         break;
4241                 o_addchr(dest, ch);
4242         }
4243 }
4244 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4245 static void add_till_double_quote(o_string *dest, struct in_str *input)
4246 {
4247         while (1) {
4248                 int ch = i_getch(input);
4249                 if (ch == '"')
4250                         break;
4251                 if (ch == '\\') {  /* \x. Copy both chars. */
4252                         o_addchr(dest, ch);
4253                         ch = i_getch(input);
4254                 }
4255                 if (ch == EOF)
4256                         break;
4257                 o_addchr(dest, ch);
4258                 if (ch == '`') {
4259                         add_till_backquote(dest, input);
4260                         o_addchr(dest, ch);
4261                         continue;
4262                 }
4263                 //if (ch == '$') ...
4264         }
4265 }
4266 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4267  * \` quoting.
4268  * "Within the backquoted style of command substitution, backslash
4269  * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4270  * The search for the matching backquote shall be satisfied by the first
4271  * backquote found without a preceding backslash; during this search,
4272  * if a non-escaped backquote is encountered within a shell comment,
4273  * a here-document, an embedded command substitution of the $(command)
4274  * form, or a quoted string, undefined results occur. A single-quoted
4275  * or double-quoted string that begins, but does not end, within the
4276  * "`...`" sequence produces undefined results."
4277  * Example                               Output
4278  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
4279  */
4280 static void add_till_backquote(o_string *dest, struct in_str *input)
4281 {
4282         while (1) {
4283                 int ch = i_getch(input);
4284                 if (ch == '`')
4285                         break;
4286                 if (ch == '\\') {  /* \x. Copy both chars unless it is \` */
4287                         int ch2 = i_getch(input);
4288                         if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4289                                 o_addchr(dest, ch);
4290                         ch = ch2;
4291                 }
4292                 if (ch == EOF)
4293                         break;
4294                 o_addchr(dest, ch);
4295         }
4296 }
4297 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4298  * quoting and nested ()s.
4299  * "With the $(command) style of command substitution, all characters
4300  * following the open parenthesis to the matching closing parenthesis
4301  * constitute the command. Any valid shell script can be used for command,
4302  * except a script consisting solely of redirections which produces
4303  * unspecified results."
4304  * Example                              Output
4305  * echo $(echo '(TEST)' BEST)           (TEST) BEST
4306  * echo $(echo 'TEST)' BEST)            TEST) BEST
4307  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
4308  */
4309 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4310 {
4311         int count = 0;
4312         while (1) {
4313                 int ch = i_getch(input);
4314                 if (ch == EOF)
4315                         break;
4316                 if (ch == '(')
4317                         count++;
4318                 if (ch == ')') {
4319                         if (--count < 0) {
4320                                 if (!dbl)
4321                                         break;
4322                                 if (i_peek(input) == ')') {
4323                                         i_getch(input);
4324                                         break;
4325                                 }
4326                         }
4327                 }
4328                 o_addchr(dest, ch);
4329                 if (ch == '\'') {
4330                         add_till_single_quote(dest, input);
4331                         o_addchr(dest, ch);
4332                         continue;
4333                 }
4334                 if (ch == '"') {
4335                         add_till_double_quote(dest, input);
4336                         o_addchr(dest, ch);
4337                         continue;
4338                 }
4339                 if (ch == '\\') { /* \x. Copy verbatim. Important for  \(, \) */
4340                         ch = i_getch(input);
4341                         if (ch == EOF)
4342                                 break;
4343                         o_addchr(dest, ch);
4344                         continue;
4345                 }
4346         }
4347 }
4348 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4349
4350 /* Return code: 0 for OK, 1 for syntax error */
4351 #if BB_MMU
4352 #define handle_dollar(as_string, dest, input) \
4353         handle_dollar(dest, input)
4354 #endif
4355 static int handle_dollar(o_string *as_string,
4356                 o_string *dest,
4357                 struct in_str *input)
4358 {
4359         int expansion;
4360         int ch = i_peek(input);  /* first character after the $ */
4361         unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4362
4363         debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4364         if (isalpha(ch)) {
4365                 ch = i_getch(input);
4366 #if !BB_MMU
4367                 if (as_string) o_addchr(as_string, ch);
4368 #endif
4369  make_var:
4370                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4371                 while (1) {
4372                         debug_printf_parse(": '%c'\n", ch);
4373                         o_addchr(dest, ch | quote_mask);
4374                         quote_mask = 0;
4375                         ch = i_peek(input);
4376                         if (!isalnum(ch) && ch != '_')
4377                                 break;
4378                         ch = i_getch(input);
4379 #if !BB_MMU
4380                         if (as_string) o_addchr(as_string, ch);
4381 #endif
4382                 }
4383                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4384         } else if (isdigit(ch)) {
4385  make_one_char_var:
4386                 ch = i_getch(input);
4387 #if !BB_MMU
4388                 if (as_string) o_addchr(as_string, ch);
4389 #endif
4390                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4391                 debug_printf_parse(": '%c'\n", ch);
4392                 o_addchr(dest, ch | quote_mask);
4393                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4394         } else switch (ch) {
4395         case '$': /* pid */
4396         case '!': /* last bg pid */
4397         case '?': /* last exit code */
4398         case '#': /* number of args */
4399         case '*': /* args */
4400         case '@': /* args */
4401                 goto make_one_char_var;
4402         case '{': {
4403                 bool first_char, all_digits;
4404
4405                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4406                 ch = i_getch(input);
4407 #if !BB_MMU
4408                 if (as_string) o_addchr(as_string, ch);
4409 #endif
4410                 /* XXX maybe someone will try to escape the '}' */
4411                 expansion = 0;
4412                 first_char = true;
4413                 all_digits = false;
4414                 while (1) {
4415                         ch = i_getch(input);
4416 #if !BB_MMU
4417                         if (as_string) o_addchr(as_string, ch);
4418 #endif
4419                         if (ch == '}')
4420                                 break;
4421
4422                         if (first_char) {
4423                                 if (ch == '#')
4424                                         /* ${#var}: length of var contents */
4425                                         goto char_ok;
4426                                 else if (isdigit(ch)) {
4427                                         all_digits = true;
4428                                         goto char_ok;
4429                                 }
4430                         }
4431
4432                         if (expansion < 2
4433                          && (  (all_digits && !isdigit(ch))
4434                             || (!all_digits && !isalnum(ch) && ch != '_')
4435                             )
4436                         ) {
4437                                 /* handle parameter expansions
4438                                  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4439                                  */
4440                                 if (first_char)
4441                                         goto case_default;
4442                                 switch (ch) {
4443                                 case ':': /* null modifier */
4444                                         if (expansion == 0) {
4445                                                 debug_printf_parse(": null modifier\n");
4446                                                 ++expansion;
4447                                                 break;
4448                                         }
4449                                         goto case_default;
4450                                 case '#': /* remove prefix */
4451                                 case '%': /* remove suffix */
4452                                         if (expansion == 0) {
4453                                                 debug_printf_parse(": remove suffix/prefix\n");
4454                                                 expansion = 2;
4455                                                 break;
4456                                         }
4457                                         goto case_default;
4458                                 case '-': /* default value */
4459                                 case '=': /* assign default */
4460                                 case '+': /* alternative */
4461                                 case '?': /* error indicate */
4462                                         debug_printf_parse(": parameter expansion\n");
4463                                         expansion = 2;
4464                                         break;
4465                                 default:
4466                                 case_default:
4467                                         syntax("unterminated ${name}");
4468                                         debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4469                                         return 1;
4470                                 }
4471                         }
4472  char_ok:
4473                         debug_printf_parse(": '%c'\n", ch);
4474                         o_addchr(dest, ch | quote_mask);
4475                         quote_mask = 0;
4476                         first_char = false;
4477                 }
4478                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4479                 break;
4480         }
4481 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4482         case '(': {
4483 # if !BB_MMU
4484                 int pos;
4485 # endif
4486                 ch = i_getch(input);
4487 # if !BB_MMU
4488                 if (as_string) o_addchr(as_string, ch);
4489 # endif
4490 # if ENABLE_SH_MATH_SUPPORT
4491                 if (i_peek(input) == '(') {
4492                         ch = i_getch(input);
4493 #  if !BB_MMU
4494                         if (as_string) o_addchr(as_string, ch);
4495 #  endif
4496                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4497                         o_addchr(dest, /*quote_mask |*/ '+');
4498 #  if !BB_MMU
4499                         pos = dest->length;
4500 #  endif
4501                         add_till_closing_paren(dest, input, true);
4502 #  if !BB_MMU
4503                         if (as_string) {
4504                                 o_addstr(as_string, dest->data + pos);
4505                                 o_addchr(as_string, ')');
4506                                 o_addchr(as_string, ')');
4507                         }
4508 #  endif
4509                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4510                         break;
4511                 }
4512 # endif
4513 # if ENABLE_HUSH_TICK
4514                 //int pos = dest->length;
4515                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4516                 o_addchr(dest, quote_mask | '`');
4517 #  if !BB_MMU
4518                 pos = dest->length;
4519 #  endif
4520                 add_till_closing_paren(dest, input, false);
4521 #  if !BB_MMU
4522                 if (as_string) {
4523                         o_addstr(as_string, dest->data + pos);
4524                         o_addchr(as_string, '`');
4525                 }
4526 #  endif
4527                 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4528                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4529 # endif
4530                 break;
4531         }
4532 #endif
4533         case '_':
4534                 ch = i_getch(input);
4535 #if !BB_MMU
4536                 if (as_string) o_addchr(as_string, ch);
4537 #endif
4538                 ch = i_peek(input);
4539                 if (isalnum(ch)) { /* it's $_name or $_123 */
4540                         ch = '_';
4541                         goto make_var;
4542                 }
4543                 /* else: it's $_ */
4544         /* TODO: */
4545         /* $_ Shell or shell script name; or last cmd name */
4546         /* $- Option flags set by set builtin or shell options (-i etc) */
4547         default:
4548                 o_addQchr(dest, '$');
4549         }
4550         debug_printf_parse("handle_dollar return 0\n");
4551         return 0;
4552 }
4553
4554 #if BB_MMU
4555 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4556         parse_stream_dquoted(dest, input, dquote_end)
4557 #endif
4558 static int parse_stream_dquoted(o_string *as_string,
4559                 o_string *dest,
4560                 struct in_str *input,
4561                 int dquote_end)
4562 {
4563         int ch;
4564         int next;
4565
4566  again:
4567         ch = i_getch(input);
4568 #if !BB_MMU
4569         if (as_string && ch != EOF) o_addchr(as_string, ch);
4570 #endif
4571         if (ch == dquote_end) { /* may be only '"' or EOF */
4572                 dest->nonnull = 1;
4573                 if (dest->o_assignment == NOT_ASSIGNMENT)
4574                         dest->o_escape ^= 1;
4575                 debug_printf_parse("parse_stream_dquoted return 0\n");
4576                 return 0;
4577         }
4578         if (ch == EOF) {
4579                 syntax("unterminated \"");
4580                 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4581                 return 1;
4582         }
4583         next = '\0';
4584         if (ch != '\n') {
4585                 next = i_peek(input);
4586         }
4587         debug_printf_parse(": ch=%c (%d) escape=%d\n",
4588                                         ch, ch, dest->o_escape);
4589         if (ch == '\\') {
4590                 if (next == EOF) {
4591                         syntax("\\<eof>");
4592                         debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4593                         return 1;
4594                 }
4595                 /* bash:
4596                  * "The backslash retains its special meaning [in "..."]
4597                  * only when followed by one of the following characters:
4598                  * $, `, ", \, or <newline>.  A double quote may be quoted
4599                  * within double quotes by preceding it with a backslash.
4600                  * If enabled, history expansion will be performed unless
4601                  * an ! appearing in double quotes is escaped using
4602                  * a backslash. The backslash preceding the ! is not removed."
4603                  */
4604                 if (strchr("$`\"\\", next) != NULL) {
4605                         o_addqchr(dest, i_getch(input));
4606                 } else {
4607                         o_addqchr(dest, '\\');
4608                 }
4609                 goto again;
4610         }
4611         if (ch == '$') {
4612                 if (handle_dollar(as_string, dest, input) != 0) {
4613                         debug_printf_parse("parse_stream_dquoted return 1: "
4614                                         "handle_dollar returned non-0\n");
4615                         return 1;
4616                 }
4617                 goto again;
4618         }
4619 #if ENABLE_HUSH_TICK
4620         if (ch == '`') {
4621                 //int pos = dest->length;
4622                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4623                 o_addchr(dest, 0x80 | '`');
4624                 add_till_backquote(dest, input);
4625                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4626                 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4627                 goto again;
4628         }
4629 #endif
4630         o_addQchr(dest, ch);
4631         if (ch == '='
4632          && (dest->o_assignment == MAYBE_ASSIGNMENT
4633             || dest->o_assignment == WORD_IS_KEYWORD)
4634          && is_assignment(dest->data)
4635         ) {
4636                 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4637         }
4638         goto again;
4639 }
4640
4641 /*
4642  * Scan input until EOF or end_trigger char.
4643  * Return a list of pipes to execute, or NULL on EOF
4644  * or if end_trigger character is met.
4645  * On syntax error, exit is shell is not interactive,
4646  * reset parsing machinery and start parsing anew,
4647  * or return ERR_PTR.
4648  */
4649 static struct pipe *parse_stream(char **pstring,
4650                 struct in_str *input,
4651                 int end_trigger)
4652 {
4653         struct parse_context ctx;
4654         o_string dest = NULL_O_STRING;
4655         int is_in_dquote;
4656         int heredoc_cnt;
4657
4658         /* Double-quote state is handled in the state variable is_in_dquote.
4659          * A single-quote triggers a bypass of the main loop until its mate is
4660          * found.  When recursing, quote state is passed in via dest->o_escape.
4661          */
4662         debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4663                         end_trigger ? : 'X');
4664
4665         G.ifs = get_local_var_value("IFS");
4666         if (G.ifs == NULL)
4667                 G.ifs = " \t\n";
4668
4669  reset:
4670 #if ENABLE_HUSH_INTERACTIVE
4671         input->promptmode = 0; /* PS1 */
4672 #endif
4673         /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4674         initialize_context(&ctx);
4675         is_in_dquote = 0;
4676         heredoc_cnt = 0;
4677         while (1) {
4678                 const char *is_ifs;
4679                 const char *is_special;
4680                 int ch;
4681                 int next;
4682                 int redir_fd;
4683                 redir_type redir_style;
4684
4685                 if (is_in_dquote) {
4686                         if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4687                                 goto parse_error;
4688                         }
4689                         /* We reached closing '"' */
4690                         is_in_dquote = 0;
4691                 }
4692                 ch = i_getch(input);
4693                 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4694                                                 ch, ch, dest.o_escape);
4695                 if (ch == EOF) {
4696                         struct pipe *pi;
4697
4698                         if (heredoc_cnt) {
4699                                 syntax("unterminated here document");
4700                                 goto parse_error;
4701                         }
4702                         if (done_word(&dest, &ctx)) {
4703                                 goto parse_error;
4704                         }
4705                         o_free(&dest);
4706                         done_pipe(&ctx, PIPE_SEQ);
4707                         pi = ctx.list_head;
4708                         /* If we got nothing... */
4709 // TODO: test script consisting of just "&"
4710                         if (pi->num_cmds == 0
4711                             IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4712                         ) {
4713                                 free_pipe_list(pi, 0);
4714                                 pi = NULL;
4715                         }
4716                         debug_printf_parse("parse_stream return %p\n", pi);
4717 #if !BB_MMU
4718                         debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4719                         if (pstring)
4720                                 *pstring = ctx.as_string.data;
4721                         else
4722                                 o_free_unsafe(&ctx.as_string);
4723 #endif
4724                         return pi;
4725                 }
4726 #if !BB_MMU
4727                 o_addchr(&ctx.as_string, ch);
4728 #endif
4729                 is_ifs = strchr(G.ifs, ch);
4730                 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4731                                 "\\$\"" USE_HUSH_TICK("`") /* always special */
4732                                 , ch);
4733
4734                 if (!is_special && !is_ifs) { /* ordinary char */
4735                         o_addQchr(&dest, ch);
4736                         if ((dest.o_assignment == MAYBE_ASSIGNMENT
4737                             || dest.o_assignment == WORD_IS_KEYWORD)
4738                          && ch == '='
4739                          && is_assignment(dest.data)
4740                         ) {
4741                                 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4742                         }
4743                         continue;
4744                 }
4745
4746                 if (is_ifs) {
4747                         if (done_word(&dest, &ctx)) {
4748                                 goto parse_error;
4749                         }
4750                         if (ch == '\n') {
4751 #if ENABLE_HUSH_CASE
4752                                 /* "case ... in <newline> word) ..." -
4753                                  * newlines are ignored (but ';' wouldn't be) */
4754                                 if (ctx.command->argv == NULL
4755                                  && ctx.ctx_res_w == RES_MATCH
4756                                 ) {
4757                                         continue;
4758                                 }
4759 #endif
4760                                 /* Treat newline as a command separator. */
4761                                 done_pipe(&ctx, PIPE_SEQ);
4762                                 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4763                                 if (heredoc_cnt) {
4764                                         if (fetch_heredocs(heredoc_cnt, &ctx, input))
4765                                                 goto parse_error;
4766                                         heredoc_cnt = 0;
4767                                 }
4768                                 dest.o_assignment = MAYBE_ASSIGNMENT;
4769                                 ch = ';';
4770                                 /* note: if (is_ifs) continue;
4771                                  * will still trigger for us */
4772                         }
4773                 }
4774                 if (end_trigger && end_trigger == ch
4775                  && (heredoc_cnt == 0 || end_trigger != ';')
4776                 ) {
4777 //TODO: disallow "{ cmd }" without semicolon
4778                         if (heredoc_cnt) {
4779                                 /* This is technically valid:
4780                                  * { cat <<HERE; }; echo Ok
4781                                  * heredoc
4782                                  * heredoc
4783                                  * heredoc
4784                                  * HERE
4785                                  * but we don't support this.
4786                                  * We require heredoc to be in enclosing {}/(),
4787                                  * if any.
4788                                  */
4789                                 syntax("unterminated here document");
4790                                 goto parse_error;
4791                         }
4792                         if (done_word(&dest, &ctx)) {
4793                                 goto parse_error;
4794                         }
4795                         done_pipe(&ctx, PIPE_SEQ);
4796                         dest.o_assignment = MAYBE_ASSIGNMENT;
4797                         /* Do we sit outside of any if's, loops or case's? */
4798                         if (!HAS_KEYWORDS
4799                          IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4800                         ) {
4801                                 debug_printf_parse("parse_stream return %p: "
4802                                                 "end_trigger char found\n",
4803                                                 ctx.list_head);
4804                                 o_free(&dest);
4805 #if !BB_MMU
4806                                 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4807                                 if (pstring)
4808                                         *pstring = ctx.as_string.data;
4809                                 else
4810                                         o_free_unsafe(&ctx.as_string);
4811 #endif
4812                                 return ctx.list_head;
4813                         }
4814                 }
4815                 if (is_ifs)
4816                         continue;
4817
4818                 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4819                         /* ch is a special char and thus this word
4820                          * cannot be an assignment */
4821                         dest.o_assignment = NOT_ASSIGNMENT;
4822                 }
4823
4824                 next = '\0';
4825                 if (ch != '\n') {
4826                         next = i_peek(input);
4827                 }
4828
4829                 switch (ch) {
4830                 case '#':
4831                         if (dest.length == 0) {
4832                                 while (1) {
4833                                         ch = i_peek(input);
4834                                         if (ch == EOF || ch == '\n')
4835                                                 break;
4836                                         i_getch(input);
4837                                         /* note: we do not add it to &ctx.as_string */
4838                                 }
4839 #if !BB_MMU
4840 //TODO: go back one char?
4841                                 o_addchr(&ctx.as_string, '\n');
4842 #endif
4843                         } else {
4844                                 o_addQchr(&dest, ch);
4845                         }
4846                         break;
4847                 case '\\':
4848                         if (next == EOF) {
4849                                 syntax("\\<eof>");
4850                                 goto parse_error;
4851                         }
4852                         o_addchr(&dest, '\\');
4853                         ch = i_getch(input);
4854                         o_addchr(&dest, ch);
4855 #if !BB_MMU
4856                         o_addchr(&ctx.as_string, ch);
4857 #endif
4858                         break;
4859                 case '$':
4860                         if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
4861                                 debug_printf_parse("parse_stream parse error: "
4862                                         "handle_dollar returned non-0\n");
4863                                 goto parse_error;
4864                         }
4865                         break;
4866                 case '\'':
4867                         dest.nonnull = 1;
4868                         while (1) {
4869                                 ch = i_getch(input);
4870                                 if (ch == EOF) {
4871                                         syntax("unterminated '");
4872                                         goto parse_error;
4873                                 }
4874 #if !BB_MMU
4875                                 o_addchr(&ctx.as_string, ch);
4876 #endif
4877                                 if (ch == '\'')
4878                                         break;
4879                                 if (dest.o_assignment == NOT_ASSIGNMENT)
4880                                         o_addqchr(&dest, ch);
4881                                 else
4882                                         o_addchr(&dest, ch);
4883                         }
4884                         break;
4885                 case '"':
4886                         dest.nonnull = 1;
4887                         is_in_dquote ^= 1; /* invert */
4888                         if (dest.o_assignment == NOT_ASSIGNMENT)
4889                                 dest.o_escape ^= 1;
4890                         break;
4891 #if ENABLE_HUSH_TICK
4892                 case '`': {
4893                         //int pos = dest.length;
4894                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4895                         o_addchr(&dest, '`');
4896                         add_till_backquote(&dest, input);
4897                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4898                         //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4899                         break;
4900                 }
4901 #endif
4902                 case '>':
4903                         redir_fd = redirect_opt_num(&dest);
4904                         if (done_word(&dest, &ctx)) {
4905                                 goto parse_error;
4906                         }
4907                         redir_style = REDIRECT_OVERWRITE;
4908                         if (next == '>') {
4909                                 redir_style = REDIRECT_APPEND;
4910                                 ch = i_getch(input);
4911 #if !BB_MMU
4912                                 o_addchr(&ctx.as_string, ch);
4913 #endif
4914                         }
4915 #if 0
4916                         else if (next == '(') {
4917                                 syntax(">(process) not supported");
4918                                 goto parse_error;
4919                         }
4920 #endif
4921                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
4922                                 goto parse_error;
4923                         break;
4924                 case '<':
4925                         redir_fd = redirect_opt_num(&dest);
4926                         if (done_word(&dest, &ctx)) {
4927                                 goto parse_error;
4928                         }
4929                         redir_style = REDIRECT_INPUT;
4930                         if (next == '<') {
4931                                 redir_style = REDIRECT_HEREDOC;
4932                                 heredoc_cnt++;
4933                                 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4934                                 ch = i_getch(input);
4935 #if !BB_MMU
4936                                 o_addchr(&ctx.as_string, ch);
4937 #endif
4938                         } else if (next == '>') {
4939                                 redir_style = REDIRECT_IO;
4940                                 ch = i_getch(input);
4941 #if !BB_MMU
4942                                 o_addchr(&ctx.as_string, ch);
4943 #endif
4944                         }
4945 #if 0
4946                         else if (next == '(') {
4947                                 syntax("<(process) not supported");
4948                                 goto parse_error;
4949                         }
4950 #endif
4951                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
4952                                 goto parse_error;
4953                         break;
4954                 case ';':
4955 #if ENABLE_HUSH_CASE
4956  case_semi:
4957 #endif
4958                         if (done_word(&dest, &ctx)) {
4959                                 goto parse_error;
4960                         }
4961                         done_pipe(&ctx, PIPE_SEQ);
4962 #if ENABLE_HUSH_CASE
4963                         /* Eat multiple semicolons, detect
4964                          * whether it means something special */
4965                         while (1) {
4966                                 ch = i_peek(input);
4967                                 if (ch != ';')
4968                                         break;
4969                                 ch = i_getch(input);
4970 #if !BB_MMU
4971                                 o_addchr(&ctx.as_string, ch);
4972 #endif
4973                                 if (ctx.ctx_res_w == RES_CASEI) {
4974                                         ctx.ctx_dsemicolon = 1;
4975                                         ctx.ctx_res_w = RES_MATCH;
4976                                         break;
4977                                 }
4978                         }
4979 #endif
4980  new_cmd:
4981                         /* We just finished a cmd. New one may start
4982                          * with an assignment */
4983                         dest.o_assignment = MAYBE_ASSIGNMENT;
4984                         break;
4985                 case '&':
4986                         if (done_word(&dest, &ctx)) {
4987                                 goto parse_error;
4988                         }
4989                         if (next == '&') {
4990                                 ch = i_getch(input);
4991 #if !BB_MMU
4992                                 o_addchr(&ctx.as_string, ch);
4993 #endif
4994                                 done_pipe(&ctx, PIPE_AND);
4995                         } else {
4996                                 done_pipe(&ctx, PIPE_BG);
4997                         }
4998                         goto new_cmd;
4999                 case '|':
5000                         if (done_word(&dest, &ctx)) {
5001                                 goto parse_error;
5002                         }
5003 #if ENABLE_HUSH_CASE
5004                         if (ctx.ctx_res_w == RES_MATCH)
5005                                 break; /* we are in case's "word | word)" */
5006 #endif
5007                         if (next == '|') { /* || */
5008                                 ch = i_getch(input);
5009 #if !BB_MMU
5010                                 o_addchr(&ctx.as_string, ch);
5011 #endif
5012                                 done_pipe(&ctx, PIPE_OR);
5013                         } else {
5014                                 /* we could pick up a file descriptor choice here
5015                                  * with redirect_opt_num(), but bash doesn't do it.
5016                                  * "echo foo 2| cat" yields "foo 2". */
5017                                 done_command(&ctx);
5018                         }
5019                         goto new_cmd;
5020                 case '(':
5021 #if ENABLE_HUSH_CASE
5022                         /* "case... in [(]word)..." - skip '(' */
5023                         if (ctx.ctx_res_w == RES_MATCH
5024                          && ctx.command->argv == NULL /* not (word|(... */
5025                          && dest.length == 0 /* not word(... */
5026                          && dest.nonnull == 0 /* not ""(... */
5027                         ) {
5028                                 continue;
5029                         }
5030 #endif
5031 #if ENABLE_HUSH_FUNCTIONS
5032                         if (dest.length != 0 /* not just () but word() */
5033                          && dest.nonnull == 0 /* not a"b"c() */
5034                          && ctx.command->argv == NULL /* it's the first word */
5035 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5036                          && i_peek(input) == ')'
5037                          && !match_reserved_word(&dest)
5038                         ) {
5039                                 bb_error_msg("seems like a function definition");
5040                                 i_getch(input);
5041 //if !BB_MMU o_addchr(&ctx.as_string...
5042                                 do {
5043 //TODO: do it properly.
5044                                         ch = i_getch(input);
5045                                 } while (ch == ' ' || ch == '\n');
5046                                 if (ch != '{') {
5047                                         syntax("was expecting {");
5048                                         goto parse_error;
5049                                 }
5050                                 ch = 'F'; /* magic value */
5051                         }
5052 #endif
5053                 case '{':
5054                         if (parse_group(&dest, &ctx, input, ch) != 0) {
5055                                 goto parse_error;
5056                         }
5057                         goto new_cmd;
5058                 case ')':
5059 #if ENABLE_HUSH_CASE
5060                         if (ctx.ctx_res_w == RES_MATCH)
5061                                 goto case_semi;
5062 #endif
5063                 case '}':
5064                         /* proper use of this character is caught by end_trigger:
5065                          * if we see {, we call parse_group(..., end_trigger='}')
5066                          * and it will match } earlier (not here). */
5067                         syntax("unexpected } or )");
5068                         goto parse_error;
5069                 default:
5070                         if (HUSH_DEBUG)
5071                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5072                 }
5073         } /* while (1) */
5074
5075  parse_error:
5076         {
5077                 struct parse_context *pctx;
5078                 IF_HAS_KEYWORDS(struct parse_context *p2;)
5079
5080                 /* Clean up allocated tree.
5081                  * Samples for finding leaks on syntax error recovery path.
5082                  * Run them from interactive shell, watch pmap `pidof hush`.
5083                  * while if false; then false; fi do break; done
5084                  * (bash accepts it)
5085                  * while if false; then false; fi; do break; fi
5086                  * Samples to catch leaks at execution:
5087                  * while if (true | {true;}); then echo ok; fi; do break; done
5088                  * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5089                  */
5090                 pctx = &ctx;
5091                 do {
5092                         /* Update pipe/command counts,
5093                          * otherwise freeing may miss some */
5094                         done_pipe(pctx, PIPE_SEQ);
5095                         debug_printf_clean("freeing list %p from ctx %p\n",
5096                                         pctx->list_head, pctx);
5097                         debug_print_tree(pctx->list_head, 0);
5098                         free_pipe_list(pctx->list_head, 0);
5099                         debug_printf_clean("freed list %p\n", pctx->list_head);
5100 #if !BB_MMU
5101                         o_free_unsafe(&pctx->as_string);
5102 #endif
5103                         IF_HAS_KEYWORDS(p2 = pctx->stack;)
5104                         if (pctx != &ctx) {
5105                                 free(pctx);
5106                         }
5107                         IF_HAS_KEYWORDS(pctx = p2;)
5108                 } while (HAS_KEYWORDS && pctx);
5109                 /* Free text, clear all dest fields */
5110                 o_free(&dest);
5111                 /* If we are not in top-level parse, we return,
5112                  * our caller will propagate error.
5113                  */
5114                 if (end_trigger != ';') {
5115 #if !BB_MMU
5116                         if (pstring)
5117                                 *pstring = NULL;
5118 #endif
5119                         return ERR_PTR;
5120                 }
5121                 /* Discard cached input, force prompt */
5122                 input->p = NULL;
5123                 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5124                 goto reset;
5125         }
5126 }
5127
5128 /* Executing from string: eval, sh -c '...'
5129  *          or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5130  * end_trigger controls how often we stop parsing
5131  * NUL: parse all, execute, return
5132  * ';': parse till ';' or newline, execute, repeat till EOF
5133  */
5134 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5135 {
5136         while (1) {
5137                 struct pipe *pipe_list;
5138
5139                 pipe_list = parse_stream(NULL, inp, end_trigger);
5140                 if (!pipe_list) /* EOF */
5141                         break;
5142                 debug_print_tree(pipe_list, 0);
5143                 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5144                 run_and_free_list(pipe_list);
5145         }
5146 }
5147
5148 static void parse_and_run_string(const char *s)
5149 {
5150         struct in_str input;
5151         setup_string_in_str(&input, s);
5152         parse_and_run_stream(&input, '\0');
5153 }
5154
5155 static void parse_and_run_file(FILE *f)
5156 {
5157         struct in_str input;
5158         setup_file_in_str(&input, f);
5159         parse_and_run_stream(&input, ';');
5160 }
5161
5162 /* Called a few times only (or even once if "sh -c") */
5163 static void block_signals(int second_time)
5164 {
5165         unsigned sig;
5166         unsigned mask;
5167
5168         mask = (1 << SIGQUIT);
5169         if (G_interactive_fd) {
5170                 mask = 0
5171                         | (1 << SIGQUIT)
5172                         | (1 << SIGTERM)
5173 //TODO                  | (1 << SIGHUP)
5174 #if ENABLE_HUSH_JOB
5175                         | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5176 #endif
5177                         | (1 << SIGINT)
5178                 ;
5179         }
5180         G.non_DFL_mask = mask;
5181
5182         if (!second_time)
5183                 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5184         sig = 0;
5185         while (mask) {
5186                 if (mask & 1)
5187                         sigaddset(&G.blocked_set, sig);
5188                 mask >>= 1;
5189                 sig++;
5190         }
5191         sigdelset(&G.blocked_set, SIGCHLD);
5192
5193         sigprocmask(SIG_SETMASK, &G.blocked_set,
5194                         second_time ? NULL : &G.inherited_set);
5195         /* POSIX allows shell to re-enable SIGCHLD
5196          * even if it was SIG_IGN on entry */
5197 //      G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5198         if (!second_time)
5199                 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5200 }
5201
5202 #if ENABLE_HUSH_JOB
5203 /* helper */
5204 static void maybe_set_to_sigexit(int sig)
5205 {
5206         void (*handler)(int);
5207         /* non_DFL_mask'ed signals are, well, masked,
5208          * no need to set handler for them.
5209          */
5210         if (!((G.non_DFL_mask >> sig) & 1)) {
5211                 handler = signal(sig, sigexit);
5212                 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5213                         signal(sig, handler);
5214         }
5215 }
5216 /* Set handlers to restore tty pgrp and exit */
5217 static void set_fatal_handlers(void)
5218 {
5219         /* We _must_ restore tty pgrp on fatal signals */
5220         if (HUSH_DEBUG) {
5221                 maybe_set_to_sigexit(SIGILL );
5222                 maybe_set_to_sigexit(SIGFPE );
5223                 maybe_set_to_sigexit(SIGBUS );
5224                 maybe_set_to_sigexit(SIGSEGV);
5225                 maybe_set_to_sigexit(SIGTRAP);
5226         } /* else: hush is perfect. what SEGV? */
5227         maybe_set_to_sigexit(SIGABRT);
5228         /* bash 3.2 seems to handle these just like 'fatal' ones */
5229         maybe_set_to_sigexit(SIGPIPE);
5230         maybe_set_to_sigexit(SIGALRM);
5231 //TODO: disable and move down when proper SIGHUP handling is added
5232         maybe_set_to_sigexit(SIGHUP );
5233         /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5234          * if we aren't interactive... but in this case
5235          * we never want to restore pgrp on exit, and this fn is not called */
5236         /*maybe_set_to_sigexit(SIGTERM);*/
5237         /*maybe_set_to_sigexit(SIGINT );*/
5238 }
5239 #endif
5240
5241 static int set_mode(const char cstate, const char mode)
5242 {
5243         int state = (cstate == '-' ? 1 : 0);
5244         switch (mode) {
5245                 case 'n': G.fake_mode = state; break;
5246                 case 'x': /*G.debug_mode = state;*/ break;
5247                 default:  return EXIT_FAILURE;
5248         }
5249         return EXIT_SUCCESS;
5250 }
5251
5252 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5253 int hush_main(int argc, char **argv)
5254 {
5255         static const struct variable const_shell_ver = {
5256                 .next = NULL,
5257                 .varstr = (char*)hush_version_str,
5258                 .max_len = 1, /* 0 can provoke free(name) */
5259                 .flg_export = 1,
5260                 .flg_read_only = 1,
5261         };
5262         int signal_mask_is_inited = 0;
5263         int opt;
5264         char **e;
5265         struct variable *cur_var;
5266
5267         INIT_G();
5268         if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5269                 G.last_exitcode = EXIT_SUCCESS;
5270 #if !BB_MMU
5271         G.argv0_for_re_execing = argv[0];
5272 #endif
5273         /* Deal with HUSH_VERSION */
5274         G.shell_ver = const_shell_ver; /* copying struct here */
5275         G.top_var = &G.shell_ver;
5276         debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5277         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5278         /* Initialize our shell local variables with the values
5279          * currently living in the environment */
5280         cur_var = G.top_var;
5281         e = environ;
5282         if (e) while (*e) {
5283                 char *value = strchr(*e, '=');
5284                 if (value) { /* paranoia */
5285                         cur_var->next = xzalloc(sizeof(*cur_var));
5286                         cur_var = cur_var->next;
5287                         cur_var->varstr = *e;
5288                         cur_var->max_len = strlen(*e);
5289                         cur_var->flg_export = 1;
5290                 }
5291                 e++;
5292         }
5293         debug_printf_env("putenv '%s'\n", hush_version_str);
5294         putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5295 #if ENABLE_FEATURE_EDITING
5296         G.line_input_state = new_line_input_t(FOR_SHELL);
5297 #endif
5298         G.global_argc = argc;
5299         G.global_argv = argv;
5300         /* Initialize some more globals to non-zero values */
5301         set_cwd();
5302 #if ENABLE_HUSH_INTERACTIVE
5303         if (ENABLE_FEATURE_EDITING)
5304                 cmdedit_set_initial_prompt();
5305         G.PS2 = "> ";
5306 #endif
5307
5308         /* Shell is non-interactive at first. We need to call
5309          * block_signals(0) if we are going to execute "sh <script>",
5310          * "sh -c <cmds>" or login shell's /etc/profile and friends.
5311          * If we later decide that we are interactive, we run block_signals(0)
5312          * (or re-run block_signals(1) if we ran block_signals(0) before)
5313          * in order to intercept (more) signals.
5314          */
5315
5316         /* Parse options */
5317         /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5318         while (1) {
5319                 opt = getopt(argc, argv, "c:xins"
5320 #if !BB_MMU
5321                                 "$:!:?:D:R:V:"
5322 #endif
5323                 );
5324                 if (opt <= 0)
5325                         break;
5326                 switch (opt) {
5327                 case 'c':
5328                         if (!G.root_pid)
5329                                 G.root_pid = getpid();
5330                         G.global_argv = argv + optind;
5331                         if (!argv[optind]) {
5332                                 /* -c 'script' (no params): prevent empty $0 */
5333                                 *--G.global_argv = argv[0];
5334                                 optind--;
5335                         } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5336                         G.global_argc = argc - optind;
5337                         block_signals(0); /* 0: called 1st time */
5338                         parse_and_run_string(optarg);
5339                         goto final_return;
5340                 case 'i':
5341                         /* Well, we cannot just declare interactiveness,
5342                          * we have to have some stuff (ctty, etc) */
5343                         /* G_interactive_fd++; */
5344                         break;
5345                 case 's':
5346                         /* "-s" means "read from stdin", but this is how we always
5347                          * operate, so simply do nothing here. */
5348                         break;
5349 #if !BB_MMU
5350                 case '$':
5351                         G.root_pid = bb_strtou(optarg, &optarg, 16);
5352                         optarg++;
5353                         G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5354                         optarg++;
5355                         G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5356 # if ENABLE_HUSH_LOOPS
5357                         optarg++;
5358                         G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5359 # endif
5360                         break;
5361                 case 'R':
5362                 case 'V':
5363                         set_local_var(xstrdup(optarg), 0, opt == 'R');
5364                         break;
5365 #endif
5366                 case 'n':
5367                 case 'x':
5368                         if (!set_mode('-', opt))
5369                                 break;
5370                 default:
5371 #ifndef BB_VER
5372                         fprintf(stderr, "Usage: sh [FILE]...\n"
5373                                         "   or: sh -c command [args]...\n\n");
5374                         exit(EXIT_FAILURE);
5375 #else
5376                         bb_show_usage();
5377 #endif
5378                 }
5379         } /* option parsing loop */
5380
5381         if (!G.root_pid)
5382                 G.root_pid = getpid();
5383
5384         /* If we are login shell... */
5385         if (argv[0] && argv[0][0] == '-') {
5386                 FILE *input;
5387                 /* XXX what should argv be while sourcing /etc/profile? */
5388                 debug_printf("sourcing /etc/profile\n");
5389                 input = fopen_for_read("/etc/profile");
5390                 if (input != NULL) {
5391                         close_on_exec_on(fileno(input));
5392                         block_signals(0); /* 0: called 1st time */
5393                         signal_mask_is_inited = 1;
5394                         parse_and_run_file(input);
5395                         fclose(input);
5396                 }
5397                 /* bash: after sourcing /etc/profile,
5398                  * tries to source (in the given order):
5399                  * ~/.bash_profile, ~/.bash_login, ~/.profile,
5400                  * stopping of first found. --noprofile turns this off.
5401                  * bash also sources ~/.bash_logout on exit.
5402                  * If called as sh, skips .bash_XXX files.
5403                  */
5404         }
5405
5406         if (argv[optind]) {
5407                 FILE *input;
5408                 /*
5409                  * "bash <script>" (which is never interactive (unless -i?))
5410                  * sources $BASH_ENV here (without scanning $PATH).
5411                  * If called as sh, does the same but with $ENV.
5412                  */
5413                 debug_printf("running script '%s'\n", argv[optind]);
5414                 G.global_argv = argv + optind;
5415                 G.global_argc = argc - optind;
5416                 input = xfopen_for_read(argv[optind]);
5417                 close_on_exec_on(fileno(input));
5418                 if (!signal_mask_is_inited)
5419                         block_signals(0); /* 0: called 1st time */
5420                 parse_and_run_file(input);
5421 #if ENABLE_FEATURE_CLEAN_UP
5422                 fclose(input);
5423 #endif
5424                 goto final_return;
5425         }
5426
5427         /* Up to here, shell was non-interactive. Now it may become one.
5428          * NB: don't forget to (re)run block_signals(0/1) as needed.
5429          */
5430
5431         /* A shell is interactive if the '-i' flag was given, or if all of
5432          * the following conditions are met:
5433          *    no -c command
5434          *    no arguments remaining or the -s flag given
5435          *    standard input is a terminal
5436          *    standard output is a terminal
5437          * Refer to Posix.2, the description of the 'sh' utility.
5438          */
5439 #if ENABLE_HUSH_JOB
5440         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5441                 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5442                 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5443 //TODO: "interactive" and "have job control" are two different things.
5444 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5445 //should stay on! Currently, we mix these into one.
5446                 if (G.saved_tty_pgrp >= 0) {
5447                         /* try to dup stdin to high fd#, >= 255 */
5448                         G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5449                         if (G_interactive_fd < 0) {
5450                                 /* try to dup to any fd */
5451                                 G_interactive_fd = dup(STDIN_FILENO);
5452                                 if (G_interactive_fd < 0)
5453                                         /* give up */
5454                                         G_interactive_fd = 0;
5455                         }
5456 // TODO: track & disallow any attempts of user
5457 // to (inadvertently) close/redirect it
5458                 }
5459         }
5460         debug_printf("interactive_fd:%d\n", G_interactive_fd);
5461         if (G_interactive_fd) {
5462                 pid_t shell_pgrp;
5463
5464                 /* We are indeed interactive shell, and we will perform
5465                  * job control. Setting up for that. */
5466
5467                 close_on_exec_on(G_interactive_fd);
5468                 /* If we were run as 'hush &', sleep until we are
5469                  * in the foreground (tty pgrp == our pgrp).
5470                  * If we get started under a job aware app (like bash),
5471                  * make sure we are now in charge so we don't fight over
5472                  * who gets the foreground */
5473                 while (1) {
5474                         shell_pgrp = getpgrp();
5475                         G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5476                         if (G.saved_tty_pgrp == shell_pgrp)
5477                                 break;
5478                         /* send TTIN to ourself (should stop us) */
5479                         kill(- shell_pgrp, SIGTTIN);
5480                 }
5481                 /* Block some signals */
5482                 block_signals(signal_mask_is_inited);
5483                 /* Set other signals to restore saved_tty_pgrp */
5484                 set_fatal_handlers();
5485                 /* Put ourselves in our own process group */
5486                 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5487                 /* Grab control of the terminal */
5488                 tcsetpgrp(G_interactive_fd, getpid());
5489                 /* -1 is special - makes xfuncs longjmp, not exit
5490                  * (we reset die_sleep = 0 whereever we [v]fork) */
5491                 die_sleep = -1;
5492                 if (setjmp(die_jmp)) {
5493                         /* xfunc has failed! die die die */
5494                         hush_exit(xfunc_error_retval);
5495                 }
5496         } else if (!signal_mask_is_inited) {
5497                 block_signals(0); /* 0: called 1st time */
5498         } /* else: block_signals(0) was done before */
5499 #elif ENABLE_HUSH_INTERACTIVE
5500         /* No job control compiled in, only prompt/line editing */
5501         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5502                 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5503                 if (G_interactive_fd < 0) {
5504                         /* try to dup to any fd */
5505                         G_interactive_fd = dup(STDIN_FILENO);
5506                         if (G_interactive_fd < 0)
5507                                 /* give up */
5508                                 G_interactive_fd = 0;
5509                 }
5510         }
5511         if (G_interactive_fd) {
5512                 close_on_exec_on(G_interactive_fd);
5513                 block_signals(signal_mask_is_inited);
5514         } else if (!signal_mask_is_inited) {
5515                 block_signals(0);
5516         }
5517 #else
5518         /* We have interactiveness code disabled */
5519         if (!signal_mask_is_inited) {
5520                 block_signals(0);
5521         }
5522 #endif
5523         /* bash:
5524          * if interactive but not a login shell, sources ~/.bashrc
5525          * (--norc turns this off, --rcfile <file> overrides)
5526          */
5527
5528         if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5529                 printf("\n\n%s hush - the humble shell\n", bb_banner);
5530                 printf("Enter 'help' for a list of built-in commands.\n\n");
5531         }
5532
5533         parse_and_run_file(stdin);
5534
5535  final_return:
5536 #if ENABLE_FEATURE_CLEAN_UP
5537         if (G.cwd != bb_msg_unknown)
5538                 free((char*)G.cwd);
5539         cur_var = G.top_var->next;
5540         while (cur_var) {
5541                 struct variable *tmp = cur_var;
5542                 if (!cur_var->max_len)
5543                         free(cur_var->varstr);
5544                 cur_var = cur_var->next;
5545                 free(tmp);
5546         }
5547 #endif
5548         hush_exit(G.last_exitcode);
5549 }
5550
5551
5552 #if ENABLE_LASH
5553 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5554 int lash_main(int argc, char **argv)
5555 {
5556         //bb_error_msg("lash is deprecated, please use hush instead");
5557         return hush_main(argc, argv);
5558 }
5559 #endif
5560
5561
5562 /*
5563  * Built-ins
5564  */
5565 static int builtin_trap(char **argv)
5566 {
5567         int i;
5568         int sig;
5569         char *new_cmd;
5570
5571         if (!G.traps)
5572                 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5573
5574         argv++;
5575         if (!*argv) {
5576                 /* No args: print all trapped. This isn't 100% correct as we
5577                  * should be escaping the cmd so that it can be pasted back in
5578                  */
5579                 for (i = 0; i < NSIG; ++i)
5580                         if (G.traps[i])
5581                                 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5582                 return EXIT_SUCCESS;
5583         }
5584
5585         new_cmd = NULL;
5586         i = 0;
5587         /* If first arg is decimal: reset all specified signals */
5588         sig = bb_strtou(*argv, NULL, 10);
5589         if (errno == 0) {
5590                 int ret;
5591  set_all:
5592                 ret = EXIT_SUCCESS;
5593                 while (*argv) {
5594                         sig = get_signum(*argv++);
5595                         if (sig < 0 || sig >= NSIG) {
5596                                 ret = EXIT_FAILURE;
5597                                 /* Mimic bash message exactly */
5598                                 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5599                                 continue;
5600                         }
5601
5602                         free(G.traps[sig]);
5603                         G.traps[sig] = xstrdup(new_cmd);
5604
5605                         debug_printf("trap: setting SIG%s (%i) to '%s'",
5606                                 get_signame(sig), sig, G.traps[sig]);
5607
5608                         /* There is no signal for 0 (EXIT) */
5609                         if (sig == 0)
5610                                 continue;
5611
5612                         if (new_cmd) {
5613                                 sigaddset(&G.blocked_set, sig);
5614                         } else {
5615                                 /* There was a trap handler, we are removing it
5616                                  * (if sig has non-DFL handling,
5617                                  * we don't need to do anything) */
5618                                 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5619                                         continue;
5620                                 sigdelset(&G.blocked_set, sig);
5621                         }
5622                         sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5623                 }
5624                 return ret;
5625         }
5626
5627         /* First arg is "-": reset all specified to default */
5628         /* First arg is "": ignore all specified */
5629         /* Everything else: execute first arg upon signal */
5630         if (!argv[1]) {
5631                 bb_error_msg("trap: invalid arguments");
5632                 return EXIT_FAILURE;
5633         }
5634         if (NOT_LONE_DASH(*argv))
5635                 new_cmd = *argv;
5636         argv++;
5637         goto set_all;
5638 }
5639
5640 static int builtin_true(char **argv UNUSED_PARAM)
5641 {
5642         return 0;
5643 }
5644
5645 static int builtin_test(char **argv)
5646 {
5647         int argc = 0;
5648         while (*argv) {
5649                 argc++;
5650                 argv++;
5651         }
5652         return test_main(argc, argv - argc);
5653 }
5654
5655 static int builtin_echo(char **argv)
5656 {
5657         int argc = 0;
5658         while (*argv) {
5659                 argc++;
5660                 argv++;
5661         }
5662         return echo_main(argc, argv - argc);
5663 }
5664
5665 static int builtin_eval(char **argv)
5666 {
5667         int rcode = EXIT_SUCCESS;
5668
5669         if (*++argv) {
5670                 char *str = expand_strvec_to_string(argv);
5671                 /* bash:
5672                  * eval "echo Hi; done" ("done" is syntax error):
5673                  * "echo Hi" will not execute too.
5674                  */
5675                 parse_and_run_string(str);
5676                 free(str);
5677                 rcode = G.last_exitcode;
5678         }
5679         return rcode;
5680 }
5681
5682 static int builtin_cd(char **argv)
5683 {
5684         const char *newdir = argv[1];
5685         if (newdir == NULL) {
5686                 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5687                  * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5688                  */
5689                 newdir = getenv("HOME") ? : "/";
5690         }
5691         if (chdir(newdir)) {
5692                 /* Mimic bash message exactly */
5693                 bb_perror_msg("cd: %s", newdir);
5694                 return EXIT_FAILURE;
5695         }
5696         set_cwd();
5697         return EXIT_SUCCESS;
5698 }
5699
5700 static int builtin_exec(char **argv)
5701 {
5702         if (*++argv == NULL)
5703                 return EXIT_SUCCESS; /* bash does this */
5704         {
5705 #if !BB_MMU
5706                 nommu_save_t dummy;
5707 #endif
5708 // FIXME: if exec fails, bash does NOT exit! We do...
5709                 pseudo_exec_argv(&dummy, argv, 0, NULL);
5710                 /* never returns */
5711         }
5712 }
5713
5714 static int builtin_exit(char **argv)
5715 {
5716         debug_printf_exec("%s()\n", __func__);
5717 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5718         //puts("exit"); /* bash does it */
5719 // TODO: warn if we have background jobs: "There are stopped jobs"
5720 // On second consecutive 'exit', exit anyway.
5721         if (*++argv == NULL)
5722                 hush_exit(G.last_exitcode);
5723         /* mimic bash: exit 123abc == exit 255 + error msg */
5724         xfunc_error_retval = 255;
5725         /* bash: exit -2 == exit 254, no error msg */
5726         hush_exit(xatoi(*argv) & 0xff);
5727 }
5728
5729 static int builtin_export(char **argv)
5730 {
5731         if (*++argv == NULL) {
5732                 // TODO:
5733                 // ash emits: export VAR='VAL'
5734                 // bash: declare -x VAR="VAL"
5735                 // (both also escape as needed (quotes, $, etc))
5736                 char **e = environ;
5737                 if (e)
5738                         while (*e)
5739                                 puts(*e++);
5740                 return EXIT_SUCCESS;
5741         }
5742
5743         do {
5744                 const char *value;
5745                 char *name = *argv;
5746
5747                 value = strchr(name, '=');
5748                 if (!value) {
5749                         /* They are exporting something without a =VALUE */
5750                         struct variable *var;
5751
5752                         var = get_local_var(name);
5753                         if (var) {
5754                                 var->flg_export = 1;
5755                                 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5756                                 putenv(var->varstr);
5757                         }
5758                         /* bash does not return an error when trying to export
5759                          * an undefined variable.  Do likewise. */
5760                         continue;
5761                 }
5762                 set_local_var(xstrdup(name), 1, 0);
5763         } while (*++argv);
5764
5765         return EXIT_SUCCESS;
5766 }
5767
5768 #if ENABLE_HUSH_JOB
5769 /* built-in 'fg' and 'bg' handler */
5770 static int builtin_fg_bg(char **argv)
5771 {
5772         int i, jobnum;
5773         struct pipe *pi;
5774
5775         if (!G_interactive_fd)
5776                 return EXIT_FAILURE;
5777         /* If they gave us no args, assume they want the last backgrounded task */
5778         if (!argv[1]) {
5779                 for (pi = G.job_list; pi; pi = pi->next) {
5780                         if (pi->jobid == G.last_jobid) {
5781                                 goto found;
5782                         }
5783                 }
5784                 bb_error_msg("%s: no current job", argv[0]);
5785                 return EXIT_FAILURE;
5786         }
5787         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5788                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5789                 return EXIT_FAILURE;
5790         }
5791         for (pi = G.job_list; pi; pi = pi->next) {
5792                 if (pi->jobid == jobnum) {
5793                         goto found;
5794                 }
5795         }
5796         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5797         return EXIT_FAILURE;
5798  found:
5799         // TODO: bash prints a string representation
5800         // of job being foregrounded (like "sleep 1 | cat")
5801         if (argv[0][0] == 'f') {
5802                 /* Put the job into the foreground.  */
5803                 tcsetpgrp(G_interactive_fd, pi->pgrp);
5804         }
5805
5806         /* Restart the processes in the job */
5807         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5808         for (i = 0; i < pi->num_cmds; i++) {
5809                 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5810                 pi->cmds[i].is_stopped = 0;
5811         }
5812         pi->stopped_cmds = 0;
5813
5814         i = kill(- pi->pgrp, SIGCONT);
5815         if (i < 0) {
5816                 if (errno == ESRCH) {
5817                         delete_finished_bg_job(pi);
5818                         return EXIT_SUCCESS;
5819                 }
5820                 bb_perror_msg("kill (SIGCONT)");
5821         }
5822
5823         if (argv[0][0] == 'f') {
5824                 remove_bg_job(pi);
5825                 return checkjobs_and_fg_shell(pi);
5826         }
5827         return EXIT_SUCCESS;
5828 }
5829 #endif
5830
5831 #if ENABLE_HUSH_HELP
5832 static int builtin_help(char **argv UNUSED_PARAM)
5833 {
5834         const struct built_in_command *x;
5835
5836         printf("\n"
5837                 "Built-in commands:\n"
5838                 "------------------\n");
5839         for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5840                 printf("%s\t%s\n", x->cmd, x->descr);
5841         }
5842         printf("\n\n");
5843         return EXIT_SUCCESS;
5844 }
5845 #endif
5846
5847 #if ENABLE_HUSH_JOB
5848 static int builtin_jobs(char **argv UNUSED_PARAM)
5849 {
5850         struct pipe *job;
5851         const char *status_string;
5852
5853         for (job = G.job_list; job; job = job->next) {
5854                 if (job->alive_cmds == job->stopped_cmds)
5855                         status_string = "Stopped";
5856                 else
5857                         status_string = "Running";
5858
5859                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5860         }
5861         return EXIT_SUCCESS;
5862 }
5863 #endif
5864
5865 static int builtin_pwd(char **argv UNUSED_PARAM)
5866 {
5867         puts(set_cwd());
5868         return EXIT_SUCCESS;
5869 }
5870
5871 static int builtin_read(char **argv)
5872 {
5873         char *string;
5874         const char *name = argv[1] ? argv[1] : "REPLY";
5875 //TODO: check that argv[1] is a valid variable name
5876
5877         string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5878         return set_local_var(string, 0, 0);
5879 }
5880
5881 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5882  * built-in 'set' handler
5883  * SUSv3 says:
5884  * set [-abCefhmnuvx] [-o option] [argument...]
5885  * set [+abCefhmnuvx] [+o option] [argument...]
5886  * set -- [argument...]
5887  * set -o
5888  * set +o
5889  * Implementations shall support the options in both their hyphen and
5890  * plus-sign forms. These options can also be specified as options to sh.
5891  * Examples:
5892  * Write out all variables and their values: set
5893  * Set $1, $2, and $3 and set "$#" to 3: set c a b
5894  * Turn on the -x and -v options: set -xv
5895  * Unset all positional parameters: set --
5896  * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5897  * Set the positional parameters to the expansion of x, even if x expands
5898  * with a leading '-' or '+': set -- $x
5899  *
5900  * So far, we only support "set -- [argument...]" and some of the short names.
5901  */
5902 static int builtin_set(char **argv)
5903 {
5904         int n;
5905         char **pp, **g_argv;
5906         char *arg = *++argv;
5907
5908         if (arg == NULL) {
5909                 struct variable *e;
5910                 for (e = G.top_var; e; e = e->next)
5911                         puts(e->varstr);
5912                 return EXIT_SUCCESS;
5913         }
5914
5915         do {
5916                 if (!strcmp(arg, "--")) {
5917                         ++argv;
5918                         goto set_argv;
5919                 }
5920
5921                 if (arg[0] == '+' || arg[0] == '-') {
5922                         for (n = 1; arg[n]; ++n)
5923                                 if (set_mode(arg[0], arg[n]))
5924                                         goto error;
5925                         continue;
5926                 }
5927
5928                 break;
5929         } while ((arg = *++argv) != NULL);
5930         /* Now argv[0] is 1st argument */
5931
5932         /* Only reset global_argv if we didn't process anything */
5933         if (arg == NULL)
5934                 return EXIT_SUCCESS;
5935  set_argv:
5936
5937         /* NB: G.global_argv[0] ($0) is never freed/changed */
5938         g_argv = G.global_argv;
5939         if (G.global_args_malloced) {
5940                 pp = g_argv;
5941                 while (*++pp)
5942                         free(*pp);
5943                 g_argv[1] = NULL;
5944         } else {
5945                 G.global_args_malloced = 1;
5946                 pp = xzalloc(sizeof(pp[0]) * 2);
5947                 pp[0] = g_argv[0]; /* retain $0 */
5948                 g_argv = pp;
5949         }
5950         /* This realloc's G.global_argv */
5951         G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5952
5953         n = 1;
5954         while (*++pp)
5955                 n++;
5956         G.global_argc = n;
5957
5958         return EXIT_SUCCESS;
5959
5960         /* Nothing known, so abort */
5961  error:
5962         bb_error_msg("set: %s: invalid option", arg);
5963         return EXIT_FAILURE;
5964 }
5965
5966 static int builtin_shift(char **argv)
5967 {
5968         int n = 1;
5969         if (argv[1]) {
5970                 n = atoi(argv[1]);
5971         }
5972         if (n >= 0 && n < G.global_argc) {
5973                 if (G.global_args_malloced) {
5974                         int m = 1;
5975                         while (m <= n)
5976                                 free(G.global_argv[m++]);
5977                 }
5978                 G.global_argc -= n;
5979                 memmove(&G.global_argv[1], &G.global_argv[n+1],
5980                                 G.global_argc * sizeof(G.global_argv[0]));
5981                 return EXIT_SUCCESS;
5982         }
5983         return EXIT_FAILURE;
5984 }
5985
5986 static int builtin_source(char **argv)
5987 {
5988         FILE *input;
5989
5990         if (*++argv == NULL)
5991                 return EXIT_FAILURE;
5992
5993         /* XXX search through $PATH is missing */
5994         input = fopen_or_warn(*argv, "r");
5995         if (!input) {
5996                 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
5997                 return EXIT_FAILURE;
5998         }
5999         close_on_exec_on(fileno(input));
6000
6001         /* Now run the file */
6002 //TODO:
6003         /* XXX argv and argc are broken; need to save old G.global_argv
6004          * (pointer only is OK!) on this stack frame,
6005          * set G.global_argv=argv+1, recurse, and restore. */
6006         parse_and_run_file(input);
6007         fclose(input);
6008         return G.last_exitcode;
6009 }
6010
6011 static int builtin_umask(char **argv)
6012 {
6013         mode_t new_umask;
6014         const char *arg = argv[1];
6015         if (arg) {
6016 //TODO: umask may take chmod-like symbolic masks
6017                 new_umask = bb_strtou(arg, NULL, 8);
6018                 if (errno) {
6019                         //Message? bash examples:
6020                         //bash: umask: 'q': invalid symbolic mode operator
6021                         //bash: umask: 999: octal number out of range
6022                         return EXIT_FAILURE;
6023                 }
6024         } else {
6025                 new_umask = umask(0);
6026                 printf("%.3o\n", (unsigned) new_umask);
6027                 /* fall through and restore new_umask which we set to 0 */
6028         }
6029         umask(new_umask);
6030         return EXIT_SUCCESS;
6031 }
6032
6033 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6034 static int builtin_unset(char **argv)
6035 {
6036         int ret;
6037         char var;
6038
6039         if (!*++argv)
6040                 return EXIT_SUCCESS;
6041
6042         var = 'v';
6043         if (argv[0][0] == '-') {
6044                 switch (argv[0][1]) {
6045                 case 'v':
6046                 case 'f':
6047                         var = argv[0][1];
6048                         break;
6049                 default:
6050                         bb_error_msg("unset: %s: invalid option", *argv);
6051                         return EXIT_FAILURE;
6052                 }
6053 //TODO: disallow "unset -vf ..." too
6054                 argv++;
6055         }
6056
6057         ret = EXIT_SUCCESS;
6058         while (*argv) {
6059                 if (var == 'v') {
6060                         if (unset_local_var(*argv)) {
6061                                 /* unset <nonexistent_var> doesn't fail.
6062                                  * Error is when one tries to unset RO var.
6063                                  * Message was printed by unset_local_var. */
6064                                 ret = EXIT_FAILURE;
6065                         }
6066                 }
6067 #if ENABLE_HUSH_FUNCTIONS
6068                 else {
6069                         unset_local_func(*argv);
6070                 }
6071 #endif
6072                 argv++;
6073         }
6074         return ret;
6075 }
6076
6077 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6078 static int builtin_wait(char **argv)
6079 {
6080         int ret = EXIT_SUCCESS;
6081         int status, sig;
6082
6083         if (*++argv == NULL) {
6084                 /* Don't care about wait results */
6085                 /* Note 1: must wait until there are no more children */
6086                 /* Note 2: must be interruptible */
6087                 /* Examples:
6088                  * $ sleep 3 & sleep 6 & wait
6089                  * [1] 30934 sleep 3
6090                  * [2] 30935 sleep 6
6091                  * [1] Done                   sleep 3
6092                  * [2] Done                   sleep 6
6093                  * $ sleep 3 & sleep 6 & wait
6094                  * [1] 30936 sleep 3
6095                  * [2] 30937 sleep 6
6096                  * [1] Done                   sleep 3
6097                  * ^C <-- after ~4 sec from keyboard
6098                  * $
6099                  */
6100                 sigaddset(&G.blocked_set, SIGCHLD);
6101                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6102                 while (1) {
6103                         checkjobs(NULL);
6104                         if (errno == ECHILD)
6105                                 break;
6106                         /* Wait for SIGCHLD or any other signal of interest */
6107                         /* sigtimedwait with infinite timeout: */
6108                         sig = sigwaitinfo(&G.blocked_set, NULL);
6109                         if (sig > 0) {
6110                                 sig = check_and_run_traps(sig);
6111                                 if (sig && sig != SIGCHLD) { /* see note 2 */
6112                                         ret = 128 + sig;
6113                                         break;
6114                                 }
6115                         }
6116                 }
6117                 sigdelset(&G.blocked_set, SIGCHLD);
6118                 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6119                 return ret;
6120         }
6121
6122         /* This is probably buggy wrt interruptible-ness */
6123         while (*argv) {
6124                 pid_t pid = bb_strtou(*argv, NULL, 10);
6125                 if (errno) {
6126                         /* mimic bash message */
6127                         bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6128                         return EXIT_FAILURE;
6129                 }
6130                 if (waitpid(pid, &status, 0) == pid) {
6131                         if (WIFSIGNALED(status))
6132                                 ret = 128 + WTERMSIG(status);
6133                         else if (WIFEXITED(status))
6134                                 ret = WEXITSTATUS(status);
6135                         else /* wtf? */
6136                                 ret = EXIT_FAILURE;
6137                 } else {
6138                         bb_perror_msg("wait %s", *argv);
6139                         ret = 127;
6140                 }
6141                 argv++;
6142         }
6143
6144         return ret;
6145 }
6146
6147 #if ENABLE_HUSH_LOOPS
6148 static int builtin_break(char **argv)
6149 {
6150         if (G.depth_of_loop == 0) {
6151                 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6152                 return EXIT_SUCCESS; /* bash compat */
6153         }
6154         G.flag_break_continue++; /* BC_BREAK = 1 */
6155         G.depth_break_continue = 1;
6156         if (argv[1]) {
6157                 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6158                 if (errno || !G.depth_break_continue || argv[2]) {
6159                         bb_error_msg("%s: bad arguments", argv[0]);
6160                         G.flag_break_continue = BC_BREAK;
6161                         G.depth_break_continue = UINT_MAX;
6162                 }
6163         }
6164         if (G.depth_of_loop < G.depth_break_continue)
6165                 G.depth_break_continue = G.depth_of_loop;
6166         return EXIT_SUCCESS;
6167 }
6168
6169 static int builtin_continue(char **argv)
6170 {
6171         G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6172         return builtin_break(argv);
6173 }
6174 #endif