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