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