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