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