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