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