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