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