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