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