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