1 /* vi: set sw=4 ts=4: */
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.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
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
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
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.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy (improved --vda)
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change map[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
83 /* #include <dmalloc.h> */
86 /* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
88 #define debug_printf(...) do {} while (0)
89 /* Finer-grained debug switches */
90 #define debug_printf_parse(...) do {} while (0)
91 #define debug_print_tree(a, b) do {} while (0)
92 #define debug_printf_exec(...) do {} while (0)
93 #define debug_printf_jobs(...) do {} while (0)
94 #define debug_printf_clean(...) do {} while (0)
97 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
100 #ifndef debug_printf_parse
101 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
104 #ifndef debug_printf_exec
105 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
108 #ifndef debug_printf_jobs
109 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
110 #define DEBUG_SHELL_JOBS 1
113 #ifndef debug_printf_clean
114 /* broken, of course, but OK for testing */
115 static const char *indenter(int i)
117 static const char blanks[] = " ";
118 return &blanks[sizeof(blanks) - i - 1];
120 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
124 #if !ENABLE_HUSH_INTERACTIVE
125 #undef ENABLE_FEATURE_EDITING
126 #define ENABLE_FEATURE_EDITING 0
127 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
128 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
131 #define SPECIAL_VAR_SYMBOL 3
132 #define FLAG_EXIT_FROM_LOOP 1
133 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
134 #define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
138 REDIRECT_OVERWRITE = 2,
144 /* The descrip member of this structure is only used to make debugging
146 static const struct {
148 signed char default_fd;
152 { O_RDONLY, 0, "<" },
153 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
154 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
155 { O_RDONLY, -1, "<<" },
166 /* might eventually control execution */
184 FLAG_END = (1 << RES_NONE ),
185 FLAG_IF = (1 << RES_IF ),
186 FLAG_THEN = (1 << RES_THEN ),
187 FLAG_ELIF = (1 << RES_ELIF ),
188 FLAG_ELSE = (1 << RES_ELSE ),
189 FLAG_FI = (1 << RES_FI ),
190 FLAG_FOR = (1 << RES_FOR ),
191 FLAG_WHILE = (1 << RES_WHILE),
192 FLAG_UNTIL = (1 << RES_UNTIL),
193 FLAG_DO = (1 << RES_DO ),
194 FLAG_DONE = (1 << RES_DONE ),
195 FLAG_IN = (1 << RES_IN ),
196 FLAG_START = (1 << RES_XXXX ),
199 /* This holds pointers to the various results of parsing */
201 struct child_prog *child;
202 struct pipe *list_head;
204 struct redir_struct *pending_redirect;
205 reserved_style res_w;
206 int old_flag; /* for figuring out valid reserved words */
207 struct p_context *stack;
208 int parse_type; /* define type of parser : ";$" common or special symbol */
209 /* How about quoting status? */
212 struct redir_struct {
213 struct redir_struct *next; /* pointer to the next redirect in the list */
214 redir_type type; /* type of redirection */
215 int fd; /* file descriptor being redirected */
216 int dup; /* -1, or file descriptor being duplicated */
217 glob_t word; /* *word.gl_pathv is the filename */
221 pid_t pid; /* 0 if exited */
222 char **argv; /* program name and arguments */
223 struct pipe *group; /* if non-NULL, first in group or subshell */
224 int subshell; /* flag, non-zero if group must be forked */
225 struct redir_struct *redirects; /* I/O redirections */
226 glob_t glob_result; /* result of parameter globbing */
227 int is_stopped; /* is the program currently running? */
228 struct pipe *family; /* pointer back to the child's parent pipe */
229 int sp; /* number of SPECIAL_VAR_SYMBOL */
235 int num_progs; /* total number of programs in job */
236 int running_progs; /* number of programs running (not exited) */
237 char *cmdbuf; /* buffer various argv's point into */
239 int jobid; /* job number */
240 char *cmdtext; /* name of job */
241 pid_t pgrp; /* process group ID for the job */
243 struct child_prog *progs; /* array of commands in pipe */
244 int stopped_progs; /* number of programs alive, but stopped */
245 int job_context; /* bitmask defining current context */
246 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
247 reserved_style r_mode; /* supports if, for, while, until */
251 struct close_me *next;
256 struct variables *next;
263 /* globals, connect us to the outside world
264 * the first three support $?, $#, and $1 */
265 static char **global_argv;
266 static int global_argc;
267 static int last_return_code;
268 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
270 /* "globals" within this file */
273 MAP_FLOWTROUGH_IF_QUOTED = 1,
274 MAP_IFS_IF_UNQUOTED = 2, /* flow through if quoted too */
275 MAP_NEVER_FLOWTROUGH = 3,
277 static unsigned char map[256];
278 static const char *ifs;
279 static int fake_mode;
280 static struct close_me *close_me_head;
281 static const char *cwd;
282 static unsigned last_bg_pid;
283 #if !ENABLE_HUSH_INTERACTIVE
284 enum { interactive_fd = 0 };
286 /* 'interactive_fd' is a fd# open to ctty, if we have one
287 * _AND_ if we decided to act interactively */
288 static int interactive_fd;
290 static pid_t saved_task_pgrp;
291 static pid_t saved_tty_pgrp;
292 static int last_jobid;
293 static struct pipe *job_list;
295 static const char *PS1;
296 static const char *PS2;
299 #define HUSH_VER_STR "0.02"
300 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
301 static struct variables *top_vars = &shell_ver;
313 #define NULL_O_STRING {NULL,0,0,0,0}
314 /* used for initialization:
315 o_string foo = NULL_O_STRING; */
317 /* I can almost use ordinary FILE *. Is open_memstream() universally
318 * available? Where is it documented? */
322 #if ENABLE_HUSH_INTERACTIVE
327 int (*get) (struct in_str *);
328 int (*peek) (struct in_str *);
330 #define b_getch(input) ((input)->get(input))
331 #define b_peek(input) ((input)->peek(input))
333 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
335 struct built_in_command {
336 const char *cmd; /* name */
337 const char *descr; /* description */
338 int (*function) (char **argv); /* function ptr */
341 static void __syntax(int line)
343 bb_error_msg("syntax error hush.c:%d", line);
345 #define syntax() __syntax(__LINE__)
347 /* Index of subroutines: */
348 /* function prototypes for builtins */
349 static int builtin_cd(char **argv);
350 static int builtin_eval(char **argv);
351 static int builtin_exec(char **argv);
352 static int builtin_exit(char **argv);
353 static int builtin_export(char **argv);
355 static int builtin_fg_bg(char **argv);
356 static int builtin_jobs(char **argv);
358 static int builtin_help(char **argv);
359 static int builtin_pwd(char **argv);
360 static int builtin_read(char **argv);
361 static int builtin_set(char **argv);
362 static int builtin_shift(char **argv);
363 static int builtin_source(char **argv);
364 static int builtin_umask(char **argv);
365 static int builtin_unset(char **argv);
366 static int builtin_not_written(char **argv);
367 /* o_string manipulation: */
368 static int b_check_space(o_string *o, int len);
369 static int b_addchr(o_string *o, int ch);
370 static void b_reset(o_string *o);
371 static int b_addqchr(o_string *o, int ch, int quote);
372 static int b_adduint(o_string *o, unsigned i);
373 /* in_str manipulations: */
374 static int static_get(struct in_str *i);
375 static int static_peek(struct in_str *i);
376 static int file_get(struct in_str *i);
377 static int file_peek(struct in_str *i);
378 static void setup_file_in_str(struct in_str *i, FILE *f);
379 static void setup_string_in_str(struct in_str *i, const char *s);
380 /* close_me manipulations: */
381 static void mark_open(int fd);
382 static void mark_closed(int fd);
383 static void close_all(void);
384 /* "run" the final data structures: */
385 //TODO: remove indent argument from non-debug build!
386 static int free_pipe_list(struct pipe *head, int indent);
387 static int free_pipe(struct pipe *pi, int indent);
388 /* really run the final data structures: */
389 static int setup_redirects(struct child_prog *prog, int squirrel[]);
390 static int run_list_real(struct pipe *pi);
391 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
392 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
393 static int run_pipe_real(struct pipe *pi);
394 /* extended glob support: */
395 static int globhack(const char *src, int flags, glob_t *pglob);
396 static int glob_needed(const char *s);
397 static int xglob(o_string *dest, int flags, glob_t *pglob);
398 /* variable assignment: */
399 static int is_assignment(const char *s);
400 /* data structure manipulation: */
401 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
402 static void initialize_context(struct p_context *ctx);
403 static int done_word(o_string *dest, struct p_context *ctx);
404 static int done_command(struct p_context *ctx);
405 static int done_pipe(struct p_context *ctx, pipe_style type);
406 /* primary string parsing: */
407 static int redirect_dup_num(struct in_str *input);
408 static int redirect_opt_num(o_string *o);
409 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
410 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
411 static const char *lookup_param(const char *src);
412 static char *make_string(char **inp);
413 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
414 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
415 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
417 static int parse_stream_outer(struct in_str *inp, int parse_flag);
418 static int parse_string_outer(const char *s, int parse_flag);
419 static int parse_file_outer(FILE *f);
420 /* job management: */
421 static int checkjobs(struct pipe* fg_pipe);
423 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
424 static void insert_bg_job(struct pipe *pi);
425 static void remove_bg_job(struct pipe *pi);
426 static void delete_finished_bg_job(struct pipe *pi);
428 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
430 /* local variable support */
431 static char **make_list_in(char **inp, char *name);
432 static char *insert_var_value(char *inp);
433 static const char *get_local_var(const char *var);
434 static int set_local_var(const char *s, int flg_export);
435 static void unset_local_var(const char *name);
437 /* Table of built-in functions. They can be forked or not, depending on
438 * context: within pipes, they fork. As simple commands, they do not.
439 * When used in non-forking context, they can change global variables
440 * in the parent shell process. If forked, of course they cannot.
441 * For example, 'unset foo | whatever' will parse and run, but foo will
442 * still be set at the end. */
443 static const struct built_in_command bltins[] = {
445 { "bg", "Resume a job in the background", builtin_fg_bg },
447 { "break", "Exit for, while or until loop", builtin_not_written },
448 { "cd", "Change working directory", builtin_cd },
449 { "continue", "Continue for, while or until loop", builtin_not_written },
450 { "eval", "Construct and run shell command", builtin_eval },
451 { "exec", "Exec command, replacing this shell with the exec'd process",
453 { "exit", "Exit from shell()", builtin_exit },
454 { "export", "Set environment variable", builtin_export },
456 { "fg", "Bring job into the foreground", builtin_fg_bg },
457 { "jobs", "Lists the active jobs", builtin_jobs },
459 { "pwd", "Print current directory", builtin_pwd },
460 { "read", "Input environment variable", builtin_read },
461 { "return", "Return from a function", builtin_not_written },
462 { "set", "Set/unset shell local variables", builtin_set },
463 { "shift", "Shift positional parameters", builtin_shift },
464 { "trap", "Trap signals", builtin_not_written },
465 { "ulimit","Controls resource limits", builtin_not_written },
466 { "umask","Sets file creation mask", builtin_umask },
467 { "unset", "Unset environment variable", builtin_unset },
468 { ".", "Source-in and run commands in a file", builtin_source },
469 { "help", "List shell built-in commands", builtin_help },
476 static void signal_SA_RESTART(int sig, void (*handler)(int))
479 sa.sa_handler = handler;
480 sa.sa_flags = SA_RESTART;
481 sigemptyset(&sa.sa_mask);
482 sigaction(sig, &sa, NULL);
485 /* Signals are grouped, we handle them in batches */
486 static void set_fatal_sighandler(void (*handler)(int))
488 signal(SIGILL , handler);
489 signal(SIGTRAP, handler);
490 signal(SIGABRT, handler);
491 signal(SIGFPE , handler);
492 signal(SIGBUS , handler);
493 signal(SIGSEGV, handler);
494 /* bash 3.2 seems to handle these just like 'fatal' ones */
495 signal(SIGHUP , handler);
496 signal(SIGPIPE, handler);
497 signal(SIGALRM, handler);
499 static void set_jobctrl_sighandler(void (*handler)(int))
501 signal(SIGTSTP, handler);
502 signal(SIGTTIN, handler);
503 signal(SIGTTOU, handler);
505 static void set_misc_sighandler(void (*handler)(int))
507 signal(SIGINT , handler);
508 signal(SIGQUIT, handler);
509 signal(SIGTERM, handler);
511 /* SIGCHLD is special and handled separately */
513 static void set_every_sighandler(void (*handler)(int))
515 set_fatal_sighandler(handler);
516 set_jobctrl_sighandler(handler);
517 set_misc_sighandler(handler);
518 signal(SIGCHLD, handler);
521 static struct pipe *toplevel_list;
522 static sigjmp_buf toplevel_jb;
523 smallint ctrl_z_flag;
524 #if ENABLE_FEATURE_SH_STANDALONE
525 struct nofork_save_area nofork_save;
528 static void handler_ctrl_c(int sig)
530 debug_printf_jobs("got sig %d\n", sig);
531 // as usual we can have all kinds of nasty problems with leaked malloc data here
532 siglongjmp(toplevel_jb, 1);
535 static void handler_ctrl_z(int sig)
539 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
541 if (pid < 0) /* can't fork. Pretend there were no ctrl-Z */
544 if (!pid) { /* child */
546 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
547 set_every_sighandler(SIG_DFL);
548 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
549 debug_printf_jobs("returning in child\n");
550 /* return to nofork, it will eventually exit now,
551 * not return back to shell */
555 /* finish filling up pipe info */
556 toplevel_list->pgrp = pid; /* child is in its own pgrp */
557 toplevel_list->progs[0].pid = pid;
558 /* parent needs to longjmp out of running nofork.
559 * we will "return" exitcode 0, with child put in background */
560 // as usual we can have all kinds of nasty problems with leaked malloc data here
561 debug_printf_jobs("siglongjmp in parent\n");
562 siglongjmp(toplevel_jb, 1);
565 /* Restores tty foreground process group, and exits.
566 * May be called as signal handler for fatal signal
567 * (will faithfully resend signal to itself, producing correct exit state)
568 * or called directly with -EXITCODE.
569 * We also call it if xfunc is exiting. */
570 static void sigexit(int sig) ATTRIBUTE_NORETURN;
571 static void sigexit(int sig)
575 /* Disable all signals: job control, SIGPIPE, etc. */
576 sigfillset(&block_all);
577 sigprocmask(SIG_SETMASK, &block_all, NULL);
580 tcsetpgrp(interactive_fd, saved_tty_pgrp);
582 /* Not a signal, just exit */
586 /* Enable only this sig and kill ourself with it */
587 signal(sig, SIG_DFL);
588 sigdelset(&block_all, sig);
589 sigprocmask(SIG_SETMASK, &block_all, NULL);
591 _exit(1); /* Should not reach it */
594 /* Restores tty foreground process group, and exits. */
595 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
596 static void hush_exit(int exitcode)
598 fflush(NULL); /* flush all streams */
599 sigexit(- (exitcode & 0xff));
604 #define set_fatal_sighandler(handler) ((void)0)
605 #define set_jobctrl_sighandler(handler) ((void)0)
606 #define set_misc_sighandler(handler) ((void)0)
607 #define hush_exit(e) exit(e)
612 static const char *set_cwd(void)
614 if (cwd == bb_msg_unknown)
615 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
616 cwd = xrealloc_getcwd_or_warn((char *)cwd);
618 cwd = bb_msg_unknown;
622 /* built-in 'eval' handler */
623 static int builtin_eval(char **argv)
626 int rcode = EXIT_SUCCESS;
629 str = make_string(argv + 1);
630 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
631 FLAG_PARSE_SEMICOLON);
633 rcode = last_return_code;
638 /* built-in 'cd <path>' handler */
639 static int builtin_cd(char **argv)
643 newdir = getenv("HOME");
647 printf("cd: %s: %s\n", newdir, strerror(errno));
654 /* built-in 'exec' handler */
655 static int builtin_exec(char **argv)
658 return EXIT_SUCCESS; /* Really? */
659 pseudo_exec_argv(argv + 1);
663 /* built-in 'exit' handler */
664 static int builtin_exit(char **argv)
666 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
667 //puts("exit"); /* bash does it */
668 // TODO: warn if we have background jobs: "There are stopped jobs"
669 // On second consecutive 'exit', exit anyway.
672 hush_exit(last_return_code);
673 /* mimic bash: exit 123abc == exit 255 + error msg */
674 xfunc_error_retval = 255;
675 /* bash: exit -2 == exit 254, no error msg */
676 hush_exit(xatoi(argv[1]) & 0xff);
679 /* built-in 'export VAR=value' handler */
680 static int builtin_export(char **argv)
683 char *name = argv[1];
687 // ash emits: export VAR='VAL'
688 // bash: declare -x VAR="VAL"
689 // (both also escape as needed (quotes, $, etc))
700 const char *value = strchr(name, '=');
704 /* They are exporting something without an =VALUE */
706 value = get_local_var(name);
708 size_t ln = strlen(name);
710 tmp = realloc(name, ln+strlen(value)+2);
714 sprintf(tmp+ln, "=%s", value);
718 /* bash does not return an error when trying to export
719 * an undefined variable. Do likewise. */
725 bb_perror_msg("export");
727 res = set_local_var(name, 1);
735 /* built-in 'fg' and 'bg' handler */
736 static int builtin_fg_bg(char **argv)
743 /* If they gave us no args, assume they want the last backgrounded task */
745 for (pi = job_list; pi; pi = pi->next) {
746 if (pi->jobid == last_jobid) {
750 bb_error_msg("%s: no current job", argv[0]);
753 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
754 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
757 for (pi = job_list; pi; pi = pi->next) {
758 if (pi->jobid == jobnum) {
762 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
765 // TODO: bash prints a string representation
766 // of job being foregrounded (like "sleep 1 | cat")
767 if (*argv[0] == 'f') {
768 /* Put the job into the foreground. */
769 tcsetpgrp(interactive_fd, pi->pgrp);
772 /* Restart the processes in the job */
773 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
774 for (i = 0; i < pi->num_progs; i++) {
775 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
776 pi->progs[i].is_stopped = 0;
778 pi->stopped_progs = 0;
780 i = kill(- pi->pgrp, SIGCONT);
782 if (errno == ESRCH) {
783 delete_finished_bg_job(pi);
786 bb_perror_msg("kill (SIGCONT)");
790 if (*argv[0] == 'f') {
792 return checkjobs_and_fg_shell(pi);
798 /* built-in 'help' handler */
799 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
801 const struct built_in_command *x;
803 printf("\nBuilt-in commands:\n");
804 printf("-------------------\n");
805 for (x = bltins; x->cmd; x++) {
806 if (x->descr == NULL)
808 printf("%s\t%s\n", x->cmd, x->descr);
815 /* built-in 'jobs' handler */
816 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
819 const char *status_string;
821 for (job = job_list; job; job = job->next) {
822 if (job->running_progs == job->stopped_progs)
823 status_string = "Stopped";
825 status_string = "Running";
827 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
833 /* built-in 'pwd' handler */
834 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
840 /* built-in 'read VAR' handler */
841 static int builtin_read(char **argv)
849 string[0] = '\0'; /* In case stdin has only EOF */
851 fgets(string, sizeof(string), stdin);
853 var = malloc(strlen(argv[1]) + strlen(string) + 2);
855 sprintf(var, "%s=%s", argv[1], string);
856 res = set_local_var(var, 0);
860 bb_perror_msg("read");
861 free(var); /* So not move up to avoid breaking errno */
864 do res = getchar(); while (res != '\n' && res != EOF);
868 /* built-in 'set VAR=value' handler */
869 static int builtin_set(char **argv)
871 char *temp = argv[1];
875 for (e = top_vars; e; e = e->next)
876 printf("%s=%s\n", e->name, e->value);
878 set_local_var(temp, 0);
884 /* Built-in 'shift' handler */
885 static int builtin_shift(char **argv)
891 if (n >= 0 && n < global_argc) {
892 /* XXX This probably breaks $0 */
900 /* Built-in '.' handler (read-in and execute commands from file) */
901 static int builtin_source(char **argv)
909 /* XXX search through $PATH is missing */
910 input = fopen(argv[1], "r");
912 bb_error_msg("cannot open '%s'", argv[1]);
916 /* Now run the file */
917 /* XXX argv and argc are broken; need to save old global_argv
918 * (pointer only is OK!) on this stack frame,
919 * set global_argv=argv+1, recurse, and restore. */
920 mark_open(fileno(input));
921 status = parse_file_outer(input);
922 mark_closed(fileno(input));
927 static int builtin_umask(char **argv)
930 const char *arg = argv[1];
933 new_umask = strtoul(arg, &end, 8);
934 if (*end != '\0' || end == arg) {
938 new_umask = umask(0);
939 printf("%.3o\n", (unsigned) new_umask);
945 /* built-in 'unset VAR' handler */
946 static int builtin_unset(char **argv)
948 /* bash returned already true */
949 unset_local_var(argv[1]);
953 static int builtin_not_written(char **argv)
955 printf("builtin_%s not written\n", argv[0]);
959 static int b_check_space(o_string *o, int len)
961 /* It would be easy to drop a more restrictive policy
962 * in here, such as setting a maximum string length */
963 if (o->length + len > o->maxlen) {
964 char *old_data = o->data;
965 /* assert(data == NULL || o->maxlen != 0); */
966 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
967 o->data = realloc(o->data, 1 + o->maxlen);
968 if (o->data == NULL) {
972 return o->data == NULL;
975 static int b_addchr(o_string *o, int ch)
977 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
978 if (b_check_space(o, 1))
980 o->data[o->length] = ch;
982 o->data[o->length] = '\0';
986 static void b_reset(o_string *o)
994 static void b_free(o_string *o)
1002 /* My analysis of quoting semantics tells me that state information
1003 * is associated with a destination, not a source.
1005 static int b_addqchr(o_string *o, int ch, int quote)
1007 if (quote && strchr("*?[\\", ch)) {
1009 rc = b_addchr(o, '\\');
1013 return b_addchr(o, ch);
1016 static int b_adduint(o_string *o, unsigned i)
1019 char buf[sizeof(unsigned)*3 + 1];
1021 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1022 /* no escape checking necessary */
1023 do r = b_addchr(o, *p++); while (r == 0 && *p);
1027 static int static_get(struct in_str *i)
1030 if (ch == '\0') return EOF;
1034 static int static_peek(struct in_str *i)
1039 #if ENABLE_HUSH_INTERACTIVE
1040 #if ENABLE_FEATURE_EDITING
1041 static void cmdedit_set_initial_prompt(void)
1043 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1046 PS1 = getenv("PS1");
1051 #endif /* EDITING */
1053 static const char* setup_prompt_string(int promptmode)
1055 const char *prompt_str;
1056 debug_printf("setup_prompt_string %d ", promptmode);
1057 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1058 /* Set up the prompt */
1059 if (promptmode == 1) {
1062 ns = xmalloc(strlen(cwd)+4);
1063 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1070 prompt_str = (promptmode == 1) ? PS1 : PS2;
1072 debug_printf("result %s\n", prompt_str);
1076 #if ENABLE_FEATURE_EDITING
1077 static line_input_t *line_input_state;
1080 static int get_user_input(struct in_str *i)
1082 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1085 const char *prompt_str;
1086 prompt_str = setup_prompt_string(i->promptmode);
1087 #if ENABLE_FEATURE_EDITING
1089 ** enable command line editing only while a command line
1090 ** is actually being read; otherwise, we'll end up bequeathing
1091 ** atexit() handlers and other unwanted stuff to our
1092 ** child processes (rob@sysgo.de)
1094 r = read_line_input(prompt_str, the_command, BUFSIZ-1, line_input_state);
1096 fputs(prompt_str, stdout);
1098 the_command[0] = r = fgetc(i->file);
1099 /*the_command[1] = '\0'; - already is and never changed */
1103 return r; /* < 0 == EOF. Not meaningful otherwise */
1105 #endif /* INTERACTIVE */
1107 /* This is the magic location that prints prompts
1108 * and gets data back from the user */
1109 static int file_get(struct in_str *i)
1114 /* If there is data waiting, eat it up */
1115 if (i->p && *i->p) {
1118 /* need to double check i->file because we might be doing something
1119 * more complicated by now, like sourcing or substituting. */
1120 #if ENABLE_HUSH_INTERACTIVE
1121 if (interactive_fd && i->__promptme && i->file == stdin) {
1122 while (!i->p || !(interactive_fd && i->p[0])) {
1123 if (get_user_input(i) < 0)
1128 if (i->p && *i->p) {
1134 ch = fgetc(i->file);
1136 debug_printf("b_getch: got a %d\n", ch);
1138 #if ENABLE_HUSH_INTERACTIVE
1145 /* All the callers guarantee this routine will never be
1146 * used right after a newline, so prompting is not needed.
1148 static int file_peek(struct in_str *i)
1150 if (i->p && *i->p) {
1153 i->peek_buf[0] = fgetc(i->file);
1154 i->peek_buf[1] = '\0';
1156 debug_printf("b_peek: got a %d\n", *i->p);
1160 static void setup_file_in_str(struct in_str *i, FILE *f)
1162 i->peek = file_peek;
1164 #if ENABLE_HUSH_INTERACTIVE
1172 static void setup_string_in_str(struct in_str *i, const char *s)
1174 i->peek = static_peek;
1175 i->get = static_get;
1176 #if ENABLE_HUSH_INTERACTIVE
1183 static void mark_open(int fd)
1185 struct close_me *new = xmalloc(sizeof(struct close_me));
1187 new->next = close_me_head;
1188 close_me_head = new;
1191 static void mark_closed(int fd)
1193 struct close_me *tmp;
1194 if (close_me_head == NULL || close_me_head->fd != fd)
1195 bb_error_msg_and_die("corrupt close_me");
1196 tmp = close_me_head;
1197 close_me_head = close_me_head->next;
1201 static void close_all(void)
1204 for (c = close_me_head; c; c = c->next) {
1207 close_me_head = NULL;
1210 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1211 * and stderr if they are redirected. */
1212 static int setup_redirects(struct child_prog *prog, int squirrel[])
1215 struct redir_struct *redir;
1217 for (redir = prog->redirects; redir; redir = redir->next) {
1218 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1219 /* something went wrong in the parse. Pretend it didn't happen */
1222 if (redir->dup == -1) {
1223 mode = redir_table[redir->type].mode;
1224 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1226 /* this could get lost if stderr has been redirected, but
1227 bash and ash both lose it as well (though zsh doesn't!) */
1231 openfd = redir->dup;
1234 if (openfd != redir->fd) {
1235 if (squirrel && redir->fd < 3) {
1236 squirrel[redir->fd] = dup(redir->fd);
1241 dup2(openfd, redir->fd);
1242 if (redir->dup == -1)
1250 static void restore_redirects(int squirrel[])
1253 for (i = 0; i < 3; i++) {
1256 /* No error checking. I sure wouldn't know what
1257 * to do with an error if I found one! */
1265 /* XXX no exit() here. If you don't exec, use _exit instead.
1266 * The at_exit handlers apparently confuse the calling process,
1267 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1268 static void pseudo_exec_argv(char **argv)
1272 const struct built_in_command *x;
1274 for (i = 0; is_assignment(argv[i]); i++) {
1275 debug_printf("pid %d environment modification: %s\n",
1277 // FIXME: vfork case??
1278 p = insert_var_value(argv[i]);
1284 /* If a variable is assigned in a forest, and nobody listens,
1285 * was it ever really set?
1287 if (argv[0] == NULL) {
1288 _exit(EXIT_SUCCESS);
1292 * Check if the command matches any of the builtins.
1293 * Depending on context, this might be redundant. But it's
1294 * easier to waste a few CPU cycles than it is to figure out
1295 * if this is one of those cases.
1297 for (x = bltins; x->cmd; x++) {
1298 if (strcmp(argv[0], x->cmd) == 0) {
1299 debug_printf("builtin exec %s\n", argv[0]);
1300 rcode = x->function(argv);
1306 /* Check if the command matches any busybox internal commands
1308 * FIXME: This feature is not 100% safe, since
1309 * BusyBox is not fully reentrant, so we have no guarantee the things
1310 * from the .bss are still zeroed, or that things from .data are still
1311 * at their defaults. We could exec ourself from /proc/self/exe, but I
1312 * really dislike relying on /proc for things. We could exec ourself
1313 * from global_argv[0], but if we are in a chroot, we may not be able
1314 * to find ourself... */
1315 #if ENABLE_FEATURE_SH_STANDALONE
1316 debug_printf("running applet %s\n", argv[0]);
1317 run_applet_and_exit(argv[0], argv);
1318 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1319 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1321 debug_printf("exec of %s\n", argv[0]);
1322 execvp(argv[0], argv);
1323 bb_perror_msg("cannot exec '%s'", argv[0]);
1327 static void pseudo_exec(struct child_prog *child)
1329 // FIXME: buggy wrt NOMMU! Must not modify any global data
1330 // until it does exec/_exit, but currently it does.
1334 pseudo_exec_argv(child->argv);
1338 // FIXME: do not modify globals! Think vfork!
1339 #if ENABLE_HUSH_INTERACTIVE
1340 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1341 interactive_fd = 0; /* crucial!!!! */
1343 debug_printf_exec("pseudo_exec: run_list_real\n");
1344 rcode = run_list_real(child->group);
1345 /* OK to leak memory by not calling free_pipe_list,
1346 * since this process is about to exit */
1350 /* Can happen. See what bash does with ">foo" by itself. */
1351 debug_printf("trying to pseudo_exec null command\n");
1352 _exit(EXIT_SUCCESS);
1356 static const char *get_cmdtext(struct pipe *pi)
1362 /* This is subtle. ->cmdtext is created only on first backgrounding.
1363 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1364 * On subsequent bg argv is trashed, but we won't use it */
1367 argv = pi->progs[0].argv;
1368 if (!argv || !argv[0])
1369 return (pi->cmdtext = xzalloc(1));
1372 do len += strlen(*argv) + 1; while (*++argv);
1373 pi->cmdtext = p = xmalloc(len);
1374 argv = pi->progs[0].argv;
1376 len = strlen(*argv);
1377 memcpy(p, *argv, len);
1385 static void insert_bg_job(struct pipe *pi)
1387 struct pipe *thejob;
1390 /* Linear search for the ID of the job to use */
1392 for (thejob = job_list; thejob; thejob = thejob->next)
1393 if (thejob->jobid >= pi->jobid)
1394 pi->jobid = thejob->jobid + 1;
1396 /* Add thejob to the list of running jobs */
1398 thejob = job_list = xmalloc(sizeof(*thejob));
1400 for (thejob = job_list; thejob->next; thejob = thejob->next)
1402 thejob->next = xmalloc(sizeof(*thejob));
1403 thejob = thejob->next;
1406 /* Physically copy the struct job */
1407 memcpy(thejob, pi, sizeof(struct pipe));
1408 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1409 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1410 for (i = 0; i < pi->num_progs; i++) {
1411 // TODO: do we really need to have so many fields which are just dead weight
1412 // at execution stage?
1413 thejob->progs[i].pid = pi->progs[i].pid;
1415 //char **argv; /* program name and arguments */
1416 //struct pipe *group; /* if non-NULL, first in group or subshell */
1417 //int subshell; /* flag, non-zero if group must be forked */
1418 //struct redir_struct *redirects; /* I/O redirections */
1419 //glob_t glob_result; /* result of parameter globbing */
1420 //int is_stopped; /* is the program currently running? */
1421 //struct pipe *family; /* pointer back to the child's parent pipe */
1422 //int sp; /* number of SPECIAL_VAR_SYMBOL */
1425 thejob->next = NULL;
1426 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1428 /* We don't wait for background thejobs to return -- append it
1429 to the list of backgrounded thejobs and leave it alone */
1430 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1431 last_bg_pid = thejob->progs[0].pid;
1432 last_jobid = thejob->jobid;
1435 static void remove_bg_job(struct pipe *pi)
1437 struct pipe *prev_pipe;
1439 if (pi == job_list) {
1440 job_list = pi->next;
1442 prev_pipe = job_list;
1443 while (prev_pipe->next != pi)
1444 prev_pipe = prev_pipe->next;
1445 prev_pipe->next = pi->next;
1448 last_jobid = job_list->jobid;
1453 /* remove a backgrounded job */
1454 static void delete_finished_bg_job(struct pipe *pi)
1457 pi->stopped_progs = 0;
1463 /* Checks to see if any processes have exited -- if they
1464 have, figure out why and see if a job has completed */
1465 static int checkjobs(struct pipe* fg_pipe)
1476 attributes = WUNTRACED;
1477 if (fg_pipe == NULL) {
1478 attributes |= WNOHANG;
1481 /* Do we do this right?
1482 * bash-3.00# sleep 20 | false
1484 * [3]+ Stopped sleep 20 | false
1485 * bash-3.00# echo $?
1486 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1489 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1490 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1491 // + killall -STOP cat
1494 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1495 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1497 #ifdef DEBUG_SHELL_JOBS
1498 if (WIFSTOPPED(status))
1499 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1500 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1501 if (WIFSIGNALED(status))
1502 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1503 childpid, WTERMSIG(status), WEXITSTATUS(status));
1504 if (WIFEXITED(status))
1505 debug_printf_jobs("pid %d exited, exitcode %d\n",
1506 childpid, WEXITSTATUS(status));
1508 /* Were we asked to wait for fg pipe? */
1511 for (i = 0; i < fg_pipe->num_progs; i++) {
1512 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1513 if (fg_pipe->progs[i].pid == childpid) {
1514 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1516 fg_pipe->progs[i].pid = 0;
1517 fg_pipe->running_progs--;
1518 if (i == fg_pipe->num_progs-1)
1519 /* last process gives overall exitstatus */
1520 rcode = WEXITSTATUS(status);
1522 fg_pipe->progs[i].is_stopped = 1;
1523 fg_pipe->stopped_progs++;
1525 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1526 fg_pipe->running_progs, fg_pipe->stopped_progs);
1527 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1528 /* All processes in fg pipe have exited/stopped */
1530 if (fg_pipe->running_progs)
1531 insert_bg_job(fg_pipe);
1535 /* There are still running processes in the fg pipe */
1539 /* fall through to searching process in bg pipes */
1543 /* We asked to wait for bg or orphaned children */
1544 /* No need to remember exitcode in this case */
1545 for (pi = job_list; pi; pi = pi->next) {
1547 while (prognum < pi->num_progs) {
1548 if (pi->progs[prognum].pid == childpid)
1549 goto found_pi_and_prognum;
1555 /* Happens when shell is used as init process (init=/bin/sh) */
1556 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1560 found_pi_and_prognum:
1563 pi->progs[prognum].pid = 0;
1564 pi->running_progs--;
1565 if (!pi->running_progs) {
1566 printf(JOB_STATUS_FORMAT, pi->jobid,
1567 "Done", pi->cmdtext);
1568 delete_finished_bg_job(pi);
1572 pi->stopped_progs++;
1573 pi->progs[prognum].is_stopped = 1;
1578 /* wait found no children or failed */
1580 if (childpid && errno != ECHILD)
1581 bb_perror_msg("waitpid");
1583 /* move the shell to the foreground */
1584 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1585 // bb_perror_msg("tcsetpgrp-2");
1590 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1593 int rcode = checkjobs(fg_pipe);
1594 /* Job finished, move the shell to the foreground */
1596 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1597 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1598 bb_perror_msg("tcsetpgrp-4a");
1603 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1604 * to finish. See checkjobs().
1606 * return code is normally -1, when the caller has to wait for children
1607 * to finish to determine the exit status of the pipe. If the pipe
1608 * is a simple builtin command, however, the action is done by the
1609 * time run_pipe_real returns, and the exit code is provided as the
1612 * The input of the pipe is always stdin, the output is always
1613 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1614 * because it tries to avoid running the command substitution in
1615 * subshell, when that is in fact necessary. The subshell process
1616 * now has its stdout directed to the input of the appropriate pipe,
1617 * so this routine is noticeably simpler.
1619 static int run_pipe_real(struct pipe *pi)
1622 int nextin, nextout;
1623 int pipefds[2]; /* pipefds[0] is for reading */
1624 struct child_prog *child;
1625 const struct built_in_command *x;
1627 /* it is not always needed, but we aim to smaller code */
1628 int squirrel[] = { -1, -1, -1 };
1630 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1632 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1638 pi->running_progs = 1;
1639 pi->stopped_progs = 0;
1641 /* Check if this is a simple builtin (not part of a pipe).
1642 * Builtins within pipes have to fork anyway, and are handled in
1643 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1645 child = &(pi->progs[0]);
1646 if (single_fg && child->group && child->subshell == 0) {
1647 debug_printf("non-subshell grouping\n");
1648 setup_redirects(child, squirrel);
1649 debug_printf_exec(": run_list_real\n");
1650 rcode = run_list_real(child->group);
1651 restore_redirects(squirrel);
1652 debug_printf_exec("run_pipe_real return %d\n", rcode);
1656 if (single_fg && child->argv != NULL) {
1657 char **argv = child->argv;
1659 for (i = 0; is_assignment(argv[i]); i++)
1661 if (i != 0 && argv[i] == NULL) {
1662 /* assignments, but no command: set the local environment */
1663 for (i = 0; argv[i] != NULL; i++) {
1664 /* Ok, this case is tricky. We have to decide if this is a
1665 * local variable, or an already exported variable. If it is
1666 * already exported, we have to export the new value. If it is
1667 * not exported, we need only set this as a local variable.
1668 * This junk is all to decide whether or not to export this
1672 name = xstrdup(argv[i]);
1673 debug_printf("Local environment set: %s\n", name);
1674 value = strchr(name, '=');
1677 if (get_local_var(name)) {
1681 p = insert_var_value(argv[i]);
1682 set_local_var(p, export_me);
1686 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1688 for (i = 0; is_assignment(argv[i]); i++) {
1689 p = insert_var_value(argv[i]);
1699 str = make_string(argv + i);
1700 debug_printf_exec(": parse_string_outer '%s'\n", str);
1701 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1703 debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1704 return last_return_code;
1706 for (x = bltins; x->cmd; x++) {
1707 if (strcmp(argv[i], x->cmd) == 0) {
1708 if (x->function == builtin_exec && argv[i+1] == NULL) {
1709 debug_printf("magic exec\n");
1710 setup_redirects(child, NULL);
1711 return EXIT_SUCCESS;
1713 debug_printf("builtin inline %s\n", argv[0]);
1714 /* XXX setup_redirects acts on file descriptors, not FILEs.
1715 * This is perfect for work that comes after exec().
1716 * Is it really safe for inline use? Experimentally,
1717 * things seem to work with glibc. */
1718 // TODO: fflush(NULL)?
1719 setup_redirects(child, squirrel);
1720 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1721 rcode = x->function(argv + i);
1722 restore_redirects(squirrel);
1723 debug_printf_exec("run_pipe_real return %d\n", rcode);
1727 #if ENABLE_FEATURE_SH_STANDALONE
1729 const struct bb_applet *a = find_applet_by_name(argv[i]);
1730 if (a && a->nofork) {
1731 setup_redirects(child, squirrel);
1732 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv[i], argv[i+1]);
1733 save_nofork_data(&nofork_save);
1734 rcode = run_nofork_applet_prime(&nofork_save, a, argv + i);
1735 restore_redirects(squirrel);
1736 debug_printf_exec("run_pipe_real return %d\n", rcode);
1743 /* Going to fork a child per each pipe member */
1744 pi->running_progs = 0;
1746 /* Disable job control signals for shell (parent) and
1747 * for initial child code after fork */
1748 set_jobctrl_sighandler(SIG_IGN);
1750 for (i = 0; i < pi->num_progs; i++) {
1751 child = &(pi->progs[i]);
1753 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1755 debug_printf_exec(": pipe member with no argv\n");
1757 /* pipes are inserted between pairs of commands */
1758 if ((i + 1) < pi->num_progs) {
1759 if (pipe(pipefds) < 0)
1760 bb_perror_msg_and_die("pipe");
1761 nextout = pipefds[1];
1767 /* XXX test for failed fork()? */
1769 child->pid = fork();
1771 child->pid = vfork();
1773 if (!child->pid) { /* child */
1774 /* Every child adds itself to new process group
1775 * with pgid == pid of first child in pipe */
1777 if (interactive_fd) {
1778 /* Don't do pgrp restore anymore on fatal signals */
1779 set_fatal_sighandler(SIG_DFL);
1780 if (pi->pgrp < 0) /* true for 1st process only */
1781 pi->pgrp = getpid();
1782 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1783 /* We do it in *every* child, not just first,
1785 tcsetpgrp(interactive_fd, pi->pgrp);
1789 // in non-interactive case fatal sigs are already SIG_DFL
1799 if (pipefds[0] != -1) {
1800 close(pipefds[0]); /* opposite end of our output pipe */
1802 /* Like bash, explicit redirects override pipes,
1803 * and the pipe fd is available for dup'ing. */
1804 setup_redirects(child, NULL);
1806 /* Restore default handlers just prior to exec */
1807 set_jobctrl_sighandler(SIG_DFL);
1808 set_misc_sighandler(SIG_DFL);
1809 signal(SIGCHLD, SIG_DFL);
1813 pi->running_progs++;
1816 /* Second and next children need to know pid of first one */
1818 pi->pgrp = child->pid;
1821 /* Don't check for errors. The child may be dead already,
1822 * in which case setpgid returns error code EACCES. */
1823 //why we do it at all?? child does it itself
1824 //if (interactive_fd)
1825 // setpgid(child->pid, pi->pgrp);
1832 /* If there isn't another process, nextin is garbage
1833 but it doesn't matter */
1834 nextin = pipefds[0];
1836 debug_printf_exec("run_pipe_real return -1\n");
1840 #ifndef debug_print_tree
1841 static void debug_print_tree(struct pipe *pi, int lvl)
1843 static const char *PIPE[] = {
1849 static const char *RES[] = {
1850 [RES_NONE ] = "NONE" ,
1852 [RES_THEN ] = "THEN" ,
1853 [RES_ELIF ] = "ELIF" ,
1854 [RES_ELSE ] = "ELSE" ,
1856 [RES_FOR ] = "FOR" ,
1857 [RES_WHILE] = "WHILE",
1858 [RES_UNTIL] = "UNTIL",
1860 [RES_DONE ] = "DONE" ,
1861 [RES_XXXX ] = "XXXX" ,
1863 [RES_SNTX ] = "SNTX" ,
1869 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1870 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1872 while (prn < pi->num_progs) {
1873 struct child_prog *child = &pi->progs[prn];
1874 char **argv = child->argv;
1876 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1878 fprintf(stderr, " group %s: (argv=%p)\n",
1879 (child->subshell ? "()" : "{}"),
1881 debug_print_tree(child->group, lvl+1);
1885 if (argv) while (*argv) {
1886 fprintf(stderr, " '%s'", *argv);
1889 fprintf(stderr, "\n");
1898 // NB: called by pseudo_exec, and therefore must not modify any
1899 // global data until exec/_exit (we can be a child after vfork!)
1900 static int run_list_real(struct pipe *pi)
1908 char *save_name = NULL;
1910 char **save_list = NULL;
1915 int rcode = 0; /* probably for gcc only */
1916 int flag_restore = 0;
1917 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1918 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1920 debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1922 /* check syntax for "for" */
1923 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1924 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1925 && (rpipe->next == NULL)
1927 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1928 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1931 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1932 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1934 /* TODO: what is tested in the first condition? */
1935 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1936 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1942 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1943 * We are saving state before entering outermost list ("while...done")
1944 * so that ctrl-Z will correctly background _entire_ outermost list,
1945 * not just a part of it (like "sleep 1 | exit 2") */
1946 if (++level == 1 && interactive_fd) {
1947 if (sigsetjmp(toplevel_jb, 1)) {
1948 /* ctrl-Z forked and we are parent; or ctrl-C.
1949 * Sighandler has longjmped us here */
1950 signal(SIGINT, SIG_IGN);
1951 signal(SIGTSTP, SIG_IGN);
1952 /* Restore level (we can be coming from deep inside
1955 #if ENABLE_FEATURE_SH_STANDALONE
1956 if (nofork_save.saved) { /* if save area is valid */
1957 debug_printf_jobs("exiting nofork early\n");
1958 restore_nofork_data(&nofork_save);
1962 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1963 * Remember this child as background job */
1966 /* ctrl-C. We just stop doing whatever we were doing */
1972 /* ctrl-Z handler will store pid etc in pi */
1975 #if ENABLE_FEATURE_SH_STANDALONE
1976 nofork_save.saved = 0; /* in case we will run a nofork later */
1978 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1979 signal(SIGINT, handler_ctrl_c);
1983 for (; pi; pi = flag_restore ? rpipe : pi->next) {
1985 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
1992 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1993 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1994 if (rmode == skip_more_in_this_rmode && flag_skip) {
1995 if (pi->followup == PIPE_SEQ)
2000 skip_more_in_this_rmode = RES_XXXX;
2001 if (rmode == RES_THEN || rmode == RES_ELSE)
2002 if_code = next_if_code;
2003 if (rmode == RES_THEN && if_code)
2005 if (rmode == RES_ELSE && !if_code)
2007 if (rmode == RES_ELIF && !if_code)
2009 if (rmode == RES_FOR && pi->num_progs) {
2011 /* if no variable values after "in" we skip "for" */
2012 if (!pi->next->progs->argv)
2014 /* create list of variable values */
2015 list = make_list_in(pi->next->progs->argv,
2016 pi->progs->argv[0]);
2018 save_name = pi->progs->argv[0];
2019 pi->progs->argv[0] = NULL;
2023 free(pi->progs->argv[0]);
2027 pi->progs->argv[0] = save_name;
2028 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2031 /* insert new value from list for variable */
2032 free(pi->progs->argv[0]);
2033 pi->progs->argv[0] = *list++;
2034 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2036 if (rmode == RES_IN)
2038 if (rmode == RES_DO) {
2042 if (rmode == RES_DONE) {
2049 if (pi->num_progs == 0)
2051 save_num_progs = pi->num_progs; /* save number of programs */
2052 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2053 rcode = run_pipe_real(pi);
2055 /* We only ran a builtin: rcode was set by the return value
2056 * of run_pipe_real(), and we don't need to wait for anything. */
2057 } else if (pi->followup == PIPE_BG) {
2058 /* What does bash do with attempts to background builtins? */
2060 /* Even bash 3.2 doesn't do that well with nested bg:
2061 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2062 * I'm considering NOT treating inner bgs as jobs -
2063 * thus maybe "if (level == 1 && pi->followup == PIPE_BG)"
2068 rcode = EXIT_SUCCESS;
2071 /* Paranoia, just "interactive_fd" should be enough */
2072 if (level == 1 && interactive_fd) {
2073 rcode = checkjobs_and_fg_shell(pi);
2077 rcode = checkjobs(pi);
2079 debug_printf_exec(": checkjobs returned %d\n", rcode);
2081 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2082 last_return_code = rcode;
2083 pi->num_progs = save_num_progs; /* restore number of programs */
2084 if (rmode == RES_IF || rmode == RES_ELIF)
2085 next_if_code = rcode; /* can be overwritten a number of times */
2086 if (rmode == RES_WHILE)
2087 flag_rep = !last_return_code;
2088 if (rmode == RES_UNTIL)
2089 flag_rep = last_return_code;
2090 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2091 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2093 skip_more_in_this_rmode = rmode;
2100 /* ctrl-Z forked somewhere in the past, we are the child,
2101 * and now we completed running the list. Exit. */
2107 debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2111 /* return code is the exit status of the pipe */
2112 static int free_pipe(struct pipe *pi, int indent)
2115 struct child_prog *child;
2116 struct redir_struct *r, *rnext;
2117 int a, i, ret_code = 0;
2119 if (pi->stopped_progs > 0)
2121 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2122 for (i = 0; i < pi->num_progs; i++) {
2123 child = &pi->progs[i];
2124 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2126 for (a = 0, p = child->argv; *p; a++, p++) {
2127 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2129 globfree(&child->glob_result);
2131 } else if (child->group) {
2132 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2133 ret_code = free_pipe_list(child->group, indent+3);
2134 debug_printf_clean("%s end group\n", indenter(indent));
2136 debug_printf_clean("%s (nil)\n", indenter(indent));
2138 for (r = child->redirects; r; r = rnext) {
2139 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2141 /* guard against the case >$FOO, where foo is unset or blank */
2142 if (r->word.gl_pathv) {
2143 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2147 debug_printf_clean("&%d\n", r->dup);
2152 child->redirects = NULL;
2154 free(pi->progs); /* children are an array, they get freed all at once */
2163 static int free_pipe_list(struct pipe *head, int indent)
2165 int rcode = 0; /* if list has no members */
2166 struct pipe *pi, *next;
2168 for (pi = head; pi; pi = next) {
2169 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2170 rcode = free_pipe(pi, indent);
2171 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2173 /*pi->next = NULL;*/
2179 /* Select which version we will use */
2180 static int run_list(struct pipe *pi)
2183 debug_printf_exec("run_list entered\n");
2184 if (fake_mode == 0) {
2185 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2186 rcode = run_list_real(pi);
2188 /* free_pipe_list has the side effect of clearing memory.
2189 * In the long run that function can be merged with run_list_real,
2190 * but doing that now would hobble the debugging effort. */
2191 free_pipe_list(pi, 0);
2192 debug_printf_exec("run_list return %d\n", rcode);
2196 /* The API for glob is arguably broken. This routine pushes a non-matching
2197 * string into the output structure, removing non-backslashed backslashes.
2198 * If someone can prove me wrong, by performing this function within the
2199 * original glob(3) api, feel free to rewrite this routine into oblivion.
2200 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2201 * XXX broken if the last character is '\\', check that before calling.
2203 static int globhack(const char *src, int flags, glob_t *pglob)
2208 for (cnt = 1, s = src; s && *s; s++) {
2209 if (*s == '\\') s++;
2214 return GLOB_NOSPACE;
2215 if (!(flags & GLOB_APPEND)) {
2216 pglob->gl_pathv = NULL;
2217 pglob->gl_pathc = 0;
2221 pathc = ++pglob->gl_pathc;
2222 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2223 if (pglob->gl_pathv == NULL)
2224 return GLOB_NOSPACE;
2225 pglob->gl_pathv[pathc-1] = dest;
2226 pglob->gl_pathv[pathc] = NULL;
2227 for (s = src; s && *s; s++, dest++) {
2228 if (*s == '\\') s++;
2235 /* XXX broken if the last character is '\\', check that before calling */
2236 static int glob_needed(const char *s)
2239 if (*s == '\\') s++;
2240 if (strchr("*[?", *s)) return 1;
2245 static int xglob(o_string *dest, int flags, glob_t *pglob)
2249 /* short-circuit for null word */
2250 /* we can code this better when the debug_printf's are gone */
2251 if (dest->length == 0) {
2252 if (dest->nonnull) {
2253 /* bash man page calls this an "explicit" null */
2254 gr = globhack(dest->data, flags, pglob);
2255 debug_printf("globhack returned %d\n", gr);
2259 } else if (glob_needed(dest->data)) {
2260 gr = glob(dest->data, flags, NULL, pglob);
2261 debug_printf("glob returned %d\n", gr);
2262 if (gr == GLOB_NOMATCH) {
2263 /* quote removal, or more accurately, backslash removal */
2264 gr = globhack(dest->data, flags, pglob);
2265 debug_printf("globhack returned %d\n", gr);
2268 gr = globhack(dest->data, flags, pglob);
2269 debug_printf("globhack returned %d\n", gr);
2271 if (gr == GLOB_NOSPACE)
2272 bb_error_msg_and_die("out of memory during glob");
2273 if (gr != 0) { /* GLOB_ABORTED ? */
2274 bb_error_msg("glob(3) error %d", gr);
2276 /* globprint(glob_target); */
2280 static char **make_list_in(char **inp, char *name)
2283 int name_len = strlen(name);
2288 /* create list of variable values */
2289 list = xmalloc(sizeof(*list));
2290 for (i = 0; inp[i]; i++) {
2291 p3 = insert_var_value(inp[i]);
2298 p2 = strchr(p1, ' ');
2305 /* we use n + 2 in realloc for list, because we add
2306 * new element and then we will add NULL element */
2307 list = xrealloc(list, sizeof(*list) * (n + 2));
2308 list[n] = xmalloc(2 + name_len + len);
2309 strcpy(list[n], name);
2310 strcat(list[n], "=");
2311 strncat(list[n], p1, len);
2312 list[n++][name_len + len + 1] = '\0';
2315 if (p3 != inp[i]) free(p3);
2321 static char *insert_var_value(char *inp)
2323 int res_str_len = 0;
2326 char *p, *res_str = NULL;
2329 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2332 res_str = xrealloc(res_str, (res_str_len + len));
2333 strncpy((res_str + res_str_len), inp, len);
2337 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2339 p1 = lookup_param(inp);
2341 len = res_str_len + strlen(p1);
2342 res_str = xrealloc(res_str, (1 + len));
2343 strcpy((res_str + res_str_len), p1);
2346 *p = SPECIAL_VAR_SYMBOL;
2351 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2352 strcpy((res_str + res_str_len), inp);
2353 while ((p = strchr(res_str, '\n'))) {
2357 return (res_str == NULL) ? inp : res_str;
2360 /* This is used to get/check local shell variables */
2361 static const char *get_local_var(const char *s)
2363 struct variables *cur;
2367 for (cur = top_vars; cur; cur = cur->next)
2368 if (strcmp(cur->name, s) == 0)
2373 /* This is used to set local shell variables
2374 flg_export == 0 if only local (not exporting) variable
2375 flg_export == 1 if "new" exporting environ
2376 flg_export > 1 if current startup environ (not call putenv()) */
2377 static int set_local_var(const char *s, int flg_export)
2381 struct variables *cur;
2385 /* Assume when we enter this function that we are already in
2386 * NAME=VALUE format. So the first order of business is to
2387 * split 's' on the '=' into 'name' and 'value' */
2388 value = strchr(name, '=');
2389 /*if (value == 0 && ++value == 0) ??? -vda */
2390 if (value == NULL || value[1] == '\0') {
2396 for (cur = top_vars; cur; cur = cur->next) {
2397 if (strcmp(cur->name, name) == 0)
2402 if (strcmp(cur->value, value) == 0) {
2403 if (flg_export > 0 && cur->flg_export == 0)
2404 cur->flg_export = flg_export;
2407 } else if (cur->flg_read_only) {
2408 bb_error_msg("%s: readonly variable", name);
2411 if (flg_export > 0 || cur->flg_export > 1)
2412 cur->flg_export = 1;
2413 free((char*)cur->value);
2415 cur->value = strdup(value);
2418 cur = malloc(sizeof(struct variables));
2422 cur->name = strdup(name);
2427 struct variables *bottom = top_vars;
2428 cur->value = strdup(value);
2430 cur->flg_export = flg_export;
2431 cur->flg_read_only = 0;
2432 while (bottom->next)
2433 bottom = bottom->next;
2439 if (result == 0 && cur->flg_export == 1) {
2441 result = putenv(name);
2444 if (result > 0) /* equivalent to previous set */
2450 static void unset_local_var(const char *name)
2452 struct variables *cur, *next;
2456 for (cur = top_vars; cur; cur = cur->next) {
2457 if (strcmp(cur->name, name) == 0) {
2458 if (cur->flg_read_only) {
2459 bb_error_msg("%s: readonly variable", name);
2462 if (cur->flg_export)
2463 unsetenv(cur->name);
2464 free((char*)cur->name);
2465 free((char*)cur->value);
2467 while (next->next != cur)
2469 next->next = cur->next;
2476 static int is_assignment(const char *s)
2478 if (!s || !isalpha(*s))
2481 while (isalnum(*s) || *s == '_')
2486 /* the src parameter allows us to peek forward to a possible &n syntax
2487 * for file descriptor duplication, e.g., "2>&1".
2488 * Return code is 0 normally, 1 if a syntax error is detected in src.
2489 * Resource errors (in xmalloc) cause the process to exit */
2490 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2491 struct in_str *input)
2493 struct child_prog *child = ctx->child;
2494 struct redir_struct *redir = child->redirects;
2495 struct redir_struct *last_redir = NULL;
2497 /* Create a new redir_struct and drop it onto the end of the linked list */
2500 redir = redir->next;
2502 redir = xmalloc(sizeof(struct redir_struct));
2504 redir->word.gl_pathv = NULL;
2506 last_redir->next = redir;
2508 child->redirects = redir;
2511 redir->type = style;
2512 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2514 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2516 /* Check for a '2>&1' type redirect */
2517 redir->dup = redirect_dup_num(input);
2518 if (redir->dup == -2) return 1; /* syntax error */
2519 if (redir->dup != -1) {
2520 /* Erik had a check here that the file descriptor in question
2521 * is legit; I postpone that to "run time"
2522 * A "-" representation of "close me" shows up as a -3 here */
2523 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2525 /* We do _not_ try to open the file that src points to,
2526 * since we need to return and let src be expanded first.
2527 * Set ctx->pending_redirect, so we know what to do at the
2528 * end of the next parsed word.
2530 ctx->pending_redirect = redir;
2535 static struct pipe *new_pipe(void)
2538 pi = xzalloc(sizeof(struct pipe));
2539 /*pi->num_progs = 0;*/
2540 /*pi->progs = NULL;*/
2541 /*pi->next = NULL;*/
2542 /*pi->followup = 0; invalid */
2544 pi->r_mode = RES_NONE;
2548 static void initialize_context(struct p_context *ctx)
2551 ctx->pending_redirect = NULL;
2553 ctx->list_head = new_pipe();
2554 ctx->pipe = ctx->list_head;
2555 ctx->res_w = RES_NONE;
2558 done_command(ctx); /* creates the memory for working child */
2561 /* normal return is 0
2562 * if a reserved word is found, and processed, return 1
2563 * should handle if, then, elif, else, fi, for, while, until, do, done.
2564 * case, function, and select are obnoxious, save those for later.
2566 static int reserved_word(o_string *dest, struct p_context *ctx)
2568 struct reserved_combo {
2573 /* Mostly a list of accepted follow-up reserved words.
2574 * FLAG_END means we are done with the sequence, and are ready
2575 * to turn the compound list into a command.
2576 * FLAG_START means the word must start a new compound list.
2578 static const struct reserved_combo reserved_list[] = {
2579 { "if", RES_IF, FLAG_THEN | FLAG_START },
2580 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2581 { "elif", RES_ELIF, FLAG_THEN },
2582 { "else", RES_ELSE, FLAG_FI },
2583 { "fi", RES_FI, FLAG_END },
2584 { "for", RES_FOR, FLAG_IN | FLAG_START },
2585 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2586 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2587 { "in", RES_IN, FLAG_DO },
2588 { "do", RES_DO, FLAG_DONE },
2589 { "done", RES_DONE, FLAG_END }
2591 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2592 const struct reserved_combo *r;
2594 for (r = reserved_list; r < reserved_list + NRES; r++) {
2595 if (strcmp(dest->data, r->literal) == 0) {
2596 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2597 if (r->flag & FLAG_START) {
2598 struct p_context *new = xmalloc(sizeof(struct p_context));
2599 debug_printf("push stack\n");
2600 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2603 ctx->res_w = RES_SNTX;
2607 *new = *ctx; /* physical copy */
2608 initialize_context(ctx);
2610 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2612 ctx->res_w = RES_SNTX;
2616 ctx->res_w = r->code;
2617 ctx->old_flag = r->flag;
2618 if (ctx->old_flag & FLAG_END) {
2619 struct p_context *old;
2620 debug_printf("pop stack\n");
2621 done_pipe(ctx, PIPE_SEQ);
2623 old->child->group = ctx->list_head;
2624 old->child->subshell = 0;
2625 *ctx = *old; /* physical copy */
2635 /* Normal return is 0.
2636 * Syntax or xglob errors return 1. */
2637 static int done_word(o_string *dest, struct p_context *ctx)
2639 struct child_prog *child = ctx->child;
2640 glob_t *glob_target;
2643 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2644 if (dest->length == 0 && !dest->nonnull) {
2645 debug_printf_parse("done_word return 0: true null, ignored\n");
2648 if (ctx->pending_redirect) {
2649 glob_target = &ctx->pending_redirect->word;
2653 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2656 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2657 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2658 if (reserved_word(dest, ctx)) {
2659 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2660 return (ctx->res_w == RES_SNTX);
2663 glob_target = &child->glob_result;
2665 flags |= GLOB_APPEND;
2667 gr = xglob(dest, flags, glob_target);
2669 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2674 if (ctx->pending_redirect) {
2675 ctx->pending_redirect = NULL;
2676 if (glob_target->gl_pathc != 1) {
2677 bb_error_msg("ambiguous redirect");
2678 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2682 child->argv = glob_target->gl_pathv;
2684 if (ctx->res_w == RES_FOR) {
2685 done_word(dest, ctx);
2686 done_pipe(ctx, PIPE_SEQ);
2688 debug_printf_parse("done_word return 0\n");
2692 /* The only possible error here is out of memory, in which case
2694 static int done_command(struct p_context *ctx)
2696 /* The child is really already in the pipe structure, so
2697 * advance the pipe counter and make a new, null child. */
2698 struct pipe *pi = ctx->pipe;
2699 struct child_prog *child = ctx->child;
2702 if (child->group == NULL
2703 && child->argv == NULL
2704 && child->redirects == NULL
2706 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2707 return pi->num_progs;
2710 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2712 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2715 /* Only real trickiness here is that the uncommitted
2716 * child structure is not counted in pi->num_progs. */
2717 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2718 child = &pi->progs[pi->num_progs];
2720 memset(child, 0, sizeof(*child));
2721 /*child->redirects = NULL;*/
2722 /*child->argv = NULL;*/
2723 /*child->is_stopped = 0;*/
2724 /*child->group = NULL;*/
2725 /*child->glob_result.gl_pathv = NULL;*/
2728 child->type = ctx->parse_type;
2731 /* but ctx->pipe and ctx->list_head remain unchanged */
2733 return pi->num_progs; /* used only for 0/nonzero check */
2736 static int done_pipe(struct p_context *ctx, pipe_style type)
2741 debug_printf_parse("done_pipe entered, followup %d\n", type);
2742 not_null = done_command(ctx); /* implicit closure of previous command */
2743 ctx->pipe->followup = type;
2744 ctx->pipe->r_mode = ctx->res_w;
2745 /* Without this check, even just <enter> on command line generates
2746 * tree of three NOPs (!). Which is harmless but annoying.
2747 * IOW: it is safe to do it unconditionally. */
2750 ctx->pipe->next = new_p;
2753 done_command(ctx); /* set up new pipe to accept commands */
2755 debug_printf_parse("done_pipe return 0\n");
2759 /* peek ahead in the in_str to find out if we have a "&n" construct,
2760 * as in "2>&1", that represents duplicating a file descriptor.
2761 * returns either -2 (syntax error), -1 (no &), or the number found.
2763 static int redirect_dup_num(struct in_str *input)
2765 int ch, d = 0, ok = 0;
2767 if (ch != '&') return -1;
2769 b_getch(input); /* get the & */
2773 return -3; /* "-" represents "close me" */
2775 while (isdigit(ch)) {
2776 d = d*10 + (ch-'0');
2783 bb_error_msg("ambiguous redirect");
2787 /* If a redirect is immediately preceded by a number, that number is
2788 * supposed to tell which file descriptor to redirect. This routine
2789 * looks for such preceding numbers. In an ideal world this routine
2790 * needs to handle all the following classes of redirects...
2791 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2792 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2793 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2794 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2795 * A -1 output from this program means no valid number was found, so the
2796 * caller should use the appropriate default for this redirection.
2798 static int redirect_opt_num(o_string *o)
2804 for (num = 0; num < o->length; num++) {
2805 if (!isdigit(*(o->data + num))) {
2809 /* reuse num (and save an int) */
2810 num = atoi(o->data);
2815 static FILE *generate_stream_from_list(struct pipe *head)
2818 int pid, channel[2];
2819 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2826 bb_perror_msg_and_die("fork");
2827 } else if (pid == 0) {
2829 if (channel[1] != 1) {
2830 dup2(channel[1], 1);
2833 _exit(run_list_real(head)); /* leaks memory */
2835 debug_printf("forked child %d\n", pid);
2837 pf = fdopen(channel[0], "r");
2838 debug_printf("pipe on FILE *%p\n", pf);
2842 /* Return code is exit status of the process that is run. */
2843 static int process_command_subs(o_string *dest, struct p_context *ctx,
2844 struct in_str *input, const char *subst_end)
2847 o_string result = NULL_O_STRING;
2848 struct p_context inner;
2850 struct in_str pipe_str;
2851 initialize_context(&inner);
2853 /* recursion to generate command */
2854 retcode = parse_stream(&result, &inner, input, subst_end);
2855 if (retcode != 0) return retcode; /* syntax error or EOF */
2856 done_word(&result, &inner);
2857 done_pipe(&inner, PIPE_SEQ);
2860 p = generate_stream_from_list(inner.list_head);
2861 if (p == NULL) return 1;
2862 mark_open(fileno(p));
2863 // FIXME: need to flag pipe_str to somehow discard all trailing newlines.
2864 // Example: echo "TEST`date;echo;echo`BEST"
2865 // must produce one line: TEST<date>BEST
2866 setup_file_in_str(&pipe_str, p);
2868 /* now send results of command back into original context */
2869 // FIXME: must not do quote parsing of the output!
2870 // Example: echo "TEST`echo '$(echo ZZ)'`BEST"
2871 // must produce TEST$(echo ZZ)BEST, not TESTZZBEST.
2872 // Example: echo "TEST`echo "'"`BEST"
2873 // must produce TEST'BEST
2874 // (maybe by setting all chars flagged as literals in map[]?)
2876 retcode = parse_stream(dest, ctx, &pipe_str, NULL);
2877 /* XXX In case of a syntax error, should we try to kill the child?
2878 * That would be tough to do right, so just read until EOF. */
2880 while (b_getch(&pipe_str) != EOF)
2884 debug_printf("done reading from pipe, pclose()ing\n");
2885 /* This is the step that wait()s for the child. Should be pretty
2886 * safe, since we just read an EOF from its stdout. We could try
2887 * to better, by using wait(), and keeping track of background jobs
2888 * at the same time. That would be a lot of work, and contrary
2889 * to the KISS philosophy of this program. */
2890 mark_closed(fileno(p));
2891 retcode = pclose(p);
2892 free_pipe_list(inner.list_head, 0);
2893 debug_printf("pclosed, retcode=%d\n", retcode);
2897 static int parse_group(o_string *dest, struct p_context *ctx,
2898 struct in_str *input, int ch)
2901 const char *endch = NULL;
2902 struct p_context sub;
2903 struct child_prog *child = ctx->child;
2905 debug_printf_parse("parse_group entered\n");
2908 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
2911 initialize_context(&sub);
2915 child->subshell = 1;
2921 syntax(); /* really logic error */
2923 rcode = parse_stream(dest, &sub, input, endch);
2924 done_word(dest, &sub); /* finish off the final word in the subcontext */
2925 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2926 child->group = sub.list_head;
2928 debug_printf_parse("parse_group return %d\n", rcode);
2930 /* child remains "open", available for possible redirects */
2933 /* Basically useful version until someone wants to get fancier,
2934 * see the bash man page under "Parameter Expansion" */
2935 static const char *lookup_param(const char *src)
2937 const char *p = NULL;
2941 p = get_local_var(src);
2946 /* Make new string for parser */
2947 static char* make_string(char ** inp)
2954 for (n = 0; inp[n]; n++) {
2955 p = insert_var_value(inp[n]);
2956 str = xrealloc(str, (len + strlen(p)));
2963 len = strlen(str) + 3;
2964 if (p != inp[n]) free(p);
2972 /* return code: 0 for OK, 1 for syntax error */
2973 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2977 int ch = input->peek(input); /* first character after the $ */
2978 debug_printf("handle_dollar: ch=%c\n", ch);
2980 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2982 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2986 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2987 } else if (isdigit(ch)) {
2988 i = ch - '0'; /* XXX is $0 special? */
2989 if (i < global_argc) {
2990 parse_string(dest, ctx, global_argv[i]); /* recursion */
2993 } else switch (ch) {
2995 b_adduint(dest, getpid());
2999 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
3003 b_adduint(dest, last_return_code);
3007 b_adduint(dest, global_argc ? global_argc-1 : 0);
3011 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3014 /* XXX maybe someone will try to escape the '}' */
3016 ch = b_getch(input);
3017 if (ch == EOF || ch == '}')
3025 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3029 process_command_subs(dest, ctx, input, ")");
3033 for (i = 1; i < global_argc; i++) {
3034 parse_string(dest, ctx, global_argv[i]);
3035 if (i+1 < global_argc)
3036 parse_string(dest, ctx, sep);
3042 /* still unhandled, but should be eventually */
3043 bb_error_msg("unhandled syntax: $%c", ch);
3047 b_addqchr(dest,'$', dest->quote);
3049 /* Eat the character if the flag was set. If the compiler
3050 * is smart enough, we could substitute "b_getch(input);"
3051 * for all the "advance = 1;" above, and also end up with
3052 * a nice size-optimized program. Hah! That'll be the day.
3054 if (advance) b_getch(input);
3058 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
3061 setup_string_in_str(&foo, src);
3062 return parse_stream(dest, ctx, &foo, NULL);
3065 /* return code is 0 for normal exit, 1 for syntax error */
3066 static int parse_stream(o_string *dest, struct p_context *ctx,
3067 struct in_str *input, const char *end_trigger)
3071 redir_type redir_style;
3074 /* Only double-quote state is handled in the state variable dest->quote.
3075 * A single-quote triggers a bypass of the main loop until its mate is
3076 * found. When recursing, quote state is passed in via dest->quote. */
3078 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3080 while ((ch = b_getch(input)) != EOF) {
3082 next = (ch == '\n') ? 0 : b_peek(input);
3083 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3084 ch, ch, m, dest->quote);
3085 if (m == MAP_ORDINARY
3086 || (m != MAP_NEVER_FLOWTROUGH && dest->quote)
3088 b_addqchr(dest, ch, dest->quote);
3091 if (m == MAP_IFS_IF_UNQUOTED) {
3092 if (done_word(dest, ctx)) {
3093 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3096 /* If we aren't performing a substitution, treat
3097 * a newline as a command separator.
3098 * [why we don't handle it exactly like ';'? --vda] */
3099 if (end_trigger && ch == '\n') {
3100 done_pipe(ctx, PIPE_SEQ);
3103 if ((end_trigger && strchr(end_trigger, ch))
3104 && !dest->quote && ctx->res_w == RES_NONE
3106 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3109 if (m == MAP_IFS_IF_UNQUOTED)
3113 if (dest->length == 0 && !dest->quote) {
3116 if (ch == EOF || ch == '\n')
3121 b_addqchr(dest, ch, dest->quote);
3127 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3130 b_addqchr(dest, '\\', dest->quote);
3131 b_addqchr(dest, b_getch(input), dest->quote);
3134 if (handle_dollar(dest, ctx, input) != 0) {
3135 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3142 ch = b_getch(input);
3143 if (ch == EOF || ch == '\'')
3149 debug_printf_parse("parse_stream return 1: unterminated '\n");
3155 dest->quote = !dest->quote;
3158 process_command_subs(dest, ctx, input, "`");
3161 redir_fd = redirect_opt_num(dest);
3162 done_word(dest, ctx);
3163 redir_style = REDIRECT_OVERWRITE;
3165 redir_style = REDIRECT_APPEND;
3167 } else if (next == '(') {
3168 syntax(); /* until we support >(list) Process Substitution */
3169 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3172 setup_redirect(ctx, redir_fd, redir_style, input);
3175 redir_fd = redirect_opt_num(dest);
3176 done_word(dest, ctx);
3177 redir_style = REDIRECT_INPUT;
3179 redir_style = REDIRECT_HEREIS;
3181 } else if (next == '>') {
3182 redir_style = REDIRECT_IO;
3184 } else if (next == '(') {
3185 syntax(); /* until we support <(list) Process Substitution */
3186 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3189 setup_redirect(ctx, redir_fd, redir_style, input);
3192 done_word(dest, ctx);
3193 done_pipe(ctx, PIPE_SEQ);
3196 done_word(dest, ctx);
3199 done_pipe(ctx, PIPE_AND);
3201 done_pipe(ctx, PIPE_BG);
3205 done_word(dest, ctx);
3208 done_pipe(ctx, PIPE_OR);
3210 /* we could pick up a file descriptor choice here
3211 * with redirect_opt_num(), but bash doesn't do it.
3212 * "echo foo 2| cat" yields "foo 2". */
3218 if (parse_group(dest, ctx, input, ch) != 0) {
3219 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3225 syntax(); /* Proper use of this character is caught by end_trigger */
3226 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3229 syntax(); /* this is really an internal logic error */
3230 debug_printf_parse("parse_stream return 1: internal logic error\n");
3234 /* Complain if quote? No, maybe we just finished a command substitution
3235 * that was quoted. Example:
3236 * $ echo "`cat foo` plus more"
3237 * and we just got the EOF generated by the subshell that ran "cat foo"
3238 * The only real complaint is if we got an EOF when end_trigger != NULL,
3239 * that is, we were really supposed to get end_trigger, and never got
3240 * one before the EOF. Can't use the standard "syntax error" return code,
3241 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3242 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3248 static void mapset(const char *set, int code)
3251 map[(unsigned char)*set++] = code;
3254 static void update_ifs_map(void)
3256 /* char *ifs and char map[256] are both globals. */
3257 ifs = getenv("IFS");
3260 /* Precompute a list of 'flow through' behavior so it can be treated
3261 * quickly up front. Computation is necessary because of IFS.
3262 * Special case handling of IFS == " \t\n" is not implemented.
3263 * The map[] array only really needs two bits each, and on most machines
3264 * that would be faster because of the reduced L1 cache footprint.
3266 memset(map, MAP_ORDINARY, sizeof(map)); /* most chars flow through always */
3267 mapset("\\$'\"`", MAP_NEVER_FLOWTROUGH);
3268 mapset("<>;&|(){}#", MAP_FLOWTROUGH_IF_QUOTED);
3269 mapset(ifs, MAP_IFS_IF_UNQUOTED); /* also flow through if quoted */
3272 /* most recursion does not come through here, the exception is
3273 * from builtin_source() */
3274 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3276 // FIXME: '{ true | exit 3; echo $? }' is parsed as a whole,
3277 // as a result $? is replaced by 0, not 3!
3279 struct p_context ctx;
3280 o_string temp = NULL_O_STRING;
3283 ctx.parse_type = parse_flag;
3284 initialize_context(&ctx);
3286 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3287 mapset(";$&|", MAP_ORDINARY);
3288 #if ENABLE_HUSH_INTERACTIVE
3289 inp->promptmode = 1;
3291 /* We will stop & execute after each ';' or '\n'.
3292 * Example: "sleep 9999; echo TEST" + ctrl-C:
3293 * TEST should be printed */
3294 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3295 if (rcode != 1 && ctx.old_flag != 0) {
3298 if (rcode != 1 && ctx.old_flag == 0) {
3299 done_word(&temp, &ctx);
3300 done_pipe(&ctx, PIPE_SEQ);
3301 debug_print_tree(ctx.list_head, 0);
3302 debug_printf_exec("parse_stream_outer: run_list\n");
3303 run_list(ctx.list_head);
3305 if (ctx.old_flag != 0) {
3312 free_pipe_list(ctx.list_head, 0);
3315 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3319 static int parse_string_outer(const char *s, int parse_flag)
3321 struct in_str input;
3322 setup_string_in_str(&input, s);
3323 return parse_stream_outer(&input, parse_flag);
3326 static int parse_file_outer(FILE *f)
3329 struct in_str input;
3330 setup_file_in_str(&input, f);
3331 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3336 /* Make sure we have a controlling tty. If we get started under a job
3337 * aware app (like bash for example), make sure we are now in charge so
3338 * we don't fight over who gets the foreground */
3339 static void setup_job_control(void)
3343 saved_task_pgrp = shell_pgrp = getpgrp();
3344 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3345 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3347 /* If we were ran as 'hush &',
3348 * sleep until we are in the foreground. */
3349 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3350 /* Send TTIN to ourself (should stop us) */
3351 kill(- shell_pgrp, SIGTTIN);
3352 shell_pgrp = getpgrp();
3355 /* Ignore job-control and misc signals. */
3356 set_jobctrl_sighandler(SIG_IGN);
3357 set_misc_sighandler(SIG_IGN);
3358 //huh? signal(SIGCHLD, SIG_IGN);
3360 /* We _must_ restore tty pgrp on fatal signals */
3361 set_fatal_sighandler(sigexit);
3363 /* Put ourselves in our own process group. */
3364 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3365 /* Grab control of the terminal. */
3366 tcsetpgrp(interactive_fd, getpid());
3370 int hush_main(int argc, char **argv);
3371 int hush_main(int argc, char **argv)
3377 #if ENABLE_FEATURE_EDITING
3378 line_input_state = new_line_input_t(FOR_SHELL);
3381 /* XXX what should these be while sourcing /etc/profile? */
3385 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3386 * hush_main(), therefore we cannot rely on the BSS to zero out this
3387 * stuff. Reset these to 0 every time. */
3389 /* map[] is taken care of with call to update_ifs_map() */
3391 close_me_head = NULL;
3392 #if ENABLE_HUSH_INTERACTIVE
3401 /* Initialize some more globals to non-zero values */
3403 #if ENABLE_HUSH_INTERACTIVE
3404 #if ENABLE_FEATURE_EDITING
3405 cmdedit_set_initial_prompt();
3411 /* initialize our shell local variables with the values
3412 * currently living in the environment */
3416 set_local_var(*e++, 2); /* without call putenv() */
3418 last_return_code = EXIT_SUCCESS;
3420 if (argv[0] && argv[0][0] == '-') {
3421 debug_printf("sourcing /etc/profile\n");
3422 input = fopen("/etc/profile", "r");
3423 if (input != NULL) {
3424 mark_open(fileno(input));
3425 parse_file_outer(input);
3426 mark_closed(fileno(input));
3432 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3435 global_argv = argv + optind;
3436 global_argc = argc - optind;
3437 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3440 // Well, we cannot just declare interactiveness,
3441 // we have to have some stuff (ctty, etc)
3442 /*interactive_fd++;*/
3449 fprintf(stderr, "Usage: sh [FILE]...\n"
3450 " or: sh -c command [args]...\n\n");
3458 /* A shell is interactive if the '-i' flag was given, or if all of
3459 * the following conditions are met:
3461 * no arguments remaining or the -s flag given
3462 * standard input is a terminal
3463 * standard output is a terminal
3464 * Refer to Posix.2, the description of the 'sh' utility. */
3465 if (argv[optind] == NULL && input == stdin
3466 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3468 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3469 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3470 if (saved_tty_pgrp >= 0) {
3471 /* try to dup to high fd#, >= 255 */
3472 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3473 if (interactive_fd < 0) {
3474 /* try to dup to any fd */
3475 interactive_fd = dup(STDIN_FILENO);
3476 if (interactive_fd < 0)
3480 // TODO: track & disallow any attempts of user
3481 // to (inadvertently) close/redirect it
3484 debug_printf("interactive_fd=%d\n", interactive_fd);
3485 if (interactive_fd) {
3486 /* Looks like they want an interactive shell */
3487 setup_job_control();
3488 /* Make xfuncs do cleanup on exit */
3489 die_sleep = -1; /* flag */
3490 // FIXME: should we reset die_sleep = 0 whereever we fork?
3491 if (setjmp(die_jmp)) {
3492 /* xfunc has failed! die die die */
3493 hush_exit(xfunc_error_retval);
3495 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3496 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3497 printf("Enter 'help' for a list of built-in commands.\n\n");
3500 #elif ENABLE_HUSH_INTERACTIVE
3501 /* no job control compiled, only prompt/line editing */
3502 if (argv[optind] == NULL && input == stdin
3503 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3505 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3506 if (interactive_fd < 0) {
3507 /* try to dup to any fd */
3508 interactive_fd = dup(STDIN_FILENO);
3509 if (interactive_fd < 0)
3517 if (argv[optind] == NULL) {
3518 opt = parse_file_outer(stdin);
3522 debug_printf("\nrunning script '%s'\n", argv[optind]);
3523 global_argv = argv + optind;
3524 global_argc = argc - optind;
3525 input = xfopen(argv[optind], "r");
3526 opt = parse_file_outer(input);
3528 #if ENABLE_FEATURE_CLEAN_UP
3530 if (cwd != bb_msg_unknown)
3533 struct variables *cur, *tmp;
3534 for (cur = top_vars; cur; cur = tmp) {
3536 if (!cur->flg_read_only) {
3537 free((char*)cur->name);
3538 free((char*)cur->value);
3546 hush_exit(opt ? opt : last_return_code);