sh: do not print empty line at the end of "help" output
[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  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12  *
13  * Credits:
14  *      The parser routines proper are all original material, first
15  *      written Dec 2000 and Jan 2001 by Larry Doolittle.  The
16  *      execution engine, the builtins, and much of the underlying
17  *      support has been adapted from busybox-0.49pre's lash, which is
18  *      Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19  *      written by Erik Andersen <andersen@codepoet.org>.  That, in turn,
20  *      is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21  *      Troan, which they placed in the public domain.  I don't know
22  *      how much of the Johnson/Troan code has survived the repeated
23  *      rewrites.
24  *
25  * Other credits:
26  *      o_addchr derived from similar w_addchar function in glibc-2.2.
27  *      parse_redirect, redirect_opt_num, and big chunks of main
28  *      and many builtins derived from contributions by Erik Andersen.
29  *      Miscellaneous bugfixes from Matt Kraai.
30  *
31  * There are two big (and related) architecture differences between
32  * this parser and the lash parser.  One is that this version is
33  * actually designed from the ground up to understand nearly all
34  * of the Bourne grammar.  The second, consequential change is that
35  * the parser and input reader have been turned inside out.  Now,
36  * the parser is in control, and asks for input as needed.  The old
37  * way had the input reader in control, and it asked for parsing to
38  * take place as needed.  The new way makes it much easier to properly
39  * handle the recursion implicit in the various substitutions, especially
40  * across continuation lines.
41  *
42  * TODOs:
43  *      grep for "TODO" and fix (some of them are easy)
44  *      special variables (done: PWD, PPID, RANDOM)
45  *      tilde expansion
46  *      aliases
47  *      follow IFS rules more precisely, including update semantics
48  *      builtins mandated by standards we don't support:
49  *          [un]alias, command, fc, getopts, newgrp, readonly, times
50  *      make complex ${var%...} constructs support optional
51  *      make here documents optional
52  *
53  * Bash compat TODO:
54  *      redirection of stdout+stderr: &> and >&
55  *      reserved words: function select
56  *      advanced test: [[ ]]
57  *      process substitution: <(list) and >(list)
58  *      =~: regex operator
59  *      let EXPR [EXPR...]
60  *          Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61  *          If the last arg evaluates to 0, let returns 1; 0 otherwise.
62  *          NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63  *      ((EXPR))
64  *          The EXPR is evaluated according to ARITHMETIC EVALUATION.
65  *          This is exactly equivalent to let "EXPR".
66  *      $[EXPR]: synonym for $((EXPR))
67  *
68  * Won't do:
69  *      In bash, export builtin is special, its arguments are assignments
70  *          and therefore expansion of them should be "one-word" expansion:
71  *              $ export i=`echo 'a  b'` # export has one arg: "i=a  b"
72  *          compare with:
73  *              $ ls i=`echo 'a  b'`     # ls has two args: "i=a" and "b"
74  *              ls: cannot access i=a: No such file or directory
75  *              ls: cannot access b: No such file or directory
76  *          Note1: same applies to local builtin.
77  *          Note2: bash 3.2.33(1) does this only if export word itself
78  *          is not quoted:
79  *              $ export i=`echo 'aaa  bbb'`; echo "$i"
80  *              aaa  bbb
81  *              $ "export" i=`echo 'aaa  bbb'`; echo "$i"
82  *              aaa
83  */
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85         || defined(__APPLE__) \
86     )
87 # include <malloc.h>   /* for malloc_trim */
88 #endif
89 #include <glob.h>
90 /* #include <dmalloc.h> */
91 #if ENABLE_HUSH_CASE
92 # include <fnmatch.h>
93 #endif
94 #include <sys/utsname.h> /* for setting $HOSTNAME */
95
96 #include "busybox.h"  /* for APPLET_IS_NOFORK/NOEXEC */
97 #include "unicode.h"
98 #include "shell_common.h"
99 #include "math.h"
100 #include "match.h"
101 #if ENABLE_HUSH_RANDOM_SUPPORT
102 # include "random.h"
103 #else
104 # define CLEAR_RANDOM_T(rnd) ((void)0)
105 #endif
106 #ifndef F_DUPFD_CLOEXEC
107 # define F_DUPFD_CLOEXEC F_DUPFD
108 #endif
109 #ifndef PIPE_BUF
110 # define PIPE_BUF 4096  /* amount of buffering in a pipe */
111 #endif
112
113 //config:config HUSH
114 //config:       bool "hush"
115 //config:       default y
116 //config:       help
117 //config:         hush is a small shell (25k). It handles the normal flow control
118 //config:         constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config:         case/esac. Redirections, here documents, $((arithmetic))
120 //config:         and functions are supported.
121 //config:
122 //config:         It will compile and work on no-mmu systems.
123 //config:
124 //config:         It does not handle select, aliases, tilde expansion,
125 //config:         &>file and >&file redirection of stdout+stderr.
126 //config:
127 //config:config HUSH_BASH_COMPAT
128 //config:       bool "bash-compatible extensions"
129 //config:       default y
130 //config:       depends on HUSH
131 //config:       help
132 //config:         Enable bash-compatible extensions.
133 //config:
134 //config:config HUSH_BRACE_EXPANSION
135 //config:       bool "Brace expansion"
136 //config:       default y
137 //config:       depends on HUSH_BASH_COMPAT
138 //config:       help
139 //config:         Enable {abc,def} extension.
140 //config:
141 //config:config HUSH_HELP
142 //config:       bool "help builtin"
143 //config:       default y
144 //config:       depends on HUSH
145 //config:       help
146 //config:         Enable help builtin in hush. Code size + ~1 kbyte.
147 //config:
148 //config:config HUSH_INTERACTIVE
149 //config:       bool "Interactive mode"
150 //config:       default y
151 //config:       depends on HUSH
152 //config:       help
153 //config:         Enable interactive mode (prompt and command editing).
154 //config:         Without this, hush simply reads and executes commands
155 //config:         from stdin just like a shell script from a file.
156 //config:         No prompt, no PS1/PS2 magic shell variables.
157 //config:
158 //config:config HUSH_SAVEHISTORY
159 //config:       bool "Save command history to .hush_history"
160 //config:       default y
161 //config:       depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162 //config:       help
163 //config:         Enable history saving in hush.
164 //config:
165 //config:config HUSH_JOB
166 //config:       bool "Job control"
167 //config:       default y
168 //config:       depends on HUSH_INTERACTIVE
169 //config:       help
170 //config:         Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config:         command (not entire shell), fg/bg builtins work. Without this option,
172 //config:         "cmd &" still works by simply spawning a process and immediately
173 //config:         prompting for next command (or executing next command in a script),
174 //config:         but no separate process group is formed.
175 //config:
176 //config:config HUSH_TICK
177 //config:       bool "Process substitution"
178 //config:       default y
179 //config:       depends on HUSH
180 //config:       help
181 //config:         Enable process substitution `command` and $(command) in hush.
182 //config:
183 //config:config HUSH_IF
184 //config:       bool "Support if/then/elif/else/fi"
185 //config:       default y
186 //config:       depends on HUSH
187 //config:       help
188 //config:         Enable if/then/elif/else/fi in hush.
189 //config:
190 //config:config HUSH_LOOPS
191 //config:       bool "Support for, while and until loops"
192 //config:       default y
193 //config:       depends on HUSH
194 //config:       help
195 //config:         Enable for, while and until loops in hush.
196 //config:
197 //config:config HUSH_CASE
198 //config:       bool "Support case ... esac statement"
199 //config:       default y
200 //config:       depends on HUSH
201 //config:       help
202 //config:         Enable case ... esac statement in hush. +400 bytes.
203 //config:
204 //config:config HUSH_FUNCTIONS
205 //config:       bool "Support funcname() { commands; } syntax"
206 //config:       default y
207 //config:       depends on HUSH
208 //config:       help
209 //config:         Enable support for shell functions in hush. +800 bytes.
210 //config:
211 //config:config HUSH_LOCAL
212 //config:       bool "Support local builtin"
213 //config:       default y
214 //config:       depends on HUSH_FUNCTIONS
215 //config:       help
216 //config:         Enable support for local variables in functions.
217 //config:
218 //config:config HUSH_RANDOM_SUPPORT
219 //config:       bool "Pseudorandom generator and $RANDOM variable"
220 //config:       default y
221 //config:       depends on HUSH
222 //config:       help
223 //config:         Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config:         Each read of "$RANDOM" will generate a new pseudorandom value.
225 //config:
226 //config:config HUSH_EXPORT_N
227 //config:       bool "Support 'export -n' option"
228 //config:       default y
229 //config:       depends on HUSH
230 //config:       help
231 //config:         export -n unexports variables. It is a bash extension.
232 //config:
233 //config:config HUSH_MODE_X
234 //config:       bool "Support 'hush -x' option and 'set -x' command"
235 //config:       default y
236 //config:       depends on HUSH
237 //config:       help
238 //config:         This instructs hush to print commands before execution.
239 //config:         Adds ~300 bytes.
240 //config:
241 //config:config MSH
242 //config:       bool "msh (deprecated: aliased to hush)"
243 //config:       default n
244 //config:       select HUSH
245 //config:       help
246 //config:         msh is deprecated and will be removed, please migrate to hush.
247 //config:
248
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
253
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
256
257 /* -i (interactive) and -s (read stdin) are also accepted,
258  * but currently do nothing, therefore aren't shown in help.
259  * NOMMU-specific options are not meant to be used by users,
260  * therefore we don't show them either.
261  */
262 //usage:#define hush_trivial_usage
263 //usage:        "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage:        "Unix shell interpreter"
266
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
269
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage    hush_full_usage
273 //usage:#endif
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage    hush_full_usage
277 //usage:#endif
278
279
280 /* Build knobs */
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284  * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285  * Keeping 1 for now even in released versions.
286  */
287 #define HUSH_DEBUG 1
288 /* Slightly bigger (+200 bytes), but faster hush.
289  * So far it only enables a trick with counting SIGCHLDs and forks,
290  * which allows us to do fewer waitpid's.
291  * (we can detect a case where neither forks were done nor SIGCHLDs happened
292  * and therefore waitpid will return the same result as last time)
293  */
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296  * So far ${var%...} ops are always enabled:
297  */
298 #define ENABLE_HUSH_DOLLAR_OPS 1
299
300
301 #if BUILD_AS_NOMMU
302 # undef BB_MMU
303 # undef USE_FOR_NOMMU
304 # undef USE_FOR_MMU
305 # define BB_MMU 0
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
308 #endif
309
310 #include "NUM_APPLETS.h"
311 #if NUM_APPLETS == 1
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
320 #endif
321
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
327 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
328 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
329 #endif
330
331 /* Do we support ANY keywords? */
332 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
333 # define HAS_KEYWORDS 1
334 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
335 # define IF_HAS_NO_KEYWORDS(...)
336 #else
337 # define HAS_KEYWORDS 0
338 # define IF_HAS_KEYWORDS(...)
339 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
340 #endif
341
342 /* If you comment out one of these below, it will be #defined later
343  * to perform debug printfs to stderr: */
344 #define debug_printf(...)        do {} while (0)
345 /* Finer-grained debug switches */
346 #define debug_printf_parse(...)  do {} while (0)
347 #define debug_print_tree(a, b)   do {} while (0)
348 #define debug_printf_exec(...)   do {} while (0)
349 #define debug_printf_env(...)    do {} while (0)
350 #define debug_printf_jobs(...)   do {} while (0)
351 #define debug_printf_expand(...) do {} while (0)
352 #define debug_printf_varexp(...) do {} while (0)
353 #define debug_printf_glob(...)   do {} while (0)
354 #define debug_printf_list(...)   do {} while (0)
355 #define debug_printf_subst(...)  do {} while (0)
356 #define debug_printf_clean(...)  do {} while (0)
357
358 #define ERR_PTR ((void*)(long)1)
359
360 #define JOB_STATUS_FORMAT    "[%d] %-22s %.40s\n"
361
362 #define _SPECIAL_VARS_STR     "_*@$!?#"
363 #define SPECIAL_VARS_STR     ("_*@$!?#" + 1)
364 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
365 #if ENABLE_HUSH_BASH_COMPAT
366 /* Support / and // replace ops */
367 /* Note that // is stored as \ in "encoded" string representation */
368 # define VAR_ENCODED_SUBST_OPS      "\\/%#:-=+?"
369 # define VAR_SUBST_OPS             ("\\/%#:-=+?" + 1)
370 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
371 #else
372 # define VAR_ENCODED_SUBST_OPS      "%#:-=+?"
373 # define VAR_SUBST_OPS              "%#:-=+?"
374 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
375 #endif
376
377 #define SPECIAL_VAR_SYMBOL   3
378
379 struct variable;
380
381 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
382
383 /* This supports saving pointers malloced in vfork child,
384  * to be freed in the parent.
385  */
386 #if !BB_MMU
387 typedef struct nommu_save_t {
388         char **new_env;
389         struct variable *old_vars;
390         char **argv;
391         char **argv_from_re_execing;
392 } nommu_save_t;
393 #endif
394
395 enum {
396         RES_NONE  = 0,
397 #if ENABLE_HUSH_IF
398         RES_IF    ,
399         RES_THEN  ,
400         RES_ELIF  ,
401         RES_ELSE  ,
402         RES_FI    ,
403 #endif
404 #if ENABLE_HUSH_LOOPS
405         RES_FOR   ,
406         RES_WHILE ,
407         RES_UNTIL ,
408         RES_DO    ,
409         RES_DONE  ,
410 #endif
411 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
412         RES_IN    ,
413 #endif
414 #if ENABLE_HUSH_CASE
415         RES_CASE  ,
416         /* three pseudo-keywords support contrived "case" syntax: */
417         RES_CASE_IN,   /* "case ... IN", turns into RES_MATCH when IN is observed */
418         RES_MATCH ,    /* "word)" */
419         RES_CASE_BODY, /* "this command is inside CASE" */
420         RES_ESAC  ,
421 #endif
422         RES_XXXX  ,
423         RES_SNTX
424 };
425
426 typedef struct o_string {
427         char *data;
428         int length; /* position where data is appended */
429         int maxlen;
430         int o_expflags;
431         /* At least some part of the string was inside '' or "",
432          * possibly empty one: word"", wo''rd etc. */
433         smallint has_quoted_part;
434         smallint has_empty_slot;
435         smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
436 } o_string;
437 enum {
438         EXP_FLAG_SINGLEWORD     = 0x80, /* must be 0x80 */
439         EXP_FLAG_GLOB           = 0x2,
440         /* Protect newly added chars against globbing
441          * by prepending \ to *, ?, [, \ */
442         EXP_FLAG_ESC_GLOB_CHARS = 0x1,
443 };
444 enum {
445         MAYBE_ASSIGNMENT      = 0,
446         DEFINITELY_ASSIGNMENT = 1,
447         NOT_ASSIGNMENT        = 2,
448         /* Not an assignment, but next word may be: "if v=xyz cmd;" */
449         WORD_IS_KEYWORD       = 3,
450 };
451 /* Used for initialization: o_string foo = NULL_O_STRING; */
452 #define NULL_O_STRING { NULL }
453
454 #ifndef debug_printf_parse
455 static const char *const assignment_flag[] = {
456         "MAYBE_ASSIGNMENT",
457         "DEFINITELY_ASSIGNMENT",
458         "NOT_ASSIGNMENT",
459         "WORD_IS_KEYWORD",
460 };
461 #endif
462
463 typedef struct in_str {
464         const char *p;
465 #if ENABLE_HUSH_INTERACTIVE
466         smallint promptmode; /* 0: PS1, 1: PS2 */
467 #endif
468         int peek_buf[2];
469         int last_char;
470         FILE *file;
471         int (*get) (struct in_str *) FAST_FUNC;
472         int (*peek) (struct in_str *) FAST_FUNC;
473 } in_str;
474 #define i_getch(input) ((input)->get(input))
475 #define i_peek(input)  ((input)->peek(input))
476
477 /* The descrip member of this structure is only used to make
478  * debugging output pretty */
479 static const struct {
480         int mode;
481         signed char default_fd;
482         char descrip[3];
483 } redir_table[] = {
484         { O_RDONLY,                  0, "<"  },
485         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
486         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
487         { O_CREAT|O_RDWR,            1, "<>" },
488         { O_RDONLY,                  0, "<<" },
489 /* Should not be needed. Bogus default_fd helps in debugging */
490 /*      { O_RDONLY,                 77, "<<" }, */
491 };
492
493 struct redir_struct {
494         struct redir_struct *next;
495         char *rd_filename;          /* filename */
496         int rd_fd;                  /* fd to redirect */
497         /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
498         int rd_dup;
499         smallint rd_type;           /* (enum redir_type) */
500         /* note: for heredocs, rd_filename contains heredoc delimiter,
501          * and subsequently heredoc itself; and rd_dup is a bitmask:
502          * bit 0: do we need to trim leading tabs?
503          * bit 1: is heredoc quoted (<<'delim' syntax) ?
504          */
505 };
506 typedef enum redir_type {
507         REDIRECT_INPUT     = 0,
508         REDIRECT_OVERWRITE = 1,
509         REDIRECT_APPEND    = 2,
510         REDIRECT_IO        = 3,
511         REDIRECT_HEREDOC   = 4,
512         REDIRECT_HEREDOC2  = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
513
514         REDIRFD_CLOSE      = -3,
515         REDIRFD_SYNTAX_ERR = -2,
516         REDIRFD_TO_FILE    = -1,
517         /* otherwise, rd_fd is redirected to rd_dup */
518
519         HEREDOC_SKIPTABS = 1,
520         HEREDOC_QUOTED   = 2,
521 } redir_type;
522
523
524 struct command {
525         pid_t pid;                  /* 0 if exited */
526         int assignment_cnt;         /* how many argv[i] are assignments? */
527         smallint cmd_type;          /* CMD_xxx */
528 #define CMD_NORMAL   0
529 #define CMD_SUBSHELL 1
530 #if ENABLE_HUSH_BASH_COMPAT
531 /* used for "[[ EXPR ]]" */
532 # define CMD_SINGLEWORD_NOGLOB 2
533 #endif
534 #if ENABLE_HUSH_FUNCTIONS
535 # define CMD_FUNCDEF 3
536 #endif
537
538         smalluint cmd_exitcode;
539         /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
540         struct pipe *group;
541 #if !BB_MMU
542         char *group_as_string;
543 #endif
544 #if ENABLE_HUSH_FUNCTIONS
545         struct function *child_func;
546 /* This field is used to prevent a bug here:
547  * while...do f1() {a;}; f1; f1() {b;}; f1; done
548  * When we execute "f1() {a;}" cmd, we create new function and clear
549  * cmd->group, cmd->group_as_string, cmd->argv[0].
550  * When we execute "f1() {b;}", we notice that f1 exists,
551  * and that its "parent cmd" struct is still "alive",
552  * we put those fields back into cmd->xxx
553  * (struct function has ->parent_cmd ptr to facilitate that).
554  * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
555  * Without this trick, loop would execute a;b;b;b;...
556  * instead of correct sequence a;b;a;b;...
557  * When command is freed, it severs the link
558  * (sets ->child_func->parent_cmd to NULL).
559  */
560 #endif
561         char **argv;                /* command name and arguments */
562 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
563  * and on execution these are substituted with their values.
564  * Substitution can make _several_ words out of one argv[n]!
565  * Example: argv[0]=='.^C*^C.' here: echo .$*.
566  * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
567  */
568         struct redir_struct *redirects; /* I/O redirections */
569 };
570 /* Is there anything in this command at all? */
571 #define IS_NULL_CMD(cmd) \
572         (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
573
574 struct pipe {
575         struct pipe *next;
576         int num_cmds;               /* total number of commands in pipe */
577         int alive_cmds;             /* number of commands running (not exited) */
578         int stopped_cmds;           /* number of commands alive, but stopped */
579 #if ENABLE_HUSH_JOB
580         int jobid;                  /* job number */
581         pid_t pgrp;                 /* process group ID for the job */
582         char *cmdtext;              /* name of job */
583 #endif
584         struct command *cmds;       /* array of commands in pipe */
585         smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
586         IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
587         IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
588 };
589 typedef enum pipe_style {
590         PIPE_SEQ = 1,
591         PIPE_AND = 2,
592         PIPE_OR  = 3,
593         PIPE_BG  = 4,
594 } pipe_style;
595 /* Is there anything in this pipe at all? */
596 #define IS_NULL_PIPE(pi) \
597         ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
598
599 /* This holds pointers to the various results of parsing */
600 struct parse_context {
601         /* linked list of pipes */
602         struct pipe *list_head;
603         /* last pipe (being constructed right now) */
604         struct pipe *pipe;
605         /* last command in pipe (being constructed right now) */
606         struct command *command;
607         /* last redirect in command->redirects list */
608         struct redir_struct *pending_redirect;
609 #if !BB_MMU
610         o_string as_string;
611 #endif
612 #if HAS_KEYWORDS
613         smallint ctx_res_w;
614         smallint ctx_inverted; /* "! cmd | cmd" */
615 #if ENABLE_HUSH_CASE
616         smallint ctx_dsemicolon; /* ";;" seen */
617 #endif
618         /* bitmask of FLAG_xxx, for figuring out valid reserved words */
619         int old_flag;
620         /* group we are enclosed in:
621          * example: "if pipe1; pipe2; then pipe3; fi"
622          * when we see "if" or "then", we malloc and copy current context,
623          * and make ->stack point to it. then we parse pipeN.
624          * when closing "then" / fi" / whatever is found,
625          * we move list_head into ->stack->command->group,
626          * copy ->stack into current context, and delete ->stack.
627          * (parsing of { list } and ( list ) doesn't use this method)
628          */
629         struct parse_context *stack;
630 #endif
631 };
632
633 /* On program start, environ points to initial environment.
634  * putenv adds new pointers into it, unsetenv removes them.
635  * Neither of these (de)allocates the strings.
636  * setenv allocates new strings in malloc space and does putenv,
637  * and thus setenv is unusable (leaky) for shell's purposes */
638 #define setenv(...) setenv_is_leaky_dont_use()
639 struct variable {
640         struct variable *next;
641         char *varstr;        /* points to "name=" portion */
642 #if ENABLE_HUSH_LOCAL
643         unsigned func_nest_level;
644 #endif
645         int max_len;         /* if > 0, name is part of initial env; else name is malloced */
646         smallint flg_export; /* putenv should be done on this var */
647         smallint flg_read_only;
648 };
649
650 enum {
651         BC_BREAK = 1,
652         BC_CONTINUE = 2,
653 };
654
655 #if ENABLE_HUSH_FUNCTIONS
656 struct function {
657         struct function *next;
658         char *name;
659         struct command *parent_cmd;
660         struct pipe *body;
661 # if !BB_MMU
662         char *body_as_string;
663 # endif
664 };
665 #endif
666
667
668 /* set -/+o OPT support. (TODO: make it optional)
669  * bash supports the following opts:
670  * allexport       off
671  * braceexpand     on
672  * emacs           on
673  * errexit         off
674  * errtrace        off
675  * functrace       off
676  * hashall         on
677  * histexpand      off
678  * history         on
679  * ignoreeof       off
680  * interactive-comments    on
681  * keyword         off
682  * monitor         on
683  * noclobber       off
684  * noexec          off
685  * noglob          off
686  * nolog           off
687  * notify          off
688  * nounset         off
689  * onecmd          off
690  * physical        off
691  * pipefail        off
692  * posix           off
693  * privileged      off
694  * verbose         off
695  * vi              off
696  * xtrace          off
697  */
698 static const char o_opt_strings[] ALIGN1 =
699         "pipefail\0"
700         "noexec\0"
701 #if ENABLE_HUSH_MODE_X
702         "xtrace\0"
703 #endif
704         ;
705 enum {
706         OPT_O_PIPEFAIL,
707         OPT_O_NOEXEC,
708 #if ENABLE_HUSH_MODE_X
709         OPT_O_XTRACE,
710 #endif
711         NUM_OPT_O
712 };
713
714
715 struct FILE_list {
716         struct FILE_list *next;
717         FILE *fp;
718         int fd;
719 };
720
721
722 /* "Globals" within this file */
723 /* Sorted roughly by size (smaller offsets == smaller code) */
724 struct globals {
725         /* interactive_fd != 0 means we are an interactive shell.
726          * If we are, then saved_tty_pgrp can also be != 0, meaning
727          * that controlling tty is available. With saved_tty_pgrp == 0,
728          * job control still works, but terminal signals
729          * (^C, ^Z, ^Y, ^\) won't work at all, and background
730          * process groups can only be created with "cmd &".
731          * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
732          * to give tty to the foreground process group,
733          * and will take it back when the group is stopped (^Z)
734          * or killed (^C).
735          */
736 #if ENABLE_HUSH_INTERACTIVE
737         /* 'interactive_fd' is a fd# open to ctty, if we have one
738          * _AND_ if we decided to act interactively */
739         int interactive_fd;
740         const char *PS1;
741         const char *PS2;
742 # define G_interactive_fd (G.interactive_fd)
743 #else
744 # define G_interactive_fd 0
745 #endif
746 #if ENABLE_FEATURE_EDITING
747         line_input_t *line_input_state;
748 #endif
749         pid_t root_pid;
750         pid_t root_ppid;
751         pid_t last_bg_pid;
752 #if ENABLE_HUSH_RANDOM_SUPPORT
753         random_t random_gen;
754 #endif
755 #if ENABLE_HUSH_JOB
756         int run_list_level;
757         int last_jobid;
758         pid_t saved_tty_pgrp;
759         struct pipe *job_list;
760 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
761 #else
762 # define G_saved_tty_pgrp 0
763 #endif
764         char o_opt[NUM_OPT_O];
765 #if ENABLE_HUSH_MODE_X
766 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
767 #else
768 # define G_x_mode 0
769 #endif
770         smallint flag_SIGINT;
771 #if ENABLE_HUSH_LOOPS
772         smallint flag_break_continue;
773 #endif
774 #if ENABLE_HUSH_FUNCTIONS
775         /* 0: outside of a function (or sourced file)
776          * -1: inside of a function, ok to use return builtin
777          * 1: return is invoked, skip all till end of func
778          */
779         smallint flag_return_in_progress;
780 # define G_flag_return_in_progress (G.flag_return_in_progress)
781 #else
782 # define G_flag_return_in_progress 0
783 #endif
784         smallint exiting; /* used to prevent EXIT trap recursion */
785         /* These four support $?, $#, and $1 */
786         smalluint last_exitcode;
787         /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
788         smalluint global_args_malloced;
789         /* how many non-NULL argv's we have. NB: $# + 1 */
790         int global_argc;
791         char **global_argv;
792 #if !BB_MMU
793         char *argv0_for_re_execing;
794 #endif
795 #if ENABLE_HUSH_LOOPS
796         unsigned depth_break_continue;
797         unsigned depth_of_loop;
798 #endif
799         const char *ifs;
800         const char *cwd;
801         struct variable *top_var;
802         char **expanded_assignments;
803 #if ENABLE_HUSH_FUNCTIONS
804         struct function *top_func;
805 # if ENABLE_HUSH_LOCAL
806         struct variable **shadowed_vars_pp;
807         unsigned func_nest_level;
808 # endif
809 #endif
810         /* Signal and trap handling */
811 #if ENABLE_HUSH_FAST
812         unsigned count_SIGCHLD;
813         unsigned handled_SIGCHLD;
814         smallint we_have_children;
815 #endif
816         struct FILE_list *FILE_list;
817         /* Which signals have non-DFL handler (even with no traps set)?
818          * Set at the start to:
819          * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
820          * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
821          * The rest is cleared right before execv syscalls.
822          * Other than these two times, never modified.
823          */
824         unsigned special_sig_mask;
825 #if ENABLE_HUSH_JOB
826         unsigned fatal_sig_mask;
827 # define G_fatal_sig_mask G.fatal_sig_mask
828 #else
829 # define G_fatal_sig_mask 0
830 #endif
831         char **traps; /* char *traps[NSIG] */
832         sigset_t pending_set;
833 #if HUSH_DEBUG
834         unsigned long memleak_value;
835         int debug_indent;
836 #endif
837         struct sigaction sa;
838 #if ENABLE_FEATURE_EDITING
839         char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
840 #endif
841 };
842 #define G (*ptr_to_globals)
843 /* Not #defining name to G.name - this quickly gets unwieldy
844  * (too many defines). Also, I actually prefer to see when a variable
845  * is global, thus "G." prefix is a useful hint */
846 #define INIT_G() do { \
847         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
848         /* memset(&G.sa, 0, sizeof(G.sa)); */  \
849         sigfillset(&G.sa.sa_mask); \
850         G.sa.sa_flags = SA_RESTART; \
851 } while (0)
852
853
854 /* Function prototypes for builtins */
855 static int builtin_cd(char **argv) FAST_FUNC;
856 static int builtin_echo(char **argv) FAST_FUNC;
857 static int builtin_eval(char **argv) FAST_FUNC;
858 static int builtin_exec(char **argv) FAST_FUNC;
859 static int builtin_exit(char **argv) FAST_FUNC;
860 static int builtin_export(char **argv) FAST_FUNC;
861 #if ENABLE_HUSH_JOB
862 static int builtin_fg_bg(char **argv) FAST_FUNC;
863 static int builtin_jobs(char **argv) FAST_FUNC;
864 #endif
865 #if ENABLE_HUSH_HELP
866 static int builtin_help(char **argv) FAST_FUNC;
867 #endif
868 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
869 static int builtin_history(char **argv) FAST_FUNC;
870 #endif
871 #if ENABLE_HUSH_LOCAL
872 static int builtin_local(char **argv) FAST_FUNC;
873 #endif
874 #if HUSH_DEBUG
875 static int builtin_memleak(char **argv) FAST_FUNC;
876 #endif
877 #if ENABLE_PRINTF
878 static int builtin_printf(char **argv) FAST_FUNC;
879 #endif
880 static int builtin_pwd(char **argv) FAST_FUNC;
881 static int builtin_read(char **argv) FAST_FUNC;
882 static int builtin_set(char **argv) FAST_FUNC;
883 static int builtin_shift(char **argv) FAST_FUNC;
884 static int builtin_source(char **argv) FAST_FUNC;
885 static int builtin_test(char **argv) FAST_FUNC;
886 static int builtin_trap(char **argv) FAST_FUNC;
887 static int builtin_type(char **argv) FAST_FUNC;
888 static int builtin_true(char **argv) FAST_FUNC;
889 static int builtin_umask(char **argv) FAST_FUNC;
890 static int builtin_unset(char **argv) FAST_FUNC;
891 static int builtin_wait(char **argv) FAST_FUNC;
892 #if ENABLE_HUSH_LOOPS
893 static int builtin_break(char **argv) FAST_FUNC;
894 static int builtin_continue(char **argv) FAST_FUNC;
895 #endif
896 #if ENABLE_HUSH_FUNCTIONS
897 static int builtin_return(char **argv) FAST_FUNC;
898 #endif
899
900 /* Table of built-in functions.  They can be forked or not, depending on
901  * context: within pipes, they fork.  As simple commands, they do not.
902  * When used in non-forking context, they can change global variables
903  * in the parent shell process.  If forked, of course they cannot.
904  * For example, 'unset foo | whatever' will parse and run, but foo will
905  * still be set at the end. */
906 struct built_in_command {
907         const char *b_cmd;
908         int (*b_function)(char **argv) FAST_FUNC;
909 #if ENABLE_HUSH_HELP
910         const char *b_descr;
911 # define BLTIN(cmd, func, help) { cmd, func, help }
912 #else
913 # define BLTIN(cmd, func, help) { cmd, func }
914 #endif
915 };
916
917 static const struct built_in_command bltins1[] = {
918         BLTIN("."        , builtin_source  , "Run commands in a file"),
919         BLTIN(":"        , builtin_true    , NULL),
920 #if ENABLE_HUSH_JOB
921         BLTIN("bg"       , builtin_fg_bg   , "Resume a job in the background"),
922 #endif
923 #if ENABLE_HUSH_LOOPS
924         BLTIN("break"    , builtin_break   , "Exit from a loop"),
925 #endif
926         BLTIN("cd"       , builtin_cd      , "Change directory"),
927 #if ENABLE_HUSH_LOOPS
928         BLTIN("continue" , builtin_continue, "Start new loop iteration"),
929 #endif
930         BLTIN("eval"     , builtin_eval    , "Construct and run shell command"),
931         BLTIN("exec"     , builtin_exec    , "Execute command, don't return to shell"),
932         BLTIN("exit"     , builtin_exit    , "Exit"),
933         BLTIN("export"   , builtin_export  , "Set environment variables"),
934 #if ENABLE_HUSH_JOB
935         BLTIN("fg"       , builtin_fg_bg   , "Bring job into the foreground"),
936 #endif
937 #if ENABLE_HUSH_HELP
938         BLTIN("help"     , builtin_help    , NULL),
939 #endif
940 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
941         BLTIN("history"  , builtin_history , "Show command history"),
942 #endif
943 #if ENABLE_HUSH_JOB
944         BLTIN("jobs"     , builtin_jobs    , "List jobs"),
945 #endif
946 #if ENABLE_HUSH_LOCAL
947         BLTIN("local"    , builtin_local   , "Set local variables"),
948 #endif
949 #if HUSH_DEBUG
950         BLTIN("memleak"  , builtin_memleak , NULL),
951 #endif
952         BLTIN("read"     , builtin_read    , "Input into variable"),
953 #if ENABLE_HUSH_FUNCTIONS
954         BLTIN("return"   , builtin_return  , "Return from a function"),
955 #endif
956         BLTIN("set"      , builtin_set     , "Set/unset positional parameters"),
957         BLTIN("shift"    , builtin_shift   , "Shift positional parameters"),
958 #if ENABLE_HUSH_BASH_COMPAT
959         BLTIN("source"   , builtin_source  , "Run commands in a file"),
960 #endif
961         BLTIN("trap"     , builtin_trap    , "Trap signals"),
962         BLTIN("true"     , builtin_true    , NULL),
963         BLTIN("type"     , builtin_type    , "Show command type"),
964         BLTIN("ulimit"   , shell_builtin_ulimit  , "Control resource limits"),
965         BLTIN("umask"    , builtin_umask   , "Set file creation mask"),
966         BLTIN("unset"    , builtin_unset   , "Unset variables"),
967         BLTIN("wait"     , builtin_wait    , "Wait for process"),
968 };
969 /* For now, echo and test are unconditionally enabled.
970  * Maybe make it configurable? */
971 static const struct built_in_command bltins2[] = {
972         BLTIN("["        , builtin_test    , NULL),
973         BLTIN("echo"     , builtin_echo    , NULL),
974 #if ENABLE_PRINTF
975         BLTIN("printf"   , builtin_printf  , NULL),
976 #endif
977         BLTIN("pwd"      , builtin_pwd     , NULL),
978         BLTIN("test"     , builtin_test    , NULL),
979 };
980
981
982 /* Debug printouts.
983  */
984 #if HUSH_DEBUG
985 /* prevent disasters with G.debug_indent < 0 */
986 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
987 # define debug_enter() (G.debug_indent++)
988 # define debug_leave() (G.debug_indent--)
989 #else
990 # define indent()      ((void)0)
991 # define debug_enter() ((void)0)
992 # define debug_leave() ((void)0)
993 #endif
994
995 #ifndef debug_printf
996 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
997 #endif
998
999 #ifndef debug_printf_parse
1000 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
1001 #endif
1002
1003 #ifndef debug_printf_exec
1004 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
1005 #endif
1006
1007 #ifndef debug_printf_env
1008 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
1009 #endif
1010
1011 #ifndef debug_printf_jobs
1012 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 # define DEBUG_JOBS 1
1014 #else
1015 # define DEBUG_JOBS 0
1016 #endif
1017
1018 #ifndef debug_printf_expand
1019 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1020 # define DEBUG_EXPAND 1
1021 #else
1022 # define DEBUG_EXPAND 0
1023 #endif
1024
1025 #ifndef debug_printf_varexp
1026 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1027 #endif
1028
1029 #ifndef debug_printf_glob
1030 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1031 # define DEBUG_GLOB 1
1032 #else
1033 # define DEBUG_GLOB 0
1034 #endif
1035
1036 #ifndef debug_printf_list
1037 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1038 #endif
1039
1040 #ifndef debug_printf_subst
1041 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1042 #endif
1043
1044 #ifndef debug_printf_clean
1045 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1046 # define DEBUG_CLEAN 1
1047 #else
1048 # define DEBUG_CLEAN 0
1049 #endif
1050
1051 #if DEBUG_EXPAND
1052 static void debug_print_strings(const char *prefix, char **vv)
1053 {
1054         indent();
1055         fdprintf(2, "%s:\n", prefix);
1056         while (*vv)
1057                 fdprintf(2, " '%s'\n", *vv++);
1058 }
1059 #else
1060 # define debug_print_strings(prefix, vv) ((void)0)
1061 #endif
1062
1063
1064 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1065  */
1066 #if LEAK_HUNTING
1067 static void *xxmalloc(int lineno, size_t size)
1068 {
1069         void *ptr = xmalloc((size + 0xff) & ~0xff);
1070         fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1071         return ptr;
1072 }
1073 static void *xxrealloc(int lineno, void *ptr, size_t size)
1074 {
1075         ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1076         fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1077         return ptr;
1078 }
1079 static char *xxstrdup(int lineno, const char *str)
1080 {
1081         char *ptr = xstrdup(str);
1082         fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1083         return ptr;
1084 }
1085 static void xxfree(void *ptr)
1086 {
1087         fdprintf(2, "free %p\n", ptr);
1088         free(ptr);
1089 }
1090 # define xmalloc(s)     xxmalloc(__LINE__, s)
1091 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1092 # define xstrdup(s)     xxstrdup(__LINE__, s)
1093 # define free(p)        xxfree(p)
1094 #endif
1095
1096
1097 /* Syntax and runtime errors. They always abort scripts.
1098  * In interactive use they usually discard unparsed and/or unexecuted commands
1099  * and return to the prompt.
1100  * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1101  */
1102 #if HUSH_DEBUG < 2
1103 # define die_if_script(lineno, ...)             die_if_script(__VA_ARGS__)
1104 # define syntax_error(lineno, msg)              syntax_error(msg)
1105 # define syntax_error_at(lineno, msg)           syntax_error_at(msg)
1106 # define syntax_error_unterm_ch(lineno, ch)     syntax_error_unterm_ch(ch)
1107 # define syntax_error_unterm_str(lineno, s)     syntax_error_unterm_str(s)
1108 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1109 #endif
1110
1111 static void die_if_script(unsigned lineno, const char *fmt, ...)
1112 {
1113         va_list p;
1114
1115 #if HUSH_DEBUG >= 2
1116         bb_error_msg("hush.c:%u", lineno);
1117 #endif
1118         va_start(p, fmt);
1119         bb_verror_msg(fmt, p, NULL);
1120         va_end(p);
1121         if (!G_interactive_fd)
1122                 xfunc_die();
1123 }
1124
1125 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1126 {
1127         if (msg)
1128                 bb_error_msg("syntax error: %s", msg);
1129         else
1130                 bb_error_msg("syntax error");
1131 }
1132
1133 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1134 {
1135         bb_error_msg("syntax error at '%s'", msg);
1136 }
1137
1138 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1139 {
1140         bb_error_msg("syntax error: unterminated %s", s);
1141 }
1142
1143 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1144 {
1145         char msg[2] = { ch, '\0' };
1146         syntax_error_unterm_str(lineno, msg);
1147 }
1148
1149 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1150 {
1151         char msg[2];
1152         msg[0] = ch;
1153         msg[1] = '\0';
1154         bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1155 }
1156
1157 #if HUSH_DEBUG < 2
1158 # undef die_if_script
1159 # undef syntax_error
1160 # undef syntax_error_at
1161 # undef syntax_error_unterm_ch
1162 # undef syntax_error_unterm_str
1163 # undef syntax_error_unexpected_ch
1164 #else
1165 # define die_if_script(...)             die_if_script(__LINE__, __VA_ARGS__)
1166 # define syntax_error(msg)              syntax_error(__LINE__, msg)
1167 # define syntax_error_at(msg)           syntax_error_at(__LINE__, msg)
1168 # define syntax_error_unterm_ch(ch)     syntax_error_unterm_ch(__LINE__, ch)
1169 # define syntax_error_unterm_str(s)     syntax_error_unterm_str(__LINE__, s)
1170 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1171 #endif
1172
1173
1174 #if ENABLE_HUSH_INTERACTIVE
1175 static void cmdedit_update_prompt(void);
1176 #else
1177 # define cmdedit_update_prompt() ((void)0)
1178 #endif
1179
1180
1181 /* Utility functions
1182  */
1183 /* Replace each \x with x in place, return ptr past NUL. */
1184 static char *unbackslash(char *src)
1185 {
1186         char *dst = src = strchrnul(src, '\\');
1187         while (1) {
1188                 if (*src == '\\')
1189                         src++;
1190                 if ((*dst++ = *src++) == '\0')
1191                         break;
1192         }
1193         return dst;
1194 }
1195
1196 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1197 {
1198         int i;
1199         unsigned count1;
1200         unsigned count2;
1201         char **v;
1202
1203         v = strings;
1204         count1 = 0;
1205         if (v) {
1206                 while (*v) {
1207                         count1++;
1208                         v++;
1209                 }
1210         }
1211         count2 = 0;
1212         v = add;
1213         while (*v) {
1214                 count2++;
1215                 v++;
1216         }
1217         v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1218         v[count1 + count2] = NULL;
1219         i = count2;
1220         while (--i >= 0)
1221                 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1222         return v;
1223 }
1224 #if LEAK_HUNTING
1225 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1226 {
1227         char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1228         fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1229         return ptr;
1230 }
1231 #define add_strings_to_strings(strings, add, need_to_dup) \
1232         xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1233 #endif
1234
1235 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1236 static char **add_string_to_strings(char **strings, char *add)
1237 {
1238         char *v[2];
1239         v[0] = add;
1240         v[1] = NULL;
1241         return add_strings_to_strings(strings, v, /*dup:*/ 0);
1242 }
1243 #if LEAK_HUNTING
1244 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1245 {
1246         char **ptr = add_string_to_strings(strings, add);
1247         fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1248         return ptr;
1249 }
1250 #define add_string_to_strings(strings, add) \
1251         xx_add_string_to_strings(__LINE__, strings, add)
1252 #endif
1253
1254 static void free_strings(char **strings)
1255 {
1256         char **v;
1257
1258         if (!strings)
1259                 return;
1260         v = strings;
1261         while (*v) {
1262                 free(*v);
1263                 v++;
1264         }
1265         free(strings);
1266 }
1267
1268
1269 static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1270 {
1271         /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1272         int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1273         if (newfd < 0) {
1274                 /* fd was not open? */
1275                 if (errno == EBADF)
1276                         return fd;
1277                 xfunc_die();
1278         }
1279         close(fd);
1280         return newfd;
1281 }
1282
1283
1284 /* Manipulating the list of open FILEs */
1285 static FILE *remember_FILE(FILE *fp)
1286 {
1287         if (fp) {
1288                 struct FILE_list *n = xmalloc(sizeof(*n));
1289                 n->next = G.FILE_list;
1290                 G.FILE_list = n;
1291                 n->fp = fp;
1292                 n->fd = fileno(fp);
1293                 close_on_exec_on(n->fd);
1294         }
1295         return fp;
1296 }
1297 static void fclose_and_forget(FILE *fp)
1298 {
1299         struct FILE_list **pp = &G.FILE_list;
1300         while (*pp) {
1301                 struct FILE_list *cur = *pp;
1302                 if (cur->fp == fp) {
1303                         *pp = cur->next;
1304                         free(cur);
1305                         break;
1306                 }
1307                 pp = &cur->next;
1308         }
1309         fclose(fp);
1310 }
1311 static int save_FILEs_on_redirect(int fd)
1312 {
1313         struct FILE_list *fl = G.FILE_list;
1314         while (fl) {
1315                 if (fd == fl->fd) {
1316                         /* We use it only on script files, they are all CLOEXEC */
1317                         fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1318                         return 1;
1319                 }
1320                 fl = fl->next;
1321         }
1322         return 0;
1323 }
1324 static void restore_redirected_FILEs(void)
1325 {
1326         struct FILE_list *fl = G.FILE_list;
1327         while (fl) {
1328                 int should_be = fileno(fl->fp);
1329                 if (fl->fd != should_be) {
1330                         xmove_fd(fl->fd, should_be);
1331                         fl->fd = should_be;
1332                 }
1333                 fl = fl->next;
1334         }
1335 }
1336 #if ENABLE_FEATURE_SH_STANDALONE
1337 static void close_all_FILE_list(void)
1338 {
1339         struct FILE_list *fl = G.FILE_list;
1340         while (fl) {
1341                 /* fclose would also free FILE object.
1342                  * It is disastrous if we share memory with a vforked parent.
1343                  * I'm not sure we never come here after vfork.
1344                  * Therefore just close fd, nothing more.
1345                  */
1346                 /*fclose(fl->fp); - unsafe */
1347                 close(fl->fd);
1348                 fl = fl->next;
1349         }
1350 }
1351 #endif
1352
1353
1354 /* Helpers for setting new $n and restoring them back
1355  */
1356 typedef struct save_arg_t {
1357         char *sv_argv0;
1358         char **sv_g_argv;
1359         int sv_g_argc;
1360         smallint sv_g_malloced;
1361 } save_arg_t;
1362
1363 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1364 {
1365         int n;
1366
1367         sv->sv_argv0 = argv[0];
1368         sv->sv_g_argv = G.global_argv;
1369         sv->sv_g_argc = G.global_argc;
1370         sv->sv_g_malloced = G.global_args_malloced;
1371
1372         argv[0] = G.global_argv[0]; /* retain $0 */
1373         G.global_argv = argv;
1374         G.global_args_malloced = 0;
1375
1376         n = 1;
1377         while (*++argv)
1378                 n++;
1379         G.global_argc = n;
1380 }
1381
1382 static void restore_G_args(save_arg_t *sv, char **argv)
1383 {
1384         char **pp;
1385
1386         if (G.global_args_malloced) {
1387                 /* someone ran "set -- arg1 arg2 ...", undo */
1388                 pp = G.global_argv;
1389                 while (*++pp) /* note: does not free $0 */
1390                         free(*pp);
1391                 free(G.global_argv);
1392         }
1393         argv[0] = sv->sv_argv0;
1394         G.global_argv = sv->sv_g_argv;
1395         G.global_argc = sv->sv_g_argc;
1396         G.global_args_malloced = sv->sv_g_malloced;
1397 }
1398
1399
1400 /* Basic theory of signal handling in shell
1401  * ========================================
1402  * This does not describe what hush does, rather, it is current understanding
1403  * what it _should_ do. If it doesn't, it's a bug.
1404  * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1405  *
1406  * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1407  * is finished or backgrounded. It is the same in interactive and
1408  * non-interactive shells, and is the same regardless of whether
1409  * a user trap handler is installed or a shell special one is in effect.
1410  * ^C or ^Z from keyboard seems to execute "at once" because it usually
1411  * backgrounds (i.e. stops) or kills all members of currently running
1412  * pipe.
1413  *
1414  * Wait builtin is interruptible by signals for which user trap is set
1415  * or by SIGINT in interactive shell.
1416  *
1417  * Trap handlers will execute even within trap handlers. (right?)
1418  *
1419  * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1420  * except for handlers set to '' (empty string).
1421  *
1422  * If job control is off, backgrounded commands ("cmd &")
1423  * have SIGINT, SIGQUIT set to SIG_IGN.
1424  *
1425  * Commands which are run in command substitution ("`cmd`")
1426  * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1427  *
1428  * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1429  * by the shell from its parent.
1430  *
1431  * Signals which differ from SIG_DFL action
1432  * (note: child (i.e., [v]forked) shell is not an interactive shell):
1433  *
1434  * SIGQUIT: ignore
1435  * SIGTERM (interactive): ignore
1436  * SIGHUP (interactive):
1437  *    send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1438  * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1439  *    Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1440  *    that all pipe members are stopped. Try this in bash:
1441  *    while :; do :; done - ^Z does not background it
1442  *    (while :; do :; done) - ^Z backgrounds it
1443  * SIGINT (interactive): wait for last pipe, ignore the rest
1444  *    of the command line, show prompt. NB: ^C does not send SIGINT
1445  *    to interactive shell while shell is waiting for a pipe,
1446  *    since shell is bg'ed (is not in foreground process group).
1447  *    Example 1: this waits 5 sec, but does not execute ls:
1448  *    "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1449  *    Example 2: this does not wait and does not execute ls:
1450  *    "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1451  *    Example 3: this does not wait 5 sec, but executes ls:
1452  *    "sleep 5; ls -l" + press ^C
1453  *    Example 4: this does not wait and does not execute ls:
1454  *    "sleep 5 & wait; ls -l" + press ^C
1455  *
1456  * (What happens to signals which are IGN on shell start?)
1457  * (What happens with signal mask on shell start?)
1458  *
1459  * Old implementation
1460  * ==================
1461  * We use in-kernel pending signal mask to determine which signals were sent.
1462  * We block all signals which we don't want to take action immediately,
1463  * i.e. we block all signals which need to have special handling as described
1464  * above, and all signals which have traps set.
1465  * After each pipe execution, we extract any pending signals via sigtimedwait()
1466  * and act on them.
1467  *
1468  * unsigned special_sig_mask: a mask of such "special" signals
1469  * sigset_t blocked_set:  current blocked signal set
1470  *
1471  * "trap - SIGxxx":
1472  *    clear bit in blocked_set unless it is also in special_sig_mask
1473  * "trap 'cmd' SIGxxx":
1474  *    set bit in blocked_set (even if 'cmd' is '')
1475  * after [v]fork, if we plan to be a shell:
1476  *    unblock signals with special interactive handling
1477  *    (child shell is not interactive),
1478  *    unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1479  * after [v]fork, if we plan to exec:
1480  *    POSIX says fork clears pending signal mask in child - no need to clear it.
1481  *    Restore blocked signal set to one inherited by shell just prior to exec.
1482  *
1483  * Note: as a result, we do not use signal handlers much. The only uses
1484  * are to count SIGCHLDs
1485  * and to restore tty pgrp on signal-induced exit.
1486  *
1487  * Note 2 (compat):
1488  * Standard says "When a subshell is entered, traps that are not being ignored
1489  * are set to the default actions". bash interprets it so that traps which
1490  * are set to '' (ignore) are NOT reset to defaults. We do the same.
1491  *
1492  * Problem: the above approach makes it unwieldy to catch signals while
1493  * we are in read builtin, or while we read commands from stdin:
1494  * masked signals are not visible!
1495  *
1496  * New implementation
1497  * ==================
1498  * We record each signal we are interested in by installing signal handler
1499  * for them - a bit like emulating kernel pending signal mask in userspace.
1500  * We are interested in: signals which need to have special handling
1501  * as described above, and all signals which have traps set.
1502  * Signals are recorded in pending_set.
1503  * After each pipe execution, we extract any pending signals
1504  * and act on them.
1505  *
1506  * unsigned special_sig_mask: a mask of shell-special signals.
1507  * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1508  * char *traps[sig] if trap for sig is set (even if it's '').
1509  * sigset_t pending_set: set of sigs we received.
1510  *
1511  * "trap - SIGxxx":
1512  *    if sig is in special_sig_mask, set handler back to:
1513  *        record_pending_signo, or to IGN if it's a tty stop signal
1514  *    if sig is in fatal_sig_mask, set handler back to sigexit.
1515  *    else: set handler back to SIG_DFL
1516  * "trap 'cmd' SIGxxx":
1517  *    set handler to record_pending_signo.
1518  * "trap '' SIGxxx":
1519  *    set handler to SIG_IGN.
1520  * after [v]fork, if we plan to be a shell:
1521  *    set signals with special interactive handling to SIG_DFL
1522  *    (because child shell is not interactive),
1523  *    unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1524  * after [v]fork, if we plan to exec:
1525  *    POSIX says fork clears pending signal mask in child - no need to clear it.
1526  *
1527  * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1528  * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1529  *
1530  * Note (compat):
1531  * Standard says "When a subshell is entered, traps that are not being ignored
1532  * are set to the default actions". bash interprets it so that traps which
1533  * are set to '' (ignore) are NOT reset to defaults. We do the same.
1534  */
1535 enum {
1536         SPECIAL_INTERACTIVE_SIGS = 0
1537                 | (1 << SIGTERM)
1538                 | (1 << SIGINT)
1539                 | (1 << SIGHUP)
1540                 ,
1541         SPECIAL_JOBSTOP_SIGS = 0
1542 #if ENABLE_HUSH_JOB
1543                 | (1 << SIGTTIN)
1544                 | (1 << SIGTTOU)
1545                 | (1 << SIGTSTP)
1546 #endif
1547                 ,
1548 };
1549
1550 static void record_pending_signo(int sig)
1551 {
1552         sigaddset(&G.pending_set, sig);
1553 #if ENABLE_HUSH_FAST
1554         if (sig == SIGCHLD) {
1555                 G.count_SIGCHLD++;
1556 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1557         }
1558 #endif
1559 }
1560
1561 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1562 {
1563         struct sigaction old_sa;
1564
1565         /* We could use signal() to install handlers... almost:
1566          * except that we need to mask ALL signals while handlers run.
1567          * I saw signal nesting in strace, race window isn't small.
1568          * SA_RESTART is also needed, but in Linux, signal()
1569          * sets SA_RESTART too.
1570          */
1571         /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1572         /* sigfillset(&G.sa.sa_mask);      - already done */
1573         /* G.sa.sa_flags = SA_RESTART;     - already done */
1574         G.sa.sa_handler = handler;
1575         sigaction(sig, &G.sa, &old_sa);
1576         return old_sa.sa_handler;
1577 }
1578
1579 static void hush_exit(int exitcode) NORETURN;
1580 static void fflush_and__exit(void) NORETURN;
1581 static void restore_ttypgrp_and__exit(void) NORETURN;
1582
1583 static void restore_ttypgrp_and__exit(void)
1584 {
1585         /* xfunc has failed! die die die */
1586         /* no EXIT traps, this is an escape hatch! */
1587         G.exiting = 1;
1588         hush_exit(xfunc_error_retval);
1589 }
1590
1591 /* Needed only on some libc:
1592  * It was observed that on exit(), fgetc'ed buffered data
1593  * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1594  * With the net effect that even after fork(), not vfork(),
1595  * exit() in NOEXECed applet in "sh SCRIPT":
1596  *      noexec_applet_here
1597  *      echo END_OF_SCRIPT
1598  * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1599  * This makes "echo END_OF_SCRIPT" executed twice.
1600  * Similar problems can be seen with die_if_script() -> xfunc_die()
1601  * and in `cmd` handling.
1602  * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1603  */
1604 static void fflush_and__exit(void)
1605 {
1606         fflush_all();
1607         _exit(xfunc_error_retval);
1608 }
1609
1610 #if ENABLE_HUSH_JOB
1611
1612 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1613 # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
1614 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1615 # define enable_restore_tty_pgrp_on_exit()  (die_func = restore_ttypgrp_and__exit)
1616
1617 /* Restores tty foreground process group, and exits.
1618  * May be called as signal handler for fatal signal
1619  * (will resend signal to itself, producing correct exit state)
1620  * or called directly with -EXITCODE.
1621  * We also call it if xfunc is exiting.
1622  */
1623 static void sigexit(int sig) NORETURN;
1624 static void sigexit(int sig)
1625 {
1626         /* Careful: we can end up here after [v]fork. Do not restore
1627          * tty pgrp then, only top-level shell process does that */
1628         if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1629                 /* Disable all signals: job control, SIGPIPE, etc.
1630                  * Mostly paranoid measure, to prevent infinite SIGTTOU.
1631                  */
1632                 sigprocmask_allsigs(SIG_BLOCK);
1633                 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1634         }
1635
1636         /* Not a signal, just exit */
1637         if (sig <= 0)
1638                 _exit(- sig);
1639
1640         kill_myself_with_sig(sig); /* does not return */
1641 }
1642 #else
1643
1644 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1645 # define enable_restore_tty_pgrp_on_exit()  ((void)0)
1646
1647 #endif
1648
1649 static sighandler_t pick_sighandler(unsigned sig)
1650 {
1651         sighandler_t handler = SIG_DFL;
1652         if (sig < sizeof(unsigned)*8) {
1653                 unsigned sigmask = (1 << sig);
1654
1655 #if ENABLE_HUSH_JOB
1656                 /* is sig fatal? */
1657                 if (G_fatal_sig_mask & sigmask)
1658                         handler = sigexit;
1659                 else
1660 #endif
1661                 /* sig has special handling? */
1662                 if (G.special_sig_mask & sigmask) {
1663                         handler = record_pending_signo;
1664                         /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1665                          * in order to ignore them: they will be raised
1666                          * in an endless loop when we try to do some
1667                          * terminal ioctls! We do have to _ignore_ these.
1668                          */
1669                         if (SPECIAL_JOBSTOP_SIGS & sigmask)
1670                                 handler = SIG_IGN;
1671                 }
1672         }
1673         return handler;
1674 }
1675
1676 /* Restores tty foreground process group, and exits. */
1677 static void hush_exit(int exitcode)
1678 {
1679 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1680         save_history(G.line_input_state);
1681 #endif
1682
1683         fflush_all();
1684         if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1685                 char *argv[3];
1686                 /* argv[0] is unused */
1687                 argv[1] = G.traps[0];
1688                 argv[2] = NULL;
1689                 G.exiting = 1; /* prevent EXIT trap recursion */
1690                 /* Note: G.traps[0] is not cleared!
1691                  * "trap" will still show it, if executed
1692                  * in the handler */
1693                 builtin_eval(argv);
1694         }
1695
1696 #if ENABLE_FEATURE_CLEAN_UP
1697         {
1698                 struct variable *cur_var;
1699                 if (G.cwd != bb_msg_unknown)
1700                         free((char*)G.cwd);
1701                 cur_var = G.top_var;
1702                 while (cur_var) {
1703                         struct variable *tmp = cur_var;
1704                         if (!cur_var->max_len)
1705                                 free(cur_var->varstr);
1706                         cur_var = cur_var->next;
1707                         free(tmp);
1708                 }
1709         }
1710 #endif
1711
1712         fflush_all();
1713 #if ENABLE_HUSH_JOB
1714         sigexit(- (exitcode & 0xff));
1715 #else
1716         _exit(exitcode);
1717 #endif
1718 }
1719
1720
1721 //TODO: return a mask of ALL handled sigs?
1722 static int check_and_run_traps(void)
1723 {
1724         int last_sig = 0;
1725
1726         while (1) {
1727                 int sig;
1728
1729                 if (sigisemptyset(&G.pending_set))
1730                         break;
1731                 sig = 0;
1732                 do {
1733                         sig++;
1734                         if (sigismember(&G.pending_set, sig)) {
1735                                 sigdelset(&G.pending_set, sig);
1736                                 goto got_sig;
1737                         }
1738                 } while (sig < NSIG);
1739                 break;
1740  got_sig:
1741                 if (G.traps && G.traps[sig]) {
1742                         debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
1743                         if (G.traps[sig][0]) {
1744                                 /* We have user-defined handler */
1745                                 smalluint save_rcode;
1746                                 char *argv[3];
1747                                 /* argv[0] is unused */
1748                                 argv[1] = G.traps[sig];
1749                                 argv[2] = NULL;
1750                                 save_rcode = G.last_exitcode;
1751                                 builtin_eval(argv);
1752                                 G.last_exitcode = save_rcode;
1753                                 last_sig = sig;
1754                         } /* else: "" trap, ignoring signal */
1755                         continue;
1756                 }
1757                 /* not a trap: special action */
1758                 switch (sig) {
1759                 case SIGINT:
1760                         debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
1761                         /* Builtin was ^C'ed, make it look prettier: */
1762                         bb_putchar('\n');
1763                         G.flag_SIGINT = 1;
1764                         last_sig = sig;
1765                         break;
1766 #if ENABLE_HUSH_JOB
1767                 case SIGHUP: {
1768                         struct pipe *job;
1769                         debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
1770                         /* bash is observed to signal whole process groups,
1771                          * not individual processes */
1772                         for (job = G.job_list; job; job = job->next) {
1773                                 if (job->pgrp <= 0)
1774                                         continue;
1775                                 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1776                                 if (kill(- job->pgrp, SIGHUP) == 0)
1777                                         kill(- job->pgrp, SIGCONT);
1778                         }
1779                         sigexit(SIGHUP);
1780                 }
1781 #endif
1782 #if ENABLE_HUSH_FAST
1783                 case SIGCHLD:
1784                         debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
1785                         G.count_SIGCHLD++;
1786 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1787                         /* Note:
1788                          * We dont do 'last_sig = sig' here -> NOT returning this sig.
1789                          * This simplifies wait builtin a bit.
1790                          */
1791                         break;
1792 #endif
1793                 default: /* ignored: */
1794                         debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
1795                         /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1796                         /* Note:
1797                          * We dont do 'last_sig = sig' here -> NOT returning this sig.
1798                          * Example: wait is not interrupted by TERM
1799                          * in interactive shell, because TERM is ignored.
1800                          */
1801                         break;
1802                 }
1803         }
1804         return last_sig;
1805 }
1806
1807
1808 static const char *get_cwd(int force)
1809 {
1810         if (force || G.cwd == NULL) {
1811                 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1812                  * we must not try to free(bb_msg_unknown) */
1813                 if (G.cwd == bb_msg_unknown)
1814                         G.cwd = NULL;
1815                 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1816                 if (!G.cwd)
1817                         G.cwd = bb_msg_unknown;
1818         }
1819         return G.cwd;
1820 }
1821
1822
1823 /*
1824  * Shell and environment variable support
1825  */
1826 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1827 {
1828         struct variable **pp;
1829         struct variable *cur;
1830
1831         pp = &G.top_var;
1832         while ((cur = *pp) != NULL) {
1833                 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1834                         return pp;
1835                 pp = &cur->next;
1836         }
1837         return NULL;
1838 }
1839
1840 static const char* FAST_FUNC get_local_var_value(const char *name)
1841 {
1842         struct variable **vpp;
1843         unsigned len = strlen(name);
1844
1845         if (G.expanded_assignments) {
1846                 char **cpp = G.expanded_assignments;
1847                 while (*cpp) {
1848                         char *cp = *cpp;
1849                         if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1850                                 return cp + len + 1;
1851                         cpp++;
1852                 }
1853         }
1854
1855         vpp = get_ptr_to_local_var(name, len);
1856         if (vpp)
1857                 return (*vpp)->varstr + len + 1;
1858
1859         if (strcmp(name, "PPID") == 0)
1860                 return utoa(G.root_ppid);
1861         // bash compat: UID? EUID?
1862 #if ENABLE_HUSH_RANDOM_SUPPORT
1863         if (strcmp(name, "RANDOM") == 0)
1864                 return utoa(next_random(&G.random_gen));
1865 #endif
1866         return NULL;
1867 }
1868
1869 /* str holds "NAME=VAL" and is expected to be malloced.
1870  * We take ownership of it.
1871  * flg_export:
1872  *  0: do not change export flag
1873  *     (if creating new variable, flag will be 0)
1874  *  1: set export flag and putenv the variable
1875  * -1: clear export flag and unsetenv the variable
1876  * flg_read_only is set only when we handle -R var=val
1877  */
1878 #if !BB_MMU && ENABLE_HUSH_LOCAL
1879 /* all params are used */
1880 #elif BB_MMU && ENABLE_HUSH_LOCAL
1881 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1882         set_local_var(str, flg_export, local_lvl)
1883 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1884 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1885         set_local_var(str, flg_export)
1886 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1887 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1888         set_local_var(str, flg_export, flg_read_only)
1889 #endif
1890 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1891 {
1892         struct variable **var_pp;
1893         struct variable *cur;
1894         char *eq_sign;
1895         int name_len;
1896
1897         eq_sign = strchr(str, '=');
1898         if (!eq_sign) { /* not expected to ever happen? */
1899                 free(str);
1900                 return -1;
1901         }
1902
1903         name_len = eq_sign - str + 1; /* including '=' */
1904         var_pp = &G.top_var;
1905         while ((cur = *var_pp) != NULL) {
1906                 if (strncmp(cur->varstr, str, name_len) != 0) {
1907                         var_pp = &cur->next;
1908                         continue;
1909                 }
1910                 /* We found an existing var with this name */
1911                 if (cur->flg_read_only) {
1912 #if !BB_MMU
1913                         if (!flg_read_only)
1914 #endif
1915                                 bb_error_msg("%s: readonly variable", str);
1916                         free(str);
1917                         return -1;
1918                 }
1919                 if (flg_export == -1) { // "&& cur->flg_export" ?
1920                         debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1921                         *eq_sign = '\0';
1922                         unsetenv(str);
1923                         *eq_sign = '=';
1924                 }
1925 #if ENABLE_HUSH_LOCAL
1926                 if (cur->func_nest_level < local_lvl) {
1927                         /* New variable is declared as local,
1928                          * and existing one is global, or local
1929                          * from enclosing function.
1930                          * Remove and save old one: */
1931                         *var_pp = cur->next;
1932                         cur->next = *G.shadowed_vars_pp;
1933                         *G.shadowed_vars_pp = cur;
1934                         /* bash 3.2.33(1) and exported vars:
1935                          * # export z=z
1936                          * # f() { local z=a; env | grep ^z; }
1937                          * # f
1938                          * z=a
1939                          * # env | grep ^z
1940                          * z=z
1941                          */
1942                         if (cur->flg_export)
1943                                 flg_export = 1;
1944                         break;
1945                 }
1946 #endif
1947                 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1948  free_and_exp:
1949                         free(str);
1950                         goto exp;
1951                 }
1952                 if (cur->max_len != 0) {
1953                         if (cur->max_len >= strlen(str)) {
1954                                 /* This one is from startup env, reuse space */
1955                                 strcpy(cur->varstr, str);
1956                                 goto free_and_exp;
1957                         }
1958                 } else {
1959                         /* max_len == 0 signifies "malloced" var, which we can
1960                          * (and has to) free */
1961                         free(cur->varstr);
1962                 }
1963                 cur->max_len = 0;
1964                 goto set_str_and_exp;
1965         }
1966
1967         /* Not found - create new variable struct */
1968         cur = xzalloc(sizeof(*cur));
1969 #if ENABLE_HUSH_LOCAL
1970         cur->func_nest_level = local_lvl;
1971 #endif
1972         cur->next = *var_pp;
1973         *var_pp = cur;
1974
1975  set_str_and_exp:
1976         cur->varstr = str;
1977 #if !BB_MMU
1978         cur->flg_read_only = flg_read_only;
1979 #endif
1980  exp:
1981         if (flg_export == 1)
1982                 cur->flg_export = 1;
1983         if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1984                 cmdedit_update_prompt();
1985         if (cur->flg_export) {
1986                 if (flg_export == -1) {
1987                         cur->flg_export = 0;
1988                         /* unsetenv was already done */
1989                 } else {
1990                         debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1991                         return putenv(cur->varstr);
1992                 }
1993         }
1994         return 0;
1995 }
1996
1997 /* Used at startup and after each cd */
1998 static void set_pwd_var(int exp)
1999 {
2000         set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2001                 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2002 }
2003
2004 static int unset_local_var_len(const char *name, int name_len)
2005 {
2006         struct variable *cur;
2007         struct variable **var_pp;
2008
2009         if (!name)
2010                 return EXIT_SUCCESS;
2011         var_pp = &G.top_var;
2012         while ((cur = *var_pp) != NULL) {
2013                 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2014                         if (cur->flg_read_only) {
2015                                 bb_error_msg("%s: readonly variable", name);
2016                                 return EXIT_FAILURE;
2017                         }
2018                         *var_pp = cur->next;
2019                         debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2020                         bb_unsetenv(cur->varstr);
2021                         if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2022                                 cmdedit_update_prompt();
2023                         if (!cur->max_len)
2024                                 free(cur->varstr);
2025                         free(cur);
2026                         return EXIT_SUCCESS;
2027                 }
2028                 var_pp = &cur->next;
2029         }
2030         return EXIT_SUCCESS;
2031 }
2032
2033 static int unset_local_var(const char *name)
2034 {
2035         return unset_local_var_len(name, strlen(name));
2036 }
2037
2038 static void unset_vars(char **strings)
2039 {
2040         char **v;
2041
2042         if (!strings)
2043                 return;
2044         v = strings;
2045         while (*v) {
2046                 const char *eq = strchrnul(*v, '=');
2047                 unset_local_var_len(*v, (int)(eq - *v));
2048                 v++;
2049         }
2050         free(strings);
2051 }
2052
2053 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
2054 {
2055         char *var = xasprintf("%s=%s", name, val);
2056         set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2057 }
2058
2059
2060 /*
2061  * Helpers for "var1=val1 var2=val2 cmd" feature
2062  */
2063 static void add_vars(struct variable *var)
2064 {
2065         struct variable *next;
2066
2067         while (var) {
2068                 next = var->next;
2069                 var->next = G.top_var;
2070                 G.top_var = var;
2071                 if (var->flg_export) {
2072                         debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
2073                         putenv(var->varstr);
2074                 } else {
2075                         debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
2076                 }
2077                 var = next;
2078         }
2079 }
2080
2081 static struct variable *set_vars_and_save_old(char **strings)
2082 {
2083         char **s;
2084         struct variable *old = NULL;
2085
2086         if (!strings)
2087                 return old;
2088         s = strings;
2089         while (*s) {
2090                 struct variable *var_p;
2091                 struct variable **var_pp;
2092                 char *eq;
2093
2094                 eq = strchr(*s, '=');
2095                 if (eq) {
2096                         var_pp = get_ptr_to_local_var(*s, eq - *s);
2097                         if (var_pp) {
2098                                 /* Remove variable from global linked list */
2099                                 var_p = *var_pp;
2100                                 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
2101                                 *var_pp = var_p->next;
2102                                 /* Add it to returned list */
2103                                 var_p->next = old;
2104                                 old = var_p;
2105                         }
2106                         set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
2107                 }
2108                 s++;
2109         }
2110         return old;
2111 }
2112
2113
2114 /*
2115  * Unicode helper
2116  */
2117 static void reinit_unicode_for_hush(void)
2118 {
2119         /* Unicode support should be activated even if LANG is set
2120          * _during_ shell execution, not only if it was set when
2121          * shell was started. Therefore, re-check LANG every time:
2122          */
2123         if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2124          || ENABLE_UNICODE_USING_LOCALE
2125         ) {
2126                 const char *s = get_local_var_value("LC_ALL");
2127                 if (!s) s = get_local_var_value("LC_CTYPE");
2128                 if (!s) s = get_local_var_value("LANG");
2129                 reinit_unicode(s);
2130         }
2131 }
2132
2133 /*
2134  * in_str support (strings, and "strings" read from files).
2135  */
2136
2137 #if ENABLE_HUSH_INTERACTIVE
2138 /* To test correct lineedit/interactive behavior, type from command line:
2139  *      echo $P\
2140  *      \
2141  *      AT\
2142  *      H\
2143  *      \
2144  * It excercises a lot of corner cases.
2145  */
2146 static void cmdedit_update_prompt(void)
2147 {
2148         if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2149                 G.PS1 = get_local_var_value("PS1");
2150                 if (G.PS1 == NULL)
2151                         G.PS1 = "\\w \\$ ";
2152                 G.PS2 = get_local_var_value("PS2");
2153         } else {
2154                 G.PS1 = NULL;
2155         }
2156         if (G.PS2 == NULL)
2157                 G.PS2 = "> ";
2158 }
2159 static const char *setup_prompt_string(int promptmode)
2160 {
2161         const char *prompt_str;
2162         debug_printf("setup_prompt_string %d ", promptmode);
2163         if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2164                 /* Set up the prompt */
2165                 if (promptmode == 0) { /* PS1 */
2166                         free((char*)G.PS1);
2167                         /* bash uses $PWD value, even if it is set by user.
2168                          * It uses current dir only if PWD is unset.
2169                          * We always use current dir. */
2170                         G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2171                         prompt_str = G.PS1;
2172                 } else
2173                         prompt_str = G.PS2;
2174         } else
2175                 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2176         debug_printf("prompt_str '%s'\n", prompt_str);
2177         return prompt_str;
2178 }
2179 static int get_user_input(struct in_str *i)
2180 {
2181         int r;
2182         const char *prompt_str;
2183
2184         prompt_str = setup_prompt_string(i->promptmode);
2185 # if ENABLE_FEATURE_EDITING
2186         do {
2187                 reinit_unicode_for_hush();
2188                 G.flag_SIGINT = 0;
2189                 /* buglet: SIGINT will not make new prompt to appear _at once_,
2190                  * only after <Enter>. (^C will work) */
2191                 r = read_line_input(G.line_input_state, prompt_str,
2192                                 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2193                                 /*timeout*/ -1
2194                 );
2195                 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2196                 check_and_run_traps();
2197         } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2198         if (r < 0) {
2199                 /* EOF/error detected */
2200                 i->p = NULL;
2201                 i->peek_buf[0] = r = EOF;
2202                 return r;
2203         }
2204         i->p = G.user_input_buf;
2205         return (unsigned char)*i->p++;
2206 # else
2207         do {
2208                 G.flag_SIGINT = 0;
2209                 if (i->last_char == '\0' || i->last_char == '\n') {
2210                         /* Why check_and_run_traps here? Try this interactively:
2211                          * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2212                          * $ <[enter], repeatedly...>
2213                          * Without check_and_run_traps, handler never runs.
2214                          */
2215                         check_and_run_traps();
2216                         fputs(prompt_str, stdout);
2217                 }
2218                 fflush_all();
2219                 r = fgetc(i->file);
2220         } while (G.flag_SIGINT || r == '\0');
2221         return r;
2222 # endif
2223 }
2224 /* This is the magic location that prints prompts
2225  * and gets data back from the user */
2226 static int fgetc_interactive(struct in_str *i)
2227 {
2228         int ch;
2229         /* If it's interactive stdin, get new line. */
2230         if (G_interactive_fd && i->file == stdin) {
2231                 /* Returns first char (or EOF), the rest is in i->p[] */
2232                 ch = get_user_input(i);
2233                 i->promptmode = 1; /* PS2 */
2234         } else {
2235                 /* Not stdin: script file, sourced file, etc */
2236                 do ch = fgetc(i->file); while (ch == '\0');
2237         }
2238         return ch;
2239 }
2240 #else
2241 static inline int fgetc_interactive(struct in_str *i)
2242 {
2243         int ch;
2244         do ch = fgetc(i->file); while (ch == '\0');
2245         return ch;
2246 }
2247 #endif  /* INTERACTIVE */
2248
2249 static int FAST_FUNC file_get(struct in_str *i)
2250 {
2251         int ch;
2252
2253 #if ENABLE_FEATURE_EDITING
2254         /* This can be stdin, check line editing char[] buffer */
2255         if (i->p && *i->p != '\0') {
2256                 ch = (unsigned char)*i->p++;
2257                 goto out;
2258         }
2259 #endif
2260         /* peek_buf[] is an int array, not char. Can contain EOF. */
2261         ch = i->peek_buf[0];
2262         if (ch != 0) {
2263                 int ch2 = i->peek_buf[1];
2264                 i->peek_buf[0] = ch2;
2265                 if (ch2 == 0) /* very likely, avoid redundant write */
2266                         goto out;
2267                 i->peek_buf[1] = 0;
2268                 goto out;
2269         }
2270
2271         ch = fgetc_interactive(i);
2272  out:
2273         debug_printf("file_get: got '%c' %d\n", ch, ch);
2274         i->last_char = ch;
2275         return ch;
2276 }
2277
2278 static int FAST_FUNC file_peek(struct in_str *i)
2279 {
2280         int ch;
2281
2282 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2283         /* This can be stdin, check line editing char[] buffer */
2284         if (i->p && *i->p != '\0')
2285                 return (unsigned char)*i->p;
2286 #endif
2287         /* peek_buf[] is an int array, not char. Can contain EOF. */
2288         ch = i->peek_buf[0];
2289         if (ch != 0)
2290                 return ch;
2291
2292         /* Need to get a new char */
2293         ch = fgetc_interactive(i);
2294         debug_printf("file_peek: got '%c' %d\n", ch, ch);
2295
2296         /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2297 #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2298         if (i->p) {
2299                 i->p -= 1;
2300                 return ch;
2301         }
2302 #endif
2303         i->peek_buf[0] = ch;
2304         /*i->peek_buf[1] = 0; - already is */
2305         return ch;
2306 }
2307
2308 static int FAST_FUNC static_get(struct in_str *i)
2309 {
2310         int ch = (unsigned char)*i->p;
2311         if (ch != '\0') {
2312                 i->p++;
2313                 i->last_char = ch;
2314                 return ch;
2315         }
2316         return EOF;
2317 }
2318
2319 static int FAST_FUNC static_peek(struct in_str *i)
2320 {
2321         /* Doesn't report EOF on NUL. None of the callers care. */
2322         return (unsigned char)*i->p;
2323 }
2324
2325 /* Only ever called if i_peek() was called, and did not return EOF.
2326  * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2327  * not end-of-line. Therefore we never need to read a new editing line here.
2328  */
2329 static int i_peek2(struct in_str *i)
2330 {
2331         int ch;
2332
2333         /* There are two cases when i->p[] buffer exists.
2334          * (1) it's a string in_str.
2335          * (2) It's a file, and we have a saved line editing buffer.
2336          * In both cases, we know that i->p[0] exists and not NUL, and
2337          * the peek2 result is in i->p[1].
2338          */
2339         if (i->p)
2340                 return (unsigned char)i->p[1];
2341
2342         /* Now we know it is a file-based in_str. */
2343
2344         /* peek_buf[] is an int array, not char. Can contain EOF. */
2345         /* Is there 2nd char? */
2346         ch = i->peek_buf[1];
2347         if (ch == 0) {
2348                 /* We did not read it yet, get it now */
2349                 do ch = fgetc(i->file); while (ch == '\0');
2350                 i->peek_buf[1] = ch;
2351         }
2352
2353         debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2354         return ch;
2355 }
2356
2357 static void setup_file_in_str(struct in_str *i, FILE *f)
2358 {
2359         memset(i, 0, sizeof(*i));
2360         i->get = file_get;
2361         i->peek = file_peek;
2362         /* i->promptmode = 0; - PS1 (memset did it) */
2363         i->file = f;
2364         /* i->p = NULL; */
2365 }
2366
2367 static void setup_string_in_str(struct in_str *i, const char *s)
2368 {
2369         memset(i, 0, sizeof(*i));
2370         i->get = static_get;
2371         i->peek = static_peek;
2372         /* i->promptmode = 0; - PS1 (memset did it) */
2373         i->p = s;
2374 }
2375
2376
2377 /*
2378  * o_string support
2379  */
2380 #define B_CHUNK  (32 * sizeof(char*))
2381
2382 static void o_reset_to_empty_unquoted(o_string *o)
2383 {
2384         o->length = 0;
2385         o->has_quoted_part = 0;
2386         if (o->data)
2387                 o->data[0] = '\0';
2388 }
2389
2390 static void o_free(o_string *o)
2391 {
2392         free(o->data);
2393         memset(o, 0, sizeof(*o));
2394 }
2395
2396 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2397 {
2398         free(o->data);
2399 }
2400
2401 static void o_grow_by(o_string *o, int len)
2402 {
2403         if (o->length + len > o->maxlen) {
2404                 o->maxlen += (2 * len) | (B_CHUNK-1);
2405                 o->data = xrealloc(o->data, 1 + o->maxlen);
2406         }
2407 }
2408
2409 static void o_addchr(o_string *o, int ch)
2410 {
2411         debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2412         if (o->length < o->maxlen) {
2413                 /* likely. avoid o_grow_by() call */
2414  add:
2415                 o->data[o->length] = ch;
2416                 o->length++;
2417                 o->data[o->length] = '\0';
2418                 return;
2419         }
2420         o_grow_by(o, 1);
2421         goto add;
2422 }
2423
2424 #if 0
2425 /* Valid only if we know o_string is not empty */
2426 static void o_delchr(o_string *o)
2427 {
2428         o->length--;
2429         o->data[o->length] = '\0';
2430 }
2431 #endif
2432
2433 static void o_addblock(o_string *o, const char *str, int len)
2434 {
2435         o_grow_by(o, len);
2436         memcpy(&o->data[o->length], str, len);
2437         o->length += len;
2438         o->data[o->length] = '\0';
2439 }
2440
2441 static void o_addstr(o_string *o, const char *str)
2442 {
2443         o_addblock(o, str, strlen(str));
2444 }
2445
2446 #if !BB_MMU
2447 static void nommu_addchr(o_string *o, int ch)
2448 {
2449         if (o)
2450                 o_addchr(o, ch);
2451 }
2452 #else
2453 # define nommu_addchr(o, str) ((void)0)
2454 #endif
2455
2456 static void o_addstr_with_NUL(o_string *o, const char *str)
2457 {
2458         o_addblock(o, str, strlen(str) + 1);
2459 }
2460
2461 /*
2462  * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2463  * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2464  * Apparently, on unquoted $v bash still does globbing
2465  * ("v='*.txt'; echo $v" prints all .txt files),
2466  * but NOT brace expansion! Thus, there should be TWO independent
2467  * quoting mechanisms on $v expansion side: one protects
2468  * $v from brace expansion, and other additionally protects "$v" against globbing.
2469  * We have only second one.
2470  */
2471
2472 #if ENABLE_HUSH_BRACE_EXPANSION
2473 # define MAYBE_BRACES "{}"
2474 #else
2475 # define MAYBE_BRACES ""
2476 #endif
2477
2478 /* My analysis of quoting semantics tells me that state information
2479  * is associated with a destination, not a source.
2480  */
2481 static void o_addqchr(o_string *o, int ch)
2482 {
2483         int sz = 1;
2484         char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2485         if (found)
2486                 sz++;
2487         o_grow_by(o, sz);
2488         if (found) {
2489                 o->data[o->length] = '\\';
2490                 o->length++;
2491         }
2492         o->data[o->length] = ch;
2493         o->length++;
2494         o->data[o->length] = '\0';
2495 }
2496
2497 static void o_addQchr(o_string *o, int ch)
2498 {
2499         int sz = 1;
2500         if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2501          && strchr("*?[\\" MAYBE_BRACES, ch)
2502         ) {
2503                 sz++;
2504                 o->data[o->length] = '\\';
2505                 o->length++;
2506         }
2507         o_grow_by(o, sz);
2508         o->data[o->length] = ch;
2509         o->length++;
2510         o->data[o->length] = '\0';
2511 }
2512
2513 static void o_addqblock(o_string *o, const char *str, int len)
2514 {
2515         while (len) {
2516                 char ch;
2517                 int sz;
2518                 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2519                 if (ordinary_cnt > len) /* paranoia */
2520                         ordinary_cnt = len;
2521                 o_addblock(o, str, ordinary_cnt);
2522                 if (ordinary_cnt == len)
2523                         return; /* NUL is already added by o_addblock */
2524                 str += ordinary_cnt;
2525                 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2526
2527                 ch = *str++;
2528                 sz = 1;
2529                 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2530                         sz++;
2531                         o->data[o->length] = '\\';
2532                         o->length++;
2533                 }
2534                 o_grow_by(o, sz);
2535                 o->data[o->length] = ch;
2536                 o->length++;
2537         }
2538         o->data[o->length] = '\0';
2539 }
2540
2541 static void o_addQblock(o_string *o, const char *str, int len)
2542 {
2543         if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2544                 o_addblock(o, str, len);
2545                 return;
2546         }
2547         o_addqblock(o, str, len);
2548 }
2549
2550 static void o_addQstr(o_string *o, const char *str)
2551 {
2552         o_addQblock(o, str, strlen(str));
2553 }
2554
2555 /* A special kind of o_string for $VAR and `cmd` expansion.
2556  * It contains char* list[] at the beginning, which is grown in 16 element
2557  * increments. Actual string data starts at the next multiple of 16 * (char*).
2558  * list[i] contains an INDEX (int!) into this string data.
2559  * It means that if list[] needs to grow, data needs to be moved higher up
2560  * but list[i]'s need not be modified.
2561  * NB: remembering how many list[i]'s you have there is crucial.
2562  * o_finalize_list() operation post-processes this structure - calculates
2563  * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2564  */
2565 #if DEBUG_EXPAND || DEBUG_GLOB
2566 static void debug_print_list(const char *prefix, o_string *o, int n)
2567 {
2568         char **list = (char**)o->data;
2569         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2570         int i = 0;
2571
2572         indent();
2573         fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2574                         prefix, list, n, string_start, o->length, o->maxlen,
2575                         !!(o->o_expflags & EXP_FLAG_GLOB),
2576                         o->has_quoted_part,
2577                         !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2578         while (i < n) {
2579                 indent();
2580                 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2581                                 o->data + (int)(uintptr_t)list[i] + string_start,
2582                                 o->data + (int)(uintptr_t)list[i] + string_start);
2583                 i++;
2584         }
2585         if (n) {
2586                 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2587                 indent();
2588                 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2589         }
2590 }
2591 #else
2592 # define debug_print_list(prefix, o, n) ((void)0)
2593 #endif
2594
2595 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2596  * in list[n] so that it points past last stored byte so far.
2597  * It returns n+1. */
2598 static int o_save_ptr_helper(o_string *o, int n)
2599 {
2600         char **list = (char**)o->data;
2601         int string_start;
2602         int string_len;
2603
2604         if (!o->has_empty_slot) {
2605                 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2606                 string_len = o->length - string_start;
2607                 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2608                         debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2609                         /* list[n] points to string_start, make space for 16 more pointers */
2610                         o->maxlen += 0x10 * sizeof(list[0]);
2611                         o->data = xrealloc(o->data, o->maxlen + 1);
2612                         list = (char**)o->data;
2613                         memmove(list + n + 0x10, list + n, string_len);
2614                         o->length += 0x10 * sizeof(list[0]);
2615                 } else {
2616                         debug_printf_list("list[%d]=%d string_start=%d\n",
2617                                         n, string_len, string_start);
2618                 }
2619         } else {
2620                 /* We have empty slot at list[n], reuse without growth */
2621                 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2622                 string_len = o->length - string_start;
2623                 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2624                                 n, string_len, string_start);
2625                 o->has_empty_slot = 0;
2626         }
2627         o->has_quoted_part = 0;
2628         list[n] = (char*)(uintptr_t)string_len;
2629         return n + 1;
2630 }
2631
2632 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2633 static int o_get_last_ptr(o_string *o, int n)
2634 {
2635         char **list = (char**)o->data;
2636         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2637
2638         return ((int)(uintptr_t)list[n-1]) + string_start;
2639 }
2640
2641 #if ENABLE_HUSH_BRACE_EXPANSION
2642 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2643  * first, it processes even {a} (no commas), second,
2644  * I didn't manage to make it return strings when they don't match
2645  * existing files. Need to re-implement it.
2646  */
2647
2648 /* Helper */
2649 static int glob_needed(const char *s)
2650 {
2651         while (*s) {
2652                 if (*s == '\\') {
2653                         if (!s[1])
2654                                 return 0;
2655                         s += 2;
2656                         continue;
2657                 }
2658                 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2659                         return 1;
2660                 s++;
2661         }
2662         return 0;
2663 }
2664 /* Return pointer to next closing brace or to comma */
2665 static const char *next_brace_sub(const char *cp)
2666 {
2667         unsigned depth = 0;
2668         cp++;
2669         while (*cp != '\0') {
2670                 if (*cp == '\\') {
2671                         if (*++cp == '\0')
2672                                 break;
2673                         cp++;
2674                         continue;
2675                 }
2676                 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2677                         break;
2678                 if (*cp++ == '{')
2679                         depth++;
2680         }
2681
2682         return *cp != '\0' ? cp : NULL;
2683 }
2684 /* Recursive brace globber. Note: may garble pattern[]. */
2685 static int glob_brace(char *pattern, o_string *o, int n)
2686 {
2687         char *new_pattern_buf;
2688         const char *begin;
2689         const char *next;
2690         const char *rest;
2691         const char *p;
2692         size_t rest_len;
2693
2694         debug_printf_glob("glob_brace('%s')\n", pattern);
2695
2696         begin = pattern;
2697         while (1) {
2698                 if (*begin == '\0')
2699                         goto simple_glob;
2700                 if (*begin == '{') {
2701                         /* Find the first sub-pattern and at the same time
2702                          * find the rest after the closing brace */
2703                         next = next_brace_sub(begin);
2704                         if (next == NULL) {
2705                                 /* An illegal expression */
2706                                 goto simple_glob;
2707                         }
2708                         if (*next == '}') {
2709                                 /* "{abc}" with no commas - illegal
2710                                  * brace expr, disregard and skip it */
2711                                 begin = next + 1;
2712                                 continue;
2713                         }
2714                         break;
2715                 }
2716                 if (*begin == '\\' && begin[1] != '\0')
2717                         begin++;
2718                 begin++;
2719         }
2720         debug_printf_glob("begin:%s\n", begin);
2721         debug_printf_glob("next:%s\n", next);
2722
2723         /* Now find the end of the whole brace expression */
2724         rest = next;
2725         while (*rest != '}') {
2726                 rest = next_brace_sub(rest);
2727                 if (rest == NULL) {
2728                         /* An illegal expression */
2729                         goto simple_glob;
2730                 }
2731                 debug_printf_glob("rest:%s\n", rest);
2732         }
2733         rest_len = strlen(++rest) + 1;
2734
2735         /* We are sure the brace expression is well-formed */
2736
2737         /* Allocate working buffer large enough for our work */
2738         new_pattern_buf = xmalloc(strlen(pattern));
2739
2740         /* We have a brace expression.  BEGIN points to the opening {,
2741          * NEXT points past the terminator of the first element, and REST
2742          * points past the final }.  We will accumulate result names from
2743          * recursive runs for each brace alternative in the buffer using
2744          * GLOB_APPEND.  */
2745
2746         p = begin + 1;
2747         while (1) {
2748                 /* Construct the new glob expression */
2749                 memcpy(
2750                         mempcpy(
2751                                 mempcpy(new_pattern_buf,
2752                                         /* We know the prefix for all sub-patterns */
2753                                         pattern, begin - pattern),
2754                                 p, next - p),
2755                         rest, rest_len);
2756
2757                 /* Note: glob_brace() may garble new_pattern_buf[].
2758                  * That's why we re-copy prefix every time (1st memcpy above).
2759                  */
2760                 n = glob_brace(new_pattern_buf, o, n);
2761                 if (*next == '}') {
2762                         /* We saw the last entry */
2763                         break;
2764                 }
2765                 p = next + 1;
2766                 next = next_brace_sub(next);
2767         }
2768         free(new_pattern_buf);
2769         return n;
2770
2771  simple_glob:
2772         {
2773                 int gr;
2774                 glob_t globdata;
2775
2776                 memset(&globdata, 0, sizeof(globdata));
2777                 gr = glob(pattern, 0, NULL, &globdata);
2778                 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2779                 if (gr != 0) {
2780                         if (gr == GLOB_NOMATCH) {
2781                                 globfree(&globdata);
2782                                 /* NB: garbles parameter */
2783                                 unbackslash(pattern);
2784                                 o_addstr_with_NUL(o, pattern);
2785                                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2786                                 return o_save_ptr_helper(o, n);
2787                         }
2788                         if (gr == GLOB_NOSPACE)
2789                                 bb_error_msg_and_die(bb_msg_memory_exhausted);
2790                         /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2791                          * but we didn't specify it. Paranoia again. */
2792                         bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2793                 }
2794                 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2795                         char **argv = globdata.gl_pathv;
2796                         while (1) {
2797                                 o_addstr_with_NUL(o, *argv);
2798                                 n = o_save_ptr_helper(o, n);
2799                                 argv++;
2800                                 if (!*argv)
2801                                         break;
2802                         }
2803                 }
2804                 globfree(&globdata);
2805         }
2806         return n;
2807 }
2808 /* Performs globbing on last list[],
2809  * saving each result as a new list[].
2810  */
2811 static int perform_glob(o_string *o, int n)
2812 {
2813         char *pattern, *copy;
2814
2815         debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2816         if (!o->data)
2817                 return o_save_ptr_helper(o, n);
2818         pattern = o->data + o_get_last_ptr(o, n);
2819         debug_printf_glob("glob pattern '%s'\n", pattern);
2820         if (!glob_needed(pattern)) {
2821                 /* unbackslash last string in o in place, fix length */
2822                 o->length = unbackslash(pattern) - o->data;
2823                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2824                 return o_save_ptr_helper(o, n);
2825         }
2826
2827         copy = xstrdup(pattern);
2828         /* "forget" pattern in o */
2829         o->length = pattern - o->data;
2830         n = glob_brace(copy, o, n);
2831         free(copy);
2832         if (DEBUG_GLOB)
2833                 debug_print_list("perform_glob returning", o, n);
2834         return n;
2835 }
2836
2837 #else /* !HUSH_BRACE_EXPANSION */
2838
2839 /* Helper */
2840 static int glob_needed(const char *s)
2841 {
2842         while (*s) {
2843                 if (*s == '\\') {
2844                         if (!s[1])
2845                                 return 0;
2846                         s += 2;
2847                         continue;
2848                 }
2849                 if (*s == '*' || *s == '[' || *s == '?')
2850                         return 1;
2851                 s++;
2852         }
2853         return 0;
2854 }
2855 /* Performs globbing on last list[],
2856  * saving each result as a new list[].
2857  */
2858 static int perform_glob(o_string *o, int n)
2859 {
2860         glob_t globdata;
2861         int gr;
2862         char *pattern;
2863
2864         debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2865         if (!o->data)
2866                 return o_save_ptr_helper(o, n);
2867         pattern = o->data + o_get_last_ptr(o, n);
2868         debug_printf_glob("glob pattern '%s'\n", pattern);
2869         if (!glob_needed(pattern)) {
2870  literal:
2871                 /* unbackslash last string in o in place, fix length */
2872                 o->length = unbackslash(pattern) - o->data;
2873                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2874                 return o_save_ptr_helper(o, n);
2875         }
2876
2877         memset(&globdata, 0, sizeof(globdata));
2878         /* Can't use GLOB_NOCHECK: it does not unescape the string.
2879          * If we glob "*.\*" and don't find anything, we need
2880          * to fall back to using literal "*.*", but GLOB_NOCHECK
2881          * will return "*.\*"!
2882          */
2883         gr = glob(pattern, 0, NULL, &globdata);
2884         debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2885         if (gr != 0) {
2886                 if (gr == GLOB_NOMATCH) {
2887                         globfree(&globdata);
2888                         goto literal;
2889                 }
2890                 if (gr == GLOB_NOSPACE)
2891                         bb_error_msg_and_die(bb_msg_memory_exhausted);
2892                 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2893                  * but we didn't specify it. Paranoia again. */
2894                 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2895         }
2896         if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2897                 char **argv = globdata.gl_pathv;
2898                 /* "forget" pattern in o */
2899                 o->length = pattern - o->data;
2900                 while (1) {
2901                         o_addstr_with_NUL(o, *argv);
2902                         n = o_save_ptr_helper(o, n);
2903                         argv++;
2904                         if (!*argv)
2905                                 break;
2906                 }
2907         }
2908         globfree(&globdata);
2909         if (DEBUG_GLOB)
2910                 debug_print_list("perform_glob returning", o, n);
2911         return n;
2912 }
2913
2914 #endif /* !HUSH_BRACE_EXPANSION */
2915
2916 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2917  * Otherwise, just finish current list[] and start new */
2918 static int o_save_ptr(o_string *o, int n)
2919 {
2920         if (o->o_expflags & EXP_FLAG_GLOB) {
2921                 /* If o->has_empty_slot, list[n] was already globbed
2922                  * (if it was requested back then when it was filled)
2923                  * so don't do that again! */
2924                 if (!o->has_empty_slot)
2925                         return perform_glob(o, n); /* o_save_ptr_helper is inside */
2926         }
2927         return o_save_ptr_helper(o, n);
2928 }
2929
2930 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2931 static char **o_finalize_list(o_string *o, int n)
2932 {
2933         char **list;
2934         int string_start;
2935
2936         n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2937         if (DEBUG_EXPAND)
2938                 debug_print_list("finalized", o, n);
2939         debug_printf_expand("finalized n:%d\n", n);
2940         list = (char**)o->data;
2941         string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2942         list[--n] = NULL;
2943         while (n) {
2944                 n--;
2945                 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2946         }
2947         return list;
2948 }
2949
2950 static void free_pipe_list(struct pipe *pi);
2951
2952 /* Returns pi->next - next pipe in the list */
2953 static struct pipe *free_pipe(struct pipe *pi)
2954 {
2955         struct pipe *next;
2956         int i;
2957
2958         debug_printf_clean("free_pipe (pid %d)\n", getpid());
2959         for (i = 0; i < pi->num_cmds; i++) {
2960                 struct command *command;
2961                 struct redir_struct *r, *rnext;
2962
2963                 command = &pi->cmds[i];
2964                 debug_printf_clean("  command %d:\n", i);
2965                 if (command->argv) {
2966                         if (DEBUG_CLEAN) {
2967                                 int a;
2968                                 char **p;
2969                                 for (a = 0, p = command->argv; *p; a++, p++) {
2970                                         debug_printf_clean("   argv[%d] = %s\n", a, *p);
2971                                 }
2972                         }
2973                         free_strings(command->argv);
2974                         //command->argv = NULL;
2975                 }
2976                 /* not "else if": on syntax error, we may have both! */
2977                 if (command->group) {
2978                         debug_printf_clean("   begin group (cmd_type:%d)\n",
2979                                         command->cmd_type);
2980                         free_pipe_list(command->group);
2981                         debug_printf_clean("   end group\n");
2982                         //command->group = NULL;
2983                 }
2984                 /* else is crucial here.
2985                  * If group != NULL, child_func is meaningless */
2986 #if ENABLE_HUSH_FUNCTIONS
2987                 else if (command->child_func) {
2988                         debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2989                         command->child_func->parent_cmd = NULL;
2990                 }
2991 #endif
2992 #if !BB_MMU
2993                 free(command->group_as_string);
2994                 //command->group_as_string = NULL;
2995 #endif
2996                 for (r = command->redirects; r; r = rnext) {
2997                         debug_printf_clean("   redirect %d%s",
2998                                         r->rd_fd, redir_table[r->rd_type].descrip);
2999                         /* guard against the case >$FOO, where foo is unset or blank */
3000                         if (r->rd_filename) {
3001                                 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3002                                 free(r->rd_filename);
3003                                 //r->rd_filename = NULL;
3004                         }
3005                         debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3006                         rnext = r->next;
3007                         free(r);
3008                 }
3009                 //command->redirects = NULL;
3010         }
3011         free(pi->cmds);   /* children are an array, they get freed all at once */
3012         //pi->cmds = NULL;
3013 #if ENABLE_HUSH_JOB
3014         free(pi->cmdtext);
3015         //pi->cmdtext = NULL;
3016 #endif
3017
3018         next = pi->next;
3019         free(pi);
3020         return next;
3021 }
3022
3023 static void free_pipe_list(struct pipe *pi)
3024 {
3025         while (pi) {
3026 #if HAS_KEYWORDS
3027                 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
3028 #endif
3029                 debug_printf_clean("pipe followup code %d\n", pi->followup);
3030                 pi = free_pipe(pi);
3031         }
3032 }
3033
3034
3035 /*** Parsing routines ***/
3036
3037 #ifndef debug_print_tree
3038 static void debug_print_tree(struct pipe *pi, int lvl)
3039 {
3040         static const char *const PIPE[] = {
3041                 [PIPE_SEQ] = "SEQ",
3042                 [PIPE_AND] = "AND",
3043                 [PIPE_OR ] = "OR" ,
3044                 [PIPE_BG ] = "BG" ,
3045         };
3046         static const char *RES[] = {
3047                 [RES_NONE ] = "NONE" ,
3048 # if ENABLE_HUSH_IF
3049                 [RES_IF   ] = "IF"   ,
3050                 [RES_THEN ] = "THEN" ,
3051                 [RES_ELIF ] = "ELIF" ,
3052                 [RES_ELSE ] = "ELSE" ,
3053                 [RES_FI   ] = "FI"   ,
3054 # endif
3055 # if ENABLE_HUSH_LOOPS
3056                 [RES_FOR  ] = "FOR"  ,
3057                 [RES_WHILE] = "WHILE",
3058                 [RES_UNTIL] = "UNTIL",
3059                 [RES_DO   ] = "DO"   ,
3060                 [RES_DONE ] = "DONE" ,
3061 # endif
3062 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3063                 [RES_IN   ] = "IN"   ,
3064 # endif
3065 # if ENABLE_HUSH_CASE
3066                 [RES_CASE ] = "CASE" ,
3067                 [RES_CASE_IN ] = "CASE_IN" ,
3068                 [RES_MATCH] = "MATCH",
3069                 [RES_CASE_BODY] = "CASE_BODY",
3070                 [RES_ESAC ] = "ESAC" ,
3071 # endif
3072                 [RES_XXXX ] = "XXXX" ,
3073                 [RES_SNTX ] = "SNTX" ,
3074         };
3075         static const char *const CMDTYPE[] = {
3076                 "{}",
3077                 "()",
3078                 "[noglob]",
3079 # if ENABLE_HUSH_FUNCTIONS
3080                 "func()",
3081 # endif
3082         };
3083
3084         int pin, prn;
3085
3086         pin = 0;
3087         while (pi) {
3088                 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3089                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3090                 prn = 0;
3091                 while (prn < pi->num_cmds) {
3092                         struct command *command = &pi->cmds[prn];
3093                         char **argv = command->argv;
3094
3095                         fdprintf(2, "%*s cmd %d assignment_cnt:%d",
3096                                         lvl*2, "", prn,
3097                                         command->assignment_cnt);
3098                         if (command->group) {
3099                                 fdprintf(2, " group %s: (argv=%p)%s%s\n",
3100                                                 CMDTYPE[command->cmd_type],
3101                                                 argv
3102 # if !BB_MMU
3103                                                 , " group_as_string:", command->group_as_string
3104 # else
3105                                                 , "", ""
3106 # endif
3107                                 );
3108                                 debug_print_tree(command->group, lvl+1);
3109                                 prn++;
3110                                 continue;
3111                         }
3112                         if (argv) while (*argv) {
3113                                 fdprintf(2, " '%s'", *argv);
3114                                 argv++;
3115                         }
3116                         fdprintf(2, "\n");
3117                         prn++;
3118                 }
3119                 pi = pi->next;
3120                 pin++;
3121         }
3122 }
3123 #endif /* debug_print_tree */
3124
3125 static struct pipe *new_pipe(void)
3126 {
3127         struct pipe *pi;
3128         pi = xzalloc(sizeof(struct pipe));
3129         /*pi->followup = 0; - deliberately invalid value */
3130         /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3131         return pi;
3132 }
3133
3134 /* Command (member of a pipe) is complete, or we start a new pipe
3135  * if ctx->command is NULL.
3136  * No errors possible here.
3137  */
3138 static int done_command(struct parse_context *ctx)
3139 {
3140         /* The command is really already in the pipe structure, so
3141          * advance the pipe counter and make a new, null command. */
3142         struct pipe *pi = ctx->pipe;
3143         struct command *command = ctx->command;
3144
3145 #if 0   /* Instead we emit error message at run time */
3146         if (ctx->pending_redirect) {
3147                 /* For example, "cmd >" (no filename to redirect to) */
3148                 die_if_script("syntax error: %s", "invalid redirect");
3149                 ctx->pending_redirect = NULL;
3150         }
3151 #endif
3152
3153         if (command) {
3154                 if (IS_NULL_CMD(command)) {
3155                         debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3156                         goto clear_and_ret;
3157                 }
3158                 pi->num_cmds++;
3159                 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3160                 //debug_print_tree(ctx->list_head, 20);
3161         } else {
3162                 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3163         }
3164
3165         /* Only real trickiness here is that the uncommitted
3166          * command structure is not counted in pi->num_cmds. */
3167         pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3168         ctx->command = command = &pi->cmds[pi->num_cmds];
3169  clear_and_ret:
3170         memset(command, 0, sizeof(*command));
3171         return pi->num_cmds; /* used only for 0/nonzero check */
3172 }
3173
3174 static void done_pipe(struct parse_context *ctx, pipe_style type)
3175 {
3176         int not_null;
3177
3178         debug_printf_parse("done_pipe entered, followup %d\n", type);
3179         /* Close previous command */
3180         not_null = done_command(ctx);
3181         ctx->pipe->followup = type;
3182 #if HAS_KEYWORDS
3183         ctx->pipe->pi_inverted = ctx->ctx_inverted;
3184         ctx->ctx_inverted = 0;
3185         ctx->pipe->res_word = ctx->ctx_res_w;
3186 #endif
3187
3188         /* Without this check, even just <enter> on command line generates
3189          * tree of three NOPs (!). Which is harmless but annoying.
3190          * IOW: it is safe to do it unconditionally. */
3191         if (not_null
3192 #if ENABLE_HUSH_IF
3193          || ctx->ctx_res_w == RES_FI
3194 #endif
3195 #if ENABLE_HUSH_LOOPS
3196          || ctx->ctx_res_w == RES_DONE
3197          || ctx->ctx_res_w == RES_FOR
3198          || ctx->ctx_res_w == RES_IN
3199 #endif
3200 #if ENABLE_HUSH_CASE
3201          || ctx->ctx_res_w == RES_ESAC
3202 #endif
3203         ) {
3204                 struct pipe *new_p;
3205                 debug_printf_parse("done_pipe: adding new pipe: "
3206                                 "not_null:%d ctx->ctx_res_w:%d\n",
3207                                 not_null, ctx->ctx_res_w);
3208                 new_p = new_pipe();
3209                 ctx->pipe->next = new_p;
3210                 ctx->pipe = new_p;
3211                 /* RES_THEN, RES_DO etc are "sticky" -
3212                  * they remain set for pipes inside if/while.
3213                  * This is used to control execution.
3214                  * RES_FOR and RES_IN are NOT sticky (needed to support
3215                  * cases where variable or value happens to match a keyword):
3216                  */
3217 #if ENABLE_HUSH_LOOPS
3218                 if (ctx->ctx_res_w == RES_FOR
3219                  || ctx->ctx_res_w == RES_IN)
3220                         ctx->ctx_res_w = RES_NONE;
3221 #endif
3222 #if ENABLE_HUSH_CASE
3223                 if (ctx->ctx_res_w == RES_MATCH)
3224                         ctx->ctx_res_w = RES_CASE_BODY;
3225                 if (ctx->ctx_res_w == RES_CASE)
3226                         ctx->ctx_res_w = RES_CASE_IN;
3227 #endif
3228                 ctx->command = NULL; /* trick done_command below */
3229                 /* Create the memory for command, roughly:
3230                  * ctx->pipe->cmds = new struct command;
3231                  * ctx->command = &ctx->pipe->cmds[0];
3232                  */
3233                 done_command(ctx);
3234                 //debug_print_tree(ctx->list_head, 10);
3235         }
3236         debug_printf_parse("done_pipe return\n");
3237 }
3238
3239 static void initialize_context(struct parse_context *ctx)
3240 {
3241         memset(ctx, 0, sizeof(*ctx));
3242         ctx->pipe = ctx->list_head = new_pipe();
3243         /* Create the memory for command, roughly:
3244          * ctx->pipe->cmds = new struct command;
3245          * ctx->command = &ctx->pipe->cmds[0];
3246          */
3247         done_command(ctx);
3248 }
3249
3250 /* If a reserved word is found and processed, parse context is modified
3251  * and 1 is returned.
3252  */
3253 #if HAS_KEYWORDS
3254 struct reserved_combo {
3255         char literal[6];
3256         unsigned char res;
3257         unsigned char assignment_flag;
3258         int flag;
3259 };
3260 enum {
3261         FLAG_END   = (1 << RES_NONE ),
3262 # if ENABLE_HUSH_IF
3263         FLAG_IF    = (1 << RES_IF   ),
3264         FLAG_THEN  = (1 << RES_THEN ),
3265         FLAG_ELIF  = (1 << RES_ELIF ),
3266         FLAG_ELSE  = (1 << RES_ELSE ),
3267         FLAG_FI    = (1 << RES_FI   ),
3268 # endif
3269 # if ENABLE_HUSH_LOOPS
3270         FLAG_FOR   = (1 << RES_FOR  ),
3271         FLAG_WHILE = (1 << RES_WHILE),
3272         FLAG_UNTIL = (1 << RES_UNTIL),
3273         FLAG_DO    = (1 << RES_DO   ),
3274         FLAG_DONE  = (1 << RES_DONE ),
3275         FLAG_IN    = (1 << RES_IN   ),
3276 # endif
3277 # if ENABLE_HUSH_CASE
3278         FLAG_MATCH = (1 << RES_MATCH),
3279         FLAG_ESAC  = (1 << RES_ESAC ),
3280 # endif
3281         FLAG_START = (1 << RES_XXXX ),
3282 };
3283
3284 static const struct reserved_combo* match_reserved_word(o_string *word)
3285 {
3286         /* Mostly a list of accepted follow-up reserved words.
3287          * FLAG_END means we are done with the sequence, and are ready
3288          * to turn the compound list into a command.
3289          * FLAG_START means the word must start a new compound list.
3290          */
3291         static const struct reserved_combo reserved_list[] = {
3292 # if ENABLE_HUSH_IF
3293                 { "!",     RES_NONE,  NOT_ASSIGNMENT  , 0 },
3294                 { "if",    RES_IF,    MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3295                 { "then",  RES_THEN,  MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3296                 { "elif",  RES_ELIF,  MAYBE_ASSIGNMENT, FLAG_THEN },
3297                 { "else",  RES_ELSE,  MAYBE_ASSIGNMENT, FLAG_FI   },
3298                 { "fi",    RES_FI,    NOT_ASSIGNMENT  , FLAG_END  },
3299 # endif
3300 # if ENABLE_HUSH_LOOPS
3301                 { "for",   RES_FOR,   NOT_ASSIGNMENT  , FLAG_IN | FLAG_DO | FLAG_START },
3302                 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3303                 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3304                 { "in",    RES_IN,    NOT_ASSIGNMENT  , FLAG_DO   },
3305                 { "do",    RES_DO,    MAYBE_ASSIGNMENT, FLAG_DONE },
3306                 { "done",  RES_DONE,  NOT_ASSIGNMENT  , FLAG_END  },
3307 # endif
3308 # if ENABLE_HUSH_CASE
3309                 { "case",  RES_CASE,  NOT_ASSIGNMENT  , FLAG_MATCH | FLAG_START },
3310                 { "esac",  RES_ESAC,  NOT_ASSIGNMENT  , FLAG_END  },
3311 # endif
3312         };
3313         const struct reserved_combo *r;
3314
3315         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3316                 if (strcmp(word->data, r->literal) == 0)
3317                         return r;
3318         }
3319         return NULL;
3320 }
3321 /* Return 0: not a keyword, 1: keyword
3322  */
3323 static int reserved_word(o_string *word, struct parse_context *ctx)
3324 {
3325 # if ENABLE_HUSH_CASE
3326         static const struct reserved_combo reserved_match = {
3327                 "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3328         };
3329 # endif
3330         const struct reserved_combo *r;
3331
3332         if (word->has_quoted_part)
3333                 return 0;
3334         r = match_reserved_word(word);
3335         if (!r)
3336                 return 0;
3337
3338         debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3339 # if ENABLE_HUSH_CASE
3340         if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3341                 /* "case word IN ..." - IN part starts first MATCH part */
3342                 r = &reserved_match;
3343         } else
3344 # endif
3345         if (r->flag == 0) { /* '!' */
3346                 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3347                         syntax_error("! ! command");
3348                         ctx->ctx_res_w = RES_SNTX;
3349                 }
3350                 ctx->ctx_inverted = 1;
3351                 return 1;
3352         }
3353         if (r->flag & FLAG_START) {
3354                 struct parse_context *old;
3355
3356                 old = xmalloc(sizeof(*old));
3357                 debug_printf_parse("push stack %p\n", old);
3358                 *old = *ctx;   /* physical copy */
3359                 initialize_context(ctx);
3360                 ctx->stack = old;
3361         } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3362                 syntax_error_at(word->data);
3363                 ctx->ctx_res_w = RES_SNTX;
3364                 return 1;
3365         } else {
3366                 /* "{...} fi" is ok. "{...} if" is not
3367                  * Example:
3368                  * if { echo foo; } then { echo bar; } fi */
3369                 if (ctx->command->group)
3370                         done_pipe(ctx, PIPE_SEQ);
3371         }
3372
3373         ctx->ctx_res_w = r->res;
3374         ctx->old_flag = r->flag;
3375         word->o_assignment = r->assignment_flag;
3376         debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3377
3378         if (ctx->old_flag & FLAG_END) {
3379                 struct parse_context *old;
3380
3381                 done_pipe(ctx, PIPE_SEQ);
3382                 debug_printf_parse("pop stack %p\n", ctx->stack);
3383                 old = ctx->stack;
3384                 old->command->group = ctx->list_head;
3385                 old->command->cmd_type = CMD_NORMAL;
3386 # if !BB_MMU
3387                 /* At this point, the compound command's string is in
3388                  * ctx->as_string... except for the leading keyword!
3389                  * Consider this example: "echo a | if true; then echo a; fi"
3390                  * ctx->as_string will contain "true; then echo a; fi",
3391                  * with "if " remaining in old->as_string!
3392                  */
3393                 {
3394                         char *str;
3395                         int len = old->as_string.length;
3396                         /* Concatenate halves */
3397                         o_addstr(&old->as_string, ctx->as_string.data);
3398                         o_free_unsafe(&ctx->as_string);
3399                         /* Find where leading keyword starts in first half */
3400                         str = old->as_string.data + len;
3401                         if (str > old->as_string.data)
3402                                 str--; /* skip whitespace after keyword */
3403                         while (str > old->as_string.data && isalpha(str[-1]))
3404                                 str--;
3405                         /* Ugh, we're done with this horrid hack */
3406                         old->command->group_as_string = xstrdup(str);
3407                         debug_printf_parse("pop, remembering as:'%s'\n",
3408                                         old->command->group_as_string);
3409                 }
3410 # endif
3411                 *ctx = *old;   /* physical copy */
3412                 free(old);
3413         }
3414         return 1;
3415 }
3416 #endif /* HAS_KEYWORDS */
3417
3418 /* Word is complete, look at it and update parsing context.
3419  * Normal return is 0. Syntax errors return 1.
3420  * Note: on return, word is reset, but not o_free'd!
3421  */
3422 static int done_word(o_string *word, struct parse_context *ctx)
3423 {
3424         struct command *command = ctx->command;
3425
3426         debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3427         if (word->length == 0 && !word->has_quoted_part) {
3428                 debug_printf_parse("done_word return 0: true null, ignored\n");
3429                 return 0;
3430         }
3431
3432         if (ctx->pending_redirect) {
3433                 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3434                  * only if run as "bash", not "sh" */
3435                 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3436                  * "2.7 Redirection
3437                  * ...the word that follows the redirection operator
3438                  * shall be subjected to tilde expansion, parameter expansion,
3439                  * command substitution, arithmetic expansion, and quote
3440                  * removal. Pathname expansion shall not be performed
3441                  * on the word by a non-interactive shell; an interactive
3442                  * shell may perform it, but shall do so only when
3443                  * the expansion would result in one word."
3444                  */
3445                 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3446                 /* Cater for >\file case:
3447                  * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3448                  * Same with heredocs:
3449                  * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3450                  */
3451                 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3452                         unbackslash(ctx->pending_redirect->rd_filename);
3453                         /* Is it <<"HEREDOC"? */
3454                         if (word->has_quoted_part) {
3455                                 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3456                         }
3457                 }
3458                 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3459                 ctx->pending_redirect = NULL;
3460         } else {
3461 #if HAS_KEYWORDS
3462 # if ENABLE_HUSH_CASE
3463                 if (ctx->ctx_dsemicolon
3464                  && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3465                 ) {
3466                         /* already done when ctx_dsemicolon was set to 1: */
3467                         /* ctx->ctx_res_w = RES_MATCH; */
3468                         ctx->ctx_dsemicolon = 0;
3469                 } else
3470 # endif
3471                 if (!command->argv /* if it's the first word... */
3472 # if ENABLE_HUSH_LOOPS
3473                  && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3474                  && ctx->ctx_res_w != RES_IN
3475 # endif
3476 # if ENABLE_HUSH_CASE
3477                  && ctx->ctx_res_w != RES_CASE
3478 # endif
3479                 ) {
3480                         int reserved = reserved_word(word, ctx);
3481                         debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3482                         if (reserved) {
3483                                 o_reset_to_empty_unquoted(word);
3484                                 debug_printf_parse("done_word return %d\n",
3485                                                 (ctx->ctx_res_w == RES_SNTX));
3486                                 return (ctx->ctx_res_w == RES_SNTX);
3487                         }
3488 # if ENABLE_HUSH_BASH_COMPAT
3489                         if (strcmp(word->data, "[[") == 0) {
3490                                 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3491                         }
3492                         /* fall through */
3493 # endif
3494                 }
3495 #endif
3496                 if (command->group) {
3497                         /* "{ echo foo; } echo bar" - bad */
3498                         syntax_error_at(word->data);
3499                         debug_printf_parse("done_word return 1: syntax error, "
3500                                         "groups and arglists don't mix\n");
3501                         return 1;
3502                 }
3503
3504                 /* If this word wasn't an assignment, next ones definitely
3505                  * can't be assignments. Even if they look like ones. */
3506                 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3507                  && word->o_assignment != WORD_IS_KEYWORD
3508                 ) {
3509                         word->o_assignment = NOT_ASSIGNMENT;
3510                 } else {
3511                         if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3512                                 command->assignment_cnt++;
3513                                 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3514                         }
3515                         debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3516                         word->o_assignment = MAYBE_ASSIGNMENT;
3517                 }
3518                 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3519
3520                 if (word->has_quoted_part
3521                  /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3522                  && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3523                  /* (otherwise it's known to be not empty and is already safe) */
3524                 ) {
3525                         /* exclude "$@" - it can expand to no word despite "" */
3526                         char *p = word->data;
3527                         while (p[0] == SPECIAL_VAR_SYMBOL
3528                             && (p[1] & 0x7f) == '@'
3529                             && p[2] == SPECIAL_VAR_SYMBOL
3530                         ) {
3531                                 p += 3;
3532                         }
3533                 }
3534                 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3535                 debug_print_strings("word appended to argv", command->argv);
3536         }
3537
3538 #if ENABLE_HUSH_LOOPS
3539         if (ctx->ctx_res_w == RES_FOR) {
3540                 if (word->has_quoted_part
3541                  || !is_well_formed_var_name(command->argv[0], '\0')
3542                 ) {
3543                         /* bash says just "not a valid identifier" */
3544                         syntax_error("not a valid identifier in for");
3545                         return 1;
3546                 }
3547                 /* Force FOR to have just one word (variable name) */
3548                 /* NB: basically, this makes hush see "for v in ..."
3549                  * syntax as if it is "for v; in ...". FOR and IN become
3550                  * two pipe structs in parse tree. */
3551                 done_pipe(ctx, PIPE_SEQ);
3552         }
3553 #endif
3554 #if ENABLE_HUSH_CASE
3555         /* Force CASE to have just one word */
3556         if (ctx->ctx_res_w == RES_CASE) {
3557                 done_pipe(ctx, PIPE_SEQ);
3558         }
3559 #endif
3560
3561         o_reset_to_empty_unquoted(word);
3562
3563         debug_printf_parse("done_word return 0\n");
3564         return 0;
3565 }
3566
3567
3568 /* Peek ahead in the input to find out if we have a "&n" construct,
3569  * as in "2>&1", that represents duplicating a file descriptor.
3570  * Return:
3571  * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3572  * REDIRFD_SYNTAX_ERR if syntax error,
3573  * REDIRFD_TO_FILE if no & was seen,
3574  * or the number found.
3575  */
3576 #if BB_MMU
3577 #define parse_redir_right_fd(as_string, input) \
3578         parse_redir_right_fd(input)
3579 #endif
3580 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3581 {
3582         int ch, d, ok;
3583
3584         ch = i_peek(input);
3585         if (ch != '&')
3586                 return REDIRFD_TO_FILE;
3587
3588         ch = i_getch(input);  /* get the & */
3589         nommu_addchr(as_string, ch);
3590         ch = i_peek(input);
3591         if (ch == '-') {
3592                 ch = i_getch(input);
3593                 nommu_addchr(as_string, ch);
3594                 return REDIRFD_CLOSE;
3595         }
3596         d = 0;
3597         ok = 0;
3598         while (ch != EOF && isdigit(ch)) {
3599                 d = d*10 + (ch-'0');
3600                 ok = 1;
3601                 ch = i_getch(input);
3602                 nommu_addchr(as_string, ch);
3603                 ch = i_peek(input);
3604         }
3605         if (ok) return d;
3606
3607 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3608
3609         bb_error_msg("ambiguous redirect");
3610         return REDIRFD_SYNTAX_ERR;
3611 }
3612
3613 /* Return code is 0 normal, 1 if a syntax error is detected
3614  */
3615 static int parse_redirect(struct parse_context *ctx,
3616                 int fd,
3617                 redir_type style,
3618                 struct in_str *input)
3619 {
3620         struct command *command = ctx->command;
3621         struct redir_struct *redir;
3622         struct redir_struct **redirp;
3623         int dup_num;
3624
3625         dup_num = REDIRFD_TO_FILE;
3626         if (style != REDIRECT_HEREDOC) {
3627                 /* Check for a '>&1' type redirect */
3628                 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3629                 if (dup_num == REDIRFD_SYNTAX_ERR)
3630                         return 1;
3631         } else {
3632                 int ch = i_peek(input);
3633                 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3634                 if (dup_num) { /* <<-... */
3635                         ch = i_getch(input);
3636                         nommu_addchr(&ctx->as_string, ch);
3637                         ch = i_peek(input);
3638                 }
3639         }
3640
3641         if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3642                 int ch = i_peek(input);
3643                 if (ch == '|') {
3644                         /* >|FILE redirect ("clobbering" >).
3645                          * Since we do not support "set -o noclobber" yet,
3646                          * >| and > are the same for now. Just eat |.
3647                          */
3648                         ch = i_getch(input);
3649                         nommu_addchr(&ctx->as_string, ch);
3650                 }
3651         }
3652
3653         /* Create a new redir_struct and append it to the linked list */
3654         redirp = &command->redirects;
3655         while ((redir = *redirp) != NULL) {
3656                 redirp = &(redir->next);
3657         }
3658         *redirp = redir = xzalloc(sizeof(*redir));
3659         /* redir->next = NULL; */
3660         /* redir->rd_filename = NULL; */
3661         redir->rd_type = style;
3662         redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3663
3664         debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3665                                 redir_table[style].descrip);
3666
3667         redir->rd_dup = dup_num;
3668         if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3669                 /* Erik had a check here that the file descriptor in question
3670                  * is legit; I postpone that to "run time"
3671                  * A "-" representation of "close me" shows up as a -3 here */
3672                 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3673                                 redir->rd_fd, redir->rd_dup);
3674         } else {
3675 #if 0           /* Instead we emit error message at run time */
3676                 if (ctx->pending_redirect) {
3677                         /* For example, "cmd > <file" */
3678                         die_if_script("syntax error: %s", "invalid redirect");
3679                 }
3680 #endif
3681                 /* Set ctx->pending_redirect, so we know what to do at the
3682                  * end of the next parsed word. */
3683                 ctx->pending_redirect = redir;
3684         }
3685         return 0;
3686 }
3687
3688 /* If a redirect is immediately preceded by a number, that number is
3689  * supposed to tell which file descriptor to redirect.  This routine
3690  * looks for such preceding numbers.  In an ideal world this routine
3691  * needs to handle all the following classes of redirects...
3692  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
3693  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
3694  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
3695  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
3696  *
3697  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3698  * "2.7 Redirection
3699  * ... If n is quoted, the number shall not be recognized as part of
3700  * the redirection expression. For example:
3701  * echo \2>a
3702  * writes the character 2 into file a"
3703  * We are getting it right by setting ->has_quoted_part on any \<char>
3704  *
3705  * A -1 return means no valid number was found,
3706  * the caller should use the appropriate default for this redirection.
3707  */
3708 static int redirect_opt_num(o_string *o)
3709 {
3710         int num;
3711
3712         if (o->data == NULL)
3713                 return -1;
3714         num = bb_strtou(o->data, NULL, 10);
3715         if (errno || num < 0)
3716                 return -1;
3717         o_reset_to_empty_unquoted(o);
3718         return num;
3719 }
3720
3721 #if BB_MMU
3722 #define fetch_till_str(as_string, input, word, skip_tabs) \
3723         fetch_till_str(input, word, skip_tabs)
3724 #endif
3725 static char *fetch_till_str(o_string *as_string,
3726                 struct in_str *input,
3727                 const char *word,
3728                 int heredoc_flags)
3729 {
3730         o_string heredoc = NULL_O_STRING;
3731         unsigned past_EOL;
3732         int prev = 0; /* not \ */
3733         int ch;
3734
3735         goto jump_in;
3736
3737         while (1) {
3738                 ch = i_getch(input);
3739                 if (ch != EOF)
3740                         nommu_addchr(as_string, ch);
3741                 if ((ch == '\n' || ch == EOF)
3742                  && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3743                 ) {
3744                         if (strcmp(heredoc.data + past_EOL, word) == 0) {
3745                                 heredoc.data[past_EOL] = '\0';
3746                                 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3747                                 return heredoc.data;
3748                         }
3749                         while (ch == '\n') {
3750                                 o_addchr(&heredoc, ch);
3751                                 prev = ch;
3752  jump_in:
3753                                 past_EOL = heredoc.length;
3754                                 do {
3755                                         ch = i_getch(input);
3756                                         if (ch != EOF)
3757                                                 nommu_addchr(as_string, ch);
3758                                 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3759                         }
3760                 }
3761                 if (ch == EOF) {
3762                         o_free_unsafe(&heredoc);
3763                         return NULL;
3764                 }
3765                 o_addchr(&heredoc, ch);
3766                 nommu_addchr(as_string, ch);
3767                 if (prev == '\\' && ch == '\\')
3768                         /* Correctly handle foo\\<eol> (not a line cont.) */
3769                         prev = 0; /* not \ */
3770                 else
3771                         prev = ch;
3772         }
3773 }
3774
3775 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3776  * and load them all. There should be exactly heredoc_cnt of them.
3777  */
3778 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3779 {
3780         struct pipe *pi = ctx->list_head;
3781
3782         while (pi && heredoc_cnt) {
3783                 int i;
3784                 struct command *cmd = pi->cmds;
3785
3786                 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3787                                 pi->num_cmds,
3788                                 cmd->argv ? cmd->argv[0] : "NONE");
3789                 for (i = 0; i < pi->num_cmds; i++) {
3790                         struct redir_struct *redir = cmd->redirects;
3791
3792                         debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3793                                         i, cmd->argv ? cmd->argv[0] : "NONE");
3794                         while (redir) {
3795                                 if (redir->rd_type == REDIRECT_HEREDOC) {
3796                                         char *p;
3797
3798                                         redir->rd_type = REDIRECT_HEREDOC2;
3799                                         /* redir->rd_dup is (ab)used to indicate <<- */
3800                                         p = fetch_till_str(&ctx->as_string, input,
3801                                                         redir->rd_filename, redir->rd_dup);
3802                                         if (!p) {
3803                                                 syntax_error("unexpected EOF in here document");
3804                                                 return 1;
3805                                         }
3806                                         free(redir->rd_filename);
3807                                         redir->rd_filename = p;
3808                                         heredoc_cnt--;
3809                                 }
3810                                 redir = redir->next;
3811                         }
3812                         cmd++;
3813                 }
3814                 pi = pi->next;
3815         }
3816 #if 0
3817         /* Should be 0. If it isn't, it's a parse error */
3818         if (heredoc_cnt)
3819                 bb_error_msg_and_die("heredoc BUG 2");
3820 #endif
3821         return 0;
3822 }
3823
3824
3825 static int run_list(struct pipe *pi);
3826 #if BB_MMU
3827 #define parse_stream(pstring, input, end_trigger) \
3828         parse_stream(input, end_trigger)
3829 #endif
3830 static struct pipe *parse_stream(char **pstring,
3831                 struct in_str *input,
3832                 int end_trigger);
3833
3834
3835 #if !ENABLE_HUSH_FUNCTIONS
3836 #define parse_group(dest, ctx, input, ch) \
3837         parse_group(ctx, input, ch)
3838 #endif
3839 static int parse_group(o_string *dest, struct parse_context *ctx,
3840         struct in_str *input, int ch)
3841 {
3842         /* dest contains characters seen prior to ( or {.
3843          * Typically it's empty, but for function defs,
3844          * it contains function name (without '()'). */
3845         struct pipe *pipe_list;
3846         int endch;
3847         struct command *command = ctx->command;
3848
3849         debug_printf_parse("parse_group entered\n");
3850 #if ENABLE_HUSH_FUNCTIONS
3851         if (ch == '(' && !dest->has_quoted_part) {
3852                 if (dest->length)
3853                         if (done_word(dest, ctx))
3854                                 return 1;
3855                 if (!command->argv)
3856                         goto skip; /* (... */
3857                 if (command->argv[1]) { /* word word ... (... */
3858                         syntax_error_unexpected_ch('(');
3859                         return 1;
3860                 }
3861                 /* it is "word(..." or "word (..." */
3862                 do
3863                         ch = i_getch(input);
3864                 while (ch == ' ' || ch == '\t');
3865                 if (ch != ')') {
3866                         syntax_error_unexpected_ch(ch);
3867                         return 1;
3868                 }
3869                 nommu_addchr(&ctx->as_string, ch);
3870                 do
3871                         ch = i_getch(input);
3872                 while (ch == ' ' || ch == '\t' || ch == '\n');
3873                 if (ch != '{') {
3874                         syntax_error_unexpected_ch(ch);
3875                         return 1;
3876                 }
3877                 nommu_addchr(&ctx->as_string, ch);
3878                 command->cmd_type = CMD_FUNCDEF;
3879                 goto skip;
3880         }
3881 #endif
3882
3883 #if 0 /* Prevented by caller */
3884         if (command->argv /* word [word]{... */
3885          || dest->length /* word{... */
3886          || dest->has_quoted_part /* ""{... */
3887         ) {
3888                 syntax_error(NULL);
3889                 debug_printf_parse("parse_group return 1: "
3890                         "syntax error, groups and arglists don't mix\n");
3891                 return 1;
3892         }
3893 #endif
3894
3895 #if ENABLE_HUSH_FUNCTIONS
3896  skip:
3897 #endif
3898         endch = '}';
3899         if (ch == '(') {
3900                 endch = ')';
3901                 command->cmd_type = CMD_SUBSHELL;
3902         } else {
3903                 /* bash does not allow "{echo...", requires whitespace */
3904                 ch = i_getch(input);
3905                 if (ch != ' ' && ch != '\t' && ch != '\n') {
3906                         syntax_error_unexpected_ch(ch);
3907                         return 1;
3908                 }
3909                 nommu_addchr(&ctx->as_string, ch);
3910         }
3911
3912         {
3913 #if BB_MMU
3914 # define as_string NULL
3915 #else
3916                 char *as_string = NULL;
3917 #endif
3918                 pipe_list = parse_stream(&as_string, input, endch);
3919 #if !BB_MMU
3920                 if (as_string)
3921                         o_addstr(&ctx->as_string, as_string);
3922 #endif
3923                 /* empty ()/{} or parse error? */
3924                 if (!pipe_list || pipe_list == ERR_PTR) {
3925                         /* parse_stream already emitted error msg */
3926                         if (!BB_MMU)
3927                                 free(as_string);
3928                         debug_printf_parse("parse_group return 1: "
3929                                 "parse_stream returned %p\n", pipe_list);
3930                         return 1;
3931                 }
3932                 command->group = pipe_list;
3933 #if !BB_MMU
3934                 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3935                 command->group_as_string = as_string;
3936                 debug_printf_parse("end of group, remembering as:'%s'\n",
3937                                 command->group_as_string);
3938 #endif
3939 #undef as_string
3940         }
3941         debug_printf_parse("parse_group return 0\n");
3942         return 0;
3943         /* command remains "open", available for possible redirects */
3944 }
3945
3946 static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3947 {
3948         for (;;) {
3949                 int ch, ch2;
3950
3951                 ch = i_getch(input);
3952                 if (ch != '\\')
3953                         return ch;
3954                 ch2 = i_peek(input);
3955                 if (ch2 != '\n')
3956                         return ch;
3957                 /* backslash+newline, skip it */
3958                 i_getch(input);
3959         }
3960 }
3961
3962 static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3963 {
3964         for (;;) {
3965                 int ch, ch2;
3966
3967                 ch = i_peek(input);
3968                 if (ch != '\\')
3969                         return ch;
3970                 ch2 = i_peek2(input);
3971                 if (ch2 != '\n')
3972                         return ch;
3973                 /* backslash+newline, skip it */
3974                 i_getch(input);
3975                 i_getch(input);
3976         }
3977 }
3978
3979 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3980 /* Subroutines for copying $(...) and `...` things */
3981 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3982 /* '...' */
3983 static int add_till_single_quote(o_string *dest, struct in_str *input)
3984 {
3985         while (1) {
3986                 int ch = i_getch(input);
3987                 if (ch == EOF) {
3988                         syntax_error_unterm_ch('\'');
3989                         return 0;
3990                 }
3991                 if (ch == '\'')
3992                         return 1;
3993                 o_addchr(dest, ch);
3994         }
3995 }
3996 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3997 static int add_till_double_quote(o_string *dest, struct in_str *input)
3998 {
3999         while (1) {
4000                 int ch = i_getch(input);
4001                 if (ch == EOF) {
4002                         syntax_error_unterm_ch('"');
4003                         return 0;
4004                 }
4005                 if (ch == '"')
4006                         return 1;
4007                 if (ch == '\\') {  /* \x. Copy both chars. */
4008                         o_addchr(dest, ch);
4009                         ch = i_getch(input);
4010                 }
4011                 o_addchr(dest, ch);
4012                 if (ch == '`') {
4013                         if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4014                                 return 0;
4015                         o_addchr(dest, ch);
4016                         continue;
4017                 }
4018                 //if (ch == '$') ...
4019         }
4020 }
4021 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4022  * \` quoting.
4023  * "Within the backquoted style of command substitution, backslash
4024  * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4025  * The search for the matching backquote shall be satisfied by the first
4026  * backquote found without a preceding backslash; during this search,
4027  * if a non-escaped backquote is encountered within a shell comment,
4028  * a here-document, an embedded command substitution of the $(command)
4029  * form, or a quoted string, undefined results occur. A single-quoted
4030  * or double-quoted string that begins, but does not end, within the
4031  * "`...`" sequence produces undefined results."
4032  * Example                               Output
4033  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
4034  */
4035 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
4036 {
4037         while (1) {
4038                 int ch = i_getch(input);
4039                 if (ch == '`')
4040                         return 1;
4041                 if (ch == '\\') {
4042                         /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4043                         ch = i_getch(input);
4044                         if (ch != '`'
4045                          && ch != '$'
4046                          && ch != '\\'
4047                          && (!in_dquote || ch != '"')
4048                         ) {
4049                                 o_addchr(dest, '\\');
4050                         }
4051                 }
4052                 if (ch == EOF) {
4053                         syntax_error_unterm_ch('`');
4054                         return 0;
4055                 }
4056                 o_addchr(dest, ch);
4057         }
4058 }
4059 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4060  * quoting and nested ()s.
4061  * "With the $(command) style of command substitution, all characters
4062  * following the open parenthesis to the matching closing parenthesis
4063  * constitute the command. Any valid shell script can be used for command,
4064  * except a script consisting solely of redirections which produces
4065  * unspecified results."
4066  * Example                              Output
4067  * echo $(echo '(TEST)' BEST)           (TEST) BEST
4068  * echo $(echo 'TEST)' BEST)            TEST) BEST
4069  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
4070  *
4071  * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
4072  * can contain arbitrary constructs, just like $(cmd).
4073  * In bash compat mode, it needs to also be able to stop on ':' or '/'
4074  * for ${var:N[:M]} and ${var/P[/R]} parsing.
4075  */
4076 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
4077 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
4078 {
4079         int ch;
4080         char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
4081 # if ENABLE_HUSH_BASH_COMPAT
4082         char end_char2 = end_ch >> 8;
4083 # endif
4084         end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4085
4086         while (1) {
4087                 ch = i_getch(input);
4088                 if (ch == EOF) {
4089                         syntax_error_unterm_ch(end_ch);
4090                         return 0;
4091                 }
4092                 if (ch == end_ch  IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
4093                         if (!dbl)
4094                                 break;
4095                         /* we look for closing )) of $((EXPR)) */
4096                         if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
4097                                 i_getch(input); /* eat second ')' */
4098                                 break;
4099                         }
4100                 }
4101                 o_addchr(dest, ch);
4102                 if (ch == '(' || ch == '{') {
4103                         ch = (ch == '(' ? ')' : '}');
4104                         if (!add_till_closing_bracket(dest, input, ch))
4105                                 return 0;
4106                         o_addchr(dest, ch);
4107                         continue;
4108                 }
4109                 if (ch == '\'') {
4110                         if (!add_till_single_quote(dest, input))
4111                                 return 0;
4112                         o_addchr(dest, ch);
4113                         continue;
4114                 }
4115                 if (ch == '"') {
4116                         if (!add_till_double_quote(dest, input))
4117                                 return 0;
4118                         o_addchr(dest, ch);
4119                         continue;
4120                 }
4121                 if (ch == '`') {
4122                         if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4123                                 return 0;
4124                         o_addchr(dest, ch);
4125                         continue;
4126                 }
4127                 if (ch == '\\') {
4128                         /* \x. Copy verbatim. Important for  \(, \) */
4129                         ch = i_getch(input);
4130                         if (ch == EOF) {
4131                                 syntax_error_unterm_ch(')');
4132                                 return 0;
4133                         }
4134 #if 0
4135                         if (ch == '\n') {
4136                                 /* "backslash+newline", ignore both */
4137                                 o_delchr(dest); /* undo insertion of '\' */
4138                                 continue;
4139                         }
4140 #endif
4141                         o_addchr(dest, ch);
4142                         continue;
4143                 }
4144         }
4145         return ch;
4146 }
4147 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
4148
4149 /* Return code: 0 for OK, 1 for syntax error */
4150 #if BB_MMU
4151 #define parse_dollar(as_string, dest, input, quote_mask) \
4152         parse_dollar(dest, input, quote_mask)
4153 #define as_string NULL
4154 #endif
4155 static int parse_dollar(o_string *as_string,
4156                 o_string *dest,
4157                 struct in_str *input, unsigned char quote_mask)
4158 {
4159         int ch = i_peek_and_eat_bkslash_nl(input);  /* first character after the $ */
4160
4161         debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
4162         if (isalpha(ch)) {
4163                 ch = i_getch(input);
4164                 nommu_addchr(as_string, ch);
4165  make_var:
4166                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4167                 while (1) {
4168                         debug_printf_parse(": '%c'\n", ch);
4169                         o_addchr(dest, ch | quote_mask);
4170                         quote_mask = 0;
4171                         ch = i_peek_and_eat_bkslash_nl(input);
4172                         if (!isalnum(ch) && ch != '_') {
4173                                 /* End of variable name reached */
4174                                 break;
4175                         }
4176                         ch = i_getch(input);
4177                         nommu_addchr(as_string, ch);
4178                 }
4179                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4180         } else if (isdigit(ch)) {
4181  make_one_char_var:
4182                 ch = i_getch(input);
4183                 nommu_addchr(as_string, ch);
4184                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4185                 debug_printf_parse(": '%c'\n", ch);
4186                 o_addchr(dest, ch | quote_mask);
4187                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4188         } else switch (ch) {
4189         case '$': /* pid */
4190         case '!': /* last bg pid */
4191         case '?': /* last exit code */
4192         case '#': /* number of args */
4193         case '*': /* args */
4194         case '@': /* args */
4195                 goto make_one_char_var;
4196         case '{': {
4197                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4198
4199                 ch = i_getch(input); /* eat '{' */
4200                 nommu_addchr(as_string, ch);
4201
4202                 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
4203                 /* It should be ${?}, or ${#var},
4204                  * or even ${?+subst} - operator acting on a special variable,
4205                  * or the beginning of variable name.
4206                  */
4207                 if (ch == EOF
4208                  || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4209                 ) {
4210  bad_dollar_syntax:
4211                         syntax_error_unterm_str("${name}");
4212                         debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4213                         return 0;
4214                 }
4215                 nommu_addchr(as_string, ch);
4216                 ch |= quote_mask;
4217
4218                 /* It's possible to just call add_till_closing_bracket() at this point.
4219                  * However, this regresses some of our testsuite cases
4220                  * which check invalid constructs like ${%}.
4221                  * Oh well... let's check that the var name part is fine... */
4222
4223                 while (1) {
4224                         unsigned pos;
4225
4226                         o_addchr(dest, ch);
4227                         debug_printf_parse(": '%c'\n", ch);
4228
4229                         ch = i_getch(input);
4230                         nommu_addchr(as_string, ch);
4231                         if (ch == '}')
4232                                 break;
4233
4234                         if (!isalnum(ch) && ch != '_') {
4235                                 unsigned end_ch;
4236                                 unsigned char last_ch;
4237                                 /* handle parameter expansions
4238                                  * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4239                                  */
4240                                 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
4241                                         goto bad_dollar_syntax;
4242
4243                                 /* Eat everything until closing '}' (or ':') */
4244                                 end_ch = '}';
4245                                 if (ENABLE_HUSH_BASH_COMPAT
4246                                  && ch == ':'
4247                                  && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
4248                                 ) {
4249                                         /* It's ${var:N[:M]} thing */
4250                                         end_ch = '}' * 0x100 + ':';
4251                                 }
4252                                 if (ENABLE_HUSH_BASH_COMPAT
4253                                  && ch == '/'
4254                                 ) {
4255                                         /* It's ${var/[/]pattern[/repl]} thing */
4256                                         if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4257                                                 i_getch(input);
4258                                                 nommu_addchr(as_string, '/');
4259                                                 ch = '\\';
4260                                         }
4261                                         end_ch = '}' * 0x100 + '/';
4262                                 }
4263                                 o_addchr(dest, ch);
4264  again:
4265                                 if (!BB_MMU)
4266                                         pos = dest->length;
4267 #if ENABLE_HUSH_DOLLAR_OPS
4268                                 last_ch = add_till_closing_bracket(dest, input, end_ch);
4269                                 if (last_ch == 0) /* error? */
4270                                         return 0;
4271 #else
4272 #error Simple code to only allow ${var} is not implemented
4273 #endif
4274                                 if (as_string) {
4275                                         o_addstr(as_string, dest->data + pos);
4276                                         o_addchr(as_string, last_ch);
4277                                 }
4278
4279                                 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4280                                         /* close the first block: */
4281                                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4282                                         /* while parsing N from ${var:N[:M]}
4283                                          * or pattern from ${var/[/]pattern[/repl]} */
4284                                         if ((end_ch & 0xff) == last_ch) {
4285                                                 /* got ':' or '/'- parse the rest */
4286                                                 end_ch = '}';
4287                                                 goto again;
4288                                         }
4289                                         /* got '}' */
4290                                         if (end_ch == '}' * 0x100 + ':') {
4291                                                 /* it's ${var:N} - emulate :999999999 */
4292                                                 o_addstr(dest, "999999999");
4293                                         } /* else: it's ${var/[/]pattern} */
4294                                 }
4295                                 break;
4296                         }
4297                 }
4298                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4299                 break;
4300         }
4301 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
4302         case '(': {
4303                 unsigned pos;
4304
4305                 ch = i_getch(input);
4306                 nommu_addchr(as_string, ch);
4307 # if ENABLE_SH_MATH_SUPPORT
4308                 if (i_peek_and_eat_bkslash_nl(input) == '(') {
4309                         ch = i_getch(input);
4310                         nommu_addchr(as_string, ch);
4311                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4312                         o_addchr(dest, /*quote_mask |*/ '+');
4313                         if (!BB_MMU)
4314                                 pos = dest->length;
4315                         if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4316                                 return 0; /* error */
4317                         if (as_string) {
4318                                 o_addstr(as_string, dest->data + pos);
4319                                 o_addchr(as_string, ')');
4320                                 o_addchr(as_string, ')');
4321                         }
4322                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4323                         break;
4324                 }
4325 # endif
4326 # if ENABLE_HUSH_TICK
4327                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4328                 o_addchr(dest, quote_mask | '`');
4329                 if (!BB_MMU)
4330                         pos = dest->length;
4331                 if (!add_till_closing_bracket(dest, input, ')'))
4332                         return 0; /* error */
4333                 if (as_string) {
4334                         o_addstr(as_string, dest->data + pos);
4335                         o_addchr(as_string, ')');
4336                 }
4337                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4338 # endif
4339                 break;
4340         }
4341 #endif
4342         case '_':
4343                 ch = i_getch(input);
4344                 nommu_addchr(as_string, ch);
4345                 ch = i_peek_and_eat_bkslash_nl(input);
4346                 if (isalnum(ch)) { /* it's $_name or $_123 */
4347                         ch = '_';
4348                         goto make_var;
4349                 }
4350                 /* else: it's $_ */
4351         /* TODO: $_ and $-: */
4352         /* $_ Shell or shell script name; or last argument of last command
4353          * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4354          * but in command's env, set to full pathname used to invoke it */
4355         /* $- Option flags set by set builtin or shell options (-i etc) */
4356         default:
4357                 o_addQchr(dest, '$');
4358         }
4359         debug_printf_parse("parse_dollar return 1 (ok)\n");
4360         return 1;
4361 #undef as_string
4362 }
4363
4364 #if BB_MMU
4365 # if ENABLE_HUSH_BASH_COMPAT
4366 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4367         encode_string(dest, input, dquote_end, process_bkslash)
4368 # else
4369 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4370 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4371         encode_string(dest, input, dquote_end)
4372 # endif
4373 #define as_string NULL
4374
4375 #else /* !MMU */
4376
4377 # if ENABLE_HUSH_BASH_COMPAT
4378 /* all parameters are needed, no macro tricks */
4379 # else
4380 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4381         encode_string(as_string, dest, input, dquote_end)
4382 # endif
4383 #endif
4384 static int encode_string(o_string *as_string,
4385                 o_string *dest,
4386                 struct in_str *input,
4387                 int dquote_end,
4388                 int process_bkslash)
4389 {
4390 #if !ENABLE_HUSH_BASH_COMPAT
4391         const int process_bkslash = 1;
4392 #endif
4393         int ch;
4394         int next;
4395
4396  again:
4397         ch = i_getch(input);
4398         if (ch != EOF)
4399                 nommu_addchr(as_string, ch);
4400         if (ch == dquote_end) { /* may be only '"' or EOF */
4401                 debug_printf_parse("encode_string return 1 (ok)\n");
4402                 return 1;
4403         }
4404         /* note: can't move it above ch == dquote_end check! */
4405         if (ch == EOF) {
4406                 syntax_error_unterm_ch('"');
4407                 return 0; /* error */
4408         }
4409         next = '\0';
4410         if (ch != '\n') {
4411                 next = i_peek(input);
4412         }
4413         debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4414                         ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4415         if (process_bkslash && ch == '\\') {
4416                 if (next == EOF) {
4417                         syntax_error("\\<eof>");
4418                         xfunc_die();
4419                 }
4420                 /* bash:
4421                  * "The backslash retains its special meaning [in "..."]
4422                  * only when followed by one of the following characters:
4423                  * $, `, ", \, or <newline>.  A double quote may be quoted
4424                  * within double quotes by preceding it with a backslash."
4425                  * NB: in (unquoted) heredoc, above does not apply to ",
4426                  * therefore we check for it by "next == dquote_end" cond.
4427                  */
4428                 if (next == dquote_end || strchr("$`\\\n", next)) {
4429                         ch = i_getch(input); /* eat next */
4430                         if (ch == '\n')
4431                                 goto again; /* skip \<newline> */
4432                 } /* else: ch remains == '\\', and we double it below: */
4433                 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4434                 nommu_addchr(as_string, ch);
4435                 goto again;
4436         }
4437         if (ch == '$') {
4438                 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4439                         debug_printf_parse("encode_string return 0: "
4440                                         "parse_dollar returned 0 (error)\n");
4441                         return 0;
4442                 }
4443                 goto again;
4444         }
4445 #if ENABLE_HUSH_TICK
4446         if (ch == '`') {
4447                 //unsigned pos = dest->length;
4448                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4449                 o_addchr(dest, 0x80 | '`');
4450                 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4451                         return 0; /* error */
4452                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4453                 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4454                 goto again;
4455         }
4456 #endif
4457         o_addQchr(dest, ch);
4458         goto again;
4459 #undef as_string
4460 }
4461
4462 /*
4463  * Scan input until EOF or end_trigger char.
4464  * Return a list of pipes to execute, or NULL on EOF
4465  * or if end_trigger character is met.
4466  * On syntax error, exit if shell is not interactive,
4467  * reset parsing machinery and start parsing anew,
4468  * or return ERR_PTR.
4469  */
4470 static struct pipe *parse_stream(char **pstring,
4471                 struct in_str *input,
4472                 int end_trigger)
4473 {
4474         struct parse_context ctx;
4475         o_string dest = NULL_O_STRING;
4476         int heredoc_cnt;
4477
4478         /* Single-quote triggers a bypass of the main loop until its mate is
4479          * found.  When recursing, quote state is passed in via dest->o_expflags.
4480          */
4481         debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4482                         end_trigger ? end_trigger : 'X');
4483         debug_enter();
4484
4485         /* If very first arg is "" or '', dest.data may end up NULL.
4486          * Preventing this: */
4487         o_addchr(&dest, '\0');
4488         dest.length = 0;
4489
4490         /* We used to separate words on $IFS here. This was wrong.
4491          * $IFS is used only for word splitting when $var is expanded,
4492          * here we should use blank chars as separators, not $IFS
4493          */
4494
4495         if (MAYBE_ASSIGNMENT != 0)
4496                 dest.o_assignment = MAYBE_ASSIGNMENT;
4497         initialize_context(&ctx);
4498         heredoc_cnt = 0;
4499         while (1) {
4500                 const char *is_blank;
4501                 const char *is_special;
4502                 int ch;
4503                 int next;
4504                 int redir_fd;
4505                 redir_type redir_style;
4506
4507                 ch = i_getch(input);
4508                 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4509                                 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4510                 if (ch == EOF) {
4511                         struct pipe *pi;
4512
4513                         if (heredoc_cnt) {
4514                                 syntax_error_unterm_str("here document");
4515                                 goto parse_error;
4516                         }
4517                         /* end_trigger == '}' case errors out earlier,
4518                          * checking only ')' */
4519                         if (end_trigger == ')') {
4520                                 syntax_error_unterm_ch('(');
4521                                 goto parse_error;
4522                         }
4523
4524                         if (done_word(&dest, &ctx)) {
4525                                 goto parse_error;
4526                         }
4527                         o_free(&dest);
4528                         done_pipe(&ctx, PIPE_SEQ);
4529                         pi = ctx.list_head;
4530                         /* If we got nothing... */
4531                         /* (this makes bare "&" cmd a no-op.
4532                          * bash says: "syntax error near unexpected token '&'") */
4533                         if (pi->num_cmds == 0
4534                         IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4535                         ) {
4536                                 free_pipe_list(pi);
4537                                 pi = NULL;
4538                         }
4539 #if !BB_MMU
4540                         debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
4541                         if (pstring)
4542                                 *pstring = ctx.as_string.data;
4543                         else
4544                                 o_free_unsafe(&ctx.as_string);
4545 #endif
4546                         debug_leave();
4547                         debug_printf_parse("parse_stream return %p\n", pi);
4548                         return pi;
4549                 }
4550                 nommu_addchr(&ctx.as_string, ch);
4551
4552                 next = '\0';
4553                 if (ch != '\n')
4554                         next = i_peek(input);
4555
4556                 is_special = "{}<>;&|()#'" /* special outside of "str" */
4557                                 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4558                 /* Are { and } special here? */
4559                 if (ctx.command->argv /* word [word]{... - non-special */
4560                  || dest.length       /* word{... - non-special */
4561                  || dest.has_quoted_part     /* ""{... - non-special */
4562                  || (next != ';'             /* }; - special */
4563                     && next != ')'           /* }) - special */
4564                     && next != '&'           /* }& and }&& ... - special */
4565                     && next != '|'           /* }|| ... - special */
4566                     && !strchr(defifs, next) /* {word - non-special */
4567                     )
4568                 ) {
4569                         /* They are not special, skip "{}" */
4570                         is_special += 2;
4571                 }
4572                 is_special = strchr(is_special, ch);
4573                 is_blank = strchr(defifs, ch);
4574
4575                 if (!is_special && !is_blank) { /* ordinary char */
4576  ordinary_char:
4577                         o_addQchr(&dest, ch);
4578                         if ((dest.o_assignment == MAYBE_ASSIGNMENT
4579                             || dest.o_assignment == WORD_IS_KEYWORD)
4580                          && ch == '='
4581                          && is_well_formed_var_name(dest.data, '=')
4582                         ) {
4583                                 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4584                                 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4585                         }
4586                         continue;
4587                 }
4588
4589                 if (is_blank) {
4590                         if (done_word(&dest, &ctx)) {
4591                                 goto parse_error;
4592                         }
4593                         if (ch == '\n') {
4594                                 /* Is this a case when newline is simply ignored?
4595                                  * Some examples:
4596                                  * "cmd | <newline> cmd ..."
4597                                  * "case ... in <newline> word) ..."
4598                                  */
4599                                 if (IS_NULL_CMD(ctx.command)
4600                                  && dest.length == 0 && !dest.has_quoted_part
4601                                 ) {
4602                                         /* This newline can be ignored. But...
4603                                          * Without check #1, interactive shell
4604                                          * ignores even bare <newline>,
4605                                          * and shows the continuation prompt:
4606                                          * ps1_prompt$ <enter>
4607                                          * ps2> _   <=== wrong, should be ps1
4608                                          * Without check #2, "cmd & <newline>"
4609                                          * is similarly mistreated.
4610                                          * (BTW, this makes "cmd & cmd"
4611                                          * and "cmd && cmd" non-orthogonal.
4612                                          * Really, ask yourself, why
4613                                          * "cmd && <newline>" doesn't start
4614                                          * cmd but waits for more input?
4615                                          * No reason...)
4616                                          */
4617                                         struct pipe *pi = ctx.list_head;
4618                                         if (pi->num_cmds != 0       /* check #1 */
4619                                          && pi->followup != PIPE_BG /* check #2 */
4620                                         ) {
4621                                                 continue;
4622                                         }
4623                                 }
4624                                 /* Treat newline as a command separator. */
4625                                 done_pipe(&ctx, PIPE_SEQ);
4626                                 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4627                                 if (heredoc_cnt) {
4628                                         if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4629                                                 goto parse_error;
4630                                         }
4631                                         heredoc_cnt = 0;
4632                                 }
4633                                 dest.o_assignment = MAYBE_ASSIGNMENT;
4634                                 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4635                                 ch = ';';
4636                                 /* note: if (is_blank) continue;
4637                                  * will still trigger for us */
4638                         }
4639                 }
4640
4641                 /* "cmd}" or "cmd }..." without semicolon or &:
4642                  * } is an ordinary char in this case, even inside { cmd; }
4643                  * Pathological example: { ""}; } should exec "}" cmd
4644                  */
4645                 if (ch == '}') {
4646                         if (!IS_NULL_CMD(ctx.command) /* cmd } */
4647                          || dest.length != 0 /* word} */
4648                          || dest.has_quoted_part    /* ""} */
4649                         ) {
4650                                 goto ordinary_char;
4651                         }
4652                         if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4653                                 goto skip_end_trigger;
4654                         /* else: } does terminate a group */
4655                 }
4656
4657                 if (end_trigger && end_trigger == ch
4658                  && (ch != ';' || heredoc_cnt == 0)
4659 #if ENABLE_HUSH_CASE
4660                  && (ch != ')'
4661                     || ctx.ctx_res_w != RES_MATCH
4662                     || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4663                     )
4664 #endif
4665                 ) {
4666                         if (heredoc_cnt) {
4667                                 /* This is technically valid:
4668                                  * { cat <<HERE; }; echo Ok
4669                                  * heredoc
4670                                  * heredoc
4671                                  * HERE
4672                                  * but we don't support this.
4673                                  * We require heredoc to be in enclosing {}/(),
4674                                  * if any.
4675                                  */
4676                                 syntax_error_unterm_str("here document");
4677                                 goto parse_error;
4678                         }
4679                         if (done_word(&dest, &ctx)) {
4680                                 goto parse_error;
4681                         }
4682                         done_pipe(&ctx, PIPE_SEQ);
4683                         dest.o_assignment = MAYBE_ASSIGNMENT;
4684                         debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4685                         /* Do we sit outside of any if's, loops or case's? */
4686                         if (!HAS_KEYWORDS
4687                         IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4688                         ) {
4689                                 o_free(&dest);
4690 #if !BB_MMU
4691                                 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
4692                                 if (pstring)
4693                                         *pstring = ctx.as_string.data;
4694                                 else
4695                                         o_free_unsafe(&ctx.as_string);
4696 #endif
4697                                 debug_leave();
4698                                 debug_printf_parse("parse_stream return %p: "
4699                                                 "end_trigger char found\n",
4700                                                 ctx.list_head);
4701                                 return ctx.list_head;
4702                         }
4703                 }
4704  skip_end_trigger:
4705                 if (is_blank)
4706                         continue;
4707
4708                 /* Catch <, > before deciding whether this word is
4709                  * an assignment. a=1 2>z b=2: b=2 is still assignment */
4710                 switch (ch) {
4711                 case '>':
4712                         redir_fd = redirect_opt_num(&dest);
4713                         if (done_word(&dest, &ctx)) {
4714                                 goto parse_error;
4715                         }
4716                         redir_style = REDIRECT_OVERWRITE;
4717                         if (next == '>') {
4718                                 redir_style = REDIRECT_APPEND;
4719                                 ch = i_getch(input);
4720                                 nommu_addchr(&ctx.as_string, ch);
4721                         }
4722 #if 0
4723                         else if (next == '(') {
4724                                 syntax_error(">(process) not supported");
4725                                 goto parse_error;
4726                         }
4727 #endif
4728                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
4729                                 goto parse_error;
4730                         continue; /* back to top of while (1) */
4731                 case '<':
4732                         redir_fd = redirect_opt_num(&dest);
4733                         if (done_word(&dest, &ctx)) {
4734                                 goto parse_error;
4735                         }
4736                         redir_style = REDIRECT_INPUT;
4737                         if (next == '<') {
4738                                 redir_style = REDIRECT_HEREDOC;
4739                                 heredoc_cnt++;
4740                                 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4741                                 ch = i_getch(input);
4742                                 nommu_addchr(&ctx.as_string, ch);
4743                         } else if (next == '>') {
4744                                 redir_style = REDIRECT_IO;
4745                                 ch = i_getch(input);
4746                                 nommu_addchr(&ctx.as_string, ch);
4747                         }
4748 #if 0
4749                         else if (next == '(') {
4750                                 syntax_error("<(process) not supported");
4751                                 goto parse_error;
4752                         }
4753 #endif
4754                         if (parse_redirect(&ctx, redir_fd, redir_style, input))
4755                                 goto parse_error;
4756                         continue; /* back to top of while (1) */
4757                 case '#':
4758                         if (dest.length == 0 && !dest.has_quoted_part) {
4759                                 /* skip "#comment" */
4760                                 while (1) {
4761                                         ch = i_peek(input);
4762                                         if (ch == EOF || ch == '\n')
4763                                                 break;
4764                                         i_getch(input);
4765                                         /* note: we do not add it to &ctx.as_string */
4766                                 }
4767                                 nommu_addchr(&ctx.as_string, '\n');
4768                                 continue; /* back to top of while (1) */
4769                         }
4770                         break;
4771                 case '\\':
4772                         if (next == '\n') {
4773                                 /* It's "\<newline>" */
4774 #if !BB_MMU
4775                                 /* Remove trailing '\' from ctx.as_string */
4776                                 ctx.as_string.data[--ctx.as_string.length] = '\0';
4777 #endif
4778                                 ch = i_getch(input); /* eat it */
4779                                 continue; /* back to top of while (1) */
4780                         }
4781                         break;
4782                 }
4783
4784                 if (dest.o_assignment == MAYBE_ASSIGNMENT
4785                  /* check that we are not in word in "a=1 2>word b=1": */
4786                  && !ctx.pending_redirect
4787                 ) {
4788                         /* ch is a special char and thus this word
4789                          * cannot be an assignment */
4790                         dest.o_assignment = NOT_ASSIGNMENT;
4791                         debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4792                 }
4793
4794                 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4795
4796                 switch (ch) {
4797                 case '#': /* non-comment #: "echo a#b" etc */
4798                         o_addQchr(&dest, ch);
4799                         break;
4800                 case '\\':
4801                         if (next == EOF) {
4802                                 syntax_error("\\<eof>");
4803                                 xfunc_die();
4804                         }
4805                         ch = i_getch(input);
4806                         /* note: ch != '\n' (that case does not reach this place) */
4807                         o_addchr(&dest, '\\');
4808                         /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4809                         o_addchr(&dest, ch);
4810                         nommu_addchr(&ctx.as_string, ch);
4811                         /* Example: echo Hello \2>file
4812                          * we need to know that word 2 is quoted */
4813                         dest.has_quoted_part = 1;
4814                         break;
4815                 case '$':
4816                         if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4817                                 debug_printf_parse("parse_stream parse error: "
4818                                         "parse_dollar returned 0 (error)\n");
4819                                 goto parse_error;
4820                         }
4821                         break;
4822                 case '\'':
4823                         dest.has_quoted_part = 1;
4824                         if (next == '\'' && !ctx.pending_redirect) {
4825  insert_empty_quoted_str_marker:
4826                                 nommu_addchr(&ctx.as_string, next);
4827                                 i_getch(input); /* eat second ' */
4828                                 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4829                                 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4830                         } else {
4831                                 while (1) {
4832                                         ch = i_getch(input);
4833                                         if (ch == EOF) {
4834                                                 syntax_error_unterm_ch('\'');
4835                                                 goto parse_error;
4836                                         }
4837                                         nommu_addchr(&ctx.as_string, ch);
4838                                         if (ch == '\'')
4839                                                 break;
4840                                         o_addqchr(&dest, ch);
4841                                 }
4842                         }
4843                         break;
4844                 case '"':
4845                         dest.has_quoted_part = 1;
4846                         if (next == '"' && !ctx.pending_redirect)
4847                                 goto insert_empty_quoted_str_marker;
4848                         if (dest.o_assignment == NOT_ASSIGNMENT)
4849                                 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4850                         if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4851                                 goto parse_error;
4852                         dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4853                         break;
4854 #if ENABLE_HUSH_TICK
4855                 case '`': {
4856                         USE_FOR_NOMMU(unsigned pos;)
4857
4858                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4859                         o_addchr(&dest, '`');
4860                         USE_FOR_NOMMU(pos = dest.length;)
4861                         if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4862                                 goto parse_error;
4863 # if !BB_MMU
4864                         o_addstr(&ctx.as_string, dest.data + pos);
4865                         o_addchr(&ctx.as_string, '`');
4866 # endif
4867                         o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4868                         //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4869                         break;
4870                 }
4871 #endif
4872                 case ';':
4873 #if ENABLE_HUSH_CASE
4874  case_semi:
4875 #endif
4876                         if (done_word(&dest, &ctx)) {
4877                                 goto parse_error;
4878                         }
4879                         done_pipe(&ctx, PIPE_SEQ);
4880 #if ENABLE_HUSH_CASE
4881                         /* Eat multiple semicolons, detect
4882                          * whether it means something special */
4883                         while (1) {
4884                                 ch = i_peek(input);
4885                                 if (ch != ';')
4886                                         break;
4887                                 ch = i_getch(input);
4888                                 nommu_addchr(&ctx.as_string, ch);
4889                                 if (ctx.ctx_res_w == RES_CASE_BODY) {
4890                                         ctx.ctx_dsemicolon = 1;
4891                                         ctx.ctx_res_w = RES_MATCH;
4892                                         break;
4893                                 }
4894                         }
4895 #endif
4896  new_cmd:
4897                         /* We just finished a cmd. New one may start
4898                          * with an assignment */
4899                         dest.o_assignment = MAYBE_ASSIGNMENT;
4900                         debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4901                         break;
4902                 case '&':
4903                         if (done_word(&dest, &ctx)) {
4904                                 goto parse_error;
4905                         }
4906                         if (next == '&') {
4907                                 ch = i_getch(input);
4908                                 nommu_addchr(&ctx.as_string, ch);
4909                                 done_pipe(&ctx, PIPE_AND);
4910                         } else {
4911                                 done_pipe(&ctx, PIPE_BG);
4912                         }
4913                         goto new_cmd;
4914                 case '|':
4915                         if (done_word(&dest, &ctx)) {
4916                                 goto parse_error;
4917                         }
4918 #if ENABLE_HUSH_CASE
4919                         if (ctx.ctx_res_w == RES_MATCH)
4920                                 break; /* we are in case's "word | word)" */
4921 #endif
4922                         if (next == '|') { /* || */
4923                                 ch = i_getch(input);
4924                                 nommu_addchr(&ctx.as_string, ch);
4925                                 done_pipe(&ctx, PIPE_OR);
4926                         } else {
4927                                 /* we could pick up a file descriptor choice here
4928                                  * with redirect_opt_num(), but bash doesn't do it.
4929                                  * "echo foo 2| cat" yields "foo 2". */
4930                                 done_command(&ctx);
4931                         }
4932                         goto new_cmd;
4933                 case '(':
4934 #if ENABLE_HUSH_CASE
4935                         /* "case... in [(]word)..." - skip '(' */
4936                         if (ctx.ctx_res_w == RES_MATCH
4937                          && ctx.command->argv == NULL /* not (word|(... */
4938                          && dest.length == 0 /* not word(... */
4939                          && dest.has_quoted_part == 0 /* not ""(... */
4940                         ) {
4941                                 continue;
4942                         }
4943 #endif
4944                 case '{':
4945                         if (parse_group(&dest, &ctx, input, ch) != 0) {
4946                                 goto parse_error;
4947                         }
4948                         goto new_cmd;
4949                 case ')':
4950 #if ENABLE_HUSH_CASE
4951                         if (ctx.ctx_res_w == RES_MATCH)
4952                                 goto case_semi;
4953 #endif
4954                 case '}':
4955                         /* proper use of this character is caught by end_trigger:
4956                          * if we see {, we call parse_group(..., end_trigger='}')
4957                          * and it will match } earlier (not here). */
4958                         syntax_error_unexpected_ch(ch);
4959                         goto parse_error;
4960                 default:
4961                         if (HUSH_DEBUG)
4962                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4963                 }
4964         } /* while (1) */
4965
4966  parse_error:
4967         {
4968                 struct parse_context *pctx;
4969                 IF_HAS_KEYWORDS(struct parse_context *p2;)
4970
4971                 /* Clean up allocated tree.
4972                  * Sample for finding leaks on syntax error recovery path.
4973                  * Run it from interactive shell, watch pmap `pidof hush`.
4974                  * while if false; then false; fi; do break; fi
4975                  * Samples to catch leaks at execution:
4976                  * while if (true | {true;}); then echo ok; fi; do break; done
4977                  * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4978                  */
4979                 pctx = &ctx;
4980                 do {
4981                         /* Update pipe/command counts,
4982                          * otherwise freeing may miss some */
4983                         done_pipe(pctx, PIPE_SEQ);
4984                         debug_printf_clean("freeing list %p from ctx %p\n",
4985                                         pctx->list_head, pctx);
4986                         debug_print_tree(pctx->list_head, 0);
4987                         free_pipe_list(pctx->list_head);
4988                         debug_printf_clean("freed list %p\n", pctx->list_head);
4989 #if !BB_MMU
4990                         o_free_unsafe(&pctx->as_string);
4991 #endif
4992                         IF_HAS_KEYWORDS(p2 = pctx->stack;)
4993                         if (pctx != &ctx) {
4994                                 free(pctx);
4995                         }
4996                         IF_HAS_KEYWORDS(pctx = p2;)
4997                 } while (HAS_KEYWORDS && pctx);
4998
4999                 o_free(&dest);
5000                 G.last_exitcode = 1;
5001 #if !BB_MMU
5002                 if (pstring)
5003                         *pstring = NULL;
5004 #endif
5005                 debug_leave();
5006                 return ERR_PTR;
5007         }
5008 }
5009
5010
5011 /*** Execution routines ***/
5012
5013 /* Expansion can recurse, need forward decls: */
5014 #if !ENABLE_HUSH_BASH_COMPAT
5015 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5016 #define expand_string_to_string(str, do_unbackslash) \
5017         expand_string_to_string(str)
5018 #endif
5019 static char *expand_string_to_string(const char *str, int do_unbackslash);
5020 #if ENABLE_HUSH_TICK
5021 static int process_command_subs(o_string *dest, const char *s);
5022 #endif
5023
5024 /* expand_strvec_to_strvec() takes a list of strings, expands
5025  * all variable references within and returns a pointer to
5026  * a list of expanded strings, possibly with larger number
5027  * of strings. (Think VAR="a b"; echo $VAR).
5028  * This new list is allocated as a single malloc block.
5029  * NULL-terminated list of char* pointers is at the beginning of it,
5030  * followed by strings themselves.
5031  * Caller can deallocate entire list by single free(list). */
5032
5033 /* A horde of its helpers come first: */
5034
5035 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5036 {
5037         while (--len >= 0) {
5038                 char c = *str++;
5039
5040 #if ENABLE_HUSH_BRACE_EXPANSION
5041                 if (c == '{' || c == '}') {
5042                         /* { -> \{, } -> \} */
5043                         o_addchr(o, '\\');
5044                         /* And now we want to add { or } and continue:
5045                          *  o_addchr(o, c);
5046                          *  continue;
5047                          * luckily, just falling throught achieves this.
5048                          */
5049                 }
5050 #endif
5051                 o_addchr(o, c);
5052                 if (c == '\\') {
5053                         /* \z -> \\\z; \<eol> -> \\<eol> */
5054                         o_addchr(o, '\\');
5055                         if (len) {
5056                                 len--;
5057                                 o_addchr(o, '\\');
5058                                 o_addchr(o, *str++);
5059                         }
5060                 }
5061         }
5062 }
5063
5064 /* Store given string, finalizing the word and starting new one whenever
5065  * we encounter IFS char(s). This is used for expanding variable values.
5066  * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5067  * Return in *ended_with_ifs:
5068  * 1 - ended with IFS char, else 0 (this includes case of empty str).
5069  */
5070 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
5071 {
5072         int last_is_ifs = 0;
5073
5074         while (1) {
5075                 int word_len;
5076
5077                 if (!*str)  /* EOL - do not finalize word */
5078                         break;
5079                 word_len = strcspn(str, G.ifs);
5080                 if (word_len) {
5081                         /* We have WORD_LEN leading non-IFS chars */
5082                         if (!(output->o_expflags & EXP_FLAG_GLOB)) {
5083                                 o_addblock(output, str, word_len);
5084                         } else {
5085                                 /* Protect backslashes against globbing up :)
5086                                  * Example: "v='\*'; echo b$v" prints "b\*"
5087                                  * (and does not try to glob on "*")
5088                                  */
5089                                 o_addblock_duplicate_backslash(output, str, word_len);
5090                                 /*/ Why can't we do it easier? */
5091                                 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5092                                 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5093                         }
5094                         last_is_ifs = 0;
5095                         str += word_len;
5096                         if (!*str)  /* EOL - do not finalize word */
5097                                 break;
5098                 }
5099
5100                 /* We know str here points to at least one IFS char */
5101                 last_is_ifs = 1;
5102                 str += strspn(str, G.ifs); /* skip IFS chars */
5103                 if (!*str)  /* EOL - do not finalize word */
5104                         break;
5105
5106                 /* Start new word... but not always! */
5107                 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
5108                 if (output->has_quoted_part
5109                 /* Case "v=' a'; echo $v":
5110                  * here nothing precedes the space in $v expansion,
5111                  * therefore we should not finish the word
5112                  * (IOW: if there *is* word to finalize, only then do it):
5113                  */
5114                  || (n > 0 && output->data[output->length - 1])
5115                 ) {
5116                         o_addchr(output, '\0');
5117                         debug_print_list("expand_on_ifs", output, n);
5118                         n = o_save_ptr(output, n);
5119                 }
5120         }
5121
5122         if (ended_with_ifs)
5123                 *ended_with_ifs = last_is_ifs;
5124         debug_print_list("expand_on_ifs[1]", output, n);
5125         return n;
5126 }
5127
5128 /* Helper to expand $((...)) and heredoc body. These act as if
5129  * they are in double quotes, with the exception that they are not :).
5130  * Just the rules are similar: "expand only $var and `cmd`"
5131  *
5132  * Returns malloced string.
5133  * As an optimization, we return NULL if expansion is not needed.
5134  */
5135 #if !ENABLE_HUSH_BASH_COMPAT
5136 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
5137 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5138         encode_then_expand_string(str)
5139 #endif
5140 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
5141 {
5142         char *exp_str;
5143         struct in_str input;
5144         o_string dest = NULL_O_STRING;
5145
5146         if (!strchr(str, '$')
5147          && !strchr(str, '\\')
5148 #if ENABLE_HUSH_TICK
5149          && !strchr(str, '`')
5150 #endif
5151         ) {
5152                 return NULL;
5153         }
5154
5155         /* We need to expand. Example:
5156          * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5157          */
5158         setup_string_in_str(&input, str);
5159         encode_string(NULL, &dest, &input, EOF, process_bkslash);
5160 //TODO: error check (encode_string returns 0 on error)?
5161         //bb_error_msg("'%s' -> '%s'", str, dest.data);
5162         exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
5163         //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5164         o_free_unsafe(&dest);
5165         return exp_str;
5166 }
5167
5168 #if ENABLE_SH_MATH_SUPPORT
5169 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
5170 {
5171         arith_state_t math_state;
5172         arith_t res;
5173         char *exp_str;
5174
5175         math_state.lookupvar = get_local_var_value;
5176         math_state.setvar = set_local_var_from_halves;
5177         //math_state.endofname = endofname;
5178         exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5179         res = arith(&math_state, exp_str ? exp_str : arg);
5180         free(exp_str);
5181         if (errmsg_p)
5182                 *errmsg_p = math_state.errmsg;
5183         if (math_state.errmsg)
5184                 die_if_script(math_state.errmsg);
5185         return res;
5186 }
5187 #endif
5188
5189 #if ENABLE_HUSH_BASH_COMPAT
5190 /* ${var/[/]pattern[/repl]} helpers */
5191 static char *strstr_pattern(char *val, const char *pattern, int *size)
5192 {
5193         while (1) {
5194                 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5195                 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5196                 if (end) {
5197                         *size = end - val;
5198                         return val;
5199                 }
5200                 if (*val == '\0')
5201                         return NULL;
5202                 /* Optimization: if "*pat" did not match the start of "string",
5203                  * we know that "tring", "ring" etc will not match too:
5204                  */
5205                 if (pattern[0] == '*')
5206                         return NULL;
5207                 val++;
5208         }
5209 }
5210 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5211 {
5212         char *result = NULL;
5213         unsigned res_len = 0;
5214         unsigned repl_len = strlen(repl);
5215
5216         while (1) {
5217                 int size;
5218                 char *s = strstr_pattern(val, pattern, &size);
5219                 if (!s)
5220                         break;
5221
5222                 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5223                 memcpy(result + res_len, val, s - val);
5224                 res_len += s - val;
5225                 strcpy(result + res_len, repl);
5226                 res_len += repl_len;
5227                 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5228
5229                 val = s + size;
5230                 if (exp_op == '/')
5231                         break;
5232         }
5233         if (val[0] && result) {
5234                 result = xrealloc(result, res_len + strlen(val) + 1);
5235                 strcpy(result + res_len, val);
5236                 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5237         }
5238         debug_printf_varexp("result:'%s'\n", result);
5239         return result;
5240 }
5241 #endif
5242
5243 /* Helper:
5244  * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5245  */
5246 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
5247 {
5248         const char *val = NULL;
5249         char *to_be_freed = NULL;
5250         char *p = *pp;
5251         char *var;
5252         char first_char;
5253         char exp_op;
5254         char exp_save = exp_save; /* for compiler */
5255         char *exp_saveptr; /* points to expansion operator */
5256         char *exp_word = exp_word; /* for compiler */
5257         char arg0;
5258
5259         *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
5260         var = arg;
5261         exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
5262         arg0 = arg[0];
5263         first_char = arg[0] = arg0 & 0x7f;
5264         exp_op = 0;
5265
5266         if (first_char == '#'      /* ${#... */
5267          && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5268         ) {
5269                 /* It must be length operator: ${#var} */
5270                 var++;
5271                 exp_op = 'L';
5272         } else {
5273                 /* Maybe handle parameter expansion */
5274                 if (exp_saveptr /* if 2nd char is one of expansion operators */
5275                  && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5276                 ) {
5277                         /* ${?:0}, ${#[:]%0} etc */
5278                         exp_saveptr = var + 1;
5279                 } else {
5280                         /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5281                         exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5282                 }
5283                 exp_op = exp_save = *exp_saveptr;
5284                 if (exp_op) {
5285                         exp_word = exp_saveptr + 1;
5286                         if (exp_op == ':') {
5287                                 exp_op = *exp_word++;
5288 //TODO: try ${var:} and ${var:bogus} in non-bash config
5289                                 if (ENABLE_HUSH_BASH_COMPAT
5290                                  && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5291                                 ) {
5292                                         /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5293                                         exp_op = ':';
5294                                         exp_word--;
5295                                 }
5296                         }
5297                         *exp_saveptr = '\0';
5298                 } /* else: it's not an expansion op, but bare ${var} */
5299         }
5300
5301         /* Look up the variable in question */
5302         if (isdigit(var[0])) {
5303                 /* parse_dollar should have vetted var for us */
5304                 int n = xatoi_positive(var);
5305                 if (n < G.global_argc)
5306                         val = G.global_argv[n];
5307                 /* else val remains NULL: $N with too big N */
5308         } else {
5309                 switch (var[0]) {
5310                 case '$': /* pid */
5311                         val = utoa(G.root_pid);
5312                         break;
5313                 case '!': /* bg pid */
5314                         val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5315                         break;
5316                 case '?': /* exitcode */
5317                         val = utoa(G.last_exitcode);
5318                         break;
5319                 case '#': /* argc */
5320                         val = utoa(G.global_argc ? G.global_argc-1 : 0);
5321                         break;
5322                 default:
5323                         val = get_local_var_value(var);
5324                 }
5325         }
5326
5327         /* Handle any expansions */
5328         if (exp_op == 'L') {
5329                 reinit_unicode_for_hush();
5330                 debug_printf_expand("expand: length(%s)=", val);
5331                 val = utoa(val ? unicode_strlen(val) : 0);
5332                 debug_printf_expand("%s\n", val);
5333         } else if (exp_op) {
5334                 if (exp_op == '%' || exp_op == '#') {
5335                         /* Standard-mandated substring removal ops:
5336                          * ${parameter%word} - remove smallest suffix pattern
5337                          * ${parameter%%word} - remove largest suffix pattern
5338                          * ${parameter#word} - remove smallest prefix pattern
5339                          * ${parameter##word} - remove largest prefix pattern
5340                          *
5341                          * Word is expanded to produce a glob pattern.
5342                          * Then var's value is matched to it and matching part removed.
5343                          */
5344                         if (val && val[0]) {
5345                                 char *t;
5346                                 char *exp_exp_word;
5347                                 char *loc;
5348                                 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5349                                 if (exp_op == *exp_word)  /* ## or %% */
5350                                         exp_word++;
5351                                 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5352                                 if (exp_exp_word)
5353                                         exp_word = exp_exp_word;
5354                                 /* HACK ALERT. We depend here on the fact that
5355                                  * G.global_argv and results of utoa and get_local_var_value
5356                                  * are actually in writable memory:
5357                                  * scan_and_match momentarily stores NULs there. */
5358                                 t = (char*)val;
5359                                 loc = scan_and_match(t, exp_word, scan_flags);
5360                                 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5361                                 //              exp_op, t, exp_word, loc);
5362                                 free(exp_exp_word);
5363                                 if (loc) { /* match was found */
5364                                         if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5365                                                 val = loc; /* take right part */
5366                                         else /* %[%] */
5367                                                 val = to_be_freed = xstrndup(val, loc - val); /* left */
5368                                 }
5369                         }
5370                 }
5371 #if ENABLE_HUSH_BASH_COMPAT
5372                 else if (exp_op == '/' || exp_op == '\\') {
5373                         /* It's ${var/[/]pattern[/repl]} thing.
5374                          * Note that in encoded form it has TWO parts:
5375                          * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5376                          * and if // is used, it is encoded as \:
5377                          * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5378                          */
5379                         /* Empty variable always gives nothing: */
5380                         // "v=''; echo ${v/*/w}" prints "", not "w"
5381                         if (val && val[0]) {
5382                                 /* pattern uses non-standard expansion.
5383                                  * repl should be unbackslashed and globbed
5384                                  * by the usual expansion rules:
5385                                  * >az; >bz;
5386                                  * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5387                                  * v='a bz'; echo "${v/a*z/\z}"  prints "\z"
5388                                  * v='a bz'; echo ${v/a*z/a*z}   prints "az"
5389                                  * v='a bz'; echo ${v/a*z/\z}    prints "z"
5390                                  * (note that a*z _pattern_ is never globbed!)
5391                                  */
5392                                 char *pattern, *repl, *t;
5393                                 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5394                                 if (!pattern)
5395                                         pattern = xstrdup(exp_word);
5396                                 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5397                                 *p++ = SPECIAL_VAR_SYMBOL;
5398                                 exp_word = p;
5399                                 p = strchr(p, SPECIAL_VAR_SYMBOL);
5400                                 *p = '\0';
5401                                 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5402                                 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5403                                 /* HACK ALERT. We depend here on the fact that
5404                                  * G.global_argv and results of utoa and get_local_var_value
5405                                  * are actually in writable memory:
5406                                  * replace_pattern momentarily stores NULs there. */
5407                                 t = (char*)val;
5408                                 to_be_freed = replace_pattern(t,
5409                                                 pattern,
5410                                                 (repl ? repl : exp_word),
5411                                                 exp_op);
5412                                 if (to_be_freed) /* at least one replace happened */
5413                                         val = to_be_freed;
5414                                 free(pattern);
5415                                 free(repl);
5416                         }
5417                 }
5418 #endif
5419                 else if (exp_op == ':') {
5420 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5421                         /* It's ${var:N[:M]} bashism.
5422                          * Note that in encoded form it has TWO parts:
5423                          * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5424                          */
5425                         arith_t beg, len;
5426                         const char *errmsg;
5427
5428                         beg = expand_and_evaluate_arith(exp_word, &errmsg);
5429                         if (errmsg)
5430                                 goto arith_err;
5431                         debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5432                         *p++ = SPECIAL_VAR_SYMBOL;
5433                         exp_word = p;
5434                         p = strchr(p, SPECIAL_VAR_SYMBOL);
5435                         *p = '\0';
5436                         len = expand_and_evaluate_arith(exp_word, &errmsg);
5437                         if (errmsg)
5438                                 goto arith_err;
5439                         debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5440                         if (len >= 0) { /* bash compat: len < 0 is illegal */
5441                                 if (beg < 0) /* bash compat */
5442                                         beg = 0;
5443                                 debug_printf_varexp("from val:'%s'\n", val);
5444                                 if (len == 0 || !val || beg >= strlen(val)) {
5445  arith_err:
5446                                         val = NULL;
5447                                 } else {
5448                                         /* Paranoia. What if user entered 9999999999999
5449                                          * which fits in arith_t but not int? */
5450                                         if (len >= INT_MAX)
5451                                                 len = INT_MAX;
5452                                         val = to_be_freed = xstrndup(val + beg, len);
5453                                 }
5454                                 debug_printf_varexp("val:'%s'\n", val);
5455                         } else
5456 #endif
5457                         {
5458                                 die_if_script("malformed ${%s:...}", var);
5459                                 val = NULL;
5460                         }
5461                 } else { /* one of "-=+?" */
5462                         /* Standard-mandated substitution ops:
5463                          * ${var?word} - indicate error if unset
5464                          *      If var is unset, word (or a message indicating it is unset
5465                          *      if word is null) is written to standard error
5466                          *      and the shell exits with a non-zero exit status.
5467                          *      Otherwise, the value of var is substituted.
5468                          * ${var-word} - use default value
5469                          *      If var is unset, word is substituted.
5470                          * ${var=word} - assign and use default value
5471                          *      If var is unset, word is assigned to var.
5472                          *      In all cases, final value of var is substituted.
5473                          * ${var+word} - use alternative value
5474                          *      If var is unset, null is substituted.
5475                          *      Otherwise, word is substituted.
5476                          *
5477                          * Word is subjected to tilde expansion, parameter expansion,
5478                          * command substitution, and arithmetic expansion.
5479                          * If word is not needed, it is not expanded.
5480                          *
5481                          * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5482                          * but also treat null var as if it is unset.
5483                          */
5484                         int use_word = (!val || ((exp_save == ':') && !val[0]));
5485                         if (exp_op == '+')
5486                                 use_word = !use_word;
5487                         debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5488                                         (exp_save == ':') ? "true" : "false", use_word);
5489                         if (use_word) {
5490                                 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5491                                 if (to_be_freed)
5492                                         exp_word = to_be_freed;
5493                                 if (exp_op == '?') {
5494                                         /* mimic bash message */
5495                                         die_if_script("%s: %s",
5496                                                 var,
5497                                                 exp_word[0] ? exp_word : "parameter null or not set"
5498                                         );
5499 //TODO: how interactive bash aborts expansion mid-command?
5500                                 } else {
5501                                         val = exp_word;
5502                                 }
5503
5504                                 if (exp_op == '=') {
5505                                         /* ${var=[word]} or ${var:=[word]} */
5506                                         if (isdigit(var[0]) || var[0] == '#') {
5507                                                 /* mimic bash message */
5508                                                 die_if_script("$%s: cannot assign in this way", var);
5509                                                 val = NULL;
5510                                         } else {
5511                                                 char *new_var = xasprintf("%s=%s", var, val);
5512                                                 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5513                                         }
5514                                 }
5515                         }
5516                 } /* one of "-=+?" */
5517
5518                 *exp_saveptr = exp_save;
5519         } /* if (exp_op) */
5520
5521         arg[0] = arg0;
5522
5523         *pp = p;
5524         *to_be_freed_pp = to_be_freed;
5525         return val;
5526 }
5527
5528 /* Expand all variable references in given string, adding words to list[]
5529  * at n, n+1,... positions. Return updated n (so that list[n] is next one
5530  * to be filled). This routine is extremely tricky: has to deal with
5531  * variables/parameters with whitespace, $* and $@, and constructs like
5532  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5533 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5534 {
5535         /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5536          * expansion of right-hand side of assignment == 1-element expand.
5537          */
5538         char cant_be_null = 0; /* only bit 0x80 matters */
5539         int ended_in_ifs = 0;  /* did last unquoted expansion end with IFS chars? */
5540         char *p;
5541
5542         debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5543                         !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5544         debug_print_list("expand_vars_to_list", output, n);
5545         n = o_save_ptr(output, n);
5546         debug_print_list("expand_vars_to_list[0]", output, n);
5547
5548         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5549                 char first_ch;
5550                 char *to_be_freed = NULL;
5551                 const char *val = NULL;
5552 #if ENABLE_HUSH_TICK
5553                 o_string subst_result = NULL_O_STRING;
5554 #endif
5555 #if ENABLE_SH_MATH_SUPPORT
5556                 char arith_buf[sizeof(arith_t)*3 + 2];
5557 #endif
5558
5559                 if (ended_in_ifs) {
5560                         o_addchr(output, '\0');
5561                         n = o_save_ptr(output, n);
5562                         ended_in_ifs = 0;
5563                 }
5564
5565                 o_addblock(output, arg, p - arg);
5566                 debug_print_list("expand_vars_to_list[1]", output, n);
5567                 arg = ++p;
5568                 p = strchr(p, SPECIAL_VAR_SYMBOL);
5569
5570                 /* Fetch special var name (if it is indeed one of them)
5571                  * and quote bit, force the bit on if singleword expansion -
5572                  * important for not getting v=$@ expand to many words. */
5573                 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5574
5575                 /* Is this variable quoted and thus expansion can't be null?
5576                  * "$@" is special. Even if quoted, it can still
5577                  * expand to nothing (not even an empty string),
5578                  * thus it is excluded. */
5579                 if ((first_ch & 0x7f) != '@')
5580                         cant_be_null |= first_ch;
5581
5582                 switch (first_ch & 0x7f) {
5583                 /* Highest bit in first_ch indicates that var is double-quoted */
5584                 case '*':
5585                 case '@': {
5586                         int i;
5587                         if (!G.global_argv[1])
5588                                 break;
5589                         i = 1;
5590                         cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5591                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5592                                 while (G.global_argv[i]) {
5593                                         n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5594                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5595                                         if (G.global_argv[i++][0] && G.global_argv[i]) {
5596                                                 /* this argv[] is not empty and not last:
5597                                                  * put terminating NUL, start new word */
5598                                                 o_addchr(output, '\0');
5599                                                 debug_print_list("expand_vars_to_list[2]", output, n);
5600                                                 n = o_save_ptr(output, n);
5601                                                 debug_print_list("expand_vars_to_list[3]", output, n);
5602                                         }
5603                                 }
5604                         } else
5605                         /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5606                          * and in this case should treat it like '$*' - see 'else...' below */
5607                         if (first_ch == ('@'|0x80)  /* quoted $@ */
5608                          && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5609                         ) {
5610                                 while (1) {
5611                                         o_addQstr(output, G.global_argv[i]);
5612                                         if (++i >= G.global_argc)
5613                                                 break;
5614                                         o_addchr(output, '\0');
5615                                         debug_print_list("expand_vars_to_list[4]", output, n);
5616                                         n = o_save_ptr(output, n);
5617                                 }
5618                         } else { /* quoted $* (or v="$@" case): add as one word */
5619                                 while (1) {
5620                                         o_addQstr(output, G.global_argv[i]);
5621                                         if (!G.global_argv[++i])
5622                                                 break;
5623                                         if (G.ifs[0])
5624                                                 o_addchr(output, G.ifs[0]);
5625                                 }
5626                                 output->has_quoted_part = 1;
5627                         }
5628                         break;
5629                 }
5630                 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5631                         /* "Empty variable", used to make "" etc to not disappear */
5632                         output->has_quoted_part = 1;
5633                         arg++;
5634                         cant_be_null = 0x80;
5635                         break;
5636 #if ENABLE_HUSH_TICK
5637                 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5638                         *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5639                         arg++;
5640                         /* Can't just stuff it into output o_string,
5641                          * expanded result may need to be globbed
5642                          * and $IFS-splitted */
5643                         debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5644                         G.last_exitcode = process_command_subs(&subst_result, arg);
5645                         debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5646                         val = subst_result.data;
5647                         goto store_val;
5648 #endif
5649 #if ENABLE_SH_MATH_SUPPORT
5650                 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5651                         arith_t res;
5652
5653                         arg++; /* skip '+' */
5654                         *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5655                         debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5656                         res = expand_and_evaluate_arith(arg, NULL);
5657                         debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5658                         sprintf(arith_buf, ARITH_FMT, res);
5659                         val = arith_buf;
5660                         break;
5661                 }
5662 #endif
5663                 default:
5664                         val = expand_one_var(&to_be_freed, arg, &p);
5665  IF_HUSH_TICK(store_val:)
5666                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
5667                                 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5668                                                 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5669                                 if (val && val[0]) {
5670                                         n = expand_on_ifs(&ended_in_ifs, output, n, val);
5671                                         val = NULL;
5672                                 }
5673                         } else { /* quoted $VAR, val will be appended below */
5674                                 output->has_quoted_part = 1;
5675                                 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5676                                                 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5677                         }
5678                         break;
5679                 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5680
5681                 if (val && val[0]) {
5682                         o_addQstr(output, val);
5683                 }
5684                 free(to_be_freed);
5685
5686                 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5687                  * Do the check to avoid writing to a const string. */
5688                 if (*p != SPECIAL_VAR_SYMBOL)
5689                         *p = SPECIAL_VAR_SYMBOL;
5690
5691 #if ENABLE_HUSH_TICK
5692                 o_free(&subst_result);
5693 #endif
5694                 arg = ++p;
5695         } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5696
5697         if (arg[0]) {
5698                 if (ended_in_ifs) {
5699                         o_addchr(output, '\0');
5700                         n = o_save_ptr(output, n);
5701                 }
5702                 debug_print_list("expand_vars_to_list[a]", output, n);
5703                 /* this part is literal, and it was already pre-quoted
5704                  * if needed (much earlier), do not use o_addQstr here! */
5705                 o_addstr_with_NUL(output, arg);
5706                 debug_print_list("expand_vars_to_list[b]", output, n);
5707         } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5708          && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5709         ) {
5710                 n--;
5711                 /* allow to reuse list[n] later without re-growth */
5712                 output->has_empty_slot = 1;
5713         } else {
5714                 o_addchr(output, '\0');
5715         }
5716
5717         return n;
5718 }
5719
5720 static char **expand_variables(char **argv, unsigned expflags)
5721 {
5722         int n;
5723         char **list;
5724         o_string output = NULL_O_STRING;
5725
5726         output.o_expflags = expflags;
5727
5728         n = 0;
5729         while (*argv) {
5730                 n = expand_vars_to_list(&output, n, *argv);
5731                 argv++;
5732         }
5733         debug_print_list("expand_variables", &output, n);
5734
5735         /* output.data (malloced in one block) gets returned in "list" */
5736         list = o_finalize_list(&output, n);
5737         debug_print_strings("expand_variables[1]", list);
5738         return list;
5739 }
5740
5741 static char **expand_strvec_to_strvec(char **argv)
5742 {
5743         return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5744 }
5745
5746 #if ENABLE_HUSH_BASH_COMPAT
5747 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5748 {
5749         return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5750 }
5751 #endif
5752
5753 /* Used for expansion of right hand of assignments,
5754  * $((...)), heredocs, variable espansion parts.
5755  *
5756  * NB: should NOT do globbing!
5757  * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5758  */
5759 static char *expand_string_to_string(const char *str, int do_unbackslash)
5760 {
5761 #if !ENABLE_HUSH_BASH_COMPAT
5762         const int do_unbackslash = 1;
5763 #endif
5764         char *argv[2], **list;
5765
5766         debug_printf_expand("string_to_string<='%s'\n", str);
5767         /* This is generally an optimization, but it also
5768          * handles "", which otherwise trips over !list[0] check below.
5769          * (is this ever happens that we actually get str="" here?)
5770          */
5771         if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5772                 //TODO: Can use on strings with \ too, just unbackslash() them?
5773                 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5774                 return xstrdup(str);
5775         }
5776
5777         argv[0] = (char*)str;
5778         argv[1] = NULL;
5779         list = expand_variables(argv, do_unbackslash
5780                         ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5781                         : EXP_FLAG_SINGLEWORD
5782         );
5783         if (HUSH_DEBUG)
5784                 if (!list[0] || list[1])
5785                         bb_error_msg_and_die("BUG in varexp2");
5786         /* actually, just move string 2*sizeof(char*) bytes back */
5787         overlapping_strcpy((char*)list, list[0]);
5788         if (do_unbackslash)
5789                 unbackslash((char*)list);
5790         debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5791         return (char*)list;
5792 }
5793
5794 /* Used for "eval" builtin */
5795 static char* expand_strvec_to_string(char **argv)
5796 {
5797         char **list;
5798
5799         list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5800         /* Convert all NULs to spaces */
5801         if (list[0]) {
5802                 int n = 1;
5803                 while (list[n]) {
5804                         if (HUSH_DEBUG)
5805                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5806                                         bb_error_msg_and_die("BUG in varexp3");
5807                         /* bash uses ' ' regardless of $IFS contents */
5808                         list[n][-1] = ' ';
5809                         n++;
5810                 }
5811         }
5812         overlapping_strcpy((char*)list, list[0] ? list[0] : "");
5813         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5814         return (char*)list;
5815 }
5816
5817 static char **expand_assignments(char **argv, int count)
5818 {
5819         int i;
5820         char **p;
5821
5822         G.expanded_assignments = p = NULL;
5823         /* Expand assignments into one string each */
5824         for (i = 0; i < count; i++) {
5825                 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5826         }
5827         G.expanded_assignments = NULL;
5828         return p;
5829 }
5830
5831
5832 static void switch_off_special_sigs(unsigned mask)
5833 {
5834         unsigned sig = 0;
5835         while ((mask >>= 1) != 0) {
5836                 sig++;
5837                 if (!(mask & 1))
5838                         continue;
5839                 if (G.traps) {
5840                         if (G.traps[sig] && !G.traps[sig][0])
5841                                 /* trap is '', has to remain SIG_IGN */
5842                                 continue;
5843                         free(G.traps[sig]);
5844                         G.traps[sig] = NULL;
5845                 }
5846                 /* We are here only if no trap or trap was not '' */
5847                 install_sighandler(sig, SIG_DFL);
5848         }
5849 }
5850
5851 #if BB_MMU
5852 /* never called */
5853 void re_execute_shell(char ***to_free, const char *s,
5854                 char *g_argv0, char **g_argv,
5855                 char **builtin_argv) NORETURN;
5856
5857 static void reset_traps_to_defaults(void)
5858 {
5859         /* This function is always called in a child shell
5860          * after fork (not vfork, NOMMU doesn't use this function).
5861          */
5862         unsigned sig;
5863         unsigned mask;
5864
5865         /* Child shells are not interactive.
5866          * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5867          * Testcase: (while :; do :; done) + ^Z should background.
5868          * Same goes for SIGTERM, SIGHUP, SIGINT.
5869          */
5870         mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5871         if (!G.traps && !mask)
5872                 return; /* already no traps and no special sigs */
5873
5874         /* Switch off special sigs */
5875         switch_off_special_sigs(mask);
5876 #if ENABLE_HUSH_JOB
5877         G_fatal_sig_mask = 0;
5878 #endif
5879         G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5880         /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5881          * remain set in G.special_sig_mask */
5882
5883         if (!G.traps)
5884                 return;
5885
5886         /* Reset all sigs to default except ones with empty traps */
5887         for (sig = 0; sig < NSIG; sig++) {
5888                 if (!G.traps[sig])
5889                         continue; /* no trap: nothing to do */
5890                 if (!G.traps[sig][0])
5891                         continue; /* empty trap: has to remain SIG_IGN */
5892                 /* sig has non-empty trap, reset it: */
5893                 free(G.traps[sig]);
5894                 G.traps[sig] = NULL;
5895                 /* There is no signal for trap 0 (EXIT) */
5896                 if (sig == 0)
5897                         continue;
5898                 install_sighandler(sig, pick_sighandler(sig));
5899         }
5900 }
5901
5902 #else /* !BB_MMU */
5903
5904 static void re_execute_shell(char ***to_free, const char *s,
5905                 char *g_argv0, char **g_argv,
5906                 char **builtin_argv) NORETURN;
5907 static void re_execute_shell(char ***to_free, const char *s,
5908                 char *g_argv0, char **g_argv,
5909                 char **builtin_argv)
5910 {
5911 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5912         /* delims + 2 * (number of bytes in printed hex numbers) */
5913         char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5914         char *heredoc_argv[4];
5915         struct variable *cur;
5916 # if ENABLE_HUSH_FUNCTIONS
5917         struct function *funcp;
5918 # endif
5919         char **argv, **pp;
5920         unsigned cnt;
5921         unsigned long long empty_trap_mask;
5922
5923         if (!g_argv0) { /* heredoc */
5924                 argv = heredoc_argv;
5925                 argv[0] = (char *) G.argv0_for_re_execing;
5926                 argv[1] = (char *) "-<";
5927                 argv[2] = (char *) s;
5928                 argv[3] = NULL;
5929                 pp = &argv[3]; /* used as pointer to empty environment */
5930                 goto do_exec;
5931         }
5932
5933         cnt = 0;
5934         pp = builtin_argv;
5935         if (pp) while (*pp++)
5936                 cnt++;
5937
5938         empty_trap_mask = 0;
5939         if (G.traps) {
5940                 int sig;
5941                 for (sig = 1; sig < NSIG; sig++) {
5942                         if (G.traps[sig] && !G.traps[sig][0])
5943                                 empty_trap_mask |= 1LL << sig;
5944                 }
5945         }
5946
5947         sprintf(param_buf, NOMMU_HACK_FMT
5948                         , (unsigned) G.root_pid
5949                         , (unsigned) G.root_ppid
5950                         , (unsigned) G.last_bg_pid
5951                         , (unsigned) G.last_exitcode
5952                         , cnt
5953                         , empty_trap_mask
5954                         IF_HUSH_LOOPS(, G.depth_of_loop)
5955                         );
5956 # undef NOMMU_HACK_FMT
5957         /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5958          * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5959          */
5960         cnt += 6;
5961         for (cur = G.top_var; cur; cur = cur->next) {
5962                 if (!cur->flg_export || cur->flg_read_only)
5963                         cnt += 2;
5964         }
5965 # if ENABLE_HUSH_FUNCTIONS
5966         for (funcp = G.top_func; funcp; funcp = funcp->next)
5967                 cnt += 3;
5968 # endif
5969         pp = g_argv;
5970         while (*pp++)
5971                 cnt++;
5972         *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5973         *pp++ = (char *) G.argv0_for_re_execing;
5974         *pp++ = param_buf;
5975         for (cur = G.top_var; cur; cur = cur->next) {
5976                 if (strcmp(cur->varstr, hush_version_str) == 0)
5977                         continue;
5978                 if (cur->flg_read_only) {
5979                         *pp++ = (char *) "-R";
5980                         *pp++ = cur->varstr;
5981                 } else if (!cur->flg_export) {
5982                         *pp++ = (char *) "-V";
5983                         *pp++ = cur->varstr;
5984                 }
5985         }
5986 # if ENABLE_HUSH_FUNCTIONS
5987         for (funcp = G.top_func; funcp; funcp = funcp->next) {
5988                 *pp++ = (char *) "-F";
5989                 *pp++ = funcp->name;
5990                 *pp++ = funcp->body_as_string;
5991         }
5992 # endif
5993         /* We can pass activated traps here. Say, -Tnn:trap_string
5994          *
5995          * However, POSIX says that subshells reset signals with traps
5996          * to SIG_DFL.
5997          * I tested bash-3.2 and it not only does that with true subshells
5998          * of the form ( list ), but with any forked children shells.
5999          * I set trap "echo W" WINCH; and then tried:
6000          *
6001          * { echo 1; sleep 20; echo 2; } &
6002          * while true; do echo 1; sleep 20; echo 2; break; done &
6003          * true | { echo 1; sleep 20; echo 2; } | cat
6004          *
6005          * In all these cases sending SIGWINCH to the child shell
6006          * did not run the trap. If I add trap "echo V" WINCH;
6007          * _inside_ group (just before echo 1), it works.
6008          *
6009          * I conclude it means we don't need to pass active traps here.
6010          */
6011         *pp++ = (char *) "-c";
6012         *pp++ = (char *) s;
6013         if (builtin_argv) {
6014                 while (*++builtin_argv)
6015                         *pp++ = *builtin_argv;
6016                 *pp++ = (char *) "";
6017         }
6018         *pp++ = g_argv0;
6019         while (*g_argv)
6020                 *pp++ = *g_argv++;
6021         /* *pp = NULL; - is already there */
6022         pp = environ;
6023
6024  do_exec:
6025         debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
6026         /* Don't propagate SIG_IGN to the child */
6027         if (SPECIAL_JOBSTOP_SIGS != 0)
6028                 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6029         execve(bb_busybox_exec_path, argv, pp);
6030         /* Fallback. Useful for init=/bin/hush usage etc */
6031         if (argv[0][0] == '/')
6032                 execve(argv[0], argv, pp);
6033         xfunc_error_retval = 127;
6034         bb_error_msg_and_die("can't re-execute the shell");
6035 }
6036 #endif  /* !BB_MMU */
6037
6038
6039 static int run_and_free_list(struct pipe *pi);
6040
6041 /* Executing from string: eval, sh -c '...'
6042  *          or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6043  * end_trigger controls how often we stop parsing
6044  * NUL: parse all, execute, return
6045  * ';': parse till ';' or newline, execute, repeat till EOF
6046  */
6047 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6048 {
6049         /* Why we need empty flag?
6050          * An obscure corner case "false; ``; echo $?":
6051          * empty command in `` should still set $? to 0.
6052          * But we can't just set $? to 0 at the start,
6053          * this breaks "false; echo `echo $?`" case.
6054          */
6055         bool empty = 1;
6056         while (1) {
6057                 struct pipe *pipe_list;
6058
6059 #if ENABLE_HUSH_INTERACTIVE
6060                 if (end_trigger == ';')
6061                         inp->promptmode = 0; /* PS1 */
6062 #endif
6063                 pipe_list = parse_stream(NULL, inp, end_trigger);
6064                 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6065                         /* If we are in "big" script
6066                          * (not in `cmd` or something similar)...
6067                          */
6068                         if (pipe_list == ERR_PTR && end_trigger == ';') {
6069                                 /* Discard cached input (rest of line) */
6070                                 int ch = inp->last_char;
6071                                 while (ch != EOF && ch != '\n') {
6072                                         //bb_error_msg("Discarded:'%c'", ch);
6073                                         ch = i_getch(inp);
6074                                 }
6075                                 /* Force prompt */
6076                                 inp->p = NULL;
6077                                 /* This stream isn't empty */
6078                                 empty = 0;
6079                                 continue;
6080                         }
6081                         if (!pipe_list && empty)
6082                                 G.last_exitcode = 0;
6083                         break;
6084                 }
6085                 debug_print_tree(pipe_list, 0);
6086                 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6087                 run_and_free_list(pipe_list);
6088                 empty = 0;
6089                 if (G_flag_return_in_progress == 1)
6090                         break;
6091         }
6092 }
6093
6094 static void parse_and_run_string(const char *s)
6095 {
6096         struct in_str input;
6097         setup_string_in_str(&input, s);
6098         parse_and_run_stream(&input, '\0');
6099 }
6100
6101 static void parse_and_run_file(FILE *f)
6102 {
6103         struct in_str input;
6104         setup_file_in_str(&input, f);
6105         parse_and_run_stream(&input, ';');
6106 }
6107
6108 #if ENABLE_HUSH_TICK
6109 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6110 {
6111         pid_t pid;
6112         int channel[2];
6113 # if !BB_MMU
6114         char **to_free = NULL;
6115 # endif
6116
6117         xpipe(channel);
6118         pid = BB_MMU ? xfork() : xvfork();
6119         if (pid == 0) { /* child */
6120                 disable_restore_tty_pgrp_on_exit();
6121                 /* Process substitution is not considered to be usual
6122                  * 'command execution'.
6123                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6124                  */
6125                 bb_signals(0
6126                         + (1 << SIGTSTP)
6127                         + (1 << SIGTTIN)
6128                         + (1 << SIGTTOU)
6129                         , SIG_IGN);
6130                 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6131                 close(channel[0]); /* NB: close _first_, then move fd! */
6132                 xmove_fd(channel[1], 1);
6133                 /* Prevent it from trying to handle ctrl-z etc */
6134                 IF_HUSH_JOB(G.run_list_level = 1;)
6135                 /* Awful hack for `trap` or $(trap).
6136                  *
6137                  * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6138                  * contains an example where "trap" is executed in a subshell:
6139                  *
6140                  * save_traps=$(trap)
6141                  * ...
6142                  * eval "$save_traps"
6143                  *
6144                  * Standard does not say that "trap" in subshell shall print
6145                  * parent shell's traps. It only says that its output
6146                  * must have suitable form, but then, in the above example
6147                  * (which is not supposed to be normative), it implies that.
6148                  *
6149                  * bash (and probably other shell) does implement it
6150                  * (traps are reset to defaults, but "trap" still shows them),
6151                  * but as a result, "trap" logic is hopelessly messed up:
6152                  *
6153                  * # trap
6154                  * trap -- 'echo Ho' SIGWINCH  <--- we have a handler
6155                  * # (trap)        <--- trap is in subshell - no output (correct, traps are reset)
6156                  * # true | trap   <--- trap is in subshell - no output (ditto)
6157                  * # echo `true | trap`    <--- in subshell - output (but traps are reset!)
6158                  * trap -- 'echo Ho' SIGWINCH
6159                  * # echo `(trap)`         <--- in subshell in subshell - output
6160                  * trap -- 'echo Ho' SIGWINCH
6161                  * # echo `true | (trap)`  <--- in subshell in subshell in subshell - output!
6162                  * trap -- 'echo Ho' SIGWINCH
6163                  *
6164                  * The rules when to forget and when to not forget traps
6165                  * get really complex and nonsensical.
6166                  *
6167                  * Our solution: ONLY bare $(trap) or `trap` is special.
6168                  */
6169                 s = skip_whitespace(s);
6170                 if (is_prefixed_with(s, "trap")
6171                  && skip_whitespace(s + 4)[0] == '\0'
6172                 ) {
6173                         static const char *const argv[] = { NULL, NULL };
6174                         builtin_trap((char**)argv);
6175                         fflush_all(); /* important */
6176                         _exit(0);
6177                 }
6178 # if BB_MMU
6179                 reset_traps_to_defaults();
6180                 parse_and_run_string(s);
6181                 _exit(G.last_exitcode);
6182 # else
6183         /* We re-execute after vfork on NOMMU. This makes this script safe:
6184          * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6185          * huge=`cat BIG` # was blocking here forever
6186          * echo OK
6187          */
6188                 re_execute_shell(&to_free,
6189                                 s,
6190                                 G.global_argv[0],
6191                                 G.global_argv + 1,
6192                                 NULL);
6193 # endif
6194         }
6195
6196         /* parent */
6197         *pid_p = pid;
6198 # if ENABLE_HUSH_FAST
6199         G.count_SIGCHLD++;
6200 //bb_error_msg("[%d] fork in generate_stream_from_string:"
6201 //              " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6202 //              getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6203 # endif
6204         enable_restore_tty_pgrp_on_exit();
6205 # if !BB_MMU
6206         free(to_free);
6207 # endif
6208         close(channel[1]);
6209         return remember_FILE(xfdopen_for_read(channel[0]));
6210 }
6211
6212 /* Return code is exit status of the process that is run. */
6213 static int process_command_subs(o_string *dest, const char *s)
6214 {
6215         FILE *fp;
6216         struct in_str pipe_str;
6217         pid_t pid;
6218         int status, ch, eol_cnt;
6219
6220         fp = generate_stream_from_string(s, &pid);
6221
6222         /* Now send results of command back into original context */
6223         setup_file_in_str(&pipe_str, fp);
6224         eol_cnt = 0;
6225         while ((ch = i_getch(&pipe_str)) != EOF) {
6226                 if (ch == '\n') {
6227                         eol_cnt++;
6228                         continue;
6229                 }
6230                 while (eol_cnt) {
6231                         o_addchr(dest, '\n');
6232                         eol_cnt--;
6233                 }
6234                 o_addQchr(dest, ch);
6235         }
6236
6237         debug_printf("done reading from `cmd` pipe, closing it\n");
6238         fclose_and_forget(fp);
6239         /* We need to extract exitcode. Test case
6240          * "true; echo `sleep 1; false` $?"
6241          * should print 1 */
6242         safe_waitpid(pid, &status, 0);
6243         debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6244         return WEXITSTATUS(status);
6245 }
6246 #endif /* ENABLE_HUSH_TICK */
6247
6248
6249 static void setup_heredoc(struct redir_struct *redir)
6250 {
6251         struct fd_pair pair;
6252         pid_t pid;
6253         int len, written;
6254         /* the _body_ of heredoc (misleading field name) */
6255         const char *heredoc = redir->rd_filename;
6256         char *expanded;
6257 #if !BB_MMU
6258         char **to_free;
6259 #endif
6260
6261         expanded = NULL;
6262         if (!(redir->rd_dup & HEREDOC_QUOTED)) {
6263                 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
6264                 if (expanded)
6265                         heredoc = expanded;
6266         }
6267         len = strlen(heredoc);
6268
6269         close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6270         xpiped_pair(pair);
6271         xmove_fd(pair.rd, redir->rd_fd);
6272
6273         /* Try writing without forking. Newer kernels have
6274          * dynamically growing pipes. Must use non-blocking write! */
6275         ndelay_on(pair.wr);
6276         while (1) {
6277                 written = write(pair.wr, heredoc, len);
6278                 if (written <= 0)
6279                         break;
6280                 len -= written;
6281                 if (len == 0) {
6282                         close(pair.wr);
6283                         free(expanded);
6284                         return;
6285                 }
6286                 heredoc += written;
6287         }
6288         ndelay_off(pair.wr);
6289
6290         /* Okay, pipe buffer was not big enough */
6291         /* Note: we must not create a stray child (bastard? :)
6292          * for the unsuspecting parent process. Child creates a grandchild
6293          * and exits before parent execs the process which consumes heredoc
6294          * (that exec happens after we return from this function) */
6295 #if !BB_MMU
6296         to_free = NULL;
6297 #endif
6298         pid = xvfork();
6299         if (pid == 0) {
6300                 /* child */
6301                 disable_restore_tty_pgrp_on_exit();
6302                 pid = BB_MMU ? xfork() : xvfork();
6303                 if (pid != 0)
6304                         _exit(0);
6305                 /* grandchild */
6306                 close(redir->rd_fd); /* read side of the pipe */
6307 #if BB_MMU
6308                 full_write(pair.wr, heredoc, len); /* may loop or block */
6309                 _exit(0);
6310 #else
6311                 /* Delegate blocking writes to another process */
6312                 xmove_fd(pair.wr, STDOUT_FILENO);
6313                 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6314 #endif
6315         }
6316         /* parent */
6317 #if ENABLE_HUSH_FAST
6318         G.count_SIGCHLD++;
6319 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6320 #endif
6321         enable_restore_tty_pgrp_on_exit();
6322 #if !BB_MMU
6323         free(to_free);
6324 #endif
6325         close(pair.wr);
6326         free(expanded);
6327         wait(NULL); /* wait till child has died */
6328 }
6329
6330 /* fd: redirect wants this fd to be used (e.g. 3>file).
6331  * Move all conflicting internally used fds,
6332  * and remember them so that we can restore them later.
6333  */
6334 static int save_fds_on_redirect(int fd, int squirrel[3])
6335 {
6336         if (squirrel) {
6337                 /* Handle redirects of fds 0,1,2 */
6338
6339                 /* If we collide with an already moved stdio fd... */
6340                 if (fd == squirrel[0]) {
6341                         squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6342                         return 1;
6343                 }
6344                 if (fd == squirrel[1]) {
6345                         squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6346                         return 1;
6347                 }
6348                 if (fd == squirrel[2]) {
6349                         squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6350                         return 1;
6351                 }
6352                 /* If we are about to redirect stdio fd, and did not yet move it... */
6353                 if (fd <= 2 && squirrel[fd] < 0) {
6354                         /* We avoid taking stdio fds */
6355                         squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6356                         if (squirrel[fd] < 0 && errno != EBADF)
6357                                 xfunc_die();
6358                         return 0; /* "we did not close fd" */
6359                 }
6360         }
6361
6362 #if ENABLE_HUSH_INTERACTIVE
6363         if (fd != 0 && fd == G.interactive_fd) {
6364                 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6365                 return 1;
6366         }
6367 #endif
6368
6369         /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6370          * (1) Redirect in a forked child. No need to save FILEs' fds,
6371          * we aren't going to use them anymore, ok to trash.
6372          * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6373          * but how are we doing to use them?
6374          * "fileno(fd) = new_fd" can't be done.
6375          */
6376         if (!squirrel)
6377                 return 0;
6378
6379         return save_FILEs_on_redirect(fd);
6380 }
6381
6382 static void restore_redirects(int squirrel[3])
6383 {
6384         int i, fd;
6385         for (i = 0; i <= 2; i++) {
6386                 fd = squirrel[i];
6387                 if (fd != -1) {
6388                         /* We simply die on error */
6389                         xmove_fd(fd, i);
6390                 }
6391         }
6392
6393         /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6394
6395         restore_redirected_FILEs();
6396 }
6397
6398 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6399  * and stderr if they are redirected. */
6400 static int setup_redirects(struct command *prog, int squirrel[])
6401 {
6402         int openfd, mode;
6403         struct redir_struct *redir;
6404
6405         for (redir = prog->redirects; redir; redir = redir->next) {
6406                 if (redir->rd_type == REDIRECT_HEREDOC2) {
6407                         /* "rd_fd<<HERE" case */
6408                         save_fds_on_redirect(redir->rd_fd, squirrel);
6409                         /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6410                          * of the heredoc */
6411                         debug_printf_parse("set heredoc '%s'\n",
6412                                         redir->rd_filename);
6413                         setup_heredoc(redir);
6414                         continue;
6415                 }
6416
6417                 if (redir->rd_dup == REDIRFD_TO_FILE) {
6418                         /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
6419                         char *p;
6420                         if (redir->rd_filename == NULL) {
6421                                 /*
6422                                  * Examples:
6423                                  * "cmd >" (no filename)
6424                                  * "cmd > <file" (2nd redirect starts too early)
6425                                  */
6426                                 die_if_script("syntax error: %s", "invalid redirect");
6427                                 continue;
6428                         }
6429                         mode = redir_table[redir->rd_type].mode;
6430                         p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6431                         openfd = open_or_warn(p, mode);
6432                         free(p);
6433                         if (openfd < 0) {
6434                                 /* Error message from open_or_warn can be lost
6435                                  * if stderr has been redirected, but bash
6436                                  * and ash both lose it as well
6437                                  * (though zsh doesn't!)
6438                                  */
6439                                 return 1;
6440                         }
6441                 } else {
6442                         /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
6443                         openfd = redir->rd_dup;
6444                 }
6445
6446                 if (openfd != redir->rd_fd) {
6447                         int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
6448                         if (openfd == REDIRFD_CLOSE) {
6449                                 /* "rd_fd >&-" means "close me" */
6450                                 if (!closed) {
6451                                         /* ^^^ optimization: saving may already
6452                                          * have closed it. If not... */
6453                                         close(redir->rd_fd);
6454                                 }
6455                         } else {
6456                                 xdup2(openfd, redir->rd_fd);
6457                                 if (redir->rd_dup == REDIRFD_TO_FILE)
6458                                         /* "rd_fd > FILE" */
6459                                         close(openfd);
6460                                 /* else: "rd_fd > rd_dup" */
6461                         }
6462                 }
6463         }
6464         return 0;
6465 }
6466
6467 static char *find_in_path(const char *arg)
6468 {
6469         char *ret = NULL;
6470         const char *PATH = get_local_var_value("PATH");
6471
6472         if (!PATH)
6473                 return NULL;
6474
6475         while (1) {
6476                 const char *end = strchrnul(PATH, ':');
6477                 int sz = end - PATH; /* must be int! */
6478
6479                 free(ret);
6480                 if (sz != 0) {
6481                         ret = xasprintf("%.*s/%s", sz, PATH, arg);
6482                 } else {
6483                         /* We have xxx::yyyy in $PATH,
6484                          * it means "use current dir" */
6485                         ret = xstrdup(arg);
6486                 }
6487                 if (access(ret, F_OK) == 0)
6488                         break;
6489
6490                 if (*end == '\0') {
6491                         free(ret);
6492                         return NULL;
6493                 }
6494                 PATH = end + 1;
6495         }
6496
6497         return ret;
6498 }
6499
6500 static const struct built_in_command *find_builtin_helper(const char *name,
6501                 const struct built_in_command *x,
6502                 const struct built_in_command *end)
6503 {
6504         while (x != end) {
6505                 if (strcmp(name, x->b_cmd) != 0) {
6506                         x++;
6507                         continue;
6508                 }
6509                 debug_printf_exec("found builtin '%s'\n", name);
6510                 return x;
6511         }
6512         return NULL;
6513 }
6514 static const struct built_in_command *find_builtin1(const char *name)
6515 {
6516         return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6517 }
6518 static const struct built_in_command *find_builtin(const char *name)
6519 {
6520         const struct built_in_command *x = find_builtin1(name);
6521         if (x)
6522                 return x;
6523         return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6524 }
6525
6526 #if ENABLE_HUSH_FUNCTIONS
6527 static struct function **find_function_slot(const char *name)
6528 {
6529         struct function **funcpp = &G.top_func;
6530         while (*funcpp) {
6531                 if (strcmp(name, (*funcpp)->name) == 0) {
6532                         break;
6533                 }
6534                 funcpp = &(*funcpp)->next;
6535         }
6536         return funcpp;
6537 }
6538
6539 static const struct function *find_function(const char *name)
6540 {
6541         const struct function *funcp = *find_function_slot(name);
6542         if (funcp)
6543                 debug_printf_exec("found function '%s'\n", name);
6544         return funcp;
6545 }
6546
6547 /* Note: takes ownership on name ptr */
6548 static struct function *new_function(char *name)
6549 {
6550         struct function **funcpp = find_function_slot(name);
6551         struct function *funcp = *funcpp;
6552
6553         if (funcp != NULL) {
6554                 struct command *cmd = funcp->parent_cmd;
6555                 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6556                 if (!cmd) {
6557                         debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6558                         free(funcp->name);
6559                         /* Note: if !funcp->body, do not free body_as_string!
6560                          * This is a special case of "-F name body" function:
6561                          * body_as_string was not malloced! */
6562                         if (funcp->body) {
6563                                 free_pipe_list(funcp->body);
6564 # if !BB_MMU
6565                                 free(funcp->body_as_string);
6566 # endif
6567                         }
6568                 } else {
6569                         debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6570                         cmd->argv[0] = funcp->name;
6571                         cmd->group = funcp->body;
6572 # if !BB_MMU
6573                         cmd->group_as_string = funcp->body_as_string;
6574 # endif
6575                 }
6576         } else {
6577                 debug_printf_exec("remembering new function '%s'\n", name);
6578                 funcp = *funcpp = xzalloc(sizeof(*funcp));
6579                 /*funcp->next = NULL;*/
6580         }
6581
6582         funcp->name = name;
6583         return funcp;
6584 }
6585
6586 static void unset_func(const char *name)
6587 {
6588         struct function **funcpp = find_function_slot(name);
6589         struct function *funcp = *funcpp;
6590
6591         if (funcp != NULL) {
6592                 debug_printf_exec("freeing function '%s'\n", funcp->name);
6593                 *funcpp = funcp->next;
6594                 /* funcp is unlinked now, deleting it.
6595                  * Note: if !funcp->body, the function was created by
6596                  * "-F name body", do not free ->body_as_string
6597                  * and ->name as they were not malloced. */
6598                 if (funcp->body) {
6599                         free_pipe_list(funcp->body);
6600                         free(funcp->name);
6601 # if !BB_MMU
6602                         free(funcp->body_as_string);
6603 # endif
6604                 }
6605                 free(funcp);
6606         }
6607 }
6608
6609 # if BB_MMU
6610 #define exec_function(to_free, funcp, argv) \
6611         exec_function(funcp, argv)
6612 # endif
6613 static void exec_function(char ***to_free,
6614                 const struct function *funcp,
6615                 char **argv) NORETURN;
6616 static void exec_function(char ***to_free,
6617                 const struct function *funcp,
6618                 char **argv)
6619 {
6620 # if BB_MMU
6621         int n = 1;
6622
6623         argv[0] = G.global_argv[0];
6624         G.global_argv = argv;
6625         while (*++argv)
6626                 n++;
6627         G.global_argc = n;
6628         /* On MMU, funcp->body is always non-NULL */
6629         n = run_list(funcp->body);
6630         fflush_all();
6631         _exit(n);
6632 # else
6633         re_execute_shell(to_free,
6634                         funcp->body_as_string,
6635                         G.global_argv[0],
6636                         argv + 1,
6637                         NULL);
6638 # endif
6639 }
6640
6641 static int run_function(const struct function *funcp, char **argv)
6642 {
6643         int rc;
6644         save_arg_t sv;
6645         smallint sv_flg;
6646
6647         save_and_replace_G_args(&sv, argv);
6648
6649         /* "we are in function, ok to use return" */
6650         sv_flg = G_flag_return_in_progress;
6651         G_flag_return_in_progress = -1;
6652 # if ENABLE_HUSH_LOCAL
6653         G.func_nest_level++;
6654 # endif
6655
6656         /* On MMU, funcp->body is always non-NULL */
6657 # if !BB_MMU
6658         if (!funcp->body) {
6659                 /* Function defined by -F */
6660                 parse_and_run_string(funcp->body_as_string);
6661                 rc = G.last_exitcode;
6662         } else
6663 # endif
6664         {
6665                 rc = run_list(funcp->body);
6666         }
6667
6668 # if ENABLE_HUSH_LOCAL
6669         {
6670                 struct variable *var;
6671                 struct variable **var_pp;
6672
6673                 var_pp = &G.top_var;
6674                 while ((var = *var_pp) != NULL) {
6675                         if (var->func_nest_level < G.func_nest_level) {
6676                                 var_pp = &var->next;
6677                                 continue;
6678                         }
6679                         /* Unexport */
6680                         if (var->flg_export)
6681                                 bb_unsetenv(var->varstr);
6682                         /* Remove from global list */
6683                         *var_pp = var->next;
6684                         /* Free */
6685                         if (!var->max_len)
6686                                 free(var->varstr);
6687                         free(var);
6688                 }
6689                 G.func_nest_level--;
6690         }
6691 # endif
6692         G_flag_return_in_progress = sv_flg;
6693
6694         restore_G_args(&sv, argv);
6695
6696         return rc;
6697 }
6698 #endif /* ENABLE_HUSH_FUNCTIONS */
6699
6700
6701 #if BB_MMU
6702 #define exec_builtin(to_free, x, argv) \
6703         exec_builtin(x, argv)
6704 #else
6705 #define exec_builtin(to_free, x, argv) \
6706         exec_builtin(to_free, argv)
6707 #endif
6708 static void exec_builtin(char ***to_free,
6709                 const struct built_in_command *x,
6710                 char **argv) NORETURN;
6711 static void exec_builtin(char ***to_free,
6712                 const struct built_in_command *x,
6713                 char **argv)
6714 {
6715 #if BB_MMU
6716         int rcode;
6717         fflush_all();
6718         rcode = x->b_function(argv);
6719         fflush_all();
6720         _exit(rcode);
6721 #else
6722         fflush_all();
6723         /* On NOMMU, we must never block!
6724          * Example: { sleep 99 | read line; } & echo Ok
6725          */
6726         re_execute_shell(to_free,
6727                         argv[0],
6728                         G.global_argv[0],
6729                         G.global_argv + 1,
6730                         argv);
6731 #endif
6732 }
6733
6734
6735 static void execvp_or_die(char **argv) NORETURN;
6736 static void execvp_or_die(char **argv)
6737 {
6738         debug_printf_exec("execing '%s'\n", argv[0]);
6739         /* Don't propagate SIG_IGN to the child */
6740         if (SPECIAL_JOBSTOP_SIGS != 0)
6741                 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6742         execvp(argv[0], argv);
6743         bb_perror_msg("can't execute '%s'", argv[0]);
6744         _exit(127); /* bash compat */
6745 }
6746
6747 #if ENABLE_HUSH_MODE_X
6748 static void dump_cmd_in_x_mode(char **argv)
6749 {
6750         if (G_x_mode && argv) {
6751                 /* We want to output the line in one write op */
6752                 char *buf, *p;
6753                 int len;
6754                 int n;
6755
6756                 len = 3;
6757                 n = 0;
6758                 while (argv[n])
6759                         len += strlen(argv[n++]) + 1;
6760                 buf = xmalloc(len);
6761                 buf[0] = '+';
6762                 p = buf + 1;
6763                 n = 0;
6764                 while (argv[n])
6765                         p += sprintf(p, " %s", argv[n++]);
6766                 *p++ = '\n';
6767                 *p = '\0';
6768                 fputs(buf, stderr);
6769                 free(buf);
6770         }
6771 }
6772 #else
6773 # define dump_cmd_in_x_mode(argv) ((void)0)
6774 #endif
6775
6776 #if BB_MMU
6777 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6778         pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6779 #define pseudo_exec(nommu_save, command, argv_expanded) \
6780         pseudo_exec(command, argv_expanded)
6781 #endif
6782
6783 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6784  * Never returns.
6785  * Don't exit() here.  If you don't exec, use _exit instead.
6786  * The at_exit handlers apparently confuse the calling process,
6787  * in particular stdin handling. Not sure why? -- because of vfork! (vda)
6788  */
6789 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6790                 char **argv, int assignment_cnt,
6791                 char **argv_expanded) NORETURN;
6792 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6793                 char **argv, int assignment_cnt,
6794                 char **argv_expanded)
6795 {
6796         char **new_env;
6797
6798         new_env = expand_assignments(argv, assignment_cnt);
6799         dump_cmd_in_x_mode(new_env);
6800
6801         if (!argv[assignment_cnt]) {
6802                 /* Case when we are here: ... | var=val | ...
6803                  * (note that we do not exit early, i.e., do not optimize out
6804                  * expand_assignments(): think about ... | var=`sleep 1` | ...
6805                  */
6806                 free_strings(new_env);
6807                 _exit(EXIT_SUCCESS);
6808         }
6809
6810 #if BB_MMU
6811         set_vars_and_save_old(new_env);
6812         free(new_env); /* optional */
6813         /* we can also destroy set_vars_and_save_old's return value,
6814          * to save memory */
6815 #else
6816         nommu_save->new_env = new_env;
6817         nommu_save->old_vars = set_vars_and_save_old(new_env);
6818 #endif
6819
6820         if (argv_expanded) {
6821                 argv = argv_expanded;
6822         } else {
6823                 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6824 #if !BB_MMU
6825                 nommu_save->argv = argv;
6826 #endif
6827         }
6828         dump_cmd_in_x_mode(argv);
6829
6830 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6831         if (strchr(argv[0], '/') != NULL)
6832                 goto skip;
6833 #endif
6834
6835         /* Check if the command matches any of the builtins.
6836          * Depending on context, this might be redundant.  But it's
6837          * easier to waste a few CPU cycles than it is to figure out
6838          * if this is one of those cases.
6839          */
6840         {
6841                 /* On NOMMU, it is more expensive to re-execute shell
6842                  * just in order to run echo or test builtin.
6843                  * It's better to skip it here and run corresponding
6844                  * non-builtin later. */
6845                 const struct built_in_command *x;
6846                 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6847                 if (x) {
6848                         exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6849                 }
6850         }
6851 #if ENABLE_HUSH_FUNCTIONS
6852         /* Check if the command matches any functions */
6853         {
6854                 const struct function *funcp = find_function(argv[0]);
6855                 if (funcp) {
6856                         exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6857                 }
6858         }
6859 #endif
6860
6861 #if ENABLE_FEATURE_SH_STANDALONE
6862         /* Check if the command matches any busybox applets */
6863         {
6864                 int a = find_applet_by_name(argv[0]);
6865                 if (a >= 0) {
6866 # if BB_MMU /* see above why on NOMMU it is not allowed */
6867                         if (APPLET_IS_NOEXEC(a)) {
6868                                 /* Do not leak open fds from opened script files etc */
6869                                 close_all_FILE_list();
6870                                 debug_printf_exec("running applet '%s'\n", argv[0]);
6871                                 run_applet_no_and_exit(a, argv);
6872                         }
6873 # endif
6874                         /* Re-exec ourselves */
6875                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6876                         /* Don't propagate SIG_IGN to the child */
6877                         if (SPECIAL_JOBSTOP_SIGS != 0)
6878                                 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6879                         execv(bb_busybox_exec_path, argv);
6880                         /* If they called chroot or otherwise made the binary no longer
6881                          * executable, fall through */
6882                 }
6883         }
6884 #endif
6885
6886 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6887  skip:
6888 #endif
6889         execvp_or_die(argv);
6890 }
6891
6892 /* Called after [v]fork() in run_pipe
6893  */
6894 static void pseudo_exec(nommu_save_t *nommu_save,
6895                 struct command *command,
6896                 char **argv_expanded) NORETURN;
6897 static void pseudo_exec(nommu_save_t *nommu_save,
6898                 struct command *command,
6899                 char **argv_expanded)
6900 {
6901         if (command->argv) {
6902                 pseudo_exec_argv(nommu_save, command->argv,
6903                                 command->assignment_cnt, argv_expanded);
6904         }
6905
6906         if (command->group) {
6907                 /* Cases when we are here:
6908                  * ( list )
6909                  * { list } &
6910                  * ... | ( list ) | ...
6911                  * ... | { list } | ...
6912                  */
6913 #if BB_MMU
6914                 int rcode;
6915                 debug_printf_exec("pseudo_exec: run_list\n");
6916                 reset_traps_to_defaults();
6917                 rcode = run_list(command->group);
6918                 /* OK to leak memory by not calling free_pipe_list,
6919                  * since this process is about to exit */
6920                 _exit(rcode);
6921 #else
6922                 re_execute_shell(&nommu_save->argv_from_re_execing,
6923                                 command->group_as_string,
6924                                 G.global_argv[0],
6925                                 G.global_argv + 1,
6926                                 NULL);
6927 #endif
6928         }
6929
6930         /* Case when we are here: ... | >file */
6931         debug_printf_exec("pseudo_exec'ed null command\n");
6932         _exit(EXIT_SUCCESS);
6933 }
6934
6935 #if ENABLE_HUSH_JOB
6936 static const char *get_cmdtext(struct pipe *pi)
6937 {
6938         char **argv;
6939         char *p;
6940         int len;
6941
6942         /* This is subtle. ->cmdtext is created only on first backgrounding.
6943          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6944          * On subsequent bg argv is trashed, but we won't use it */
6945         if (pi->cmdtext)
6946                 return pi->cmdtext;
6947         argv = pi->cmds[0].argv;
6948         if (!argv || !argv[0]) {
6949                 pi->cmdtext = xzalloc(1);
6950                 return pi->cmdtext;
6951         }
6952
6953         len = 0;
6954         do {
6955                 len += strlen(*argv) + 1;
6956         } while (*++argv);
6957         p = xmalloc(len);
6958         pi->cmdtext = p;
6959         argv = pi->cmds[0].argv;
6960         do {
6961                 len = strlen(*argv);
6962                 memcpy(p, *argv, len);
6963                 p += len;
6964                 *p++ = ' ';
6965         } while (*++argv);
6966         p[-1] = '\0';
6967         return pi->cmdtext;
6968 }
6969
6970 static void insert_bg_job(struct pipe *pi)
6971 {
6972         struct pipe *job, **jobp;
6973         int i;
6974
6975         /* Linear search for the ID of the job to use */
6976         pi->jobid = 1;
6977         for (job = G.job_list; job; job = job->next)
6978                 if (job->jobid >= pi->jobid)
6979                         pi->jobid = job->jobid + 1;
6980
6981         /* Add job to the list of running jobs */
6982         jobp = &G.job_list;
6983         while ((job = *jobp) != NULL)
6984                 jobp = &job->next;
6985         job = *jobp = xmalloc(sizeof(*job));
6986
6987         *job = *pi; /* physical copy */
6988         job->next = NULL;
6989         job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6990         /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6991         for (i = 0; i < pi->num_cmds; i++) {
6992                 job->cmds[i].pid = pi->cmds[i].pid;
6993                 /* all other fields are not used and stay zero */
6994         }
6995         job->cmdtext = xstrdup(get_cmdtext(pi));
6996
6997         if (G_interactive_fd)
6998                 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6999         G.last_jobid = job->jobid;
7000 }
7001
7002 static void remove_bg_job(struct pipe *pi)
7003 {
7004         struct pipe *prev_pipe;
7005
7006         if (pi == G.job_list) {
7007                 G.job_list = pi->next;
7008         } else {
7009                 prev_pipe = G.job_list;
7010                 while (prev_pipe->next != pi)
7011                         prev_pipe = prev_pipe->next;
7012                 prev_pipe->next = pi->next;
7013         }
7014         if (G.job_list)
7015                 G.last_jobid = G.job_list->jobid;
7016         else
7017                 G.last_jobid = 0;
7018 }
7019
7020 /* Remove a backgrounded job */
7021 static void delete_finished_bg_job(struct pipe *pi)
7022 {
7023         remove_bg_job(pi);
7024         free_pipe(pi);
7025 }
7026 #endif /* JOB */
7027
7028 /* Check to see if any processes have exited -- if they
7029  * have, figure out why and see if a job has completed */
7030 static int checkjobs(struct pipe *fg_pipe)
7031 {
7032         int attributes;
7033         int status;
7034 #if ENABLE_HUSH_JOB
7035         struct pipe *pi;
7036 #endif
7037         pid_t childpid;
7038         int rcode = 0;
7039
7040         debug_printf_jobs("checkjobs %p\n", fg_pipe);
7041
7042         attributes = WUNTRACED;
7043         if (fg_pipe == NULL)
7044                 attributes |= WNOHANG;
7045
7046         errno = 0;
7047 #if ENABLE_HUSH_FAST
7048         if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7049 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7050 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7051                 /* There was neither fork nor SIGCHLD since last waitpid */
7052                 /* Avoid doing waitpid syscall if possible */
7053                 if (!G.we_have_children) {
7054                         errno = ECHILD;
7055                         return -1;
7056                 }
7057                 if (fg_pipe == NULL) { /* is WNOHANG set? */
7058                         /* We have children, but they did not exit
7059                          * or stop yet (we saw no SIGCHLD) */
7060                         return 0;
7061                 }
7062                 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7063         }
7064 #endif
7065
7066 /* Do we do this right?
7067  * bash-3.00# sleep 20 | false
7068  * <ctrl-Z pressed>
7069  * [3]+  Stopped          sleep 20 | false
7070  * bash-3.00# echo $?
7071  * 1   <========== bg pipe is not fully done, but exitcode is already known!
7072  * [hush 1.14.0: yes we do it right]
7073  */
7074  wait_more:
7075         while (1) {
7076                 int i;
7077                 int dead;
7078
7079 #if ENABLE_HUSH_FAST
7080                 i = G.count_SIGCHLD;
7081 #endif
7082                 childpid = waitpid(-1, &status, attributes);
7083                 if (childpid <= 0) {
7084                         if (childpid && errno != ECHILD)
7085                                 bb_perror_msg("waitpid");
7086 #if ENABLE_HUSH_FAST
7087                         else { /* Until next SIGCHLD, waitpid's are useless */
7088                                 G.we_have_children = (childpid == 0);
7089                                 G.handled_SIGCHLD = i;
7090 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7091                         }
7092 #endif
7093                         break;
7094                 }
7095                 dead = WIFEXITED(status) || WIFSIGNALED(status);
7096
7097 #if DEBUG_JOBS
7098                 if (WIFSTOPPED(status))
7099                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7100                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
7101                 if (WIFSIGNALED(status))
7102                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7103                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
7104                 if (WIFEXITED(status))
7105                         debug_printf_jobs("pid %d exited, exitcode %d\n",
7106                                         childpid, WEXITSTATUS(status));
7107 #endif
7108                 /* Were we asked to wait for fg pipe? */
7109                 if (fg_pipe) {
7110                         i = fg_pipe->num_cmds;
7111                         while (--i >= 0) {
7112                                 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7113                                 if (fg_pipe->cmds[i].pid != childpid)
7114                                         continue;
7115                                 if (dead) {
7116                                         int ex;
7117                                         fg_pipe->cmds[i].pid = 0;
7118                                         fg_pipe->alive_cmds--;
7119                                         ex = WEXITSTATUS(status);
7120                                         /* bash prints killer signal's name for *last*
7121                                          * process in pipe (prints just newline for SIGINT/SIGPIPE).
7122                                          * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7123                                          */
7124                                         if (WIFSIGNALED(status)) {
7125                                                 int sig = WTERMSIG(status);
7126                                                 if (i == fg_pipe->num_cmds-1)
7127                                                         /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7128                                                         puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7129                                                 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7130                                                 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7131                                                  * Maybe we need to use sig | 128? */
7132                                                 ex = sig + 128;
7133                                         }
7134                                         fg_pipe->cmds[i].cmd_exitcode = ex;
7135                                 } else {
7136                                         fg_pipe->stopped_cmds++;
7137                                 }
7138                                 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7139                                                 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
7140                                 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
7141                                         /* All processes in fg pipe have exited or stopped */
7142                                         i = fg_pipe->num_cmds;
7143                                         while (--i >= 0) {
7144                                                 rcode = fg_pipe->cmds[i].cmd_exitcode;
7145                                                 /* usually last process gives overall exitstatus,
7146                                                  * but with "set -o pipefail", last *failed* process does */
7147                                                 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7148                                                         break;
7149                                         }
7150                                         IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
7151 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
7152  * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7153  * and "killall -STOP cat" */
7154                                         if (G_interactive_fd) {
7155 #if ENABLE_HUSH_JOB
7156                                                 if (fg_pipe->alive_cmds != 0)
7157                                                         insert_bg_job(fg_pipe);
7158 #endif
7159                                                 return rcode;
7160                                         }
7161                                         if (fg_pipe->alive_cmds == 0)
7162                                                 return rcode;
7163                                 }
7164                                 /* There are still running processes in the fg pipe */
7165                                 goto wait_more; /* do waitpid again */
7166                         }
7167                         /* it wasnt fg_pipe, look for process in bg pipes */
7168                 }
7169
7170 #if ENABLE_HUSH_JOB
7171                 /* We asked to wait for bg or orphaned children */
7172                 /* No need to remember exitcode in this case */
7173                 for (pi = G.job_list; pi; pi = pi->next) {
7174                         for (i = 0; i < pi->num_cmds; i++) {
7175                                 if (pi->cmds[i].pid == childpid)
7176                                         goto found_pi_and_prognum;
7177                         }
7178                 }
7179                 /* Happens when shell is used as init process (init=/bin/sh) */
7180                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7181                 continue; /* do waitpid again */
7182
7183  found_pi_and_prognum:
7184                 if (dead) {
7185                         /* child exited */
7186                         pi->cmds[i].pid = 0;
7187                         pi->alive_cmds--;
7188                         if (!pi->alive_cmds) {
7189                                 if (G_interactive_fd)
7190                                         printf(JOB_STATUS_FORMAT, pi->jobid,
7191                                                         "Done", pi->cmdtext);
7192                                 delete_finished_bg_job(pi);
7193                         }
7194                 } else {
7195                         /* child stopped */
7196                         pi->stopped_cmds++;
7197                 }
7198 #endif
7199         } /* while (waitpid succeeds)... */
7200
7201         return rcode;
7202 }
7203
7204 #if ENABLE_HUSH_JOB
7205 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
7206 {
7207         pid_t p;
7208         int rcode = checkjobs(fg_pipe);
7209         if (G_saved_tty_pgrp) {
7210                 /* Job finished, move the shell to the foreground */
7211                 p = getpgrp(); /* our process group id */
7212                 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7213                 tcsetpgrp(G_interactive_fd, p);
7214         }
7215         return rcode;
7216 }
7217 #endif
7218
7219 /* Start all the jobs, but don't wait for anything to finish.
7220  * See checkjobs().
7221  *
7222  * Return code is normally -1, when the caller has to wait for children
7223  * to finish to determine the exit status of the pipe.  If the pipe
7224  * is a simple builtin command, however, the action is done by the
7225  * time run_pipe returns, and the exit code is provided as the
7226  * return value.
7227  *
7228  * Returns -1 only if started some children. IOW: we have to
7229  * mask out retvals of builtins etc with 0xff!
7230  *
7231  * The only case when we do not need to [v]fork is when the pipe
7232  * is single, non-backgrounded, non-subshell command. Examples:
7233  * cmd ; ...   { list } ; ...
7234  * cmd && ...  { list } && ...
7235  * cmd || ...  { list } || ...
7236  * If it is, then we can run cmd as a builtin, NOFORK,
7237  * or (if SH_STANDALONE) an applet, and we can run the { list }
7238  * with run_list. If it isn't one of these, we fork and exec cmd.
7239  *
7240  * Cases when we must fork:
7241  * non-single:   cmd | cmd
7242  * backgrounded: cmd &     { list } &
7243  * subshell:     ( list ) [&]
7244  */
7245 #if !ENABLE_HUSH_MODE_X
7246 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
7247         redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7248 #endif
7249 static int redirect_and_varexp_helper(char ***new_env_p,
7250                 struct variable **old_vars_p,
7251                 struct command *command,
7252                 int squirrel[3],
7253                 char **argv_expanded)
7254 {
7255         /* setup_redirects acts on file descriptors, not FILEs.
7256          * This is perfect for work that comes after exec().
7257          * Is it really safe for inline use?  Experimentally,
7258          * things seem to work. */
7259         int rcode = setup_redirects(command, squirrel);
7260         if (rcode == 0) {
7261                 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7262                 *new_env_p = new_env;
7263                 dump_cmd_in_x_mode(new_env);
7264                 dump_cmd_in_x_mode(argv_expanded);
7265                 if (old_vars_p)
7266                         *old_vars_p = set_vars_and_save_old(new_env);
7267         }
7268         return rcode;
7269 }
7270 static NOINLINE int run_pipe(struct pipe *pi)
7271 {
7272         static const char *const null_ptr = NULL;
7273
7274         int cmd_no;
7275         int next_infd;
7276         struct command *command;
7277         char **argv_expanded;
7278         char **argv;
7279         /* it is not always needed, but we aim to smaller code */
7280         int squirrel[] = { -1, -1, -1 };
7281         int rcode;
7282
7283         debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7284         debug_enter();
7285
7286         /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7287          * Result should be 3 lines: q w e, qwe, q w e
7288          */
7289         G.ifs = get_local_var_value("IFS");
7290         if (!G.ifs)
7291                 G.ifs = defifs;
7292
7293         IF_HUSH_JOB(pi->pgrp = -1;)
7294         pi->stopped_cmds = 0;
7295         command = &pi->cmds[0];
7296         argv_expanded = NULL;
7297
7298         if (pi->num_cmds != 1
7299          || pi->followup == PIPE_BG
7300          || command->cmd_type == CMD_SUBSHELL
7301         ) {
7302                 goto must_fork;
7303         }
7304
7305         pi->alive_cmds = 1;
7306
7307         debug_printf_exec(": group:%p argv:'%s'\n",
7308                 command->group, command->argv ? command->argv[0] : "NONE");
7309
7310         if (command->group) {
7311 #if ENABLE_HUSH_FUNCTIONS
7312                 if (command->cmd_type == CMD_FUNCDEF) {
7313                         /* "executing" func () { list } */
7314                         struct function *funcp;
7315
7316                         funcp = new_function(command->argv[0]);
7317                         /* funcp->name is already set to argv[0] */
7318                         funcp->body = command->group;
7319 # if !BB_MMU
7320                         funcp->body_as_string = command->group_as_string;
7321                         command->group_as_string = NULL;
7322 # endif
7323                         command->group = NULL;
7324                         command->argv[0] = NULL;
7325                         debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7326                         funcp->parent_cmd = command;
7327                         command->child_func = funcp;
7328
7329                         debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7330                         debug_leave();
7331                         return EXIT_SUCCESS;
7332                 }
7333 #endif
7334                 /* { list } */
7335                 debug_printf("non-subshell group\n");
7336                 rcode = 1; /* exitcode if redir failed */
7337                 if (setup_redirects(command, squirrel) == 0) {
7338                         debug_printf_exec(": run_list\n");
7339                         rcode = run_list(command->group) & 0xff;
7340                 }
7341                 restore_redirects(squirrel);
7342                 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7343                 debug_leave();
7344                 debug_printf_exec("run_pipe: return %d\n", rcode);
7345                 return rcode;
7346         }
7347
7348         argv = command->argv ? command->argv : (char **) &null_ptr;
7349         {
7350                 const struct built_in_command *x;
7351 #if ENABLE_HUSH_FUNCTIONS
7352                 const struct function *funcp;
7353 #else
7354                 enum { funcp = 0 };
7355 #endif
7356                 char **new_env = NULL;
7357                 struct variable *old_vars = NULL;
7358
7359                 if (argv[command->assignment_cnt] == NULL) {
7360                         /* Assignments, but no command */
7361                         /* Ensure redirects take effect (that is, create files).
7362                          * Try "a=t >file" */
7363 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7364                         rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7365                         /* Set shell variables */
7366                         if (new_env) {
7367                                 argv = new_env;
7368                                 while (*argv) {
7369                                         set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7370                                         /* Do we need to flag set_local_var() errors?
7371                                          * "assignment to readonly var" and "putenv error"
7372                                          */
7373                                         argv++;
7374                                 }
7375                         }
7376                         /* Redirect error sets $? to 1. Otherwise,
7377                          * if evaluating assignment value set $?, retain it.
7378                          * Try "false; q=`exit 2`; echo $?" - should print 2: */
7379                         if (rcode == 0)
7380                                 rcode = G.last_exitcode;
7381                         /* Exit, _skipping_ variable restoring code: */
7382                         goto clean_up_and_ret0;
7383
7384 #else /* Older, bigger, but more correct code */
7385
7386                         rcode = setup_redirects(command, squirrel);
7387                         restore_redirects(squirrel);
7388                         /* Set shell variables */
7389                         if (G_x_mode)
7390                                 bb_putchar_stderr('+');
7391                         while (*argv) {
7392                                 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7393                                 if (G_x_mode)
7394                                         fprintf(stderr, " %s", p);
7395                                 debug_printf_exec("set shell var:'%s'->'%s'\n",
7396                                                 *argv, p);
7397                                 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7398                                 /* Do we need to flag set_local_var() errors?
7399                                  * "assignment to readonly var" and "putenv error"
7400                                  */
7401                                 argv++;
7402                         }
7403                         if (G_x_mode)
7404                                 bb_putchar_stderr('\n');
7405                         /* Redirect error sets $? to 1. Otherwise,
7406                          * if evaluating assignment value set $?, retain it.
7407                          * Try "false; q=`exit 2`; echo $?" - should print 2: */
7408                         if (rcode == 0)
7409                                 rcode = G.last_exitcode;
7410                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7411                         debug_leave();
7412                         debug_printf_exec("run_pipe: return %d\n", rcode);
7413                         return rcode;
7414 #endif
7415                 }
7416
7417                 /* Expand the rest into (possibly) many strings each */
7418 #if ENABLE_HUSH_BASH_COMPAT
7419                 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7420                         argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7421                 } else
7422 #endif
7423                 {
7424                         argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7425                 }
7426
7427                 /* if someone gives us an empty string: `cmd with empty output` */
7428                 if (!argv_expanded[0]) {
7429                         free(argv_expanded);
7430                         debug_leave();
7431                         return G.last_exitcode;
7432                 }
7433
7434                 x = find_builtin(argv_expanded[0]);
7435 #if ENABLE_HUSH_FUNCTIONS
7436                 funcp = NULL;
7437                 if (!x)
7438                         funcp = find_function(argv_expanded[0]);
7439 #endif
7440                 if (x || funcp) {
7441                         if (!funcp) {
7442                                 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7443                                         debug_printf("exec with redirects only\n");
7444                                         rcode = setup_redirects(command, NULL);
7445                                         /* rcode=1 can be if redir file can't be opened */
7446                                         goto clean_up_and_ret1;
7447                                 }
7448                         }
7449                         rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7450                         if (rcode == 0) {
7451                                 if (!funcp) {
7452                                         debug_printf_exec(": builtin '%s' '%s'...\n",
7453                                                 x->b_cmd, argv_expanded[1]);
7454                                         fflush_all();
7455                                         rcode = x->b_function(argv_expanded) & 0xff;
7456                                         fflush_all();
7457                                 }
7458 #if ENABLE_HUSH_FUNCTIONS
7459                                 else {
7460 # if ENABLE_HUSH_LOCAL
7461                                         struct variable **sv;
7462                                         sv = G.shadowed_vars_pp;
7463                                         G.shadowed_vars_pp = &old_vars;
7464 # endif
7465                                         debug_printf_exec(": function '%s' '%s'...\n",
7466                                                 funcp->name, argv_expanded[1]);
7467                                         rcode = run_function(funcp, argv_expanded) & 0xff;
7468 # if ENABLE_HUSH_LOCAL
7469                                         G.shadowed_vars_pp = sv;
7470 # endif
7471                                 }
7472 #endif
7473                         }
7474  clean_up_and_ret:
7475                         unset_vars(new_env);
7476                         add_vars(old_vars);
7477 /* clean_up_and_ret0: */
7478                         restore_redirects(squirrel);
7479  clean_up_and_ret1:
7480                         free(argv_expanded);
7481                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7482                         debug_leave();
7483                         debug_printf_exec("run_pipe return %d\n", rcode);
7484                         return rcode;
7485                 }
7486
7487                 if (ENABLE_FEATURE_SH_NOFORK) {
7488                         int n = find_applet_by_name(argv_expanded[0]);
7489                         if (n >= 0 && APPLET_IS_NOFORK(n)) {
7490                                 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7491                                 if (rcode == 0) {
7492                                         debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7493                                                 argv_expanded[0], argv_expanded[1]);
7494                                         rcode = run_nofork_applet(n, argv_expanded);
7495                                 }
7496                                 goto clean_up_and_ret;
7497                         }
7498                 }
7499                 /* It is neither builtin nor applet. We must fork. */
7500         }
7501
7502  must_fork:
7503         /* NB: argv_expanded may already be created, and that
7504          * might include `cmd` runs! Do not rerun it! We *must*
7505          * use argv_expanded if it's non-NULL */
7506
7507         /* Going to fork a child per each pipe member */
7508         pi->alive_cmds = 0;
7509         next_infd = 0;
7510
7511         cmd_no = 0;
7512         while (cmd_no < pi->num_cmds) {
7513                 struct fd_pair pipefds;
7514 #if !BB_MMU
7515                 volatile nommu_save_t nommu_save;
7516                 nommu_save.new_env = NULL;
7517                 nommu_save.old_vars = NULL;
7518                 nommu_save.argv = NULL;
7519                 nommu_save.argv_from_re_execing = NULL;
7520 #endif
7521                 command = &pi->cmds[cmd_no];
7522                 cmd_no++;
7523                 if (command->argv) {
7524                         debug_printf_exec(": pipe member '%s' '%s'...\n",
7525                                         command->argv[0], command->argv[1]);
7526                 } else {
7527                         debug_printf_exec(": pipe member with no argv\n");
7528                 }
7529
7530                 /* pipes are inserted between pairs of commands */
7531                 pipefds.rd = 0;
7532                 pipefds.wr = 1;
7533                 if (cmd_no < pi->num_cmds)
7534                         xpiped_pair(pipefds);
7535
7536                 command->pid = BB_MMU ? fork() : vfork();
7537                 if (!command->pid) { /* child */
7538 #if ENABLE_HUSH_JOB
7539                         disable_restore_tty_pgrp_on_exit();
7540                         CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7541
7542                         /* Every child adds itself to new process group
7543                          * with pgid == pid_of_first_child_in_pipe */
7544                         if (G.run_list_level == 1 && G_interactive_fd) {
7545                                 pid_t pgrp;
7546                                 pgrp = pi->pgrp;
7547                                 if (pgrp < 0) /* true for 1st process only */
7548                                         pgrp = getpid();
7549                                 if (setpgid(0, pgrp) == 0
7550                                  && pi->followup != PIPE_BG
7551                                  && G_saved_tty_pgrp /* we have ctty */
7552                                 ) {
7553                                         /* We do it in *every* child, not just first,
7554                                          * to avoid races */
7555                                         tcsetpgrp(G_interactive_fd, pgrp);
7556                                 }
7557                         }
7558 #endif
7559                         if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7560                                 /* 1st cmd in backgrounded pipe
7561                                  * should have its stdin /dev/null'ed */
7562                                 close(0);
7563                                 if (open(bb_dev_null, O_RDONLY))
7564                                         xopen("/", O_RDONLY);
7565                         } else {
7566                                 xmove_fd(next_infd, 0);
7567                         }
7568                         xmove_fd(pipefds.wr, 1);
7569                         if (pipefds.rd > 1)
7570                                 close(pipefds.rd);
7571                         /* Like bash, explicit redirects override pipes,
7572                          * and the pipe fd (fd#1) is available for dup'ing:
7573                          * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7574                          * of cmd1 goes into pipe.
7575                          */
7576                         if (setup_redirects(command, NULL)) {
7577                                 /* Happens when redir file can't be opened:
7578                                  * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7579                                  * FOO
7580                                  * hush: can't open '/qwe/rty': No such file or directory
7581                                  * BAZ
7582                                  * (echo BAR is not executed, it hits _exit(1) below)
7583                                  */
7584                                 _exit(1);
7585                         }
7586
7587                         /* Stores to nommu_save list of env vars putenv'ed
7588                          * (NOMMU, on MMU we don't need that) */
7589                         /* cast away volatility... */
7590                         pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7591                         /* pseudo_exec() does not return */
7592                 }
7593
7594                 /* parent or error */
7595 #if ENABLE_HUSH_FAST
7596                 G.count_SIGCHLD++;
7597 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7598 #endif
7599                 enable_restore_tty_pgrp_on_exit();
7600 #if !BB_MMU
7601                 /* Clean up after vforked child */
7602                 free(nommu_save.argv);
7603                 free(nommu_save.argv_from_re_execing);
7604                 unset_vars(nommu_save.new_env);
7605                 add_vars(nommu_save.old_vars);
7606 #endif
7607                 free(argv_expanded);
7608                 argv_expanded = NULL;
7609                 if (command->pid < 0) { /* [v]fork failed */
7610                         /* Clearly indicate, was it fork or vfork */
7611                         bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7612                 } else {
7613                         pi->alive_cmds++;
7614 #if ENABLE_HUSH_JOB
7615                         /* Second and next children need to know pid of first one */
7616                         if (pi->pgrp < 0)
7617                                 pi->pgrp = command->pid;
7618 #endif
7619                 }
7620
7621                 if (cmd_no > 1)
7622                         close(next_infd);
7623                 if (cmd_no < pi->num_cmds)
7624                         close(pipefds.wr);
7625                 /* Pass read (output) pipe end to next iteration */
7626                 next_infd = pipefds.rd;
7627         }
7628
7629         if (!pi->alive_cmds) {
7630                 debug_leave();
7631                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7632                 return 1;
7633         }
7634
7635         debug_leave();
7636         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7637         return -1;
7638 }
7639
7640 /* NB: called by pseudo_exec, and therefore must not modify any
7641  * global data until exec/_exit (we can be a child after vfork!) */
7642 static int run_list(struct pipe *pi)
7643 {
7644 #if ENABLE_HUSH_CASE
7645         char *case_word = NULL;
7646 #endif
7647 #if ENABLE_HUSH_LOOPS
7648         struct pipe *loop_top = NULL;
7649         char **for_lcur = NULL;
7650         char **for_list = NULL;
7651 #endif
7652         smallint last_followup;
7653         smalluint rcode;
7654 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7655         smalluint cond_code = 0;
7656 #else
7657         enum { cond_code = 0 };
7658 #endif
7659 #if HAS_KEYWORDS
7660         smallint rword;      /* RES_foo */
7661         smallint last_rword; /* ditto */
7662 #endif
7663
7664         debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7665         debug_enter();
7666
7667 #if ENABLE_HUSH_LOOPS
7668         /* Check syntax for "for" */
7669         {
7670                 struct pipe *cpipe;
7671                 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7672                         if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7673                                 continue;
7674                         /* current word is FOR or IN (BOLD in comments below) */
7675                         if (cpipe->next == NULL) {
7676                                 syntax_error("malformed for");
7677                                 debug_leave();
7678                                 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7679                                 return 1;
7680                         }
7681                         /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7682                         if (cpipe->next->res_word == RES_DO)
7683                                 continue;
7684                         /* next word is not "do". It must be "in" then ("FOR v in ...") */
7685                         if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7686                          || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7687                         ) {
7688                                 syntax_error("malformed for");
7689                                 debug_leave();
7690                                 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7691                                 return 1;
7692                         }
7693                 }
7694         }
7695 #endif
7696
7697         /* Past this point, all code paths should jump to ret: label
7698          * in order to return, no direct "return" statements please.
7699          * This helps to ensure that no memory is leaked. */
7700
7701 #if ENABLE_HUSH_JOB
7702         G.run_list_level++;
7703 #endif
7704
7705 #if HAS_KEYWORDS
7706         rword = RES_NONE;
7707         last_rword = RES_XXXX;
7708 #endif
7709         last_followup = PIPE_SEQ;
7710         rcode = G.last_exitcode;
7711
7712         /* Go through list of pipes, (maybe) executing them. */
7713         for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7714                 if (G.flag_SIGINT)
7715                         break;
7716                 if (G_flag_return_in_progress == 1)
7717                         break;
7718
7719                 IF_HAS_KEYWORDS(rword = pi->res_word;)
7720                 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7721                                 rword, cond_code, last_rword);
7722 #if ENABLE_HUSH_LOOPS
7723                 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7724                  && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7725                 ) {
7726                         /* start of a loop: remember where loop starts */
7727                         loop_top = pi;
7728                         G.depth_of_loop++;
7729                 }
7730 #endif
7731                 /* Still in the same "if...", "then..." or "do..." branch? */
7732                 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7733                         if ((rcode == 0 && last_followup == PIPE_OR)
7734                          || (rcode != 0 && last_followup == PIPE_AND)
7735                         ) {
7736                                 /* It is "<true> || CMD" or "<false> && CMD"
7737                                  * and we should not execute CMD */
7738                                 debug_printf_exec("skipped cmd because of || or &&\n");
7739                                 last_followup = pi->followup;
7740                                 goto dont_check_jobs_but_continue;
7741                         }
7742                 }
7743                 last_followup = pi->followup;
7744                 IF_HAS_KEYWORDS(last_rword = rword;)
7745 #if ENABLE_HUSH_IF
7746                 if (cond_code) {
7747                         if (rword == RES_THEN) {
7748                                 /* if false; then ... fi has exitcode 0! */
7749                                 G.last_exitcode = rcode = EXIT_SUCCESS;
7750                                 /* "if <false> THEN cmd": skip cmd */
7751                                 continue;
7752                         }
7753                 } else {
7754                         if (rword == RES_ELSE || rword == RES_ELIF) {
7755                                 /* "if <true> then ... ELSE/ELIF cmd":
7756                                  * skip cmd and all following ones */
7757                                 break;
7758                         }
7759                 }
7760 #endif
7761 #if ENABLE_HUSH_LOOPS
7762                 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7763                         if (!for_lcur) {
7764                                 /* first loop through for */
7765
7766                                 static const char encoded_dollar_at[] ALIGN1 = {
7767                                         SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7768                                 }; /* encoded representation of "$@" */
7769                                 static const char *const encoded_dollar_at_argv[] = {
7770                                         encoded_dollar_at, NULL
7771                                 }; /* argv list with one element: "$@" */
7772                                 char **vals;
7773
7774                                 vals = (char**)encoded_dollar_at_argv;
7775                                 if (pi->next->res_word == RES_IN) {
7776                                         /* if no variable values after "in" we skip "for" */
7777                                         if (!pi->next->cmds[0].argv) {
7778                                                 G.last_exitcode = rcode = EXIT_SUCCESS;
7779                                                 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7780                                                 break;
7781                                         }
7782                                         vals = pi->next->cmds[0].argv;
7783                                 } /* else: "for var; do..." -> assume "$@" list */
7784                                 /* create list of variable values */
7785                                 debug_print_strings("for_list made from", vals);
7786                                 for_list = expand_strvec_to_strvec(vals);
7787                                 for_lcur = for_list;
7788                                 debug_print_strings("for_list", for_list);
7789                         }
7790                         if (!*for_lcur) {
7791                                 /* "for" loop is over, clean up */
7792                                 free(for_list);
7793                                 for_list = NULL;
7794                                 for_lcur = NULL;
7795                                 break;
7796                         }
7797                         /* Insert next value from for_lcur */
7798                         /* note: *for_lcur already has quotes removed, $var expanded, etc */
7799                         set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7800                         continue;
7801                 }
7802                 if (rword == RES_IN) {
7803                         continue; /* "for v IN list;..." - "in" has no cmds anyway */
7804                 }
7805                 if (rword == RES_DONE) {
7806                         continue; /* "done" has no cmds too */
7807                 }
7808 #endif
7809 #if ENABLE_HUSH_CASE
7810                 if (rword == RES_CASE) {
7811                         case_word = expand_strvec_to_string(pi->cmds->argv);
7812                         continue;
7813                 }
7814                 if (rword == RES_MATCH) {
7815                         char **argv;
7816
7817                         if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7818                                 break;
7819                         /* all prev words didn't match, does this one match? */
7820                         argv = pi->cmds->argv;
7821                         while (*argv) {
7822                                 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7823                                 /* TODO: which FNM_xxx flags to use? */
7824                                 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7825                                 free(pattern);
7826                                 if (cond_code == 0) { /* match! we will execute this branch */
7827                                         free(case_word); /* make future "word)" stop */
7828                                         case_word = NULL;
7829                                         break;
7830                                 }
7831                                 argv++;
7832                         }
7833                         continue;
7834                 }
7835                 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7836                         if (cond_code != 0)
7837                                 continue; /* not matched yet, skip this pipe */
7838                 }
7839 #endif
7840                 /* Just pressing <enter> in shell should check for jobs.
7841                  * OTOH, in non-interactive shell this is useless
7842                  * and only leads to extra job checks */
7843                 if (pi->num_cmds == 0) {
7844                         if (G_interactive_fd)
7845                                 goto check_jobs_and_continue;
7846                         continue;
7847                 }
7848
7849                 /* After analyzing all keywords and conditions, we decided
7850                  * to execute this pipe. NB: have to do checkjobs(NULL)
7851                  * after run_pipe to collect any background children,
7852                  * even if list execution is to be stopped. */
7853                 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7854                 {
7855                         int r;
7856 #if ENABLE_HUSH_LOOPS
7857                         G.flag_break_continue = 0;
7858 #endif
7859                         rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7860                         if (r != -1) {
7861                                 /* We ran a builtin, function, or group.
7862                                  * rcode is already known
7863                                  * and we don't need to wait for anything. */
7864                                 G.last_exitcode = rcode;
7865                                 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7866                                 check_and_run_traps();
7867 #if ENABLE_HUSH_LOOPS
7868                                 /* Was it "break" or "continue"? */
7869                                 if (G.flag_break_continue) {
7870                                         smallint fbc = G.flag_break_continue;
7871                                         /* We might fall into outer *loop*,
7872                                          * don't want to break it too */
7873                                         if (loop_top) {
7874                                                 G.depth_break_continue--;
7875                                                 if (G.depth_break_continue == 0)
7876                                                         G.flag_break_continue = 0;
7877                                                 /* else: e.g. "continue 2" should *break* once, *then* continue */
7878                                         } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7879                                         if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7880                                                 checkjobs(NULL);
7881                                                 break;
7882                                         }
7883                                         /* "continue": simulate end of loop */
7884                                         rword = RES_DONE;
7885                                         continue;
7886                                 }
7887 #endif
7888                                 if (G_flag_return_in_progress == 1) {
7889                                         checkjobs(NULL);
7890                                         break;
7891                                 }
7892                         } else if (pi->followup == PIPE_BG) {
7893                                 /* What does bash do with attempts to background builtins? */
7894                                 /* even bash 3.2 doesn't do that well with nested bg:
7895                                  * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7896                                  * I'm NOT treating inner &'s as jobs */
7897                                 check_and_run_traps();
7898 #if ENABLE_HUSH_JOB
7899                                 if (G.run_list_level == 1)
7900                                         insert_bg_job(pi);
7901 #endif
7902                                 /* Last command's pid goes to $! */
7903                                 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7904                                 G.last_exitcode = rcode = EXIT_SUCCESS;
7905                                 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7906                         } else {
7907 #if ENABLE_HUSH_JOB
7908                                 if (G.run_list_level == 1 && G_interactive_fd) {
7909                                         /* Waits for completion, then fg's main shell */
7910                                         rcode = checkjobs_and_fg_shell(pi);
7911                                         debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7912                                         check_and_run_traps();
7913                                 } else
7914 #endif
7915                                 { /* This one just waits for completion */
7916                                         rcode = checkjobs(pi);
7917                                         debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7918                                         check_and_run_traps();
7919                                 }
7920                                 G.last_exitcode = rcode;
7921                         }
7922                 }
7923
7924                 /* Analyze how result affects subsequent commands */
7925 #if ENABLE_HUSH_IF
7926                 if (rword == RES_IF || rword == RES_ELIF)
7927                         cond_code = rcode;
7928 #endif
7929  check_jobs_and_continue:
7930                 checkjobs(NULL);
7931  dont_check_jobs_but_continue: ;
7932 #if ENABLE_HUSH_LOOPS
7933                 /* Beware of "while false; true; do ..."! */
7934                 if (pi->next
7935                  && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7936                  /* check for RES_DONE is needed for "while ...; do \n done" case */
7937                 ) {
7938                         if (rword == RES_WHILE) {
7939                                 if (rcode) {
7940                                         /* "while false; do...done" - exitcode 0 */
7941                                         G.last_exitcode = rcode = EXIT_SUCCESS;
7942                                         debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7943                                         break;
7944                                 }
7945                         }
7946                         if (rword == RES_UNTIL) {
7947                                 if (!rcode) {
7948                                         debug_printf_exec(": until expr is true: breaking\n");
7949                                         break;
7950                                 }
7951                         }
7952                 }
7953 #endif
7954         } /* for (pi) */
7955
7956 #if ENABLE_HUSH_JOB
7957         G.run_list_level--;
7958 #endif
7959 #if ENABLE_HUSH_LOOPS
7960         if (loop_top)
7961                 G.depth_of_loop--;
7962         free(for_list);
7963 #endif
7964 #if ENABLE_HUSH_CASE
7965         free(case_word);
7966 #endif
7967         debug_leave();
7968         debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7969         return rcode;
7970 }
7971
7972 /* Select which version we will use */
7973 static int run_and_free_list(struct pipe *pi)
7974 {
7975         int rcode = 0;
7976         debug_printf_exec("run_and_free_list entered\n");
7977         if (!G.o_opt[OPT_O_NOEXEC]) {
7978                 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7979                 rcode = run_list(pi);
7980         }
7981         /* free_pipe_list has the side effect of clearing memory.
7982          * In the long run that function can be merged with run_list,
7983          * but doing that now would hobble the debugging effort. */
7984         free_pipe_list(pi);
7985         debug_printf_exec("run_and_free_list return %d\n", rcode);
7986         return rcode;
7987 }
7988
7989
7990 static void install_sighandlers(unsigned mask)
7991 {
7992         sighandler_t old_handler;
7993         unsigned sig = 0;
7994         while ((mask >>= 1) != 0) {
7995                 sig++;
7996                 if (!(mask & 1))
7997                         continue;
7998                 old_handler = install_sighandler(sig, pick_sighandler(sig));
7999                 /* POSIX allows shell to re-enable SIGCHLD
8000                  * even if it was SIG_IGN on entry.
8001                  * Therefore we skip IGN check for it:
8002                  */
8003                 if (sig == SIGCHLD)
8004                         continue;
8005                 if (old_handler == SIG_IGN) {
8006                         /* oops... restore back to IGN, and record this fact */
8007                         install_sighandler(sig, old_handler);
8008                         if (!G.traps)
8009                                 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8010                         free(G.traps[sig]);
8011                         G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8012                 }
8013         }
8014 }
8015
8016 /* Called a few times only (or even once if "sh -c") */
8017 static void install_special_sighandlers(void)
8018 {
8019         unsigned mask;
8020
8021         /* Which signals are shell-special? */
8022         mask = (1 << SIGQUIT) | (1 << SIGCHLD);
8023         if (G_interactive_fd) {
8024                 mask |= SPECIAL_INTERACTIVE_SIGS;
8025                 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
8026                         mask |= SPECIAL_JOBSTOP_SIGS;
8027         }
8028         /* Careful, do not re-install handlers we already installed */
8029         if (G.special_sig_mask != mask) {
8030                 unsigned diff = mask & ~G.special_sig_mask;
8031                 G.special_sig_mask = mask;
8032                 install_sighandlers(diff);
8033         }
8034 }
8035
8036 #if ENABLE_HUSH_JOB
8037 /* helper */
8038 /* Set handlers to restore tty pgrp and exit */
8039 static void install_fatal_sighandlers(void)
8040 {
8041         unsigned mask;
8042
8043         /* We will restore tty pgrp on these signals */
8044         mask = 0
8045                 + (1 << SIGILL ) * HUSH_DEBUG
8046                 + (1 << SIGFPE ) * HUSH_DEBUG
8047                 + (1 << SIGBUS ) * HUSH_DEBUG
8048                 + (1 << SIGSEGV) * HUSH_DEBUG
8049                 + (1 << SIGTRAP) * HUSH_DEBUG
8050                 + (1 << SIGABRT)
8051         /* bash 3.2 seems to handle these just like 'fatal' ones */
8052                 + (1 << SIGPIPE)
8053                 + (1 << SIGALRM)
8054         /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
8055          * if we aren't interactive... but in this case
8056          * we never want to restore pgrp on exit, and this fn is not called
8057          */
8058                 /*+ (1 << SIGHUP )*/
8059                 /*+ (1 << SIGTERM)*/
8060                 /*+ (1 << SIGINT )*/
8061         ;
8062         G_fatal_sig_mask = mask;
8063
8064         install_sighandlers(mask);
8065 }
8066 #endif
8067
8068 static int set_mode(int state, char mode, const char *o_opt)
8069 {
8070         int idx;
8071         switch (mode) {
8072         case 'n':
8073                 G.o_opt[OPT_O_NOEXEC] = state;
8074                 break;
8075         case 'x':
8076                 IF_HUSH_MODE_X(G_x_mode = state;)
8077                 break;
8078         case 'o':
8079                 if (!o_opt) {
8080                         /* "set -+o" without parameter.
8081                          * in bash, set -o produces this output:
8082                          *  pipefail        off
8083                          * and set +o:
8084                          *  set +o pipefail
8085                          * We always use the second form.
8086                          */
8087                         const char *p = o_opt_strings;
8088                         idx = 0;
8089                         while (*p) {
8090                                 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8091                                 idx++;
8092                                 p += strlen(p) + 1;
8093                         }
8094                         break;
8095                 }
8096                 idx = index_in_strings(o_opt_strings, o_opt);
8097                 if (idx >= 0) {
8098                         G.o_opt[idx] = state;
8099                         break;
8100                 }
8101         default:
8102                 return EXIT_FAILURE;
8103         }
8104         return EXIT_SUCCESS;
8105 }
8106
8107 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8108 int hush_main(int argc, char **argv)
8109 {
8110         enum {
8111                 OPT_login = (1 << 0),
8112         };
8113         unsigned flags;
8114         int opt;
8115         unsigned builtin_argc;
8116         char **e;
8117         struct variable *cur_var;
8118         struct variable *shell_ver;
8119
8120         INIT_G();
8121         if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
8122                 G.last_exitcode = EXIT_SUCCESS;
8123
8124 #if ENABLE_HUSH_FAST
8125         G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8126 #endif
8127 #if !BB_MMU
8128         G.argv0_for_re_execing = argv[0];
8129 #endif
8130         /* Deal with HUSH_VERSION */
8131         shell_ver = xzalloc(sizeof(*shell_ver));
8132         shell_ver->flg_export = 1;
8133         shell_ver->flg_read_only = 1;
8134         /* Code which handles ${var<op>...} needs writable values for all variables,
8135          * therefore we xstrdup: */
8136         shell_ver->varstr = xstrdup(hush_version_str);
8137         /* Create shell local variables from the values
8138          * currently living in the environment */
8139         debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
8140         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
8141         G.top_var = shell_ver;
8142         cur_var = G.top_var;
8143         e = environ;
8144         if (e) while (*e) {
8145                 char *value = strchr(*e, '=');
8146                 if (value) { /* paranoia */
8147                         cur_var->next = xzalloc(sizeof(*cur_var));
8148                         cur_var = cur_var->next;
8149                         cur_var->varstr = *e;
8150                         cur_var->max_len = strlen(*e);
8151                         cur_var->flg_export = 1;
8152                 }
8153                 e++;
8154         }
8155         /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
8156         debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8157         putenv(shell_ver->varstr);
8158
8159         /* Export PWD */
8160         set_pwd_var(/*exp:*/ 1);
8161
8162 #if ENABLE_HUSH_BASH_COMPAT
8163         /* Set (but not export) HOSTNAME unless already set */
8164         if (!get_local_var_value("HOSTNAME")) {
8165                 struct utsname uts;
8166                 uname(&uts);
8167                 set_local_var_from_halves("HOSTNAME", uts.nodename);
8168         }
8169         /* bash also exports SHLVL and _,
8170          * and sets (but doesn't export) the following variables:
8171          * BASH=/bin/bash
8172          * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8173          * BASH_VERSION='3.2.0(1)-release'
8174          * HOSTTYPE=i386
8175          * MACHTYPE=i386-pc-linux-gnu
8176          * OSTYPE=linux-gnu
8177          * PPID=<NNNNN> - we also do it elsewhere
8178          * EUID=<NNNNN>
8179          * UID=<NNNNN>
8180          * GROUPS=()
8181          * LINES=<NNN>
8182          * COLUMNS=<NNN>
8183          * BASH_ARGC=()
8184          * BASH_ARGV=()
8185          * BASH_LINENO=()
8186          * BASH_SOURCE=()
8187          * DIRSTACK=()
8188          * PIPESTATUS=([0]="0")
8189          * HISTFILE=/<xxx>/.bash_history
8190          * HISTFILESIZE=500
8191          * HISTSIZE=500
8192          * MAILCHECK=60
8193          * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8194          * SHELL=/bin/bash
8195          * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8196          * TERM=dumb
8197          * OPTERR=1
8198          * OPTIND=1
8199          * IFS=$' \t\n'
8200          * PS1='\s-\v\$ '
8201          * PS2='> '
8202          * PS4='+ '
8203          */
8204 #endif
8205
8206 #if ENABLE_FEATURE_EDITING
8207         G.line_input_state = new_line_input_t(FOR_SHELL);
8208 #endif
8209
8210         /* Initialize some more globals to non-zero values */
8211         cmdedit_update_prompt();
8212
8213         die_func = restore_ttypgrp_and__exit;
8214
8215         /* Shell is non-interactive at first. We need to call
8216          * install_special_sighandlers() if we are going to execute "sh <script>",
8217          * "sh -c <cmds>" or login shell's /etc/profile and friends.
8218          * If we later decide that we are interactive, we run install_special_sighandlers()
8219          * in order to intercept (more) signals.
8220          */
8221
8222         /* Parse options */
8223         /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
8224         flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
8225         builtin_argc = 0;
8226         while (1) {
8227                 opt = getopt(argc, argv, "+c:xinsl"
8228 #if !BB_MMU
8229                                 "<:$:R:V:"
8230 # if ENABLE_HUSH_FUNCTIONS
8231                                 "F:"
8232 # endif
8233 #endif
8234                 );
8235                 if (opt <= 0)
8236                         break;
8237                 switch (opt) {
8238                 case 'c':
8239                         /* Possibilities:
8240                          * sh ... -c 'script'
8241                          * sh ... -c 'script' ARG0 [ARG1...]
8242                          * On NOMMU, if builtin_argc != 0,
8243                          * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
8244                          * "" needs to be replaced with NULL
8245                          * and BARGV vector fed to builtin function.
8246                          * Note: the form without ARG0 never happens:
8247                          * sh ... -c 'builtin' BARGV... ""
8248                          */
8249                         if (!G.root_pid) {
8250                                 G.root_pid = getpid();
8251                                 G.root_ppid = getppid();
8252                         }
8253                         G.global_argv = argv + optind;
8254                         G.global_argc = argc - optind;
8255                         if (builtin_argc) {
8256                                 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8257                                 const struct built_in_command *x;
8258
8259                                 install_special_sighandlers();
8260                                 x = find_builtin(optarg);
8261                                 if (x) { /* paranoia */
8262                                         G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8263                                         G.global_argv += builtin_argc;
8264                                         G.global_argv[-1] = NULL; /* replace "" */
8265                                         fflush_all();
8266                                         G.last_exitcode = x->b_function(argv + optind - 1);
8267                                 }
8268                                 goto final_return;
8269                         }
8270                         if (!G.global_argv[0]) {
8271                                 /* -c 'script' (no params): prevent empty $0 */
8272                                 G.global_argv--; /* points to argv[i] of 'script' */
8273                                 G.global_argv[0] = argv[0];
8274                                 G.global_argc++;
8275                         } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
8276                         install_special_sighandlers();
8277                         parse_and_run_string(optarg);
8278                         goto final_return;
8279                 case 'i':
8280                         /* Well, we cannot just declare interactiveness,
8281                          * we have to have some stuff (ctty, etc) */
8282                         /* G_interactive_fd++; */
8283                         break;
8284                 case 's':
8285                         /* "-s" means "read from stdin", but this is how we always
8286                          * operate, so simply do nothing here. */
8287                         break;
8288                 case 'l':
8289                         flags |= OPT_login;
8290                         break;
8291 #if !BB_MMU
8292                 case '<': /* "big heredoc" support */
8293                         full_write1_str(optarg);
8294                         _exit(0);
8295                 case '$': {
8296                         unsigned long long empty_trap_mask;
8297
8298                         G.root_pid = bb_strtou(optarg, &optarg, 16);
8299                         optarg++;
8300                         G.root_ppid = bb_strtou(optarg, &optarg, 16);
8301                         optarg++;
8302                         G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8303                         optarg++;
8304                         G.last_exitcode = bb_strtou(optarg, &optarg, 16);
8305                         optarg++;
8306                         builtin_argc = bb_strtou(optarg, &optarg, 16);
8307                         optarg++;
8308                         empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8309                         if (empty_trap_mask != 0) {
8310                                 int sig;
8311                                 install_special_sighandlers();
8312                                 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8313                                 for (sig = 1; sig < NSIG; sig++) {
8314                                         if (empty_trap_mask & (1LL << sig)) {
8315                                                 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8316                                                 install_sighandler(sig, SIG_IGN);
8317                                         }
8318                                 }
8319                         }
8320 # if ENABLE_HUSH_LOOPS
8321                         optarg++;
8322                         G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
8323 # endif
8324                         break;
8325                 }
8326                 case 'R':
8327                 case 'V':
8328                         set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
8329                         break;
8330 # if ENABLE_HUSH_FUNCTIONS
8331                 case 'F': {
8332                         struct function *funcp = new_function(optarg);
8333                         /* funcp->name is already set to optarg */
8334                         /* funcp->body is set to NULL. It's a special case. */
8335                         funcp->body_as_string = argv[optind];
8336                         optind++;
8337                         break;
8338                 }
8339 # endif
8340 #endif
8341                 case 'n':
8342                 case 'x':
8343                         if (set_mode(1, opt, NULL) == 0) /* no error */
8344                                 break;
8345                 default:
8346 #ifndef BB_VER
8347                         fprintf(stderr, "Usage: sh [FILE]...\n"
8348                                         "   or: sh -c command [args]...\n\n");
8349                         exit(EXIT_FAILURE);
8350 #else
8351                         bb_show_usage();
8352 #endif
8353                 }
8354         } /* option parsing loop */
8355
8356         /* Skip options. Try "hush -l": $1 should not be "-l"! */
8357         G.global_argc = argc - (optind - 1);
8358         G.global_argv = argv + (optind - 1);
8359         G.global_argv[0] = argv[0];
8360
8361         if (!G.root_pid) {
8362                 G.root_pid = getpid();
8363                 G.root_ppid = getppid();
8364         }
8365
8366         /* If we are login shell... */
8367         if (flags & OPT_login) {
8368                 FILE *input;
8369                 debug_printf("sourcing /etc/profile\n");
8370                 input = fopen_for_read("/etc/profile");
8371                 if (input != NULL) {
8372                         remember_FILE(input);
8373                         install_special_sighandlers();
8374                         parse_and_run_file(input);
8375                         fclose_and_forget(input);
8376                 }
8377                 /* bash: after sourcing /etc/profile,
8378                  * tries to source (in the given order):
8379                  * ~/.bash_profile, ~/.bash_login, ~/.profile,
8380                  * stopping on first found. --noprofile turns this off.
8381                  * bash also sources ~/.bash_logout on exit.
8382                  * If called as sh, skips .bash_XXX files.
8383                  */
8384         }
8385
8386         if (G.global_argv[1]) {
8387                 FILE *input;
8388                 /*
8389                  * "bash <script>" (which is never interactive (unless -i?))
8390                  * sources $BASH_ENV here (without scanning $PATH).
8391                  * If called as sh, does the same but with $ENV.
8392                  */
8393                 G.global_argc--;
8394                 G.global_argv++;
8395                 debug_printf("running script '%s'\n", G.global_argv[0]);
8396                 input = xfopen_for_read(G.global_argv[0]);
8397                 remember_FILE(input);
8398                 install_special_sighandlers();
8399                 parse_and_run_file(input);
8400 #if ENABLE_FEATURE_CLEAN_UP
8401                 fclose_and_forget(input);
8402 #endif
8403                 goto final_return;
8404         }
8405
8406         /* Up to here, shell was non-interactive. Now it may become one.
8407          * NB: don't forget to (re)run install_special_sighandlers() as needed.
8408          */
8409
8410         /* A shell is interactive if the '-i' flag was given,
8411          * or if all of the following conditions are met:
8412          *    no -c command
8413          *    no arguments remaining or the -s flag given
8414          *    standard input is a terminal
8415          *    standard output is a terminal
8416          * Refer to Posix.2, the description of the 'sh' utility.
8417          */
8418 #if ENABLE_HUSH_JOB
8419         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8420                 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8421                 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8422                 if (G_saved_tty_pgrp < 0)
8423                         G_saved_tty_pgrp = 0;
8424
8425                 /* try to dup stdin to high fd#, >= 255 */
8426                 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8427                 if (G_interactive_fd < 0) {
8428                         /* try to dup to any fd */
8429                         G_interactive_fd = dup(STDIN_FILENO);
8430                         if (G_interactive_fd < 0) {
8431                                 /* give up */
8432                                 G_interactive_fd = 0;
8433                                 G_saved_tty_pgrp = 0;
8434                         }
8435                 }
8436 // TODO: track & disallow any attempts of user
8437 // to (inadvertently) close/redirect G_interactive_fd
8438         }
8439         debug_printf("interactive_fd:%d\n", G_interactive_fd);
8440         if (G_interactive_fd) {
8441                 close_on_exec_on(G_interactive_fd);
8442
8443                 if (G_saved_tty_pgrp) {
8444                         /* If we were run as 'hush &', sleep until we are
8445                          * in the foreground (tty pgrp == our pgrp).
8446                          * If we get started under a job aware app (like bash),
8447                          * make sure we are now in charge so we don't fight over
8448                          * who gets the foreground */
8449                         while (1) {
8450                                 pid_t shell_pgrp = getpgrp();
8451                                 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8452                                 if (G_saved_tty_pgrp == shell_pgrp)
8453                                         break;
8454                                 /* send TTIN to ourself (should stop us) */
8455                                 kill(- shell_pgrp, SIGTTIN);
8456                         }
8457                 }
8458
8459                 /* Install more signal handlers */
8460                 install_special_sighandlers();
8461
8462                 if (G_saved_tty_pgrp) {
8463                         /* Set other signals to restore saved_tty_pgrp */
8464                         install_fatal_sighandlers();
8465                         /* Put ourselves in our own process group
8466                          * (bash, too, does this only if ctty is available) */
8467                         bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8468                         /* Grab control of the terminal */
8469                         tcsetpgrp(G_interactive_fd, getpid());
8470                 }
8471                 enable_restore_tty_pgrp_on_exit();
8472
8473 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8474                 {
8475                         const char *hp = get_local_var_value("HISTFILE");
8476                         if (!hp) {
8477                                 hp = get_local_var_value("HOME");
8478                                 if (hp)
8479                                         hp = concat_path_file(hp, ".hush_history");
8480                         } else {
8481                                 hp = xstrdup(hp);
8482                         }
8483                         if (hp) {
8484                                 G.line_input_state->hist_file = hp;
8485                                 //set_local_var(xasprintf("HISTFILE=%s", ...));
8486                         }
8487 #  if ENABLE_FEATURE_SH_HISTFILESIZE
8488                         hp = get_local_var_value("HISTFILESIZE");
8489                         G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8490 #  endif
8491                 }
8492 # endif
8493         } else {
8494                 install_special_sighandlers();
8495         }
8496 #elif ENABLE_HUSH_INTERACTIVE
8497         /* No job control compiled in, only prompt/line editing */
8498         if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8499                 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8500                 if (G_interactive_fd < 0) {
8501                         /* try to dup to any fd */
8502                         G_interactive_fd = dup(STDIN_FILENO);
8503                         if (G_interactive_fd < 0)
8504                                 /* give up */
8505                                 G_interactive_fd = 0;
8506                 }
8507         }
8508         if (G_interactive_fd) {
8509                 close_on_exec_on(G_interactive_fd);
8510         }
8511         install_special_sighandlers();
8512 #else
8513         /* We have interactiveness code disabled */
8514         install_special_sighandlers();
8515 #endif
8516         /* bash:
8517          * if interactive but not a login shell, sources ~/.bashrc
8518          * (--norc turns this off, --rcfile <file> overrides)
8519          */
8520
8521         if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8522                 /* note: ash and hush share this string */
8523                 printf("\n\n%s %s\n"
8524                         IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8525                         "\n",
8526                         bb_banner,
8527                         "hush - the humble shell"
8528                 );
8529         }
8530
8531         parse_and_run_file(stdin);
8532
8533  final_return:
8534         hush_exit(G.last_exitcode);
8535 }
8536
8537
8538 #if ENABLE_MSH
8539 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8540 int msh_main(int argc, char **argv)
8541 {
8542         bb_error_msg("msh is deprecated, please use hush instead");
8543         return hush_main(argc, argv);
8544 }
8545 #endif
8546
8547
8548 /*
8549  * Built-ins
8550  */
8551 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8552 {
8553         return 0;
8554 }
8555
8556 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8557 {
8558         int argc = 0;
8559         while (*argv) {
8560                 argc++;
8561                 argv++;
8562         }
8563         return applet_main_func(argc, argv - argc);
8564 }
8565
8566 static int FAST_FUNC builtin_test(char **argv)
8567 {
8568         return run_applet_main(argv, test_main);
8569 }
8570
8571 static int FAST_FUNC builtin_echo(char **argv)
8572 {
8573         return run_applet_main(argv, echo_main);
8574 }
8575
8576 #if ENABLE_PRINTF
8577 static int FAST_FUNC builtin_printf(char **argv)
8578 {
8579         return run_applet_main(argv, printf_main);
8580 }
8581 #endif
8582
8583 static char **skip_dash_dash(char **argv)
8584 {
8585         argv++;
8586         if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8587                 argv++;
8588         return argv;
8589 }
8590
8591 static int FAST_FUNC builtin_eval(char **argv)
8592 {
8593         int rcode = EXIT_SUCCESS;
8594
8595         argv = skip_dash_dash(argv);
8596         if (*argv) {
8597                 char *str = expand_strvec_to_string(argv);
8598                 /* bash:
8599                  * eval "echo Hi; done" ("done" is syntax error):
8600                  * "echo Hi" will not execute too.
8601                  */
8602                 parse_and_run_string(str);
8603                 free(str);
8604                 rcode = G.last_exitcode;
8605         }
8606         return rcode;
8607 }
8608
8609 static int FAST_FUNC builtin_cd(char **argv)
8610 {
8611         const char *newdir;
8612
8613         argv = skip_dash_dash(argv);
8614         newdir = argv[0];
8615         if (newdir == NULL) {
8616                 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8617                  * bash says "bash: cd: HOME not set" and does nothing
8618                  * (exitcode 1)
8619                  */
8620                 const char *home = get_local_var_value("HOME");
8621                 newdir = home ? home : "/";
8622         }
8623         if (chdir(newdir)) {
8624                 /* Mimic bash message exactly */
8625                 bb_perror_msg("cd: %s", newdir);
8626                 return EXIT_FAILURE;
8627         }
8628         /* Read current dir (get_cwd(1) is inside) and set PWD.
8629          * Note: do not enforce exporting. If PWD was unset or unexported,
8630          * set it again, but do not export. bash does the same.
8631          */
8632         set_pwd_var(/*exp:*/ 0);
8633         return EXIT_SUCCESS;
8634 }
8635
8636 static int FAST_FUNC builtin_exec(char **argv)
8637 {
8638         argv = skip_dash_dash(argv);
8639         if (argv[0] == NULL)
8640                 return EXIT_SUCCESS; /* bash does this */
8641
8642         /* Careful: we can end up here after [v]fork. Do not restore
8643          * tty pgrp then, only top-level shell process does that */
8644         if (G_saved_tty_pgrp && getpid() == G.root_pid)
8645                 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8646
8647         /* TODO: if exec fails, bash does NOT exit! We do.
8648          * We'll need to undo trap cleanup (it's inside execvp_or_die)
8649          * and tcsetpgrp, and this is inherently racy.
8650          */
8651         execvp_or_die(argv);
8652 }
8653
8654 static int FAST_FUNC builtin_exit(char **argv)
8655 {
8656         debug_printf_exec("%s()\n", __func__);
8657
8658         /* interactive bash:
8659          * # trap "echo EEE" EXIT
8660          * # exit
8661          * exit
8662          * There are stopped jobs.
8663          * (if there are _stopped_ jobs, running ones don't count)
8664          * # exit
8665          * exit
8666          * EEE (then bash exits)
8667          *
8668          * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8669          */
8670
8671         /* note: EXIT trap is run by hush_exit */
8672         argv = skip_dash_dash(argv);
8673         if (argv[0] == NULL)
8674                 hush_exit(G.last_exitcode);
8675         /* mimic bash: exit 123abc == exit 255 + error msg */
8676         xfunc_error_retval = 255;
8677         /* bash: exit -2 == exit 254, no error msg */
8678         hush_exit(xatoi(argv[0]) & 0xff);
8679 }
8680
8681 static void print_escaped(const char *s)
8682 {
8683         if (*s == '\'')
8684                 goto squote;
8685         do {
8686                 const char *p = strchrnul(s, '\'');
8687                 /* print 'xxxx', possibly just '' */
8688                 printf("'%.*s'", (int)(p - s), s);
8689                 if (*p == '\0')
8690                         break;
8691                 s = p;
8692  squote:
8693                 /* s points to '; print "'''...'''" */
8694                 putchar('"');
8695                 do putchar('\''); while (*++s == '\'');
8696                 putchar('"');
8697         } while (*s);
8698 }
8699
8700 #if !ENABLE_HUSH_LOCAL
8701 #define helper_export_local(argv, exp, lvl) \
8702         helper_export_local(argv, exp)
8703 #endif
8704 static void helper_export_local(char **argv, int exp, int lvl)
8705 {
8706         do {
8707                 char *name = *argv;
8708                 char *name_end = strchrnul(name, '=');
8709
8710                 /* So far we do not check that name is valid (TODO?) */
8711
8712                 if (*name_end == '\0') {
8713                         struct variable *var, **vpp;
8714
8715                         vpp = get_ptr_to_local_var(name, name_end - name);
8716                         var = vpp ? *vpp : NULL;
8717
8718                         if (exp == -1) { /* unexporting? */
8719                                 /* export -n NAME (without =VALUE) */
8720                                 if (var) {
8721                                         var->flg_export = 0;
8722                                         debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8723                                         unsetenv(name);
8724                                 } /* else: export -n NOT_EXISTING_VAR: no-op */
8725                                 continue;
8726                         }
8727                         if (exp == 1) { /* exporting? */
8728                                 /* export NAME (without =VALUE) */
8729                                 if (var) {
8730                                         var->flg_export = 1;
8731                                         debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8732                                         putenv(var->varstr);
8733                                         continue;
8734                                 }
8735                         }
8736                         /* Exporting non-existing variable.
8737                          * bash does not put it in environment,
8738                          * but remembers that it is exported,
8739                          * and does put it in env when it is set later.
8740                          * We just set it to "" and export. */
8741                         /* Or, it's "local NAME" (without =VALUE).
8742                          * bash sets the value to "". */
8743                         name = xasprintf("%s=", name);
8744                 } else {
8745                         /* (Un)exporting/making local NAME=VALUE */
8746                         name = xstrdup(name);
8747                 }
8748                 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8749         } while (*++argv);
8750 }
8751
8752 static int FAST_FUNC builtin_export(char **argv)
8753 {
8754         unsigned opt_unexport;
8755
8756 #if ENABLE_HUSH_EXPORT_N
8757         /* "!": do not abort on errors */
8758         opt_unexport = getopt32(argv, "!n");
8759         if (opt_unexport == (uint32_t)-1)
8760                 return EXIT_FAILURE;
8761         argv += optind;
8762 #else
8763         opt_unexport = 0;
8764         argv++;
8765 #endif
8766
8767         if (argv[0] == NULL) {
8768                 char **e = environ;
8769                 if (e) {
8770                         while (*e) {
8771 #if 0
8772                                 puts(*e++);
8773 #else
8774                                 /* ash emits: export VAR='VAL'
8775                                  * bash: declare -x VAR="VAL"
8776                                  * we follow ash example */
8777                                 const char *s = *e++;
8778                                 const char *p = strchr(s, '=');
8779
8780                                 if (!p) /* wtf? take next variable */
8781                                         continue;
8782                                 /* export var= */
8783                                 printf("export %.*s", (int)(p - s) + 1, s);
8784                                 print_escaped(p + 1);
8785                                 putchar('\n');
8786 #endif
8787                         }
8788                         /*fflush_all(); - done after each builtin anyway */
8789                 }
8790                 return EXIT_SUCCESS;
8791         }
8792
8793         helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8794
8795         return EXIT_SUCCESS;
8796 }
8797
8798 #if ENABLE_HUSH_LOCAL
8799 static int FAST_FUNC builtin_local(char **argv)
8800 {
8801         if (G.func_nest_level == 0) {
8802                 bb_error_msg("%s: not in a function", argv[0]);
8803                 return EXIT_FAILURE; /* bash compat */
8804         }
8805         helper_export_local(argv, 0, G.func_nest_level);
8806         return EXIT_SUCCESS;
8807 }
8808 #endif
8809
8810 static int FAST_FUNC builtin_trap(char **argv)
8811 {
8812         int sig;
8813         char *new_cmd;
8814
8815         if (!G.traps)
8816                 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8817
8818         argv++;
8819         if (!*argv) {
8820                 int i;
8821                 /* No args: print all trapped */
8822                 for (i = 0; i < NSIG; ++i) {
8823                         if (G.traps[i]) {
8824                                 printf("trap -- ");
8825                                 print_escaped(G.traps[i]);
8826                                 /* note: bash adds "SIG", but only if invoked
8827                                  * as "bash". If called as "sh", or if set -o posix,
8828                                  * then it prints short signal names.
8829                                  * We are printing short names: */
8830                                 printf(" %s\n", get_signame(i));
8831                         }
8832                 }
8833                 /*fflush_all(); - done after each builtin anyway */
8834                 return EXIT_SUCCESS;
8835         }
8836
8837         new_cmd = NULL;
8838         /* If first arg is a number: reset all specified signals */
8839         sig = bb_strtou(*argv, NULL, 10);
8840         if (errno == 0) {
8841                 int ret;
8842  process_sig_list:
8843                 ret = EXIT_SUCCESS;
8844                 while (*argv) {
8845                         sighandler_t handler;
8846
8847                         sig = get_signum(*argv++);
8848                         if (sig < 0 || sig >= NSIG) {
8849                                 ret = EXIT_FAILURE;
8850                                 /* Mimic bash message exactly */
8851                                 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8852                                 continue;
8853                         }
8854
8855                         free(G.traps[sig]);
8856                         G.traps[sig] = xstrdup(new_cmd);
8857
8858                         debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8859                                 get_signame(sig), sig, G.traps[sig]);
8860
8861                         /* There is no signal for 0 (EXIT) */
8862                         if (sig == 0)
8863                                 continue;
8864
8865                         if (new_cmd)
8866                                 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8867                         else
8868                                 /* We are removing trap handler */
8869                                 handler = pick_sighandler(sig);
8870                         install_sighandler(sig, handler);
8871                 }
8872                 return ret;
8873         }
8874
8875         if (!argv[1]) { /* no second arg */
8876                 bb_error_msg("trap: invalid arguments");
8877                 return EXIT_FAILURE;
8878         }
8879
8880         /* First arg is "-": reset all specified to default */
8881         /* First arg is "--": skip it, the rest is "handler SIGs..." */
8882         /* Everything else: set arg as signal handler
8883          * (includes "" case, which ignores signal) */
8884         if (argv[0][0] == '-') {
8885                 if (argv[0][1] == '\0') { /* "-" */
8886                         /* new_cmd remains NULL: "reset these sigs" */
8887                         goto reset_traps;
8888                 }
8889                 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8890                         argv++;
8891                 }
8892                 /* else: "-something", no special meaning */
8893         }
8894         new_cmd = *argv;
8895  reset_traps:
8896         argv++;
8897         goto process_sig_list;
8898 }
8899
8900 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8901 static int FAST_FUNC builtin_type(char **argv)
8902 {
8903         int ret = EXIT_SUCCESS;
8904
8905         while (*++argv) {
8906                 const char *type;
8907                 char *path = NULL;
8908
8909                 if (0) {} /* make conditional compile easier below */
8910                 /*else if (find_alias(*argv))
8911                         type = "an alias";*/
8912 #if ENABLE_HUSH_FUNCTIONS
8913                 else if (find_function(*argv))
8914                         type = "a function";
8915 #endif
8916                 else if (find_builtin(*argv))
8917                         type = "a shell builtin";
8918                 else if ((path = find_in_path(*argv)) != NULL)
8919                         type = path;
8920                 else {
8921                         bb_error_msg("type: %s: not found", *argv);
8922                         ret = EXIT_FAILURE;
8923                         continue;
8924                 }
8925
8926                 printf("%s is %s\n", *argv, type);
8927                 free(path);
8928         }
8929
8930         return ret;
8931 }
8932
8933 #if ENABLE_HUSH_JOB
8934 /* built-in 'fg' and 'bg' handler */
8935 static int FAST_FUNC builtin_fg_bg(char **argv)
8936 {
8937         int i, jobnum;
8938         struct pipe *pi;
8939
8940         if (!G_interactive_fd)
8941                 return EXIT_FAILURE;
8942
8943         /* If they gave us no args, assume they want the last backgrounded task */
8944         if (!argv[1]) {
8945                 for (pi = G.job_list; pi; pi = pi->next) {
8946                         if (pi->jobid == G.last_jobid) {
8947                                 goto found;
8948                         }
8949                 }
8950                 bb_error_msg("%s: no current job", argv[0]);
8951                 return EXIT_FAILURE;
8952         }
8953         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8954                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8955                 return EXIT_FAILURE;
8956         }
8957         for (pi = G.job_list; pi; pi = pi->next) {
8958                 if (pi->jobid == jobnum) {
8959                         goto found;
8960                 }
8961         }
8962         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8963         return EXIT_FAILURE;
8964  found:
8965         /* TODO: bash prints a string representation
8966          * of job being foregrounded (like "sleep 1 | cat") */
8967         if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8968                 /* Put the job into the foreground.  */
8969                 tcsetpgrp(G_interactive_fd, pi->pgrp);
8970         }
8971
8972         /* Restart the processes in the job */
8973         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8974         for (i = 0; i < pi->num_cmds; i++) {
8975                 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8976         }
8977         pi->stopped_cmds = 0;
8978
8979         i = kill(- pi->pgrp, SIGCONT);
8980         if (i < 0) {
8981                 if (errno == ESRCH) {
8982                         delete_finished_bg_job(pi);
8983                         return EXIT_SUCCESS;
8984                 }
8985                 bb_perror_msg("kill (SIGCONT)");
8986         }
8987
8988         if (argv[0][0] == 'f') {
8989                 remove_bg_job(pi);
8990                 return checkjobs_and_fg_shell(pi);
8991         }
8992         return EXIT_SUCCESS;
8993 }
8994 #endif
8995
8996 #if ENABLE_HUSH_HELP
8997 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8998 {
8999         const struct built_in_command *x;
9000
9001         printf(
9002                 "Built-in commands:\n"
9003                 "------------------\n");
9004         for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9005                 if (x->b_descr)
9006                         printf("%-10s%s\n", x->b_cmd, x->b_descr);
9007         }
9008         return EXIT_SUCCESS;
9009 }
9010 #endif
9011
9012 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
9013 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9014 {
9015         show_history(G.line_input_state);
9016         return EXIT_SUCCESS;
9017 }
9018 #endif
9019
9020 #if ENABLE_HUSH_JOB
9021 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
9022 {
9023         struct pipe *job;
9024         const char *status_string;
9025
9026         for (job = G.job_list; job; job = job->next) {
9027                 if (job->alive_cmds == job->stopped_cmds)
9028                         status_string = "Stopped";
9029                 else
9030                         status_string = "Running";
9031
9032                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9033         }
9034         return EXIT_SUCCESS;
9035 }
9036 #endif
9037
9038 #if HUSH_DEBUG
9039 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
9040 {
9041         void *p;
9042         unsigned long l;
9043
9044 # ifdef M_TRIM_THRESHOLD
9045         /* Optional. Reduces probability of false positives */
9046         malloc_trim(0);
9047 # endif
9048         /* Crude attempt to find where "free memory" starts,
9049          * sans fragmentation. */
9050         p = malloc(240);
9051         l = (unsigned long)p;
9052         free(p);
9053         p = malloc(3400);
9054         if (l < (unsigned long)p) l = (unsigned long)p;
9055         free(p);
9056
9057         if (!G.memleak_value)
9058                 G.memleak_value = l;
9059
9060         l -= G.memleak_value;
9061         if ((long)l < 0)
9062                 l = 0;
9063         l /= 1024;
9064         if (l > 127)
9065                 l = 127;
9066
9067         /* Exitcode is "how many kilobytes we leaked since 1st call" */
9068         return l;
9069 }
9070 #endif
9071
9072 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9073 {
9074         puts(get_cwd(0));
9075         return EXIT_SUCCESS;
9076 }
9077
9078 /* Interruptibility of read builtin in bash
9079  * (tested on bash-4.2.8 by sending signals (not by ^C)):
9080  *
9081  * Empty trap makes read ignore corresponding signal, for any signal.
9082  *
9083  * SIGINT:
9084  * - terminates non-interactive shell;
9085  * - interrupts read in interactive shell;
9086  * if it has non-empty trap:
9087  * - executes trap and returns to command prompt in interactive shell;
9088  * - executes trap and returns to read in non-interactive shell;
9089  * SIGTERM:
9090  * - is ignored (does not interrupt) read in interactive shell;
9091  * - terminates non-interactive shell;
9092  * if it has non-empty trap:
9093  * - executes trap and returns to read;
9094  * SIGHUP:
9095  * - terminates shell (regardless of interactivity);
9096  * if it has non-empty trap:
9097  * - executes trap and returns to read;
9098  */
9099 static int FAST_FUNC builtin_read(char **argv)
9100 {
9101         const char *r;
9102         char *opt_n = NULL;
9103         char *opt_p = NULL;
9104         char *opt_t = NULL;
9105         char *opt_u = NULL;
9106         const char *ifs;
9107         int read_flags;
9108
9109         /* "!": do not abort on errors.
9110          * Option string must start with "sr" to match BUILTIN_READ_xxx
9111          */
9112         read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9113         if (read_flags == (uint32_t)-1)
9114                 return EXIT_FAILURE;
9115         argv += optind;
9116         ifs = get_local_var_value("IFS"); /* can be NULL */
9117
9118  again:
9119         r = shell_builtin_read(set_local_var_from_halves,
9120                 argv,
9121                 ifs,
9122                 read_flags,
9123                 opt_n,
9124                 opt_p,
9125                 opt_t,
9126                 opt_u
9127         );
9128
9129         if ((uintptr_t)r == 1 && errno == EINTR) {
9130                 unsigned sig = check_and_run_traps();
9131                 if (sig && sig != SIGINT)
9132                         goto again;
9133         }
9134
9135         if ((uintptr_t)r > 1) {
9136                 bb_error_msg("%s", r);
9137                 r = (char*)(uintptr_t)1;
9138         }
9139
9140         return (uintptr_t)r;
9141 }
9142
9143 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9144  * built-in 'set' handler
9145  * SUSv3 says:
9146  * set [-abCefhmnuvx] [-o option] [argument...]
9147  * set [+abCefhmnuvx] [+o option] [argument...]
9148  * set -- [argument...]
9149  * set -o
9150  * set +o
9151  * Implementations shall support the options in both their hyphen and
9152  * plus-sign forms. These options can also be specified as options to sh.
9153  * Examples:
9154  * Write out all variables and their values: set
9155  * Set $1, $2, and $3 and set "$#" to 3: set c a b
9156  * Turn on the -x and -v options: set -xv
9157  * Unset all positional parameters: set --
9158  * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9159  * Set the positional parameters to the expansion of x, even if x expands
9160  * with a leading '-' or '+': set -- $x
9161  *
9162  * So far, we only support "set -- [argument...]" and some of the short names.
9163  */
9164 static int FAST_FUNC builtin_set(char **argv)
9165 {
9166         int n;
9167         char **pp, **g_argv;
9168         char *arg = *++argv;
9169
9170         if (arg == NULL) {
9171                 struct variable *e;
9172                 for (e = G.top_var; e; e = e->next)
9173                         puts(e->varstr);
9174                 return EXIT_SUCCESS;
9175         }
9176
9177         do {
9178                 if (strcmp(arg, "--") == 0) {
9179                         ++argv;
9180                         goto set_argv;
9181                 }
9182                 if (arg[0] != '+' && arg[0] != '-')
9183                         break;
9184                 for (n = 1; arg[n]; ++n) {
9185                         if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9186                                 goto error;
9187                         if (arg[n] == 'o' && argv[1])
9188                                 argv++;
9189                 }
9190         } while ((arg = *++argv) != NULL);
9191         /* Now argv[0] is 1st argument */
9192
9193         if (arg == NULL)
9194                 return EXIT_SUCCESS;
9195  set_argv:
9196
9197         /* NB: G.global_argv[0] ($0) is never freed/changed */
9198         g_argv = G.global_argv;
9199         if (G.global_args_malloced) {
9200                 pp = g_argv;
9201                 while (*++pp)
9202                         free(*pp);
9203                 g_argv[1] = NULL;
9204         } else {
9205                 G.global_args_malloced = 1;
9206                 pp = xzalloc(sizeof(pp[0]) * 2);
9207                 pp[0] = g_argv[0]; /* retain $0 */
9208                 g_argv = pp;
9209         }
9210         /* This realloc's G.global_argv */
9211         G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9212
9213         n = 1;
9214         while (*++pp)
9215                 n++;
9216         G.global_argc = n;
9217
9218         return EXIT_SUCCESS;
9219
9220         /* Nothing known, so abort */
9221  error:
9222         bb_error_msg("set: %s: invalid option", arg);
9223         return EXIT_FAILURE;
9224 }
9225
9226 static int FAST_FUNC builtin_shift(char **argv)
9227 {
9228         int n = 1;
9229         argv = skip_dash_dash(argv);
9230         if (argv[0]) {
9231                 n = atoi(argv[0]);
9232         }
9233         if (n >= 0 && n < G.global_argc) {
9234                 if (G.global_args_malloced) {
9235                         int m = 1;
9236                         while (m <= n)
9237                                 free(G.global_argv[m++]);
9238                 }
9239                 G.global_argc -= n;
9240                 memmove(&G.global_argv[1], &G.global_argv[n+1],
9241                                 G.global_argc * sizeof(G.global_argv[0]));
9242                 return EXIT_SUCCESS;
9243         }
9244         return EXIT_FAILURE;
9245 }
9246
9247 static int FAST_FUNC builtin_source(char **argv)
9248 {
9249         char *arg_path, *filename;
9250         FILE *input;
9251         save_arg_t sv;
9252 #if ENABLE_HUSH_FUNCTIONS
9253         smallint sv_flg;
9254 #endif
9255
9256         argv = skip_dash_dash(argv);
9257         filename = argv[0];
9258         if (!filename) {
9259                 /* bash says: "bash: .: filename argument required" */
9260                 return 2; /* bash compat */
9261         }
9262         arg_path = NULL;
9263         if (!strchr(filename, '/')) {
9264                 arg_path = find_in_path(filename);
9265                 if (arg_path)
9266                         filename = arg_path;
9267         }
9268         input = remember_FILE(fopen_or_warn(filename, "r"));
9269         free(arg_path);
9270         if (!input) {
9271                 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
9272                 /* POSIX: non-interactive shell should abort here,
9273                  * not merely fail. So far no one complained :)
9274                  */
9275                 return EXIT_FAILURE;
9276         }
9277
9278 #if ENABLE_HUSH_FUNCTIONS
9279         sv_flg = G_flag_return_in_progress;
9280         /* "we are inside sourced file, ok to use return" */
9281         G_flag_return_in_progress = -1;
9282 #endif
9283         if (argv[1])
9284                 save_and_replace_G_args(&sv, argv);
9285
9286         /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9287         G.last_exitcode = 0;
9288         parse_and_run_file(input);
9289         fclose_and_forget(input);
9290
9291         if (argv[1])
9292                 restore_G_args(&sv, argv);
9293 #if ENABLE_HUSH_FUNCTIONS
9294         G_flag_return_in_progress = sv_flg;
9295 #endif
9296
9297         return G.last_exitcode;
9298 }
9299
9300 static int FAST_FUNC builtin_umask(char **argv)
9301 {
9302         int rc;
9303         mode_t mask;
9304
9305         rc = 1;
9306         mask = umask(0);
9307         argv = skip_dash_dash(argv);
9308         if (argv[0]) {
9309                 mode_t old_mask = mask;
9310
9311                 /* numeric umasks are taken as-is */
9312                 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9313                 if (!isdigit(argv[0][0]))
9314                         mask ^= 0777;
9315                 mask = bb_parse_mode(argv[0], mask);
9316                 if (!isdigit(argv[0][0]))
9317                         mask ^= 0777;
9318                 if ((unsigned)mask > 0777) {
9319                         mask = old_mask;
9320                         /* bash messages:
9321                          * bash: umask: 'q': invalid symbolic mode operator
9322                          * bash: umask: 999: octal number out of range
9323                          */
9324                         bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9325                         rc = 0;
9326                 }
9327         } else {
9328                 /* Mimic bash */
9329                 printf("%04o\n", (unsigned) mask);
9330                 /* fall through and restore mask which we set to 0 */
9331         }
9332         umask(mask);
9333
9334         return !rc; /* rc != 0 - success */
9335 }
9336
9337 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9338 static int FAST_FUNC builtin_unset(char **argv)
9339 {
9340         int ret;
9341         unsigned opts;
9342
9343         /* "!": do not abort on errors */
9344         /* "+": stop at 1st non-option */
9345         opts = getopt32(argv, "!+vf");
9346         if (opts == (unsigned)-1)
9347                 return EXIT_FAILURE;
9348         if (opts == 3) {
9349                 bb_error_msg("unset: -v and -f are exclusive");
9350                 return EXIT_FAILURE;
9351         }
9352         argv += optind;
9353
9354         ret = EXIT_SUCCESS;
9355         while (*argv) {
9356                 if (!(opts & 2)) { /* not -f */
9357                         if (unset_local_var(*argv)) {
9358                                 /* unset <nonexistent_var> doesn't fail.
9359                                  * Error is when one tries to unset RO var.
9360                                  * Message was printed by unset_local_var. */
9361                                 ret = EXIT_FAILURE;
9362                         }
9363                 }
9364 #if ENABLE_HUSH_FUNCTIONS
9365                 else {
9366                         unset_func(*argv);
9367                 }
9368 #endif
9369                 argv++;
9370         }
9371         return ret;
9372 }
9373
9374 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9375 static int FAST_FUNC builtin_wait(char **argv)
9376 {
9377         int ret = EXIT_SUCCESS;
9378         int status;
9379
9380         argv = skip_dash_dash(argv);
9381         if (argv[0] == NULL) {
9382                 /* Don't care about wait results */
9383                 /* Note 1: must wait until there are no more children */
9384                 /* Note 2: must be interruptible */
9385                 /* Examples:
9386                  * $ sleep 3 & sleep 6 & wait
9387                  * [1] 30934 sleep 3
9388                  * [2] 30935 sleep 6
9389                  * [1] Done                   sleep 3
9390                  * [2] Done                   sleep 6
9391                  * $ sleep 3 & sleep 6 & wait
9392                  * [1] 30936 sleep 3
9393                  * [2] 30937 sleep 6
9394                  * [1] Done                   sleep 3
9395                  * ^C <-- after ~4 sec from keyboard
9396                  * $
9397                  */
9398                 while (1) {
9399                         int sig;
9400                         sigset_t oldset, allsigs;
9401
9402                         /* waitpid is not interruptible by SA_RESTARTed
9403                          * signals which we use. Thus, this ugly dance:
9404                          */
9405
9406                         /* Make sure possible SIGCHLD is stored in kernel's
9407                          * pending signal mask before we call waitpid.
9408                          * Or else we may race with SIGCHLD, lose it,
9409                          * and get stuck in sigwaitinfo...
9410                          */
9411                         sigfillset(&allsigs);
9412                         sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9413
9414                         if (!sigisemptyset(&G.pending_set)) {
9415                                 /* Crap! we raced with some signal! */
9416                         //      sig = 0;
9417                                 goto restore;
9418                         }
9419
9420                         checkjobs(NULL); /* waitpid(WNOHANG) inside */
9421                         if (errno == ECHILD) {
9422                                 sigprocmask(SIG_SETMASK, &oldset, NULL);
9423                                 break;
9424                         }
9425
9426                         /* Wait for SIGCHLD or any other signal */
9427                         //sig = sigwaitinfo(&allsigs, NULL);
9428                         /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9429                         /* Note: sigsuspend invokes signal handler */
9430                         sigsuspend(&oldset);
9431  restore:
9432                         sigprocmask(SIG_SETMASK, &oldset, NULL);
9433
9434                         /* So, did we get a signal? */
9435                         //if (sig > 0)
9436                         //      raise(sig); /* run handler */
9437                         sig = check_and_run_traps();
9438                         if (sig /*&& sig != SIGCHLD - always true */) {
9439                                 /* see note 2 */
9440                                 ret = 128 + sig;
9441                                 break;
9442                         }
9443                         /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9444                 }
9445                 return ret;
9446         }
9447
9448         /* This is probably buggy wrt interruptible-ness */
9449         while (*argv) {
9450                 pid_t pid = bb_strtou(*argv, NULL, 10);
9451                 if (errno) {
9452                         /* mimic bash message */
9453                         bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9454                         return EXIT_FAILURE;
9455                 }
9456                 if (waitpid(pid, &status, 0) == pid) {
9457                         ret = WEXITSTATUS(status);
9458                         if (WIFSIGNALED(status))
9459                                 ret = 128 + WTERMSIG(status);
9460                 } else {
9461                         bb_perror_msg("wait %s", *argv);
9462                         ret = 127;
9463                 }
9464                 argv++;
9465         }
9466
9467         return ret;
9468 }
9469
9470 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9471 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9472 {
9473         if (argv[1]) {
9474                 def = bb_strtou(argv[1], NULL, 10);
9475                 if (errno || def < def_min || argv[2]) {
9476                         bb_error_msg("%s: bad arguments", argv[0]);
9477                         def = UINT_MAX;
9478                 }
9479         }
9480         return def;
9481 }
9482 #endif
9483
9484 #if ENABLE_HUSH_LOOPS
9485 static int FAST_FUNC builtin_break(char **argv)
9486 {
9487         unsigned depth;
9488         if (G.depth_of_loop == 0) {
9489                 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9490                 /* if we came from builtin_continue(), need to undo "= 1" */
9491                 G.flag_break_continue = 0;
9492                 return EXIT_SUCCESS; /* bash compat */
9493         }
9494         G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
9495
9496         G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9497         if (depth == UINT_MAX)
9498                 G.flag_break_continue = BC_BREAK;
9499         if (G.depth_of_loop < depth)
9500                 G.depth_break_continue = G.depth_of_loop;
9501
9502         return EXIT_SUCCESS;
9503 }
9504
9505 static int FAST_FUNC builtin_continue(char **argv)
9506 {
9507         G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9508         return builtin_break(argv);
9509 }
9510 #endif
9511
9512 #if ENABLE_HUSH_FUNCTIONS
9513 static int FAST_FUNC builtin_return(char **argv)
9514 {
9515         int rc;
9516
9517         if (G_flag_return_in_progress != -1) {
9518                 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9519                 return EXIT_FAILURE; /* bash compat */
9520         }
9521
9522         G_flag_return_in_progress = 1;
9523
9524         /* bash:
9525          * out of range: wraps around at 256, does not error out
9526          * non-numeric param:
9527          * f() { false; return qwe; }; f; echo $?
9528          * bash: return: qwe: numeric argument required  <== we do this
9529          * 255  <== we also do this
9530          */
9531         rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9532         return rc;
9533 }
9534 #endif