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