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