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