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