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