implement `wait` builtin
[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  *
10  * Credits:
11  *      The parser routines proper are all original material, first
12  *      written Dec 2000 and Jan 2001 by Larry Doolittle.  The
13  *      execution engine, the builtins, and much of the underlying
14  *      support has been adapted from busybox-0.49pre's lash, which is
15  *      Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16  *      written by Erik Andersen <andersen@codepoet.org>.  That, in turn,
17  *      is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18  *      Troan, which they placed in the public domain.  I don't know
19  *      how much of the Johnson/Troan code has survived the repeated
20  *      rewrites.
21  *
22  * Other credits:
23  *      o_addchr() derived from similar w_addchar function in glibc-2.2.
24  *      setup_redirect(), redirect_opt_num(), and big chunks of main()
25  *      and many builtins derived from contributions by Erik Andersen.
26  *      Miscellaneous bugfixes from Matt Kraai.
27  *
28  * There are two big (and related) architecture differences between
29  * this parser and the lash parser.  One is that this version is
30  * actually designed from the ground up to understand nearly all
31  * of the Bourne grammar.  The second, consequential change is that
32  * the parser and input reader have been turned inside out.  Now,
33  * the parser is in control, and asks for input as needed.  The old
34  * way had the input reader in control, and it asked for parsing to
35  * take place as needed.  The new way makes it much easier to properly
36  * handle the recursion implicit in the various substitutions, especially
37  * across continuation lines.
38  *
39  * POSIX syntax not implemented:
40  *      aliases
41  *      Arithmetic Expansion
42  *      <(list) and >(list) Process Substitution
43  *      Here Documents ( << word )
44  *      Functions
45  *      Tilde Expansion
46  *      Parameter Expansion for substring processing ${var#word} ${var%word}
47  *
48  * Bash stuff maybe optional enable:
49  *      &> and >& redirection of stdout+stderr
50  *      Brace expansion
51  *      reserved words: [[ ]] function select
52  *      substrings ${var:1:5}
53  *
54  * Major bugs:
55  *      job handling woefully incomplete and buggy (improved --vda)
56  * to-do:
57  *      port selected bugfixes from post-0.49 busybox lash - done?
58  *      change { and } from special chars to reserved words
59  *      builtins: return, trap, ulimit
60  *      test magic exec with redirection only
61  *      follow IFS rules more precisely, including update semantics
62  *      figure out what to do with backslash-newline
63  *      propagate syntax errors, die on resource errors?
64  *      continuation lines, both explicit and implicit - done?
65  *      maybe change charmap[] to use 2-bit entries
66  *
67  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
68  */
69
70 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
71 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
72 //#include "applet_tables.h" doesn't work
73 #include <glob.h>
74 /* #include <dmalloc.h> */
75 #if ENABLE_HUSH_CASE
76 #include <fnmatch.h>
77 #endif
78
79 #define HUSH_VER_STR "0.92"
80
81 #if defined SINGLE_APPLET_MAIN
82 /* STANDALONE does not make sense, and won't compile */
83 #undef CONFIG_FEATURE_SH_STANDALONE
84 #undef ENABLE_FEATURE_SH_STANDALONE
85 #undef USE_FEATURE_SH_STANDALONE
86 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87 #define ENABLE_FEATURE_SH_STANDALONE 0
88 #define USE_FEATURE_SH_STANDALONE(...)
89 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
90 #endif
91
92 #if !BB_MMU && ENABLE_HUSH_TICK
93 //#undef ENABLE_HUSH_TICK
94 //#define ENABLE_HUSH_TICK 0
95 #warning On NOMMU, hush command substitution is dangerous.
96 #warning Dont use it for commands which produce lots of output.
97 #warning For more info see shell/hush.c, generate_stream_from_list().
98 #endif
99
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
105 #endif
106
107 /* Do we support ANY keywords? */
108 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109 #define HAS_KEYWORDS 1
110 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
111 #define IF_HAS_NO_KEYWORDS(...)
112 #else
113 #define HAS_KEYWORDS 0
114 #define IF_HAS_KEYWORDS(...)
115 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
116 #endif
117
118 /* Keep unconditionally on for now */
119 #define HUSH_DEBUG 1
120 /* In progress... */
121 #define ENABLE_HUSH_FUNCTIONS 0
122
123
124 /* If you comment out one of these below, it will be #defined later
125  * to perform debug printfs to stderr: */
126 #define debug_printf(...)        do {} while (0)
127 /* Finer-grained debug switches */
128 #define debug_printf_parse(...)  do {} while (0)
129 #define debug_print_tree(a, b)   do {} while (0)
130 #define debug_printf_exec(...)   do {} while (0)
131 #define debug_printf_env(...)    do {} while (0)
132 #define debug_printf_jobs(...)   do {} while (0)
133 #define debug_printf_expand(...) do {} while (0)
134 #define debug_printf_glob(...)   do {} while (0)
135 #define debug_printf_list(...)   do {} while (0)
136 #define debug_printf_subst(...)  do {} while (0)
137 #define debug_printf_clean(...)  do {} while (0)
138
139 #ifndef debug_printf
140 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
141 #endif
142
143 #ifndef debug_printf_parse
144 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
145 #endif
146
147 #ifndef debug_printf_exec
148 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
149 #endif
150
151 #ifndef debug_printf_env
152 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
153 #endif
154
155 #ifndef debug_printf_jobs
156 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
157 #define DEBUG_JOBS 1
158 #else
159 #define DEBUG_JOBS 0
160 #endif
161
162 #ifndef debug_printf_expand
163 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164 #define DEBUG_EXPAND 1
165 #else
166 #define DEBUG_EXPAND 0
167 #endif
168
169 #ifndef debug_printf_glob
170 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
171 #define DEBUG_GLOB 1
172 #else
173 #define DEBUG_GLOB 0
174 #endif
175
176 #ifndef debug_printf_list
177 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
178 #endif
179
180 #ifndef debug_printf_subst
181 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
182 #endif
183
184 #ifndef debug_printf_clean
185 /* broken, of course, but OK for testing */
186 static const char *indenter(int i)
187 {
188         static const char blanks[] ALIGN1 =
189                 "                                    ";
190         return &blanks[sizeof(blanks) - i - 1];
191 }
192 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
193 #define DEBUG_CLEAN 1
194 #endif
195
196 #if DEBUG_EXPAND
197 static void debug_print_strings(const char *prefix, char **vv)
198 {
199         fprintf(stderr, "%s:\n", prefix);
200         while (*vv)
201                 fprintf(stderr, " '%s'\n", *vv++);
202 }
203 #else
204 #define debug_print_strings(prefix, vv) ((void)0)
205 #endif
206
207 /*
208  * Leak hunting. Use hush_leaktool.sh for post-processing.
209  */
210 #ifdef FOR_HUSH_LEAKTOOL
211 /* suppress "warning: no previous prototype..." */
212 void *xxmalloc(int lineno, size_t size);
213 void *xxrealloc(int lineno, void *ptr, size_t size);
214 char *xxstrdup(int lineno, const char *str);
215 void xxfree(void *ptr);
216 void *xxmalloc(int lineno, size_t size)
217 {
218         void *ptr = xmalloc((size + 0xff) & ~0xff);
219         fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
220         return ptr;
221 }
222 void *xxrealloc(int lineno, void *ptr, size_t size)
223 {
224         ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
225         fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
226         return ptr;
227 }
228 char *xxstrdup(int lineno, const char *str)
229 {
230         char *ptr = xstrdup(str);
231         fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
232         return ptr;
233 }
234 void xxfree(void *ptr)
235 {
236         fprintf(stderr, "free %p\n", ptr);
237         free(ptr);
238 }
239 #define xmalloc(s)     xxmalloc(__LINE__, s)
240 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
241 #define xstrdup(s)     xxstrdup(__LINE__, s)
242 #define free(p)        xxfree(p)
243 #endif
244
245
246 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
247
248 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
249
250 #define SPECIAL_VAR_SYMBOL       3
251 #define PARSEFLAG_EXIT_FROM_LOOP 1
252
253 typedef enum redir_type {
254         REDIRECT_INPUT     = 1,
255         REDIRECT_OVERWRITE = 2,
256         REDIRECT_APPEND    = 3,
257         REDIRECT_HEREIS    = 4,
258         REDIRECT_IO        = 5
259 } redir_type;
260
261 /* The descrip member of this structure is only used to make
262  * debugging output pretty */
263 static const struct {
264         int mode;
265         signed char default_fd;
266         char descrip[3];
267 } redir_table[] = {
268         { 0,                         0, "()" },
269         { O_RDONLY,                  0, "<"  },
270         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
271         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272         { O_RDONLY,                 -1, "<<" },
273         { O_RDWR,                    1, "<>" }
274 };
275
276 typedef enum pipe_style {
277         PIPE_SEQ = 1,
278         PIPE_AND = 2,
279         PIPE_OR  = 3,
280         PIPE_BG  = 4,
281 } pipe_style;
282
283 typedef enum reserved_style {
284         RES_NONE  = 0,
285 #if ENABLE_HUSH_IF
286         RES_IF    ,
287         RES_THEN  ,
288         RES_ELIF  ,
289         RES_ELSE  ,
290         RES_FI    ,
291 #endif
292 #if ENABLE_HUSH_LOOPS
293         RES_FOR   ,
294         RES_WHILE ,
295         RES_UNTIL ,
296         RES_DO    ,
297         RES_DONE  ,
298 #endif
299 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
300         RES_IN    ,
301 #endif
302 #if ENABLE_HUSH_CASE
303         RES_CASE  ,
304         /* two pseudo-keywords support contrived "case" syntax: */
305         RES_MATCH , /* "word)" */
306         RES_CASEI , /* "this command is inside CASE" */
307         RES_ESAC  ,
308 #endif
309         RES_XXXX  ,
310         RES_SNTX
311 } reserved_style;
312
313 struct redir_struct {
314         struct redir_struct *next;
315         char *rd_filename;          /* filename */
316         int fd;                     /* file descriptor being redirected */
317         int dup;                    /* -1, or file descriptor being duplicated */
318         smallint /*enum redir_type*/ rd_type;
319 };
320
321 struct command {
322         pid_t pid;                  /* 0 if exited */
323         int assignment_cnt;         /* how many argv[i] are assignments? */
324         smallint is_stopped;        /* is the command currently running? */
325         smallint grp_type;          /* GRP_xxx */
326         struct pipe *group;         /* if non-NULL, this "prog" is {} group,
327                                      * subshell, or a compound statement */
328         char **argv;                /* command name and arguments */
329         struct redir_struct *redirects; /* I/O redirections */
330 };
331 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
332  * and on execution these are substituted with their values.
333  * Substitution can make _several_ words out of one argv[n]!
334  * Example: argv[0]=='.^C*^C.' here: echo .$*.
335  * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
336  */
337 #define GRP_NORMAL   0
338 #define GRP_SUBSHELL 1
339 #if ENABLE_HUSH_FUNCTIONS
340 #define GRP_FUNCTION 2
341 #endif
342
343 struct pipe {
344         struct pipe *next;
345         int num_cmds;               /* total number of commands in job */
346         int alive_cmds;             /* number of commands running (not exited) */
347         int stopped_cmds;           /* number of commands alive, but stopped */
348 #if ENABLE_HUSH_JOB
349         int jobid;                  /* job number */
350         pid_t pgrp;                 /* process group ID for the job */
351         char *cmdtext;              /* name of job */
352 #endif
353         struct command *cmds;       /* array of commands in pipe */
354         smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
355         IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356         IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
357 };
358
359 /* This holds pointers to the various results of parsing */
360 struct parse_context {
361         struct command *command;
362         struct pipe *list_head;
363         struct pipe *pipe;
364         struct redir_struct *pending_redirect;
365 #if HAS_KEYWORDS
366         smallint ctx_res_w;
367         smallint ctx_inverted; /* "! cmd | cmd" */
368 #if ENABLE_HUSH_CASE
369         smallint ctx_dsemicolon; /* ";;" seen */
370 #endif
371         int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
372         struct parse_context *stack;
373 #endif
374 };
375
376 /* On program start, environ points to initial environment.
377  * putenv adds new pointers into it, unsetenv removes them.
378  * Neither of these (de)allocates the strings.
379  * setenv allocates new strings in malloc space and does putenv,
380  * and thus setenv is unusable (leaky) for shell's purposes */
381 #define setenv(...) setenv_is_leaky_dont_use()
382 struct variable {
383         struct variable *next;
384         char *varstr;        /* points to "name=" portion */
385         int max_len;         /* if > 0, name is part of initial env; else name is malloced */
386         smallint flg_export; /* putenv should be done on this var */
387         smallint flg_read_only;
388 };
389
390 typedef struct o_string {
391         char *data;
392         int length; /* position where data is appended */
393         int maxlen;
394         /* Misnomer! it's not "quoting", it's "protection against globbing"!
395          * (by prepending \ to *, ?, [ and to \ too) */
396         smallint o_quote;
397         smallint o_glob;
398         smallint nonnull;
399         smallint has_empty_slot;
400         smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
401 } o_string;
402 enum {
403         MAYBE_ASSIGNMENT = 0,
404         DEFINITELY_ASSIGNMENT = 1,
405         NOT_ASSIGNMENT = 2,
406         WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
407 };
408 /* Used for initialization: o_string foo = NULL_O_STRING; */
409 #define NULL_O_STRING { NULL }
410
411 /* I can almost use ordinary FILE*.  Is open_memstream() universally
412  * available?  Where is it documented? */
413 typedef struct in_str {
414         const char *p;
415         /* eof_flag=1: last char in ->p is really an EOF */
416         char eof_flag; /* meaningless if ->p == NULL */
417         char peek_buf[2];
418 #if ENABLE_HUSH_INTERACTIVE
419         smallint promptme;
420         smallint promptmode; /* 0: PS1, 1: PS2 */
421 #endif
422         FILE *file;
423         int (*get) (struct in_str *);
424         int (*peek) (struct in_str *);
425 } in_str;
426 #define i_getch(input) ((input)->get(input))
427 #define i_peek(input) ((input)->peek(input))
428
429 enum {
430         CHAR_ORDINARY           = 0,
431         CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
432         CHAR_IFS                = 2, /* treated as ordinary if quoted */
433         CHAR_SPECIAL            = 3, /* example: $ */
434 };
435
436 enum {
437         BC_BREAK = 1,
438         BC_CONTINUE = 2,
439 };
440
441
442 /* "Globals" within this file */
443 /* Sorted roughly by size (smaller offsets == smaller code) */
444 struct globals {
445 #if ENABLE_HUSH_INTERACTIVE
446         /* 'interactive_fd' is a fd# open to ctty, if we have one
447          * _AND_ if we decided to act interactively */
448         int interactive_fd;
449         const char *PS1;
450         const char *PS2;
451 #endif
452 #if ENABLE_FEATURE_EDITING
453         line_input_t *line_input_state;
454 #endif
455         pid_t root_pid;
456         pid_t last_bg_pid;
457 #if ENABLE_HUSH_JOB
458         int run_list_level;
459         pid_t saved_tty_pgrp;
460         int last_jobid;
461         struct pipe *job_list;
462         struct pipe *toplevel_list;
463         smallint ctrl_z_flag;
464 #endif
465 #if ENABLE_HUSH_LOOPS
466         smallint flag_break_continue;
467 #endif
468         smallint fake_mode;
469         /* these three support $?, $#, and $1 */
470         smalluint last_return_code;
471         /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
472         smalluint global_args_malloced;
473         /* how many non-NULL argv's we have. NB: $# + 1 */
474         int global_argc;
475         char **global_argv;
476 #if ENABLE_HUSH_LOOPS
477         unsigned depth_break_continue;
478         unsigned depth_of_loop;
479 #endif
480         const char *ifs;
481         const char *cwd;
482         struct variable *top_var; /* = &G.shell_ver (set in main()) */
483         struct variable shell_ver;
484 #if ENABLE_FEATURE_SH_STANDALONE
485         struct nofork_save_area nofork_save;
486 #endif
487 #if ENABLE_HUSH_JOB
488         sigjmp_buf toplevel_jb;
489 #endif
490         unsigned char charmap[256];
491         char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
492 };
493
494 #define G (*ptr_to_globals)
495 /* Not #defining name to G.name - this quickly gets unwieldy
496  * (too many defines). Also, I actually prefer to see when a variable
497  * is global, thus "G." prefix is a useful hint */
498 #define INIT_G() do { \
499         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
500 } while (0)
501
502
503 /* Function prototypes for builtins */
504 static int builtin_cd(char **argv);
505 static int builtin_echo(char **argv);
506 static int builtin_eval(char **argv);
507 static int builtin_exec(char **argv);
508 static int builtin_exit(char **argv);
509 static int builtin_export(char **argv);
510 #if ENABLE_HUSH_JOB
511 static int builtin_fg_bg(char **argv);
512 static int builtin_jobs(char **argv);
513 #endif
514 #if ENABLE_HUSH_HELP
515 static int builtin_help(char **argv);
516 #endif
517 static int builtin_pwd(char **argv);
518 static int builtin_read(char **argv);
519 static int builtin_test(char **argv);
520 static int builtin_true(char **argv);
521 static int builtin_set(char **argv);
522 static int builtin_set_mode(const char, const char);
523 static int builtin_shift(char **argv);
524 static int builtin_source(char **argv);
525 static int builtin_umask(char **argv);
526 static int builtin_unset(char **argv);
527 static int builtin_wait(char **argv);
528 #if ENABLE_HUSH_LOOPS
529 static int builtin_break(char **argv);
530 static int builtin_continue(char **argv);
531 #endif
532 //static int builtin_not_written(char **argv);
533
534 /* Table of built-in functions.  They can be forked or not, depending on
535  * context: within pipes, they fork.  As simple commands, they do not.
536  * When used in non-forking context, they can change global variables
537  * in the parent shell process.  If forked, of course they cannot.
538  * For example, 'unset foo | whatever' will parse and run, but foo will
539  * still be set at the end. */
540 struct built_in_command {
541         const char *cmd;
542         int (*function)(char **argv);
543 #if ENABLE_HUSH_HELP
544         const char *descr;
545 #define BLTIN(cmd, func, help) { cmd, func, help }
546 #else
547 #define BLTIN(cmd, func, help) { cmd, func }
548 #endif
549 };
550
551 /* For now, echo and test are unconditionally enabled.
552  * Maybe make it configurable? */
553 static const struct built_in_command bltins[] = {
554         BLTIN("."     , builtin_source, "Run commands in a file"),
555         BLTIN(":"     , builtin_true, "No-op"),
556         BLTIN("["     , builtin_test, "Test condition"),
557 #if ENABLE_HUSH_JOB
558         BLTIN("bg"    , builtin_fg_bg, "Resume a job in the background"),
559 #endif
560 #if ENABLE_HUSH_LOOPS
561         BLTIN("break" , builtin_break, "Exit from a loop"),
562 #endif
563         BLTIN("cd"    , builtin_cd, "Change directory"),
564 #if ENABLE_HUSH_LOOPS
565         BLTIN("continue", builtin_continue, "Start new loop iteration"),
566 #endif
567         BLTIN("echo"  , builtin_echo, "Write to stdout"),
568         BLTIN("eval"  , builtin_eval, "Construct and run shell command"),
569         BLTIN("exec"  , builtin_exec, "Execute command, don't return to shell"),
570         BLTIN("exit"  , builtin_exit, "Exit"),
571         BLTIN("export", builtin_export, "Set environment variable"),
572 #if ENABLE_HUSH_JOB
573         BLTIN("fg"    , builtin_fg_bg, "Bring job into the foreground"),
574         BLTIN("jobs"  , builtin_jobs, "List active jobs"),
575 #endif
576         BLTIN("pwd"   , builtin_pwd, "Print current directory"),
577         BLTIN("read"  , builtin_read, "Input environment variable"),
578 //      BLTIN("return", builtin_not_written, "Return from a function"),
579         BLTIN("set"   , builtin_set, "Set/unset shell local variables"),
580         BLTIN("shift" , builtin_shift, "Shift positional parameters"),
581 //      BLTIN("trap"  , builtin_not_written, "Trap signals"),
582         BLTIN("test"  , builtin_test, "Test condition"),
583 //      BLTIN("ulimit", builtin_not_written, "Control resource limits"),
584         BLTIN("umask" , builtin_umask, "Set file creation mask"),
585         BLTIN("unset" , builtin_unset, "Unset environment variable"),
586         BLTIN("wait"  , builtin_wait, "Wait for process"),
587 #if ENABLE_HUSH_HELP
588         BLTIN("help"  , builtin_help, "List shell built-in commands"),
589 #endif
590 };
591
592
593 /* Normal */
594 static void maybe_die(const char *notice, const char *msg)
595 {
596         /* Was using fancy stuff:
597          * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
598          * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
599         void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
600 #if ENABLE_HUSH_INTERACTIVE
601         fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
602 #endif
603         fp(msg ? "%s: %s" : notice, notice, msg);
604 }
605 #if 1
606 #define syntax(msg) maybe_die("syntax error", msg);
607 #else
608 /* Debug -- trick gcc to expand __LINE__ and convert to string */
609 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
610 #define _syntax(msg, line) __syntax(msg, line)
611 #define syntax(msg) _syntax(msg, __LINE__)
612 #endif
613
614 static int glob_needed(const char *s)
615 {
616         while (*s) {
617                 if (*s == '\\')
618                         s++;
619                 if (*s == '*' || *s == '[' || *s == '?')
620                         return 1;
621                 s++;
622         }
623         return 0;
624 }
625
626 static int is_assignment(const char *s)
627 {
628         if (!s || !(isalpha(*s) || *s == '_'))
629                 return 0;
630         s++;
631         while (isalnum(*s) || *s == '_')
632                 s++;
633         return *s == '=';
634 }
635
636 /* Replace each \x with x in place, return ptr past NUL. */
637 static char *unbackslash(char *src)
638 {
639         char *dst = src;
640         while (1) {
641                 if (*src == '\\')
642                         src++;
643                 if ((*dst++ = *src++) == '\0')
644                         break;
645         }
646         return dst;
647 }
648
649 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
650 {
651         int i;
652         unsigned count1;
653         unsigned count2;
654         char **v;
655
656         v = strings;
657         count1 = 0;
658         if (v) {
659                 while (*v) {
660                         count1++;
661                         v++;
662                 }
663         }
664         count2 = 0;
665         v = add;
666         while (*v) {
667                 count2++;
668                 v++;
669         }
670         v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671         v[count1 + count2] = NULL;
672         i = count2;
673         while (--i >= 0)
674                 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
675         return v;
676 }
677
678 static char **add_string_to_strings(char **strings, char *add)
679 {
680         char *v[2];
681         v[0] = add;
682         v[1] = NULL;
683         return add_strings_to_strings(strings, v, /*dup:*/ 0);
684 }
685
686 static void putenv_all(char **strings)
687 {
688         if (!strings)
689                 return;
690         while (*strings) {
691                 debug_printf_env("putenv '%s'\n", *strings);
692                 putenv(*strings++);
693         }
694 }
695
696 static char **putenv_all_and_save_old(char **strings)
697 {
698         char **old = NULL;
699         char **s = strings;
700
701         if (!strings)
702                 return old;
703         while (*strings) {
704                 char *v, *eq;
705
706                 eq = strchr(*strings, '=');
707                 if (eq) {
708                         *eq = '\0';
709                         v = getenv(*strings);
710                         *eq = '=';
711                         if (v) {
712                                 /* v points to VAL in VAR=VAL, go back to VAR */
713                                 v -= (eq - *strings) + 1;
714                                 old = add_string_to_strings(old, v);
715                         }
716                 }
717                 strings++;
718         }
719         putenv_all(s);
720         return old;
721 }
722
723 static void free_strings_and_unsetenv(char **strings, int unset)
724 {
725         char **v;
726
727         if (!strings)
728                 return;
729
730         v = strings;
731         while (*v) {
732                 if (unset) {
733                         debug_printf_env("unsetenv '%s'\n", *v);
734                         bb_unsetenv(*v);
735                 }
736                 free(*v++);
737         }
738         free(strings);
739 }
740
741 static void free_strings(char **strings)
742 {
743         free_strings_and_unsetenv(strings, 0);
744 }
745
746
747 /* Signals are grouped, we handle them in batches */
748 static void set_misc_sighandler(void (*handler)(int))
749 {
750         bb_signals(0
751                 + (1 << SIGINT)
752                 + (1 << SIGQUIT)
753                 + (1 << SIGTERM)
754                 , handler);
755 }
756
757 #if ENABLE_HUSH_JOB
758
759 static void set_fatal_sighandler(void (*handler)(int))
760 {
761         bb_signals(0
762                 + (1 << SIGILL)
763                 + (1 << SIGTRAP)
764                 + (1 << SIGABRT)
765                 + (1 << SIGFPE)
766                 + (1 << SIGBUS)
767                 + (1 << SIGSEGV)
768         /* bash 3.2 seems to handle these just like 'fatal' ones */
769                 + (1 << SIGHUP)
770                 + (1 << SIGPIPE)
771                 + (1 << SIGALRM)
772                 , handler);
773 }
774 static void set_jobctrl_sighandler(void (*handler)(int))
775 {
776         bb_signals(0
777                 + (1 << SIGTSTP)
778                 + (1 << SIGTTIN)
779                 + (1 << SIGTTOU)
780                 , handler);
781 }
782 /* SIGCHLD is special and handled separately */
783
784 static void set_every_sighandler(void (*handler)(int))
785 {
786         set_fatal_sighandler(handler);
787         set_jobctrl_sighandler(handler);
788         set_misc_sighandler(handler);
789         signal(SIGCHLD, handler);
790 }
791
792 static void handler_ctrl_c(int sig UNUSED_PARAM)
793 {
794         debug_printf_jobs("got sig %d\n", sig);
795 // as usual we can have all kinds of nasty problems with leaked malloc data here
796         siglongjmp(G.toplevel_jb, 1);
797 }
798
799 static void handler_ctrl_z(int sig UNUSED_PARAM)
800 {
801         pid_t pid;
802
803         debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
804
805         if (!BB_MMU) {
806                 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
807                 return;
808         }
809
810         pid = fork();
811         if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
812                 return;
813         G.ctrl_z_flag = 1;
814         if (!pid) { /* child */
815                 if (ENABLE_HUSH_JOB)
816                         die_sleep = 0; /* let nofork's xfuncs die */
817                 bb_setpgrp();
818                 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
819                 set_every_sighandler(SIG_DFL);
820                 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
821                 debug_printf_jobs("returning in child\n");
822                 /* return to nofork, it will eventually exit now,
823                  * not return back to shell */
824                 return;
825         }
826         /* parent */
827         /* finish filling up pipe info */
828         G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
829         G.toplevel_list->cmds[0].pid = pid;
830         /* parent needs to longjmp out of running nofork.
831          * we will "return" exitcode 0, with child put in background */
832 // as usual we can have all kinds of nasty problems with leaked malloc data here
833         debug_printf_jobs("siglongjmp in parent\n");
834         siglongjmp(G.toplevel_jb, 1);
835 }
836
837 /* Restores tty foreground process group, and exits.
838  * May be called as signal handler for fatal signal
839  * (will faithfully resend signal to itself, producing correct exit state)
840  * or called directly with -EXITCODE.
841  * We also call it if xfunc is exiting. */
842 static void sigexit(int sig) NORETURN;
843 static void sigexit(int sig)
844 {
845         /* Disable all signals: job control, SIGPIPE, etc. */
846         sigprocmask_allsigs(SIG_BLOCK);
847
848 #if ENABLE_HUSH_INTERACTIVE
849         if (G.interactive_fd)
850                 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
851 #endif
852
853         /* Not a signal, just exit */
854         if (sig <= 0)
855                 _exit(- sig);
856
857         kill_myself_with_sig(sig); /* does not return */
858 }
859
860 /* Restores tty foreground process group, and exits. */
861 static void hush_exit(int exitcode) NORETURN;
862 static void hush_exit(int exitcode)
863 {
864         fflush(NULL); /* flush all streams */
865         sigexit(- (exitcode & 0xff));
866 }
867
868 #else /* !JOB */
869
870 #define set_fatal_sighandler(handler)   ((void)0)
871 #define set_jobctrl_sighandler(handler) ((void)0)
872 #define hush_exit(e)                    exit(e)
873
874 #endif /* JOB */
875
876
877 static const char *set_cwd(void)
878 {
879         /* xrealloc_getcwd_or_warn(arg) calls free(arg),
880          * we must not try to free(bb_msg_unknown) */
881         if (G.cwd == bb_msg_unknown)
882                 G.cwd = NULL;
883         G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
884         if (!G.cwd)
885                 G.cwd = bb_msg_unknown;
886         return G.cwd;
887 }
888
889
890 /* Get/check local shell variables */
891 static struct variable *get_local_var(const char *name)
892 {
893         struct variable *cur;
894         int len;
895
896         if (!name)
897                 return NULL;
898         len = strlen(name);
899         for (cur = G.top_var; cur; cur = cur->next) {
900                 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
901                         return cur;
902         }
903         return NULL;
904 }
905
906 /* Basically useful version until someone wants to get fancier,
907  * see the bash man page under "Parameter Expansion" */
908 static const char *lookup_param(const char *src)
909 {
910         struct variable *var = get_local_var(src);
911         if (var)
912                 return strchr(var->varstr, '=') + 1;
913         return NULL;
914 }
915
916 /* str holds "NAME=VAL" and is expected to be malloced.
917  * We take ownership of it.
918  * flg_export is used by:
919  *  0: do not export
920  *  1: export
921  * -1: if NAME is set, leave export status alone
922  *     if NAME is not set, do not export
923  */
924 static int set_local_var(char *str, int flg_export)
925 {
926         struct variable *cur;
927         char *value;
928         int name_len;
929
930         value = strchr(str, '=');
931         if (!value) { /* not expected to ever happen? */
932                 free(str);
933                 return -1;
934         }
935
936         name_len = value - str + 1; /* including '=' */
937         cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
938         while (1) {
939                 if (strncmp(cur->varstr, str, name_len) != 0) {
940                         if (!cur->next) {
941                                 /* Bail out. Note that now cur points
942                                  * to last var in linked list */
943                                 break;
944                         }
945                         cur = cur->next;
946                         continue;
947                 }
948                 /* We found an existing var with this name */
949                 *value = '\0';
950                 if (cur->flg_read_only) {
951                         bb_error_msg("%s: readonly variable", str);
952                         free(str);
953                         return -1;
954                 }
955                 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
956                 unsetenv(str); /* just in case */
957                 *value = '=';
958                 if (strcmp(cur->varstr, str) == 0) {
959  free_and_exp:
960                         free(str);
961                         goto exp;
962                 }
963                 if (cur->max_len >= strlen(str)) {
964                         /* This one is from startup env, reuse space */
965                         strcpy(cur->varstr, str);
966                         goto free_and_exp;
967                 }
968                 /* max_len == 0 signifies "malloced" var, which we can
969                  * (and has to) free */
970                 if (!cur->max_len)
971                         free(cur->varstr);
972                 cur->max_len = 0;
973                 goto set_str_and_exp;
974         }
975
976         /* Not found - create next variable struct */
977         cur->next = xzalloc(sizeof(*cur));
978         cur = cur->next;
979
980  set_str_and_exp:
981         cur->varstr = str;
982  exp:
983         if (flg_export == 1)
984                 cur->flg_export = 1;
985         if (cur->flg_export) {
986                 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
987                 return putenv(cur->varstr);
988         }
989         return 0;
990 }
991
992 static void unset_local_var(const char *name)
993 {
994         struct variable *cur;
995         struct variable *prev = prev; /* for gcc */
996         int name_len;
997
998         if (!name)
999                 return;
1000         name_len = strlen(name);
1001         cur = G.top_var;
1002         while (cur) {
1003                 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1004                         if (cur->flg_read_only) {
1005                                 bb_error_msg("%s: readonly variable", name);
1006                                 return;
1007                         }
1008                         /* prev is ok to use here because 1st variable, HUSH_VERSION,
1009                          * is ro, and we cannot reach this code on the 1st pass */
1010                         prev->next = cur->next;
1011                         debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1012                         bb_unsetenv(cur->varstr);
1013                         if (!cur->max_len)
1014                                 free(cur->varstr);
1015                         free(cur);
1016                         return;
1017                 }
1018                 prev = cur;
1019                 cur = cur->next;
1020         }
1021 }
1022
1023
1024 /*
1025  * in_str support
1026  */
1027 static int static_get(struct in_str *i)
1028 {
1029         int ch = *i->p++;
1030         if (ch == '\0') return EOF;
1031         return ch;
1032 }
1033
1034 static int static_peek(struct in_str *i)
1035 {
1036         return *i->p;
1037 }
1038
1039 #if ENABLE_HUSH_INTERACTIVE
1040
1041 static void cmdedit_set_initial_prompt(void)
1042 {
1043         if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1044                 G.PS1 = getenv("PS1");
1045                 if (G.PS1 == NULL)
1046                         G.PS1 = "\\w \\$ ";
1047         } else
1048                 G.PS1 = NULL;
1049 }
1050
1051 static const char* setup_prompt_string(int promptmode)
1052 {
1053         const char *prompt_str;
1054         debug_printf("setup_prompt_string %d ", promptmode);
1055         if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1056                 /* Set up the prompt */
1057                 if (promptmode == 0) { /* PS1 */
1058                         free((char*)G.PS1);
1059                         G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1060                         prompt_str = G.PS1;
1061                 } else
1062                         prompt_str = G.PS2;
1063         } else
1064                 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1065         debug_printf("result '%s'\n", prompt_str);
1066         return prompt_str;
1067 }
1068
1069 static void get_user_input(struct in_str *i)
1070 {
1071         int r;
1072         const char *prompt_str;
1073
1074         prompt_str = setup_prompt_string(i->promptmode);
1075 #if ENABLE_FEATURE_EDITING
1076         /* Enable command line editing only while a command line
1077          * is actually being read */
1078         do {
1079                 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1080         } while (r == 0); /* repeat if Ctrl-C */
1081         i->eof_flag = (r < 0);
1082         if (i->eof_flag) { /* EOF/error detected */
1083                 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1084                 G.user_input_buf[1] = '\0';
1085         }
1086 #else
1087         fputs(prompt_str, stdout);
1088         fflush(stdout);
1089         G.user_input_buf[0] = r = fgetc(i->file);
1090         /*G.user_input_buf[1] = '\0'; - already is and never changed */
1091         i->eof_flag = (r == EOF);
1092 #endif
1093         i->p = G.user_input_buf;
1094 }
1095
1096 #endif  /* INTERACTIVE */
1097
1098 /* This is the magic location that prints prompts
1099  * and gets data back from the user */
1100 static int file_get(struct in_str *i)
1101 {
1102         int ch;
1103
1104         /* If there is data waiting, eat it up */
1105         if (i->p && *i->p) {
1106 #if ENABLE_HUSH_INTERACTIVE
1107  take_cached:
1108 #endif
1109                 ch = *i->p++;
1110                 if (i->eof_flag && !*i->p)
1111                         ch = EOF;
1112         } else {
1113                 /* need to double check i->file because we might be doing something
1114                  * more complicated by now, like sourcing or substituting. */
1115 #if ENABLE_HUSH_INTERACTIVE
1116                 if (G.interactive_fd && i->promptme && i->file == stdin) {
1117                         do {
1118                                 get_user_input(i);
1119                         } while (!*i->p); /* need non-empty line */
1120                         i->promptmode = 1; /* PS2 */
1121                         i->promptme = 0;
1122                         goto take_cached;
1123                 }
1124 #endif
1125                 ch = fgetc(i->file);
1126         }
1127         debug_printf("file_get: got a '%c' %d\n", ch, ch);
1128 #if ENABLE_HUSH_INTERACTIVE
1129         if (ch == '\n')
1130                 i->promptme = 1;
1131 #endif
1132         return ch;
1133 }
1134
1135 /* All the callers guarantee this routine will never be
1136  * used right after a newline, so prompting is not needed.
1137  */
1138 static int file_peek(struct in_str *i)
1139 {
1140         int ch;
1141         if (i->p && *i->p) {
1142                 if (i->eof_flag && !i->p[1])
1143                         return EOF;
1144                 return *i->p;
1145         }
1146         ch = fgetc(i->file);
1147         i->eof_flag = (ch == EOF);
1148         i->peek_buf[0] = ch;
1149         i->peek_buf[1] = '\0';
1150         i->p = i->peek_buf;
1151         debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1152         return ch;
1153 }
1154
1155 static void setup_file_in_str(struct in_str *i, FILE *f)
1156 {
1157         i->peek = file_peek;
1158         i->get = file_get;
1159 #if ENABLE_HUSH_INTERACTIVE
1160         i->promptme = 1;
1161         i->promptmode = 0; /* PS1 */
1162 #endif
1163         i->file = f;
1164         i->p = NULL;
1165 }
1166
1167 static void setup_string_in_str(struct in_str *i, const char *s)
1168 {
1169         i->peek = static_peek;
1170         i->get = static_get;
1171 #if ENABLE_HUSH_INTERACTIVE
1172         i->promptme = 1;
1173         i->promptmode = 0; /* PS1 */
1174 #endif
1175         i->p = s;
1176         i->eof_flag = 0;
1177 }
1178
1179
1180 /*
1181  * o_string support
1182  */
1183 #define B_CHUNK  (32 * sizeof(char*))
1184
1185 static void o_reset(o_string *o)
1186 {
1187         o->length = 0;
1188         o->nonnull = 0;
1189         if (o->data)
1190                 o->data[0] = '\0';
1191 }
1192
1193 static void o_free(o_string *o)
1194 {
1195         free(o->data);
1196         memset(o, 0, sizeof(*o));
1197 }
1198
1199 static void o_grow_by(o_string *o, int len)
1200 {
1201         if (o->length + len > o->maxlen) {
1202                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1203                 o->data = xrealloc(o->data, 1 + o->maxlen);
1204         }
1205 }
1206
1207 static void o_addchr(o_string *o, int ch)
1208 {
1209         debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1210         o_grow_by(o, 1);
1211         o->data[o->length] = ch;
1212         o->length++;
1213         o->data[o->length] = '\0';
1214 }
1215
1216 static void o_addstr(o_string *o, const char *str, int len)
1217 {
1218         o_grow_by(o, len);
1219         memcpy(&o->data[o->length], str, len);
1220         o->length += len;
1221         o->data[o->length] = '\0';
1222 }
1223
1224 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1225 {
1226         while (len) {
1227                 o_addchr(o, *str);
1228                 if (*str++ == '\\'
1229                  && (*str != '*' && *str != '?' && *str != '[')
1230                 ) {
1231                         o_addchr(o, '\\');
1232                 }
1233                 len--;
1234         }
1235 }
1236
1237 /* My analysis of quoting semantics tells me that state information
1238  * is associated with a destination, not a source.
1239  */
1240 static void o_addqchr(o_string *o, int ch)
1241 {
1242         int sz = 1;
1243         char *found = strchr("*?[\\", ch);
1244         if (found)
1245                 sz++;
1246         o_grow_by(o, sz);
1247         if (found) {
1248                 o->data[o->length] = '\\';
1249                 o->length++;
1250         }
1251         o->data[o->length] = ch;
1252         o->length++;
1253         o->data[o->length] = '\0';
1254 }
1255
1256 static void o_addQchr(o_string *o, int ch)
1257 {
1258         int sz = 1;
1259         if (o->o_quote && strchr("*?[\\", ch)) {
1260                 sz++;
1261                 o->data[o->length] = '\\';
1262                 o->length++;
1263         }
1264         o_grow_by(o, sz);
1265         o->data[o->length] = ch;
1266         o->length++;
1267         o->data[o->length] = '\0';
1268 }
1269
1270 static void o_addQstr(o_string *o, const char *str, int len)
1271 {
1272         if (!o->o_quote) {
1273                 o_addstr(o, str, len);
1274                 return;
1275         }
1276         while (len) {
1277                 char ch;
1278                 int sz;
1279                 int ordinary_cnt = strcspn(str, "*?[\\");
1280                 if (ordinary_cnt > len) /* paranoia */
1281                         ordinary_cnt = len;
1282                 o_addstr(o, str, ordinary_cnt);
1283                 if (ordinary_cnt == len)
1284                         return;
1285                 str += ordinary_cnt;
1286                 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1287
1288                 ch = *str++;
1289                 sz = 1;
1290                 if (ch) { /* it is necessarily one of "*?[\\" */
1291                         sz++;
1292                         o->data[o->length] = '\\';
1293                         o->length++;
1294                 }
1295                 o_grow_by(o, sz);
1296                 o->data[o->length] = ch;
1297                 o->length++;
1298                 o->data[o->length] = '\0';
1299         }
1300 }
1301
1302 /* A special kind of o_string for $VAR and `cmd` expansion.
1303  * It contains char* list[] at the beginning, which is grown in 16 element
1304  * increments. Actual string data starts at the next multiple of 16 * (char*).
1305  * list[i] contains an INDEX (int!) into this string data.
1306  * It means that if list[] needs to grow, data needs to be moved higher up
1307  * but list[i]'s need not be modified.
1308  * NB: remembering how many list[i]'s you have there is crucial.
1309  * o_finalize_list() operation post-processes this structure - calculates
1310  * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1311  */
1312 #if DEBUG_EXPAND || DEBUG_GLOB
1313 static void debug_print_list(const char *prefix, o_string *o, int n)
1314 {
1315         char **list = (char**)o->data;
1316         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1317         int i = 0;
1318         fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1319                         prefix, list, n, string_start, o->length, o->maxlen);
1320         while (i < n) {
1321                 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1322                                 o->data + (int)list[i] + string_start,
1323                                 o->data + (int)list[i] + string_start);
1324                 i++;
1325         }
1326         if (n) {
1327                 const char *p = o->data + (int)list[n - 1] + string_start;
1328                 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
1329         }
1330 }
1331 #else
1332 #define debug_print_list(prefix, o, n) ((void)0)
1333 #endif
1334
1335 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1336  * in list[n] so that it points past last stored byte so far.
1337  * It returns n+1. */
1338 static int o_save_ptr_helper(o_string *o, int n)
1339 {
1340         char **list = (char**)o->data;
1341         int string_start;
1342         int string_len;
1343
1344         if (!o->has_empty_slot) {
1345                 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1346                 string_len = o->length - string_start;
1347                 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1348                         debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1349                         /* list[n] points to string_start, make space for 16 more pointers */
1350                         o->maxlen += 0x10 * sizeof(list[0]);
1351                         o->data = xrealloc(o->data, o->maxlen + 1);
1352                         list = (char**)o->data;
1353                         memmove(list + n + 0x10, list + n, string_len);
1354                         o->length += 0x10 * sizeof(list[0]);
1355                 } else
1356                         debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1357         } else {
1358                 /* We have empty slot at list[n], reuse without growth */
1359                 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1360                 string_len = o->length - string_start;
1361                 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1362                 o->has_empty_slot = 0;
1363         }
1364         list[n] = (char*)(ptrdiff_t)string_len;
1365         return n + 1;
1366 }
1367
1368 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1369 static int o_get_last_ptr(o_string *o, int n)
1370 {
1371         char **list = (char**)o->data;
1372         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1373
1374         return ((int)(ptrdiff_t)list[n-1]) + string_start;
1375 }
1376
1377 /* o_glob performs globbing on last list[], saving each result
1378  * as a new list[]. */
1379 static int o_glob(o_string *o, int n)
1380 {
1381         glob_t globdata;
1382         int gr;
1383         char *pattern;
1384
1385         debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1386         if (!o->data)
1387                 return o_save_ptr_helper(o, n);
1388         pattern = o->data + o_get_last_ptr(o, n);
1389         debug_printf_glob("glob pattern '%s'\n", pattern);
1390         if (!glob_needed(pattern)) {
1391  literal:
1392                 o->length = unbackslash(pattern) - o->data;
1393                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1394                 return o_save_ptr_helper(o, n);
1395         }
1396
1397         memset(&globdata, 0, sizeof(globdata));
1398         gr = glob(pattern, 0, NULL, &globdata);
1399         debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1400         if (gr == GLOB_NOSPACE)
1401                 bb_error_msg_and_die("out of memory during glob");
1402         if (gr == GLOB_NOMATCH) {
1403                 globfree(&globdata);
1404                 goto literal;
1405         }
1406         if (gr != 0) { /* GLOB_ABORTED ? */
1407 //TODO: testcase for bad glob pattern behavior
1408                 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1409         }
1410         if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1411                 char **argv = globdata.gl_pathv;
1412                 o->length = pattern - o->data; /* "forget" pattern */
1413                 while (1) {
1414                         o_addstr(o, *argv, strlen(*argv) + 1);
1415                         n = o_save_ptr_helper(o, n);
1416                         argv++;
1417                         if (!*argv)
1418                                 break;
1419                 }
1420         }
1421         globfree(&globdata);
1422         if (DEBUG_GLOB)
1423                 debug_print_list("o_glob returning", o, n);
1424         return n;
1425 }
1426
1427 /* If o->o_glob == 1, glob the string so far remembered.
1428  * Otherwise, just finish current list[] and start new */
1429 static int o_save_ptr(o_string *o, int n)
1430 {
1431         if (o->o_glob) { /* if globbing is requested */
1432                 /* If o->has_empty_slot, list[n] was already globbed
1433                  * (if it was requested back then when it was filled)
1434                  * so don't do that again! */
1435                 if (!o->has_empty_slot)
1436                         return o_glob(o, n); /* o_save_ptr_helper is inside */
1437         }
1438         return o_save_ptr_helper(o, n);
1439 }
1440
1441 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1442 static char **o_finalize_list(o_string *o, int n)
1443 {
1444         char **list;
1445         int string_start;
1446
1447         n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1448         if (DEBUG_EXPAND)
1449                 debug_print_list("finalized", o, n);
1450         debug_printf_expand("finalized n:%d\n", n);
1451         list = (char**)o->data;
1452         string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1453         list[--n] = NULL;
1454         while (n) {
1455                 n--;
1456                 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1457         }
1458         return list;
1459 }
1460
1461
1462 /* expand_strvec_to_strvec() takes a list of strings, expands
1463  * all variable references within and returns a pointer to
1464  * a list of expanded strings, possibly with larger number
1465  * of strings. (Think VAR="a b"; echo $VAR).
1466  * This new list is allocated as a single malloc block.
1467  * NULL-terminated list of char* pointers is at the beginning of it,
1468  * followed by strings themself.
1469  * Caller can deallocate entire list by single free(list). */
1470
1471 /* Store given string, finalizing the word and starting new one whenever
1472  * we encounter IFS char(s). This is used for expanding variable values.
1473  * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1474 static int expand_on_ifs(o_string *output, int n, const char *str)
1475 {
1476         while (1) {
1477                 int word_len = strcspn(str, G.ifs);
1478                 if (word_len) {
1479                         if (output->o_quote || !output->o_glob)
1480                                 o_addQstr(output, str, word_len);
1481                         else /* protect backslashes against globbing up :) */
1482                                 o_addstr_duplicate_backslash(output, str, word_len);
1483                         str += word_len;
1484                 }
1485                 if (!*str)  /* EOL - do not finalize word */
1486                         break;
1487                 o_addchr(output, '\0');
1488                 debug_print_list("expand_on_ifs", output, n);
1489                 n = o_save_ptr(output, n);
1490                 str += strspn(str, G.ifs); /* skip ifs chars */
1491         }
1492         debug_print_list("expand_on_ifs[1]", output, n);
1493         return n;
1494 }
1495
1496 #if ENABLE_HUSH_TICK
1497 static int process_command_subs(o_string *dest,
1498                 struct in_str *input, const char *subst_end);
1499 #endif
1500
1501 /* Expand all variable references in given string, adding words to list[]
1502  * at n, n+1,... positions. Return updated n (so that list[n] is next one
1503  * to be filled). This routine is extremely tricky: has to deal with
1504  * variables/parameters with whitespace, $* and $@, and constructs like
1505  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1506 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1507 {
1508         /* or_mask is either 0 (normal case) or 0x80
1509          * (expansion of right-hand side of assignment == 1-element expand.
1510          * It will also do no globbing, and thus we must not backslash-quote!) */
1511
1512         char first_ch, ored_ch;
1513         int i;
1514         const char *val;
1515         char *p;
1516
1517         ored_ch = 0;
1518
1519         debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1520         debug_print_list("expand_vars_to_list", output, n);
1521         n = o_save_ptr(output, n);
1522         debug_print_list("expand_vars_to_list[0]", output, n);
1523
1524         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1525 #if ENABLE_HUSH_TICK
1526                 o_string subst_result = NULL_O_STRING;
1527 #endif
1528                 o_addstr(output, arg, p - arg);
1529                 debug_print_list("expand_vars_to_list[1]", output, n);
1530                 arg = ++p;
1531                 p = strchr(p, SPECIAL_VAR_SYMBOL);
1532
1533                 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1534                 /* "$@" is special. Even if quoted, it can still
1535                  * expand to nothing (not even an empty string) */
1536                 if ((first_ch & 0x7f) != '@')
1537                         ored_ch |= first_ch;
1538                 val = NULL;
1539                 switch (first_ch & 0x7f) {
1540                 /* Highest bit in first_ch indicates that var is double-quoted */
1541                 case '$': /* pid */
1542                         val = utoa(G.root_pid);
1543                         break;
1544                 case '!': /* bg pid */
1545                         val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1546                         break;
1547                 case '?': /* exitcode */
1548                         val = utoa(G.last_return_code);
1549                         break;
1550                 case '#': /* argc */
1551                         if (arg[1] != SPECIAL_VAR_SYMBOL)
1552                                 /* actually, it's a ${#var} */
1553                                 goto case_default;
1554                         val = utoa(G.global_argc ? G.global_argc-1 : 0);
1555                         break;
1556                 case '*':
1557                 case '@':
1558                         i = 1;
1559                         if (!G.global_argv[i])
1560                                 break;
1561                         ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1562                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1563                                 smallint sv = output->o_quote;
1564                                 /* unquoted var's contents should be globbed, so don't quote */
1565                                 output->o_quote = 0;
1566                                 while (G.global_argv[i]) {
1567                                         n = expand_on_ifs(output, n, G.global_argv[i]);
1568                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1569                                         if (G.global_argv[i++][0] && G.global_argv[i]) {
1570                                                 /* this argv[] is not empty and not last:
1571                                                  * put terminating NUL, start new word */
1572                                                 o_addchr(output, '\0');
1573                                                 debug_print_list("expand_vars_to_list[2]", output, n);
1574                                                 n = o_save_ptr(output, n);
1575                                                 debug_print_list("expand_vars_to_list[3]", output, n);
1576                                         }
1577                                 }
1578                                 output->o_quote = sv;
1579                         } else
1580                         /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1581                          * and in this case should treat it like '$*' - see 'else...' below */
1582                         if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1583                                 while (1) {
1584                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1585                                         if (++i >= G.global_argc)
1586                                                 break;
1587                                         o_addchr(output, '\0');
1588                                         debug_print_list("expand_vars_to_list[4]", output, n);
1589                                         n = o_save_ptr(output, n);
1590                                 }
1591                         } else { /* quoted $*: add as one word */
1592                                 while (1) {
1593                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1594                                         if (!G.global_argv[++i])
1595                                                 break;
1596                                         if (G.ifs[0])
1597                                                 o_addchr(output, G.ifs[0]);
1598                                 }
1599                         }
1600                         break;
1601                 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1602                         /* "Empty variable", used to make "" etc to not disappear */
1603                         arg++;
1604                         ored_ch = 0x80;
1605                         break;
1606 #if ENABLE_HUSH_TICK
1607                 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1608                         struct in_str input;
1609                         *p = '\0';
1610                         arg++;
1611 //TODO: can we just stuff it into "output" directly?
1612                         debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1613                         setup_string_in_str(&input, arg);
1614                         process_command_subs(&subst_result, &input, NULL);
1615                         debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1616                         val = subst_result.data;
1617                         goto store_val;
1618                 }
1619 #endif
1620                 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1621                 case_default: {
1622                         bool exp_len = false, exp_null = false;
1623                         char *var = arg, exp_save, exp_op, *exp_word;
1624                         size_t exp_off = 0;
1625                         *p = '\0';
1626                         arg[0] = first_ch & 0x7f;
1627
1628                         /* prepare for expansions */
1629                         if (var[0] == '#') {
1630                                 /* handle length expansion ${#var} */
1631                                 exp_len = true;
1632                                 ++var;
1633                         } else {
1634                                 /* maybe handle parameter expansion */
1635                                 exp_off = strcspn(var, ":-=+?");
1636                                 if (!var[exp_off])
1637                                         exp_off = 0;
1638                                 if (exp_off) {
1639                                         exp_save = var[exp_off];
1640                                         exp_null = exp_save == ':';
1641                                         exp_word = var + exp_off;
1642                                         if (exp_null) ++exp_word;
1643                                         exp_op = *exp_word++;
1644                                         var[exp_off] = '\0';
1645                                 }
1646                         }
1647
1648                         /* lookup the variable in question */
1649                         if (isdigit(var[0])) {
1650                                 i = xatoi_u(var);
1651                                 if (i < G.global_argc)
1652                                         val = G.global_argv[i];
1653                                 /* else val remains NULL: $N with too big N */
1654                         } else
1655                                 val = lookup_param(var);
1656
1657                         /* handle any expansions */
1658                         if (exp_len) {
1659                                 debug_printf_expand("expand: length of '%s' = ", val);
1660                                 val = utoa(val ? strlen(val) : 0);
1661                                 debug_printf_expand("%s\n", val);
1662                         } else if (exp_off) {
1663                                 /* we need to do an expansion */
1664                                 int exp_test = (!val || (exp_null && !val[0]));
1665                                 if (exp_op == '+')
1666                                         exp_test = !exp_test;
1667                                 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1668                                         exp_null ? "true" : "false", exp_test);
1669                                 if (exp_test) {
1670                                         if (exp_op == '?')
1671                                                 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1672                                         else
1673                                                 val = exp_word;
1674
1675                                         if (exp_op == '=') {
1676                                                 if (isdigit(var[0]) || var[0] == '#') {
1677                                                         maybe_die(var, "special vars cannot assign in this way");
1678                                                         val = NULL;
1679                                                 } else {
1680                                                         char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1681                                                         sprintf(new_var, "%s=%s", var, val);
1682                                                         set_local_var(new_var, -1);
1683                                                 }
1684                                         }
1685                                 }
1686                                 var[exp_off] = exp_save;
1687                         }
1688
1689                         arg[0] = first_ch;
1690
1691 #if ENABLE_HUSH_TICK
1692  store_val:
1693 #endif
1694                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
1695                                 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1696                                 if (val) {
1697                                         /* unquoted var's contents should be globbed, so don't quote */
1698                                         smallint sv = output->o_quote;
1699                                         output->o_quote = 0;
1700                                         n = expand_on_ifs(output, n, val);
1701                                         val = NULL;
1702                                         output->o_quote = sv;
1703                                 }
1704                         } else { /* quoted $VAR, val will be appended below */
1705                                 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1706                         }
1707                 }
1708                 }
1709                 if (val) {
1710                         o_addQstr(output, val, strlen(val));
1711                 }
1712                 /* Do the check to avoid writing to a const string */
1713                 if (p && *p != SPECIAL_VAR_SYMBOL)
1714                         *p = SPECIAL_VAR_SYMBOL;
1715
1716 #if ENABLE_HUSH_TICK
1717                 o_free(&subst_result);
1718 #endif
1719                 arg = ++p;
1720         } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1721
1722         if (arg[0]) {
1723                 debug_print_list("expand_vars_to_list[a]", output, n);
1724                 /* this part is literal, and it was already pre-quoted
1725                  * if needed (much earlier), do not use o_addQstr here! */
1726                 o_addstr(output, arg, strlen(arg) + 1);
1727                 debug_print_list("expand_vars_to_list[b]", output, n);
1728         } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1729          && !(ored_ch & 0x80) /* and all vars were not quoted. */
1730         ) {
1731                 n--;
1732                 /* allow to reuse list[n] later without re-growth */
1733                 output->has_empty_slot = 1;
1734         } else {
1735                 o_addchr(output, '\0');
1736         }
1737         return n;
1738 }
1739
1740 static char **expand_variables(char **argv, int or_mask)
1741 {
1742         int n;
1743         char **list;
1744         char **v;
1745         o_string output = NULL_O_STRING;
1746
1747         if (or_mask & 0x100) {
1748                 output.o_quote = 1; /* protect against globbing for "$var" */
1749                 /* (unquoted $var will temporarily switch it off) */
1750                 output.o_glob = 1;
1751         }
1752
1753         n = 0;
1754         v = argv;
1755         while (*v) {
1756                 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1757                 v++;
1758         }
1759         debug_print_list("expand_variables", &output, n);
1760
1761         /* output.data (malloced in one block) gets returned in "list" */
1762         list = o_finalize_list(&output, n);
1763         debug_print_strings("expand_variables[1]", list);
1764         return list;
1765 }
1766
1767 static char **expand_strvec_to_strvec(char **argv)
1768 {
1769         return expand_variables(argv, 0x100);
1770 }
1771
1772 /* Used for expansion of right hand of assignments */
1773 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1774  * "v=/bin/c*" */
1775 static char *expand_string_to_string(const char *str)
1776 {
1777         char *argv[2], **list;
1778
1779         argv[0] = (char*)str;
1780         argv[1] = NULL;
1781         list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1782         if (HUSH_DEBUG)
1783                 if (!list[0] || list[1])
1784                         bb_error_msg_and_die("BUG in varexp2");
1785         /* actually, just move string 2*sizeof(char*) bytes back */
1786         overlapping_strcpy((char*)list, list[0]);
1787         debug_printf_expand("string_to_string='%s'\n", (char*)list);
1788         return (char*)list;
1789 }
1790
1791 /* Used for "eval" builtin */
1792 static char* expand_strvec_to_string(char **argv)
1793 {
1794         char **list;
1795
1796         list = expand_variables(argv, 0x80);
1797         /* Convert all NULs to spaces */
1798         if (list[0]) {
1799                 int n = 1;
1800                 while (list[n]) {
1801                         if (HUSH_DEBUG)
1802                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1803                                         bb_error_msg_and_die("BUG in varexp3");
1804                         list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1805                         n++;
1806                 }
1807         }
1808         overlapping_strcpy((char*)list, list[0]);
1809         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1810         return (char*)list;
1811 }
1812
1813 static char **expand_assignments(char **argv, int count)
1814 {
1815         int i;
1816         char **p = NULL;
1817         /* Expand assignments into one string each */
1818         for (i = 0; i < count; i++) {
1819                 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1820         }
1821         return p;
1822 }
1823
1824
1825 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1826  * and stderr if they are redirected. */
1827 static int setup_redirects(struct command *prog, int squirrel[])
1828 {
1829         int openfd, mode;
1830         struct redir_struct *redir;
1831
1832         for (redir = prog->redirects; redir; redir = redir->next) {
1833                 if (redir->dup == -1 && redir->rd_filename == NULL) {
1834                         /* something went wrong in the parse.  Pretend it didn't happen */
1835                         continue;
1836                 }
1837                 if (redir->dup == -1) {
1838                         char *p;
1839                         mode = redir_table[redir->rd_type].mode;
1840 //TODO: check redir for names like '\\'
1841                         p = expand_string_to_string(redir->rd_filename);
1842                         openfd = open_or_warn(p, mode);
1843                         free(p);
1844                         if (openfd < 0) {
1845                         /* this could get lost if stderr has been redirected, but
1846                            bash and ash both lose it as well (though zsh doesn't!) */
1847                                 return 1;
1848                         }
1849                 } else {
1850                         openfd = redir->dup;
1851                 }
1852
1853                 if (openfd != redir->fd) {
1854                         if (squirrel && redir->fd < 3) {
1855                                 squirrel[redir->fd] = dup(redir->fd);
1856                         }
1857                         if (openfd == -3) {
1858                                 //close(openfd); // close(-3) ??!
1859                         } else {
1860                                 dup2(openfd, redir->fd);
1861                                 if (redir->dup == -1)
1862                                         close(openfd);
1863                         }
1864                 }
1865         }
1866         return 0;
1867 }
1868
1869 static void restore_redirects(int squirrel[])
1870 {
1871         int i, fd;
1872         for (i = 0; i < 3; i++) {
1873                 fd = squirrel[i];
1874                 if (fd != -1) {
1875                         /* We simply die on error */
1876                         xmove_fd(fd, i);
1877                 }
1878         }
1879 }
1880
1881
1882 #if !defined(DEBUG_CLEAN)
1883 #define free_pipe_list(head, indent) free_pipe_list(head)
1884 #define free_pipe(pi, indent)        free_pipe(pi)
1885 #endif
1886 static int free_pipe_list(struct pipe *head, int indent);
1887
1888 /* return code is the exit status of the pipe */
1889 static int free_pipe(struct pipe *pi, int indent)
1890 {
1891         char **p;
1892         struct command *command;
1893         struct redir_struct *r, *rnext;
1894         int a, i, ret_code = 0;
1895
1896         if (pi->stopped_cmds > 0)
1897                 return ret_code;
1898         debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1899         for (i = 0; i < pi->num_cmds; i++) {
1900                 command = &pi->cmds[i];
1901                 debug_printf_clean("%s  command %d:\n", indenter(indent), i);
1902                 if (command->argv) {
1903                         for (a = 0, p = command->argv; *p; a++, p++) {
1904                                 debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
1905                         }
1906                         free_strings(command->argv);
1907                         command->argv = NULL;
1908                 } else if (command->group) {
1909                         debug_printf_clean("%s   begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1910                         ret_code = free_pipe_list(command->group, indent+3);
1911                         debug_printf_clean("%s   end group\n", indenter(indent));
1912                 } else {
1913                         debug_printf_clean("%s   (nil)\n", indenter(indent));
1914                 }
1915                 for (r = command->redirects; r; r = rnext) {
1916                         debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1917                         if (r->dup == -1) {
1918                                 /* guard against the case >$FOO, where foo is unset or blank */
1919                                 if (r->rd_filename) {
1920                                         debug_printf_clean(" %s\n", r->rd_filename);
1921                                         free(r->rd_filename);
1922                                         r->rd_filename = NULL;
1923                                 }
1924                         } else {
1925                                 debug_printf_clean("&%d\n", r->dup);
1926                         }
1927                         rnext = r->next;
1928                         free(r);
1929                 }
1930                 command->redirects = NULL;
1931         }
1932         free(pi->cmds);   /* children are an array, they get freed all at once */
1933         pi->cmds = NULL;
1934 #if ENABLE_HUSH_JOB
1935         free(pi->cmdtext);
1936         pi->cmdtext = NULL;
1937 #endif
1938         return ret_code;
1939 }
1940
1941 static int free_pipe_list(struct pipe *head, int indent)
1942 {
1943         int rcode = 0;   /* if list has no members */
1944         struct pipe *pi, *next;
1945
1946         for (pi = head; pi; pi = next) {
1947 #if HAS_KEYWORDS
1948                 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1949 #endif
1950                 rcode = free_pipe(pi, indent);
1951                 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1952                 next = pi->next;
1953                 /*pi->next = NULL;*/
1954                 free(pi);
1955         }
1956         return rcode;
1957 }
1958
1959
1960 #if !BB_MMU
1961 typedef struct nommu_save_t {
1962         char **new_env;
1963         char **old_env;
1964         char **argv;
1965 } nommu_save_t;
1966 #else
1967 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1968         pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1969 #define pseudo_exec(nommu_save, command, argv_expanded) \
1970         pseudo_exec(command, argv_expanded)
1971 #endif
1972
1973 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1974  * Never returns.
1975  * XXX no exit() here.  If you don't exec, use _exit instead.
1976  * The at_exit handlers apparently confuse the calling process,
1977  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
1978 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
1979 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1980 {
1981         int rcode;
1982         char **new_env;
1983         const struct built_in_command *x;
1984
1985         /* If a variable is assigned in a forest, and nobody listens,
1986          * was it ever really set?
1987          */
1988         if (!argv[assignment_cnt])
1989                 _exit(EXIT_SUCCESS);
1990
1991         new_env = expand_assignments(argv, assignment_cnt);
1992 #if BB_MMU
1993         putenv_all(new_env);
1994         free(new_env); /* optional */
1995 #else
1996         nommu_save->new_env = new_env;
1997         nommu_save->old_env = putenv_all_and_save_old(new_env);
1998 #endif
1999         if (argv_expanded) {
2000                 argv = argv_expanded;
2001         } else {
2002                 argv = expand_strvec_to_strvec(argv);
2003 #if !BB_MMU
2004                 nommu_save->argv = argv;
2005 #endif
2006         }
2007
2008         /*
2009          * Check if the command matches any of the builtins.
2010          * Depending on context, this might be redundant.  But it's
2011          * easier to waste a few CPU cycles than it is to figure out
2012          * if this is one of those cases.
2013          */
2014         for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2015                 if (strcmp(argv[0], x->cmd) == 0) {
2016                         debug_printf_exec("running builtin '%s'\n", argv[0]);
2017                         rcode = x->function(argv);
2018                         fflush(stdout);
2019                         _exit(rcode);
2020                 }
2021         }
2022
2023         /* Check if the command matches any busybox applets */
2024 #if ENABLE_FEATURE_SH_STANDALONE
2025         if (strchr(argv[0], '/') == NULL) {
2026                 int a = find_applet_by_name(argv[0]);
2027                 if (a >= 0) {
2028                         if (APPLET_IS_NOEXEC(a)) {
2029                                 debug_printf_exec("running applet '%s'\n", argv[0]);
2030 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2031                                 run_applet_no_and_exit(a, argv);
2032                         }
2033                         /* re-exec ourselves with the new arguments */
2034                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2035                         execvp(bb_busybox_exec_path, argv);
2036                         /* If they called chroot or otherwise made the binary no longer
2037                          * executable, fall through */
2038                 }
2039         }
2040 #endif
2041
2042         debug_printf_exec("execing '%s'\n", argv[0]);
2043         execvp(argv[0], argv);
2044         bb_perror_msg("can't exec '%s'", argv[0]);
2045         _exit(EXIT_FAILURE);
2046 }
2047
2048 static int run_list(struct pipe *pi);
2049
2050 /* Called after [v]fork() in run_pipe()
2051  */
2052 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
2053 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
2054 {
2055         if (command->argv)
2056                 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
2057
2058         if (command->group) {
2059 #if !BB_MMU
2060                 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2061 #else
2062                 int rcode;
2063                 debug_printf_exec("pseudo_exec: run_list\n");
2064                 rcode = run_list(command->group);
2065                 /* OK to leak memory by not calling free_pipe_list,
2066                  * since this process is about to exit */
2067                 _exit(rcode);
2068 #endif
2069         }
2070
2071         /* Can happen.  See what bash does with ">foo" by itself. */
2072         debug_printf("trying to pseudo_exec null command\n");
2073         _exit(EXIT_SUCCESS);
2074 }
2075
2076 #if ENABLE_HUSH_JOB
2077 static const char *get_cmdtext(struct pipe *pi)
2078 {
2079         char **argv;
2080         char *p;
2081         int len;
2082
2083         /* This is subtle. ->cmdtext is created only on first backgrounding.
2084          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2085          * On subsequent bg argv is trashed, but we won't use it */
2086         if (pi->cmdtext)
2087                 return pi->cmdtext;
2088         argv = pi->cmds[0].argv;
2089         if (!argv || !argv[0]) {
2090                 pi->cmdtext = xzalloc(1);
2091                 return pi->cmdtext;
2092         }
2093
2094         len = 0;
2095         do len += strlen(*argv) + 1; while (*++argv);
2096         pi->cmdtext = p = xmalloc(len);
2097         argv = pi->cmds[0].argv;
2098         do {
2099                 len = strlen(*argv);
2100                 memcpy(p, *argv, len);
2101                 p += len;
2102                 *p++ = ' ';
2103         } while (*++argv);
2104         p[-1] = '\0';
2105         return pi->cmdtext;
2106 }
2107
2108 static void insert_bg_job(struct pipe *pi)
2109 {
2110         struct pipe *thejob;
2111         int i;
2112
2113         /* Linear search for the ID of the job to use */
2114         pi->jobid = 1;
2115         for (thejob = G.job_list; thejob; thejob = thejob->next)
2116                 if (thejob->jobid >= pi->jobid)
2117                         pi->jobid = thejob->jobid + 1;
2118
2119         /* Add thejob to the list of running jobs */
2120         if (!G.job_list) {
2121                 thejob = G.job_list = xmalloc(sizeof(*thejob));
2122         } else {
2123                 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2124                         continue;
2125                 thejob->next = xmalloc(sizeof(*thejob));
2126                 thejob = thejob->next;
2127         }
2128
2129         /* Physically copy the struct job */
2130         memcpy(thejob, pi, sizeof(struct pipe));
2131         thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2132         /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2133         for (i = 0; i < pi->num_cmds; i++) {
2134 // TODO: do we really need to have so many fields which are just dead weight
2135 // at execution stage?
2136                 thejob->cmds[i].pid = pi->cmds[i].pid;
2137                 /* all other fields are not used and stay zero */
2138         }
2139         thejob->next = NULL;
2140         thejob->cmdtext = xstrdup(get_cmdtext(pi));
2141
2142         /* We don't wait for background thejobs to return -- append it
2143            to the list of backgrounded thejobs and leave it alone */
2144         printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2145         G.last_bg_pid = thejob->cmds[0].pid;
2146         G.last_jobid = thejob->jobid;
2147 }
2148
2149 static void remove_bg_job(struct pipe *pi)
2150 {
2151         struct pipe *prev_pipe;
2152
2153         if (pi == G.job_list) {
2154                 G.job_list = pi->next;
2155         } else {
2156                 prev_pipe = G.job_list;
2157                 while (prev_pipe->next != pi)
2158                         prev_pipe = prev_pipe->next;
2159                 prev_pipe->next = pi->next;
2160         }
2161         if (G.job_list)
2162                 G.last_jobid = G.job_list->jobid;
2163         else
2164                 G.last_jobid = 0;
2165 }
2166
2167 /* Remove a backgrounded job */
2168 static void delete_finished_bg_job(struct pipe *pi)
2169 {
2170         remove_bg_job(pi);
2171         pi->stopped_cmds = 0;
2172         free_pipe(pi, 0);
2173         free(pi);
2174 }
2175 #endif /* JOB */
2176
2177 /* Check to see if any processes have exited -- if they
2178  * have, figure out why and see if a job has completed */
2179 static int checkjobs(struct pipe* fg_pipe)
2180 {
2181         int attributes;
2182         int status;
2183 #if ENABLE_HUSH_JOB
2184         struct pipe *pi;
2185 #endif
2186         pid_t childpid;
2187         int rcode = 0;
2188
2189         attributes = WUNTRACED;
2190         if (fg_pipe == NULL)
2191                 attributes |= WNOHANG;
2192
2193 /* Do we do this right?
2194  * bash-3.00# sleep 20 | false
2195  * <ctrl-Z pressed>
2196  * [3]+  Stopped          sleep 20 | false
2197  * bash-3.00# echo $?
2198  * 1   <========== bg pipe is not fully done, but exitcode is already known!
2199  */
2200
2201 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2202 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2203 // + killall -STOP cat
2204
2205  wait_more:
2206 // TODO: safe_waitpid?
2207         while ((childpid = waitpid(-1, &status, attributes)) > 0) {
2208                 int i;
2209                 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
2210 #if DEBUG_JOBS
2211                 if (WIFSTOPPED(status))
2212                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2213                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
2214                 if (WIFSIGNALED(status))
2215                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2216                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
2217                 if (WIFEXITED(status))
2218                         debug_printf_jobs("pid %d exited, exitcode %d\n",
2219                                         childpid, WEXITSTATUS(status));
2220 #endif
2221                 /* Were we asked to wait for fg pipe? */
2222                 if (fg_pipe) {
2223                         for (i = 0; i < fg_pipe->num_cmds; i++) {
2224                                 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2225                                 if (fg_pipe->cmds[i].pid != childpid)
2226                                         continue;
2227                                 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2228                                 if (dead) {
2229                                         fg_pipe->cmds[i].pid = 0;
2230                                         fg_pipe->alive_cmds--;
2231                                         if (i == fg_pipe->num_cmds - 1) {
2232                                                 /* last process gives overall exitstatus */
2233                                                 rcode = WEXITSTATUS(status);
2234                                                 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2235                                         }
2236                                 } else {
2237                                         fg_pipe->cmds[i].is_stopped = 1;
2238                                         fg_pipe->stopped_cmds++;
2239                                 }
2240                                 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2241                                                 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2242                                 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2243                                         /* All processes in fg pipe have exited/stopped */
2244 #if ENABLE_HUSH_JOB
2245                                         if (fg_pipe->alive_cmds)
2246                                                 insert_bg_job(fg_pipe);
2247 #endif
2248                                         return rcode;
2249                                 }
2250                                 /* There are still running processes in the fg pipe */
2251                                 goto wait_more; /* do waitpid again */
2252                         }
2253                         /* it wasnt fg_pipe, look for process in bg pipes */
2254                 }
2255
2256 #if ENABLE_HUSH_JOB
2257                 /* We asked to wait for bg or orphaned children */
2258                 /* No need to remember exitcode in this case */
2259                 for (pi = G.job_list; pi; pi = pi->next) {
2260                         for (i = 0; i < pi->num_cmds; i++) {
2261                                 if (pi->cmds[i].pid == childpid)
2262                                         goto found_pi_and_prognum;
2263                         }
2264                 }
2265                 /* Happens when shell is used as init process (init=/bin/sh) */
2266                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2267                 continue; /* do waitpid again */
2268
2269  found_pi_and_prognum:
2270                 if (dead) {
2271                         /* child exited */
2272                         pi->cmds[i].pid = 0;
2273                         pi->alive_cmds--;
2274                         if (!pi->alive_cmds) {
2275                                 printf(JOB_STATUS_FORMAT, pi->jobid,
2276                                                 "Done", pi->cmdtext);
2277                                 delete_finished_bg_job(pi);
2278                         }
2279                 } else {
2280                         /* child stopped */
2281                         pi->cmds[i].is_stopped = 1;
2282                         pi->stopped_cmds++;
2283                 }
2284 #endif
2285         } /* while (waitpid succeeds)... */
2286
2287         /* wait found no children or failed */
2288
2289         if (childpid && errno != ECHILD)
2290                 bb_perror_msg("waitpid");
2291         return rcode;
2292 }
2293
2294 #if ENABLE_HUSH_JOB
2295 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2296 {
2297         pid_t p;
2298         int rcode = checkjobs(fg_pipe);
2299         /* Job finished, move the shell to the foreground */
2300         p = getpgid(0); /* pgid of our process */
2301         debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2302         tcsetpgrp(G.interactive_fd, p);
2303         return rcode;
2304 }
2305 #endif
2306
2307 /* run_pipe() starts all the jobs, but doesn't wait for anything
2308  * to finish.  See checkjobs().
2309  *
2310  * return code is normally -1, when the caller has to wait for children
2311  * to finish to determine the exit status of the pipe.  If the pipe
2312  * is a simple builtin command, however, the action is done by the
2313  * time run_pipe returns, and the exit code is provided as the
2314  * return value.
2315  *
2316  * The input of the pipe is always stdin, the output is always
2317  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2318  * because it tries to avoid running the command substitution in
2319  * subshell, when that is in fact necessary.  The subshell process
2320  * now has its stdout directed to the input of the appropriate pipe,
2321  * so this routine is noticeably simpler.
2322  *
2323  * Returns -1 only if started some children. IOW: we have to
2324  * mask out retvals of builtins etc with 0xff!
2325  */
2326 static int run_pipe(struct pipe *pi)
2327 {
2328         int i;
2329         int nextin;
2330         int pipefds[2];         /* pipefds[0] is for reading */
2331         struct command *command;
2332         char **argv_expanded;
2333         char **argv;
2334         const struct built_in_command *x;
2335         char *p;
2336         /* it is not always needed, but we aim to smaller code */
2337         int squirrel[] = { -1, -1, -1 };
2338         int rcode;
2339         const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2340
2341         debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2342
2343 #if ENABLE_HUSH_JOB
2344         pi->pgrp = -1;
2345 #endif
2346         pi->alive_cmds = 1;
2347         pi->stopped_cmds = 0;
2348
2349         /* Check if this is a simple builtin (not part of a pipe).
2350          * Builtins within pipes have to fork anyway, and are handled in
2351          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
2352          */
2353         command = &(pi->cmds[0]);
2354
2355 #if ENABLE_HUSH_FUNCTIONS
2356         if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2357                 /* We "execute" function definition */
2358                 bb_error_msg("here we ought to remember function definition, and go on");
2359                 return EXIT_SUCCESS;
2360         }
2361 #endif
2362
2363         if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2364                 debug_printf("non-subshell grouping\n");
2365                 setup_redirects(command, squirrel);
2366                 debug_printf_exec(": run_list\n");
2367                 rcode = run_list(command->group) & 0xff;
2368                 restore_redirects(squirrel);
2369                 debug_printf_exec("run_pipe return %d\n", rcode);
2370                 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2371                 return rcode;
2372         }
2373
2374         argv = command->argv;
2375         argv_expanded = NULL;
2376
2377         if (single_and_fg && argv != NULL) {
2378                 char **new_env = NULL;
2379                 char **old_env = NULL;
2380
2381                 i = command->assignment_cnt;
2382                 if (i != 0 && argv[i] == NULL) {
2383                         /* assignments, but no command: set local environment */
2384                         for (i = 0; argv[i] != NULL; i++) {
2385                                 debug_printf("local environment set: %s\n", argv[i]);
2386                                 p = expand_string_to_string(argv[i]);
2387                                 set_local_var(p, 0);
2388                         }
2389                         return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2390                 }
2391
2392                 /* Expand the rest into (possibly) many strings each */
2393                 argv_expanded = expand_strvec_to_strvec(argv + i);
2394
2395                 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2396                         if (strcmp(argv_expanded[0], x->cmd) != 0)
2397                                 continue;
2398                         if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2399                                 debug_printf("exec with redirects only\n");
2400                                 setup_redirects(command, NULL);
2401                                 rcode = EXIT_SUCCESS;
2402                                 goto clean_up_and_ret1;
2403                         }
2404                         debug_printf("builtin inline %s\n", argv_expanded[0]);
2405                         /* XXX setup_redirects acts on file descriptors, not FILEs.
2406                          * This is perfect for work that comes after exec().
2407                          * Is it really safe for inline use?  Experimentally,
2408                          * things seem to work with glibc. */
2409                         setup_redirects(command, squirrel);
2410                         new_env = expand_assignments(argv, command->assignment_cnt);
2411                         old_env = putenv_all_and_save_old(new_env);
2412                         debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2413                         rcode = x->function(argv_expanded) & 0xff;
2414 #if ENABLE_FEATURE_SH_STANDALONE
2415  clean_up_and_ret:
2416 #endif
2417                         restore_redirects(squirrel);
2418                         free_strings_and_unsetenv(new_env, 1);
2419                         putenv_all(old_env);
2420                         free(old_env); /* not free_strings()! */
2421  clean_up_and_ret1:
2422                         free(argv_expanded);
2423                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2424                         debug_printf_exec("run_pipe return %d\n", rcode);
2425                         return rcode;
2426                 }
2427 #if ENABLE_FEATURE_SH_STANDALONE
2428                 i = find_applet_by_name(argv_expanded[0]);
2429                 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2430                         setup_redirects(command, squirrel);
2431                         save_nofork_data(&G.nofork_save);
2432                         new_env = expand_assignments(argv, command->assignment_cnt);
2433                         old_env = putenv_all_and_save_old(new_env);
2434                         debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2435                         rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2436                         goto clean_up_and_ret;
2437                 }
2438 #endif
2439         }
2440
2441         /* NB: argv_expanded may already be created, and that
2442          * might include `cmd` runs! Do not rerun it! We *must*
2443          * use argv_expanded if it's non-NULL */
2444
2445         /* Disable job control signals for shell (parent) and
2446          * for initial child code after fork */
2447         set_jobctrl_sighandler(SIG_IGN);
2448
2449         /* Going to fork a child per each pipe member */
2450         pi->alive_cmds = 0;
2451         nextin = 0;
2452
2453         for (i = 0; i < pi->num_cmds; i++) {
2454 #if !BB_MMU
2455                 volatile nommu_save_t nommu_save;
2456                 nommu_save.new_env = NULL;
2457                 nommu_save.old_env = NULL;
2458                 nommu_save.argv = NULL;
2459 #endif
2460                 command = &(pi->cmds[i]);
2461                 if (command->argv) {
2462                         debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2463                 } else
2464                         debug_printf_exec(": pipe member with no argv\n");
2465
2466                 /* pipes are inserted between pairs of commands */
2467                 pipefds[0] = 0;
2468                 pipefds[1] = 1;
2469                 if ((i + 1) < pi->num_cmds)
2470                         xpipe(pipefds);
2471
2472                 command->pid = BB_MMU ? fork() : vfork();
2473                 if (!command->pid) { /* child */
2474                         if (ENABLE_HUSH_JOB)
2475                                 die_sleep = 0; /* let nofork's xfuncs die */
2476 #if ENABLE_HUSH_JOB
2477                         /* Every child adds itself to new process group
2478                          * with pgid == pid_of_first_child_in_pipe */
2479                         if (G.run_list_level == 1 && G.interactive_fd) {
2480                                 pid_t pgrp;
2481                                 /* Don't do pgrp restore anymore on fatal signals */
2482                                 set_fatal_sighandler(SIG_DFL);
2483                                 pgrp = pi->pgrp;
2484                                 if (pgrp < 0) /* true for 1st process only */
2485                                         pgrp = getpid();
2486                                 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2487                                         /* We do it in *every* child, not just first,
2488                                          * to avoid races */
2489                                         tcsetpgrp(G.interactive_fd, pgrp);
2490                                 }
2491                         }
2492 #endif
2493                         xmove_fd(nextin, 0);
2494                         xmove_fd(pipefds[1], 1); /* write end */
2495                         if (pipefds[0] > 1)
2496                                 close(pipefds[0]); /* read end */
2497                         /* Like bash, explicit redirects override pipes,
2498                          * and the pipe fd is available for dup'ing. */
2499                         setup_redirects(command, NULL);
2500
2501                         /* Restore default handlers just prior to exec */
2502                         set_jobctrl_sighandler(SIG_DFL);
2503                         set_misc_sighandler(SIG_DFL);
2504                         signal(SIGCHLD, SIG_DFL);
2505                         /* Stores to nommu_save list of env vars putenv'ed
2506                          * (NOMMU, on MMU we don't need that) */
2507                         /* cast away volatility... */
2508                         pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2509                         /* pseudo_exec() does not return */
2510                 }
2511                 /* parent */
2512 #if !BB_MMU
2513                 /* Clean up after vforked child */
2514                 free(nommu_save.argv);
2515                 free_strings_and_unsetenv(nommu_save.new_env, 1);
2516                 putenv_all(nommu_save.old_env);
2517 #endif
2518                 free(argv_expanded);
2519                 argv_expanded = NULL;
2520                 if (command->pid < 0) { /* [v]fork failed */
2521                         /* Clearly indicate, was it fork or vfork */
2522                         bb_perror_msg(BB_MMU ? "fork" : "vfork");
2523                 } else {
2524                         pi->alive_cmds++;
2525 #if ENABLE_HUSH_JOB
2526                         /* Second and next children need to know pid of first one */
2527                         if (pi->pgrp < 0)
2528                                 pi->pgrp = command->pid;
2529 #endif
2530                 }
2531
2532                 if (i)
2533                         close(nextin);
2534                 if ((i + 1) < pi->num_cmds)
2535                         close(pipefds[1]); /* write end */
2536                 /* Pass read (output) pipe end to next iteration */
2537                 nextin = pipefds[0];
2538         }
2539
2540         if (!pi->alive_cmds) {
2541                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2542                 return 1;
2543         }
2544
2545         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2546         return -1;
2547 }
2548
2549 #ifndef debug_print_tree
2550 static void debug_print_tree(struct pipe *pi, int lvl)
2551 {
2552         static const char *const PIPE[] = {
2553                 [PIPE_SEQ] = "SEQ",
2554                 [PIPE_AND] = "AND",
2555                 [PIPE_OR ] = "OR" ,
2556                 [PIPE_BG ] = "BG" ,
2557         };
2558         static const char *RES[] = {
2559                 [RES_NONE ] = "NONE" ,
2560 #if ENABLE_HUSH_IF
2561                 [RES_IF   ] = "IF"   ,
2562                 [RES_THEN ] = "THEN" ,
2563                 [RES_ELIF ] = "ELIF" ,
2564                 [RES_ELSE ] = "ELSE" ,
2565                 [RES_FI   ] = "FI"   ,
2566 #endif
2567 #if ENABLE_HUSH_LOOPS
2568                 [RES_FOR  ] = "FOR"  ,
2569                 [RES_WHILE] = "WHILE",
2570                 [RES_UNTIL] = "UNTIL",
2571                 [RES_DO   ] = "DO"   ,
2572                 [RES_DONE ] = "DONE" ,
2573 #endif
2574 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2575                 [RES_IN   ] = "IN"   ,
2576 #endif
2577 #if ENABLE_HUSH_CASE
2578                 [RES_CASE ] = "CASE" ,
2579                 [RES_MATCH] = "MATCH",
2580                 [RES_CASEI] = "CASEI",
2581                 [RES_ESAC ] = "ESAC" ,
2582 #endif
2583                 [RES_XXXX ] = "XXXX" ,
2584                 [RES_SNTX ] = "SNTX" ,
2585         };
2586         static const char *const GRPTYPE[] = {
2587                 "()",
2588                 "{}",
2589 #if ENABLE_HUSH_FUNCTIONS
2590                 "func()",
2591 #endif
2592         };
2593
2594         int pin, prn;
2595
2596         pin = 0;
2597         while (pi) {
2598                 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2599                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2600                 prn = 0;
2601                 while (prn < pi->num_cmds) {
2602                         struct command *command = &pi->cmds[prn];
2603                         char **argv = command->argv;
2604
2605                         fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2606                         if (command->group) {
2607                                 fprintf(stderr, " group %s: (argv=%p)\n",
2608                                                 GRPTYPE[command->grp_type],
2609                                                 argv);
2610                                 debug_print_tree(command->group, lvl+1);
2611                                 prn++;
2612                                 continue;
2613                         }
2614                         if (argv) while (*argv) {
2615                                 fprintf(stderr, " '%s'", *argv);
2616                                 argv++;
2617                         }
2618                         fprintf(stderr, "\n");
2619                         prn++;
2620                 }
2621                 pi = pi->next;
2622                 pin++;
2623         }
2624 }
2625 #endif
2626
2627 /* NB: called by pseudo_exec, and therefore must not modify any
2628  * global data until exec/_exit (we can be a child after vfork!) */
2629 static int run_list(struct pipe *pi)
2630 {
2631 #if ENABLE_HUSH_CASE
2632         char *case_word = NULL;
2633 #endif
2634 #if ENABLE_HUSH_LOOPS
2635         struct pipe *loop_top = NULL;
2636         char *for_varname = NULL;
2637         char **for_lcur = NULL;
2638         char **for_list = NULL;
2639 #endif
2640         smallint flag_skip = 1;
2641         smalluint rcode = 0; /* probably just for compiler */
2642 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2643         smalluint cond_code = 0;
2644 #else
2645         enum { cond_code = 0, };
2646 #endif
2647         /*enum reserved_style*/ smallint rword = RES_NONE;
2648         /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2649
2650         debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2651
2652 #if ENABLE_HUSH_LOOPS
2653         /* Check syntax for "for" */
2654         for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2655                 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2656                         continue;
2657                 /* current word is FOR or IN (BOLD in comments below) */
2658                 if (cpipe->next == NULL) {
2659                         syntax("malformed for");
2660                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2661                         return 1;
2662                 }
2663                 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2664                 if (cpipe->next->res_word == RES_DO)
2665                         continue;
2666                 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2667                 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2668                  || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2669                 ) {
2670                         syntax("malformed for");
2671                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2672                         return 1;
2673                 }
2674         }
2675 #endif
2676
2677         /* Past this point, all code paths should jump to ret: label
2678          * in order to return, no direct "return" statements please.
2679          * This helps to ensure that no memory is leaked. */
2680
2681 #if ENABLE_HUSH_JOB
2682         /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2683          * We are saving state before entering outermost list ("while...done")
2684          * so that ctrl-Z will correctly background _entire_ outermost list,
2685          * not just a part of it (like "sleep 1 | exit 2") */
2686         if (++G.run_list_level == 1 && G.interactive_fd) {
2687                 if (sigsetjmp(G.toplevel_jb, 1)) {
2688                         /* ctrl-Z forked and we are parent; or ctrl-C.
2689                          * Sighandler has longjmped us here */
2690                         signal(SIGINT, SIG_IGN);
2691                         signal(SIGTSTP, SIG_IGN);
2692                         /* Restore level (we can be coming from deep inside
2693                          * nested levels) */
2694                         G.run_list_level = 1;
2695 #if ENABLE_FEATURE_SH_STANDALONE
2696                         if (G.nofork_save.saved) { /* if save area is valid */
2697                                 debug_printf_jobs("exiting nofork early\n");
2698                                 restore_nofork_data(&G.nofork_save);
2699                         }
2700 #endif
2701                         if (G.ctrl_z_flag) {
2702                                 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2703                                  * Remember this child as background job */
2704                                 insert_bg_job(pi);
2705                         } else {
2706                                 /* ctrl-C. We just stop doing whatever we were doing */
2707                                 bb_putchar('\n');
2708                         }
2709                         USE_HUSH_LOOPS(loop_top = NULL;)
2710                         USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2711                         rcode = 0;
2712                         goto ret;
2713                 }
2714                 /* ctrl-Z handler will store pid etc in pi */
2715                 G.toplevel_list = pi;
2716                 G.ctrl_z_flag = 0;
2717 #if ENABLE_FEATURE_SH_STANDALONE
2718                 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2719 #endif
2720                 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2721                 signal(SIGINT, handler_ctrl_c);
2722         }
2723 #endif /* JOB */
2724
2725         /* Go through list of pipes, (maybe) executing them. */
2726         for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2727                 IF_HAS_KEYWORDS(rword = pi->res_word;)
2728                 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2729                 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2730                                 rword, cond_code, skip_more_for_this_rword);
2731 #if ENABLE_HUSH_LOOPS
2732                 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2733                  && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2734                 ) {
2735                         /* start of a loop: remember where loop starts */
2736                         loop_top = pi;
2737                         G.depth_of_loop++;
2738                 }
2739 #endif
2740                 if (rword == skip_more_for_this_rword && flag_skip) {
2741                         if (pi->followup == PIPE_SEQ)
2742                                 flag_skip = 0;
2743                         /* it is "<false> && CMD" or "<true> || CMD"
2744                          * and we should not execute CMD */
2745                         continue;
2746                 }
2747                 flag_skip = 1;
2748                 skip_more_for_this_rword = RES_XXXX;
2749 #if ENABLE_HUSH_IF
2750                 if (cond_code) {
2751                         if (rword == RES_THEN) {
2752                                 /* "if <false> THEN cmd": skip cmd */
2753                                 continue;
2754                         }
2755                 } else {
2756                         if (rword == RES_ELSE || rword == RES_ELIF) {
2757                                 /* "if <true> then ... ELSE/ELIF cmd":
2758                                  * skip cmd and all following ones */
2759                                 break;
2760                         }
2761                 }
2762 #endif
2763 #if ENABLE_HUSH_LOOPS
2764                 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2765                         if (!for_lcur) {
2766                                 /* first loop through for */
2767
2768                                 static const char encoded_dollar_at[] ALIGN1 = {
2769                                         SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2770                                 }; /* encoded representation of "$@" */
2771                                 static const char *const encoded_dollar_at_argv[] = {
2772                                         encoded_dollar_at, NULL
2773                                 }; /* argv list with one element: "$@" */
2774                                 char **vals;
2775
2776                                 vals = (char**)encoded_dollar_at_argv;
2777                                 if (pi->next->res_word == RES_IN) {
2778                                         /* if no variable values after "in" we skip "for" */
2779                                         if (!pi->next->cmds[0].argv)
2780                                                 break;
2781                                         vals = pi->next->cmds[0].argv;
2782                                 } /* else: "for var; do..." -> assume "$@" list */
2783                                 /* create list of variable values */
2784                                 debug_print_strings("for_list made from", vals);
2785                                 for_list = expand_strvec_to_strvec(vals);
2786                                 for_lcur = for_list;
2787                                 debug_print_strings("for_list", for_list);
2788                                 for_varname = pi->cmds[0].argv[0];
2789                                 pi->cmds[0].argv[0] = NULL;
2790                         }
2791                         free(pi->cmds[0].argv[0]);
2792                         if (!*for_lcur) {
2793                                 /* "for" loop is over, clean up */
2794                                 free(for_list);
2795                                 for_list = NULL;
2796                                 for_lcur = NULL;
2797                                 pi->cmds[0].argv[0] = for_varname;
2798                                 break;
2799                         }
2800                         /* insert next value from for_lcur */
2801 //TODO: does it need escaping?
2802                         pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2803                         pi->cmds[0].assignment_cnt = 1;
2804                 }
2805                 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2806                         continue;
2807                 if (rword == RES_DONE) {
2808                         continue; /* "done" has no cmds too */
2809                 }
2810 #endif
2811 #if ENABLE_HUSH_CASE
2812                 if (rword == RES_CASE) {
2813                         case_word = expand_strvec_to_string(pi->cmds->argv);
2814                         continue;
2815                 }
2816                 if (rword == RES_MATCH) {
2817                         char **argv;
2818
2819                         if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2820                                 break;
2821                         /* all prev words didn't match, does this one match? */
2822                         argv = pi->cmds->argv;
2823                         while (*argv) {
2824                                 char *pattern = expand_string_to_string(*argv);
2825                                 /* TODO: which FNM_xxx flags to use? */
2826                                 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2827                                 free(pattern);
2828                                 if (cond_code == 0) { /* match! we will execute this branch */
2829                                         free(case_word); /* make future "word)" stop */
2830                                         case_word = NULL;
2831                                         break;
2832                                 }
2833                                 argv++;
2834                         }
2835                         continue;
2836                 }
2837                 if (rword == RES_CASEI) { /* inside of a case branch */
2838                         if (cond_code != 0)
2839                                 continue; /* not matched yet, skip this pipe */
2840                 }
2841 #endif
2842                 if (pi->num_cmds == 0)
2843                         continue;
2844
2845                 /* After analyzing all keywords and conditions, we decided
2846                  * to execute this pipe. NB: has to do checkjobs(NULL)
2847                  * after run_pipe() to collect any background children,
2848                  * even if list execution is to be stopped. */
2849                 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2850                 {
2851                         int r;
2852 #if ENABLE_HUSH_LOOPS
2853                         G.flag_break_continue = 0;
2854 #endif
2855                         rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2856                         if (r != -1) {
2857                                 /* we only ran a builtin: rcode is already known
2858                                  * and we don't need to wait for anything. */
2859 #if ENABLE_HUSH_LOOPS
2860                                 /* was it "break" or "continue"? */
2861                                 if (G.flag_break_continue) {
2862                                         smallint fbc = G.flag_break_continue;
2863                                         /* we might fall into outer *loop*,
2864                                          * don't want to break it too */
2865                                         if (loop_top) {
2866                                                 G.depth_break_continue--;
2867                                                 if (G.depth_break_continue == 0)
2868                                                         G.flag_break_continue = 0;
2869                                                 /* else: e.g. "continue 2" should *break* once, *then* continue */
2870                                         } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2871                                         if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2872                                                 goto check_jobs_and_break;
2873                                         /* "continue": simulate end of loop */
2874                                         rword = RES_DONE;
2875                                         continue;
2876                                 }
2877 #endif
2878                         } else if (pi->followup == PIPE_BG) {
2879                                 /* what does bash do with attempts to background builtins? */
2880                                 /* even bash 3.2 doesn't do that well with nested bg:
2881                                  * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2882                                  * I'm NOT treating inner &'s as jobs */
2883 #if ENABLE_HUSH_JOB
2884                                 if (G.run_list_level == 1)
2885                                         insert_bg_job(pi);
2886 #endif
2887                                 rcode = 0; /* EXIT_SUCCESS */
2888                         } else {
2889 #if ENABLE_HUSH_JOB
2890                                 if (G.run_list_level == 1 && G.interactive_fd) {
2891                                         /* waits for completion, then fg's main shell */
2892                                         rcode = checkjobs_and_fg_shell(pi);
2893                                         debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2894                                 } else
2895 #endif
2896                                 { /* this one just waits for completion */
2897                                         rcode = checkjobs(pi);
2898                                         debug_printf_exec(": checkjobs returned %d\n", rcode);
2899                                 }
2900                         }
2901                 }
2902                 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2903                 G.last_return_code = rcode;
2904
2905                 /* Analyze how result affects subsequent commands */
2906 #if ENABLE_HUSH_IF
2907                 if (rword == RES_IF || rword == RES_ELIF)
2908                         cond_code = rcode;
2909 #endif
2910 #if ENABLE_HUSH_LOOPS
2911                 if (rword == RES_WHILE) {
2912                         if (rcode) {
2913                                 rcode = 0; /* "while false; do...done" - exitcode 0 */
2914                                 goto check_jobs_and_break;
2915                         }
2916                 }
2917                 if (rword == RES_UNTIL) {
2918                         if (!rcode) {
2919  check_jobs_and_break:
2920                                 checkjobs(NULL);
2921                                 break;
2922                         }
2923                 }
2924 #endif
2925                 if ((rcode == 0 && pi->followup == PIPE_OR)
2926                  || (rcode != 0 && pi->followup == PIPE_AND)
2927                 ) {
2928                         skip_more_for_this_rword = rword;
2929                 }
2930                 checkjobs(NULL);
2931         } /* for (pi) */
2932
2933 #if ENABLE_HUSH_JOB
2934         if (G.ctrl_z_flag) {
2935                 /* ctrl-Z forked somewhere in the past, we are the child,
2936                  * and now we completed running the list. Exit. */
2937 //TODO: _exit?
2938                 exit(rcode);
2939         }
2940  ret:
2941         if (!--G.run_list_level && G.interactive_fd) {
2942                 signal(SIGTSTP, SIG_IGN);
2943                 signal(SIGINT, SIG_IGN);
2944         }
2945 #endif
2946         debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2947 #if ENABLE_HUSH_LOOPS
2948         if (loop_top)
2949                 G.depth_of_loop--;
2950         free(for_list);
2951 #endif
2952 #if ENABLE_HUSH_CASE
2953         free(case_word);
2954 #endif
2955         return rcode;
2956 }
2957
2958 /* Select which version we will use */
2959 static int run_and_free_list(struct pipe *pi)
2960 {
2961         int rcode = 0;
2962         debug_printf_exec("run_and_free_list entered\n");
2963         if (!G.fake_mode) {
2964                 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2965                 rcode = run_list(pi);
2966         }
2967         /* free_pipe_list has the side effect of clearing memory.
2968          * In the long run that function can be merged with run_list,
2969          * but doing that now would hobble the debugging effort. */
2970         free_pipe_list(pi, /* indent: */ 0);
2971         debug_printf_exec("run_and_free_list return %d\n", rcode);
2972         return rcode;
2973 }
2974
2975
2976 /* Peek ahead in the in_str to find out if we have a "&n" construct,
2977  * as in "2>&1", that represents duplicating a file descriptor.
2978  * Return either -2 (syntax error), -1 (no &), or the number found.
2979  */
2980 static int redirect_dup_num(struct in_str *input)
2981 {
2982         int ch, d = 0, ok = 0;
2983         ch = i_peek(input);
2984         if (ch != '&') return -1;
2985
2986         i_getch(input);  /* get the & */
2987         ch = i_peek(input);
2988         if (ch == '-') {
2989                 i_getch(input);
2990                 return -3;  /* "-" represents "close me" */
2991         }
2992         while (isdigit(ch)) {
2993                 d = d*10 + (ch-'0');
2994                 ok = 1;
2995                 i_getch(input);
2996                 ch = i_peek(input);
2997         }
2998         if (ok) return d;
2999
3000         bb_error_msg("ambiguous redirect");
3001         return -2;
3002 }
3003
3004 /* The src parameter allows us to peek forward to a possible &n syntax
3005  * for file descriptor duplication, e.g., "2>&1".
3006  * Return code is 0 normally, 1 if a syntax error is detected in src.
3007  * Resource errors (in xmalloc) cause the process to exit */
3008 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
3009         struct in_str *input)
3010 {
3011         struct command *command = ctx->command;
3012         struct redir_struct *redir = command->redirects;
3013         struct redir_struct *last_redir = NULL;
3014
3015         /* Create a new redir_struct and drop it onto the end of the linked list */
3016         while (redir) {
3017                 last_redir = redir;
3018                 redir = redir->next;
3019         }
3020         redir = xzalloc(sizeof(struct redir_struct));
3021         /* redir->next = NULL; */
3022         /* redir->rd_filename = NULL; */
3023         if (last_redir) {
3024                 last_redir->next = redir;
3025         } else {
3026                 command->redirects = redir;
3027         }
3028
3029         redir->rd_type = style;
3030         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3031
3032         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3033
3034         /* Check for a '2>&1' type redirect */
3035         redir->dup = redirect_dup_num(input);
3036         if (redir->dup == -2)
3037                 return 1;  /* syntax error */
3038         if (redir->dup != -1) {
3039                 /* Erik had a check here that the file descriptor in question
3040                  * is legit; I postpone that to "run time"
3041                  * A "-" representation of "close me" shows up as a -3 here */
3042                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3043         } else {
3044                 /* We do _not_ try to open the file that src points to,
3045                  * since we need to return and let src be expanded first.
3046                  * Set ctx->pending_redirect, so we know what to do at the
3047                  * end of the next parsed word. */
3048                 ctx->pending_redirect = redir;
3049         }
3050         return 0;
3051 }
3052
3053
3054 static struct pipe *new_pipe(void)
3055 {
3056         struct pipe *pi;
3057         pi = xzalloc(sizeof(struct pipe));
3058         /*pi->followup = 0; - deliberately invalid value */
3059         /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3060         return pi;
3061 }
3062
3063 /* Command (member of a pipe) is complete. The only possible error here
3064  * is out of memory, in which case xmalloc exits. */
3065 static int done_command(struct parse_context *ctx)
3066 {
3067         /* The command is really already in the pipe structure, so
3068          * advance the pipe counter and make a new, null command. */
3069         struct pipe *pi = ctx->pipe;
3070         struct command *command = ctx->command;
3071
3072         if (command) {
3073                 if (command->group == NULL
3074                  && command->argv == NULL
3075                  && command->redirects == NULL
3076                 ) {
3077                         debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3078                         return pi->num_cmds;
3079                 }
3080                 pi->num_cmds++;
3081                 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3082         } else {
3083                 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3084         }
3085
3086         /* Only real trickiness here is that the uncommitted
3087          * command structure is not counted in pi->num_cmds. */
3088         pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3089         command = &pi->cmds[pi->num_cmds];
3090         memset(command, 0, sizeof(*command));
3091
3092         ctx->command = command;
3093         /* but ctx->pipe and ctx->list_head remain unchanged */
3094
3095         return pi->num_cmds; /* used only for 0/nonzero check */
3096 }
3097
3098 static void done_pipe(struct parse_context *ctx, pipe_style type)
3099 {
3100         int not_null;
3101
3102         debug_printf_parse("done_pipe entered, followup %d\n", type);
3103         /* Close previous command */
3104         not_null = done_command(ctx);
3105         ctx->pipe->followup = type;
3106         IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3107         IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3108         IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3109
3110         /* Without this check, even just <enter> on command line generates
3111          * tree of three NOPs (!). Which is harmless but annoying.
3112          * IOW: it is safe to do it unconditionally.
3113          * RES_NONE case is for "for a in; do ..." (empty IN set)
3114          * to work, possibly other cases too. */
3115         if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3116                 struct pipe *new_p;
3117                 debug_printf_parse("done_pipe: adding new pipe: "
3118                                 "not_null:%d ctx->ctx_res_w:%d\n",
3119                                 not_null, ctx->ctx_res_w);
3120                 new_p = new_pipe();
3121                 ctx->pipe->next = new_p;
3122                 ctx->pipe = new_p;
3123                 ctx->command = NULL; /* needed! */
3124                 /* RES_THEN, RES_DO etc are "sticky" -
3125                  * they remain set for commands inside if/while.
3126                  * This is used to control execution.
3127                  * RES_FOR and RES_IN are NOT sticky (needed to support
3128                  * cases where variable or value happens to match a keyword):
3129                  */
3130 #if ENABLE_HUSH_LOOPS
3131                 if (ctx->ctx_res_w == RES_FOR
3132                  || ctx->ctx_res_w == RES_IN)
3133                         ctx->ctx_res_w = RES_NONE;
3134 #endif
3135 #if ENABLE_HUSH_CASE
3136                 if (ctx->ctx_res_w == RES_MATCH)
3137                         ctx->ctx_res_w = RES_CASEI;
3138 #endif
3139                 /* Create the memory for command, roughly:
3140                  * ctx->pipe->cmds = new struct command;
3141                  * ctx->command = &ctx->pipe->cmds[0];
3142                  */
3143                 done_command(ctx);
3144         }
3145         debug_printf_parse("done_pipe return\n");
3146 }
3147
3148 static void initialize_context(struct parse_context *ctx)
3149 {
3150         memset(ctx, 0, sizeof(*ctx));
3151         ctx->pipe = ctx->list_head = new_pipe();
3152         /* Create the memory for command, roughly:
3153          * ctx->pipe->cmds = new struct command;
3154          * ctx->command = &ctx->pipe->cmds[0];
3155          */
3156         done_command(ctx);
3157 }
3158
3159
3160 /* If a reserved word is found and processed, parse context is modified
3161  * and 1 is returned.
3162  * Handles if, then, elif, else, fi, for, while, until, do, done.
3163  * case, function, and select are obnoxious, save those for later.
3164  */
3165 #if HAS_KEYWORDS
3166 struct reserved_combo {
3167         char literal[6];
3168         unsigned char res;
3169         unsigned char assignment_flag;
3170         int flag;
3171 };
3172 enum {
3173         FLAG_END   = (1 << RES_NONE ),
3174 #if ENABLE_HUSH_IF
3175         FLAG_IF    = (1 << RES_IF   ),
3176         FLAG_THEN  = (1 << RES_THEN ),
3177         FLAG_ELIF  = (1 << RES_ELIF ),
3178         FLAG_ELSE  = (1 << RES_ELSE ),
3179         FLAG_FI    = (1 << RES_FI   ),
3180 #endif
3181 #if ENABLE_HUSH_LOOPS
3182         FLAG_FOR   = (1 << RES_FOR  ),
3183         FLAG_WHILE = (1 << RES_WHILE),
3184         FLAG_UNTIL = (1 << RES_UNTIL),
3185         FLAG_DO    = (1 << RES_DO   ),
3186         FLAG_DONE  = (1 << RES_DONE ),
3187         FLAG_IN    = (1 << RES_IN   ),
3188 #endif
3189 #if ENABLE_HUSH_CASE
3190         FLAG_MATCH = (1 << RES_MATCH),
3191         FLAG_ESAC  = (1 << RES_ESAC ),
3192 #endif
3193         FLAG_START = (1 << RES_XXXX ),
3194 };
3195
3196 static const struct reserved_combo* match_reserved_word(o_string *word)
3197 {
3198         /* Mostly a list of accepted follow-up reserved words.
3199          * FLAG_END means we are done with the sequence, and are ready
3200          * to turn the compound list into a command.
3201          * FLAG_START means the word must start a new compound list.
3202          */
3203         static const struct reserved_combo reserved_list[] = {
3204 #if ENABLE_HUSH_IF
3205                 { "!",     RES_NONE,  NOT_ASSIGNMENT , 0 },
3206                 { "if",    RES_IF,    WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3207                 { "then",  RES_THEN,  WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3208                 { "elif",  RES_ELIF,  WORD_IS_KEYWORD, FLAG_THEN },
3209                 { "else",  RES_ELSE,  WORD_IS_KEYWORD, FLAG_FI   },
3210                 { "fi",    RES_FI,    NOT_ASSIGNMENT , FLAG_END  },
3211 #endif
3212 #if ENABLE_HUSH_LOOPS
3213                 { "for",   RES_FOR,   NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3214                 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3215                 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3216                 { "in",    RES_IN,    NOT_ASSIGNMENT , FLAG_DO   },
3217                 { "do",    RES_DO,    WORD_IS_KEYWORD, FLAG_DONE },
3218                 { "done",  RES_DONE,  NOT_ASSIGNMENT , FLAG_END  },
3219 #endif
3220 #if ENABLE_HUSH_CASE
3221                 { "case",  RES_CASE,  NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3222                 { "esac",  RES_ESAC,  NOT_ASSIGNMENT , FLAG_END  },
3223 #endif
3224         };
3225         const struct reserved_combo *r;
3226
3227         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3228                 if (strcmp(word->data, r->literal) == 0)
3229                         return r;
3230         }
3231         return NULL;
3232 }
3233 static int reserved_word(o_string *word, struct parse_context *ctx)
3234 {
3235 #if ENABLE_HUSH_CASE
3236         static const struct reserved_combo reserved_match = {
3237                 "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3238         };
3239 #endif
3240         const struct reserved_combo *r;
3241
3242         r = match_reserved_word(word);
3243         if (!r)
3244                 return 0;
3245
3246         debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3247 #if ENABLE_HUSH_CASE
3248         if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3249                 /* "case word IN ..." - IN part starts first match part */
3250                 r = &reserved_match;
3251         else
3252 #endif
3253         if (r->flag == 0) { /* '!' */
3254                 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3255                         syntax(NULL);
3256                         IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3257                 }
3258                 ctx->ctx_inverted = 1;
3259                 return 1;
3260         }
3261         if (r->flag & FLAG_START) {
3262                 struct parse_context *new;
3263                 debug_printf("push stack\n");
3264                 new = xmalloc(sizeof(*new));
3265                 *new = *ctx;   /* physical copy */
3266                 initialize_context(ctx);
3267                 ctx->stack = new;
3268         } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3269                 syntax(NULL);
3270                 ctx->ctx_res_w = RES_SNTX;
3271                 return 1;
3272         }
3273         ctx->ctx_res_w = r->res;
3274         ctx->old_flag = r->flag;
3275         if (ctx->old_flag & FLAG_END) {
3276                 struct parse_context *old;
3277                 debug_printf("pop stack\n");
3278                 done_pipe(ctx, PIPE_SEQ);
3279                 old = ctx->stack;
3280                 old->command->group = ctx->list_head;
3281                 old->command->grp_type = GRP_NORMAL;
3282                 *ctx = *old;   /* physical copy */
3283                 free(old);
3284         }
3285         word->o_assignment = r->assignment_flag;
3286         return 1;
3287 }
3288 #endif
3289
3290 //TODO: many, many callers don't check error from done_word()
3291
3292 /* Word is complete, look at it and update parsing context.
3293  * Normal return is 0. Syntax errors return 1. */
3294 static int done_word(o_string *word, struct parse_context *ctx)
3295 {
3296         struct command *command = ctx->command;
3297
3298         debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3299         if (word->length == 0 && word->nonnull == 0) {
3300                 debug_printf_parse("done_word return 0: true null, ignored\n");
3301                 return 0;
3302         }
3303         /* If this word wasn't an assignment, next ones definitely
3304          * can't be assignments. Even if they look like ones. */
3305         if (word->o_assignment != DEFINITELY_ASSIGNMENT
3306          && word->o_assignment != WORD_IS_KEYWORD
3307         ) {
3308                 word->o_assignment = NOT_ASSIGNMENT;
3309         } else {
3310                 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3311                         command->assignment_cnt++;
3312                 word->o_assignment = MAYBE_ASSIGNMENT;
3313         }
3314
3315         if (ctx->pending_redirect) {
3316                 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3317                  * only if run as "bash", not "sh" */
3318                 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3319                 word->o_assignment = NOT_ASSIGNMENT;
3320                 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3321         } else {
3322                 /* "{ echo foo; } echo bar" - bad */
3323                 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3324                 if (command->group) {
3325                         syntax(NULL);
3326                         debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3327                         return 1;
3328                 }
3329 #if HAS_KEYWORDS
3330 #if ENABLE_HUSH_CASE
3331                 if (ctx->ctx_dsemicolon
3332                  && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3333                 ) {
3334                         /* already done when ctx_dsemicolon was set to 1: */
3335                         /* ctx->ctx_res_w = RES_MATCH; */
3336                         ctx->ctx_dsemicolon = 0;
3337                 } else
3338 #endif
3339
3340                 if (!command->argv /* if it's the first word... */
3341 #if ENABLE_HUSH_LOOPS
3342                  && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3343                  && ctx->ctx_res_w != RES_IN
3344 #endif
3345                 ) {
3346                         debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3347                         if (reserved_word(word, ctx)) {
3348                                 o_reset(word);
3349                                 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3350                                 return (ctx->ctx_res_w == RES_SNTX);
3351                         }
3352                 }
3353 #endif
3354                 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3355                  /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3356                  && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3357                  /* (otherwise it's known to be not empty and is already safe) */
3358                 ) {
3359                         /* exclude "$@" - it can expand to no word despite "" */
3360                         char *p = word->data;
3361                         while (p[0] == SPECIAL_VAR_SYMBOL
3362                             && (p[1] & 0x7f) == '@'
3363                             && p[2] == SPECIAL_VAR_SYMBOL
3364                         ) {
3365                                 p += 3;
3366                         }
3367                         if (p == word->data || p[0] != '\0') {
3368                                 /* saw no "$@", or not only "$@" but some
3369                                  * real text is there too */
3370                                 /* insert "empty variable" reference, this makes
3371                                  * e.g. "", $empty"" etc to not disappear */
3372                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3373                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3374                         }
3375                 }
3376                 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3377                 debug_print_strings("word appended to argv", command->argv);
3378         }
3379
3380         o_reset(word);
3381         ctx->pending_redirect = NULL;
3382
3383 #if ENABLE_HUSH_LOOPS
3384         /* Force FOR to have just one word (variable name) */
3385         /* NB: basically, this makes hush see "for v in ..." syntax as if
3386          * as it is "for v; in ...". FOR and IN become two pipe structs
3387          * in parse tree. */
3388         if (ctx->ctx_res_w == RES_FOR) {
3389 //TODO: check that command->argv[0] is a valid variable name!
3390                 done_pipe(ctx, PIPE_SEQ);
3391         }
3392 #endif
3393 #if ENABLE_HUSH_CASE
3394         /* Force CASE to have just one word */
3395         if (ctx->ctx_res_w == RES_CASE) {
3396                 done_pipe(ctx, PIPE_SEQ);
3397         }
3398 #endif
3399         debug_printf_parse("done_word return 0\n");
3400         return 0;
3401 }
3402
3403 /* If a redirect is immediately preceded by a number, that number is
3404  * supposed to tell which file descriptor to redirect.  This routine
3405  * looks for such preceding numbers.  In an ideal world this routine
3406  * needs to handle all the following classes of redirects...
3407  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
3408  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
3409  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
3410  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
3411  * A -1 output from this program means no valid number was found, so the
3412  * caller should use the appropriate default for this redirection.
3413  */
3414 static int redirect_opt_num(o_string *o)
3415 {
3416         int num;
3417
3418         if (o->length == 0)
3419                 return -1;
3420         for (num = 0; num < o->length; num++) {
3421                 if (!isdigit(o->data[num])) {
3422                         return -1;
3423                 }
3424         }
3425         num = atoi(o->data);
3426         o_reset(o);
3427         return num;
3428 }
3429
3430 static int parse_stream(o_string *dest, struct parse_context *ctx,
3431                 struct in_str *input0, const char *end_trigger);
3432
3433 #if ENABLE_HUSH_TICK
3434 static FILE *generate_stream_from_list(struct pipe *head)
3435 {
3436         FILE *pf;
3437         int pid, channel[2];
3438
3439         xpipe(channel);
3440 /* *** NOMMU WARNING *** */
3441 /* By using vfork here, we suspend parent till child exits or execs.
3442  * If child will not do it before it fills the pipe, it can block forever
3443  * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3444  * Try this script:
3445  * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3446  * huge=`cat TESTFILE` # will block here forever
3447  * echo OK
3448  */
3449         pid = BB_MMU ? fork() : vfork();
3450         if (pid < 0)
3451                 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3452         if (pid == 0) { /* child */
3453                 if (ENABLE_HUSH_JOB)
3454                         die_sleep = 0; /* let nofork's xfuncs die */
3455                 close(channel[0]); /* NB: close _first_, then move fd! */
3456                 xmove_fd(channel[1], 1);
3457                 /* Prevent it from trying to handle ctrl-z etc */
3458 #if ENABLE_HUSH_JOB
3459                 G.run_list_level = 1;
3460 #endif
3461                 /* Process substitution is not considered to be usual
3462                  * 'command execution'.
3463                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3464                 /* Not needed, we are relying on it being disabled
3465                  * everywhere outside actual command execution. */
3466                 /*set_jobctrl_sighandler(SIG_IGN);*/
3467                 set_misc_sighandler(SIG_DFL);
3468                 /* Freeing 'head' here would break NOMMU. */
3469                 _exit(run_list(head));
3470         }
3471         close(channel[1]);
3472         pf = fdopen(channel[0], "r");
3473         return pf;
3474         /* 'head' is freed by the caller */
3475 }
3476
3477 /* Return code is exit status of the process that is run. */
3478 static int process_command_subs(o_string *dest,
3479                 struct in_str *input,
3480                 const char *subst_end)
3481 {
3482         int retcode, ch, eol_cnt;
3483         o_string result = NULL_O_STRING;
3484         struct parse_context inner;
3485         FILE *p;
3486         struct in_str pipe_str;
3487
3488         initialize_context(&inner);
3489
3490         /* Recursion to generate command */
3491         retcode = parse_stream(&result, &inner, input, subst_end);
3492         if (retcode != 0)
3493                 return retcode;  /* syntax error or EOF */
3494         done_word(&result, &inner);
3495         done_pipe(&inner, PIPE_SEQ);
3496         o_free(&result);
3497
3498         p = generate_stream_from_list(inner.list_head);
3499         if (p == NULL)
3500                 return 1;
3501         close_on_exec_on(fileno(p));
3502         setup_file_in_str(&pipe_str, p);
3503
3504         /* Now send results of command back into original context */
3505         eol_cnt = 0;
3506         while ((ch = i_getch(&pipe_str)) != EOF) {
3507                 if (ch == '\n') {
3508                         eol_cnt++;
3509                         continue;
3510                 }
3511                 while (eol_cnt) {
3512                         o_addchr(dest, '\n');
3513                         eol_cnt--;
3514                 }
3515                 o_addQchr(dest, ch);
3516         }
3517
3518         debug_printf("done reading from pipe, pclose()ing\n");
3519         /* This is the step that wait()s for the child.  Should be pretty
3520          * safe, since we just read an EOF from its stdout.  We could try
3521          * to do better, by using wait(), and keeping track of background jobs
3522          * at the same time.  That would be a lot of work, and contrary
3523          * to the KISS philosophy of this program. */
3524         retcode = fclose(p);
3525         free_pipe_list(inner.list_head, /* indent: */ 0);
3526         debug_printf("closed FILE from child, retcode=%d\n", retcode);
3527         return retcode;
3528 }
3529 #endif
3530
3531 static int parse_group(o_string *dest, struct parse_context *ctx,
3532         struct in_str *input, int ch)
3533 {
3534         /* dest contains characters seen prior to ( or {.
3535          * Typically it's empty, but for functions defs,
3536          * it contains function name (without '()'). */
3537         int rcode;
3538         const char *endch = NULL;
3539         struct parse_context sub;
3540         struct command *command = ctx->command;
3541
3542         debug_printf_parse("parse_group entered\n");
3543 #if ENABLE_HUSH_FUNCTIONS
3544         if (ch == 'F') { /* function definition? */
3545                 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3546                 //command->fname = dest->data;
3547                 command->grp_type = GRP_FUNCTION;
3548 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3549                 memset(dest, 0, sizeof(*dest));
3550         }
3551 #endif
3552         if (command->argv /* word [word](... */
3553          || dest->length /* word(... */
3554          || dest->nonnull /* ""(... */
3555         ) {
3556                 syntax(NULL);
3557                 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3558                 return 1;
3559         }
3560         initialize_context(&sub);
3561         endch = "}";
3562         if (ch == '(') {
3563                 endch = ")";
3564                 command->grp_type = GRP_SUBSHELL;
3565         }
3566         rcode = parse_stream(dest, &sub, input, endch);
3567         if (rcode == 0) {
3568                 done_word(dest, &sub); /* finish off the final word in the subcontext */
3569                 done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
3570                 command->group = sub.list_head;
3571         }
3572         debug_printf_parse("parse_group return %d\n", rcode);
3573         return rcode;
3574         /* command remains "open", available for possible redirects */
3575 }
3576
3577 #if ENABLE_HUSH_TICK
3578 /* Subroutines for copying $(...) and `...` things */
3579 static void add_till_backquote(o_string *dest, struct in_str *input);
3580 /* '...' */
3581 static void add_till_single_quote(o_string *dest, struct in_str *input)
3582 {
3583         while (1) {
3584                 int ch = i_getch(input);
3585                 if (ch == EOF)
3586                         break;
3587                 if (ch == '\'')
3588                         break;
3589                 o_addchr(dest, ch);
3590         }
3591 }
3592 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3593 static void add_till_double_quote(o_string *dest, struct in_str *input)
3594 {
3595         while (1) {
3596                 int ch = i_getch(input);
3597                 if (ch == '"')
3598                         break;
3599                 if (ch == '\\') {  /* \x. Copy both chars. */
3600                         o_addchr(dest, ch);
3601                         ch = i_getch(input);
3602                 }
3603                 if (ch == EOF)
3604                         break;
3605                 o_addchr(dest, ch);
3606                 if (ch == '`') {
3607                         add_till_backquote(dest, input);
3608                         o_addchr(dest, ch);
3609                         continue;
3610                 }
3611                 //if (ch == '$') ...
3612         }
3613 }
3614 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3615  * \` quoting.
3616  * "Within the backquoted style of command substitution, backslash
3617  * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3618  * The search for the matching backquote shall be satisfied by the first
3619  * backquote found without a preceding backslash; during this search,
3620  * if a non-escaped backquote is encountered within a shell comment,
3621  * a here-document, an embedded command substitution of the $(command)
3622  * form, or a quoted string, undefined results occur. A single-quoted
3623  * or double-quoted string that begins, but does not end, within the
3624  * "`...`" sequence produces undefined results."
3625  * Example                               Output
3626  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
3627  */
3628 static void add_till_backquote(o_string *dest, struct in_str *input)
3629 {
3630         while (1) {
3631                 int ch = i_getch(input);
3632                 if (ch == '`')
3633                         break;
3634                 if (ch == '\\') {  /* \x. Copy both chars unless it is \` */
3635                         int ch2 = i_getch(input);
3636                         if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3637                                 o_addchr(dest, ch);
3638                         ch = ch2;
3639                 }
3640                 if (ch == EOF)
3641                         break;
3642                 o_addchr(dest, ch);
3643         }
3644 }
3645 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3646  * quoting and nested ()s.
3647  * "With the $(command) style of command substitution, all characters
3648  * following the open parenthesis to the matching closing parenthesis
3649  * constitute the command. Any valid shell script can be used for command,
3650  * except a script consisting solely of redirections which produces
3651  * unspecified results."
3652  * Example                              Output
3653  * echo $(echo '(TEST)' BEST)           (TEST) BEST
3654  * echo $(echo 'TEST)' BEST)            TEST) BEST
3655  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
3656  */
3657 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3658 {
3659         int count = 0;
3660         while (1) {
3661                 int ch = i_getch(input);
3662                 if (ch == EOF)
3663                         break;
3664                 if (ch == '(')
3665                         count++;
3666                 if (ch == ')')
3667                         if (--count < 0)
3668                                 break;
3669                 o_addchr(dest, ch);
3670                 if (ch == '\'') {
3671                         add_till_single_quote(dest, input);
3672                         o_addchr(dest, ch);
3673                         continue;
3674                 }
3675                 if (ch == '"') {
3676                         add_till_double_quote(dest, input);
3677                         o_addchr(dest, ch);
3678                         continue;
3679                 }
3680                 if (ch == '\\') { /* \x. Copy verbatim. Important for  \(, \) */
3681                         ch = i_getch(input);
3682                         if (ch == EOF)
3683                                 break;
3684                         o_addchr(dest, ch);
3685                         continue;
3686                 }
3687         }
3688 }
3689 #endif /* ENABLE_HUSH_TICK */
3690
3691 /* Return code: 0 for OK, 1 for syntax error */
3692 static int handle_dollar(o_string *dest, struct in_str *input)
3693 {
3694         int expansion;
3695         int ch = i_peek(input);  /* first character after the $ */
3696         unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3697
3698         debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3699         if (isalpha(ch)) {
3700                 i_getch(input);
3701  make_var:
3702                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3703                 while (1) {
3704                         debug_printf_parse(": '%c'\n", ch);
3705                         o_addchr(dest, ch | quote_mask);
3706                         quote_mask = 0;
3707                         ch = i_peek(input);
3708                         if (!isalnum(ch) && ch != '_')
3709                                 break;
3710                         i_getch(input);
3711                 }
3712                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3713         } else if (isdigit(ch)) {
3714  make_one_char_var:
3715                 i_getch(input);
3716                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3717                 debug_printf_parse(": '%c'\n", ch);
3718                 o_addchr(dest, ch | quote_mask);
3719                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720         } else switch (ch) {
3721                 case '$': /* pid */
3722                 case '!': /* last bg pid */
3723                 case '?': /* last exit code */
3724                 case '#': /* number of args */
3725                 case '*': /* args */
3726                 case '@': /* args */
3727                         goto make_one_char_var;
3728                 case '{': {
3729                         bool first_char;
3730
3731                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3732                         i_getch(input);
3733                         /* XXX maybe someone will try to escape the '}' */
3734                         expansion = 0;
3735                         first_char = true;
3736                         while (1) {
3737                                 ch = i_getch(input);
3738                                 if (ch == '}')
3739                                         break;
3740
3741                                 if (ch == '#' && first_char)
3742                                         /* ${#var}: length of var contents */;
3743
3744                                 else if (expansion < 2 && !isalnum(ch) && ch != '_') {
3745                                         /* handle parameter expansions
3746                                          * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3747                                          */
3748                                         if (first_char)
3749                                                 goto case_default;
3750                                         switch (ch) {
3751                                                 case ':': /* null modifier */
3752                                                         if (expansion == 0) {
3753                                                                 debug_printf_parse(": null modifier\n");
3754                                                                 ++expansion;
3755                                                                 break;
3756                                                         }
3757                                                         goto case_default;
3758
3759 #if 0 /* not implemented yet :( */
3760                                                 case '#': /* remove prefix */
3761                                                 case '%': /* remove suffix */
3762                                                         if (expansion == 0) {
3763                                                                 debug_printf_parse(": remove suffix/prefix\n");
3764                                                                 expansion = 2;
3765                                                                 break;
3766                                                         }
3767                                                         goto case_default;
3768 #endif
3769
3770                                                 case '-': /* default value */
3771                                                 case '=': /* assign default */
3772                                                 case '+': /* alternative */
3773                                                 case '?': /* error indicate */
3774                                                         debug_printf_parse(": parameter expansion\n");
3775                                                         expansion = 2;
3776                                                         break;
3777
3778                                                 default:
3779                                                 case_default:
3780                                                         syntax("unterminated ${name}");
3781                                                         debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3782                                                         return 1;
3783                                                 }
3784                                 }
3785                                 debug_printf_parse(": '%c'\n", ch);
3786                                 o_addchr(dest, ch | quote_mask);
3787                                 quote_mask = 0;
3788                                 first_char = false;
3789                         }
3790                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3791                         break;
3792                 }
3793 #if ENABLE_HUSH_TICK
3794                 case '(': {
3795                         //int pos = dest->length;
3796                         i_getch(input);
3797                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3798                         o_addchr(dest, quote_mask | '`');
3799                         add_till_closing_curly_brace(dest, input);
3800                         //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3801                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3802                         break;
3803                 }
3804 #endif
3805                 case '_':
3806                         i_getch(input);
3807                         ch = i_peek(input);
3808                         if (isalnum(ch)) { /* it's $_name or $_123 */
3809                                 ch = '_';
3810                                 goto make_var;
3811                         }
3812                         /* else: it's $_ */
3813                 case '-':
3814                         /* still unhandled, but should be eventually */
3815                         bb_error_msg("unhandled syntax: $%c", ch);
3816                         return 1;
3817                         break;
3818                 default:
3819                         o_addQchr(dest, '$');
3820         }
3821         debug_printf_parse("handle_dollar return 0\n");
3822         return 0;
3823 }
3824
3825 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3826  * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3827  * Return code is 0 if end_trigger char is met,
3828  * -1 on EOF (but if end_trigger == NULL then return 0),
3829  * 1 for syntax error */
3830 static int parse_stream(o_string *dest, struct parse_context *ctx,
3831                 struct in_str *input, const char *end_trigger)
3832 {
3833         int ch, m;
3834         int redir_fd;
3835         redir_type redir_style;
3836         int shadow_quote = dest->o_quote;
3837         int next;
3838
3839         /* Only double-quote state is handled in the state variable dest->o_quote.
3840          * A single-quote triggers a bypass of the main loop until its mate is
3841          * found.  When recursing, quote state is passed in via dest->o_quote. */
3842
3843         debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3844
3845         while (1) {
3846                 m = CHAR_IFS;
3847                 next = '\0';
3848                 ch = i_getch(input);
3849                 if (ch != EOF) {
3850                         m = G.charmap[ch];
3851                         if (ch != '\n') {
3852                                 next = i_peek(input);
3853                         }
3854                 }
3855                 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3856                                                 ch, ch, m, dest->o_quote);
3857                 if (m == CHAR_ORDINARY
3858                  || (m != CHAR_SPECIAL && shadow_quote)
3859                 ) {
3860                         if (ch == EOF) {
3861                                 syntax("unterminated \"");
3862                                 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3863                                 return 1;
3864                         }
3865                         o_addQchr(dest, ch);
3866                         if ((dest->o_assignment == MAYBE_ASSIGNMENT
3867                             || dest->o_assignment == WORD_IS_KEYWORD)
3868                          && ch == '='
3869                          && is_assignment(dest->data)
3870                         ) {
3871                                 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3872                         }
3873                         continue;
3874                 }
3875                 if (m == CHAR_IFS) {
3876                         if (done_word(dest, ctx)) {
3877                                 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3878                                 return 1;
3879                         }
3880                         if (ch == EOF)
3881                                 break;
3882                         /* If we aren't performing a substitution, treat
3883                          * a newline as a command separator.
3884                          * [why we don't handle it exactly like ';'? --vda] */
3885                         if (end_trigger && ch == '\n') {
3886 #if ENABLE_HUSH_CASE
3887                                 /* "case ... in <newline> word) ..." -
3888                                  * newlines are ignored (but ';' wouldn't be) */
3889                                 if (dest->length == 0 // && argv[0] == NULL
3890                                  && ctx->ctx_res_w == RES_MATCH
3891                                 ) {
3892                                         continue;
3893                                 }
3894 #endif
3895                                 done_pipe(ctx, PIPE_SEQ);
3896                                 dest->o_assignment = MAYBE_ASSIGNMENT;
3897                         }
3898                 }
3899                 if (end_trigger) {
3900                         if (!shadow_quote && strchr(end_trigger, ch)) {
3901                                 /* Special case: (...word) makes last word terminate,
3902                                  * as if ';' is seen */
3903                                 if (ch == ')') {
3904                                         done_word(dest, ctx);
3905 //err chk?
3906                                         done_pipe(ctx, PIPE_SEQ);
3907                                         dest->o_assignment = MAYBE_ASSIGNMENT;
3908                                 }
3909                                 if (!HAS_KEYWORDS
3910                                  IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3911                                 ) {
3912                                         debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3913                                         return 0;
3914                                 }
3915                         }
3916                 }
3917                 if (m == CHAR_IFS)
3918                         continue;
3919
3920                 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3921                         /* ch is a special char and thus this word
3922                          * cannot be an assignment: */
3923                         dest->o_assignment = NOT_ASSIGNMENT;
3924                 }
3925
3926                 switch (ch) {
3927                 case '#':
3928                         if (dest->length == 0 && !shadow_quote) {
3929                                 while (1) {
3930                                         ch = i_peek(input);
3931                                         if (ch == EOF || ch == '\n')
3932                                                 break;
3933                                         i_getch(input);
3934                                 }
3935                         } else {
3936                                 o_addQchr(dest, ch);
3937                         }
3938                         break;
3939                 case '\\':
3940                         if (next == EOF) {
3941                                 syntax("\\<eof>");
3942                                 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3943                                 return 1;
3944                         }
3945                         /* bash:
3946                          * "The backslash retains its special meaning [in "..."]
3947                          * only when followed by one of the following characters:
3948                          * $, `, ", \, or <newline>.  A double quote may be quoted
3949                          * within double quotes by preceding it with a  backslash.
3950                          * If enabled, history expansion will be performed unless
3951                          * an ! appearing in double quotes is escaped using
3952                          * a backslash. The backslash preceding the ! is not removed."
3953                          */
3954                         if (shadow_quote) { //NOT SURE   dest->o_quote) {
3955                                 if (strchr("$`\"\\", next) != NULL) {
3956                                         o_addqchr(dest, i_getch(input));
3957                                 } else {
3958                                         o_addqchr(dest, '\\');
3959                                 }
3960                         } else {
3961                                 o_addchr(dest, '\\');
3962                                 o_addchr(dest, i_getch(input));
3963                         }
3964                         break;
3965                 case '$':
3966                         if (handle_dollar(dest, input) != 0) {
3967                                 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3968                                 return 1;
3969                         }
3970                         break;
3971                 case '\'':
3972                         dest->nonnull = 1;
3973                         while (1) {
3974                                 ch = i_getch(input);
3975                                 if (ch == EOF) {
3976                                         syntax("unterminated '");
3977                                         debug_printf_parse("parse_stream return 1: unterminated '\n");
3978                                         return 1;
3979                                 }
3980                                 if (ch == '\'')
3981                                         break;
3982                                 if (dest->o_assignment == NOT_ASSIGNMENT)
3983                                         o_addqchr(dest, ch);
3984                                 else
3985                                         o_addchr(dest, ch);
3986                         }
3987                         break;
3988                 case '"':
3989                         dest->nonnull = 1;
3990                         shadow_quote ^= 1; /* invert */
3991                         if (dest->o_assignment == NOT_ASSIGNMENT)
3992                                 dest->o_quote ^= 1;
3993                         break;
3994 #if ENABLE_HUSH_TICK
3995                 case '`': {
3996                         //int pos = dest->length;
3997                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3998                         o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
3999                         add_till_backquote(dest, input);
4000                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
4001                         //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4002                         break;
4003                 }
4004 #endif
4005                 case '>':
4006                         redir_fd = redirect_opt_num(dest);
4007                         done_word(dest, ctx);
4008                         redir_style = REDIRECT_OVERWRITE;
4009                         if (next == '>') {
4010                                 redir_style = REDIRECT_APPEND;
4011                                 i_getch(input);
4012                         }
4013 #if 0
4014                         else if (next == '(') {
4015                                 syntax(">(process) not supported");
4016                                 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
4017                                 return 1;
4018                         }
4019 #endif
4020                         setup_redirect(ctx, redir_fd, redir_style, input);
4021                         break;
4022                 case '<':
4023                         redir_fd = redirect_opt_num(dest);
4024                         done_word(dest, ctx);
4025                         redir_style = REDIRECT_INPUT;
4026                         if (next == '<') {
4027                                 redir_style = REDIRECT_HEREIS;
4028                                 i_getch(input);
4029                         } else if (next == '>') {
4030                                 redir_style = REDIRECT_IO;
4031                                 i_getch(input);
4032                         }
4033 #if 0
4034                         else if (next == '(') {
4035                                 syntax("<(process) not supported");
4036                                 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
4037                                 return 1;
4038                         }
4039 #endif
4040                         setup_redirect(ctx, redir_fd, redir_style, input);
4041                         break;
4042                 case ';':
4043 #if ENABLE_HUSH_CASE
4044  case_semi:
4045 #endif
4046                         done_word(dest, ctx);
4047                         done_pipe(ctx, PIPE_SEQ);
4048 #if ENABLE_HUSH_CASE
4049                         /* Eat multiple semicolons, detect
4050                          * whether it means something special */
4051                         while (1) {
4052                                 ch = i_peek(input);
4053                                 if (ch != ';')
4054                                         break;
4055                                 i_getch(input);
4056                                 if (ctx->ctx_res_w == RES_CASEI) {
4057                                         ctx->ctx_dsemicolon = 1;
4058                                         ctx->ctx_res_w = RES_MATCH;
4059                                         break;
4060                                 }
4061                         }
4062 #endif
4063  new_cmd:
4064                         /* We just finished a cmd. New one may start
4065                          * with an assignment */
4066                         dest->o_assignment = MAYBE_ASSIGNMENT;
4067                         break;
4068                 case '&':
4069                         done_word(dest, ctx);
4070                         if (next == '&') {
4071                                 i_getch(input);
4072                                 done_pipe(ctx, PIPE_AND);
4073                         } else {
4074                                 done_pipe(ctx, PIPE_BG);
4075                         }
4076                         goto new_cmd;
4077                 case '|':
4078                         done_word(dest, ctx);
4079 #if ENABLE_HUSH_CASE
4080                         if (ctx->ctx_res_w == RES_MATCH)
4081                                 break; /* we are in case's "word | word)" */
4082 #endif
4083                         if (next == '|') { /* || */
4084                                 i_getch(input);
4085                                 done_pipe(ctx, PIPE_OR);
4086                         } else {
4087                                 /* we could pick up a file descriptor choice here
4088                                  * with redirect_opt_num(), but bash doesn't do it.
4089                                  * "echo foo 2| cat" yields "foo 2". */
4090                                 done_command(ctx);
4091                         }
4092                         goto new_cmd;
4093                 case '(':
4094 #if ENABLE_HUSH_CASE
4095                         /* "case... in [(]word)..." - skip '(' */
4096                         if (ctx->ctx_res_w == RES_MATCH
4097                          && ctx->command->argv == NULL /* not (word|(... */
4098                          && dest->length == 0 /* not word(... */
4099                          && dest->nonnull == 0 /* not ""(... */
4100                         ) {
4101                                 continue;
4102                         }
4103 #endif
4104 #if ENABLE_HUSH_FUNCTIONS
4105                         if (dest->length != 0 /* not just () but word() */
4106                          && dest->nonnull == 0 /* not a"b"c() */
4107                          && ctx->command->argv == NULL /* it's the first word */
4108 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4109                          && i_peek(input) == ')'
4110                          && !match_reserved_word(dest)
4111                         ) {
4112                                 bb_error_msg("seems like a function definition");
4113                                 i_getch(input);
4114                                 do {
4115 //TODO: do it properly.
4116                                         ch = i_getch(input);
4117                                 } while (ch == ' ' || ch == '\n');
4118                                 if (ch != '{') {
4119                                         syntax("was expecting {");
4120                                         debug_printf_parse("parse_stream return 1\n");
4121                                         return 1;
4122                                 }
4123                                 ch = 'F'; /* magic value */
4124                         }
4125 #endif
4126                 case '{':
4127                         if (parse_group(dest, ctx, input, ch) != 0) {
4128                                 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4129                                 return 1;
4130                         }
4131                         goto new_cmd;
4132                 case ')':
4133 #if ENABLE_HUSH_CASE
4134                         if (ctx->ctx_res_w == RES_MATCH)
4135                                 goto case_semi;
4136 #endif
4137                 case '}':
4138                         /* proper use of this character is caught by end_trigger:
4139                          * if we see {, we call parse_group(..., end_trigger='}')
4140                          * and it will match } earlier (not here). */
4141                         syntax("unexpected } or )");
4142                         debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4143                         return 1;
4144                 default:
4145                         if (HUSH_DEBUG)
4146                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4147                 }
4148         } /* while (1) */
4149         debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4150         if (end_trigger)
4151                 return -1;
4152         return 0;
4153 }
4154
4155 static void set_in_charmap(const char *set, int code)
4156 {
4157         while (*set)
4158                 G.charmap[(unsigned char)*set++] = code;
4159 }
4160
4161 static void update_charmap(void)
4162 {
4163         G.ifs = getenv("IFS");
4164         if (G.ifs == NULL)
4165                 G.ifs = " \t\n";
4166         /* Precompute a list of 'flow through' behavior so it can be treated
4167          * quickly up front.  Computation is necessary because of IFS.
4168          * Special case handling of IFS == " \t\n" is not implemented.
4169          * The charmap[] array only really needs two bits each,
4170          * and on most machines that would be faster (reduced L1 cache use).
4171          */
4172         memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4173 #if ENABLE_HUSH_TICK
4174         set_in_charmap("\\$\"`", CHAR_SPECIAL);
4175 #else
4176         set_in_charmap("\\$\"", CHAR_SPECIAL);
4177 #endif
4178         set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4179         set_in_charmap(G.ifs, CHAR_IFS);  /* are ordinary if quoted */
4180 }
4181
4182 /* Most recursion does not come through here, the exception is
4183  * from builtin_source() and builtin_eval() */
4184 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4185 {
4186         struct parse_context ctx;
4187         o_string temp = NULL_O_STRING;
4188         int rcode;
4189
4190         do {
4191                 initialize_context(&ctx);
4192                 update_charmap();
4193 #if ENABLE_HUSH_INTERACTIVE
4194                 inp->promptmode = 0; /* PS1 */
4195 #endif
4196                 /* We will stop & execute after each ';' or '\n'.
4197                  * Example: "sleep 9999; echo TEST" + ctrl-C:
4198                  * TEST should be printed */
4199                 temp.o_assignment = MAYBE_ASSIGNMENT;
4200                 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4201 #if HAS_KEYWORDS
4202                 if (rcode != 1 && ctx.old_flag != 0) {
4203                         syntax(NULL);
4204                 }
4205 #endif
4206                 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4207                         done_word(&temp, &ctx);
4208                         done_pipe(&ctx, PIPE_SEQ);
4209                         debug_print_tree(ctx.list_head, 0);
4210                         debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4211                         run_and_free_list(ctx.list_head);
4212                 } else {
4213                         /* We arrive here also if rcode == 1 (error in parse_stream) */
4214 #if HAS_KEYWORDS
4215                         if (ctx.old_flag != 0) {
4216                                 free(ctx.stack);
4217                                 o_reset(&temp);
4218                         }
4219 #endif
4220                         /*temp.nonnull = 0; - o_free does it below */
4221                         /*temp.o_quote = 0; - o_free does it below */
4222                         free_pipe_list(ctx.list_head, /* indent: */ 0);
4223                         /* Discard all unprocessed line input, force prompt on */
4224                         inp->p = NULL;
4225 #if ENABLE_HUSH_INTERACTIVE
4226                         inp->promptme = 1;
4227 #endif
4228                 }
4229                 o_free(&temp);
4230                 /* loop on syntax errors, return on EOF: */
4231         } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4232         return 0;
4233 }
4234
4235 static int parse_and_run_string(const char *s, int parse_flag)
4236 {
4237         struct in_str input;
4238         setup_string_in_str(&input, s);
4239         return parse_and_run_stream(&input, parse_flag);
4240 }
4241
4242 static int parse_and_run_file(FILE *f)
4243 {
4244         int rcode;
4245         struct in_str input;
4246         setup_file_in_str(&input, f);
4247         rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4248         return rcode;
4249 }
4250
4251 #if ENABLE_HUSH_JOB
4252 /* Make sure we have a controlling tty.  If we get started under a job
4253  * aware app (like bash for example), make sure we are now in charge so
4254  * we don't fight over who gets the foreground */
4255 static void setup_job_control(void)
4256 {
4257         pid_t shell_pgrp;
4258
4259         shell_pgrp = getpgrp();
4260         close_on_exec_on(G.interactive_fd);
4261
4262         /* If we were ran as 'hush &',
4263          * sleep until we are in the foreground.  */
4264         while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4265                 /* Send TTIN to ourself (should stop us) */
4266                 kill(- shell_pgrp, SIGTTIN);
4267                 shell_pgrp = getpgrp();
4268         }
4269
4270         /* Ignore job-control and misc signals.  */
4271         set_jobctrl_sighandler(SIG_IGN);
4272         set_misc_sighandler(SIG_IGN);
4273 //huh?  signal(SIGCHLD, SIG_IGN);
4274
4275         /* We _must_ restore tty pgrp on fatal signals */
4276         set_fatal_sighandler(sigexit);
4277
4278         /* Put ourselves in our own process group.  */
4279         bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4280         /* Grab control of the terminal.  */
4281         tcsetpgrp(G.interactive_fd, getpid());
4282 }
4283 #endif
4284
4285
4286 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4287 int hush_main(int argc, char **argv)
4288 {
4289         static const struct variable const_shell_ver = {
4290                 .next = NULL,
4291                 .varstr = (char*)hush_version_str,
4292                 .max_len = 1, /* 0 can provoke free(name) */
4293                 .flg_export = 1,
4294                 .flg_read_only = 1,
4295         };
4296
4297         int opt;
4298         FILE *input;
4299         char **e;
4300         struct variable *cur_var;
4301
4302         INIT_G();
4303
4304         G.root_pid = getpid();
4305
4306         /* Deal with HUSH_VERSION */
4307         G.shell_ver = const_shell_ver; /* copying struct here */
4308         G.top_var = &G.shell_ver;
4309         debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4310         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4311         /* Initialize our shell local variables with the values
4312          * currently living in the environment */
4313         cur_var = G.top_var;
4314         e = environ;
4315         if (e) while (*e) {
4316                 char *value = strchr(*e, '=');
4317                 if (value) { /* paranoia */
4318                         cur_var->next = xzalloc(sizeof(*cur_var));
4319                         cur_var = cur_var->next;
4320                         cur_var->varstr = *e;
4321                         cur_var->max_len = strlen(*e);
4322                         cur_var->flg_export = 1;
4323                 }
4324                 e++;
4325         }
4326         debug_printf_env("putenv '%s'\n", hush_version_str);
4327         putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4328
4329 #if ENABLE_FEATURE_EDITING
4330         G.line_input_state = new_line_input_t(FOR_SHELL);
4331 #endif
4332         /* XXX what should these be while sourcing /etc/profile? */
4333         G.global_argc = argc;
4334         G.global_argv = argv;
4335         /* Initialize some more globals to non-zero values */
4336         set_cwd();
4337 #if ENABLE_HUSH_INTERACTIVE
4338         if (ENABLE_FEATURE_EDITING)
4339                 cmdedit_set_initial_prompt();
4340         G.PS2 = "> ";
4341 #endif
4342
4343         if (EXIT_SUCCESS) /* otherwise is already done */
4344                 G.last_return_code = EXIT_SUCCESS;
4345
4346         if (argv[0] && argv[0][0] == '-') {
4347                 debug_printf("sourcing /etc/profile\n");
4348                 input = fopen_for_read("/etc/profile");
4349                 if (input != NULL) {
4350                         close_on_exec_on(fileno(input));
4351                         parse_and_run_file(input);
4352                         fclose(input);
4353                 }
4354         }
4355         input = stdin;
4356
4357         /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4358         while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4359                 switch (opt) {
4360                 case 'c':
4361                         G.global_argv = argv + optind;
4362                         if (!argv[optind]) {
4363                                 /* -c 'script' (no params): prevent empty $0 */
4364                                 *--G.global_argv = argv[0];
4365                                 optind--;
4366                         } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4367                         G.global_argc = argc - optind;
4368                         opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4369                         goto final_return;
4370                 case 'i':
4371                         /* Well, we cannot just declare interactiveness,
4372                          * we have to have some stuff (ctty, etc) */
4373                         /* G.interactive_fd++; */
4374                         break;
4375                 case 's':
4376                         /* "-s" means "read from stdin", but this is how we always
4377                          * operate, so simply do nothing here. */
4378                         break;
4379                 case 'n':
4380                 case 'x':
4381                         if (!builtin_set_mode('-', opt))
4382                                 break;
4383                 default:
4384 #ifndef BB_VER
4385                         fprintf(stderr, "Usage: sh [FILE]...\n"
4386                                         "   or: sh -c command [args]...\n\n");
4387                         exit(EXIT_FAILURE);
4388 #else
4389                         bb_show_usage();
4390 #endif
4391                 }
4392         }
4393 #if ENABLE_HUSH_JOB
4394         /* A shell is interactive if the '-i' flag was given, or if all of
4395          * the following conditions are met:
4396          *    no -c command
4397          *    no arguments remaining or the -s flag given
4398          *    standard input is a terminal
4399          *    standard output is a terminal
4400          *    Refer to Posix.2, the description of the 'sh' utility. */
4401         if (argv[optind] == NULL && input == stdin
4402          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4403         ) {
4404                 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4405                 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4406                 if (G.saved_tty_pgrp >= 0) {
4407                         /* try to dup to high fd#, >= 255 */
4408                         G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4409                         if (G.interactive_fd < 0) {
4410                                 /* try to dup to any fd */
4411                                 G.interactive_fd = dup(STDIN_FILENO);
4412                                 if (G.interactive_fd < 0)
4413                                         /* give up */
4414                                         G.interactive_fd = 0;
4415                         }
4416                         // TODO: track & disallow any attempts of user
4417                         // to (inadvertently) close/redirect it
4418                 }
4419         }
4420         debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4421         if (G.interactive_fd) {
4422                 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4423                 /* Looks like they want an interactive shell */
4424                 setup_job_control();
4425                 /* -1 is special - makes xfuncs longjmp, not exit
4426                  * (we reset die_sleep = 0 whereever we [v]fork) */
4427                 die_sleep = -1;
4428                 if (setjmp(die_jmp)) {
4429                         /* xfunc has failed! die die die */
4430                         hush_exit(xfunc_error_retval);
4431                 }
4432         }
4433 #elif ENABLE_HUSH_INTERACTIVE
4434 /* no job control compiled, only prompt/line editing */
4435         if (argv[optind] == NULL && input == stdin
4436          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4437         ) {
4438                 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4439                 if (G.interactive_fd < 0) {
4440                         /* try to dup to any fd */
4441                         G.interactive_fd = dup(STDIN_FILENO);
4442                         if (G.interactive_fd < 0)
4443                                 /* give up */
4444                                 G.interactive_fd = 0;
4445                 }
4446                 if (G.interactive_fd) {
4447                         fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4448                         set_misc_sighandler(SIG_IGN);
4449                 }
4450         }
4451 #endif
4452
4453 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4454         if (G.interactive_fd) {
4455                 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4456                 printf("Enter 'help' for a list of built-in commands.\n\n");
4457         }
4458 #endif
4459
4460         if (argv[optind] == NULL) {
4461                 opt = parse_and_run_file(stdin);
4462         } else {
4463                 debug_printf("\nrunning script '%s'\n", argv[optind]);
4464                 G.global_argv = argv + optind;
4465                 G.global_argc = argc - optind;
4466                 input = xfopen_for_read(argv[optind]);
4467                 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4468                 opt = parse_and_run_file(input);
4469         }
4470
4471  final_return:
4472
4473 #if ENABLE_FEATURE_CLEAN_UP
4474         fclose(input);
4475         if (G.cwd != bb_msg_unknown)
4476                 free((char*)G.cwd);
4477         cur_var = G.top_var->next;
4478         while (cur_var) {
4479                 struct variable *tmp = cur_var;
4480                 if (!cur_var->max_len)
4481                         free(cur_var->varstr);
4482                 cur_var = cur_var->next;
4483                 free(tmp);
4484         }
4485 #endif
4486         hush_exit(opt ? opt : G.last_return_code);
4487 }
4488
4489
4490 #if ENABLE_LASH
4491 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4492 int lash_main(int argc, char **argv)
4493 {
4494         //bb_error_msg("lash is deprecated, please use hush instead");
4495         return hush_main(argc, argv);
4496 }
4497 #endif
4498
4499
4500 /*
4501  * Built-ins
4502  */
4503 static int builtin_true(char **argv UNUSED_PARAM)
4504 {
4505         return 0;
4506 }
4507
4508 static int builtin_test(char **argv)
4509 {
4510         int argc = 0;
4511         while (*argv) {
4512                 argc++;
4513                 argv++;
4514         }
4515         return test_main(argc, argv - argc);
4516 }
4517
4518 static int builtin_echo(char **argv)
4519 {
4520         int argc = 0;
4521         while (*argv) {
4522                 argc++;
4523                 argv++;
4524         }
4525         return echo_main(argc, argv - argc);
4526 }
4527
4528 static int builtin_eval(char **argv)
4529 {
4530         int rcode = EXIT_SUCCESS;
4531
4532         if (argv[1]) {
4533                 char *str = expand_strvec_to_string(argv + 1);
4534                 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4535                 free(str);
4536                 rcode = G.last_return_code;
4537         }
4538         return rcode;
4539 }
4540
4541 static int builtin_cd(char **argv)
4542 {
4543         const char *newdir;
4544         if (argv[1] == NULL) {
4545                 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4546                 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4547                 newdir = getenv("HOME") ? : "/";
4548         } else
4549                 newdir = argv[1];
4550         if (chdir(newdir)) {
4551                 printf("cd: %s: %s\n", newdir, strerror(errno));
4552                 return EXIT_FAILURE;
4553         }
4554         set_cwd();
4555         return EXIT_SUCCESS;
4556 }
4557
4558 static int builtin_exec(char **argv)
4559 {
4560         if (argv[1] == NULL)
4561                 return EXIT_SUCCESS; /* bash does this */
4562         {
4563 #if !BB_MMU
4564                 nommu_save_t dummy;
4565 #endif
4566 // FIXME: if exec fails, bash does NOT exit! We do...
4567                 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4568                 /* never returns */
4569         }
4570 }
4571
4572 static int builtin_exit(char **argv)
4573 {
4574 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4575         //puts("exit"); /* bash does it */
4576 // TODO: warn if we have background jobs: "There are stopped jobs"
4577 // On second consecutive 'exit', exit anyway.
4578         if (argv[1] == NULL)
4579                 hush_exit(G.last_return_code);
4580         /* mimic bash: exit 123abc == exit 255 + error msg */
4581         xfunc_error_retval = 255;
4582         /* bash: exit -2 == exit 254, no error msg */
4583         hush_exit(xatoi(argv[1]) & 0xff);
4584 }
4585
4586 static int builtin_export(char **argv)
4587 {
4588         const char *value;
4589         char *name = argv[1];
4590
4591         if (name == NULL) {
4592                 // TODO:
4593                 // ash emits: export VAR='VAL'
4594                 // bash: declare -x VAR="VAL"
4595                 // (both also escape as needed (quotes, $, etc))
4596                 char **e = environ;
4597                 if (e)
4598                         while (*e)
4599                                 puts(*e++);
4600                 return EXIT_SUCCESS;
4601         }
4602
4603         value = strchr(name, '=');
4604         if (!value) {
4605                 /* They are exporting something without a =VALUE */
4606                 struct variable *var;
4607
4608                 var = get_local_var(name);
4609                 if (var) {
4610                         var->flg_export = 1;
4611                         debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4612                         putenv(var->varstr);
4613                 }
4614                 /* bash does not return an error when trying to export
4615                  * an undefined variable.  Do likewise. */
4616                 return EXIT_SUCCESS;
4617         }
4618
4619         set_local_var(xstrdup(name), 1);
4620         return EXIT_SUCCESS;
4621 }
4622
4623 #if ENABLE_HUSH_JOB
4624 /* built-in 'fg' and 'bg' handler */
4625 static int builtin_fg_bg(char **argv)
4626 {
4627         int i, jobnum;
4628         struct pipe *pi;
4629
4630         if (!G.interactive_fd)
4631                 return EXIT_FAILURE;
4632         /* If they gave us no args, assume they want the last backgrounded task */
4633         if (!argv[1]) {
4634                 for (pi = G.job_list; pi; pi = pi->next) {
4635                         if (pi->jobid == G.last_jobid) {
4636                                 goto found;
4637                         }
4638                 }
4639                 bb_error_msg("%s: no current job", argv[0]);
4640                 return EXIT_FAILURE;
4641         }
4642         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4643                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4644                 return EXIT_FAILURE;
4645         }
4646         for (pi = G.job_list; pi; pi = pi->next) {
4647                 if (pi->jobid == jobnum) {
4648                         goto found;
4649                 }
4650         }
4651         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4652         return EXIT_FAILURE;
4653  found:
4654         // TODO: bash prints a string representation
4655         // of job being foregrounded (like "sleep 1 | cat")
4656         if (*argv[0] == 'f') {
4657                 /* Put the job into the foreground.  */
4658                 tcsetpgrp(G.interactive_fd, pi->pgrp);
4659         }
4660
4661         /* Restart the processes in the job */
4662         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4663         for (i = 0; i < pi->num_cmds; i++) {
4664                 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4665                 pi->cmds[i].is_stopped = 0;
4666         }
4667         pi->stopped_cmds = 0;
4668
4669         i = kill(- pi->pgrp, SIGCONT);
4670         if (i < 0) {
4671                 if (errno == ESRCH) {
4672                         delete_finished_bg_job(pi);
4673                         return EXIT_SUCCESS;
4674                 } else {
4675                         bb_perror_msg("kill (SIGCONT)");
4676                 }
4677         }
4678
4679         if (*argv[0] == 'f') {
4680                 remove_bg_job(pi);
4681                 return checkjobs_and_fg_shell(pi);
4682         }
4683         return EXIT_SUCCESS;
4684 }
4685 #endif
4686
4687 #if ENABLE_HUSH_HELP
4688 static int builtin_help(char **argv UNUSED_PARAM)
4689 {
4690         const struct built_in_command *x;
4691
4692         printf("\nBuilt-in commands:\n");
4693         printf("-------------------\n");
4694         for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4695                 printf("%s\t%s\n", x->cmd, x->descr);
4696         }
4697         printf("\n\n");
4698         return EXIT_SUCCESS;
4699 }
4700 #endif
4701
4702 #if ENABLE_HUSH_JOB
4703 static int builtin_jobs(char **argv UNUSED_PARAM)
4704 {
4705         struct pipe *job;
4706         const char *status_string;
4707
4708         for (job = G.job_list; job; job = job->next) {
4709                 if (job->alive_cmds == job->stopped_cmds)
4710                         status_string = "Stopped";
4711                 else
4712                         status_string = "Running";
4713
4714                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4715         }
4716         return EXIT_SUCCESS;
4717 }
4718 #endif
4719
4720 static int builtin_pwd(char **argv UNUSED_PARAM)
4721 {
4722         puts(set_cwd());
4723         return EXIT_SUCCESS;
4724 }
4725
4726 static int builtin_read(char **argv)
4727 {
4728         char *string;
4729         const char *name = argv[1] ? argv[1] : "REPLY";
4730
4731         string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4732         return set_local_var(string, 0);
4733 }
4734
4735 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4736  * built-in 'set' handler
4737  * SUSv3 says:
4738  * set [-abCefhmnuvx] [-o option] [argument...]
4739  * set [+abCefhmnuvx] [+o option] [argument...]
4740  * set -- [argument...]
4741  * set -o
4742  * set +o
4743  * Implementations shall support the options in both their hyphen and
4744  * plus-sign forms. These options can also be specified as options to sh.
4745  * Examples:
4746  * Write out all variables and their values: set
4747  * Set $1, $2, and $3 and set "$#" to 3: set c a b
4748  * Turn on the -x and -v options: set -xv
4749  * Unset all positional parameters: set --
4750  * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4751  * Set the positional parameters to the expansion of x, even if x expands
4752  * with a leading '-' or '+': set -- $x
4753  *
4754  * So far, we only support "set -- [argument...]" and some of the short names.
4755  */
4756 static int builtin_set_mode(const char cstate, const char mode)
4757 {
4758         int state = (cstate == '-' ? 1 : 0);
4759         switch (mode) {
4760                 case 'n': G.fake_mode = state; break;
4761                 case 'x': /*G.debug_mode = state;*/ break;
4762                 default:  return EXIT_FAILURE;
4763         }
4764         return EXIT_SUCCESS;
4765 }
4766 static int builtin_set(char **argv)
4767 {
4768         int n;
4769         char **pp, **g_argv;
4770         char *arg = *++argv;
4771
4772         if (arg == NULL) {
4773                 struct variable *e;
4774                 for (e = G.top_var; e; e = e->next)
4775                         puts(e->varstr);
4776                 return EXIT_SUCCESS;
4777         }
4778
4779         do {
4780                 if (!strcmp(arg, "--")) {
4781                         ++argv;
4782                         goto set_argv;
4783                 }
4784
4785                 if (arg[0] == '+' || arg[0] == '-') {
4786                         for (n = 1; arg[n]; ++n)
4787                                 if (builtin_set_mode(arg[0], arg[n]))
4788                                         goto error;
4789                         continue;
4790                 }
4791
4792                 break;
4793         } while ((arg = *++argv) != NULL);
4794         /* Now argv[0] is 1st argument */
4795
4796         /* Only reset global_argv if we didn't process anything */
4797         if (arg == NULL)
4798                 return EXIT_SUCCESS;
4799  set_argv:
4800
4801         /* NB: G.global_argv[0] ($0) is never freed/changed */
4802         g_argv = G.global_argv;
4803         if (G.global_args_malloced) {
4804                 pp = g_argv;
4805                 while (*++pp)
4806                         free(*pp);
4807                 g_argv[1] = NULL;
4808         } else {
4809                 G.global_args_malloced = 1;
4810                 pp = xzalloc(sizeof(pp[0]) * 2);
4811                 pp[0] = g_argv[0]; /* retain $0 */
4812                 g_argv = pp;
4813         }
4814         /* This realloc's G.global_argv */
4815         G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4816
4817         n = 1;
4818         while (*++pp)
4819                 n++;
4820         G.global_argc = n;
4821
4822         return EXIT_SUCCESS;
4823
4824         /* Nothing known, so abort */
4825  error:
4826         bb_error_msg("set: %s: invalid option", arg);
4827         return EXIT_FAILURE;
4828 }
4829
4830 static int builtin_shift(char **argv)
4831 {
4832         int n = 1;
4833         if (argv[1]) {
4834                 n = atoi(argv[1]);
4835         }
4836         if (n >= 0 && n < G.global_argc) {
4837                 if (G.global_args_malloced) {
4838                         int m = 1;
4839                         while (m <= n)
4840                                 free(G.global_argv[m++]);
4841                 }
4842                 G.global_argc -= n;
4843                 memmove(&G.global_argv[1], &G.global_argv[n+1],
4844                                 G.global_argc * sizeof(G.global_argv[0]));
4845                 return EXIT_SUCCESS;
4846         }
4847         return EXIT_FAILURE;
4848 }
4849
4850 static int builtin_source(char **argv)
4851 {
4852         FILE *input;
4853         int status;
4854
4855         if (argv[1] == NULL)
4856                 return EXIT_FAILURE;
4857
4858         /* XXX search through $PATH is missing */
4859         input = fopen_for_read(argv[1]);
4860         if (!input) {
4861                 bb_error_msg("can't open '%s'", argv[1]);
4862                 return EXIT_FAILURE;
4863         }
4864         close_on_exec_on(fileno(input));
4865
4866         /* Now run the file */
4867         /* XXX argv and argc are broken; need to save old G.global_argv
4868          * (pointer only is OK!) on this stack frame,
4869          * set G.global_argv=argv+1, recurse, and restore. */
4870         status = parse_and_run_file(input);
4871         fclose(input);
4872         return status;
4873 }
4874
4875 static int builtin_umask(char **argv)
4876 {
4877         mode_t new_umask;
4878         const char *arg = argv[1];
4879         char *end;
4880         if (arg) {
4881                 new_umask = strtoul(arg, &end, 8);
4882                 if (*end != '\0' || end == arg) {
4883                         return EXIT_FAILURE;
4884                 }
4885         } else {
4886                 new_umask = umask(0);
4887                 printf("%.3o\n", (unsigned) new_umask);
4888         }
4889         umask(new_umask);
4890         return EXIT_SUCCESS;
4891 }
4892
4893 static int builtin_unset(char **argv)
4894 {
4895         /* bash always returns true */
4896         unset_local_var(argv[1]);
4897         return EXIT_SUCCESS;
4898 }
4899
4900 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
4901 static int builtin_wait(char **argv)
4902 {
4903         int ret = EXIT_SUCCESS;
4904         int status;
4905
4906         if (argv[1] == NULL)
4907                 /* don't care about exit status */
4908                 wait(&status);
4909
4910         while (argv[1]) {
4911                 char *endp;
4912                 pid_t pid = bb_strtou(argv[1], &endp, 10);
4913                 if (*endp) {
4914                         bb_perror_msg("wait %s", argv[1]);
4915                         return EXIT_FAILURE;
4916                 } else if (waitpid(pid, &status, 0) == pid) {
4917                         if (WIFSIGNALED(status))
4918                                 ret = 128 + WTERMSIG(status);
4919                         else if (WIFEXITED(status))
4920                                 ret = WEXITSTATUS(status);
4921                         else
4922                                 ret = EXIT_FAILURE;
4923                 } else {
4924                         bb_perror_msg("wait %s", argv[1]);
4925                         ret = 127;
4926                 }
4927                 ++argv;
4928         }
4929
4930         return ret;
4931 }
4932
4933 #if ENABLE_HUSH_LOOPS
4934 static int builtin_break(char **argv)
4935 {
4936         if (G.depth_of_loop == 0) {
4937                 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4938                 return EXIT_SUCCESS; /* bash compat */
4939         }
4940         G.flag_break_continue++; /* BC_BREAK = 1 */
4941         G.depth_break_continue = 1;
4942         if (argv[1]) {
4943                 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4944                 if (errno || !G.depth_break_continue || argv[2]) {
4945                         bb_error_msg("%s: bad arguments", argv[0]);
4946                         G.flag_break_continue = BC_BREAK;
4947                         G.depth_break_continue = UINT_MAX;
4948                 }
4949         }
4950         if (G.depth_of_loop < G.depth_break_continue)
4951                 G.depth_break_continue = G.depth_of_loop;
4952         return EXIT_SUCCESS;
4953 }
4954
4955 static int builtin_continue(char **argv)
4956 {
4957         G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4958         return builtin_break(argv);
4959 }
4960 #endif