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