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