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