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