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