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