ash: add missing comma in debug scaffolding
[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  *      o_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  *      &> and >& redirection of stdout+stderr
42  *      Brace Expansion
43  *      Tilde Expansion
44  *      fancy forms of Parameter Expansion
45  *      aliases
46  *      Arithmetic Expansion
47  *      <(list) and >(list) Process Substitution
48  *      reserved words: select, function
49  *      Here Documents ( << word )
50  *      Functions
51  * Major bugs:
52  *      job handling woefully incomplete and buggy (improved --vda)
53  * to-do:
54  *      port selected bugfixes from post-0.49 busybox lash - done?
55  *      change { and } from special chars to reserved words
56  *      builtins: return, trap, ulimit
57  *      test magic exec with redirection only
58  *      check setting of global_argc and global_argv
59  *      follow IFS rules more precisely, including update semantics
60  *      figure out what to do with backslash-newline
61  *      propagate syntax errors, die on resource errors?
62  *      continuation lines, both explicit and implicit - done?
63  *      memory leak finding and plugging - done?
64  *      maybe change charmap[] to use 2-bit entries
65  *
66  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
67  */
68
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
72 #include <glob.h>
73 /* #include <dmalloc.h> */
74 #if ENABLE_HUSH_CASE
75 #include <fnmatch.h>
76 #endif
77
78 #define HUSH_VER_STR "0.91"
79
80 #if defined SINGLE_APPLET_MAIN
81 /* STANDALONE does not make sense, and won't compile */
82 #undef CONFIG_FEATURE_SH_STANDALONE
83 #undef ENABLE_FEATURE_SH_STANDALONE
84 #undef USE_FEATURE_SH_STANDALONE
85 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
86 #define ENABLE_FEATURE_SH_STANDALONE 0
87 #define USE_FEATURE_SH_STANDALONE(...)
88 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
89 #endif
90
91 #if !BB_MMU && ENABLE_HUSH_TICK
92 //#undef ENABLE_HUSH_TICK
93 //#define ENABLE_HUSH_TICK 0
94 #warning On NOMMU, hush command substitution is dangerous.
95 #warning Dont use it for commands which produce lots of output.
96 #warning For more info see shell/hush.c, generate_stream_from_list().
97 #endif
98
99 #if !BB_MMU && ENABLE_HUSH_JOB
100 #undef ENABLE_HUSH_JOB
101 #define ENABLE_HUSH_JOB 0
102 #endif
103
104 #if !ENABLE_HUSH_INTERACTIVE
105 #undef ENABLE_FEATURE_EDITING
106 #define ENABLE_FEATURE_EDITING 0
107 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
108 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
109 #endif
110
111
112 /* Keep unconditionally on for now */
113 #define HUSH_DEBUG 1
114 /* In progress... */
115 #define ENABLE_HUSH_FUNCTIONS 0
116
117
118 /* If you comment out one of these below, it will be #defined later
119  * to perform debug printfs to stderr: */
120 #define debug_printf(...)        do {} while (0)
121 /* Finer-grained debug switches */
122 #define debug_printf_parse(...)  do {} while (0)
123 #define debug_print_tree(a, b)   do {} while (0)
124 #define debug_printf_exec(...)   do {} while (0)
125 #define debug_printf_env(...)    do {} while (0)
126 #define debug_printf_jobs(...)   do {} while (0)
127 #define debug_printf_expand(...) do {} while (0)
128 #define debug_printf_glob(...)   do {} while (0)
129 #define debug_printf_list(...)   do {} while (0)
130 #define debug_printf_subst(...)  do {} while (0)
131 #define debug_printf_clean(...)  do {} while (0)
132
133 #ifndef debug_printf
134 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
135 #endif
136
137 #ifndef debug_printf_parse
138 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
139 #endif
140
141 #ifndef debug_printf_exec
142 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
143 #endif
144
145 #ifndef debug_printf_env
146 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
147 #endif
148
149 #ifndef debug_printf_jobs
150 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
151 #define DEBUG_JOBS 1
152 #else
153 #define DEBUG_JOBS 0
154 #endif
155
156 #ifndef debug_printf_expand
157 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
158 #define DEBUG_EXPAND 1
159 #else
160 #define DEBUG_EXPAND 0
161 #endif
162
163 #ifndef debug_printf_glob
164 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
165 #define DEBUG_GLOB 1
166 #else
167 #define DEBUG_GLOB 0
168 #endif
169
170 #ifndef debug_printf_list
171 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
172 #endif
173
174 #ifndef debug_printf_subst
175 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
176 #endif
177
178 #ifndef debug_printf_clean
179 /* broken, of course, but OK for testing */
180 static const char *indenter(int i)
181 {
182         static const char blanks[] ALIGN1 =
183                 "                                    ";
184         return &blanks[sizeof(blanks) - i - 1];
185 }
186 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
187 #define DEBUG_CLEAN 1
188 #endif
189
190 #if DEBUG_EXPAND
191 static void debug_print_strings(const char *prefix, char **vv)
192 {
193         fprintf(stderr, "%s:\n", prefix);
194         while (*vv)
195                 fprintf(stderr, " '%s'\n", *vv++);
196 }
197 #else
198 #define debug_print_strings(prefix, vv) ((void)0)
199 #endif
200
201 /*
202  * Leak hunting. Use hush_leaktool.sh for post-processing.
203  */
204 #ifdef FOR_HUSH_LEAKTOOL
205 /* suppress "warning: no previous prototype..." */
206 void *xxmalloc(int lineno, size_t size);
207 void *xxrealloc(int lineno, void *ptr, size_t size);
208 char *xxstrdup(int lineno, const char *str);
209 void xxfree(void *ptr);
210 void *xxmalloc(int lineno, size_t size)
211 {
212         void *ptr = xmalloc((size + 0xff) & ~0xff);
213         fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
214         return ptr;
215 }
216 void *xxrealloc(int lineno, void *ptr, size_t size)
217 {
218         ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
219         fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
220         return ptr;
221 }
222 char *xxstrdup(int lineno, const char *str)
223 {
224         char *ptr = xstrdup(str);
225         fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
226         return ptr;
227 }
228 void xxfree(void *ptr)
229 {
230         fprintf(stderr, "free %p\n", ptr);
231         free(ptr);
232 }
233 #define xmalloc(s)     xxmalloc(__LINE__, s)
234 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
235 #define xstrdup(s)     xxstrdup(__LINE__, s)
236 #define free(p)        xxfree(p)
237 #endif
238
239
240 /* Do we support ANY keywords? */
241 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
242 #define HAS_KEYWORDS 1
243 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
244 #define IF_HAS_NO_KEYWORDS(...)
245 #else
246 #define HAS_KEYWORDS 0
247 #define IF_HAS_KEYWORDS(...)
248 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
249 #endif
250
251
252 #define SPECIAL_VAR_SYMBOL       3
253 #define PARSEFLAG_EXIT_FROM_LOOP 1
254
255 typedef enum redir_type {
256         REDIRECT_INPUT     = 1,
257         REDIRECT_OVERWRITE = 2,
258         REDIRECT_APPEND    = 3,
259         REDIRECT_HEREIS    = 4,
260         REDIRECT_IO        = 5
261 } redir_type;
262
263 /* The descrip member of this structure is only used to make
264  * debugging output pretty */
265 static const struct {
266         int mode;
267         signed char default_fd;
268         char descrip[3];
269 } redir_table[] = {
270         { 0,                         0, "()" },
271         { O_RDONLY,                  0, "<"  },
272         { O_CREAT|O_TRUNC|O_WRONLY,  1, ">"  },
273         { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
274         { O_RDONLY,                 -1, "<<" },
275         { O_RDWR,                    1, "<>" }
276 };
277
278 typedef enum pipe_style {
279         PIPE_SEQ = 1,
280         PIPE_AND = 2,
281         PIPE_OR  = 3,
282         PIPE_BG  = 4,
283 } pipe_style;
284
285 typedef enum reserved_style {
286         RES_NONE  = 0,
287 #if ENABLE_HUSH_IF
288         RES_IF    ,
289         RES_THEN  ,
290         RES_ELIF  ,
291         RES_ELSE  ,
292         RES_FI    ,
293 #endif
294 #if ENABLE_HUSH_LOOPS
295         RES_FOR   ,
296         RES_WHILE ,
297         RES_UNTIL ,
298         RES_DO    ,
299         RES_DONE  ,
300 #endif
301 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
302         RES_IN    ,
303 #endif
304 #if ENABLE_HUSH_CASE
305         RES_CASE  ,
306         /* two pseudo-keywords support contrived "case" syntax: */
307         RES_MATCH , /* "word)" */
308         RES_CASEI , /* "this command is inside CASE" */
309         RES_ESAC  ,
310 #endif
311         RES_XXXX  ,
312         RES_SNTX
313 } reserved_style;
314
315 struct redir_struct {
316         struct redir_struct *next;
317         char *rd_filename;          /* filename */
318         int fd;                     /* file descriptor being redirected */
319         int dup;                    /* -1, or file descriptor being duplicated */
320         smallint /*enum redir_type*/ rd_type;
321 };
322
323 struct command {
324         pid_t pid;                  /* 0 if exited */
325         int assignment_cnt;         /* how many argv[i] are assignments? */
326         smallint is_stopped;        /* is the command currently running? */
327         smallint grp_type;
328         struct pipe *group;         /* if non-NULL, this "prog" is {} group,
329                                      * subshell, or a compound statement */
330         char **argv;                /* command name and arguments */
331         struct redir_struct *redirects; /* I/O redirections */
332 };
333 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
334  * and on execution these are substituted with their values.
335  * Substitution can make _several_ words out of one argv[n]!
336  * Example: argv[0]=='.^C*^C.' here: echo .$*.
337  * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
338  */
339 #define GRP_NORMAL   0
340 #define GRP_SUBSHELL 1
341 #if ENABLE_HUSH_FUNCTIONS
342 #define GRP_FUNCTION 2
343 #endif
344
345 struct pipe {
346         struct pipe *next;
347         int num_cmds;               /* total number of commands in job */
348         int alive_cmds;             /* number of commands running (not exited) */
349         int stopped_cmds;           /* number of commands alive, but stopped */
350 #if ENABLE_HUSH_JOB
351         int jobid;                  /* job number */
352         pid_t pgrp;                 /* process group ID for the job */
353         char *cmdtext;              /* name of job */
354 #endif
355         struct command *cmds;       /* array of commands in pipe */
356         smallint followup;          /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
357         IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
358         IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
359 };
360
361 /* This holds pointers to the various results of parsing */
362 struct parse_context {
363         struct command *command;
364         struct pipe *list_head;
365         struct pipe *pipe;
366         struct redir_struct *pending_redirect;
367 #if HAS_KEYWORDS
368         smallint ctx_res_w;
369         smallint ctx_inverted; /* "! cmd | cmd" */
370 #if ENABLE_HUSH_CASE
371         smallint ctx_dsemicolon; /* ";;" seen */
372 #endif
373         int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
374         struct parse_context *stack;
375 #endif
376 };
377
378 /* On program start, environ points to initial environment.
379  * putenv adds new pointers into it, unsetenv removes them.
380  * Neither of these (de)allocates the strings.
381  * setenv allocates new strings in malloc space and does putenv,
382  * and thus setenv is unusable (leaky) for shell's purposes */
383 #define setenv(...) setenv_is_leaky_dont_use()
384 struct variable {
385         struct variable *next;
386         char *varstr;        /* points to "name=" portion */
387         int max_len;         /* if > 0, name is part of initial env; else name is malloced */
388         smallint flg_export; /* putenv should be done on this var */
389         smallint flg_read_only;
390 };
391
392 typedef struct o_string {
393         char *data;
394         int length; /* position where data is appended */
395         int maxlen;
396         /* Misnomer! it's not "quoting", it's "protection against globbing"!
397          * (by prepending \ to *, ?, [ and to \ too) */
398         smallint o_quote;
399         smallint o_glob;
400         smallint nonnull;
401         smallint has_empty_slot;
402         smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
403 } o_string;
404 enum {
405         MAYBE_ASSIGNMENT = 0,
406         DEFINITELY_ASSIGNMENT = 1,
407         NOT_ASSIGNMENT = 2,
408         WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
409 };
410 /* Used for initialization: o_string foo = NULL_O_STRING; */
411 #define NULL_O_STRING { NULL }
412
413 /* I can almost use ordinary FILE*.  Is open_memstream() universally
414  * available?  Where is it documented? */
415 typedef struct in_str {
416         const char *p;
417         /* eof_flag=1: last char in ->p is really an EOF */
418         char eof_flag; /* meaningless if ->p == NULL */
419         char peek_buf[2];
420 #if ENABLE_HUSH_INTERACTIVE
421         smallint promptme;
422         smallint promptmode; /* 0: PS1, 1: PS2 */
423 #endif
424         FILE *file;
425         int (*get) (struct in_str *);
426         int (*peek) (struct in_str *);
427 } in_str;
428 #define i_getch(input) ((input)->get(input))
429 #define i_peek(input) ((input)->peek(input))
430
431 enum {
432         CHAR_ORDINARY           = 0,
433         CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
434         CHAR_IFS                = 2, /* treated as ordinary if quoted */
435         CHAR_SPECIAL            = 3, /* example: $ */
436 };
437
438 enum {
439         BC_BREAK = 1,
440         BC_CONTINUE = 2,
441 };
442
443
444 /* "Globals" within this file */
445
446 /* Sorted roughly by size (smaller offsets == smaller code) */
447 struct globals {
448 #if ENABLE_HUSH_INTERACTIVE
449         /* 'interactive_fd' is a fd# open to ctty, if we have one
450          * _AND_ if we decided to act interactively */
451         int interactive_fd;
452         const char *PS1;
453         const char *PS2;
454 #endif
455 #if ENABLE_FEATURE_EDITING
456         line_input_t *line_input_state;
457 #endif
458         pid_t root_pid;
459         pid_t last_bg_pid;
460 #if ENABLE_HUSH_JOB
461         int run_list_level;
462         pid_t saved_tty_pgrp;
463         int last_jobid;
464         struct pipe *job_list;
465         struct pipe *toplevel_list;
466         smallint ctrl_z_flag;
467 #endif
468 #if ENABLE_HUSH_LOOPS
469         smallint flag_break_continue;
470 #endif
471         smallint fake_mode;
472         /* these three support $?, $#, and $1 */
473         smalluint last_return_code;
474         char **global_argv;
475         int global_argc;
476 #if ENABLE_HUSH_LOOPS
477         unsigned depth_break_continue;
478         unsigned depth_of_loop;
479 #endif
480         const char *ifs;
481         const char *cwd;
482         struct variable *top_var; /* = &G.shell_ver (set in main()) */
483         struct variable shell_ver;
484 #if ENABLE_FEATURE_SH_STANDALONE
485         struct nofork_save_area nofork_save;
486 #endif
487 #if ENABLE_HUSH_JOB
488         sigjmp_buf toplevel_jb;
489 #endif
490         unsigned char charmap[256];
491         char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
492 };
493
494 #define G (*ptr_to_globals)
495 /* Not #defining name to G.name - this quickly gets unwieldy
496  * (too many defines). Also, I actually prefer to see when a variable
497  * is global, thus "G." prefix is a useful hint */
498 #define INIT_G() do { \
499         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
500 } while (0)
501
502
503 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
504
505 #if 1
506 /* Normal */
507 static void syntax(const char *msg)
508 {
509 #if ENABLE_HUSH_INTERACTIVE
510         /* Was using fancy stuff:
511          * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
512          * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
513         void FAST_FUNC (*fp)(const char *s, ...);
514         fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
515         fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
516 #else
517         bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
518 #endif
519 }
520
521 #else
522 /* Debug */
523 static void syntax_lineno(int line)
524 {
525 #if ENABLE_HUSH_INTERACTIVE
526         void FAST_FUNC (*fp)(const char *s, ...);
527         fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
528         fp("syntax error hush.c:%d", line);
529 #else
530         bb_error_msg_and_die("syntax error hush.c:%d", line);
531 #endif
532 }
533 #define syntax(str) syntax_lineno(__LINE__)
534 #endif
535
536 /* Index of subroutines: */
537 /*  in_str manipulations: */
538 static int static_get(struct in_str *i);
539 static int static_peek(struct in_str *i);
540 static int file_get(struct in_str *i);
541 static int file_peek(struct in_str *i);
542 static void setup_file_in_str(struct in_str *i, FILE *f);
543 static void setup_string_in_str(struct in_str *i, const char *s);
544 /*  "run" the final data structures: */
545 #if !defined(DEBUG_CLEAN)
546 #define free_pipe_list(head, indent) free_pipe_list(head)
547 #define free_pipe(pi, indent)        free_pipe(pi)
548 #endif
549 static int free_pipe_list(struct pipe *head, int indent);
550 static int free_pipe(struct pipe *pi, int indent);
551 /*  really run the final data structures: */
552 typedef struct nommu_save_t {
553         char **new_env;
554         char **old_env;
555         char **argv;
556 } nommu_save_t;
557 #if BB_MMU
558 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
559         pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
560 #define pseudo_exec(nommu_save, command, argv_expanded) \
561         pseudo_exec(command, argv_expanded)
562 #endif
563 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
564 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
565 static int setup_redirects(struct command *prog, int squirrel[]);
566 static int run_list(struct pipe *pi);
567 static int run_pipe(struct pipe *pi);
568 /*   data structure manipulation: */
569 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
570 static void initialize_context(struct parse_context *ctx);
571 static int done_word(o_string *dest, struct parse_context *ctx);
572 static int done_command(struct parse_context *ctx);
573 static void done_pipe(struct parse_context *ctx, pipe_style type);
574 /*   primary string parsing: */
575 static int redirect_dup_num(struct in_str *input);
576 static int redirect_opt_num(o_string *o);
577 #if ENABLE_HUSH_TICK
578 static int process_command_subs(o_string *dest,
579                 struct in_str *input, const char *subst_end);
580 #endif
581 static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
582 static const char *lookup_param(const char *src);
583 static int handle_dollar(o_string *dest,
584                 struct in_str *input);
585 static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger);
586 /*   setup: */
587 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
588 static int parse_and_run_string(const char *s, int parse_flag);
589 static int parse_and_run_file(FILE *f);
590 /*   job management: */
591 static int checkjobs(struct pipe* fg_pipe);
592 #if ENABLE_HUSH_JOB
593 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
594 static void insert_bg_job(struct pipe *pi);
595 static void remove_bg_job(struct pipe *pi);
596 static void delete_finished_bg_job(struct pipe *pi);
597 #else
598 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
599 #endif
600 /*     local variable support */
601 static char **expand_strvec_to_strvec(char **argv);
602 /* used for eval */
603 static char *expand_strvec_to_string(char **argv);
604 /* used for expansion of right hand of assignments */
605 static char *expand_string_to_string(const char *str);
606 static struct variable *get_local_var(const char *name);
607 static int set_local_var(char *str, int flg_export);
608 static void unset_local_var(const char *name);
609
610
611 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
612
613
614 static int glob_needed(const char *s)
615 {
616         while (*s) {
617                 if (*s == '\\')
618                         s++;
619                 if (*s == '*' || *s == '[' || *s == '?')
620                         return 1;
621                 s++;
622         }
623         return 0;
624 }
625
626 static int is_assignment(const char *s)
627 {
628         if (!s || !(isalpha(*s) || *s == '_'))
629                 return 0;
630         s++;
631         while (isalnum(*s) || *s == '_')
632                 s++;
633         return *s == '=';
634 }
635
636 /* Replace each \x with x in place, return ptr past NUL. */
637 static char *unbackslash(char *src)
638 {
639         char *dst = src;
640         while (1) {
641                 if (*src == '\\')
642                         src++;
643                 if ((*dst++ = *src++) == '\0')
644                         break;
645         }
646         return dst;
647 }
648
649 static char **add_strings_to_strings(char **strings, char **add)
650 {
651         int i;
652         unsigned count1;
653         unsigned count2;
654         char **v;
655
656         v = strings;
657         count1 = 0;
658         if (v) {
659                 while (*v) {
660                         count1++;
661                         v++;
662                 }
663         }
664         count2 = 0;
665         v = add;
666         while (*v) {
667                 count2++;
668                 v++;
669         }
670         v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671         v[count1 + count2] = NULL;
672         i = count2;
673         while (--i >= 0)
674                 v[count1 + i] = add[i];
675         return v;
676 }
677
678 static char **add_string_to_strings(char **strings, char *add)
679 {
680         char *v[2];
681         v[0] = add;
682         v[1] = NULL;
683         return add_strings_to_strings(strings, v);
684 }
685
686 static void putenv_all(char **strings)
687 {
688         if (!strings)
689                 return;
690         while (*strings) {
691                 debug_printf_env("putenv '%s'\n", *strings);
692                 putenv(*strings++);
693         }
694 }
695
696 static char **putenv_all_and_save_old(char **strings)
697 {
698         char **old = NULL;
699         char **s = strings;
700
701         if (!strings)
702                 return old;
703         while (*strings) {
704                 char *v, *eq;
705
706                 eq = strchr(*strings, '=');
707                 if (eq) {
708                         *eq = '\0';
709                         v = getenv(*strings);
710                         *eq = '=';
711                         if (v) {
712                                 /* v points to VAL in VAR=VAL, go back to VAR */
713                                 v -= (eq - *strings) + 1;
714                                 old = add_string_to_strings(old, v);
715                         }
716                 }
717                 strings++;
718         }
719         putenv_all(s);
720         return old;
721 }
722
723 static void free_strings_and_unsetenv(char **strings, int unset)
724 {
725         char **v;
726
727         if (!strings)
728                 return;
729
730         v = strings;
731         while (*v) {
732                 if (unset) {
733                         debug_printf_env("unsetenv '%s'\n", *v);
734                         bb_unsetenv(*v);
735                 }
736                 free(*v++);
737         }
738         free(strings);
739 }
740
741 static void free_strings(char **strings)
742 {
743         free_strings_and_unsetenv(strings, 0);
744 }
745
746
747 /* Function prototypes for builtins */
748 static int builtin_cd(char **argv);
749 static int builtin_echo(char **argv);
750 static int builtin_eval(char **argv);
751 static int builtin_exec(char **argv);
752 static int builtin_exit(char **argv);
753 static int builtin_export(char **argv);
754 #if ENABLE_HUSH_JOB
755 static int builtin_fg_bg(char **argv);
756 static int builtin_jobs(char **argv);
757 #endif
758 #if ENABLE_HUSH_HELP
759 static int builtin_help(char **argv);
760 #endif
761 static int builtin_pwd(char **argv);
762 static int builtin_read(char **argv);
763 static int builtin_test(char **argv);
764 static int builtin_true(char **argv);
765 static int builtin_set(char **argv);
766 static int builtin_shift(char **argv);
767 static int builtin_source(char **argv);
768 static int builtin_umask(char **argv);
769 static int builtin_unset(char **argv);
770 #if ENABLE_HUSH_LOOPS
771 static int builtin_break(char **argv);
772 static int builtin_continue(char **argv);
773 #endif
774 //static int builtin_not_written(char **argv);
775
776 /* Table of built-in functions.  They can be forked or not, depending on
777  * context: within pipes, they fork.  As simple commands, they do not.
778  * When used in non-forking context, they can change global variables
779  * in the parent shell process.  If forked, of course they cannot.
780  * For example, 'unset foo | whatever' will parse and run, but foo will
781  * still be set at the end. */
782 struct built_in_command {
783         const char *cmd;
784         int (*function)(char **argv);
785 #if ENABLE_HUSH_HELP
786         const char *descr;
787 #define BLTIN(cmd, func, help) { cmd, func, help }
788 #else
789 #define BLTIN(cmd, func, help) { cmd, func }
790 #endif
791 };
792
793 /* For now, echo and test are unconditionally enabled.
794  * Maybe make it configurable? */
795 static const struct built_in_command bltins[] = {
796         BLTIN("."     , builtin_source, "Run commands in a file"),
797         BLTIN(":"     , builtin_true, "No-op"),
798         BLTIN("["     , builtin_test, "Test condition"),
799         BLTIN("[["    , builtin_test, "Test condition"),
800 #if ENABLE_HUSH_JOB
801         BLTIN("bg"    , builtin_fg_bg, "Resume a job in the background"),
802 #endif
803 #if ENABLE_HUSH_LOOPS
804         BLTIN("break" , builtin_break, "Exit from a loop"),
805 #endif
806         BLTIN("cd"    , builtin_cd, "Change directory"),
807 #if ENABLE_HUSH_LOOPS
808         BLTIN("continue", builtin_continue, "Start new loop iteration"),
809 #endif
810         BLTIN("echo"  , builtin_echo, "Write to stdout"),
811         BLTIN("eval"  , builtin_eval, "Construct and run shell command"),
812         BLTIN("exec"  , builtin_exec, "Execute command, don't return to shell"),
813         BLTIN("exit"  , builtin_exit, "Exit"),
814         BLTIN("export", builtin_export, "Set environment variable"),
815 #if ENABLE_HUSH_JOB
816         BLTIN("fg"    , builtin_fg_bg, "Bring job into the foreground"),
817         BLTIN("jobs"  , builtin_jobs, "List active jobs"),
818 #endif
819         BLTIN("pwd"   , builtin_pwd, "Print current directory"),
820         BLTIN("read"  , builtin_read, "Input environment variable"),
821 //      BLTIN("return", builtin_not_written, "Return from a function"),
822         BLTIN("set"   , builtin_set, "Set/unset shell local variables"),
823         BLTIN("shift" , builtin_shift, "Shift positional parameters"),
824 //      BLTIN("trap"  , builtin_not_written, "Trap signals"),
825         BLTIN("test"  , builtin_test, "Test condition"),
826 //      BLTIN("ulimit", builtin_not_written, "Control resource limits"),
827         BLTIN("umask" , builtin_umask, "Set file creation mask"),
828         BLTIN("unset" , builtin_unset, "Unset environment variable"),
829 #if ENABLE_HUSH_HELP
830         BLTIN("help"  , builtin_help, "List shell built-in commands"),
831 #endif
832 };
833
834
835 /* Signals are grouped, we handle them in batches */
836 static void set_misc_sighandler(void (*handler)(int))
837 {
838         bb_signals(0
839                 + (1 << SIGINT)
840                 + (1 << SIGQUIT)
841                 + (1 << SIGTERM)
842                 , handler);
843 }
844
845 #if ENABLE_HUSH_JOB
846
847 static void set_fatal_sighandler(void (*handler)(int))
848 {
849         bb_signals(0
850                 + (1 << SIGILL)
851                 + (1 << SIGTRAP)
852                 + (1 << SIGABRT)
853                 + (1 << SIGFPE)
854                 + (1 << SIGBUS)
855                 + (1 << SIGSEGV)
856         /* bash 3.2 seems to handle these just like 'fatal' ones */
857                 + (1 << SIGHUP)
858                 + (1 << SIGPIPE)
859                 + (1 << SIGALRM)
860                 , handler);
861 }
862 static void set_jobctrl_sighandler(void (*handler)(int))
863 {
864         bb_signals(0
865                 + (1 << SIGTSTP)
866                 + (1 << SIGTTIN)
867                 + (1 << SIGTTOU)
868                 , handler);
869 }
870 /* SIGCHLD is special and handled separately */
871
872 static void set_every_sighandler(void (*handler)(int))
873 {
874         set_fatal_sighandler(handler);
875         set_jobctrl_sighandler(handler);
876         set_misc_sighandler(handler);
877         signal(SIGCHLD, handler);
878 }
879
880 static void handler_ctrl_c(int sig UNUSED_PARAM)
881 {
882         debug_printf_jobs("got sig %d\n", sig);
883 // as usual we can have all kinds of nasty problems with leaked malloc data here
884         siglongjmp(G.toplevel_jb, 1);
885 }
886
887 static void handler_ctrl_z(int sig UNUSED_PARAM)
888 {
889         pid_t pid;
890
891         debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
892         pid = fork();
893         if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
894                 return;
895         G.ctrl_z_flag = 1;
896         if (!pid) { /* child */
897                 if (ENABLE_HUSH_JOB)
898                         die_sleep = 0; /* let nofork's xfuncs die */
899                 bb_setpgrp();
900                 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
901                 set_every_sighandler(SIG_DFL);
902                 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
903                 debug_printf_jobs("returning in child\n");
904                 /* return to nofork, it will eventually exit now,
905                  * not return back to shell */
906                 return;
907         }
908         /* parent */
909         /* finish filling up pipe info */
910         G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
911         G.toplevel_list->cmds[0].pid = pid;
912         /* parent needs to longjmp out of running nofork.
913          * we will "return" exitcode 0, with child put in background */
914 // as usual we can have all kinds of nasty problems with leaked malloc data here
915         debug_printf_jobs("siglongjmp in parent\n");
916         siglongjmp(G.toplevel_jb, 1);
917 }
918
919 /* Restores tty foreground process group, and exits.
920  * May be called as signal handler for fatal signal
921  * (will faithfully resend signal to itself, producing correct exit state)
922  * or called directly with -EXITCODE.
923  * We also call it if xfunc is exiting. */
924 static void sigexit(int sig) NORETURN;
925 static void sigexit(int sig)
926 {
927         /* Disable all signals: job control, SIGPIPE, etc. */
928         sigprocmask_allsigs(SIG_BLOCK);
929
930 #if ENABLE_HUSH_INTERACTIVE
931         if (G.interactive_fd)
932                 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
933 #endif
934
935         /* Not a signal, just exit */
936         if (sig <= 0)
937                 _exit(- sig);
938
939         kill_myself_with_sig(sig); /* does not return */
940 }
941
942 /* Restores tty foreground process group, and exits. */
943 static void hush_exit(int exitcode) NORETURN;
944 static void hush_exit(int exitcode)
945 {
946         fflush(NULL); /* flush all streams */
947         sigexit(- (exitcode & 0xff));
948 }
949
950 #else /* !JOB */
951
952 #define set_fatal_sighandler(handler)   ((void)0)
953 #define set_jobctrl_sighandler(handler) ((void)0)
954 #define hush_exit(e)                    exit(e)
955
956 #endif /* JOB */
957
958
959 static const char *set_cwd(void)
960 {
961         if (G.cwd == bb_msg_unknown)
962                 G.cwd = NULL;     /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
963         G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
964         if (!G.cwd)
965                 G.cwd = bb_msg_unknown;
966         return G.cwd;
967 }
968
969
970 /*
971  * o_string support
972  */
973 #define B_CHUNK  (32 * sizeof(char*))
974
975 static void o_reset(o_string *o)
976 {
977         o->length = 0;
978         o->nonnull = 0;
979         if (o->data)
980                 o->data[0] = '\0';
981 }
982
983 static void o_free(o_string *o)
984 {
985         free(o->data);
986         memset(o, 0, sizeof(*o));
987 }
988
989 static void o_grow_by(o_string *o, int len)
990 {
991         if (o->length + len > o->maxlen) {
992                 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
993                 o->data = xrealloc(o->data, 1 + o->maxlen);
994         }
995 }
996
997 static void o_addchr(o_string *o, int ch)
998 {
999         debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1000         o_grow_by(o, 1);
1001         o->data[o->length] = ch;
1002         o->length++;
1003         o->data[o->length] = '\0';
1004 }
1005
1006 static void o_addstr(o_string *o, const char *str, int len)
1007 {
1008         o_grow_by(o, len);
1009         memcpy(&o->data[o->length], str, len);
1010         o->length += len;
1011         o->data[o->length] = '\0';
1012 }
1013
1014 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1015 {
1016         while (len) {
1017                 o_addchr(o, *str);
1018                 if (*str++ == '\\'
1019                  && (*str != '*' && *str != '?' && *str != '[')
1020                 ) {
1021                         o_addchr(o, '\\');
1022                 }
1023                 len--;
1024         }
1025 }
1026
1027 /* My analysis of quoting semantics tells me that state information
1028  * is associated with a destination, not a source.
1029  */
1030 static void o_addqchr(o_string *o, int ch)
1031 {
1032         int sz = 1;
1033         char *found = strchr("*?[\\", ch);
1034         if (found)
1035                 sz++;
1036         o_grow_by(o, sz);
1037         if (found) {
1038                 o->data[o->length] = '\\';
1039                 o->length++;
1040         }
1041         o->data[o->length] = ch;
1042         o->length++;
1043         o->data[o->length] = '\0';
1044 }
1045
1046 static void o_addQchr(o_string *o, int ch)
1047 {
1048         int sz = 1;
1049         if (o->o_quote && strchr("*?[\\", ch)) {
1050                 sz++;
1051                 o->data[o->length] = '\\';
1052                 o->length++;
1053         }
1054         o_grow_by(o, sz);
1055         o->data[o->length] = ch;
1056         o->length++;
1057         o->data[o->length] = '\0';
1058 }
1059
1060 static void o_addQstr(o_string *o, const char *str, int len)
1061 {
1062         if (!o->o_quote) {
1063                 o_addstr(o, str, len);
1064                 return;
1065         }
1066         while (len) {
1067                 char ch;
1068                 int sz;
1069                 int ordinary_cnt = strcspn(str, "*?[\\");
1070                 if (ordinary_cnt > len) /* paranoia */
1071                         ordinary_cnt = len;
1072                 o_addstr(o, str, ordinary_cnt);
1073                 if (ordinary_cnt == len)
1074                         return;
1075                 str += ordinary_cnt;
1076                 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1077
1078                 ch = *str++;
1079                 sz = 1;
1080                 if (ch) { /* it is necessarily one of "*?[\\" */
1081                         sz++;
1082                         o->data[o->length] = '\\';
1083                         o->length++;
1084                 }
1085                 o_grow_by(o, sz);
1086                 o->data[o->length] = ch;
1087                 o->length++;
1088                 o->data[o->length] = '\0';
1089         }
1090 }
1091
1092 /* A special kind of o_string for $VAR and `cmd` expansion.
1093  * It contains char* list[] at the beginning, which is grown in 16 element
1094  * increments. Actual string data starts at the next multiple of 16 * (char*).
1095  * list[i] contains an INDEX (int!) into this string data.
1096  * It means that if list[] needs to grow, data needs to be moved higher up
1097  * but list[i]'s need not be modified.
1098  * NB: remembering how many list[i]'s you have there is crucial.
1099  * o_finalize_list() operation post-processes this structure - calculates
1100  * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1101  */
1102 #if DEBUG_EXPAND || DEBUG_GLOB
1103 static void debug_print_list(const char *prefix, o_string *o, int n)
1104 {
1105         char **list = (char**)o->data;
1106         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1107         int i = 0;
1108         fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1109                         prefix, list, n, string_start, o->length, o->maxlen);
1110         while (i < n) {
1111                 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1112                                 o->data + (int)list[i] + string_start,
1113                                 o->data + (int)list[i] + string_start);
1114                 i++;
1115         }
1116         if (n) {
1117                 const char *p = o->data + (int)list[n - 1] + string_start;
1118                 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1119         }
1120 }
1121 #else
1122 #define debug_print_list(prefix, o, n) ((void)0)
1123 #endif
1124
1125 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1126  * in list[n] so that it points past last stored byte so far.
1127  * It returns n+1. */
1128 static int o_save_ptr_helper(o_string *o, int n)
1129 {
1130         char **list = (char**)o->data;
1131         int string_start;
1132         int string_len;
1133
1134         if (!o->has_empty_slot) {
1135                 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1136                 string_len = o->length - string_start;
1137                 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1138                         debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1139                         /* list[n] points to string_start, make space for 16 more pointers */
1140                         o->maxlen += 0x10 * sizeof(list[0]);
1141                         o->data = xrealloc(o->data, o->maxlen + 1);
1142                         list = (char**)o->data;
1143                         memmove(list + n + 0x10, list + n, string_len);
1144                         o->length += 0x10 * sizeof(list[0]);
1145                 } else
1146                         debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1147         } else {
1148                 /* We have empty slot at list[n], reuse without growth */
1149                 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1150                 string_len = o->length - string_start;
1151                 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1152                 o->has_empty_slot = 0;
1153         }
1154         list[n] = (char*)(ptrdiff_t)string_len;
1155         return n + 1;
1156 }
1157
1158 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1159 static int o_get_last_ptr(o_string *o, int n)
1160 {
1161         char **list = (char**)o->data;
1162         int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1163
1164         return ((int)(ptrdiff_t)list[n-1]) + string_start;
1165 }
1166
1167 /* o_glob performs globbing on last list[], saving each result
1168  * as a new list[]. */
1169 static int o_glob(o_string *o, int n)
1170 {
1171         glob_t globdata;
1172         int gr;
1173         char *pattern;
1174
1175         debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1176         if (!o->data)
1177                 return o_save_ptr_helper(o, n);
1178         pattern = o->data + o_get_last_ptr(o, n);
1179         debug_printf_glob("glob pattern '%s'\n", pattern);
1180         if (!glob_needed(pattern)) {
1181  literal:
1182                 o->length = unbackslash(pattern) - o->data;
1183                 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1184                 return o_save_ptr_helper(o, n);
1185         }
1186
1187         memset(&globdata, 0, sizeof(globdata));
1188         gr = glob(pattern, 0, NULL, &globdata);
1189         debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1190         if (gr == GLOB_NOSPACE)
1191                 bb_error_msg_and_die("out of memory during glob");
1192         if (gr == GLOB_NOMATCH) {
1193                 globfree(&globdata);
1194                 goto literal;
1195         }
1196         if (gr != 0) { /* GLOB_ABORTED ? */
1197 //TODO: testcase for bad glob pattern behavior
1198                 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1199         }
1200         if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1201                 char **argv = globdata.gl_pathv;
1202                 o->length = pattern - o->data; /* "forget" pattern */
1203                 while (1) {
1204                         o_addstr(o, *argv, strlen(*argv) + 1);
1205                         n = o_save_ptr_helper(o, n);
1206                         argv++;
1207                         if (!*argv)
1208                                 break;
1209                 }
1210         }
1211         globfree(&globdata);
1212         if (DEBUG_GLOB)
1213                 debug_print_list("o_glob returning", o, n);
1214         return n;
1215 }
1216
1217 /* If o->o_glob == 1, glob the string so far remembered.
1218  * Otherwise, just finish current list[] and start new */
1219 static int o_save_ptr(o_string *o, int n)
1220 {
1221         if (o->o_glob)
1222                 return o_glob(o, n); /* o_save_ptr_helper is inside */
1223         return o_save_ptr_helper(o, n);
1224 }
1225
1226 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1227 static char **o_finalize_list(o_string *o, int n)
1228 {
1229         char **list;
1230         int string_start;
1231
1232         n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1233         if (DEBUG_EXPAND)
1234                 debug_print_list("finalized", o, n);
1235         debug_printf_expand("finalized n:%d\n", n);
1236         list = (char**)o->data;
1237         string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1238         list[--n] = NULL;
1239         while (n) {
1240                 n--;
1241                 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1242         }
1243         return list;
1244 }
1245
1246
1247 /*
1248  * in_str support
1249  */
1250 static int static_get(struct in_str *i)
1251 {
1252         int ch = *i->p++;
1253         if (ch == '\0') return EOF;
1254         return ch;
1255 }
1256
1257 static int static_peek(struct in_str *i)
1258 {
1259         return *i->p;
1260 }
1261
1262 #if ENABLE_HUSH_INTERACTIVE
1263
1264 #if ENABLE_FEATURE_EDITING
1265 static void cmdedit_set_initial_prompt(void)
1266 {
1267 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1268         G.PS1 = NULL;
1269 #else
1270         G.PS1 = getenv("PS1");
1271         if (G.PS1 == NULL)
1272                 G.PS1 = "\\w \\$ ";
1273 #endif
1274 }
1275 #endif /* EDITING */
1276
1277 static const char* setup_prompt_string(int promptmode)
1278 {
1279         const char *prompt_str;
1280         debug_printf("setup_prompt_string %d ", promptmode);
1281 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1282         /* Set up the prompt */
1283         if (promptmode == 0) { /* PS1 */
1284                 free((char*)G.PS1);
1285                 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1286                 prompt_str = G.PS1;
1287         } else {
1288                 prompt_str = G.PS2;
1289         }
1290 #else
1291         prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1292 #endif
1293         debug_printf("result '%s'\n", prompt_str);
1294         return prompt_str;
1295 }
1296
1297 static void get_user_input(struct in_str *i)
1298 {
1299         int r;
1300         const char *prompt_str;
1301
1302         prompt_str = setup_prompt_string(i->promptmode);
1303 #if ENABLE_FEATURE_EDITING
1304         /* Enable command line editing only while a command line
1305          * is actually being read */
1306         do {
1307                 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1308         } while (r == 0); /* repeat if Ctrl-C */
1309         i->eof_flag = (r < 0);
1310         if (i->eof_flag) { /* EOF/error detected */
1311                 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1312                 G.user_input_buf[1] = '\0';
1313         }
1314 #else
1315         fputs(prompt_str, stdout);
1316         fflush(stdout);
1317         G.user_input_buf[0] = r = fgetc(i->file);
1318         /*G.user_input_buf[1] = '\0'; - already is and never changed */
1319         i->eof_flag = (r == EOF);
1320 #endif
1321         i->p = G.user_input_buf;
1322 }
1323
1324 #endif  /* INTERACTIVE */
1325
1326 /* This is the magic location that prints prompts
1327  * and gets data back from the user */
1328 static int file_get(struct in_str *i)
1329 {
1330         int ch;
1331
1332         /* If there is data waiting, eat it up */
1333         if (i->p && *i->p) {
1334 #if ENABLE_HUSH_INTERACTIVE
1335  take_cached:
1336 #endif
1337                 ch = *i->p++;
1338                 if (i->eof_flag && !*i->p)
1339                         ch = EOF;
1340         } else {
1341                 /* need to double check i->file because we might be doing something
1342                  * more complicated by now, like sourcing or substituting. */
1343 #if ENABLE_HUSH_INTERACTIVE
1344                 if (G.interactive_fd && i->promptme && i->file == stdin) {
1345                         do {
1346                                 get_user_input(i);
1347                         } while (!*i->p); /* need non-empty line */
1348                         i->promptmode = 1; /* PS2 */
1349                         i->promptme = 0;
1350                         goto take_cached;
1351                 }
1352 #endif
1353                 ch = fgetc(i->file);
1354         }
1355         debug_printf("file_get: got a '%c' %d\n", ch, ch);
1356 #if ENABLE_HUSH_INTERACTIVE
1357         if (ch == '\n')
1358                 i->promptme = 1;
1359 #endif
1360         return ch;
1361 }
1362
1363 /* All the callers guarantee this routine will never be
1364  * used right after a newline, so prompting is not needed.
1365  */
1366 static int file_peek(struct in_str *i)
1367 {
1368         int ch;
1369         if (i->p && *i->p) {
1370                 if (i->eof_flag && !i->p[1])
1371                         return EOF;
1372                 return *i->p;
1373         }
1374         ch = fgetc(i->file);
1375         i->eof_flag = (ch == EOF);
1376         i->peek_buf[0] = ch;
1377         i->peek_buf[1] = '\0';
1378         i->p = i->peek_buf;
1379         debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1380         return ch;
1381 }
1382
1383 static void setup_file_in_str(struct in_str *i, FILE *f)
1384 {
1385         i->peek = file_peek;
1386         i->get = file_get;
1387 #if ENABLE_HUSH_INTERACTIVE
1388         i->promptme = 1;
1389         i->promptmode = 0; /* PS1 */
1390 #endif
1391         i->file = f;
1392         i->p = NULL;
1393 }
1394
1395 static void setup_string_in_str(struct in_str *i, const char *s)
1396 {
1397         i->peek = static_peek;
1398         i->get = static_get;
1399 #if ENABLE_HUSH_INTERACTIVE
1400         i->promptme = 1;
1401         i->promptmode = 0; /* PS1 */
1402 #endif
1403         i->p = s;
1404         i->eof_flag = 0;
1405 }
1406
1407
1408 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1409  * and stderr if they are redirected. */
1410 static int setup_redirects(struct command *prog, int squirrel[])
1411 {
1412         int openfd, mode;
1413         struct redir_struct *redir;
1414
1415         for (redir = prog->redirects; redir; redir = redir->next) {
1416                 if (redir->dup == -1 && redir->rd_filename == NULL) {
1417                         /* something went wrong in the parse.  Pretend it didn't happen */
1418                         continue;
1419                 }
1420                 if (redir->dup == -1) {
1421                         char *p;
1422                         mode = redir_table[redir->rd_type].mode;
1423 //TODO: check redir for names like '\\'
1424                         p = expand_string_to_string(redir->rd_filename);
1425                         openfd = open_or_warn(p, mode);
1426                         free(p);
1427                         if (openfd < 0) {
1428                         /* this could get lost if stderr has been redirected, but
1429                            bash and ash both lose it as well (though zsh doesn't!) */
1430                                 return 1;
1431                         }
1432                 } else {
1433                         openfd = redir->dup;
1434                 }
1435
1436                 if (openfd != redir->fd) {
1437                         if (squirrel && redir->fd < 3) {
1438                                 squirrel[redir->fd] = dup(redir->fd);
1439                         }
1440                         if (openfd == -3) {
1441                                 //close(openfd); // close(-3) ??!
1442                         } else {
1443                                 dup2(openfd, redir->fd);
1444                                 if (redir->dup == -1)
1445                                         close(openfd);
1446                         }
1447                 }
1448         }
1449         return 0;
1450 }
1451
1452 static void restore_redirects(int squirrel[])
1453 {
1454         int i, fd;
1455         for (i = 0; i < 3; i++) {
1456                 fd = squirrel[i];
1457                 if (fd != -1) {
1458                         /* We simply die on error */
1459                         xmove_fd(fd, i);
1460                 }
1461         }
1462 }
1463
1464 static char **expand_assignments(char **argv, int count)
1465 {
1466         int i;
1467         char **p = NULL;
1468         /* Expand assignments into one string each */
1469         for (i = 0; i < count; i++) {
1470                 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1471         }
1472         return p;
1473 }
1474
1475 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1476  * Never returns.
1477  * XXX no exit() here.  If you don't exec, use _exit instead.
1478  * The at_exit handlers apparently confuse the calling process,
1479  * in particular stdin handling.  Not sure why? -- because of vfork! (vda) */
1480 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1481 {
1482         int rcode;
1483         char **new_env;
1484         const struct built_in_command *x;
1485
1486         /* If a variable is assigned in a forest, and nobody listens,
1487          * was it ever really set?
1488          */
1489         if (!argv[assignment_cnt])
1490                 _exit(EXIT_SUCCESS);
1491
1492         new_env = expand_assignments(argv, assignment_cnt);
1493 #if BB_MMU
1494         putenv_all(new_env);
1495         free(new_env); /* optional */
1496 #else
1497         nommu_save->new_env = new_env;
1498         nommu_save->old_env = putenv_all_and_save_old(new_env);
1499 #endif
1500         if (argv_expanded) {
1501                 argv = argv_expanded;
1502         } else {
1503                 argv = expand_strvec_to_strvec(argv);
1504 #if !BB_MMU
1505                 nommu_save->argv = argv;
1506 #endif
1507         }
1508
1509         /*
1510          * Check if the command matches any of the builtins.
1511          * Depending on context, this might be redundant.  But it's
1512          * easier to waste a few CPU cycles than it is to figure out
1513          * if this is one of those cases.
1514          */
1515         for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1516                 if (strcmp(argv[0], x->cmd) == 0) {
1517                         debug_printf_exec("running builtin '%s'\n", argv[0]);
1518                         rcode = x->function(argv);
1519                         fflush(stdout);
1520                         _exit(rcode);
1521                 }
1522         }
1523
1524         /* Check if the command matches any busybox applets */
1525 #if ENABLE_FEATURE_SH_STANDALONE
1526         if (strchr(argv[0], '/') == NULL) {
1527                 int a = find_applet_by_name(argv[0]);
1528                 if (a >= 0) {
1529                         if (APPLET_IS_NOEXEC(a)) {
1530                                 debug_printf_exec("running applet '%s'\n", argv[0]);
1531 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1532                                 run_applet_no_and_exit(a, argv);
1533                         }
1534                         /* re-exec ourselves with the new arguments */
1535                         debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1536                         execvp(bb_busybox_exec_path, argv);
1537                         /* If they called chroot or otherwise made the binary no longer
1538                          * executable, fall through */
1539                 }
1540         }
1541 #endif
1542
1543         debug_printf_exec("execing '%s'\n", argv[0]);
1544         execvp(argv[0], argv);
1545         bb_perror_msg("can't exec '%s'", argv[0]);
1546         _exit(EXIT_FAILURE);
1547 }
1548
1549 /* Called after [v]fork() in run_pipe()
1550  */
1551 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
1552 {
1553         if (command->argv)
1554                 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
1555
1556         if (command->group) {
1557 #if !BB_MMU
1558                 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1559 #else
1560                 int rcode;
1561                 debug_printf_exec("pseudo_exec: run_list\n");
1562                 rcode = run_list(command->group);
1563                 /* OK to leak memory by not calling free_pipe_list,
1564                  * since this process is about to exit */
1565                 _exit(rcode);
1566 #endif
1567         }
1568
1569         /* Can happen.  See what bash does with ">foo" by itself. */
1570         debug_printf("trying to pseudo_exec null command\n");
1571         _exit(EXIT_SUCCESS);
1572 }
1573
1574 #if ENABLE_HUSH_JOB
1575 static const char *get_cmdtext(struct pipe *pi)
1576 {
1577         char **argv;
1578         char *p;
1579         int len;
1580
1581         /* This is subtle. ->cmdtext is created only on first backgrounding.
1582          * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1583          * On subsequent bg argv is trashed, but we won't use it */
1584         if (pi->cmdtext)
1585                 return pi->cmdtext;
1586         argv = pi->cmds[0].argv;
1587         if (!argv || !argv[0]) {
1588                 pi->cmdtext = xzalloc(1);
1589                 return pi->cmdtext;
1590         }
1591
1592         len = 0;
1593         do len += strlen(*argv) + 1; while (*++argv);
1594         pi->cmdtext = p = xmalloc(len);
1595         argv = pi->cmds[0].argv;
1596         do {
1597                 len = strlen(*argv);
1598                 memcpy(p, *argv, len);
1599                 p += len;
1600                 *p++ = ' ';
1601         } while (*++argv);
1602         p[-1] = '\0';
1603         return pi->cmdtext;
1604 }
1605
1606 static void insert_bg_job(struct pipe *pi)
1607 {
1608         struct pipe *thejob;
1609         int i;
1610
1611         /* Linear search for the ID of the job to use */
1612         pi->jobid = 1;
1613         for (thejob = G.job_list; thejob; thejob = thejob->next)
1614                 if (thejob->jobid >= pi->jobid)
1615                         pi->jobid = thejob->jobid + 1;
1616
1617         /* Add thejob to the list of running jobs */
1618         if (!G.job_list) {
1619                 thejob = G.job_list = xmalloc(sizeof(*thejob));
1620         } else {
1621                 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
1622                         continue;
1623                 thejob->next = xmalloc(sizeof(*thejob));
1624                 thejob = thejob->next;
1625         }
1626
1627         /* Physically copy the struct job */
1628         memcpy(thejob, pi, sizeof(struct pipe));
1629         thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1630         /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1631         for (i = 0; i < pi->num_cmds; i++) {
1632 // TODO: do we really need to have so many fields which are just dead weight
1633 // at execution stage?
1634                 thejob->cmds[i].pid = pi->cmds[i].pid;
1635                 /* all other fields are not used and stay zero */
1636         }
1637         thejob->next = NULL;
1638         thejob->cmdtext = xstrdup(get_cmdtext(pi));
1639
1640         /* We don't wait for background thejobs to return -- append it
1641            to the list of backgrounded thejobs and leave it alone */
1642         printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1643         G.last_bg_pid = thejob->cmds[0].pid;
1644         G.last_jobid = thejob->jobid;
1645 }
1646
1647 static void remove_bg_job(struct pipe *pi)
1648 {
1649         struct pipe *prev_pipe;
1650
1651         if (pi == G.job_list) {
1652                 G.job_list = pi->next;
1653         } else {
1654                 prev_pipe = G.job_list;
1655                 while (prev_pipe->next != pi)
1656                         prev_pipe = prev_pipe->next;
1657                 prev_pipe->next = pi->next;
1658         }
1659         if (G.job_list)
1660                 G.last_jobid = G.job_list->jobid;
1661         else
1662                 G.last_jobid = 0;
1663 }
1664
1665 /* Remove a backgrounded job */
1666 static void delete_finished_bg_job(struct pipe *pi)
1667 {
1668         remove_bg_job(pi);
1669         pi->stopped_cmds = 0;
1670         free_pipe(pi, 0);
1671         free(pi);
1672 }
1673 #endif /* JOB */
1674
1675 /* Check to see if any processes have exited -- if they
1676  * have, figure out why and see if a job has completed */
1677 static int checkjobs(struct pipe* fg_pipe)
1678 {
1679         int attributes;
1680         int status;
1681 #if ENABLE_HUSH_JOB
1682         struct pipe *pi;
1683 #endif
1684         pid_t childpid;
1685         int rcode = 0;
1686
1687         attributes = WUNTRACED;
1688         if (fg_pipe == NULL)
1689                 attributes |= WNOHANG;
1690
1691 /* Do we do this right?
1692  * bash-3.00# sleep 20 | false
1693  * <ctrl-Z pressed>
1694  * [3]+  Stopped          sleep 20 | false
1695  * bash-3.00# echo $?
1696  * 1   <========== bg pipe is not fully done, but exitcode is already known!
1697  */
1698
1699 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1700 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1701 // + killall -STOP cat
1702
1703  wait_more:
1704 // TODO: safe_waitpid?
1705         while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1706                 int i;
1707                 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1708 #if DEBUG_JOBS
1709                 if (WIFSTOPPED(status))
1710                         debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1711                                         childpid, WSTOPSIG(status), WEXITSTATUS(status));
1712                 if (WIFSIGNALED(status))
1713                         debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1714                                         childpid, WTERMSIG(status), WEXITSTATUS(status));
1715                 if (WIFEXITED(status))
1716                         debug_printf_jobs("pid %d exited, exitcode %d\n",
1717                                         childpid, WEXITSTATUS(status));
1718 #endif
1719                 /* Were we asked to wait for fg pipe? */
1720                 if (fg_pipe) {
1721                         for (i = 0; i < fg_pipe->num_cmds; i++) {
1722                                 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1723                                 if (fg_pipe->cmds[i].pid != childpid)
1724                                         continue;
1725                                 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1726                                 if (dead) {
1727                                         fg_pipe->cmds[i].pid = 0;
1728                                         fg_pipe->alive_cmds--;
1729                                         if (i == fg_pipe->num_cmds - 1) {
1730                                                 /* last process gives overall exitstatus */
1731                                                 rcode = WEXITSTATUS(status);
1732                                                 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
1733                                         }
1734                                 } else {
1735                                         fg_pipe->cmds[i].is_stopped = 1;
1736                                         fg_pipe->stopped_cmds++;
1737                                 }
1738                                 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1739                                                 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1740                                 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
1741                                         /* All processes in fg pipe have exited/stopped */
1742 #if ENABLE_HUSH_JOB
1743                                         if (fg_pipe->alive_cmds)
1744                                                 insert_bg_job(fg_pipe);
1745 #endif
1746                                         return rcode;
1747                                 }
1748                                 /* There are still running processes in the fg pipe */
1749                                 goto wait_more; /* do waitpid again */
1750                         }
1751                         /* it wasnt fg_pipe, look for process in bg pipes */
1752                 }
1753
1754 #if ENABLE_HUSH_JOB
1755                 /* We asked to wait for bg or orphaned children */
1756                 /* No need to remember exitcode in this case */
1757                 for (pi = G.job_list; pi; pi = pi->next) {
1758                         for (i = 0; i < pi->num_cmds; i++) {
1759                                 if (pi->cmds[i].pid == childpid)
1760                                         goto found_pi_and_prognum;
1761                         }
1762                 }
1763                 /* Happens when shell is used as init process (init=/bin/sh) */
1764                 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1765                 continue; /* do waitpid again */
1766
1767  found_pi_and_prognum:
1768                 if (dead) {
1769                         /* child exited */
1770                         pi->cmds[i].pid = 0;
1771                         pi->alive_cmds--;
1772                         if (!pi->alive_cmds) {
1773                                 printf(JOB_STATUS_FORMAT, pi->jobid,
1774                                                 "Done", pi->cmdtext);
1775                                 delete_finished_bg_job(pi);
1776                         }
1777                 } else {
1778                         /* child stopped */
1779                         pi->cmds[i].is_stopped = 1;
1780                         pi->stopped_cmds++;
1781                 }
1782 #endif
1783         } /* while (waitpid succeeds)... */
1784
1785         /* wait found no children or failed */
1786
1787         if (childpid && errno != ECHILD)
1788                 bb_perror_msg("waitpid");
1789         return rcode;
1790 }
1791
1792 #if ENABLE_HUSH_JOB
1793 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1794 {
1795         pid_t p;
1796         int rcode = checkjobs(fg_pipe);
1797         /* Job finished, move the shell to the foreground */
1798         p = getpgid(0); /* pgid of our process */
1799         debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1800         tcsetpgrp(G.interactive_fd, p);
1801         return rcode;
1802 }
1803 #endif
1804
1805 /* run_pipe() starts all the jobs, but doesn't wait for anything
1806  * to finish.  See checkjobs().
1807  *
1808  * return code is normally -1, when the caller has to wait for children
1809  * to finish to determine the exit status of the pipe.  If the pipe
1810  * is a simple builtin command, however, the action is done by the
1811  * time run_pipe returns, and the exit code is provided as the
1812  * return value.
1813  *
1814  * The input of the pipe is always stdin, the output is always
1815  * stdout.  The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1816  * because it tries to avoid running the command substitution in
1817  * subshell, when that is in fact necessary.  The subshell process
1818  * now has its stdout directed to the input of the appropriate pipe,
1819  * so this routine is noticeably simpler.
1820  *
1821  * Returns -1 only if started some children. IOW: we have to
1822  * mask out retvals of builtins etc with 0xff!
1823  */
1824 static int run_pipe(struct pipe *pi)
1825 {
1826         int i;
1827         int nextin;
1828         int pipefds[2];         /* pipefds[0] is for reading */
1829         struct command *command;
1830         char **argv_expanded;
1831         char **argv;
1832         const struct built_in_command *x;
1833         char *p;
1834         /* it is not always needed, but we aim to smaller code */
1835         int squirrel[] = { -1, -1, -1 };
1836         int rcode;
1837         const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
1838
1839         debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
1840
1841 #if ENABLE_HUSH_JOB
1842         pi->pgrp = -1;
1843 #endif
1844         pi->alive_cmds = 1;
1845         pi->stopped_cmds = 0;
1846
1847         /* Check if this is a simple builtin (not part of a pipe).
1848          * Builtins within pipes have to fork anyway, and are handled in
1849          * pseudo_exec.  "echo foo | read bar" doesn't work on bash, either.
1850          */
1851         command = &(pi->cmds[0]);
1852
1853 #if ENABLE_HUSH_FUNCTIONS
1854         if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
1855                 /* We "execute" function definition */
1856                 bb_error_msg("here we ought to remember function definition, and go on");
1857                 return EXIT_SUCCESS;
1858         }
1859 #endif
1860
1861         if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
1862                 debug_printf("non-subshell grouping\n");
1863                 setup_redirects(command, squirrel);
1864                 debug_printf_exec(": run_list\n");
1865                 rcode = run_list(command->group) & 0xff;
1866                 restore_redirects(squirrel);
1867                 debug_printf_exec("run_pipe return %d\n", rcode);
1868                 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1869                 return rcode;
1870         }
1871
1872         argv = command->argv;
1873         argv_expanded = NULL;
1874
1875         if (single_and_fg && argv != NULL) {
1876                 char **new_env = NULL;
1877                 char **old_env = NULL;
1878
1879                 i = command->assignment_cnt;
1880                 if (i != 0 && argv[i] == NULL) {
1881                         /* assignments, but no command: set local environment */
1882                         for (i = 0; argv[i] != NULL; i++) {
1883                                 debug_printf("local environment set: %s\n", argv[i]);
1884                                 p = expand_string_to_string(argv[i]);
1885                                 set_local_var(p, 0);
1886                         }
1887                         return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1888                 }
1889
1890                 /* Expand the rest into (possibly) many strings each */
1891                 argv_expanded = expand_strvec_to_strvec(argv + i);
1892
1893                 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1894                         if (strcmp(argv_expanded[0], x->cmd) != 0)
1895                                 continue;
1896                         if (x->function == builtin_exec && argv_expanded[1] == NULL) {
1897                                 debug_printf("exec with redirects only\n");
1898                                 setup_redirects(command, NULL);
1899                                 rcode = EXIT_SUCCESS;
1900                                 goto clean_up_and_ret1;
1901                         }
1902                         debug_printf("builtin inline %s\n", argv_expanded[0]);
1903                         /* XXX setup_redirects acts on file descriptors, not FILEs.
1904                          * This is perfect for work that comes after exec().
1905                          * Is it really safe for inline use?  Experimentally,
1906                          * things seem to work with glibc. */
1907                         setup_redirects(command, squirrel);
1908                         new_env = expand_assignments(argv, command->assignment_cnt);
1909                         old_env = putenv_all_and_save_old(new_env);
1910                         debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
1911                         rcode = x->function(argv_expanded) & 0xff;
1912 #if ENABLE_FEATURE_SH_STANDALONE
1913  clean_up_and_ret:
1914 #endif
1915                         restore_redirects(squirrel);
1916                         free_strings_and_unsetenv(new_env, 1);
1917                         putenv_all(old_env);
1918                         free(old_env); /* not free_strings()! */
1919  clean_up_and_ret1:
1920                         free(argv_expanded);
1921                         IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1922                         debug_printf_exec("run_pipe return %d\n", rcode);
1923                         return rcode;
1924                 }
1925 #if ENABLE_FEATURE_SH_STANDALONE
1926                 i = find_applet_by_name(argv_expanded[0]);
1927                 if (i >= 0 && APPLET_IS_NOFORK(i)) {
1928                         setup_redirects(command, squirrel);
1929                         save_nofork_data(&G.nofork_save);
1930                         new_env = expand_assignments(argv, command->assignment_cnt);
1931                         old_env = putenv_all_and_save_old(new_env);
1932                         debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1933                         rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
1934                         goto clean_up_and_ret;
1935                 }
1936 #endif
1937         }
1938
1939         /* NB: argv_expanded may already be created, and that
1940          * might include `cmd` runs! Do not rerun it! We *must*
1941          * use argv_expanded if it's non-NULL */
1942
1943         /* Disable job control signals for shell (parent) and
1944          * for initial child code after fork */
1945         set_jobctrl_sighandler(SIG_IGN);
1946
1947         /* Going to fork a child per each pipe member */
1948         pi->alive_cmds = 0;
1949         nextin = 0;
1950
1951         for (i = 0; i < pi->num_cmds; i++) {
1952 #if !BB_MMU
1953                 volatile nommu_save_t nommu_save;
1954                 nommu_save.new_env = NULL;
1955                 nommu_save.old_env = NULL;
1956                 nommu_save.argv = NULL;
1957 #endif
1958                 command = &(pi->cmds[i]);
1959                 if (command->argv) {
1960                         debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
1961                 } else
1962                         debug_printf_exec(": pipe member with no argv\n");
1963
1964                 /* pipes are inserted between pairs of commands */
1965                 pipefds[0] = 0;
1966                 pipefds[1] = 1;
1967                 if ((i + 1) < pi->num_cmds)
1968                         xpipe(pipefds);
1969
1970                 command->pid = BB_MMU ? fork() : vfork();
1971                 if (!command->pid) { /* child */
1972                         if (ENABLE_HUSH_JOB)
1973                                 die_sleep = 0; /* let nofork's xfuncs die */
1974 #if ENABLE_HUSH_JOB
1975                         /* Every child adds itself to new process group
1976                          * with pgid == pid_of_first_child_in_pipe */
1977                         if (G.run_list_level == 1 && G.interactive_fd) {
1978                                 pid_t pgrp;
1979                                 /* Don't do pgrp restore anymore on fatal signals */
1980                                 set_fatal_sighandler(SIG_DFL);
1981                                 pgrp = pi->pgrp;
1982                                 if (pgrp < 0) /* true for 1st process only */
1983                                         pgrp = getpid();
1984                                 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
1985                                         /* We do it in *every* child, not just first,
1986                                          * to avoid races */
1987                                         tcsetpgrp(G.interactive_fd, pgrp);
1988                                 }
1989                         }
1990 #endif
1991                         xmove_fd(nextin, 0);
1992                         xmove_fd(pipefds[1], 1); /* write end */
1993                         if (pipefds[0] > 1)
1994                                 close(pipefds[0]); /* read end */
1995                         /* Like bash, explicit redirects override pipes,
1996                          * and the pipe fd is available for dup'ing. */
1997                         setup_redirects(command, NULL);
1998
1999                         /* Restore default handlers just prior to exec */
2000                         set_jobctrl_sighandler(SIG_DFL);
2001                         set_misc_sighandler(SIG_DFL);
2002                         signal(SIGCHLD, SIG_DFL);
2003                         /* Stores to nommu_save list of env vars putenv'ed
2004                          * (NOMMU, on MMU we don't need that) */
2005                         /* cast away volatility... */
2006                         pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2007                         /* pseudo_exec() does not return */
2008                 }
2009                 /* parent */
2010 #if !BB_MMU
2011                 /* Clean up after vforked child */
2012                 free(nommu_save.argv);
2013                 free_strings_and_unsetenv(nommu_save.new_env, 1);
2014                 putenv_all(nommu_save.old_env);
2015 #endif
2016                 free(argv_expanded);
2017                 argv_expanded = NULL;
2018                 if (command->pid < 0) { /* [v]fork failed */
2019                         /* Clearly indicate, was it fork or vfork */
2020                         bb_perror_msg(BB_MMU ? "fork" : "vfork");
2021                 } else {
2022                         pi->alive_cmds++;
2023 #if ENABLE_HUSH_JOB
2024                         /* Second and next children need to know pid of first one */
2025                         if (pi->pgrp < 0)
2026                                 pi->pgrp = command->pid;
2027 #endif
2028                 }
2029
2030                 if (i)
2031                         close(nextin);
2032                 if ((i + 1) < pi->num_cmds)
2033                         close(pipefds[1]); /* write end */
2034                 /* Pass read (output) pipe end to next iteration */
2035                 nextin = pipefds[0];
2036         }
2037
2038         if (!pi->alive_cmds) {
2039                 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2040                 return 1;
2041         }
2042
2043         debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2044         return -1;
2045 }
2046
2047 #ifndef debug_print_tree
2048 static void debug_print_tree(struct pipe *pi, int lvl)
2049 {
2050         static const char *const PIPE[] = {
2051                 [PIPE_SEQ] = "SEQ",
2052                 [PIPE_AND] = "AND",
2053                 [PIPE_OR ] = "OR" ,
2054                 [PIPE_BG ] = "BG" ,
2055         };
2056         static const char *RES[] = {
2057                 [RES_NONE ] = "NONE" ,
2058 #if ENABLE_HUSH_IF
2059                 [RES_IF   ] = "IF"   ,
2060                 [RES_THEN ] = "THEN" ,
2061                 [RES_ELIF ] = "ELIF" ,
2062                 [RES_ELSE ] = "ELSE" ,
2063                 [RES_FI   ] = "FI"   ,
2064 #endif
2065 #if ENABLE_HUSH_LOOPS
2066                 [RES_FOR  ] = "FOR"  ,
2067                 [RES_WHILE] = "WHILE",
2068                 [RES_UNTIL] = "UNTIL",
2069                 [RES_DO   ] = "DO"   ,
2070                 [RES_DONE ] = "DONE" ,
2071 #endif
2072 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2073                 [RES_IN   ] = "IN"   ,
2074 #endif
2075 #if ENABLE_HUSH_CASE
2076                 [RES_CASE ] = "CASE" ,
2077                 [RES_MATCH] = "MATCH",
2078                 [RES_CASEI] = "CASEI",
2079                 [RES_ESAC ] = "ESAC" ,
2080 #endif
2081                 [RES_XXXX ] = "XXXX" ,
2082                 [RES_SNTX ] = "SNTX" ,
2083         };
2084         static const char *const GRPTYPE[] = {
2085                 "()",
2086                 "{}",
2087 #if ENABLE_HUSH_FUNCTIONS
2088                 "func()",
2089 #endif
2090         };
2091
2092         int pin, prn;
2093
2094         pin = 0;
2095         while (pi) {
2096                 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2097                                 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2098                 prn = 0;
2099                 while (prn < pi->num_cmds) {
2100                         struct command *command = &pi->cmds[prn];
2101                         char **argv = command->argv;
2102
2103                         fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2104                         if (command->group) {
2105                                 fprintf(stderr, " group %s: (argv=%p)\n",
2106                                                 GRPTYPE[command->grp_type],
2107                                                 argv);
2108                                 debug_print_tree(command->group, lvl+1);
2109                                 prn++;
2110                                 continue;
2111                         }
2112                         if (argv) while (*argv) {
2113                                 fprintf(stderr, " '%s'", *argv);
2114                                 argv++;
2115                         }
2116                         fprintf(stderr, "\n");
2117                         prn++;
2118                 }
2119                 pi = pi->next;
2120                 pin++;
2121         }
2122 }
2123 #endif
2124
2125 /* NB: called by pseudo_exec, and therefore must not modify any
2126  * global data until exec/_exit (we can be a child after vfork!) */
2127 static int run_list(struct pipe *pi)
2128 {
2129 #if ENABLE_HUSH_CASE
2130         char *case_word = NULL;
2131 #endif
2132 #if ENABLE_HUSH_LOOPS
2133         struct pipe *loop_top = NULL;
2134         char *for_varname = NULL;
2135         char **for_lcur = NULL;
2136         char **for_list = NULL;
2137 #endif
2138         smallint flag_skip = 1;
2139         smalluint rcode = 0; /* probably just for compiler */
2140 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2141         smalluint cond_code = 0;
2142 #else
2143         enum { cond_code = 0, };
2144 #endif
2145         /*enum reserved_style*/ smallint rword = RES_NONE;
2146         /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2147
2148         debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2149
2150 #if ENABLE_HUSH_LOOPS
2151         /* Check syntax for "for" */
2152         for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2153                 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2154                         continue;
2155                 /* current word is FOR or IN (BOLD in comments below) */
2156                 if (cpipe->next == NULL) {
2157                         syntax("malformed for");
2158                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2159                         return 1;
2160                 }
2161                 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2162                 if (cpipe->next->res_word == RES_DO)
2163                         continue;
2164                 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2165                 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2166                  || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2167                 ) {
2168                         syntax("malformed for");
2169                         debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2170                         return 1;
2171                 }
2172         }
2173 #endif
2174
2175         /* Past this point, all code paths should jump to ret: label
2176          * in order to return, no direct "return" statements please.
2177          * This helps to ensure that no memory is leaked. */
2178
2179 #if ENABLE_HUSH_JOB
2180         /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2181          * We are saving state before entering outermost list ("while...done")
2182          * so that ctrl-Z will correctly background _entire_ outermost list,
2183          * not just a part of it (like "sleep 1 | exit 2") */
2184         if (++G.run_list_level == 1 && G.interactive_fd) {
2185                 if (sigsetjmp(G.toplevel_jb, 1)) {
2186                         /* ctrl-Z forked and we are parent; or ctrl-C.
2187                          * Sighandler has longjmped us here */
2188                         signal(SIGINT, SIG_IGN);
2189                         signal(SIGTSTP, SIG_IGN);
2190                         /* Restore level (we can be coming from deep inside
2191                          * nested levels) */
2192                         G.run_list_level = 1;
2193 #if ENABLE_FEATURE_SH_STANDALONE
2194                         if (G.nofork_save.saved) { /* if save area is valid */
2195                                 debug_printf_jobs("exiting nofork early\n");
2196                                 restore_nofork_data(&G.nofork_save);
2197                         }
2198 #endif
2199                         if (G.ctrl_z_flag) {
2200                                 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2201                                  * Remember this child as background job */
2202                                 insert_bg_job(pi);
2203                         } else {
2204                                 /* ctrl-C. We just stop doing whatever we were doing */
2205                                 bb_putchar('\n');
2206                         }
2207                         USE_HUSH_LOOPS(loop_top = NULL;)
2208                         USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2209                         rcode = 0;
2210                         goto ret;
2211                 }
2212                 /* ctrl-Z handler will store pid etc in pi */
2213                 G.toplevel_list = pi;
2214                 G.ctrl_z_flag = 0;
2215 #if ENABLE_FEATURE_SH_STANDALONE
2216                 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2217 #endif
2218                 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2219                 signal(SIGINT, handler_ctrl_c);
2220         }
2221 #endif /* JOB */
2222
2223         /* Go through list of pipes, (maybe) executing them. */
2224         for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2225                 IF_HAS_KEYWORDS(rword = pi->res_word;)
2226                 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2227                 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2228                                 rword, cond_code, skip_more_for_this_rword);
2229 #if ENABLE_HUSH_LOOPS
2230                 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2231                  && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2232                 ) {
2233                         /* start of a loop: remember where loop starts */
2234                         loop_top = pi;
2235                         G.depth_of_loop++;
2236                 }
2237 #endif
2238                 if (rword == skip_more_for_this_rword && flag_skip) {
2239                         if (pi->followup == PIPE_SEQ)
2240                                 flag_skip = 0;
2241                         /* it is "<false> && CMD" or "<true> || CMD"
2242                          * and we should not execute CMD */
2243                         continue;
2244                 }
2245                 flag_skip = 1;
2246                 skip_more_for_this_rword = RES_XXXX;
2247 #if ENABLE_HUSH_IF
2248                 if (cond_code) {
2249                         if (rword == RES_THEN) {
2250                                 /* "if <false> THEN cmd": skip cmd */
2251                                 continue;
2252                         }
2253                 } else {
2254                         if (rword == RES_ELSE || rword == RES_ELIF) {
2255                                 /* "if <true> then ... ELSE/ELIF cmd":
2256                                  * skip cmd and all following ones */
2257                                 break;
2258                         }
2259                 }
2260 #endif
2261 #if ENABLE_HUSH_LOOPS
2262                 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2263                         if (!for_lcur) {
2264                                 /* first loop through for */
2265
2266                                 static const char encoded_dollar_at[] ALIGN1 = {
2267                                         SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2268                                 }; /* encoded representation of "$@" */
2269                                 static const char *const encoded_dollar_at_argv[] = {
2270                                         encoded_dollar_at, NULL
2271                                 }; /* argv list with one element: "$@" */
2272                                 char **vals;
2273
2274                                 vals = (char**)encoded_dollar_at_argv;
2275                                 if (pi->next->res_word == RES_IN) {
2276                                         /* if no variable values after "in" we skip "for" */
2277                                         if (!pi->next->cmds[0].argv)
2278                                                 break;
2279                                         vals = pi->next->cmds[0].argv;
2280                                 } /* else: "for var; do..." -> assume "$@" list */
2281                                 /* create list of variable values */
2282                                 debug_print_strings("for_list made from", vals);
2283                                 for_list = expand_strvec_to_strvec(vals);
2284                                 for_lcur = for_list;
2285                                 debug_print_strings("for_list", for_list);
2286                                 for_varname = pi->cmds[0].argv[0];
2287                                 pi->cmds[0].argv[0] = NULL;
2288                         }
2289                         free(pi->cmds[0].argv[0]);
2290                         if (!*for_lcur) {
2291                                 /* "for" loop is over, clean up */
2292                                 free(for_list);
2293                                 for_list = NULL;
2294                                 for_lcur = NULL;
2295                                 pi->cmds[0].argv[0] = for_varname;
2296                                 break;
2297                         }
2298                         /* insert next value from for_lcur */
2299 //TODO: does it need escaping?
2300                         pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2301                         pi->cmds[0].assignment_cnt = 1;
2302                 }
2303                 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2304                         continue;
2305                 if (rword == RES_DONE) {
2306                         continue; /* "done" has no cmds too */
2307                 }
2308 #endif
2309 #if ENABLE_HUSH_CASE
2310                 if (rword == RES_CASE) {
2311                         case_word = expand_strvec_to_string(pi->cmds->argv);
2312                         continue;
2313                 }
2314                 if (rword == RES_MATCH) {
2315                         char **argv;
2316
2317                         if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2318                                 break;
2319                         /* all prev words didn't match, does this one match? */
2320                         argv = pi->cmds->argv;
2321                         while (*argv) {
2322                                 char *pattern = expand_string_to_string(*argv);
2323                                 /* TODO: which FNM_xxx flags to use? */
2324                                 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2325                                 free(pattern);
2326                                 if (cond_code == 0) { /* match! we will execute this branch */
2327                                         free(case_word); /* make future "word)" stop */
2328                                         case_word = NULL;
2329                                         break;
2330                                 }
2331                                 argv++;
2332                         }
2333                         continue;
2334                 }
2335                 if (rword == RES_CASEI) { /* inside of a case branch */
2336                         if (cond_code != 0)
2337                                 continue; /* not matched yet, skip this pipe */
2338                 }
2339 #endif
2340                 if (pi->num_cmds == 0)
2341                         continue;
2342
2343                 /* After analyzing all keywords and conditions, we decided
2344                  * to execute this pipe. NB: has to do checkjobs(NULL)
2345                  * after run_pipe() to collect any background children,
2346                  * even if list execution is to be stopped. */
2347                 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2348                 {
2349                         int r;
2350 #if ENABLE_HUSH_LOOPS
2351                         G.flag_break_continue = 0;
2352 #endif
2353                         rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2354                         if (r != -1) {
2355                                 /* we only ran a builtin: rcode is already known
2356                                  * and we don't need to wait for anything. */
2357 #if ENABLE_HUSH_LOOPS
2358                                 /* was it "break" or "continue"? */
2359                                 if (G.flag_break_continue) {
2360                                         smallint fbc = G.flag_break_continue;
2361                                         /* we might fall into outer *loop*,
2362                                          * don't want to break it too */
2363                                         if (loop_top) {
2364                                                 G.depth_break_continue--;
2365                                                 if (G.depth_break_continue == 0)
2366                                                         G.flag_break_continue = 0;
2367                                                 /* else: e.g. "continue 2" should *break* once, *then* continue */
2368                                         } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2369                                         if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2370                                                 goto check_jobs_and_break;
2371                                         /* "continue": simulate end of loop */
2372                                         rword = RES_DONE;
2373                                         continue;
2374                                 }
2375 #endif
2376                         } else if (pi->followup == PIPE_BG) {
2377                                 /* what does bash do with attempts to background builtins? */
2378                                 /* even bash 3.2 doesn't do that well with nested bg:
2379                                  * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2380                                  * I'm NOT treating inner &'s as jobs */
2381 #if ENABLE_HUSH_JOB
2382                                 if (G.run_list_level == 1)
2383                                         insert_bg_job(pi);
2384 #endif
2385                                 rcode = 0; /* EXIT_SUCCESS */
2386                         } else {
2387 #if ENABLE_HUSH_JOB
2388                                 if (G.run_list_level == 1 && G.interactive_fd) {
2389                                         /* waits for completion, then fg's main shell */
2390                                         rcode = checkjobs_and_fg_shell(pi);
2391                                         debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2392                                 } else
2393 #endif
2394                                 { /* this one just waits for completion */
2395                                         rcode = checkjobs(pi);
2396                                         debug_printf_exec(": checkjobs returned %d\n", rcode);
2397                                 }
2398                         }
2399                 }
2400                 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2401                 G.last_return_code = rcode;
2402
2403                 /* Analyze how result affects subsequent commands */
2404 #if ENABLE_HUSH_IF
2405                 if (rword == RES_IF || rword == RES_ELIF)
2406                         cond_code = rcode;
2407 #endif
2408 #if ENABLE_HUSH_LOOPS
2409                 if (rword == RES_WHILE) {
2410                         if (rcode) {
2411                                 rcode = 0; /* "while false; do...done" - exitcode 0 */
2412                                 goto check_jobs_and_break;
2413                         }
2414                 }
2415                 if (rword == RES_UNTIL) {
2416                         if (!rcode) {
2417  check_jobs_and_break:
2418                                 checkjobs(NULL);
2419                                 break;
2420                         }
2421                 }
2422 #endif
2423                 if ((rcode == 0 && pi->followup == PIPE_OR)
2424                  || (rcode != 0 && pi->followup == PIPE_AND)
2425                 ) {
2426                         skip_more_for_this_rword = rword;
2427                 }
2428                 checkjobs(NULL);
2429         } /* for (pi) */
2430
2431 #if ENABLE_HUSH_JOB
2432         if (G.ctrl_z_flag) {
2433                 /* ctrl-Z forked somewhere in the past, we are the child,
2434                  * and now we completed running the list. Exit. */
2435 //TODO: _exit?
2436                 exit(rcode);
2437         }
2438  ret:
2439         if (!--G.run_list_level && G.interactive_fd) {
2440                 signal(SIGTSTP, SIG_IGN);
2441                 signal(SIGINT, SIG_IGN);
2442         }
2443 #endif
2444         debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2445 #if ENABLE_HUSH_LOOPS
2446         if (loop_top)
2447                 G.depth_of_loop--;
2448         free(for_list);
2449 #endif
2450 #if ENABLE_HUSH_CASE
2451         free(case_word);
2452 #endif
2453         return rcode;
2454 }
2455
2456 /* return code is the exit status of the pipe */
2457 static int free_pipe(struct pipe *pi, int indent)
2458 {
2459         char **p;
2460         struct command *command;
2461         struct redir_struct *r, *rnext;
2462         int a, i, ret_code = 0;
2463
2464         if (pi->stopped_cmds > 0)
2465                 return ret_code;
2466         debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2467         for (i = 0; i < pi->num_cmds; i++) {
2468                 command = &pi->cmds[i];
2469                 debug_printf_clean("%s  command %d:\n", indenter(indent), i);
2470                 if (command->argv) {
2471                         for (a = 0, p = command->argv; *p; a++, p++) {
2472                                 debug_printf_clean("%s   argv[%d] = %s\n", indenter(indent), a, *p);
2473                         }
2474                         free_strings(command->argv);
2475                         command->argv = NULL;
2476                 } else if (command->group) {
2477                         debug_printf_clean("%s   begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2478                         ret_code = free_pipe_list(command->group, indent+3);
2479                         debug_printf_clean("%s   end group\n", indenter(indent));
2480                 } else {
2481                         debug_printf_clean("%s   (nil)\n", indenter(indent));
2482                 }
2483                 for (r = command->redirects; r; r = rnext) {
2484                         debug_printf_clean("%s   redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2485                         if (r->dup == -1) {
2486                                 /* guard against the case >$FOO, where foo is unset or blank */
2487                                 if (r->rd_filename) {
2488                                         debug_printf_clean(" %s\n", r->rd_filename);
2489                                         free(r->rd_filename);
2490                                         r->rd_filename = NULL;
2491                                 }
2492                         } else {
2493                                 debug_printf_clean("&%d\n", r->dup);
2494                         }
2495                         rnext = r->next;
2496                         free(r);
2497                 }
2498                 command->redirects = NULL;
2499         }
2500         free(pi->cmds);   /* children are an array, they get freed all at once */
2501         pi->cmds = NULL;
2502 #if ENABLE_HUSH_JOB
2503         free(pi->cmdtext);
2504         pi->cmdtext = NULL;
2505 #endif
2506         return ret_code;
2507 }
2508
2509 static int free_pipe_list(struct pipe *head, int indent)
2510 {
2511         int rcode = 0;   /* if list has no members */
2512         struct pipe *pi, *next;
2513
2514         for (pi = head; pi; pi = next) {
2515 #if HAS_KEYWORDS
2516                 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2517 #endif
2518                 rcode = free_pipe(pi, indent);
2519                 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2520                 next = pi->next;
2521                 /*pi->next = NULL;*/
2522                 free(pi);
2523         }
2524         return rcode;
2525 }
2526
2527 /* Select which version we will use */
2528 static int run_and_free_list(struct pipe *pi)
2529 {
2530         int rcode = 0;
2531         debug_printf_exec("run_and_free_list entered\n");
2532         if (!G.fake_mode) {
2533                 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2534                 rcode = run_list(pi);
2535         }
2536         /* free_pipe_list has the side effect of clearing memory.
2537          * In the long run that function can be merged with run_list,
2538          * but doing that now would hobble the debugging effort. */
2539         free_pipe_list(pi, /* indent: */ 0);
2540         debug_printf_exec("run_and_free_list return %d\n", rcode);
2541         return rcode;
2542 }
2543
2544
2545 /* expand_strvec_to_strvec() takes a list of strings, expands
2546  * all variable references within and returns a pointer to
2547  * a list of expanded strings, possibly with larger number
2548  * of strings. (Think VAR="a b"; echo $VAR).
2549  * This new list is allocated as a single malloc block.
2550  * NULL-terminated list of char* pointers is at the beginning of it,
2551  * followed by strings themself.
2552  * Caller can deallocate entire list by single free(list). */
2553
2554 /* Store given string, finalizing the word and starting new one whenever
2555  * we encounter IFS char(s). This is used for expanding variable values.
2556  * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2557 static int expand_on_ifs(o_string *output, int n, const char *str)
2558 {
2559         while (1) {
2560                 int word_len = strcspn(str, G.ifs);
2561                 if (word_len) {
2562                         if (output->o_quote || !output->o_glob)
2563                                 o_addQstr(output, str, word_len);
2564                         else /* protect backslashes against globbing up :) */
2565                                 o_addstr_duplicate_backslash(output, str, word_len);
2566                         str += word_len;
2567                 }
2568                 if (!*str)  /* EOL - do not finalize word */
2569                         break;
2570                 o_addchr(output, '\0');
2571                 debug_print_list("expand_on_ifs", output, n);
2572                 n = o_save_ptr(output, n);
2573                 str += strspn(str, G.ifs); /* skip ifs chars */
2574         }
2575         debug_print_list("expand_on_ifs[1]", output, n);
2576         return n;
2577 }
2578
2579 /* Expand all variable references in given string, adding words to list[]
2580  * at n, n+1,... positions. Return updated n (so that list[n] is next one
2581  * to be filled). This routine is extremely tricky: has to deal with
2582  * variables/parameters with whitespace, $* and $@, and constructs like
2583  * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2584 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2585 {
2586         /* or_mask is either 0 (normal case) or 0x80
2587          * (expansion of right-hand side of assignment == 1-element expand.
2588          * It will also do no globbing, and thus we must not backslash-quote!) */
2589
2590         char first_ch, ored_ch;
2591         int i;
2592         const char *val;
2593         char *p;
2594
2595         ored_ch = 0;
2596
2597         debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2598         debug_print_list("expand_vars_to_list", output, n);
2599         n = o_save_ptr(output, n);
2600         debug_print_list("expand_vars_to_list[0]", output, n);
2601
2602         while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2603 #if ENABLE_HUSH_TICK
2604                 o_string subst_result = NULL_O_STRING;
2605 #endif
2606                 o_addstr(output, arg, p - arg);
2607                 debug_print_list("expand_vars_to_list[1]", output, n);
2608                 arg = ++p;
2609                 p = strchr(p, SPECIAL_VAR_SYMBOL);
2610
2611                 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2612                 /* "$@" is special. Even if quoted, it can still
2613                  * expand to nothing (not even an empty string) */
2614                 if ((first_ch & 0x7f) != '@')
2615                         ored_ch |= first_ch;
2616                 val = NULL;
2617                 switch (first_ch & 0x7f) {
2618                 /* Highest bit in first_ch indicates that var is double-quoted */
2619                 case '$': /* pid */
2620                         val = utoa(G.root_pid);
2621                         break;
2622                 case '!': /* bg pid */
2623                         val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2624                         break;
2625                 case '?': /* exitcode */
2626                         val = utoa(G.last_return_code);
2627                         break;
2628                 case '#': /* argc */
2629                         val = utoa(G.global_argc ? G.global_argc-1 : 0);
2630                         break;
2631                 case '*':
2632                 case '@':
2633                         i = 1;
2634                         if (!G.global_argv[i])
2635                                 break;
2636                         ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2637                         if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2638                                 smallint sv = output->o_quote;
2639                                 /* unquoted var's contents should be globbed, so don't quote */
2640                                 output->o_quote = 0;
2641                                 while (G.global_argv[i]) {
2642                                         n = expand_on_ifs(output, n, G.global_argv[i]);
2643                                         debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2644                                         if (G.global_argv[i++][0] && G.global_argv[i]) {
2645                                                 /* this argv[] is not empty and not last:
2646                                                  * put terminating NUL, start new word */
2647                                                 o_addchr(output, '\0');
2648                                                 debug_print_list("expand_vars_to_list[2]", output, n);
2649                                                 n = o_save_ptr(output, n);
2650                                                 debug_print_list("expand_vars_to_list[3]", output, n);
2651                                         }
2652                                 }
2653                                 output->o_quote = sv;
2654                         } else
2655                         /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2656                          * and in this case should treat it like '$*' - see 'else...' below */
2657                         if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2658                                 while (1) {
2659                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2660                                         if (++i >= G.global_argc)
2661                                                 break;
2662                                         o_addchr(output, '\0');
2663                                         debug_print_list("expand_vars_to_list[4]", output, n);
2664                                         n = o_save_ptr(output, n);
2665                                 }
2666                         } else { /* quoted $*: add as one word */
2667                                 while (1) {
2668                                         o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2669                                         if (!G.global_argv[++i])
2670                                                 break;
2671                                         if (G.ifs[0])
2672                                                 o_addchr(output, G.ifs[0]);
2673                                 }
2674                         }
2675                         break;
2676                 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2677                         /* "Empty variable", used to make "" etc to not disappear */
2678                         arg++;
2679                         ored_ch = 0x80;
2680                         break;
2681 #if ENABLE_HUSH_TICK
2682                 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2683                         struct in_str input;
2684                         *p = '\0';
2685                         arg++;
2686 //TODO: can we just stuff it into "output" directly?
2687                         debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2688                         setup_string_in_str(&input, arg);
2689                         process_command_subs(&subst_result, &input, NULL);
2690                         debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2691                         val = subst_result.data;
2692                         goto store_val;
2693                 }
2694 #endif
2695                 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2696                         *p = '\0';
2697                         arg[0] = first_ch & 0x7f;
2698                         if (isdigit(arg[0])) {
2699                                 i = xatoi_u(arg);
2700                                 if (i < G.global_argc)
2701                                         val = G.global_argv[i];
2702                                 /* else val remains NULL: $N with too big N */
2703                         } else
2704                                 val = lookup_param(arg);
2705                         arg[0] = first_ch;
2706 #if ENABLE_HUSH_TICK
2707  store_val:
2708 #endif
2709                         *p = SPECIAL_VAR_SYMBOL;
2710                         if (!(first_ch & 0x80)) { /* unquoted $VAR */
2711                                 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
2712                                 if (val) {
2713                                         /* unquoted var's contents should be globbed, so don't quote */
2714                                         smallint sv = output->o_quote;
2715                                         output->o_quote = 0;
2716                                         n = expand_on_ifs(output, n, val);
2717                                         val = NULL;
2718                                         output->o_quote = sv;
2719                                 }
2720                         } else { /* quoted $VAR, val will be appended below */
2721                                 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
2722                         }
2723                 }
2724                 if (val) {
2725                         o_addQstr(output, val, strlen(val));
2726                 }
2727
2728 #if ENABLE_HUSH_TICK
2729                 o_free(&subst_result);
2730 #endif
2731                 arg = ++p;
2732         } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2733
2734         if (arg[0]) {
2735                 debug_print_list("expand_vars_to_list[a]", output, n);
2736                 /* this part is literal, and it was already pre-quoted
2737                  * if needed (much earlier), do not use o_addQstr here! */
2738                 o_addstr(output, arg, strlen(arg) + 1);
2739                 debug_print_list("expand_vars_to_list[b]", output, n);
2740         } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2741          && !(ored_ch & 0x80) /* and all vars were not quoted. */
2742         ) {
2743                 n--;
2744                 /* allow to reuse list[n] later without re-growth */
2745                 output->has_empty_slot = 1;
2746         } else {
2747                 o_addchr(output, '\0');
2748         }
2749         return n;
2750 }
2751
2752 static char **expand_variables(char **argv, int or_mask)
2753 {
2754         int n;
2755         char **list;
2756         char **v;
2757         o_string output = NULL_O_STRING;
2758
2759         if (or_mask & 0x100) {
2760                 output.o_quote = 1; /* protect against globbing for "$var" */
2761                 /* (unquoted $var will temporarily switch it off) */
2762                 output.o_glob = 1;
2763         }
2764
2765         n = 0;
2766         v = argv;
2767         while (*v) {
2768                 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2769                 v++;
2770         }
2771         debug_print_list("expand_variables", &output, n);
2772
2773         /* output.data (malloced in one block) gets returned in "list" */
2774         list = o_finalize_list(&output, n);
2775         debug_print_strings("expand_variables[1]", list);
2776         return list;
2777 }
2778
2779 static char **expand_strvec_to_strvec(char **argv)
2780 {
2781         return expand_variables(argv, 0x100);
2782 }
2783
2784 /* Used for expansion of right hand of assignments */
2785 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2786  * "v=/bin/c*" */
2787 static char *expand_string_to_string(const char *str)
2788 {
2789         char *argv[2], **list;
2790
2791         argv[0] = (char*)str;
2792         argv[1] = NULL;
2793         list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2794         if (HUSH_DEBUG)
2795                 if (!list[0] || list[1])
2796                         bb_error_msg_and_die("BUG in varexp2");
2797         /* actually, just move string 2*sizeof(char*) bytes back */
2798         strcpy((char*)list, list[0]);
2799         debug_printf_expand("string_to_string='%s'\n", (char*)list);
2800         return (char*)list;
2801 }
2802
2803 /* Used for "eval" builtin */
2804 static char* expand_strvec_to_string(char **argv)
2805 {
2806         char **list;
2807
2808         list = expand_variables(argv, 0x80);
2809         /* Convert all NULs to spaces */
2810         if (list[0]) {
2811                 int n = 1;
2812                 while (list[n]) {
2813                         if (HUSH_DEBUG)
2814                                 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2815                                         bb_error_msg_and_die("BUG in varexp3");
2816                         list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2817                         n++;
2818                 }
2819         }
2820         strcpy((char*)list, list[0]);
2821         debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2822         return (char*)list;
2823 }
2824
2825
2826 /* Used to get/check local shell variables */
2827 static struct variable *get_local_var(const char *name)
2828 {
2829         struct variable *cur;
2830         int len;
2831
2832         if (!name)
2833                 return NULL;
2834         len = strlen(name);
2835         for (cur = G.top_var; cur; cur = cur->next) {
2836                 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2837                         return cur;
2838         }
2839         return NULL;
2840 }
2841
2842 /* str holds "NAME=VAL" and is expected to be malloced.
2843  * We take ownership of it. */
2844 static int set_local_var(char *str, int flg_export)
2845 {
2846         struct variable *cur;
2847         char *value;
2848         int name_len;
2849
2850         value = strchr(str, '=');
2851         if (!value) { /* not expected to ever happen? */
2852                 free(str);
2853                 return -1;
2854         }
2855
2856         name_len = value - str + 1; /* including '=' */
2857         cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2858         while (1) {
2859                 if (strncmp(cur->varstr, str, name_len) != 0) {
2860                         if (!cur->next) {
2861                                 /* Bail out. Note that now cur points
2862                                  * to last var in linked list */
2863                                 break;
2864                         }
2865                         cur = cur->next;
2866                         continue;
2867                 }
2868                 /* We found an existing var with this name */
2869                 *value = '\0';
2870                 if (cur->flg_read_only) {
2871                         bb_error_msg("%s: readonly variable", str);
2872                         free(str);
2873                         return -1;
2874                 }
2875                 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2876                 unsetenv(str); /* just in case */
2877                 *value = '=';
2878                 if (strcmp(cur->varstr, str) == 0) {
2879  free_and_exp:
2880                         free(str);
2881                         goto exp;
2882                 }
2883                 if (cur->max_len >= strlen(str)) {
2884                         /* This one is from startup env, reuse space */
2885                         strcpy(cur->varstr, str);
2886                         goto free_and_exp;
2887                 }
2888                 /* max_len == 0 signifies "malloced" var, which we can
2889                  * (and has to) free */
2890                 if (!cur->max_len)
2891                         free(cur->varstr);
2892                 cur->max_len = 0;
2893                 goto set_str_and_exp;
2894         }
2895
2896         /* Not found - create next variable struct */
2897         cur->next = xzalloc(sizeof(*cur));
2898         cur = cur->next;
2899
2900  set_str_and_exp:
2901         cur->varstr = str;
2902  exp:
2903         if (flg_export)
2904                 cur->flg_export = 1;
2905         if (cur->flg_export) {
2906                 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2907                 return putenv(cur->varstr);
2908         }
2909         return 0;
2910 }
2911
2912 static void unset_local_var(const char *name)
2913 {
2914         struct variable *cur;
2915         struct variable *prev = prev; /* for gcc */
2916         int name_len;
2917
2918         if (!name)
2919                 return;
2920         name_len = strlen(name);
2921         cur = G.top_var;
2922         while (cur) {
2923                 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2924                         if (cur->flg_read_only) {
2925                                 bb_error_msg("%s: readonly variable", name);
2926                                 return;
2927                         }
2928                         /* prev is ok to use here because 1st variable, HUSH_VERSION,
2929                          * is ro, and we cannot reach this code on the 1st pass */
2930                         prev->next = cur->next;
2931                         debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2932                         bb_unsetenv(cur->varstr);
2933                         if (!cur->max_len)
2934                                 free(cur->varstr);
2935                         free(cur);
2936                         return;
2937                 }
2938                 prev = cur;
2939                 cur = cur->next;
2940         }
2941 }
2942
2943 /* The src parameter allows us to peek forward to a possible &n syntax
2944  * for file descriptor duplication, e.g., "2>&1".
2945  * Return code is 0 normally, 1 if a syntax error is detected in src.
2946  * Resource errors (in xmalloc) cause the process to exit */
2947 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
2948         struct in_str *input)
2949 {
2950         struct command *command = ctx->command;
2951         struct redir_struct *redir = command->redirects;
2952         struct redir_struct *last_redir = NULL;
2953
2954         /* Create a new redir_struct and drop it onto the end of the linked list */
2955         while (redir) {
2956                 last_redir = redir;
2957                 redir = redir->next;
2958         }
2959         redir = xzalloc(sizeof(struct redir_struct));
2960         /* redir->next = NULL; */
2961         /* redir->rd_filename = NULL; */
2962         if (last_redir) {
2963                 last_redir->next = redir;
2964         } else {
2965                 command->redirects = redir;
2966         }
2967
2968         redir->rd_type = style;
2969         redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2970
2971         debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2972
2973         /* Check for a '2>&1' type redirect */
2974         redir->dup = redirect_dup_num(input);
2975         if (redir->dup == -2)
2976                 return 1;  /* syntax error */
2977         if (redir->dup != -1) {
2978                 /* Erik had a check here that the file descriptor in question
2979                  * is legit; I postpone that to "run time"
2980                  * A "-" representation of "close me" shows up as a -3 here */
2981                 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2982         } else {
2983                 /* We do _not_ try to open the file that src points to,
2984                  * since we need to return and let src be expanded first.
2985                  * Set ctx->pending_redirect, so we know what to do at the
2986                  * end of the next parsed word. */
2987                 ctx->pending_redirect = redir;
2988         }
2989         return 0;
2990 }
2991
2992 static struct pipe *new_pipe(void)
2993 {
2994         struct pipe *pi;
2995         pi = xzalloc(sizeof(struct pipe));
2996         /*pi->followup = 0; - deliberately invalid value */
2997         /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2998         return pi;
2999 }
3000
3001 static void initialize_context(struct parse_context *ctx)
3002 {
3003         memset(ctx, 0, sizeof(*ctx));
3004         ctx->pipe = ctx->list_head = new_pipe();
3005         /* Create the memory for command, roughly:
3006          * ctx->pipe->cmds = new struct command;
3007          * ctx->command = &ctx->pipe->cmds[0];
3008          */
3009         done_command(ctx);
3010 }
3011
3012 /* If a reserved word is found and processed, parse context is modified
3013  * and 1 is returned.
3014  * Handles if, then, elif, else, fi, for, while, until, do, done.
3015  * case, function, and select are obnoxious, save those for later.
3016  */
3017 #if HAS_KEYWORDS
3018 struct reserved_combo {
3019         char literal[6];
3020         unsigned char res;
3021         unsigned char assignment_flag;
3022         int flag;
3023 };
3024 enum {
3025         FLAG_END   = (1 << RES_NONE ),
3026 #if ENABLE_HUSH_IF
3027         FLAG_IF    = (1 << RES_IF   ),
3028         FLAG_THEN  = (1 << RES_THEN ),
3029         FLAG_ELIF  = (1 << RES_ELIF ),
3030         FLAG_ELSE  = (1 << RES_ELSE ),
3031         FLAG_FI    = (1 << RES_FI   ),
3032 #endif
3033 #if ENABLE_HUSH_LOOPS
3034         FLAG_FOR   = (1 << RES_FOR  ),
3035         FLAG_WHILE = (1 << RES_WHILE),
3036         FLAG_UNTIL = (1 << RES_UNTIL),
3037         FLAG_DO    = (1 << RES_DO   ),
3038         FLAG_DONE  = (1 << RES_DONE ),
3039         FLAG_IN    = (1 << RES_IN   ),
3040 #endif
3041 #if ENABLE_HUSH_CASE
3042         FLAG_MATCH = (1 << RES_MATCH),
3043         FLAG_ESAC  = (1 << RES_ESAC ),
3044 #endif
3045         FLAG_START = (1 << RES_XXXX ),
3046 };
3047
3048 static const struct reserved_combo* match_reserved_word(o_string *word)
3049 {
3050         /* Mostly a list of accepted follow-up reserved words.
3051          * FLAG_END means we are done with the sequence, and are ready
3052          * to turn the compound list into a command.
3053          * FLAG_START means the word must start a new compound list.
3054          */
3055         static const struct reserved_combo reserved_list[] = {
3056 #if ENABLE_HUSH_IF
3057                 { "!",     RES_NONE,  NOT_ASSIGNMENT , 0 },
3058                 { "if",    RES_IF,    WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3059                 { "then",  RES_THEN,  WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3060                 { "elif",  RES_ELIF,  WORD_IS_KEYWORD, FLAG_THEN },
3061                 { "else",  RES_ELSE,  WORD_IS_KEYWORD, FLAG_FI   },
3062                 { "fi",    RES_FI,    NOT_ASSIGNMENT , FLAG_END  },
3063 #endif
3064 #if ENABLE_HUSH_LOOPS
3065                 { "for",   RES_FOR,   NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3066                 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3067                 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3068                 { "in",    RES_IN,    NOT_ASSIGNMENT , FLAG_DO   },
3069                 { "do",    RES_DO,    WORD_IS_KEYWORD, FLAG_DONE },
3070                 { "done",  RES_DONE,  NOT_ASSIGNMENT , FLAG_END  },
3071 #endif
3072 #if ENABLE_HUSH_CASE
3073                 { "case",  RES_CASE,  NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3074                 { "esac",  RES_ESAC,  NOT_ASSIGNMENT , FLAG_END  },
3075 #endif
3076         };
3077         const struct reserved_combo *r;
3078
3079         for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3080                 if (strcmp(word->data, r->literal) == 0)
3081                         return r;
3082         }
3083         return NULL;
3084 }
3085 static int reserved_word(o_string *word, struct parse_context *ctx)
3086 {
3087 #if ENABLE_HUSH_CASE
3088         static const struct reserved_combo reserved_match = {
3089                 "",        RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3090         };
3091 #endif
3092         const struct reserved_combo *r;
3093
3094         r = match_reserved_word(word);
3095         if (!r)
3096                 return 0;
3097
3098         debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3099 #if ENABLE_HUSH_CASE
3100         if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3101                 /* "case word IN ..." - IN part starts first match part */
3102                 r = &reserved_match;
3103         else
3104 #endif
3105         if (r->flag == 0) { /* '!' */
3106                 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3107                         syntax(NULL);
3108                         IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3109                 }
3110                 ctx->ctx_inverted = 1;
3111                 return 1;
3112         }
3113         if (r->flag & FLAG_START) {
3114                 struct parse_context *new;
3115                 debug_printf("push stack\n");
3116                 new = xmalloc(sizeof(*new));
3117                 *new = *ctx;   /* physical copy */
3118                 initialize_context(ctx);
3119                 ctx->stack = new;
3120         } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3121                 syntax(NULL);
3122                 ctx->ctx_res_w = RES_SNTX;
3123                 return 1;
3124         }
3125         ctx->ctx_res_w = r->res;
3126         ctx->old_flag = r->flag;
3127         if (ctx->old_flag & FLAG_END) {
3128                 struct parse_context *old;
3129                 debug_printf("pop stack\n");
3130                 done_pipe(ctx, PIPE_SEQ);
3131                 old = ctx->stack;
3132                 old->command->group = ctx->list_head;
3133                 old->command->grp_type = GRP_NORMAL;
3134                 *ctx = *old;   /* physical copy */
3135                 free(old);
3136         }
3137         word->o_assignment = r->assignment_flag;
3138         return 1;
3139 }
3140 #endif
3141
3142 //TODO: many, many callers don't check error from done_word()
3143
3144 /* Word is complete, look at it and update parsing context.
3145  * Normal return is 0. Syntax errors return 1. */
3146 static int done_word(o_string *word, struct parse_context *ctx)
3147 {
3148         struct command *command = ctx->command;
3149
3150         debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3151         if (word->length == 0 && word->nonnull == 0) {
3152                 debug_printf_parse("done_word return 0: true null, ignored\n");
3153                 return 0;
3154         }
3155         /* If this word wasn't an assignment, next ones definitely
3156          * can't be assignments. Even if they look like ones. */
3157         if (word->o_assignment != DEFINITELY_ASSIGNMENT
3158          && word->o_assignment != WORD_IS_KEYWORD
3159         ) {
3160                 word->o_assignment = NOT_ASSIGNMENT;
3161         } else {
3162                 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3163                         command->assignment_cnt++;
3164                 word->o_assignment = MAYBE_ASSIGNMENT;
3165         }
3166
3167         if (ctx->pending_redirect) {
3168                 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3169                  * only if run as "bash", not "sh" */
3170                 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3171                 word->o_assignment = NOT_ASSIGNMENT;
3172                 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3173         } else {
3174                 /* "{ echo foo; } echo bar" - bad */
3175                 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3176                 if (command->group) {
3177                         syntax(NULL);
3178                         debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3179                         return 1;
3180                 }
3181 #if HAS_KEYWORDS
3182 #if ENABLE_HUSH_CASE
3183                 if (ctx->ctx_dsemicolon
3184                  && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3185                 ) {
3186                         /* already done when ctx_dsemicolon was set to 1: */
3187                         /* ctx->ctx_res_w = RES_MATCH; */
3188                         ctx->ctx_dsemicolon = 0;
3189                 } else
3190 #endif
3191
3192                 if (!command->argv /* if it's the first word... */
3193 #if ENABLE_HUSH_LOOPS
3194                  && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3195                  && ctx->ctx_res_w != RES_IN
3196 #endif
3197                 ) {
3198                         debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3199                         if (reserved_word(word, ctx)) {
3200                                 o_reset(word);
3201                                 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3202                                 return (ctx->ctx_res_w == RES_SNTX);
3203                         }
3204                 }
3205 #endif
3206                 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3207                  /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3208                  && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3209                  /* (otherwise it's known to be not empty and is already safe) */
3210                 ) {
3211                         /* exclude "$@" - it can expand to no word despite "" */
3212                         char *p = word->data;
3213                         while (p[0] == SPECIAL_VAR_SYMBOL
3214                             && (p[1] & 0x7f) == '@'
3215                             && p[2] == SPECIAL_VAR_SYMBOL
3216                         ) {
3217                                 p += 3;
3218                         }
3219                         if (p == word->data || p[0] != '\0') {
3220                                 /* saw no "$@", or not only "$@" but some
3221                                  * real text is there too */
3222                                 /* insert "empty variable" reference, this makes
3223                                  * e.g. "", $empty"" etc to not disappear */
3224                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3225                                 o_addchr(word, SPECIAL_VAR_SYMBOL);
3226                         }
3227                 }
3228                 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3229                 debug_print_strings("word appended to argv", command->argv);
3230         }
3231
3232         o_reset(word);
3233         ctx->pending_redirect = NULL;
3234
3235 #if ENABLE_HUSH_LOOPS
3236         /* Force FOR to have just one word (variable name) */
3237         /* NB: basically, this makes hush see "for v in ..." syntax as if
3238          * as it is "for v; in ...". FOR and IN become two pipe structs
3239          * in parse tree. */
3240         if (ctx->ctx_res_w == RES_FOR) {
3241 //TODO: check that command->argv[0] is a valid variable name!
3242                 done_pipe(ctx, PIPE_SEQ);
3243         }
3244 #endif
3245 #if ENABLE_HUSH_CASE
3246         /* Force CASE to have just one word */
3247         if (ctx->ctx_res_w == RES_CASE) {
3248                 done_pipe(ctx, PIPE_SEQ);
3249         }
3250 #endif
3251         debug_printf_parse("done_word return 0\n");
3252         return 0;
3253 }
3254
3255 /* Command (member of a pipe) is complete. The only possible error here
3256  * is out of memory, in which case xmalloc exits. */
3257 static int done_command(struct parse_context *ctx)
3258 {
3259         /* The command is really already in the pipe structure, so
3260          * advance the pipe counter and make a new, null command. */
3261         struct pipe *pi = ctx->pipe;
3262         struct command *command = ctx->command;
3263
3264         if (command) {
3265                 if (command->group == NULL
3266                  && command->argv == NULL
3267                  && command->redirects == NULL
3268                 ) {
3269                         debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3270                         return pi->num_cmds;
3271                 }
3272                 pi->num_cmds++;
3273                 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3274         } else {
3275                 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3276         }
3277
3278         /* Only real trickiness here is that the uncommitted
3279          * command structure is not counted in pi->num_cmds. */
3280         pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3281         command = &pi->cmds[pi->num_cmds];
3282         memset(command, 0, sizeof(*command));
3283
3284         ctx->command = command;
3285         /* but ctx->pipe and ctx->list_head remain unchanged */
3286
3287         return pi->num_cmds; /* used only for 0/nonzero check */
3288 }
3289
3290 static void done_pipe(struct parse_context *ctx, pipe_style type)
3291 {
3292         int not_null;
3293
3294         debug_printf_parse("done_pipe entered, followup %d\n", type);
3295         /* Close previous command */
3296         not_null = done_command(ctx);
3297         ctx->pipe->followup = type;
3298         IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3299         IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3300         IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3301
3302         /* Without this check, even just <enter> on command line generates
3303          * tree of three NOPs (!). Which is harmless but annoying.
3304          * IOW: it is safe to do it unconditionally.
3305          * RES_NONE case is for "for a in; do ..." (empty IN set)
3306          * to work, possibly other cases too. */
3307         if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3308                 struct pipe *new_p;
3309                 debug_printf_parse("done_pipe: adding new pipe: "
3310                                 "not_null:%d ctx->ctx_res_w:%d\n",
3311                                 not_null, ctx->ctx_res_w);
3312                 new_p = new_pipe();
3313                 ctx->pipe->next = new_p;
3314                 ctx->pipe = new_p;
3315                 ctx->command = NULL; /* needed! */
3316                 /* RES_THEN, RES_DO etc are "sticky" -
3317                  * they remain set for commands inside if/while.
3318                  * This is used to control execution.
3319                  * RES_FOR and RES_IN are NOT sticky (needed to support
3320                  * cases where variable or value happens to match a keyword):
3321                  */
3322 #if ENABLE_HUSH_LOOPS
3323                 if (ctx->ctx_res_w == RES_FOR
3324                  || ctx->ctx_res_w == RES_IN)
3325                         ctx->ctx_res_w = RES_NONE;
3326 #endif
3327 #if ENABLE_HUSH_CASE
3328                 if (ctx->ctx_res_w == RES_MATCH)
3329                         ctx->ctx_res_w = RES_CASEI;
3330 #endif
3331                 /* Create the memory for command, roughly:
3332                  * ctx->pipe->cmds = new struct command;
3333                  * ctx->command = &ctx->pipe->cmds[0];
3334                  */
3335                 done_command(ctx);
3336         }
3337         debug_printf_parse("done_pipe return\n");
3338 }
3339
3340 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3341  * as in "2>&1", that represents duplicating a file descriptor.
3342  * Return either -2 (syntax error), -1 (no &), or the number found.
3343  */
3344 static int redirect_dup_num(struct in_str *input)
3345 {
3346         int ch, d = 0, ok = 0;
3347         ch = i_peek(input);
3348         if (ch != '&') return -1;
3349
3350         i_getch(input);  /* get the & */
3351         ch = i_peek(input);
3352         if (ch == '-') {
3353                 i_getch(input);
3354                 return -3;  /* "-" represents "close me" */
3355         }
3356         while (isdigit(ch)) {
3357                 d = d*10 + (ch-'0');
3358                 ok = 1;
3359                 i_getch(input);
3360                 ch = i_peek(input);
3361         }
3362         if (ok) return d;
3363
3364         bb_error_msg("ambiguous redirect");
3365         return -2;
3366 }
3367
3368 /* If a redirect is immediately preceded by a number, that number is
3369  * supposed to tell which file descriptor to redirect.  This routine
3370  * looks for such preceding numbers.  In an ideal world this routine
3371  * needs to handle all the following classes of redirects...
3372  *     echo 2>foo     # redirects fd  2 to file "foo", nothing passed to echo
3373  *     echo 49>foo    # redirects fd 49 to file "foo", nothing passed to echo
3374  *     echo -2>foo    # redirects fd  1 to file "foo",    "-2" passed to echo
3375  *     echo 49x>foo   # redirects fd  1 to file "foo",   "49x" passed to echo
3376  * A -1 output from this program means no valid number was found, so the
3377  * caller should use the appropriate default for this redirection.
3378  */
3379 static int redirect_opt_num(o_string *o)
3380 {
3381         int num;
3382
3383         if (o->length == 0)
3384                 return -1;
3385         for (num = 0; num < o->length; num++) {
3386                 if (!isdigit(o->data[num])) {
3387                         return -1;
3388                 }
3389         }
3390         num = atoi(o->data);
3391         o_reset(o);
3392         return num;
3393 }
3394
3395 #if ENABLE_HUSH_TICK
3396 static FILE *generate_stream_from_list(struct pipe *head)
3397 {
3398         FILE *pf;
3399         int pid, channel[2];
3400
3401         xpipe(channel);
3402 /* *** NOMMU WARNING *** */
3403 /* By using vfork here, we suspend parent till child exits or execs.
3404  * If child will not do it before it fills the pipe, it can block forever
3405  * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3406  * Try this script:
3407  * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3408  * huge=`cat TESTFILE` # will block here forever
3409  * echo OK
3410  */
3411         pid = BB_MMU ? fork() : vfork();
3412         if (pid < 0)
3413                 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3414         if (pid == 0) { /* child */
3415                 if (ENABLE_HUSH_JOB)
3416                         die_sleep = 0; /* let nofork's xfuncs die */
3417                 close(channel[0]); /* NB: close _first_, then move fd! */
3418                 xmove_fd(channel[1], 1);
3419                 /* Prevent it from trying to handle ctrl-z etc */
3420 #if ENABLE_HUSH_JOB
3421                 G.run_list_level = 1;
3422 #endif
3423                 /* Process substitution is not considered to be usual
3424                  * 'command execution'.
3425                  * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3426                 /* Not needed, we are relying on it being disabled
3427                  * everywhere outside actual command execution. */
3428                 /*set_jobctrl_sighandler(SIG_IGN);*/
3429                 set_misc_sighandler(SIG_DFL);
3430                 /* Freeing 'head' here would break NOMMU. */
3431                 _exit(run_list(head));
3432         }
3433         close(channel[1]);
3434         pf = fdopen(channel[0], "r");
3435         return pf;
3436         /* 'head' is freed by the caller */
3437 }
3438
3439 /* Return code is exit status of the process that is run. */
3440 static int process_command_subs(o_string *dest,
3441                 struct in_str *input,
3442                 const char *subst_end)
3443 {
3444         int retcode, ch, eol_cnt;
3445         o_string result = NULL_O_STRING;
3446         struct parse_context inner;
3447         FILE *p;
3448         struct in_str pipe_str;
3449
3450         initialize_context(&inner);
3451
3452         /* Recursion to generate command */
3453         retcode = parse_stream(&result, &inner, input, subst_end);
3454         if (retcode != 0)
3455                 return retcode;  /* syntax error or EOF */
3456         done_word(&result, &inner);
3457         done_pipe(&inner, PIPE_SEQ);
3458         o_free(&result);
3459
3460         p = generate_stream_from_list(inner.list_head);
3461         if (p == NULL)
3462                 return 1;
3463         close_on_exec_on(fileno(p));
3464         setup_file_in_str(&pipe_str, p);
3465
3466         /* Now send results of command back into original context */
3467         eol_cnt = 0;
3468         while ((ch = i_getch(&pipe_str)) != EOF) {
3469                 if (ch == '\n') {
3470                         eol_cnt++;
3471                         continue;
3472                 }
3473                 while (eol_cnt) {
3474                         o_addchr(dest, '\n');
3475                         eol_cnt--;
3476                 }
3477                 o_addQchr(dest, ch);
3478         }
3479
3480         debug_printf("done reading from pipe, pclose()ing\n");
3481         /* This is the step that wait()s for the child.  Should be pretty
3482          * safe, since we just read an EOF from its stdout.  We could try
3483          * to do better, by using wait(), and keeping track of background jobs
3484          * at the same time.  That would be a lot of work, and contrary
3485          * to the KISS philosophy of this program. */
3486         retcode = fclose(p);
3487         free_pipe_list(inner.list_head, /* indent: */ 0);
3488         debug_printf("closed FILE from child, retcode=%d\n", retcode);
3489         return retcode;
3490 }
3491 #endif
3492
3493 static int parse_group(o_string *dest, struct parse_context *ctx,
3494         struct in_str *input, int ch)
3495 {
3496         /* dest contains characters seen prior to ( or {.
3497          * Typically it's empty, but for functions defs,
3498          * it contains function name (without '()'). */
3499         int rcode;
3500         const char *endch = NULL;
3501         struct parse_context sub;
3502         struct command *command = ctx->command;
3503
3504         debug_printf_parse("parse_group entered\n");
3505 #if ENABLE_HUSH_FUNCTIONS
3506         if (ch == 'F') { /* function definition? */
3507                 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3508                 //command->fname = dest->data;
3509                 command->grp_type = GRP_FUNCTION;
3510 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3511                 memset(dest, 0, sizeof(*dest));
3512         }
3513 #endif
3514         if (command->argv /* word [word](... */
3515          || dest->length /* word(... */
3516          || dest->nonnull /* ""(... */
3517         ) {
3518                 syntax(NULL);
3519                 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3520                 return 1;
3521         }
3522         initialize_context(&sub);
3523         endch = "}";
3524         if (ch == '(') {
3525                 endch = ")";
3526                 command->grp_type = GRP_SUBSHELL;
3527         }
3528         rcode = parse_stream(dest, &sub, input, endch);
3529         if (rcode == 0) {
3530                 done_word(dest, &sub); /* finish off the final word in the subcontext */
3531                 done_pipe(&sub, PIPE_SEQ);  /* and the final command there, too */
3532                 command->group = sub.list_head;
3533         }
3534         debug_printf_parse("parse_group return %d\n", rcode);
3535         return rcode;
3536         /* command remains "open", available for possible redirects */
3537 }
3538
3539 /* Basically useful version until someone wants to get fancier,
3540  * see the bash man page under "Parameter Expansion" */
3541 static const char *lookup_param(const char *src)
3542 {
3543         struct variable *var = get_local_var(src);
3544         if (var)
3545                 return strchr(var->varstr, '=') + 1;
3546         return NULL;
3547 }
3548
3549 #if ENABLE_HUSH_TICK
3550 /* Subroutines for copying $(...) and `...` things */
3551 static void add_till_backquote(o_string *dest, struct in_str *input);
3552 /* '...' */
3553 static void add_till_single_quote(o_string *dest, struct in_str *input)
3554 {
3555         while (1) {
3556                 int ch = i_getch(input);
3557                 if (ch == EOF)
3558                         break;
3559                 if (ch == '\'')
3560                         break;
3561                 o_addchr(dest, ch);
3562         }
3563 }
3564 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3565 static void add_till_double_quote(o_string *dest, struct in_str *input)
3566 {
3567         while (1) {
3568                 int ch = i_getch(input);
3569                 if (ch == '"')
3570                         break;
3571                 if (ch == '\\') {  /* \x. Copy both chars. */
3572                         o_addchr(dest, ch);
3573                         ch = i_getch(input);
3574                 }
3575                 if (ch == EOF)
3576                         break;
3577                 o_addchr(dest, ch);
3578                 if (ch == '`') {
3579                         add_till_backquote(dest, input);
3580                         o_addchr(dest, ch);
3581                         continue;
3582                 }
3583                 //if (ch == '$') ...
3584         }
3585 }
3586 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3587  * \` quoting.
3588  * "Within the backquoted style of command substitution, backslash
3589  * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3590  * The search for the matching backquote shall be satisfied by the first
3591  * backquote found without a preceding backslash; during this search,
3592  * if a non-escaped backquote is encountered within a shell comment,
3593  * a here-document, an embedded command substitution of the $(command)
3594  * form, or a quoted string, undefined results occur. A single-quoted
3595  * or double-quoted string that begins, but does not end, within the
3596  * "`...`" sequence produces undefined results."
3597  * Example                               Output
3598  * echo `echo '\'TEST\`echo ZZ\`BEST`    \TESTZZBEST
3599  */
3600 static void add_till_backquote(o_string *dest, struct in_str *input)
3601 {
3602         while (1) {
3603                 int ch = i_getch(input);
3604                 if (ch == '`')
3605                         break;
3606                 if (ch == '\\') {  /* \x. Copy both chars unless it is \` */
3607                         int ch2 = i_getch(input);
3608                         if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3609                                 o_addchr(dest, ch);
3610                         ch = ch2;
3611                 }
3612                 if (ch == EOF)
3613                         break;
3614                 o_addchr(dest, ch);
3615         }
3616 }
3617 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3618  * quoting and nested ()s.
3619  * "With the $(command) style of command substitution, all characters
3620  * following the open parenthesis to the matching closing parenthesis
3621  * constitute the command. Any valid shell script can be used for command,
3622  * except a script consisting solely of redirections which produces
3623  * unspecified results."
3624  * Example                              Output
3625  * echo $(echo '(TEST)' BEST)           (TEST) BEST
3626  * echo $(echo 'TEST)' BEST)            TEST) BEST
3627  * echo $(echo \(\(TEST\) BEST)         ((TEST) BEST
3628  */
3629 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3630 {
3631         int count = 0;
3632         while (1) {
3633                 int ch = i_getch(input);
3634                 if (ch == EOF)
3635                         break;
3636                 if (ch == '(')
3637                         count++;
3638                 if (ch == ')')
3639                         if (--count < 0)
3640                                 break;
3641                 o_addchr(dest, ch);
3642                 if (ch == '\'') {
3643                         add_till_single_quote(dest, input);
3644                         o_addchr(dest, ch);
3645                         continue;
3646                 }
3647                 if (ch == '"') {
3648                         add_till_double_quote(dest, input);
3649                         o_addchr(dest, ch);
3650                         continue;
3651                 }
3652                 if (ch == '\\') { /* \x. Copy verbatim. Important for  \(, \) */
3653                         ch = i_getch(input);
3654                         if (ch == EOF)
3655                                 break;
3656                         o_addchr(dest, ch);
3657                         continue;
3658                 }
3659         }
3660 }
3661 #endif /* ENABLE_HUSH_TICK */
3662
3663 /* Return code: 0 for OK, 1 for syntax error */
3664 static int handle_dollar(o_string *dest, struct in_str *input)
3665 {
3666         int ch = i_peek(input);  /* first character after the $ */
3667         unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3668
3669         debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3670         if (isalpha(ch)) {
3671                 i_getch(input);
3672  make_var:
3673                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3674                 while (1) {
3675                         debug_printf_parse(": '%c'\n", ch);
3676                         o_addchr(dest, ch | quote_mask);
3677                         quote_mask = 0;
3678                         ch = i_peek(input);
3679                         if (!isalnum(ch) && ch != '_')
3680                                 break;
3681                         i_getch(input);
3682                 }
3683                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3684         } else if (isdigit(ch)) {
3685  make_one_char_var:
3686                 i_getch(input);
3687                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3688                 debug_printf_parse(": '%c'\n", ch);
3689                 o_addchr(dest, ch | quote_mask);
3690                 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691         } else switch (ch) {
3692                 case '$': /* pid */
3693                 case '!': /* last bg pid */
3694                 case '?': /* last exit code */
3695                 case '#': /* number of args */
3696                 case '*': /* args */
3697                 case '@': /* args */
3698                         goto make_one_char_var;
3699                 case '{':
3700                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3701                         i_getch(input);
3702                         /* XXX maybe someone will try to escape the '}' */
3703                         while (1) {
3704                                 ch = i_getch(input);
3705                                 if (ch == '}')
3706                                         break;
3707                                 if (!isalnum(ch) && ch != '_') {
3708                                         syntax("unterminated ${name}");
3709                                         debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3710                                         return 1;
3711                                 }
3712                                 debug_printf_parse(": '%c'\n", ch);
3713                                 o_addchr(dest, ch | quote_mask);
3714                                 quote_mask = 0;
3715                         }
3716                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3717                         break;
3718 #if ENABLE_HUSH_TICK
3719                 case '(': {
3720                         //int pos = dest->length;
3721                         i_getch(input);
3722                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3723                         o_addchr(dest, quote_mask | '`');
3724                         add_till_closing_curly_brace(dest, input);
3725                         //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3726                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3727                         break;
3728                 }
3729 #endif
3730                 case '_':
3731                         i_getch(input);
3732                         ch = i_peek(input);
3733                         if (isalnum(ch)) { /* it's $_name or $_123 */
3734                                 ch = '_';
3735                                 goto make_var;
3736                         }
3737                         /* else: it's $_ */
3738                 case '-':
3739                         /* still unhandled, but should be eventually */
3740                         bb_error_msg("unhandled syntax: $%c", ch);
3741                         return 1;
3742                         break;
3743                 default:
3744                         o_addQchr(dest, '$');
3745         }
3746         debug_printf_parse("handle_dollar return 0\n");
3747         return 0;
3748 }
3749
3750 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3751  * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3752  * Return code is 0 if end_trigger char is met,
3753  * -1 on EOF (but if end_trigger == NULL then return 0),
3754  * 1 for syntax error */
3755 static int parse_stream(o_string *dest, struct parse_context *ctx,
3756         struct in_str *input, const char *end_trigger)
3757 {
3758         int ch, m;
3759         int redir_fd;
3760         redir_type redir_style;
3761         int shadow_quote = dest->o_quote;
3762         int next;
3763
3764         /* Only double-quote state is handled in the state variable dest->o_quote.
3765          * A single-quote triggers a bypass of the main loop until its mate is
3766          * found.  When recursing, quote state is passed in via dest->o_quote. */
3767
3768         debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3769
3770         while (1) {
3771                 m = CHAR_IFS;
3772                 next = '\0';
3773                 ch = i_getch(input);
3774                 if (ch != EOF) {
3775                         m = G.charmap[ch];
3776                         if (ch != '\n') {
3777                                 next = i_peek(input);
3778                         }
3779                 }
3780                 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3781                                                 ch, ch, m, dest->o_quote);
3782                 if (m == CHAR_ORDINARY
3783                  || (m != CHAR_SPECIAL && shadow_quote)
3784                 ) {
3785                         if (ch == EOF) {
3786                                 syntax("unterminated \"");
3787                                 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3788                                 return 1;
3789                         }
3790                         o_addQchr(dest, ch);
3791                         if ((dest->o_assignment == MAYBE_ASSIGNMENT
3792                             || dest->o_assignment == WORD_IS_KEYWORD)
3793                          && ch == '='
3794                          && is_assignment(dest->data)
3795                         ) {
3796                                 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3797                         }
3798                         continue;
3799                 }
3800                 if (m == CHAR_IFS) {
3801                         if (done_word(dest, ctx)) {
3802                                 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3803                                 return 1;
3804                         }
3805                         if (ch == EOF)
3806                                 break;
3807                         /* If we aren't performing a substitution, treat
3808                          * a newline as a command separator.
3809                          * [why we don't handle it exactly like ';'? --vda] */
3810                         if (end_trigger && ch == '\n') {
3811 #if ENABLE_HUSH_CASE
3812                                 /* "case ... in <newline> word) ..." -
3813                                  * newlines are ignored (but ';' wouldn't be) */
3814                                 if (dest->length == 0 // && argv[0] == NULL
3815                                  && ctx->ctx_res_w == RES_MATCH
3816                                 ) {
3817                                         continue;
3818                                 }
3819 #endif
3820                                 done_pipe(ctx, PIPE_SEQ);
3821                                 dest->o_assignment = MAYBE_ASSIGNMENT;
3822                         }
3823                 }
3824                 if (end_trigger) {
3825                         if (!shadow_quote && strchr(end_trigger, ch)) {
3826                                 /* Special case: (...word) makes last word terminate,
3827                                  * as if ';' is seen */
3828                                 if (ch == ')') {
3829                                         done_word(dest, ctx);
3830 //err chk?
3831                                         done_pipe(ctx, PIPE_SEQ);
3832                                         dest->o_assignment = MAYBE_ASSIGNMENT;
3833                                 }
3834                                 if (!HAS_KEYWORDS
3835                                  IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3836                                 ) {
3837                                         debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3838                                         return 0;
3839                                 }
3840                         }
3841                 }
3842                 if (m == CHAR_IFS)
3843                         continue;
3844
3845                 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3846                         /* ch is a special char and thus this word
3847                          * cannot be an assignment: */
3848                         dest->o_assignment = NOT_ASSIGNMENT;
3849                 }
3850
3851                 switch (ch) {
3852                 case '#':
3853                         if (dest->length == 0 && !shadow_quote) {
3854                                 while (1) {
3855                                         ch = i_peek(input);
3856                                         if (ch == EOF || ch == '\n')
3857                                                 break;
3858                                         i_getch(input);
3859                                 }
3860                         } else {
3861                                 o_addQchr(dest, ch);
3862                         }
3863                         break;
3864                 case '\\':
3865                         if (next == EOF) {
3866                                 syntax("\\<eof>");
3867                                 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3868                                 return 1;
3869                         }
3870                         /* bash:
3871                          * "The backslash retains its special meaning [in "..."]
3872                          * only when followed by one of the following characters:
3873                          * $, `, ", \, or <newline>.  A double quote may be quoted
3874                          * within double quotes by preceding it with a  backslash.
3875                          * If enabled, history expansion will be performed unless
3876                          * an ! appearing in double quotes is escaped using
3877                          * a backslash. The backslash preceding the ! is not removed."
3878                          */
3879                         if (shadow_quote) { //NOT SURE   dest->o_quote) {
3880                                 if (strchr("$`\"\\", next) != NULL) {
3881                                         o_addqchr(dest, i_getch(input));
3882                                 } else {
3883                                         o_addqchr(dest, '\\');
3884                                 }
3885                         } else {
3886                                 o_addchr(dest, '\\');
3887                                 o_addchr(dest, i_getch(input));
3888                         }
3889                         break;
3890                 case '$':
3891                         if (handle_dollar(dest, input) != 0) {
3892                                 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3893                                 return 1;
3894                         }
3895                         break;
3896                 case '\'':
3897                         dest->nonnull = 1;
3898                         while (1) {
3899                                 ch = i_getch(input);
3900                                 if (ch == EOF) {
3901                                         syntax("unterminated '");
3902                                         debug_printf_parse("parse_stream return 1: unterminated '\n");
3903                                         return 1;
3904                                 }
3905                                 if (ch == '\'')
3906                                         break;
3907                                 if (dest->o_assignment == NOT_ASSIGNMENT)
3908                                         o_addqchr(dest, ch);
3909                                 else
3910                                         o_addchr(dest, ch);
3911                         }
3912                         break;
3913                 case '"':
3914                         dest->nonnull = 1;
3915                         shadow_quote ^= 1; /* invert */
3916                         if (dest->o_assignment == NOT_ASSIGNMENT)
3917                                 dest->o_quote ^= 1;
3918                         break;
3919 #if ENABLE_HUSH_TICK
3920                 case '`': {
3921                         //int pos = dest->length;
3922                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3923                         o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
3924                         add_till_backquote(dest, input);
3925                         o_addchr(dest, SPECIAL_VAR_SYMBOL);
3926                         //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3927                         break;
3928                 }
3929 #endif
3930                 case '>':
3931                         redir_fd = redirect_opt_num(dest);
3932                         done_word(dest, ctx);
3933                         redir_style = REDIRECT_OVERWRITE;
3934                         if (next == '>') {
3935                                 redir_style = REDIRECT_APPEND;
3936                                 i_getch(input);
3937                         }
3938 #if 0
3939                         else if (next == '(') {
3940                                 syntax(">(process) not supported");
3941                                 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3942                                 return 1;
3943                         }
3944 #endif
3945                         setup_redirect(ctx, redir_fd, redir_style, input);
3946                         break;
3947                 case '<':
3948                         redir_fd = redirect_opt_num(dest);
3949                         done_word(dest, ctx);
3950                         redir_style = REDIRECT_INPUT;
3951                         if (next == '<') {
3952                                 redir_style = REDIRECT_HEREIS;
3953                                 i_getch(input);
3954                         } else if (next == '>') {
3955                                 redir_style = REDIRECT_IO;
3956                                 i_getch(input);
3957                         }
3958 #if 0
3959                         else if (next == '(') {
3960                                 syntax("<(process) not supported");
3961                                 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3962                                 return 1;
3963                         }
3964 #endif
3965                         setup_redirect(ctx, redir_fd, redir_style, input);
3966                         break;
3967                 case ';':
3968 #if ENABLE_HUSH_CASE
3969  case_semi:
3970 #endif
3971                         done_word(dest, ctx);
3972                         done_pipe(ctx, PIPE_SEQ);
3973 #if ENABLE_HUSH_CASE
3974                         /* Eat multiple semicolons, detect
3975                          * whether it means something special */
3976                         while (1) {
3977                                 ch = i_peek(input);
3978                                 if (ch != ';')
3979                                         break;
3980                                 i_getch(input);
3981                                 if (ctx->ctx_res_w == RES_CASEI) {
3982                                         ctx->ctx_dsemicolon = 1;
3983                                         ctx->ctx_res_w = RES_MATCH;
3984                                         break;
3985                                 }
3986                         }
3987 #endif
3988  new_cmd:
3989                         /* We just finished a cmd. New one may start
3990                          * with an assignment */
3991                         dest->o_assignment = MAYBE_ASSIGNMENT;
3992                         break;
3993                 case '&':
3994                         done_word(dest, ctx);
3995                         if (next == '&') {
3996                                 i_getch(input);
3997                                 done_pipe(ctx, PIPE_AND);
3998                         } else {
3999                                 done_pipe(ctx, PIPE_BG);
4000                         }
4001                         goto new_cmd;
4002                 case '|':
4003                         done_word(dest, ctx);
4004 #if ENABLE_HUSH_CASE
4005                         if (ctx->ctx_res_w == RES_MATCH)
4006                                 break; /* we are in case's "word | word)" */
4007 #endif
4008                         if (next == '|') { /* || */
4009                                 i_getch(input);
4010                                 done_pipe(ctx, PIPE_OR);
4011                         } else {
4012                                 /* we could pick up a file descriptor choice here
4013                                  * with redirect_opt_num(), but bash doesn't do it.
4014                                  * "echo foo 2| cat" yields "foo 2". */
4015                                 done_command(ctx);
4016                         }
4017                         goto new_cmd;
4018                 case '(':
4019 #if ENABLE_HUSH_CASE
4020                         /* "case... in [(]word)..." - skip '(' */
4021                         if (ctx->ctx_res_w == RES_MATCH
4022                          && ctx->command->argv == NULL /* not (word|(... */
4023                          && dest->length == 0 /* not word(... */
4024                          && dest->nonnull == 0 /* not ""(... */
4025                         ) {
4026                                 continue;
4027                         }
4028 #endif
4029 #if ENABLE_HUSH_FUNCTIONS
4030                         if (dest->length != 0 /* not just () but word() */
4031                          && dest->nonnull == 0 /* not a"b"c() */
4032                          && ctx->command->argv == NULL /* it's the first word */
4033 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4034                          && i_peek(input) == ')'
4035                          && !match_reserved_word(dest)
4036                         ) {
4037                                 bb_error_msg("seems like a function definition");
4038                                 i_getch(input);
4039                                 do {
4040 //TODO: do it properly.
4041                                         ch = i_getch(input);
4042                                 } while (ch == ' ' || ch == '\n');
4043                                 if (ch != '{') {
4044                                         syntax("was expecting {");
4045                                         debug_printf_parse("parse_stream return 1\n");
4046                                         return 1;
4047                                 }
4048                                 ch = 'F'; /* magic value */
4049                         }
4050 #endif
4051                 case '{':
4052                         if (parse_group(dest, ctx, input, ch) != 0) {
4053                                 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4054                                 return 1;
4055                         }
4056                         goto new_cmd;
4057                 case ')':
4058 #if ENABLE_HUSH_CASE
4059                         if (ctx->ctx_res_w == RES_MATCH)
4060                                 goto case_semi;
4061 #endif
4062                 case '}':
4063                         /* proper use of this character is caught by end_trigger:
4064                          * if we see {, we call parse_group(..., end_trigger='}')
4065                          * and it will match } earlier (not here). */
4066                         syntax("unexpected } or )");
4067                         debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4068                         return 1;
4069                 default:
4070                         if (HUSH_DEBUG)
4071                                 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4072                 }
4073         } /* while (1) */
4074         debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4075         if (end_trigger)
4076                 return -1;
4077         return 0;
4078 }
4079
4080 static void set_in_charmap(const char *set, int code)
4081 {
4082         while (*set)
4083                 G.charmap[(unsigned char)*set++] = code;
4084 }
4085
4086 static void update_charmap(void)
4087 {
4088         G.ifs = getenv("IFS");
4089         if (G.ifs == NULL)
4090                 G.ifs = " \t\n";
4091         /* Precompute a list of 'flow through' behavior so it can be treated
4092          * quickly up front.  Computation is necessary because of IFS.
4093          * Special case handling of IFS == " \t\n" is not implemented.
4094          * The charmap[] array only really needs two bits each,
4095          * and on most machines that would be faster (reduced L1 cache use).
4096          */
4097         memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4098 #if ENABLE_HUSH_TICK
4099         set_in_charmap("\\$\"`", CHAR_SPECIAL);
4100 #else
4101         set_in_charmap("\\$\"", CHAR_SPECIAL);
4102 #endif
4103         set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4104         set_in_charmap(G.ifs, CHAR_IFS);  /* are ordinary if quoted */
4105 }
4106
4107 /* Most recursion does not come through here, the exception is
4108  * from builtin_source() and builtin_eval() */
4109 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4110 {
4111         struct parse_context ctx;
4112         o_string temp = NULL_O_STRING;
4113         int rcode;
4114
4115         do {
4116                 initialize_context(&ctx);
4117                 update_charmap();
4118 #if ENABLE_HUSH_INTERACTIVE
4119                 inp->promptmode = 0; /* PS1 */
4120 #endif
4121                 /* We will stop & execute after each ';' or '\n'.
4122                  * Example: "sleep 9999; echo TEST" + ctrl-C:
4123                  * TEST should be printed */
4124                 temp.o_assignment = MAYBE_ASSIGNMENT;
4125                 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4126 #if HAS_KEYWORDS
4127                 if (rcode != 1 && ctx.old_flag != 0) {
4128                         syntax(NULL);
4129                 }
4130 #endif
4131                 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4132                         done_word(&temp, &ctx);
4133                         done_pipe(&ctx, PIPE_SEQ);
4134                         debug_print_tree(ctx.list_head, 0);
4135                         debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4136                         run_and_free_list(ctx.list_head);
4137                 } else {
4138                         /* We arrive here also if rcode == 1 (error in parse_stream) */
4139 #if HAS_KEYWORDS
4140                         if (ctx.old_flag != 0) {
4141                                 free(ctx.stack);
4142                                 o_reset(&temp);
4143                         }
4144 #endif
4145                         /*temp.nonnull = 0; - o_free does it below */
4146                         /*temp.o_quote = 0; - o_free does it below */
4147                         free_pipe_list(ctx.list_head, /* indent: */ 0);
4148                         /* Discard all unprocessed line input, force prompt on */
4149                         inp->p = NULL;
4150 #if ENABLE_HUSH_INTERACTIVE
4151                         inp->promptme = 1;
4152 #endif
4153                 }
4154                 o_free(&temp);
4155                 /* loop on syntax errors, return on EOF: */
4156         } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4157         return 0;
4158 }
4159
4160 static int parse_and_run_string(const char *s, int parse_flag)
4161 {
4162         struct in_str input;
4163         setup_string_in_str(&input, s);
4164         return parse_and_run_stream(&input, parse_flag);
4165 }
4166
4167 static int parse_and_run_file(FILE *f)
4168 {
4169         int rcode;
4170         struct in_str input;
4171         setup_file_in_str(&input, f);
4172         rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4173         return rcode;
4174 }
4175
4176 #if ENABLE_HUSH_JOB
4177 /* Make sure we have a controlling tty.  If we get started under a job
4178  * aware app (like bash for example), make sure we are now in charge so
4179  * we don't fight over who gets the foreground */
4180 static void setup_job_control(void)
4181 {
4182         pid_t shell_pgrp;
4183
4184         shell_pgrp = getpgrp();
4185         close_on_exec_on(G.interactive_fd);
4186
4187         /* If we were ran as 'hush &',
4188          * sleep until we are in the foreground.  */
4189         while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4190                 /* Send TTIN to ourself (should stop us) */
4191                 kill(- shell_pgrp, SIGTTIN);
4192                 shell_pgrp = getpgrp();
4193         }
4194
4195         /* Ignore job-control and misc signals.  */
4196         set_jobctrl_sighandler(SIG_IGN);
4197         set_misc_sighandler(SIG_IGN);
4198 //huh?  signal(SIGCHLD, SIG_IGN);
4199
4200         /* We _must_ restore tty pgrp on fatal signals */
4201         set_fatal_sighandler(sigexit);
4202
4203         /* Put ourselves in our own process group.  */
4204         bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4205         /* Grab control of the terminal.  */
4206         tcsetpgrp(G.interactive_fd, getpid());
4207 }
4208 #endif
4209
4210
4211 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4212 int hush_main(int argc, char **argv)
4213 {
4214         static const struct variable const_shell_ver = {
4215                 .next = NULL,
4216                 .varstr = (char*)hush_version_str,
4217                 .max_len = 1, /* 0 can provoke free(name) */
4218                 .flg_export = 1,
4219                 .flg_read_only = 1,
4220         };
4221
4222         int opt;
4223         FILE *input;
4224         char **e;
4225         struct variable *cur_var;
4226
4227         INIT_G();
4228
4229         G.root_pid = getpid();
4230
4231         /* Deal with HUSH_VERSION */
4232         G.shell_ver = const_shell_ver; /* copying struct here */
4233         G.top_var = &G.shell_ver;
4234         debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4235         unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4236         /* Initialize our shell local variables with the values
4237          * currently living in the environment */
4238         cur_var = G.top_var;
4239         e = environ;
4240         if (e) while (*e) {
4241                 char *value = strchr(*e, '=');
4242                 if (value) { /* paranoia */
4243                         cur_var->next = xzalloc(sizeof(*cur_var));
4244                         cur_var = cur_var->next;
4245                         cur_var->varstr = *e;
4246                         cur_var->max_len = strlen(*e);
4247                         cur_var->flg_export = 1;
4248                 }
4249                 e++;
4250         }
4251         debug_printf_env("putenv '%s'\n", hush_version_str);
4252         putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4253
4254 #if ENABLE_FEATURE_EDITING
4255         G.line_input_state = new_line_input_t(FOR_SHELL);
4256 #endif
4257         /* XXX what should these be while sourcing /etc/profile? */
4258         G.global_argc = argc;
4259         G.global_argv = argv;
4260         /* Initialize some more globals to non-zero values */
4261         set_cwd();
4262 #if ENABLE_HUSH_INTERACTIVE
4263 #if ENABLE_FEATURE_EDITING
4264         cmdedit_set_initial_prompt();
4265 #endif
4266         G.PS2 = "> ";
4267 #endif
4268
4269         if (EXIT_SUCCESS) /* otherwise is already done */
4270                 G.last_return_code = EXIT_SUCCESS;
4271
4272         if (argv[0] && argv[0][0] == '-') {
4273                 debug_printf("sourcing /etc/profile\n");
4274                 input = fopen_for_read("/etc/profile");
4275                 if (input != NULL) {
4276                         close_on_exec_on(fileno(input));
4277                         parse_and_run_file(input);
4278                         fclose(input);
4279                 }
4280         }
4281         input = stdin;
4282
4283         while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4284                 switch (opt) {
4285                 case 'c':
4286                         G.global_argv = argv + optind;
4287                         G.global_argc = argc - optind;
4288                         opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4289                         goto final_return;
4290                 case 'i':
4291                         /* Well, we cannot just declare interactiveness,
4292                          * we have to have some stuff (ctty, etc) */
4293                         /* G.interactive_fd++; */
4294                         break;
4295                 case 'f':
4296                         G.fake_mode = 1;
4297                         break;
4298                 default:
4299 #ifndef BB_VER
4300                         fprintf(stderr, "Usage: sh [FILE]...\n"
4301                                         "   or: sh -c command [args]...\n\n");
4302                         exit(EXIT_FAILURE);
4303 #else
4304                         bb_show_usage();
4305 #endif
4306                 }
4307         }
4308 #if ENABLE_HUSH_JOB
4309         /* A shell is interactive if the '-i' flag was given, or if all of
4310          * the following conditions are met:
4311          *    no -c command
4312          *    no arguments remaining or the -s flag given
4313          *    standard input is a terminal
4314          *    standard output is a terminal
4315          *    Refer to Posix.2, the description of the 'sh' utility. */
4316         if (argv[optind] == NULL && input == stdin
4317          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4318         ) {
4319                 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4320                 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4321                 if (G.saved_tty_pgrp >= 0) {
4322                         /* try to dup to high fd#, >= 255 */
4323                         G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4324                         if (G.interactive_fd < 0) {
4325                                 /* try to dup to any fd */
4326                                 G.interactive_fd = dup(STDIN_FILENO);
4327                                 if (G.interactive_fd < 0)
4328                                         /* give up */
4329                                         G.interactive_fd = 0;
4330                         }
4331                         // TODO: track & disallow any attempts of user
4332                         // to (inadvertently) close/redirect it
4333                 }
4334         }
4335         debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4336         if (G.interactive_fd) {
4337                 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4338                 /* Looks like they want an interactive shell */
4339                 setup_job_control();
4340                 /* -1 is special - makes xfuncs longjmp, not exit
4341                  * (we reset die_sleep = 0 whereever we [v]fork) */
4342                 die_sleep = -1;
4343                 if (setjmp(die_jmp)) {
4344                         /* xfunc has failed! die die die */
4345                         hush_exit(xfunc_error_retval);
4346                 }
4347 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
4348                 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4349                 printf("Enter 'help' for a list of built-in commands.\n\n");
4350 #endif
4351         }
4352 #elif ENABLE_HUSH_INTERACTIVE
4353 /* no job control compiled, only prompt/line editing */
4354         if (argv[optind] == NULL && input == stdin
4355          && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4356         ) {
4357                 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4358                 if (G.interactive_fd < 0) {
4359                         /* try to dup to any fd */
4360                         G.interactive_fd = dup(STDIN_FILENO);
4361                         if (G.interactive_fd < 0)
4362                                 /* give up */
4363                                 G.interactive_fd = 0;
4364                 }
4365                 if (G.interactive_fd) {
4366                         fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4367                         set_misc_sighandler(SIG_IGN);
4368                 }
4369         }
4370 #endif
4371
4372         if (argv[optind] == NULL) {
4373                 opt = parse_and_run_file(stdin);
4374         } else {
4375                 debug_printf("\nrunning script '%s'\n", argv[optind]);
4376                 G.global_argv = argv + optind;
4377                 G.global_argc = argc - optind;
4378                 input = xfopen_for_read(argv[optind]);
4379                 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4380                 opt = parse_and_run_file(input);
4381         }
4382
4383  final_return:
4384
4385 #if ENABLE_FEATURE_CLEAN_UP
4386         fclose(input);
4387         if (G.cwd != bb_msg_unknown)
4388                 free((char*)G.cwd);
4389         cur_var = G.top_var->next;
4390         while (cur_var) {
4391                 struct variable *tmp = cur_var;
4392                 if (!cur_var->max_len)
4393                         free(cur_var->varstr);
4394                 cur_var = cur_var->next;
4395                 free(tmp);
4396         }
4397 #endif
4398         hush_exit(opt ? opt : G.last_return_code);
4399 }
4400
4401
4402 #if ENABLE_LASH
4403 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4404 int lash_main(int argc, char **argv)
4405 {
4406         //bb_error_msg("lash is deprecated, please use hush instead");
4407         return hush_main(argc, argv);
4408 }
4409 #endif
4410
4411
4412 /*
4413  * Built-ins
4414  */
4415 static int builtin_true(char **argv UNUSED_PARAM)
4416 {
4417         return 0;
4418 }
4419
4420 static int builtin_test(char **argv)
4421 {
4422         int argc = 0;
4423         while (*argv) {
4424                 argc++;
4425                 argv++;
4426         }
4427         return test_main(argc, argv - argc);
4428 }
4429
4430 static int builtin_echo(char **argv)
4431 {
4432         int argc = 0;
4433         while (*argv) {
4434                 argc++;
4435                 argv++;
4436         }
4437         return echo_main(argc, argv - argc);
4438 }
4439
4440 static int builtin_eval(char **argv)
4441 {
4442         int rcode = EXIT_SUCCESS;
4443
4444         if (argv[1]) {
4445                 char *str = expand_strvec_to_string(argv + 1);
4446                 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4447                 free(str);
4448                 rcode = G.last_return_code;
4449         }
4450         return rcode;
4451 }
4452
4453 static int builtin_cd(char **argv)
4454 {
4455         const char *newdir;
4456         if (argv[1] == NULL) {
4457                 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4458                 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4459                 newdir = getenv("HOME") ? : "/";
4460         } else
4461                 newdir = argv[1];
4462         if (chdir(newdir)) {
4463                 printf("cd: %s: %s\n", newdir, strerror(errno));
4464                 return EXIT_FAILURE;
4465         }
4466         set_cwd();
4467         return EXIT_SUCCESS;
4468 }
4469
4470 static int builtin_exec(char **argv)
4471 {
4472         if (argv[1] == NULL)
4473                 return EXIT_SUCCESS; /* bash does this */
4474         {
4475 #if !BB_MMU
4476                 nommu_save_t dummy;
4477 #endif
4478 // FIXME: if exec fails, bash does NOT exit! We do...
4479                 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4480                 /* never returns */
4481         }
4482 }
4483
4484 static int builtin_exit(char **argv)
4485 {
4486 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4487         //puts("exit"); /* bash does it */
4488 // TODO: warn if we have background jobs: "There are stopped jobs"
4489 // On second consecutive 'exit', exit anyway.
4490         if (argv[1] == NULL)
4491                 hush_exit(G.last_return_code);
4492         /* mimic bash: exit 123abc == exit 255 + error msg */
4493         xfunc_error_retval = 255;
4494         /* bash: exit -2 == exit 254, no error msg */
4495         hush_exit(xatoi(argv[1]) & 0xff);
4496 }
4497
4498 static int builtin_export(char **argv)
4499 {
4500         const char *value;
4501         char *name = argv[1];
4502
4503         if (name == NULL) {
4504                 // TODO:
4505                 // ash emits: export VAR='VAL'
4506                 // bash: declare -x VAR="VAL"
4507                 // (both also escape as needed (quotes, $, etc))
4508                 char **e = environ;
4509                 if (e)
4510                         while (*e)
4511                                 puts(*e++);
4512                 return EXIT_SUCCESS;
4513         }
4514
4515         value = strchr(name, '=');
4516         if (!value) {
4517                 /* They are exporting something without a =VALUE */
4518                 struct variable *var;
4519
4520                 var = get_local_var(name);
4521                 if (var) {
4522                         var->flg_export = 1;
4523                         debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4524                         putenv(var->varstr);
4525                 }
4526                 /* bash does not return an error when trying to export
4527                  * an undefined variable.  Do likewise. */
4528                 return EXIT_SUCCESS;
4529         }
4530
4531         set_local_var(xstrdup(name), 1);
4532         return EXIT_SUCCESS;
4533 }
4534
4535 #if ENABLE_HUSH_JOB
4536 /* built-in 'fg' and 'bg' handler */
4537 static int builtin_fg_bg(char **argv)
4538 {
4539         int i, jobnum;
4540         struct pipe *pi;
4541
4542         if (!G.interactive_fd)
4543                 return EXIT_FAILURE;
4544         /* If they gave us no args, assume they want the last backgrounded task */
4545         if (!argv[1]) {
4546                 for (pi = G.job_list; pi; pi = pi->next) {
4547                         if (pi->jobid == G.last_jobid) {
4548                                 goto found;
4549                         }
4550                 }
4551                 bb_error_msg("%s: no current job", argv[0]);
4552                 return EXIT_FAILURE;
4553         }
4554         if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4555                 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4556                 return EXIT_FAILURE;
4557         }
4558         for (pi = G.job_list; pi; pi = pi->next) {
4559                 if (pi->jobid == jobnum) {
4560                         goto found;
4561                 }
4562         }
4563         bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4564         return EXIT_FAILURE;
4565  found:
4566         // TODO: bash prints a string representation
4567         // of job being foregrounded (like "sleep 1 | cat")
4568         if (*argv[0] == 'f') {
4569                 /* Put the job into the foreground.  */
4570                 tcsetpgrp(G.interactive_fd, pi->pgrp);
4571         }
4572
4573         /* Restart the processes in the job */
4574         debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4575         for (i = 0; i < pi->num_cmds; i++) {
4576                 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4577                 pi->cmds[i].is_stopped = 0;
4578         }
4579         pi->stopped_cmds = 0;
4580
4581         i = kill(- pi->pgrp, SIGCONT);
4582         if (i < 0) {
4583                 if (errno == ESRCH) {
4584                         delete_finished_bg_job(pi);
4585                         return EXIT_SUCCESS;
4586                 } else {
4587                         bb_perror_msg("kill (SIGCONT)");
4588                 }
4589         }
4590
4591         if (*argv[0] == 'f') {
4592                 remove_bg_job(pi);
4593                 return checkjobs_and_fg_shell(pi);
4594         }
4595         return EXIT_SUCCESS;
4596 }
4597 #endif
4598
4599 #if ENABLE_HUSH_HELP
4600 static int builtin_help(char **argv UNUSED_PARAM)
4601 {
4602         const struct built_in_command *x;
4603
4604         printf("\nBuilt-in commands:\n");
4605         printf("-------------------\n");
4606         for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4607                 printf("%s\t%s\n", x->cmd, x->descr);
4608         }
4609         printf("\n\n");
4610         return EXIT_SUCCESS;
4611 }
4612 #endif
4613
4614 #if ENABLE_HUSH_JOB
4615 static int builtin_jobs(char **argv UNUSED_PARAM)
4616 {
4617         struct pipe *job;
4618         const char *status_string;
4619
4620         for (job = G.job_list; job; job = job->next) {
4621                 if (job->alive_cmds == job->stopped_cmds)
4622                         status_string = "Stopped";
4623                 else
4624                         status_string = "Running";
4625
4626                 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4627         }
4628         return EXIT_SUCCESS;
4629 }
4630 #endif
4631
4632 static int builtin_pwd(char **argv UNUSED_PARAM)
4633 {
4634         puts(set_cwd());
4635         return EXIT_SUCCESS;
4636 }
4637
4638 static int builtin_read(char **argv)
4639 {
4640         char *string;
4641         const char *name = argv[1] ? argv[1] : "REPLY";
4642
4643         string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4644         return set_local_var(string, 0);
4645 }
4646
4647 /* built-in 'set [VAR=value]' handler */
4648 static int builtin_set(char **argv)
4649 {
4650         char *temp = argv[1];
4651         struct variable *e;
4652
4653         if (temp == NULL)
4654                 for (e = G.top_var; e; e = e->next)
4655                         puts(e->varstr);
4656         else
4657                 set_local_var(xstrdup(temp), 0);
4658
4659         return EXIT_SUCCESS;
4660 }
4661
4662 static int builtin_shift(char **argv)
4663 {
4664         int n = 1;
4665         if (argv[1]) {
4666                 n = atoi(argv[1]);
4667         }
4668         if (n >= 0 && n < G.global_argc) {
4669                 G.global_argv[n] = G.global_argv[0];
4670                 G.global_argc -= n;
4671                 G.global_argv += n;
4672                 return EXIT_SUCCESS;
4673         }
4674         return EXIT_FAILURE;
4675 }
4676
4677 static int builtin_source(char **argv)
4678 {
4679         FILE *input;
4680         int status;
4681
4682         if (argv[1] == NULL)
4683                 return EXIT_FAILURE;
4684
4685         /* XXX search through $PATH is missing */
4686         input = fopen_for_read(argv[1]);
4687         if (!input) {
4688                 bb_error_msg("can't open '%s'", argv[1]);
4689                 return EXIT_FAILURE;
4690         }
4691         close_on_exec_on(fileno(input));
4692
4693         /* Now run the file */
4694         /* XXX argv and argc are broken; need to save old G.global_argv
4695          * (pointer only is OK!) on this stack frame,
4696          * set G.global_argv=argv+1, recurse, and restore. */
4697         status = parse_and_run_file(input);
4698         fclose(input);
4699         return status;
4700 }
4701
4702 static int builtin_umask(char **argv)
4703 {
4704         mode_t new_umask;
4705         const char *arg = argv[1];
4706         char *end;
4707         if (arg) {
4708                 new_umask = strtoul(arg, &end, 8);
4709                 if (*end != '\0' || end == arg) {
4710                         return EXIT_FAILURE;
4711                 }
4712         } else {
4713                 new_umask = umask(0);
4714                 printf("%.3o\n", (unsigned) new_umask);
4715         }
4716         umask(new_umask);
4717         return EXIT_SUCCESS;
4718 }
4719
4720 static int builtin_unset(char **argv)
4721 {
4722         /* bash always returns true */
4723         unset_local_var(argv[1]);
4724         return EXIT_SUCCESS;
4725 }
4726
4727 #if ENABLE_HUSH_LOOPS
4728 static int builtin_break(char **argv)
4729 {
4730         if (G.depth_of_loop == 0) {
4731                 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4732                 return EXIT_SUCCESS; /* bash compat */
4733         }
4734         G.flag_break_continue++; /* BC_BREAK = 1 */
4735         G.depth_break_continue = 1;
4736         if (argv[1]) {
4737                 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4738                 if (errno || !G.depth_break_continue || argv[2]) {
4739                         bb_error_msg("%s: bad arguments", argv[0]);
4740                         G.flag_break_continue = BC_BREAK;
4741                         G.depth_break_continue = UINT_MAX;
4742                 }
4743         }
4744         if (G.depth_of_loop < G.depth_break_continue)
4745                 G.depth_break_continue = G.depth_of_loop;
4746         return EXIT_SUCCESS;
4747 }
4748
4749 static int builtin_continue(char **argv)
4750 {
4751         G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4752         return builtin_break(argv);
4753 }
4754 #endif