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