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