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