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