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