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