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