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