hush: fix double-free in "echo TEST &"
[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  *      b_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  *      $@ (those sure look like weird quoting rules)
41  *      $_
42  *      ! negation operator for pipes
43  *      &> and >& redirection of stdout+stderr
44  *      Brace Expansion
45  *      Tilde Expansion
46  *      fancy forms of Parameter Expansion
47  *      aliases
48  *      Arithmetic Expansion
49  *      <(list) and >(list) Process Substitution
50  *      reserved words: case, esac, select, function
51  *      Here Documents ( << word )
52  *      Functions
53  * Major bugs:
54  *      job handling woefully incomplete and buggy (improved --vda)
55  *      reserved word execution woefully incomplete and buggy
56  * to-do:
57  *      port selected bugfixes from post-0.49 busybox lash - done?
58  *      finish implementing reserved words: for, while, until, do, done
59  *      change { and } from special chars to reserved words
60  *      builtins: break, continue, eval, return, set, trap, ulimit
61  *      test magic exec
62  *      handle children going into background
63  *      clean up recognition of null pipes
64  *      check setting of global_argc and global_argv
65  *      control-C handling, probably with longjmp
66  *      follow IFS rules more precisely, including update semantics
67  *      figure out what to do with backslash-newline
68  *      explain why we use signal instead of sigaction
69  *      propagate syntax errors, die on resource errors?
70  *      continuation lines, both explicit and implicit - done?
71  *      memory leak finding and plugging - done?
72  *      more testing, especially quoting rules and redirection
73  *      document how quoting rules not precisely followed for variable assignments
74  *      maybe change map[] to use 2-bit entries
75  *      (eventually) remove all the printf's
76  *
77  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
78  */
79
80 #include "busybox.h"
81 #include <glob.h>      /* glob, of course */
82 #include <getopt.h>    /* should be pretty obvious */
83 /* #include <dmalloc.h> */
84
85
86 /* If you comment out one of these below, it will be #defined later
87  * to perform debug printfs to stderr: */
88 #define debug_printf(...)       do {} while (0)
89 /* Finer-grained debug switches */
90 #define debug_printf_parse(...) do {} while (0)
91 #define debug_print_tree(a, b)  do {} while (0)
92 #define debug_printf_exec(...)  do {} while (0)
93 #define debug_printf_jobs(...)  do {} while (0)
94 #define debug_printf_clean(...) do {} while (0)
95
96 #ifndef debug_printf
97 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
98 #endif
99
100 #ifndef debug_printf_parse
101 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
102 #endif
103
104 #ifndef debug_printf_exec
105 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
106 #endif
107
108 #ifndef debug_printf_jobs
109 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
110 #define DEBUG_SHELL_JOBS 1
111 #endif
112
113 #ifndef debug_printf_clean
114 /* broken, of course, but OK for testing */
115 static const char *indenter(int i)
116 {
117         static const char blanks[] = "                                    ";
118         return &blanks[sizeof(blanks) - i - 1];
119 }
120 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
121 #endif
122
123
124 #if !ENABLE_HUSH_INTERACTIVE
125 #undef ENABLE_FEATURE_EDITING
126 #define ENABLE_FEATURE_EDITING 0
127 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
128 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
129 #endif
130
131 #define SPECIAL_VAR_SYMBOL   3
132 #define FLAG_EXIT_FROM_LOOP  1
133 #define FLAG_PARSE_SEMICOLON (1 << 1)           /* symbol ';' is special for parser */
134 #define FLAG_REPARSING       (1 << 2)           /* >= 2nd pass */
135
136 typedef enum {
137         REDIRECT_INPUT     = 1,
138         REDIRECT_OVERWRITE = 2,
139         REDIRECT_APPEND    = 3,
140         REDIRECT_HEREIS    = 4,
141         REDIRECT_IO        = 5
142 } redir_type;
143
144 /* The descrip member of this structure is only used to make debugging
145  * output pretty */
146 static const struct {
147         int mode;
148         signed char default_fd;
149         char descrip[3];
150 } redir_table[] = {
151         { 0,                         0, "()" },
152         { O_RDONLY,                  0, "<"  },
153         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
154         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
155         { O_RDONLY,                 -1, "<<" },
156         { O_RDWR,                    1, "<>" }
157 };
158
159 typedef enum {
160         PIPE_SEQ = 1,
161         PIPE_AND = 2,
162         PIPE_OR  = 3,
163         PIPE_BG  = 4,
164 } pipe_style;
165
166 /* might eventually control execution */
167 typedef enum {
168         RES_NONE  = 0,
169         RES_IF    = 1,
170         RES_THEN  = 2,
171         RES_ELIF  = 3,
172         RES_ELSE  = 4,
173         RES_FI    = 5,
174         RES_FOR   = 6,
175         RES_WHILE = 7,
176         RES_UNTIL = 8,
177         RES_DO    = 9,
178         RES_DONE  = 10,
179         RES_XXXX  = 11,
180         RES_IN    = 12,
181         RES_SNTX  = 13
182 } reserved_style;
183 enum {
184         FLAG_END   = (1 << RES_NONE ),
185         FLAG_IF    = (1 << RES_IF   ),
186         FLAG_THEN  = (1 << RES_THEN ),
187         FLAG_ELIF  = (1 << RES_ELIF ),
188         FLAG_ELSE  = (1 << RES_ELSE ),
189         FLAG_FI    = (1 << RES_FI   ),
190         FLAG_FOR   = (1 << RES_FOR  ),
191         FLAG_WHILE = (1 << RES_WHILE),
192         FLAG_UNTIL = (1 << RES_UNTIL),
193         FLAG_DO    = (1 << RES_DO   ),
194         FLAG_DONE  = (1 << RES_DONE ),
195         FLAG_IN    = (1 << RES_IN   ),
196         FLAG_START = (1 << RES_XXXX ),
197 };
198
199 /* This holds pointers to the various results of parsing */
200 struct p_context {
201         struct child_prog *child;
202         struct pipe *list_head;
203         struct pipe *pipe;
204         struct redir_struct *pending_redirect;
205         reserved_style res_w;
206         int old_flag;           /* for figuring out valid reserved words */
207         struct p_context *stack;
208         int parse_type;         /* define type of parser : ";$" common or special symbol */
209         /* How about quoting status? */
210 };
211
212 struct redir_struct {
213         struct redir_struct *next;  /* pointer to the next redirect in the list */
214         redir_type type;            /* type of redirection */
215         int fd;                     /* file descriptor being redirected */
216         int dup;                    /* -1, or file descriptor being duplicated */
217         glob_t word;                /* *word.gl_pathv is the filename */
218 };
219
220 struct child_prog {
221         pid_t pid;                  /* 0 if exited */
222         char **argv;                /* program name and arguments */
223         struct pipe *group;         /* if non-NULL, first in group or subshell */
224         int subshell;               /* flag, non-zero if group must be forked */
225         struct redir_struct *redirects; /* I/O redirections */
226         glob_t glob_result;         /* result of parameter globbing */
227         int is_stopped;             /* is the program currently running? */
228         struct pipe *family;        /* pointer back to the child's parent pipe */
229         int sp;                     /* number of SPECIAL_VAR_SYMBOL */
230         int type;
231 };
232
233 struct pipe {
234         struct pipe *next;
235         int num_progs;              /* total number of programs in job */
236         int running_progs;          /* number of programs running (not exited) */
237         char *cmdbuf;               /* buffer various argv's point into */
238 #if ENABLE_HUSH_JOB
239         int jobid;                  /* job number */
240         char *cmdtext;              /* name of job */
241         pid_t pgrp;                 /* process group ID for the job */
242 #endif
243         struct child_prog *progs;   /* array of commands in pipe */
244         int stopped_progs;          /* number of programs alive, but stopped */
245         int job_context;            /* bitmask defining current context */
246         pipe_style followup;        /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
247         reserved_style r_mode;      /* supports if, for, while, until */
248 };
249
250 struct close_me {
251         struct close_me *next;
252         int fd;
253 };
254
255 struct variables {
256         struct variables *next;
257         const char *name;
258         const char *value;
259         int flg_export;
260         int flg_read_only;
261 };
262
263 /* globals, connect us to the outside world
264  * the first three support $?, $#, and $1 */
265 static char **global_argv;
266 static int global_argc;
267 static int last_return_code;
268 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
269
270 /* "globals" within this file */
271 enum {
272         MAP_ORDINARY             = 0,
273         MAP_FLOWTROUGH_IF_QUOTED = 1,
274         MAP_IFS_IF_UNQUOTED      = 2, /* flow through if quoted too */
275         MAP_NEVER_FLOWTROUGH     = 3,
276 };
277 static unsigned char map[256];
278 static const char *ifs;
279 static int fake_mode;
280 static struct close_me *close_me_head;
281 static const char *cwd;
282 static unsigned last_bg_pid;
283 #if !ENABLE_HUSH_INTERACTIVE
284 enum { interactive_fd = 0 };
285 #else
286 /* 'interactive_fd' is a fd# open to ctty, if we have one
287  * _AND_ if we decided to act interactively */
288 static int interactive_fd;
289 #if ENABLE_HUSH_JOB
290 static pid_t saved_task_pgrp;
291 static pid_t saved_tty_pgrp;
292 static int last_jobid;
293 static struct pipe *job_list;
294 #endif
295 static const char *PS1;
296 static const char *PS2;
297 #endif
298
299 #define HUSH_VER_STR "0.02"
300 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
301 static struct variables *top_vars = &shell_ver;
302
303 #define B_CHUNK  100
304 #define B_NOSPAC 1
305
306 typedef struct {
307         char *data;
308         int length;
309         int maxlen;
310         int quote;
311         int nonnull;
312 } o_string;
313 #define NULL_O_STRING {NULL,0,0,0,0}
314 /* used for initialization:
315         o_string foo = NULL_O_STRING; */
316
317 /* I can almost use ordinary FILE *.  Is open_memstream() universally
318  * available?  Where is it documented? */
319 struct in_str {
320         const char *p;
321         char peek_buf[2];
322 #if ENABLE_HUSH_INTERACTIVE
323         int __promptme;
324         int promptmode;
325 #endif
326         FILE *file;
327         int (*get) (struct in_str *);
328         int (*peek) (struct in_str *);
329 };
330 #define b_getch(input) ((input)->get(input))
331 #define b_peek(input) ((input)->peek(input))
332
333 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
334
335 struct built_in_command {
336         const char *cmd;                /* name */
337         const char *descr;              /* description */
338         int (*function) (char **argv);  /* function ptr */
339 };
340
341 static void __syntax(int line)
342 {
343         bb_error_msg("syntax error hush.c:%d", line);
344 }
345 #define syntax() __syntax(__LINE__)
346
347 /* Index of subroutines: */
348 /*   function prototypes for builtins */
349 static int builtin_cd(char **argv);
350 static int builtin_eval(char **argv);
351 static int builtin_exec(char **argv);
352 static int builtin_exit(char **argv);
353 static int builtin_export(char **argv);
354 #if ENABLE_HUSH_JOB
355 static int builtin_fg_bg(char **argv);
356 static int builtin_jobs(char **argv);
357 #endif
358 static int builtin_help(char **argv);
359 static int builtin_pwd(char **argv);
360 static int builtin_read(char **argv);
361 static int builtin_set(char **argv);
362 static int builtin_shift(char **argv);
363 static int builtin_source(char **argv);
364 static int builtin_umask(char **argv);
365 static int builtin_unset(char **argv);
366 static int builtin_not_written(char **argv);
367 /*   o_string manipulation: */
368 static int b_check_space(o_string *o, int len);
369 static int b_addchr(o_string *o, int ch);
370 static void b_reset(o_string *o);
371 static int b_addqchr(o_string *o, int ch, int quote);
372 static int b_adduint(o_string *o, unsigned i);
373 /*  in_str manipulations: */
374 static int static_get(struct in_str *i);
375 static int static_peek(struct in_str *i);
376 static int file_get(struct in_str *i);
377 static int file_peek(struct in_str *i);
378 static void setup_file_in_str(struct in_str *i, FILE *f);
379 static void setup_string_in_str(struct in_str *i, const char *s);
380 /*  close_me manipulations: */
381 static void mark_open(int fd);
382 static void mark_closed(int fd);
383 static void close_all(void);
384 /*  "run" the final data structures: */
385 //TODO: remove indent argument from non-debug build!
386 static int free_pipe_list(struct pipe *head, int indent);
387 static int free_pipe(struct pipe *pi, int indent);
388 /*  really run the final data structures: */
389 static int setup_redirects(struct child_prog *prog, int squirrel[]);
390 static int run_list_real(struct pipe *pi);
391 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
392 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
393 static int run_pipe_real(struct pipe *pi);
394 /*   extended glob support: */
395 static int globhack(const char *src, int flags, glob_t *pglob);
396 static int glob_needed(const char *s);
397 static int xglob(o_string *dest, int flags, glob_t *pglob);
398 /*   variable assignment: */
399 static int is_assignment(const char *s);
400 /*   data structure manipulation: */
401 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
402 static void initialize_context(struct p_context *ctx);
403 static int done_word(o_string *dest, struct p_context *ctx);
404 static int done_command(struct p_context *ctx);
405 static int done_pipe(struct p_context *ctx, pipe_style type);
406 /*   primary string parsing: */
407 static int redirect_dup_num(struct in_str *input);
408 static int redirect_opt_num(o_string *o);
409 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
410 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
411 static const char *lookup_param(const char *src);
412 static char *make_string(char **inp);
413 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
414 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
415 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
416 /*   setup: */
417 static int parse_stream_outer(struct in_str *inp, int parse_flag);
418 static int parse_string_outer(const char *s, int parse_flag);
419 static int parse_file_outer(FILE *f);
420 /*   job management: */
421 static int checkjobs(struct pipe* fg_pipe);
422 #if ENABLE_HUSH_JOB
423 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
424 static void insert_bg_job(struct pipe *pi);
425 static void remove_bg_job(struct pipe *pi);
426 static void delete_finished_bg_job(struct pipe *pi);
427 #else
428 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
429 #endif
430 /*     local variable support */
431 static char **make_list_in(char **inp, char *name);
432 static char *insert_var_value(char *inp);
433 static const char *get_local_var(const char *var);
434 static int set_local_var(const char *s, int flg_export);
435 static void unset_local_var(const char *name);
436
437 /* Table of built-in functions.  They can be forked or not, depending on
438  * context: within pipes, they fork.  As simple commands, they do not.
439  * When used in non-forking context, they can change global variables
440  * in the parent shell process.  If forked, of course they cannot.
441  * For example, 'unset foo | whatever' will parse and run, but foo will
442  * still be set at the end. */
443 static const struct built_in_command bltins[] = {
444 #if ENABLE_HUSH_JOB
445         { "bg", "Resume a job in the background", builtin_fg_bg },
446 #endif
447         { "break", "Exit for, while or until loop", builtin_not_written },
448         { "cd", "Change working directory", builtin_cd },
449         { "continue", "Continue for, while or until loop", builtin_not_written },
450         { "eval", "Construct and run shell command", builtin_eval },
451         { "exec", "Exec command, replacing this shell with the exec'd process",
452                 builtin_exec },
453         { "exit", "Exit from shell()", builtin_exit },
454         { "export", "Set environment variable", builtin_export },
455 #if ENABLE_HUSH_JOB
456         { "fg", "Bring job into the foreground", builtin_fg_bg },
457         { "jobs", "Lists the active jobs", builtin_jobs },
458 #endif
459         { "pwd", "Print current directory", builtin_pwd },
460         { "read", "Input environment variable", builtin_read },
461         { "return", "Return from a function", builtin_not_written },
462         { "set", "Set/unset shell local variables", builtin_set },
463         { "shift", "Shift positional parameters", builtin_shift },
464         { "trap", "Trap signals", builtin_not_written },
465         { "ulimit","Controls resource limits", builtin_not_written },
466         { "umask","Sets file creation mask", builtin_umask },
467         { "unset", "Unset environment variable", builtin_unset },
468         { ".", "Source-in and run commands in a file", builtin_source },
469         { "help", "List shell built-in commands", builtin_help },
470         { NULL, NULL, NULL }
471 };
472
473 #if ENABLE_HUSH_JOB
474
475 /* move to libbb? */
476 static void signal_SA_RESTART(int sig, void (*handler)(int))
477 {
478         struct sigaction sa;
479         sa.sa_handler = handler;
480         sa.sa_flags = SA_RESTART;
481         sigemptyset(&sa.sa_mask);
482         sigaction(sig, &sa, NULL);
483 }
484
485 /* Signals are grouped, we handle them in batches */
486 static void set_fatal_sighandler(void (*handler)(int))
487 {
488         signal(SIGILL , handler);
489         signal(SIGTRAP, handler);
490         signal(SIGABRT, handler);
491         signal(SIGFPE , handler);
492         signal(SIGBUS , handler);
493         signal(SIGSEGV, handler);
494         /* bash 3.2 seems to handle these just like 'fatal' ones */
495         signal(SIGHUP , handler);
496         signal(SIGPIPE, handler);
497         signal(SIGALRM, handler);
498 }
499 static void set_jobctrl_sighandler(void (*handler)(int))
500 {
501         signal(SIGTSTP, handler);
502         signal(SIGTTIN, handler);
503         signal(SIGTTOU, handler);
504 }
505 static void set_misc_sighandler(void (*handler)(int))
506 {
507         signal(SIGINT , handler);
508         signal(SIGQUIT, handler);
509         signal(SIGTERM, handler);
510 }
511 /* SIGCHLD is special and handled separately */
512
513 static void set_every_sighandler(void (*handler)(int))
514 {
515         set_fatal_sighandler(handler);
516         set_jobctrl_sighandler(handler);
517         set_misc_sighandler(handler);
518         signal(SIGCHLD, handler);
519 }
520
521 static struct pipe *toplevel_list;
522 static sigjmp_buf toplevel_jb;
523 smallint ctrl_z_flag;
524 #if ENABLE_FEATURE_SH_STANDALONE
525 struct nofork_save_area nofork_save;
526 #endif
527
528 static void handler_ctrl_c(int sig)
529 {
530         debug_printf_jobs("got sig %d\n", sig);
531 // as usual we can have all kinds of nasty problems with leaked malloc data here
532         siglongjmp(toplevel_jb, 1);
533 }
534
535 static void handler_ctrl_z(int sig)
536 {
537         pid_t pid;
538
539         debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
540         pid = fork();
541         if (pid < 0) /* can't fork. Pretend there were no ctrl-Z */
542                 return;
543         ctrl_z_flag = 1;
544         if (!pid) { /* child */
545                 setpgrp();
546                 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
547                 set_every_sighandler(SIG_DFL);
548                 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
549                 debug_printf_jobs("returning in child\n");
550                 /* return to nofork, it will eventually exit now,
551                  * not return back to shell */
552                 return;
553         }
554         /* parent */
555         /* finish filling up pipe info */
556         toplevel_list->pgrp = pid; /* child is in its own pgrp */
557         toplevel_list->progs[0].pid = pid;
558         /* parent needs to longjmp out of running nofork.
559          * we will "return" exitcode 0, with child put in background */
560 // as usual we can have all kinds of nasty problems with leaked malloc data here
561         debug_printf_jobs("siglongjmp in parent\n");
562         siglongjmp(toplevel_jb, 1);
563 }
564
565 /* Restores tty foreground process group, and exits.
566  * May be called as signal handler for fatal signal
567  * (will faithfully resend signal to itself, producing correct exit state)
568  * or called directly with -EXITCODE.
569  * We also call it if xfunc is exiting. */
570 static void sigexit(int sig) ATTRIBUTE_NORETURN;
571 static void sigexit(int sig)
572 {
573         sigset_t block_all;
574
575         /* Disable all signals: job control, SIGPIPE, etc. */
576         sigfillset(&block_all);
577         sigprocmask(SIG_SETMASK, &block_all, NULL);
578
579         if (interactive_fd)
580                 tcsetpgrp(interactive_fd, saved_tty_pgrp);
581
582         /* Not a signal, just exit */
583         if (sig <= 0)
584                 _exit(- sig);
585
586         /* Enable only this sig and kill ourself with it */
587         signal(sig, SIG_DFL);
588         sigdelset(&block_all, sig);
589         sigprocmask(SIG_SETMASK, &block_all, NULL);
590         raise(sig);
591         _exit(1); /* Should not reach it */
592 }
593
594 /* Restores tty foreground process group, and exits. */
595 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
596 static void hush_exit(int exitcode)
597 {
598         fflush(NULL); /* flush all streams */
599         sigexit(- (exitcode & 0xff));
600 }
601
602 #else /* !JOB */
603
604 #define set_fatal_sighandler(handler)   ((void)0)
605 #define set_jobctrl_sighandler(handler) ((void)0)
606 #define set_misc_sighandler(handler)    ((void)0)
607 #define hush_exit(e)                    exit(e)
608
609 #endif /* JOB */
610
611
612 static const char *set_cwd(void)
613 {
614         if (cwd == bb_msg_unknown)
615                 cwd = NULL;     /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
616         cwd = xrealloc_getcwd_or_warn((char *)cwd);
617         if (!cwd)
618                 cwd = bb_msg_unknown;
619         return cwd;
620 }
621
622 /* built-in 'eval' handler */
623 static int builtin_eval(char **argv)
624 {
625         char *str = NULL;
626         int rcode = EXIT_SUCCESS;
627
628         if (argv[1]) {
629                 str = make_string(argv + 1);
630                 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
631                                         FLAG_PARSE_SEMICOLON);
632                 free(str);
633                 rcode = last_return_code;
634         }
635         return rcode;
636 }
637
638 /* built-in 'cd <path>' handler */
639 static int builtin_cd(char **argv)
640 {
641         char *newdir;
642         if (argv[1] == NULL)
643                 newdir = getenv("HOME");
644         else
645                 newdir = argv[1];
646         if (chdir(newdir)) {
647                 printf("cd: %s: %s\n", newdir, strerror(errno));
648                 return EXIT_FAILURE;
649         }
650         set_cwd();
651         return EXIT_SUCCESS;
652 }
653
654 /* built-in 'exec' handler */
655 static int builtin_exec(char **argv)
656 {
657         if (argv[1] == NULL)
658                 return EXIT_SUCCESS;   /* Really? */
659         pseudo_exec_argv(argv + 1);
660         /* never returns */
661 }
662
663 /* built-in 'exit' handler */
664 static int builtin_exit(char **argv)
665 {
666 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
667         //puts("exit"); /* bash does it */
668 // TODO: warn if we have background jobs: "There are stopped jobs"
669 // On second consecutive 'exit', exit anyway.
670
671         if (argv[1] == NULL)
672                 hush_exit(last_return_code);
673         /* mimic bash: exit 123abc == exit 255 + error msg */
674         xfunc_error_retval = 255;
675         /* bash: exit -2 == exit 254, no error msg */
676         hush_exit(xatoi(argv[1]) & 0xff);
677 }
678
679 /* built-in 'export VAR=value' handler */
680 static int builtin_export(char **argv)
681 {
682         int res = 0;
683         char *name = argv[1];
684
685         if (name == NULL) {
686                 // TODO:
687                 // ash emits: export VAR='VAL'
688                 // bash: declare -x VAR="VAL"
689                 // (both also escape as needed (quotes, $, etc))
690                 char **e = environ;
691                 if (e)
692                         while (*e)
693                                 puts(*e++);
694                 return EXIT_SUCCESS;
695         }
696
697         name = strdup(name);
698
699         if (name) {
700                 const char *value = strchr(name, '=');
701
702                 if (!value) {
703                         char *tmp;
704                         /* They are exporting something without an =VALUE */
705
706                         value = get_local_var(name);
707                         if (value) {
708                                 size_t ln = strlen(name);
709
710                                 tmp = realloc(name, ln+strlen(value)+2);
711                                 if (tmp == NULL)
712                                         res = -1;
713                                 else {
714                                         sprintf(tmp+ln, "=%s", value);
715                                         name = tmp;
716                                 }
717                         } else {
718                                 /* bash does not return an error when trying to export
719                                  * an undefined variable.  Do likewise. */
720                                 res = 1;
721                         }
722                 }
723         }
724         if (res < 0)
725                 bb_perror_msg("export");
726         else if (res == 0)
727                 res = set_local_var(name, 1);
728         else
729                 res = 0;
730         free(name);
731         return res;
732 }
733
734 #if ENABLE_HUSH_JOB
735 /* built-in 'fg' and 'bg' handler */
736 static int builtin_fg_bg(char **argv)
737 {
738         int i, jobnum;
739         struct pipe *pi;
740
741         if (!interactive_fd)
742                 return EXIT_FAILURE;
743         /* If they gave us no args, assume they want the last backgrounded task */
744         if (!argv[1]) {
745                 for (pi = job_list; pi; pi = pi->next) {
746                         if (pi->jobid == last_jobid) {
747                                 goto found;
748                         }
749                 }
750                 bb_error_msg("%s: no current job", argv[0]);
751                 return EXIT_FAILURE;
752         }
753         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
754                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
755                 return EXIT_FAILURE;
756         }
757         for (pi = job_list; pi; pi = pi->next) {
758                 if (pi->jobid == jobnum) {
759                         goto found;
760                 }
761         }
762         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
763         return EXIT_FAILURE;
764  found:
765         // TODO: bash prints a string representation
766         // of job being foregrounded (like "sleep 1 | cat")
767         if (*argv[0] == 'f') {
768                 /* Put the job into the foreground.  */
769                 tcsetpgrp(interactive_fd, pi->pgrp);
770         }
771
772         /* Restart the processes in the job */
773         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
774         for (i = 0; i < pi->num_progs; i++) {
775                 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
776                 pi->progs[i].is_stopped = 0;
777         }
778         pi->stopped_progs = 0;
779
780         i = kill(- pi->pgrp, SIGCONT);
781         if (i < 0) {
782                 if (errno == ESRCH) {
783                         delete_finished_bg_job(pi);
784                         return EXIT_SUCCESS;
785                 } else {
786                         bb_perror_msg("kill (SIGCONT)");
787                 }
788         }
789
790         if (*argv[0] == 'f') {
791                 remove_bg_job(pi);
792                 return checkjobs_and_fg_shell(pi);
793         }
794         return EXIT_SUCCESS;
795 }
796 #endif
797
798 /* built-in 'help' handler */
799 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
800 {
801         const struct built_in_command *x;
802
803         printf("\nBuilt-in commands:\n");
804         printf("-------------------\n");
805         for (x = bltins; x->cmd; x++) {
806                 if (x->descr == NULL)
807                         continue;
808                 printf("%s\t%s\n", x->cmd, x->descr);
809         }
810         printf("\n\n");
811         return EXIT_SUCCESS;
812 }
813
814 #if ENABLE_HUSH_JOB
815 /* built-in 'jobs' handler */
816 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
817 {
818         struct pipe *job;
819         const char *status_string;
820
821         for (job = job_list; job; job = job->next) {
822                 if (job->running_progs == job->stopped_progs)
823                         status_string = "Stopped";
824                 else
825                         status_string = "Running";
826
827                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
828         }
829         return EXIT_SUCCESS;
830 }
831 #endif
832
833 /* built-in 'pwd' handler */
834 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
835 {
836         puts(set_cwd());
837         return EXIT_SUCCESS;
838 }
839
840 /* built-in 'read VAR' handler */
841 static int builtin_read(char **argv)
842 {
843         int res;
844
845         if (argv[1]) {
846                 char string[BUFSIZ];
847                 char *var = NULL;
848
849                 string[0] = '\0';  /* In case stdin has only EOF */
850                 /* read string */
851                 fgets(string, sizeof(string), stdin);
852                 chomp(string);
853                 var = malloc(strlen(argv[1]) + strlen(string) + 2);
854                 if (var) {
855                         sprintf(var, "%s=%s", argv[1], string);
856                         res = set_local_var(var, 0);
857                 } else
858                         res = -1;
859                 if (res)
860                         bb_perror_msg("read");
861                 free(var);      /* So not move up to avoid breaking errno */
862                 return res;
863         }
864         do res = getchar(); while (res != '\n' && res != EOF);
865         return 0;
866 }
867
868 /* built-in 'set VAR=value' handler */
869 static int builtin_set(char **argv)
870 {
871         char *temp = argv[1];
872         struct variables *e;
873
874         if (temp == NULL)
875                 for (e = top_vars; e; e = e->next)
876                         printf("%s=%s\n", e->name, e->value);
877         else
878                 set_local_var(temp, 0);
879
880         return EXIT_SUCCESS;
881 }
882
883
884 /* Built-in 'shift' handler */
885 static int builtin_shift(char **argv)
886 {
887         int n = 1;
888         if (argv[1]) {
889                 n = atoi(argv[1]);
890         }
891         if (n >= 0 && n < global_argc) {
892                 /* XXX This probably breaks $0 */
893                 global_argc -= n;
894                 global_argv += n;
895                 return EXIT_SUCCESS;
896         }
897         return EXIT_FAILURE;
898 }
899
900 /* Built-in '.' handler (read-in and execute commands from file) */
901 static int builtin_source(char **argv)
902 {
903         FILE *input;
904         int status;
905
906         if (argv[1] == NULL)
907                 return EXIT_FAILURE;
908
909         /* XXX search through $PATH is missing */
910         input = fopen(argv[1], "r");
911         if (!input) {
912                 bb_error_msg("cannot open '%s'", argv[1]);
913                 return EXIT_FAILURE;
914         }
915
916         /* Now run the file */
917         /* XXX argv and argc are broken; need to save old global_argv
918          * (pointer only is OK!) on this stack frame,
919          * set global_argv=argv+1, recurse, and restore. */
920         mark_open(fileno(input));
921         status = parse_file_outer(input);
922         mark_closed(fileno(input));
923         fclose(input);
924         return status;
925 }
926
927 static int builtin_umask(char **argv)
928 {
929         mode_t new_umask;
930         const char *arg = argv[1];
931         char *end;
932         if (arg) {
933                 new_umask = strtoul(arg, &end, 8);
934                 if (*end != '\0' || end == arg) {
935                         return EXIT_FAILURE;
936                 }
937         } else {
938                 new_umask = umask(0);
939                 printf("%.3o\n", (unsigned) new_umask);
940         }
941         umask(new_umask);
942         return EXIT_SUCCESS;
943 }
944
945 /* built-in 'unset VAR' handler */
946 static int builtin_unset(char **argv)
947 {
948         /* bash returned already true */
949         unset_local_var(argv[1]);
950         return EXIT_SUCCESS;
951 }
952
953 static int builtin_not_written(char **argv)
954 {
955         printf("builtin_%s not written\n", argv[0]);
956         return EXIT_FAILURE;
957 }
958
959 static int b_check_space(o_string *o, int len)
960 {
961         /* It would be easy to drop a more restrictive policy
962          * in here, such as setting a maximum string length */
963         if (o->length + len > o->maxlen) {
964                 char *old_data = o->data;
965                 /* assert(data == NULL || o->maxlen != 0); */
966                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
967                 o->data = realloc(o->data, 1 + o->maxlen);
968                 if (o->data == NULL) {
969                         free(old_data);
970                 }
971         }
972         return o->data == NULL;
973 }
974
975 static int b_addchr(o_string *o, int ch)
976 {
977         debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
978         if (b_check_space(o, 1))
979                 return B_NOSPAC;
980         o->data[o->length] = ch;
981         o->length++;
982         o->data[o->length] = '\0';
983         return 0;
984 }
985
986 static void b_reset(o_string *o)
987 {
988         o->length = 0;
989         o->nonnull = 0;
990         if (o->data != NULL)
991                 *o->data = '\0';
992 }
993
994 static void b_free(o_string *o)
995 {
996         b_reset(o);
997         free(o->data);
998         o->data = NULL;
999         o->maxlen = 0;
1000 }
1001
1002 /* My analysis of quoting semantics tells me that state information
1003  * is associated with a destination, not a source.
1004  */
1005 static int b_addqchr(o_string *o, int ch, int quote)
1006 {
1007         if (quote && strchr("*?[\\", ch)) {
1008                 int rc;
1009                 rc = b_addchr(o, '\\');
1010                 if (rc)
1011                         return rc;
1012         }
1013         return b_addchr(o, ch);
1014 }
1015
1016 static int b_adduint(o_string *o, unsigned i)
1017 {
1018         int r;
1019         char buf[sizeof(unsigned)*3 + 1];
1020         char *p = buf;
1021         *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1022         /* no escape checking necessary */
1023         do r = b_addchr(o, *p++); while (r == 0 && *p);
1024         return r;
1025 }
1026
1027 static int static_get(struct in_str *i)
1028 {
1029         int ch = *i->p++;
1030         if (ch == '\0') return EOF;
1031         return ch;
1032 }
1033
1034 static int static_peek(struct in_str *i)
1035 {
1036         return *i->p;
1037 }
1038
1039 #if ENABLE_HUSH_INTERACTIVE
1040 #if ENABLE_FEATURE_EDITING
1041 static void cmdedit_set_initial_prompt(void)
1042 {
1043 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1044         PS1 = NULL;
1045 #else
1046         PS1 = getenv("PS1");
1047         if (PS1 == NULL)
1048                 PS1 = "\\w \\$ ";
1049 #endif
1050 }
1051 #endif /* EDITING */
1052
1053 static const char* setup_prompt_string(int promptmode)
1054 {
1055         const char *prompt_str;
1056         debug_printf("setup_prompt_string %d ", promptmode);
1057 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1058         /* Set up the prompt */
1059         if (promptmode == 1) {
1060                 char *ns;
1061                 free((char*)PS1);
1062                 ns = xmalloc(strlen(cwd)+4);
1063                 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1064                 prompt_str = ns;
1065                 PS1 = ns;
1066         } else {
1067                 prompt_str = PS2;
1068         }
1069 #else
1070         prompt_str = (promptmode == 1) ? PS1 : PS2;
1071 #endif
1072         debug_printf("result %s\n", prompt_str);
1073         return prompt_str;
1074 }
1075
1076 #if ENABLE_FEATURE_EDITING
1077 static line_input_t *line_input_state;
1078 #endif
1079
1080 static int get_user_input(struct in_str *i)
1081 {
1082         static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1083
1084         int r;
1085         const char *prompt_str;
1086         prompt_str = setup_prompt_string(i->promptmode);
1087 #if ENABLE_FEATURE_EDITING
1088         /*
1089          ** enable command line editing only while a command line
1090          ** is actually being read; otherwise, we'll end up bequeathing
1091          ** atexit() handlers and other unwanted stuff to our
1092          ** child processes (rob@sysgo.de)
1093          */
1094         r = read_line_input(prompt_str, the_command, BUFSIZ-1, line_input_state);
1095 #else
1096         fputs(prompt_str, stdout);
1097         fflush(stdout);
1098         the_command[0] = r = fgetc(i->file);
1099         /*the_command[1] = '\0'; - already is and never changed */
1100 #endif
1101         fflush(stdout);
1102         i->p = the_command;
1103         return r; /* < 0 == EOF. Not meaningful otherwise */
1104 }
1105 #endif  /* INTERACTIVE */
1106
1107 /* This is the magic location that prints prompts
1108  * and gets data back from the user */
1109 static int file_get(struct in_str *i)
1110 {
1111         int ch;
1112
1113         ch = 0;
1114         /* If there is data waiting, eat it up */
1115         if (i->p && *i->p) {
1116                 ch = *i->p++;
1117         } else {
1118                 /* need to double check i->file because we might be doing something
1119                  * more complicated by now, like sourcing or substituting. */
1120 #if ENABLE_HUSH_INTERACTIVE
1121                 if (interactive_fd && i->__promptme && i->file == stdin) {
1122                         while (!i->p || !(interactive_fd && i->p[0])) {
1123                                 if (get_user_input(i) < 0)
1124                                         return EOF;
1125                         }
1126                         i->promptmode = 2;
1127                         i->__promptme = 0;
1128                         if (i->p && *i->p) {
1129                                 ch = *i->p++;
1130                         }
1131                 } else
1132 #endif
1133                 {
1134                         ch = fgetc(i->file);
1135                 }
1136                 debug_printf("b_getch: got a %d\n", ch);
1137         }
1138 #if ENABLE_HUSH_INTERACTIVE
1139         if (ch == '\n')
1140                 i->__promptme = 1;
1141 #endif
1142         return ch;
1143 }
1144
1145 /* All the callers guarantee this routine will never be
1146  * used right after a newline, so prompting is not needed.
1147  */
1148 static int file_peek(struct in_str *i)
1149 {
1150         if (i->p && *i->p) {
1151                 return *i->p;
1152         }
1153         i->peek_buf[0] = fgetc(i->file);
1154         i->peek_buf[1] = '\0';
1155         i->p = i->peek_buf;
1156         debug_printf("b_peek: got a %d\n", *i->p);
1157         return *i->p;
1158 }
1159
1160 static void setup_file_in_str(struct in_str *i, FILE *f)
1161 {
1162         i->peek = file_peek;
1163         i->get = file_get;
1164 #if ENABLE_HUSH_INTERACTIVE
1165         i->__promptme = 1;
1166         i->promptmode = 1;
1167 #endif
1168         i->file = f;
1169         i->p = NULL;
1170 }
1171
1172 static void setup_string_in_str(struct in_str *i, const char *s)
1173 {
1174         i->peek = static_peek;
1175         i->get = static_get;
1176 #if ENABLE_HUSH_INTERACTIVE
1177         i->__promptme = 1;
1178         i->promptmode = 1;
1179 #endif
1180         i->p = s;
1181 }
1182
1183 static void mark_open(int fd)
1184 {
1185         struct close_me *new = xmalloc(sizeof(struct close_me));
1186         new->fd = fd;
1187         new->next = close_me_head;
1188         close_me_head = new;
1189 }
1190
1191 static void mark_closed(int fd)
1192 {
1193         struct close_me *tmp;
1194         if (close_me_head == NULL || close_me_head->fd != fd)
1195                 bb_error_msg_and_die("corrupt close_me");
1196         tmp = close_me_head;
1197         close_me_head = close_me_head->next;
1198         free(tmp);
1199 }
1200
1201 static void close_all(void)
1202 {
1203         struct close_me *c;
1204         for (c = close_me_head; c; c = c->next) {
1205                 close(c->fd);
1206         }
1207         close_me_head = NULL;
1208 }
1209
1210 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1211  * and stderr if they are redirected. */
1212 static int setup_redirects(struct child_prog *prog, int squirrel[])
1213 {
1214         int openfd, mode;
1215         struct redir_struct *redir;
1216
1217         for (redir = prog->redirects; redir; redir = redir->next) {
1218                 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1219                         /* something went wrong in the parse.  Pretend it didn't happen */
1220                         continue;
1221                 }
1222                 if (redir->dup == -1) {
1223                         mode = redir_table[redir->type].mode;
1224                         openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1225                         if (openfd < 0) {
1226                         /* this could get lost if stderr has been redirected, but
1227                            bash and ash both lose it as well (though zsh doesn't!) */
1228                                 return 1;
1229                         }
1230                 } else {
1231                         openfd = redir->dup;
1232                 }
1233
1234                 if (openfd != redir->fd) {
1235                         if (squirrel && redir->fd < 3) {
1236                                 squirrel[redir->fd] = dup(redir->fd);
1237                         }
1238                         if (openfd == -3) {
1239                                 close(openfd);
1240                         } else {
1241                                 dup2(openfd, redir->fd);
1242                                 if (redir->dup == -1)
1243                                         close(openfd);
1244                         }
1245                 }
1246         }
1247         return 0;
1248 }
1249
1250 static void restore_redirects(int squirrel[])
1251 {
1252         int i, fd;
1253         for (i = 0; i < 3; i++) {
1254                 fd = squirrel[i];
1255                 if (fd != -1) {
1256                         /* No error checking.  I sure wouldn't know what
1257                          * to do with an error if I found one! */
1258                         dup2(fd, i);
1259                         close(fd);
1260                 }
1261         }
1262 }
1263
1264 /* never returns */
1265 /* XXX no exit() here.  If you don't exec, use _exit instead.
1266  * The at_exit handlers apparently confuse the calling process,
1267  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
1268 static void pseudo_exec_argv(char **argv)
1269 {
1270         int i, rcode;
1271         char *p;
1272         const struct built_in_command *x;
1273
1274         for (i = 0; is_assignment(argv[i]); i++) {
1275                 debug_printf("pid %d environment modification: %s\n",
1276                                 getpid(), argv[i]);
1277 // FIXME: vfork case??
1278                 p = insert_var_value(argv[i]);
1279                 putenv(strdup(p));
1280                 if (p != argv[i])
1281                         free(p);
1282         }
1283         argv += i;
1284         /* If a variable is assigned in a forest, and nobody listens,
1285          * was it ever really set?
1286          */
1287         if (argv[0] == NULL) {
1288                 _exit(EXIT_SUCCESS);
1289         }
1290
1291         /*
1292          * Check if the command matches any of the builtins.
1293          * Depending on context, this might be redundant.  But it's
1294          * easier to waste a few CPU cycles than it is to figure out
1295          * if this is one of those cases.
1296          */
1297         for (x = bltins; x->cmd; x++) {
1298                 if (strcmp(argv[0], x->cmd) == 0) {
1299                         debug_printf("builtin exec %s\n", argv[0]);
1300                         rcode = x->function(argv);
1301                         fflush(stdout);
1302                         _exit(rcode);
1303                 }
1304         }
1305
1306         /* Check if the command matches any busybox internal commands
1307          * ("applets") here.
1308          * FIXME: This feature is not 100% safe, since
1309          * BusyBox is not fully reentrant, so we have no guarantee the things
1310          * from the .bss are still zeroed, or that things from .data are still
1311          * at their defaults.  We could exec ourself from /proc/self/exe, but I
1312          * really dislike relying on /proc for things.  We could exec ourself
1313          * from global_argv[0], but if we are in a chroot, we may not be able
1314          * to find ourself... */
1315 #if ENABLE_FEATURE_SH_STANDALONE
1316         debug_printf("running applet %s\n", argv[0]);
1317         run_applet_and_exit(argv[0], argv);
1318 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1319 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1320 #endif
1321         debug_printf("exec of %s\n", argv[0]);
1322         execvp(argv[0], argv);
1323         bb_perror_msg("cannot exec '%s'", argv[0]);
1324         _exit(1);
1325 }
1326
1327 static void pseudo_exec(struct child_prog *child)
1328 {
1329 // FIXME: buggy wrt NOMMU! Must not modify any global data
1330 // until it does exec/_exit, but currently it does.
1331         int rcode;
1332
1333         if (child->argv) {
1334                 pseudo_exec_argv(child->argv);
1335         }
1336
1337         if (child->group) {
1338         // FIXME: do not modify globals! Think vfork!
1339 #if ENABLE_HUSH_INTERACTIVE
1340                 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1341                 interactive_fd = 0;    /* crucial!!!! */
1342 #endif
1343                 debug_printf_exec("pseudo_exec: run_list_real\n");
1344                 rcode = run_list_real(child->group);
1345                 /* OK to leak memory by not calling free_pipe_list,
1346                  * since this process is about to exit */
1347                 _exit(rcode);
1348         }
1349
1350         /* Can happen.  See what bash does with ">foo" by itself. */
1351         debug_printf("trying to pseudo_exec null command\n");
1352         _exit(EXIT_SUCCESS);
1353 }
1354
1355 #if ENABLE_HUSH_JOB
1356 static const char *get_cmdtext(struct pipe *pi)
1357 {
1358         char **argv;
1359         char *p;
1360         int len;
1361
1362         /* This is subtle. ->cmdtext is created only on first backgrounding.
1363          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1364          * On subsequent bg argv is trashed, but we won't use it */
1365         if (pi->cmdtext)
1366                 return pi->cmdtext;
1367         argv = pi->progs[0].argv;
1368         if (!argv || !argv[0])
1369                 return (pi->cmdtext = xzalloc(1));
1370
1371         len = 0;
1372         do len += strlen(*argv) + 1; while (*++argv);
1373         pi->cmdtext = p = xmalloc(len);
1374         argv = pi->progs[0].argv;
1375         do {
1376                 len = strlen(*argv);
1377                 memcpy(p, *argv, len);
1378                 p += len;
1379                 *p++ = ' ';
1380         } while (*++argv);
1381         p[-1] = '\0';
1382         return pi->cmdtext;
1383 }
1384
1385 static void insert_bg_job(struct pipe *pi)
1386 {
1387         struct pipe *thejob;
1388         int i;
1389
1390         /* Linear search for the ID of the job to use */
1391         pi->jobid = 1;
1392         for (thejob = job_list; thejob; thejob = thejob->next)
1393                 if (thejob->jobid >= pi->jobid)
1394                         pi->jobid = thejob->jobid + 1;
1395
1396         /* Add thejob to the list of running jobs */
1397         if (!job_list) {
1398                 thejob = job_list = xmalloc(sizeof(*thejob));
1399         } else {
1400                 for (thejob = job_list; thejob->next; thejob = thejob->next)
1401                         continue;
1402                 thejob->next = xmalloc(sizeof(*thejob));
1403                 thejob = thejob->next;
1404         }
1405
1406         /* Physically copy the struct job */
1407         memcpy(thejob, pi, sizeof(struct pipe));
1408         thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1409         /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1410         for (i = 0; i < pi->num_progs; i++) {
1411 // TODO: do we really need to have so many fields which are just dead weight
1412 // at execution stage?
1413                 thejob->progs[i].pid = pi->progs[i].pid;
1414                 //rest:
1415                 //char **argv;                /* program name and arguments */
1416                 //struct pipe *group;         /* if non-NULL, first in group or subshell */
1417                 //int subshell;               /* flag, non-zero if group must be forked */
1418                 //struct redir_struct *redirects; /* I/O redirections */
1419                 //glob_t glob_result;         /* result of parameter globbing */
1420                 //int is_stopped;             /* is the program currently running? */
1421                 //struct pipe *family;        /* pointer back to the child's parent pipe */
1422                 //int sp;                     /* number of SPECIAL_VAR_SYMBOL */
1423                 //int type;
1424         }
1425         thejob->next = NULL;
1426         thejob->cmdtext = xstrdup(get_cmdtext(pi));
1427
1428         /* We don't wait for background thejobs to return -- append it
1429            to the list of backgrounded thejobs and leave it alone */
1430         printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1431         last_bg_pid = thejob->progs[0].pid;
1432         last_jobid = thejob->jobid;
1433 }
1434
1435 static void remove_bg_job(struct pipe *pi)
1436 {
1437         struct pipe *prev_pipe;
1438
1439         if (pi == job_list) {
1440                 job_list = pi->next;
1441         } else {
1442                 prev_pipe = job_list;
1443                 while (prev_pipe->next != pi)
1444                         prev_pipe = prev_pipe->next;
1445                 prev_pipe->next = pi->next;
1446         }
1447         if (job_list)
1448                 last_jobid = job_list->jobid;
1449         else
1450                 last_jobid = 0;
1451 }
1452
1453 /* remove a backgrounded job */
1454 static void delete_finished_bg_job(struct pipe *pi)
1455 {
1456         remove_bg_job(pi);
1457         pi->stopped_progs = 0;
1458         free_pipe(pi, 0);
1459         free(pi);
1460 }
1461 #endif /* JOB */
1462
1463 /* Checks to see if any processes have exited -- if they
1464    have, figure out why and see if a job has completed */
1465 static int checkjobs(struct pipe* fg_pipe)
1466 {
1467         int attributes;
1468         int status;
1469 #if ENABLE_HUSH_JOB
1470         int prognum = 0;
1471         struct pipe *pi;
1472 #endif
1473         pid_t childpid;
1474         int rcode = 0;
1475
1476         attributes = WUNTRACED;
1477         if (fg_pipe == NULL) {
1478                 attributes |= WNOHANG;
1479         }
1480
1481 /* Do we do this right?
1482  * bash-3.00# sleep 20 | false
1483  * <ctrl-Z pressed>
1484  * [3]+  Stopped          sleep 20 | false
1485  * bash-3.00# echo $?
1486  * 1   <========== bg pipe is not fully done, but exitcode is already known!
1487  */
1488
1489 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1490 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1491 // + killall -STOP cat
1492
1493  wait_more:
1494         while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1495                 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1496
1497 #ifdef DEBUG_SHELL_JOBS
1498                 if (WIFSTOPPED(status))
1499                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1500                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
1501                 if (WIFSIGNALED(status))
1502                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1503                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
1504                 if (WIFEXITED(status))
1505                         debug_printf_jobs("pid %d exited, exitcode %d\n",
1506                                         childpid, WEXITSTATUS(status));
1507 #endif
1508                 /* Were we asked to wait for fg pipe? */
1509                 if (fg_pipe) {
1510                         int i;
1511                         for (i = 0; i < fg_pipe->num_progs; i++) {
1512                                 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1513                                 if (fg_pipe->progs[i].pid == childpid) {
1514                                         /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1515                                         if (dead) {
1516                                                 fg_pipe->progs[i].pid = 0;
1517                                                 fg_pipe->running_progs--;
1518                                                 if (i == fg_pipe->num_progs-1)
1519                                                         /* last process gives overall exitstatus */
1520                                                         rcode = WEXITSTATUS(status);
1521                                         } else {
1522                                                 fg_pipe->progs[i].is_stopped = 1;
1523                                                 fg_pipe->stopped_progs++;
1524                                         }
1525                                         debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1526                                                         fg_pipe->running_progs, fg_pipe->stopped_progs);
1527                                         if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1528                                                 /* All processes in fg pipe have exited/stopped */
1529 #if ENABLE_HUSH_JOB
1530                                                 if (fg_pipe->running_progs)
1531                                                         insert_bg_job(fg_pipe);
1532 #endif
1533                                                 return rcode;
1534                                         }
1535                                         /* There are still running processes in the fg pipe */
1536                                         goto wait_more;
1537                                 }
1538                         }
1539                         /* fall through to searching process in bg pipes */
1540                 }
1541
1542 #if ENABLE_HUSH_JOB
1543                 /* We asked to wait for bg or orphaned children */
1544                 /* No need to remember exitcode in this case */
1545                 for (pi = job_list; pi; pi = pi->next) {
1546                         prognum = 0;
1547                         while (prognum < pi->num_progs) {
1548                                 if (pi->progs[prognum].pid == childpid)
1549                                         goto found_pi_and_prognum;
1550                                 prognum++;
1551                         }
1552                 }
1553 #endif
1554
1555                 /* Happens when shell is used as init process (init=/bin/sh) */
1556                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1557                 goto wait_more;
1558
1559 #if ENABLE_HUSH_JOB
1560  found_pi_and_prognum:
1561                 if (dead) {
1562                         /* child exited */
1563                         pi->progs[prognum].pid = 0;
1564                         pi->running_progs--;
1565                         if (!pi->running_progs) {
1566                                 printf(JOB_STATUS_FORMAT, pi->jobid,
1567                                                         "Done", pi->cmdtext);
1568                                 delete_finished_bg_job(pi);
1569                         }
1570                 } else {
1571                         /* child stopped */
1572                         pi->stopped_progs++;
1573                         pi->progs[prognum].is_stopped = 1;
1574                 }
1575 #endif
1576         }
1577
1578         /* wait found no children or failed */
1579
1580         if (childpid && errno != ECHILD)
1581                 bb_perror_msg("waitpid");
1582
1583         /* move the shell to the foreground */
1584         //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1585         //      bb_perror_msg("tcsetpgrp-2");
1586         return rcode;
1587 }
1588
1589 #if ENABLE_HUSH_JOB
1590 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1591 {
1592         pid_t p;
1593         int rcode = checkjobs(fg_pipe);
1594         /* Job finished, move the shell to the foreground */
1595         p = getpgid(0);
1596         debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1597         if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1598                 bb_perror_msg("tcsetpgrp-4a");
1599         return rcode;
1600 }
1601 #endif
1602
1603 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1604  * to finish.  See checkjobs().
1605  *
1606  * return code is normally -1, when the caller has to wait for children
1607  * to finish to determine the exit status of the pipe.  If the pipe
1608  * is a simple builtin command, however, the action is done by the
1609  * time run_pipe_real returns, and the exit code is provided as the
1610  * return value.
1611  *
1612  * The input of the pipe is always stdin, the output is always
1613  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1614  * because it tries to avoid running the command substitution in
1615  * subshell, when that is in fact necessary.  The subshell process
1616  * now has its stdout directed to the input of the appropriate pipe,
1617  * so this routine is noticeably simpler.
1618  */
1619 static int run_pipe_real(struct pipe *pi)
1620 {
1621         int i;
1622         int nextin, nextout;
1623         int pipefds[2];                         /* pipefds[0] is for reading */
1624         struct child_prog *child;
1625         const struct built_in_command *x;
1626         char *p;
1627         /* it is not always needed, but we aim to smaller code */
1628         int squirrel[] = { -1, -1, -1 };
1629         int rcode;
1630         const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1631
1632         debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1633
1634         nextin = 0;
1635 #if ENABLE_HUSH_JOB
1636         pi->pgrp = -1;
1637 #endif
1638         pi->running_progs = 1;
1639         pi->stopped_progs = 0;
1640
1641         /* Check if this is a simple builtin (not part of a pipe).
1642          * Builtins within pipes have to fork anyway, and are handled in
1643          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1644          */
1645         child = &(pi->progs[0]);
1646         if (single_fg && child->group && child->subshell == 0) {
1647                 debug_printf("non-subshell grouping\n");
1648                 setup_redirects(child, squirrel);
1649                 debug_printf_exec(": run_list_real\n");
1650                 rcode = run_list_real(child->group);
1651                 restore_redirects(squirrel);
1652                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1653                 return rcode;
1654         }
1655
1656         if (single_fg && child->argv != NULL) {
1657                 char **argv = child->argv;
1658
1659                 for (i = 0; is_assignment(argv[i]); i++)
1660                         continue;
1661                 if (i != 0 && argv[i] == NULL) {
1662                         /* assignments, but no command: set the local environment */
1663                         for (i = 0; argv[i] != NULL; i++) {
1664                                 /* Ok, this case is tricky.  We have to decide if this is a
1665                                  * local variable, or an already exported variable.  If it is
1666                                  * already exported, we have to export the new value.  If it is
1667                                  * not exported, we need only set this as a local variable.
1668                                  * This junk is all to decide whether or not to export this
1669                                  * variable. */
1670                                 int export_me = 0;
1671                                 char *name, *value;
1672                                 name = xstrdup(argv[i]);
1673                                 debug_printf("Local environment set: %s\n", name);
1674                                 value = strchr(name, '=');
1675                                 if (value)
1676                                         *value = 0;
1677                                 if (get_local_var(name)) {
1678                                         export_me = 1;
1679                                 }
1680                                 free(name);
1681                                 p = insert_var_value(argv[i]);
1682                                 set_local_var(p, export_me);
1683                                 if (p != argv[i])
1684                                         free(p);
1685                         }
1686                         return EXIT_SUCCESS;   /* don't worry about errors in set_local_var() yet */
1687                 }
1688                 for (i = 0; is_assignment(argv[i]); i++) {
1689                         p = insert_var_value(argv[i]);
1690                         putenv(strdup(p));
1691                         if (p != argv[i]) {
1692                                 child->sp--;
1693                                 free(p);
1694                         }
1695                 }
1696                 if (child->sp) {
1697                         char *str;
1698
1699                         str = make_string(argv + i);
1700                         debug_printf_exec(": parse_string_outer '%s'\n", str);
1701                         parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1702                         free(str);
1703                         debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1704                         return last_return_code;
1705                 }
1706                 for (x = bltins; x->cmd; x++) {
1707                         if (strcmp(argv[i], x->cmd) == 0) {
1708                                 if (x->function == builtin_exec && argv[i+1] == NULL) {
1709                                         debug_printf("magic exec\n");
1710                                         setup_redirects(child, NULL);
1711                                         return EXIT_SUCCESS;
1712                                 }
1713                                 debug_printf("builtin inline %s\n", argv[0]);
1714                                 /* XXX setup_redirects acts on file descriptors, not FILEs.
1715                                  * This is perfect for work that comes after exec().
1716                                  * Is it really safe for inline use?  Experimentally,
1717                                  * things seem to work with glibc. */
1718 // TODO: fflush(NULL)?
1719                                 setup_redirects(child, squirrel);
1720                                 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1721                                 rcode = x->function(argv + i);
1722                                 restore_redirects(squirrel);
1723                                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1724                                 return rcode;
1725                         }
1726                 }
1727 #if ENABLE_FEATURE_SH_STANDALONE
1728                 {
1729                         const struct bb_applet *a = find_applet_by_name(argv[i]);
1730                         if (a && a->nofork) {
1731                                 setup_redirects(child, squirrel);
1732                                 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv[i], argv[i+1]);
1733                                 save_nofork_data(&nofork_save);
1734                                 rcode = run_nofork_applet_prime(&nofork_save, a, argv + i);
1735                                 restore_redirects(squirrel);
1736                                 debug_printf_exec("run_pipe_real return %d\n", rcode);
1737                                 return rcode;
1738                         }
1739                 }
1740 #endif
1741         }
1742
1743         /* Going to fork a child per each pipe member */
1744         pi->running_progs = 0;
1745
1746         /* Disable job control signals for shell (parent) and
1747          * for initial child code after fork */
1748         set_jobctrl_sighandler(SIG_IGN);
1749
1750         for (i = 0; i < pi->num_progs; i++) {
1751                 child = &(pi->progs[i]);
1752                 if (child->argv)
1753                         debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1754                 else
1755                         debug_printf_exec(": pipe member with no argv\n");
1756
1757                 /* pipes are inserted between pairs of commands */
1758                 if ((i + 1) < pi->num_progs) {
1759                         if (pipe(pipefds) < 0)
1760                                 bb_perror_msg_and_die("pipe");
1761                         nextout = pipefds[1];
1762                 } else {
1763                         nextout = 1;
1764                         pipefds[0] = -1;
1765                 }
1766
1767                 /* XXX test for failed fork()? */
1768 #if BB_MMU
1769                 child->pid = fork();
1770 #else
1771                 child->pid = vfork();
1772 #endif
1773                 if (!child->pid) { /* child */
1774                         /* Every child adds itself to new process group
1775                          * with pgid == pid of first child in pipe */
1776 #if ENABLE_HUSH_JOB
1777                         if (interactive_fd) {
1778                                 /* Don't do pgrp restore anymore on fatal signals */
1779                                 set_fatal_sighandler(SIG_DFL);
1780                                 if (pi->pgrp < 0) /* true for 1st process only */
1781                                         pi->pgrp = getpid();
1782                                 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1783                                         /* We do it in *every* child, not just first,
1784                                          * to avoid races */
1785                                         tcsetpgrp(interactive_fd, pi->pgrp);
1786                                 }
1787                         }
1788 #endif
1789                         // in non-interactive case fatal sigs are already SIG_DFL
1790                         close_all();
1791                         if (nextin != 0) {
1792                                 dup2(nextin, 0);
1793                                 close(nextin);
1794                         }
1795                         if (nextout != 1) {
1796                                 dup2(nextout, 1);
1797                                 close(nextout);
1798                         }
1799                         if (pipefds[0] != -1) {
1800                                 close(pipefds[0]);  /* opposite end of our output pipe */
1801                         }
1802                         /* Like bash, explicit redirects override pipes,
1803                          * and the pipe fd is available for dup'ing. */
1804                         setup_redirects(child, NULL);
1805
1806                         /* Restore default handlers just prior to exec */
1807                         set_jobctrl_sighandler(SIG_DFL);
1808                         set_misc_sighandler(SIG_DFL);
1809                         signal(SIGCHLD, SIG_DFL);
1810                         pseudo_exec(child);
1811                 }
1812
1813                 pi->running_progs++;
1814
1815 #if ENABLE_HUSH_JOB
1816                 /* Second and next children need to know pid of first one */
1817                 if (pi->pgrp < 0)
1818                         pi->pgrp = child->pid;
1819 #endif
1820
1821                 /* Don't check for errors.  The child may be dead already,
1822                  * in which case setpgid returns error code EACCES. */
1823                 //why we do it at all?? child does it itself
1824                 //if (interactive_fd)
1825                 //      setpgid(child->pid, pi->pgrp);
1826
1827                 if (nextin != 0)
1828                         close(nextin);
1829                 if (nextout != 1)
1830                         close(nextout);
1831
1832                 /* If there isn't another process, nextin is garbage
1833                    but it doesn't matter */
1834                 nextin = pipefds[0];
1835         }
1836         debug_printf_exec("run_pipe_real return -1\n");
1837         return -1;
1838 }
1839
1840 #ifndef debug_print_tree        
1841 static void debug_print_tree(struct pipe *pi, int lvl)
1842 {
1843         static const char *PIPE[] = {
1844                 [PIPE_SEQ] = "SEQ",
1845                 [PIPE_AND] = "AND",
1846                 [PIPE_OR ] = "OR" ,
1847                 [PIPE_BG ] = "BG" ,
1848         };
1849         static const char *RES[] = {
1850                 [RES_NONE ] = "NONE" ,
1851                 [RES_IF   ] = "IF"   ,
1852                 [RES_THEN ] = "THEN" ,
1853                 [RES_ELIF ] = "ELIF" ,
1854                 [RES_ELSE ] = "ELSE" ,
1855                 [RES_FI   ] = "FI"   ,
1856                 [RES_FOR  ] = "FOR"  ,
1857                 [RES_WHILE] = "WHILE",
1858                 [RES_UNTIL] = "UNTIL",
1859                 [RES_DO   ] = "DO"   ,
1860                 [RES_DONE ] = "DONE" ,
1861                 [RES_XXXX ] = "XXXX" ,
1862                 [RES_IN   ] = "IN"   ,
1863                 [RES_SNTX ] = "SNTX" ,
1864         };
1865
1866         int pin, prn;
1867         pin = 0;
1868         while (pi) {
1869                 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1870                                 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1871                 prn = 0;
1872                 while (prn < pi->num_progs) {
1873                         struct child_prog *child = &pi->progs[prn];
1874                         char **argv = child->argv;
1875
1876                         fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1877                         if (child->group) {
1878                                 fprintf(stderr, " group %s: (argv=%p)\n",
1879                                                 (child->subshell ? "()" : "{}"),
1880                                                 argv);
1881                                 debug_print_tree(child->group, lvl+1);
1882                                 prn++;
1883                                 continue;
1884                         }
1885                         if (argv) while (*argv) {
1886                                 fprintf(stderr, " '%s'", *argv);
1887                                 argv++;
1888                         }                               
1889                         fprintf(stderr, "\n");
1890                         prn++;
1891                 }
1892                 pi = pi->next;
1893                 pin++;
1894         }
1895 }
1896 #endif
1897
1898 // NB: called by pseudo_exec, and therefore must not modify any
1899 // global data until exec/_exit (we can be a child after vfork!)
1900 static int run_list_real(struct pipe *pi)
1901 {
1902 #if ENABLE_HUSH_JOB
1903         static int level;
1904 #else
1905         enum { level = 0 };
1906 #endif
1907
1908         char *save_name = NULL;
1909         char **list = NULL;
1910         char **save_list = NULL;
1911         struct pipe *rpipe;
1912         int flag_rep = 0;
1913         int save_num_progs;
1914         int flag_skip = 1;
1915         int rcode = 0; /* probably for gcc only */
1916         int flag_restore = 0;
1917         int if_code = 0, next_if_code = 0;  /* need double-buffer to handle elif */
1918         reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1919
1920         debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1921
1922         /* check syntax for "for" */
1923         for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1924                 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1925                  && (rpipe->next == NULL)
1926                 ) {
1927                         syntax(); /* unterminated FOR (no IN or no commands after IN) */
1928                         debug_printf_exec("run_list_real lvl %d return 1\n", level);
1929                         return 1;
1930                 }
1931                 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1932                  || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1933                 ) {
1934                         /* TODO: what is tested in the first condition? */
1935                         syntax(); /* 2nd: malformed FOR (not followed by IN) */
1936                         debug_printf_exec("run_list_real lvl %d return 1\n", level);
1937                         return 1;
1938                 }
1939         }
1940
1941 #if ENABLE_HUSH_JOB
1942         /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1943          * We are saving state before entering outermost list ("while...done")
1944          * so that ctrl-Z will correctly background _entire_ outermost list,
1945          * not just a part of it (like "sleep 1 | exit 2") */
1946         if (++level == 1 && interactive_fd) {
1947                 if (sigsetjmp(toplevel_jb, 1)) {
1948                         /* ctrl-Z forked and we are parent; or ctrl-C.
1949                          * Sighandler has longjmped us here */
1950                         signal(SIGINT, SIG_IGN);
1951                         signal(SIGTSTP, SIG_IGN);
1952                         /* Restore level (we can be coming from deep inside
1953                          * nested levels) */
1954                         level = 1;
1955 #if ENABLE_FEATURE_SH_STANDALONE
1956                         if (nofork_save.saved) { /* if save area is valid */
1957                                 debug_printf_jobs("exiting nofork early\n");
1958                                 restore_nofork_data(&nofork_save);
1959                         }
1960 #endif
1961                         if (ctrl_z_flag) {
1962                                 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1963                                  * Remember this child as background job */
1964                                 insert_bg_job(pi);
1965                         } else {
1966                                 /* ctrl-C. We just stop doing whatever we were doing */
1967                                 putchar('\n');
1968                         }
1969                         rcode = 0;
1970                         goto ret;
1971                 }
1972                 /* ctrl-Z handler will store pid etc in pi */
1973                 toplevel_list = pi;
1974                 ctrl_z_flag = 0;
1975 #if ENABLE_FEATURE_SH_STANDALONE
1976                 nofork_save.saved = 0; /* in case we will run a nofork later */
1977 #endif
1978                 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1979                 signal(SIGINT, handler_ctrl_c);
1980         }
1981 #endif
1982
1983         for (; pi; pi = flag_restore ? rpipe : pi->next) {
1984                 rmode = pi->r_mode;
1985                 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
1986                         flag_restore = 0;
1987                         if (!rpipe) {
1988                                 flag_rep = 0;
1989                                 rpipe = pi;
1990                         }
1991                 }
1992                 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1993                                 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1994                 if (rmode == skip_more_in_this_rmode && flag_skip) {
1995                         if (pi->followup == PIPE_SEQ)
1996                                 flag_skip = 0;
1997                         continue;
1998                 }
1999                 flag_skip = 1;
2000                 skip_more_in_this_rmode = RES_XXXX;
2001                 if (rmode == RES_THEN || rmode == RES_ELSE)
2002                         if_code = next_if_code;
2003                 if (rmode == RES_THEN && if_code)
2004                         continue;
2005                 if (rmode == RES_ELSE && !if_code)
2006                         continue;
2007                 if (rmode == RES_ELIF && !if_code)
2008                         break;
2009                 if (rmode == RES_FOR && pi->num_progs) {
2010                         if (!list) {
2011                                 /* if no variable values after "in" we skip "for" */
2012                                 if (!pi->next->progs->argv)
2013                                         continue;
2014                                 /* create list of variable values */
2015                                 list = make_list_in(pi->next->progs->argv,
2016                                                 pi->progs->argv[0]);
2017                                 save_list = list;
2018                                 save_name = pi->progs->argv[0];
2019                                 pi->progs->argv[0] = NULL;
2020                                 flag_rep = 1;
2021                         }
2022                         if (!*list) {
2023                                 free(pi->progs->argv[0]);
2024                                 free(save_list);
2025                                 list = NULL;
2026                                 flag_rep = 0;
2027                                 pi->progs->argv[0] = save_name;
2028                                 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2029                                 continue;
2030                         }
2031                         /* insert new value from list for variable */
2032                         free(pi->progs->argv[0]);
2033                         pi->progs->argv[0] = *list++;
2034                         pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2035                 }
2036                 if (rmode == RES_IN)
2037                         continue;
2038                 if (rmode == RES_DO) {
2039                         if (!flag_rep)
2040                                 continue;
2041                 }
2042                 if (rmode == RES_DONE) {
2043                         if (flag_rep) {
2044                                 flag_restore = 1;
2045                         } else {
2046                                 rpipe = NULL;
2047                         }
2048                 }
2049                 if (pi->num_progs == 0)
2050                         continue;
2051                 save_num_progs = pi->num_progs; /* save number of programs */
2052                 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2053                 rcode = run_pipe_real(pi);
2054                 if (rcode != -1) {
2055                         /* We only ran a builtin: rcode was set by the return value
2056                          * of run_pipe_real(), and we don't need to wait for anything. */
2057                 } else if (pi->followup == PIPE_BG) {
2058                         /* What does bash do with attempts to background builtins? */
2059
2060                         /* Even bash 3.2 doesn't do that well with nested bg:
2061                          * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2062                          * I'm considering NOT treating inner bgs as jobs -
2063                          * thus maybe "if (level == 1 && pi->followup == PIPE_BG)"
2064                          * above? */
2065 #if ENABLE_HUSH_JOB
2066                         insert_bg_job(pi);
2067 #endif
2068                         rcode = EXIT_SUCCESS;
2069                 } else {
2070 #if ENABLE_HUSH_JOB
2071                         /* Paranoia, just "interactive_fd" should be enough */
2072                         if (level == 1 && interactive_fd) {
2073                                 rcode = checkjobs_and_fg_shell(pi);
2074                         } else
2075 #endif
2076                         {
2077                                 rcode = checkjobs(pi);
2078                         }
2079                         debug_printf_exec(": checkjobs returned %d\n", rcode);
2080                 }
2081                 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2082                 last_return_code = rcode;
2083                 pi->num_progs = save_num_progs; /* restore number of programs */
2084                 if (rmode == RES_IF || rmode == RES_ELIF)
2085                         next_if_code = rcode;  /* can be overwritten a number of times */
2086                 if (rmode == RES_WHILE)
2087                         flag_rep = !last_return_code;
2088                 if (rmode == RES_UNTIL)
2089                         flag_rep = last_return_code;
2090                 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2091                  || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2092                 ) {
2093                         skip_more_in_this_rmode = rmode;
2094                 }
2095                 checkjobs(NULL);
2096         }
2097
2098 #if ENABLE_HUSH_JOB
2099         if (ctrl_z_flag) {
2100                 /* ctrl-Z forked somewhere in the past, we are the child,
2101                  * and now we completed running the list. Exit. */
2102                 exit(rcode);
2103         }
2104  ret:
2105         level--;
2106 #endif
2107         debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2108         return rcode;
2109 }
2110
2111 /* return code is the exit status of the pipe */
2112 static int free_pipe(struct pipe *pi, int indent)
2113 {
2114         char **p;
2115         struct child_prog *child;
2116         struct redir_struct *r, *rnext;
2117         int a, i, ret_code = 0;
2118
2119         if (pi->stopped_progs > 0)
2120                 return ret_code;
2121         debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2122         for (i = 0; i < pi->num_progs; i++) {
2123                 child = &pi->progs[i];
2124                 debug_printf_clean("%s  command %d:\n", indenter(indent), i);
2125                 if (child->argv) {
2126                         for (a = 0, p = child->argv; *p; a++, p++) {
2127                                 debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
2128                         }
2129                         globfree(&child->glob_result);
2130                         child->argv = NULL;
2131                 } else if (child->group) {
2132                         debug_printf_clean("%s   begin group (subshell:%d)\n", indenter(indent), child->subshell);
2133                         ret_code = free_pipe_list(child->group, indent+3);
2134                         debug_printf_clean("%s   end group\n", indenter(indent));
2135                 } else {
2136                         debug_printf_clean("%s   (nil)\n", indenter(indent));
2137                 }
2138                 for (r = child->redirects; r; r = rnext) {
2139                         debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2140                         if (r->dup == -1) {
2141                                 /* guard against the case >$FOO, where foo is unset or blank */
2142                                 if (r->word.gl_pathv) {
2143                                         debug_printf_clean(" %s\n", *r->word.gl_pathv);
2144                                         globfree(&r->word);
2145                                 }
2146                         } else {
2147                                 debug_printf_clean("&%d\n", r->dup);
2148                         }
2149                         rnext = r->next;
2150                         free(r);
2151                 }
2152                 child->redirects = NULL;
2153         }
2154         free(pi->progs);   /* children are an array, they get freed all at once */
2155         pi->progs = NULL;
2156 #if ENABLE_HUSH_JOB
2157         free(pi->cmdtext);
2158         pi->cmdtext = NULL;
2159 #endif
2160         return ret_code;
2161 }
2162
2163 static int free_pipe_list(struct pipe *head, int indent)
2164 {
2165         int rcode = 0;   /* if list has no members */
2166         struct pipe *pi, *next;
2167
2168         for (pi = head; pi; pi = next) {
2169                 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2170                 rcode = free_pipe(pi, indent);
2171                 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2172                 next = pi->next;
2173                 /*pi->next = NULL;*/
2174                 free(pi);
2175         }
2176         return rcode;
2177 }
2178
2179 /* Select which version we will use */
2180 static int run_list(struct pipe *pi)
2181 {
2182         int rcode = 0;
2183         debug_printf_exec("run_list entered\n");
2184         if (fake_mode == 0) {
2185                 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2186                 rcode = run_list_real(pi);
2187         }
2188         /* free_pipe_list has the side effect of clearing memory.
2189          * In the long run that function can be merged with run_list_real,
2190          * but doing that now would hobble the debugging effort. */
2191         free_pipe_list(pi, 0);
2192         debug_printf_exec("run_list return %d\n", rcode);
2193         return rcode;
2194 }
2195
2196 /* The API for glob is arguably broken.  This routine pushes a non-matching
2197  * string into the output structure, removing non-backslashed backslashes.
2198  * If someone can prove me wrong, by performing this function within the
2199  * original glob(3) api, feel free to rewrite this routine into oblivion.
2200  * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2201  * XXX broken if the last character is '\\', check that before calling.
2202  */
2203 static int globhack(const char *src, int flags, glob_t *pglob)
2204 {
2205         int cnt = 0, pathc;
2206         const char *s;
2207         char *dest;
2208         for (cnt = 1, s = src; s && *s; s++) {
2209                 if (*s == '\\') s++;
2210                 cnt++;
2211         }
2212         dest = malloc(cnt);
2213         if (!dest)
2214                 return GLOB_NOSPACE;
2215         if (!(flags & GLOB_APPEND)) {
2216                 pglob->gl_pathv = NULL;
2217                 pglob->gl_pathc = 0;
2218                 pglob->gl_offs = 0;
2219                 pglob->gl_offs = 0;
2220         }
2221         pathc = ++pglob->gl_pathc;
2222         pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2223         if (pglob->gl_pathv == NULL)
2224                 return GLOB_NOSPACE;
2225         pglob->gl_pathv[pathc-1] = dest;
2226         pglob->gl_pathv[pathc] = NULL;
2227         for (s = src; s && *s; s++, dest++) {
2228                 if (*s == '\\') s++;
2229                 *dest = *s;
2230         }
2231         *dest = '\0';
2232         return 0;
2233 }
2234
2235 /* XXX broken if the last character is '\\', check that before calling */
2236 static int glob_needed(const char *s)
2237 {
2238         for (; *s; s++) {
2239                 if (*s == '\\') s++;
2240                 if (strchr("*[?", *s)) return 1;
2241         }
2242         return 0;
2243 }
2244
2245 static int xglob(o_string *dest, int flags, glob_t *pglob)
2246 {
2247         int gr;
2248
2249         /* short-circuit for null word */
2250         /* we can code this better when the debug_printf's are gone */
2251         if (dest->length == 0) {
2252                 if (dest->nonnull) {
2253                         /* bash man page calls this an "explicit" null */
2254                         gr = globhack(dest->data, flags, pglob);
2255                         debug_printf("globhack returned %d\n", gr);
2256                 } else {
2257                         return 0;
2258                 }
2259         } else if (glob_needed(dest->data)) {
2260                 gr = glob(dest->data, flags, NULL, pglob);
2261                 debug_printf("glob returned %d\n", gr);
2262                 if (gr == GLOB_NOMATCH) {
2263                         /* quote removal, or more accurately, backslash removal */
2264                         gr = globhack(dest->data, flags, pglob);
2265                         debug_printf("globhack returned %d\n", gr);
2266                 }
2267         } else {
2268                 gr = globhack(dest->data, flags, pglob);
2269                 debug_printf("globhack returned %d\n", gr);
2270         }
2271         if (gr == GLOB_NOSPACE)
2272                 bb_error_msg_and_die("out of memory during glob");
2273         if (gr != 0) { /* GLOB_ABORTED ? */
2274                 bb_error_msg("glob(3) error %d", gr);
2275         }
2276         /* globprint(glob_target); */
2277         return gr;
2278 }
2279
2280 static char **make_list_in(char **inp, char *name)
2281 {
2282         int len, i;
2283         int name_len = strlen(name);
2284         int n = 0;
2285         char **list;
2286         char *p1, *p2, *p3;
2287
2288         /* create list of variable values */
2289         list = xmalloc(sizeof(*list));
2290         for (i = 0; inp[i]; i++) {
2291                 p3 = insert_var_value(inp[i]);
2292                 p1 = p3;
2293                 while (*p1) {
2294                         if ((*p1 == ' ')) {
2295                                 p1++;
2296                                 continue;
2297                         }
2298                         p2 = strchr(p1, ' ');
2299                         if (p2) {
2300                                 len = p2 - p1;
2301                         } else {
2302                                 len = strlen(p1);
2303                                 p2 = p1 + len;
2304                         }
2305                         /* we use n + 2 in realloc for list, because we add
2306                          * new element and then we will add NULL element */
2307                         list = xrealloc(list, sizeof(*list) * (n + 2));
2308                         list[n] = xmalloc(2 + name_len + len);
2309                         strcpy(list[n], name);
2310                         strcat(list[n], "=");
2311                         strncat(list[n], p1, len);
2312                         list[n++][name_len + len + 1] = '\0';
2313                         p1 = p2;
2314                 }
2315                 if (p3 != inp[i]) free(p3);
2316         }
2317         list[n] = NULL;
2318         return list;
2319 }
2320
2321 static char *insert_var_value(char *inp)
2322 {
2323         int res_str_len = 0;
2324         int len;
2325         int done = 0;
2326         char *p, *res_str = NULL;
2327         const char *p1;
2328
2329         while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2330                 if (p != inp) {
2331                         len = p - inp;
2332                         res_str = xrealloc(res_str, (res_str_len + len));
2333                         strncpy((res_str + res_str_len), inp, len);
2334                         res_str_len += len;
2335                 }
2336                 inp = ++p;
2337                 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2338                 *p = '\0';
2339                 p1 = lookup_param(inp);
2340                 if (p1) {
2341                         len = res_str_len + strlen(p1);
2342                         res_str = xrealloc(res_str, (1 + len));
2343                         strcpy((res_str + res_str_len), p1);
2344                         res_str_len = len;
2345                 }
2346                 *p = SPECIAL_VAR_SYMBOL;
2347                 inp = ++p;
2348                 done = 1;
2349         }
2350         if (done) {
2351                 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2352                 strcpy((res_str + res_str_len), inp);
2353                 while ((p = strchr(res_str, '\n'))) {
2354                         *p = ' ';
2355                 }
2356         }
2357         return (res_str == NULL) ? inp : res_str;
2358 }
2359
2360 /* This is used to get/check local shell variables */
2361 static const char *get_local_var(const char *s)
2362 {
2363         struct variables *cur;
2364
2365         if (!s)
2366                 return NULL;
2367         for (cur = top_vars; cur; cur = cur->next)
2368                 if (strcmp(cur->name, s) == 0)
2369                         return cur->value;
2370         return NULL;
2371 }
2372
2373 /* This is used to set local shell variables
2374    flg_export == 0 if only local (not exporting) variable
2375    flg_export == 1 if "new" exporting environ
2376    flg_export > 1  if current startup environ (not call putenv()) */
2377 static int set_local_var(const char *s, int flg_export)
2378 {
2379         char *name, *value;
2380         int result = 0;
2381         struct variables *cur;
2382
2383         name = strdup(s);
2384
2385         /* Assume when we enter this function that we are already in
2386          * NAME=VALUE format.  So the first order of business is to
2387          * split 's' on the '=' into 'name' and 'value' */
2388         value = strchr(name, '=');
2389         /*if (value == 0 && ++value == 0) ??? -vda */
2390         if (value == NULL || value[1] == '\0') {
2391                 free(name);
2392                 return -1;
2393         }
2394         *value++ = '\0';
2395
2396         for (cur = top_vars; cur; cur = cur->next) {
2397                 if (strcmp(cur->name, name) == 0)
2398                         break;
2399         }
2400
2401         if (cur) {
2402                 if (strcmp(cur->value, value) == 0) {
2403                         if (flg_export > 0 && cur->flg_export == 0)
2404                                 cur->flg_export = flg_export;
2405                         else
2406                                 result++;
2407                 } else if (cur->flg_read_only) {
2408                         bb_error_msg("%s: readonly variable", name);
2409                         result = -1;
2410                 } else {
2411                         if (flg_export > 0 || cur->flg_export > 1)
2412                                 cur->flg_export = 1;
2413                         free((char*)cur->value);
2414
2415                         cur->value = strdup(value);
2416                 }
2417         } else {
2418                 cur = malloc(sizeof(struct variables));
2419                 if (!cur) {
2420                         result = -1;
2421                 } else {
2422                         cur->name = strdup(name);
2423                         if (cur->name) {
2424                                 free(cur);
2425                                 result = -1;
2426                         } else {
2427                                 struct variables *bottom = top_vars;
2428                                 cur->value = strdup(value);
2429                                 cur->next = 0;
2430                                 cur->flg_export = flg_export;
2431                                 cur->flg_read_only = 0;
2432                                 while (bottom->next)
2433                                         bottom = bottom->next;
2434                                 bottom->next = cur;
2435                         }
2436                 }
2437         }
2438
2439         if (result == 0 && cur->flg_export == 1) {
2440                 *(value-1) = '=';
2441                 result = putenv(name);
2442         } else {
2443                 free(name);
2444                 if (result > 0)            /* equivalent to previous set */
2445                         result = 0;
2446         }
2447         return result;
2448 }
2449
2450 static void unset_local_var(const char *name)
2451 {
2452         struct variables *cur, *next;
2453
2454         if (!name)
2455                 return;
2456         for (cur = top_vars; cur; cur = cur->next) {
2457                 if (strcmp(cur->name, name) == 0) {
2458                         if (cur->flg_read_only) {
2459                                 bb_error_msg("%s: readonly variable", name);
2460                                 return;
2461                         }
2462                         if (cur->flg_export)
2463                                 unsetenv(cur->name);
2464                         free((char*)cur->name);
2465                         free((char*)cur->value);
2466                         next = top_vars;
2467                         while (next->next != cur)
2468                                 next = next->next;
2469                         next->next = cur->next;
2470                         free(cur);
2471                         return;
2472                 }
2473         }
2474 }
2475
2476 static int is_assignment(const char *s)
2477 {
2478         if (!s || !isalpha(*s))
2479                 return 0;
2480         s++;
2481         while (isalnum(*s) || *s == '_')
2482                 s++;
2483         return *s == '=';
2484 }
2485
2486 /* the src parameter allows us to peek forward to a possible &n syntax
2487  * for file descriptor duplication, e.g., "2>&1".
2488  * Return code is 0 normally, 1 if a syntax error is detected in src.
2489  * Resource errors (in xmalloc) cause the process to exit */
2490 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2491         struct in_str *input)
2492 {
2493         struct child_prog *child = ctx->child;
2494         struct redir_struct *redir = child->redirects;
2495         struct redir_struct *last_redir = NULL;
2496
2497         /* Create a new redir_struct and drop it onto the end of the linked list */
2498         while (redir) {
2499                 last_redir = redir;
2500                 redir = redir->next;
2501         }
2502         redir = xmalloc(sizeof(struct redir_struct));
2503         redir->next = NULL;
2504         redir->word.gl_pathv = NULL;
2505         if (last_redir) {
2506                 last_redir->next = redir;
2507         } else {
2508                 child->redirects = redir;
2509         }
2510
2511         redir->type = style;
2512         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2513
2514         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2515
2516         /* Check for a '2>&1' type redirect */
2517         redir->dup = redirect_dup_num(input);
2518         if (redir->dup == -2) return 1;  /* syntax error */
2519         if (redir->dup != -1) {
2520                 /* Erik had a check here that the file descriptor in question
2521                  * is legit; I postpone that to "run time"
2522                  * A "-" representation of "close me" shows up as a -3 here */
2523                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2524         } else {
2525                 /* We do _not_ try to open the file that src points to,
2526                  * since we need to return and let src be expanded first.
2527                  * Set ctx->pending_redirect, so we know what to do at the
2528                  * end of the next parsed word.
2529                  */
2530                 ctx->pending_redirect = redir;
2531         }
2532         return 0;
2533 }
2534
2535 static struct pipe *new_pipe(void)
2536 {
2537         struct pipe *pi;
2538         pi = xzalloc(sizeof(struct pipe));
2539         /*pi->num_progs = 0;*/
2540         /*pi->progs = NULL;*/
2541         /*pi->next = NULL;*/
2542         /*pi->followup = 0;  invalid */
2543         if (RES_NONE)
2544                 pi->r_mode = RES_NONE;
2545         return pi;
2546 }
2547
2548 static void initialize_context(struct p_context *ctx)
2549 {
2550         ctx->pipe = NULL;
2551         ctx->pending_redirect = NULL;
2552         ctx->child = NULL;
2553         ctx->list_head = new_pipe();
2554         ctx->pipe = ctx->list_head;
2555         ctx->res_w = RES_NONE;
2556         ctx->stack = NULL;
2557         ctx->old_flag = 0;
2558         done_command(ctx);   /* creates the memory for working child */
2559 }
2560
2561 /* normal return is 0
2562  * if a reserved word is found, and processed, return 1
2563  * should handle if, then, elif, else, fi, for, while, until, do, done.
2564  * case, function, and select are obnoxious, save those for later.
2565  */
2566 static int reserved_word(o_string *dest, struct p_context *ctx)
2567 {
2568         struct reserved_combo {
2569                 char literal[7];
2570                 unsigned char code;
2571                 int flag;
2572         };
2573         /* Mostly a list of accepted follow-up reserved words.
2574          * FLAG_END means we are done with the sequence, and are ready
2575          * to turn the compound list into a command.
2576          * FLAG_START means the word must start a new compound list.
2577          */
2578         static const struct reserved_combo reserved_list[] = {
2579                 { "if",    RES_IF,    FLAG_THEN | FLAG_START },
2580                 { "then",  RES_THEN,  FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2581                 { "elif",  RES_ELIF,  FLAG_THEN },
2582                 { "else",  RES_ELSE,  FLAG_FI   },
2583                 { "fi",    RES_FI,    FLAG_END  },
2584                 { "for",   RES_FOR,   FLAG_IN   | FLAG_START },
2585                 { "while", RES_WHILE, FLAG_DO   | FLAG_START },
2586                 { "until", RES_UNTIL, FLAG_DO   | FLAG_START },
2587                 { "in",    RES_IN,    FLAG_DO   },
2588                 { "do",    RES_DO,    FLAG_DONE },
2589                 { "done",  RES_DONE,  FLAG_END  }
2590         };
2591         enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2592         const struct reserved_combo *r;
2593
2594         for (r = reserved_list; r < reserved_list + NRES; r++) {
2595                 if (strcmp(dest->data, r->literal) == 0) {
2596                         debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2597                         if (r->flag & FLAG_START) {
2598                                 struct p_context *new = xmalloc(sizeof(struct p_context));
2599                                 debug_printf("push stack\n");
2600                                 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2601                                         syntax();
2602                                         free(new);
2603                                         ctx->res_w = RES_SNTX;
2604                                         b_reset(dest);
2605                                         return 1;
2606                                 }
2607                                 *new = *ctx;   /* physical copy */
2608                                 initialize_context(ctx);
2609                                 ctx->stack = new;
2610                         } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2611                                 syntax();
2612                                 ctx->res_w = RES_SNTX;
2613                                 b_reset(dest);
2614                                 return 1;
2615                         }
2616                         ctx->res_w = r->code;
2617                         ctx->old_flag = r->flag;
2618                         if (ctx->old_flag & FLAG_END) {
2619                                 struct p_context *old;
2620                                 debug_printf("pop stack\n");
2621                                 done_pipe(ctx, PIPE_SEQ);
2622                                 old = ctx->stack;
2623                                 old->child->group = ctx->list_head;
2624                                 old->child->subshell = 0;
2625                                 *ctx = *old;   /* physical copy */
2626                                 free(old);
2627                         }
2628                         b_reset(dest);
2629                         return 1;
2630                 }
2631         }
2632         return 0;
2633 }
2634
2635 /* Normal return is 0.
2636  * Syntax or xglob errors return 1. */
2637 static int done_word(o_string *dest, struct p_context *ctx)
2638 {
2639         struct child_prog *child = ctx->child;
2640         glob_t *glob_target;
2641         int gr, flags = 0;
2642
2643         debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2644         if (dest->length == 0 && !dest->nonnull) {
2645                 debug_printf_parse("done_word return 0: true null, ignored\n");
2646                 return 0;
2647         }
2648         if (ctx->pending_redirect) {
2649                 glob_target = &ctx->pending_redirect->word;
2650         } else {
2651                 if (child->group) {
2652                         syntax();
2653                         debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2654                         return 1;
2655                 }
2656                 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2657                         debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2658                         if (reserved_word(dest, ctx)) {
2659                                 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2660                                 return (ctx->res_w == RES_SNTX);
2661                         }
2662                 }
2663                 glob_target = &child->glob_result;
2664                 if (child->argv)
2665                         flags |= GLOB_APPEND;
2666         }
2667         gr = xglob(dest, flags, glob_target);
2668         if (gr != 0) {
2669                 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2670                 return 1;
2671         }
2672
2673         b_reset(dest);
2674         if (ctx->pending_redirect) {
2675                 ctx->pending_redirect = NULL;
2676                 if (glob_target->gl_pathc != 1) {
2677                         bb_error_msg("ambiguous redirect");
2678                         debug_printf_parse("done_word return 1: ambiguous redirect\n");
2679                         return 1;
2680                 }
2681         } else {
2682                 child->argv = glob_target->gl_pathv;
2683         }
2684         if (ctx->res_w == RES_FOR) {
2685                 done_word(dest, ctx);
2686                 done_pipe(ctx, PIPE_SEQ);
2687         }
2688         debug_printf_parse("done_word return 0\n");
2689         return 0;
2690 }
2691
2692 /* The only possible error here is out of memory, in which case
2693  * xmalloc exits. */
2694 static int done_command(struct p_context *ctx)
2695 {
2696         /* The child is really already in the pipe structure, so
2697          * advance the pipe counter and make a new, null child. */
2698         struct pipe *pi = ctx->pipe;
2699         struct child_prog *child = ctx->child;
2700
2701         if (child) {
2702                 if (child->group == NULL
2703                  && child->argv == NULL
2704                  && child->redirects == NULL
2705                 ) {
2706                         debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2707                         return pi->num_progs;
2708                 }
2709                 pi->num_progs++;
2710                 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2711         } else {
2712                 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2713         }
2714
2715         /* Only real trickiness here is that the uncommitted
2716          * child structure is not counted in pi->num_progs. */
2717         pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2718         child = &pi->progs[pi->num_progs];
2719
2720         memset(child, 0, sizeof(*child));
2721         /*child->redirects = NULL;*/
2722         /*child->argv = NULL;*/
2723         /*child->is_stopped = 0;*/
2724         /*child->group = NULL;*/
2725         /*child->glob_result.gl_pathv = NULL;*/
2726         child->family = pi;
2727         /*child->sp = 0;*/
2728         child->type = ctx->parse_type;
2729
2730         ctx->child = child;
2731         /* but ctx->pipe and ctx->list_head remain unchanged */
2732
2733         return pi->num_progs; /* used only for 0/nonzero check */
2734 }
2735
2736 static int done_pipe(struct p_context *ctx, pipe_style type)
2737 {
2738         struct pipe *new_p;
2739         int not_null;
2740
2741         debug_printf_parse("done_pipe entered, followup %d\n", type);
2742         not_null = done_command(ctx);  /* implicit closure of previous command */
2743         ctx->pipe->followup = type;
2744         ctx->pipe->r_mode = ctx->res_w;
2745         /* Without this check, even just <enter> on command line generates
2746          * tree of three NOPs (!). Which is harmless but annoying.
2747          * IOW: it is safe to do it unconditionally. */
2748         if (not_null) {
2749                 new_p = new_pipe();
2750                 ctx->pipe->next = new_p;
2751                 ctx->pipe = new_p;
2752                 ctx->child = NULL;
2753                 done_command(ctx);  /* set up new pipe to accept commands */
2754         }
2755         debug_printf_parse("done_pipe return 0\n");
2756         return 0;
2757 }
2758
2759 /* peek ahead in the in_str to find out if we have a "&n" construct,
2760  * as in "2>&1", that represents duplicating a file descriptor.
2761  * returns either -2 (syntax error), -1 (no &), or the number found.
2762  */
2763 static int redirect_dup_num(struct in_str *input)
2764 {
2765         int ch, d = 0, ok = 0;
2766         ch = b_peek(input);
2767         if (ch != '&') return -1;
2768
2769         b_getch(input);  /* get the & */
2770         ch = b_peek(input);
2771         if (ch == '-') {
2772                 b_getch(input);
2773                 return -3;  /* "-" represents "close me" */
2774         }
2775         while (isdigit(ch)) {
2776                 d = d*10 + (ch-'0');
2777                 ok = 1;
2778                 b_getch(input);
2779                 ch = b_peek(input);
2780         }
2781         if (ok) return d;
2782
2783         bb_error_msg("ambiguous redirect");
2784         return -2;
2785 }
2786
2787 /* If a redirect is immediately preceded by a number, that number is
2788  * supposed to tell which file descriptor to redirect.  This routine
2789  * looks for such preceding numbers.  In an ideal world this routine
2790  * needs to handle all the following classes of redirects...
2791  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
2792  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
2793  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
2794  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
2795  * A -1 output from this program means no valid number was found, so the
2796  * caller should use the appropriate default for this redirection.
2797  */
2798 static int redirect_opt_num(o_string *o)
2799 {
2800         int num;
2801
2802         if (o->length == 0)
2803                 return -1;
2804         for (num = 0; num < o->length; num++) {
2805                 if (!isdigit(*(o->data + num))) {
2806                         return -1;
2807                 }
2808         }
2809         /* reuse num (and save an int) */
2810         num = atoi(o->data);
2811         b_reset(o);
2812         return num;
2813 }
2814
2815 static FILE *generate_stream_from_list(struct pipe *head)
2816 {
2817         FILE *pf;
2818         int pid, channel[2];
2819         if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2820 #if BB_MMU
2821         pid = fork();
2822 #else
2823         pid = vfork();
2824 #endif
2825         if (pid < 0) {
2826                 bb_perror_msg_and_die("fork");
2827         } else if (pid == 0) {
2828                 close(channel[0]);
2829                 if (channel[1] != 1) {
2830                         dup2(channel[1], 1);
2831                         close(channel[1]);
2832                 }
2833                 _exit(run_list_real(head));   /* leaks memory */
2834         }
2835         debug_printf("forked child %d\n", pid);
2836         close(channel[1]);
2837         pf = fdopen(channel[0], "r");
2838         debug_printf("pipe on FILE *%p\n", pf);
2839         return pf;
2840 }
2841
2842 /* Return code is exit status of the process that is run. */
2843 static int process_command_subs(o_string *dest, struct p_context *ctx,
2844         struct in_str *input, const char *subst_end)
2845 {
2846         int retcode;
2847         o_string result = NULL_O_STRING;
2848         struct p_context inner;
2849         FILE *p;
2850         struct in_str pipe_str;
2851         initialize_context(&inner);
2852
2853         /* recursion to generate command */
2854         retcode = parse_stream(&result, &inner, input, subst_end);
2855         if (retcode != 0) return retcode;  /* syntax error or EOF */
2856         done_word(&result, &inner);
2857         done_pipe(&inner, PIPE_SEQ);
2858         b_free(&result);
2859
2860         p = generate_stream_from_list(inner.list_head);
2861         if (p == NULL) return 1;
2862         mark_open(fileno(p));
2863 // FIXME: need to flag pipe_str to somehow discard all trailing newlines.
2864 // Example: echo "TEST`date;echo;echo`BEST"
2865 //          must produce one line: TEST<date>BEST
2866         setup_file_in_str(&pipe_str, p);
2867
2868         /* now send results of command back into original context */
2869 // FIXME: must not do quote parsing of the output!
2870 // Example: echo "TEST`echo '$(echo ZZ)'`BEST"
2871 //          must produce TEST$(echo ZZ)BEST, not TESTZZBEST.
2872 // Example: echo "TEST`echo "'"`BEST"
2873 //          must produce TEST'BEST
2874 // (maybe by setting all chars flagged as literals in map[]?)
2875
2876         retcode = parse_stream(dest, ctx, &pipe_str, NULL);
2877         /* XXX In case of a syntax error, should we try to kill the child?
2878          * That would be tough to do right, so just read until EOF. */
2879         if (retcode == 1) {
2880                 while (b_getch(&pipe_str) != EOF)
2881                         /* discard */;
2882         }
2883
2884         debug_printf("done reading from pipe, pclose()ing\n");
2885         /* This is the step that wait()s for the child.  Should be pretty
2886          * safe, since we just read an EOF from its stdout.  We could try
2887          * to better, by using wait(), and keeping track of background jobs
2888          * at the same time.  That would be a lot of work, and contrary
2889          * to the KISS philosophy of this program. */
2890         mark_closed(fileno(p));
2891         retcode = pclose(p);
2892         free_pipe_list(inner.list_head, 0);
2893         debug_printf("pclosed, retcode=%d\n", retcode);
2894         return retcode;
2895 }
2896
2897 static int parse_group(o_string *dest, struct p_context *ctx,
2898         struct in_str *input, int ch)
2899 {
2900         int rcode;
2901         const char *endch = NULL;
2902         struct p_context sub;
2903         struct child_prog *child = ctx->child;
2904
2905         debug_printf_parse("parse_group entered\n");
2906         if (child->argv) {
2907                 syntax();
2908                 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
2909                 return 1;
2910         }
2911         initialize_context(&sub);
2912         switch (ch) {
2913         case '(':
2914                 endch = ")";
2915                 child->subshell = 1;
2916                 break;
2917         case '{':
2918                 endch = "}";
2919                 break;
2920         default:
2921                 syntax();   /* really logic error */
2922         }
2923         rcode = parse_stream(dest, &sub, input, endch);
2924         done_word(dest, &sub); /* finish off the final word in the subcontext */
2925         done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
2926         child->group = sub.list_head;
2927
2928         debug_printf_parse("parse_group return %d\n", rcode);
2929         return rcode;
2930         /* child remains "open", available for possible redirects */
2931 }
2932
2933 /* Basically useful version until someone wants to get fancier,
2934  * see the bash man page under "Parameter Expansion" */
2935 static const char *lookup_param(const char *src)
2936 {
2937         const char *p = NULL;
2938         if (src) {
2939                 p = getenv(src);
2940                 if (!p)
2941                         p = get_local_var(src);
2942         }
2943         return p;
2944 }
2945
2946 /* Make new string for parser */
2947 static char* make_string(char ** inp)
2948 {
2949         char *p;
2950         char *str = NULL;
2951         int n;
2952         int len = 2;
2953
2954         for (n = 0; inp[n]; n++) {
2955                 p = insert_var_value(inp[n]);
2956                 str = xrealloc(str, (len + strlen(p)));
2957                 if (n) {
2958                         strcat(str, " ");
2959                 } else {
2960                         *str = '\0';
2961                 }
2962                 strcat(str, p);
2963                 len = strlen(str) + 3;
2964                 if (p != inp[n]) free(p);
2965         }
2966         len = strlen(str);
2967         str[len] = '\n';
2968         str[len+1] = '\0';
2969         return str;
2970 }
2971
2972 /* return code: 0 for OK, 1 for syntax error */
2973 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2974 {
2975         int i, advance = 0;
2976         char sep[] = " ";
2977         int ch = input->peek(input);  /* first character after the $ */
2978         debug_printf("handle_dollar: ch=%c\n", ch);
2979         if (isalpha(ch)) {
2980                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2981                 ctx->child->sp++;
2982                 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2983                         b_getch(input);
2984                         b_addchr(dest, ch);
2985                 }
2986                 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2987         } else if (isdigit(ch)) {
2988                 i = ch - '0';  /* XXX is $0 special? */
2989                 if (i < global_argc) {
2990                         parse_string(dest, ctx, global_argv[i]); /* recursion */
2991                 }
2992                 advance = 1;
2993         } else switch (ch) {
2994                 case '$':
2995                         b_adduint(dest, getpid());
2996                         advance = 1;
2997                         break;
2998                 case '!':
2999                         if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
3000                         advance = 1;
3001                         break;
3002                 case '?':
3003                         b_adduint(dest, last_return_code);
3004                         advance = 1;
3005                         break;
3006                 case '#':
3007                         b_adduint(dest, global_argc ? global_argc-1 : 0);
3008                         advance = 1;
3009                         break;
3010                 case '{':
3011                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
3012                         ctx->child->sp++;
3013                         b_getch(input);
3014                         /* XXX maybe someone will try to escape the '}' */
3015                         while (1) {
3016                                 ch = b_getch(input);
3017                                 if (ch == EOF || ch == '}')
3018                                         break;
3019                                 b_addchr(dest, ch);
3020                         }
3021                         if (ch != '}') {
3022                                 syntax();
3023                                 return 1;
3024                         }
3025                         b_addchr(dest, SPECIAL_VAR_SYMBOL);
3026                         break;
3027                 case '(':
3028                         b_getch(input);
3029                         process_command_subs(dest, ctx, input, ")");
3030                         break;
3031                 case '*':
3032                         sep[0] = ifs[0];
3033                         for (i = 1; i < global_argc; i++) {
3034                                 parse_string(dest, ctx, global_argv[i]);
3035                                 if (i+1 < global_argc)
3036                                         parse_string(dest, ctx, sep);
3037                         }
3038                         break;
3039                 case '@':
3040                 case '-':
3041                 case '_':
3042                         /* still unhandled, but should be eventually */
3043                         bb_error_msg("unhandled syntax: $%c", ch);
3044                         return 1;
3045                         break;
3046                 default:
3047                         b_addqchr(dest,'$', dest->quote);
3048         }
3049         /* Eat the character if the flag was set.  If the compiler
3050          * is smart enough, we could substitute "b_getch(input);"
3051          * for all the "advance = 1;" above, and also end up with
3052          * a nice size-optimized program.  Hah!  That'll be the day.
3053          */
3054         if (advance) b_getch(input);
3055         return 0;
3056 }
3057
3058 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
3059 {
3060         struct in_str foo;
3061         setup_string_in_str(&foo, src);
3062         return parse_stream(dest, ctx, &foo, NULL);
3063 }
3064
3065 /* return code is 0 for normal exit, 1 for syntax error */
3066 static int parse_stream(o_string *dest, struct p_context *ctx,
3067         struct in_str *input, const char *end_trigger)
3068 {
3069         int ch, m;
3070         int redir_fd;
3071         redir_type redir_style;
3072         int next;
3073
3074         /* Only double-quote state is handled in the state variable dest->quote.
3075          * A single-quote triggers a bypass of the main loop until its mate is
3076          * found.  When recursing, quote state is passed in via dest->quote. */
3077
3078         debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3079
3080         while ((ch = b_getch(input)) != EOF) {
3081                 m = map[ch];
3082                 next = (ch == '\n') ? 0 : b_peek(input);
3083                 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3084                                                 ch, ch, m, dest->quote);
3085                 if (m == MAP_ORDINARY
3086                  || (m != MAP_NEVER_FLOWTROUGH && dest->quote)
3087                 ) {
3088                         b_addqchr(dest, ch, dest->quote);
3089                         continue;
3090                 }
3091                 if (m == MAP_IFS_IF_UNQUOTED) {
3092                         if (done_word(dest, ctx)) {
3093                                 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3094                                 return 1;
3095                         }
3096                         /* If we aren't performing a substitution, treat
3097                          * a newline as a command separator.
3098                          * [why we don't handle it exactly like ';'? --vda] */
3099                         if (end_trigger && ch == '\n') {
3100                                 done_pipe(ctx, PIPE_SEQ);
3101                         }
3102                 }
3103                 if ((end_trigger && strchr(end_trigger, ch))
3104                  && !dest->quote && ctx->res_w == RES_NONE
3105                 ) {
3106                         debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3107                         return 0;
3108                 }
3109                 if (m == MAP_IFS_IF_UNQUOTED)
3110                         continue;
3111                 switch (ch) {
3112                 case '#':
3113                         if (dest->length == 0 && !dest->quote) {
3114                                 while (1) {
3115                                         ch = b_peek(input);
3116                                         if (ch == EOF || ch == '\n')
3117                                                 break;
3118                                         b_getch(input);
3119                                 }
3120                         } else {
3121                                 b_addqchr(dest, ch, dest->quote);
3122                         }
3123                         break;
3124                 case '\\':
3125                         if (next == EOF) {
3126                                 syntax();
3127                                 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3128                                 return 1;
3129                         }
3130                         b_addqchr(dest, '\\', dest->quote);
3131                         b_addqchr(dest, b_getch(input), dest->quote);
3132                         break;
3133                 case '$':
3134                         if (handle_dollar(dest, ctx, input) != 0) {
3135                                 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3136                                 return 1;
3137                         }
3138                         break;
3139                 case '\'':
3140                         dest->nonnull = 1;
3141                         while (1) {
3142                                 ch = b_getch(input);
3143                                 if (ch == EOF || ch == '\'')
3144                                         break;
3145                                 b_addchr(dest, ch);
3146                         }
3147                         if (ch == EOF) {
3148                                 syntax();
3149                                 debug_printf_parse("parse_stream return 1: unterminated '\n");
3150                                 return 1;
3151                         }
3152                         break;
3153                 case '"':
3154                         dest->nonnull = 1;
3155                         dest->quote = !dest->quote;
3156                         break;
3157                 case '`':
3158                         process_command_subs(dest, ctx, input, "`");
3159                         break;
3160                 case '>':
3161                         redir_fd = redirect_opt_num(dest);
3162                         done_word(dest, ctx);
3163                         redir_style = REDIRECT_OVERWRITE;
3164                         if (next == '>') {
3165                                 redir_style = REDIRECT_APPEND;
3166                                 b_getch(input);
3167                         } else if (next == '(') {
3168                                 syntax();   /* until we support >(list) Process Substitution */
3169                                 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3170                                 return 1;
3171                         }
3172                         setup_redirect(ctx, redir_fd, redir_style, input);
3173                         break;
3174                 case '<':
3175                         redir_fd = redirect_opt_num(dest);
3176                         done_word(dest, ctx);
3177                         redir_style = REDIRECT_INPUT;
3178                         if (next == '<') {
3179                                 redir_style = REDIRECT_HEREIS;
3180                                 b_getch(input);
3181                         } else if (next == '>') {
3182                                 redir_style = REDIRECT_IO;
3183                                 b_getch(input);
3184                         } else if (next == '(') {
3185                                 syntax();   /* until we support <(list) Process Substitution */
3186                                 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3187                                 return 1;
3188                         }
3189                         setup_redirect(ctx, redir_fd, redir_style, input);
3190                         break;
3191                 case ';':
3192                         done_word(dest, ctx);
3193                         done_pipe(ctx, PIPE_SEQ);
3194                         break;
3195                 case '&':
3196                         done_word(dest, ctx);
3197                         if (next == '&') {
3198                                 b_getch(input);
3199                                 done_pipe(ctx, PIPE_AND);
3200                         } else {
3201                                 done_pipe(ctx, PIPE_BG);
3202                         }
3203                         break;
3204                 case '|':
3205                         done_word(dest, ctx);
3206                         if (next == '|') {
3207                                 b_getch(input);
3208                                 done_pipe(ctx, PIPE_OR);
3209                         } else {
3210                                 /* we could pick up a file descriptor choice here
3211                                  * with redirect_opt_num(), but bash doesn't do it.
3212                                  * "echo foo 2| cat" yields "foo 2". */
3213                                 done_command(ctx);
3214                         }
3215                         break;
3216                 case '(':
3217                 case '{':
3218                         if (parse_group(dest, ctx, input, ch) != 0) {
3219                                 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3220                                 return 1;
3221                         }
3222                         break;
3223                 case ')':
3224                 case '}':
3225                         syntax();   /* Proper use of this character is caught by end_trigger */
3226                         debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3227                         return 1;
3228                 default:
3229                         syntax();   /* this is really an internal logic error */
3230                         debug_printf_parse("parse_stream return 1: internal logic error\n");
3231                         return 1;
3232                 }
3233         }
3234         /* Complain if quote?  No, maybe we just finished a command substitution
3235          * that was quoted.  Example:
3236          * $ echo "`cat foo` plus more"
3237          * and we just got the EOF generated by the subshell that ran "cat foo"
3238          * The only real complaint is if we got an EOF when end_trigger != NULL,
3239          * that is, we were really supposed to get end_trigger, and never got
3240          * one before the EOF.  Can't use the standard "syntax error" return code,
3241          * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3242         debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3243         if (end_trigger)
3244                 return -1;
3245         return 0;
3246 }
3247
3248 static void mapset(const char *set, int code)
3249 {
3250         while (*set)
3251                 map[(unsigned char)*set++] = code;
3252 }
3253
3254 static void update_ifs_map(void)
3255 {
3256         /* char *ifs and char map[256] are both globals. */
3257         ifs = getenv("IFS");
3258         if (ifs == NULL)
3259                 ifs = " \t\n";
3260         /* Precompute a list of 'flow through' behavior so it can be treated
3261          * quickly up front.  Computation is necessary because of IFS.
3262          * Special case handling of IFS == " \t\n" is not implemented.
3263          * The map[] array only really needs two bits each, and on most machines
3264          * that would be faster because of the reduced L1 cache footprint.
3265          */
3266         memset(map, MAP_ORDINARY, sizeof(map)); /* most chars flow through always */
3267         mapset("\\$'\"`", MAP_NEVER_FLOWTROUGH);
3268         mapset("<>;&|(){}#", MAP_FLOWTROUGH_IF_QUOTED);
3269         mapset(ifs, MAP_IFS_IF_UNQUOTED);  /* also flow through if quoted */
3270 }
3271
3272 /* most recursion does not come through here, the exception is
3273  * from builtin_source() */
3274 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3275 {
3276 // FIXME: '{ true | exit 3; echo $? }' is parsed as a whole,
3277 // as a result $? is replaced by 0, not 3!
3278
3279         struct p_context ctx;
3280         o_string temp = NULL_O_STRING;
3281         int rcode;
3282         do {
3283                 ctx.parse_type = parse_flag;
3284                 initialize_context(&ctx);
3285                 update_ifs_map();
3286                 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3287                         mapset(";$&|", MAP_ORDINARY);
3288 #if ENABLE_HUSH_INTERACTIVE
3289                 inp->promptmode = 1;
3290 #endif
3291                 /* We will stop & execute after each ';' or '\n'.
3292                  * Example: "sleep 9999; echo TEST" + ctrl-C:
3293                  * TEST should be printed */
3294                 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3295                 if (rcode != 1 && ctx.old_flag != 0) {
3296                         syntax();
3297                 }
3298                 if (rcode != 1 && ctx.old_flag == 0) {
3299                         done_word(&temp, &ctx);
3300                         done_pipe(&ctx, PIPE_SEQ);
3301                         debug_print_tree(ctx.list_head, 0);
3302                         debug_printf_exec("parse_stream_outer: run_list\n");
3303                         run_list(ctx.list_head);
3304                 } else {
3305                         if (ctx.old_flag != 0) {
3306                                 free(ctx.stack);
3307                                 b_reset(&temp);
3308                         }
3309                         temp.nonnull = 0;
3310                         temp.quote = 0;
3311                         inp->p = NULL;
3312                         free_pipe_list(ctx.list_head, 0);
3313                 }
3314                 b_free(&temp);
3315         } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP));   /* loop on syntax errors, return on EOF */
3316         return 0;
3317 }
3318
3319 static int parse_string_outer(const char *s, int parse_flag)
3320 {
3321         struct in_str input;
3322         setup_string_in_str(&input, s);
3323         return parse_stream_outer(&input, parse_flag);
3324 }
3325
3326 static int parse_file_outer(FILE *f)
3327 {
3328         int rcode;
3329         struct in_str input;
3330         setup_file_in_str(&input, f);
3331         rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3332         return rcode;
3333 }
3334
3335 #if ENABLE_HUSH_JOB
3336 /* Make sure we have a controlling tty.  If we get started under a job
3337  * aware app (like bash for example), make sure we are now in charge so
3338  * we don't fight over who gets the foreground */
3339 static void setup_job_control(void)
3340 {
3341         pid_t shell_pgrp;
3342
3343         saved_task_pgrp = shell_pgrp = getpgrp();
3344         debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3345         fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3346
3347         /* If we were ran as 'hush &',
3348          * sleep until we are in the foreground.  */
3349         while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3350                 /* Send TTIN to ourself (should stop us) */
3351                 kill(- shell_pgrp, SIGTTIN);
3352                 shell_pgrp = getpgrp();
3353         }
3354
3355         /* Ignore job-control and misc signals.  */
3356         set_jobctrl_sighandler(SIG_IGN);
3357         set_misc_sighandler(SIG_IGN);
3358 //huh?  signal(SIGCHLD, SIG_IGN);
3359
3360         /* We _must_ restore tty pgrp on fatal signals */
3361         set_fatal_sighandler(sigexit);
3362
3363         /* Put ourselves in our own process group.  */
3364         setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3365         /* Grab control of the terminal.  */
3366         tcsetpgrp(interactive_fd, getpid());
3367 }
3368 #endif
3369
3370 int hush_main(int argc, char **argv);
3371 int hush_main(int argc, char **argv)
3372 {
3373         int opt;
3374         FILE *input;
3375         char **e;
3376
3377 #if ENABLE_FEATURE_EDITING
3378         line_input_state = new_line_input_t(FOR_SHELL);
3379 #endif
3380
3381         /* XXX what should these be while sourcing /etc/profile? */
3382         global_argc = argc;
3383         global_argv = argv;
3384
3385         /* (re?) initialize globals.  Sometimes hush_main() ends up calling
3386          * hush_main(), therefore we cannot rely on the BSS to zero out this
3387          * stuff.  Reset these to 0 every time. */
3388         ifs = NULL;
3389         /* map[] is taken care of with call to update_ifs_map() */
3390         fake_mode = 0;
3391         close_me_head = NULL;
3392 #if ENABLE_HUSH_INTERACTIVE
3393         interactive_fd = 0;
3394 #endif
3395 #if ENABLE_HUSH_JOB
3396         last_bg_pid = 0;
3397         job_list = NULL;
3398         last_jobid = 0;
3399 #endif
3400
3401         /* Initialize some more globals to non-zero values */
3402         set_cwd();
3403 #if ENABLE_HUSH_INTERACTIVE
3404 #if ENABLE_FEATURE_EDITING
3405         cmdedit_set_initial_prompt();
3406 #else
3407         PS1 = NULL;
3408 #endif
3409         PS2 = "> ";
3410 #endif
3411         /* initialize our shell local variables with the values
3412          * currently living in the environment */
3413         e = environ;
3414         if (e)
3415                 while (*e)
3416                         set_local_var(*e++, 2);   /* without call putenv() */
3417
3418         last_return_code = EXIT_SUCCESS;
3419
3420         if (argv[0] && argv[0][0] == '-') {
3421                 debug_printf("sourcing /etc/profile\n");
3422                 input = fopen("/etc/profile", "r");
3423                 if (input != NULL) {
3424                         mark_open(fileno(input));
3425                         parse_file_outer(input);
3426                         mark_closed(fileno(input));
3427                         fclose(input);
3428                 }
3429         }
3430         input = stdin;
3431
3432         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3433                 switch (opt) {
3434                 case 'c':
3435                         global_argv = argv + optind;
3436                         global_argc = argc - optind;
3437                         opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3438                         goto final_return;
3439                 case 'i':
3440                         // Well, we cannot just declare interactiveness,
3441                         // we have to have some stuff (ctty, etc)
3442                         /*interactive_fd++;*/
3443                         break;
3444                 case 'f':
3445                         fake_mode++;
3446                         break;
3447                 default:
3448 #ifndef BB_VER
3449                         fprintf(stderr, "Usage: sh [FILE]...\n"
3450                                         "   or: sh -c command [args]...\n\n");
3451                         exit(EXIT_FAILURE);
3452 #else
3453                         bb_show_usage();
3454 #endif
3455                 }
3456         }
3457 #if ENABLE_HUSH_JOB
3458         /* A shell is interactive if the '-i' flag was given, or if all of
3459          * the following conditions are met:
3460          *    no -c command
3461          *    no arguments remaining or the -s flag given
3462          *    standard input is a terminal
3463          *    standard output is a terminal
3464          *    Refer to Posix.2, the description of the 'sh' utility. */
3465         if (argv[optind] == NULL && input == stdin
3466          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3467         ) {
3468                 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3469                 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3470                 if (saved_tty_pgrp >= 0) {
3471                         /* try to dup to high fd#, >= 255 */
3472                         interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3473                         if (interactive_fd < 0) {
3474                                 /* try to dup to any fd */
3475                                 interactive_fd = dup(STDIN_FILENO);
3476                                 if (interactive_fd < 0)
3477                                         /* give up */
3478                                         interactive_fd = 0;
3479                         }
3480                         // TODO: track & disallow any attempts of user
3481                         // to (inadvertently) close/redirect it
3482                 }
3483         }
3484         debug_printf("interactive_fd=%d\n", interactive_fd);
3485         if (interactive_fd) {
3486                 /* Looks like they want an interactive shell */
3487                 setup_job_control();
3488                 /* Make xfuncs do cleanup on exit */
3489                 die_sleep = -1; /* flag */
3490 // FIXME: should we reset die_sleep = 0 whereever we fork?
3491                 if (setjmp(die_jmp)) {
3492                         /* xfunc has failed! die die die */
3493                         hush_exit(xfunc_error_retval);
3494                 }
3495 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3496                 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3497                 printf("Enter 'help' for a list of built-in commands.\n\n");
3498 #endif
3499         }
3500 #elif ENABLE_HUSH_INTERACTIVE
3501 /* no job control compiled, only prompt/line editing */
3502         if (argv[optind] == NULL && input == stdin
3503          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3504         ) {
3505                 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3506                 if (interactive_fd < 0) {
3507                         /* try to dup to any fd */
3508                         interactive_fd = dup(STDIN_FILENO);
3509                         if (interactive_fd < 0)
3510                                 /* give up */
3511                                 interactive_fd = 0;
3512                 }
3513         }
3514
3515 #endif
3516
3517         if (argv[optind] == NULL) {
3518                 opt = parse_file_outer(stdin);
3519                 goto final_return;
3520         }
3521
3522         debug_printf("\nrunning script '%s'\n", argv[optind]);
3523         global_argv = argv + optind;
3524         global_argc = argc - optind;
3525         input = xfopen(argv[optind], "r");
3526         opt = parse_file_outer(input);
3527
3528 #if ENABLE_FEATURE_CLEAN_UP
3529         fclose(input);
3530         if (cwd != bb_msg_unknown)
3531                 free((char*)cwd);
3532         {
3533                 struct variables *cur, *tmp;
3534                 for (cur = top_vars; cur; cur = tmp) {
3535                         tmp = cur->next;
3536                         if (!cur->flg_read_only) {
3537                                 free((char*)cur->name);
3538                                 free((char*)cur->value);
3539                                 free(cur);
3540                         }
3541                 }
3542         }
3543 #endif
3544
3545  final_return:
3546         hush_exit(opt ? opt : last_return_code);
3547 }