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