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