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