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