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