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