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