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