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