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