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