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