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