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