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