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