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