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