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