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