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