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