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