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