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