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