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