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