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? */
324 #if ENABLE_HUSH_INTERACTIVE
329 int (*get) (struct in_str *);
330 int (*peek) (struct in_str *);
332 #define b_getch(input) ((input)->get(input))
333 #define b_peek(input) ((input)->peek(input))
335 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
337 struct built_in_command {
338 const char *cmd; /* name */
339 const char *descr; /* description */
340 int (*function) (char **argv); /* function ptr */
343 static void __syntax(int line)
345 bb_error_msg("syntax error hush.c:%d", line);
347 #define syntax() __syntax(__LINE__)
349 /* Index of subroutines: */
350 /* function prototypes for builtins */
351 static int builtin_cd(char **argv);
352 static int builtin_eval(char **argv);
353 static int builtin_exec(char **argv);
354 static int builtin_exit(char **argv);
355 static int builtin_export(char **argv);
357 static int builtin_fg_bg(char **argv);
358 static int builtin_jobs(char **argv);
360 static int builtin_help(char **argv);
361 static int builtin_pwd(char **argv);
362 static int builtin_read(char **argv);
363 static int builtin_set(char **argv);
364 static int builtin_shift(char **argv);
365 static int builtin_source(char **argv);
366 static int builtin_umask(char **argv);
367 static int builtin_unset(char **argv);
368 static int builtin_not_written(char **argv);
369 /* o_string manipulation: */
370 static int b_check_space(o_string *o, int len);
371 static int b_addchr(o_string *o, int ch);
372 static void b_reset(o_string *o);
373 static int b_addqchr(o_string *o, int ch, int quote);
374 static int b_adduint(o_string *o, unsigned i);
375 /* in_str manipulations: */
376 static int static_get(struct in_str *i);
377 static int static_peek(struct in_str *i);
378 static int file_get(struct in_str *i);
379 static int file_peek(struct in_str *i);
380 static void setup_file_in_str(struct in_str *i, FILE *f);
381 static void setup_string_in_str(struct in_str *i, const char *s);
382 /* close_me manipulations: */
383 static void mark_open(int fd);
384 static void mark_closed(int fd);
385 static void close_all(void);
386 /* "run" the final data structures: */
387 //TODO: remove indent argument from non-debug build!
388 static int free_pipe_list(struct pipe *head, int indent);
389 static int free_pipe(struct pipe *pi, int indent);
390 /* really run the final data structures: */
391 static int setup_redirects(struct child_prog *prog, int squirrel[]);
392 static int run_list_real(struct pipe *pi);
393 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
394 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
395 static int run_pipe_real(struct pipe *pi);
396 /* extended glob support: */
397 static int globhack(const char *src, int flags, glob_t *pglob);
398 static int glob_needed(const char *s);
399 static int xglob(o_string *dest, int flags, glob_t *pglob);
400 /* variable assignment: */
401 static int is_assignment(const char *s);
402 /* data structure manipulation: */
403 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
404 static void initialize_context(struct p_context *ctx);
405 static int done_word(o_string *dest, struct p_context *ctx);
406 static int done_command(struct p_context *ctx);
407 static int done_pipe(struct p_context *ctx, pipe_style type);
408 /* primary string parsing: */
409 static int redirect_dup_num(struct in_str *input);
410 static int redirect_opt_num(o_string *o);
411 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
412 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
413 static const char *lookup_param(const char *src);
414 static char *make_string(char **inp);
415 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
416 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
417 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
419 static int parse_stream_outer(struct in_str *inp, int parse_flag);
420 static int parse_string_outer(const char *s, int parse_flag);
421 static int parse_file_outer(FILE *f);
422 /* job management: */
423 static int checkjobs(struct pipe* fg_pipe);
425 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
426 static void insert_bg_job(struct pipe *pi);
427 static void remove_bg_job(struct pipe *pi);
428 static void delete_finished_bg_job(struct pipe *pi);
430 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
432 /* local variable support */
433 static char **make_list_in(char **inp, char *name);
434 static char *insert_var_value(char *inp);
435 static const char *get_local_var(const char *var);
436 static int set_local_var(const char *s, int flg_export);
437 static void unset_local_var(const char *name);
439 /* Table of built-in functions. They can be forked or not, depending on
440 * context: within pipes, they fork. As simple commands, they do not.
441 * When used in non-forking context, they can change global variables
442 * in the parent shell process. If forked, of course they cannot.
443 * For example, 'unset foo | whatever' will parse and run, but foo will
444 * still be set at the end. */
445 static const struct built_in_command bltins[] = {
447 { "bg", "Resume a job in the background", builtin_fg_bg },
449 { "break", "Exit for, while or until loop", builtin_not_written },
450 { "cd", "Change working directory", builtin_cd },
451 { "continue", "Continue for, while or until loop", builtin_not_written },
452 { "eval", "Construct and run shell command", builtin_eval },
453 { "exec", "Exec command, replacing this shell with the exec'd process",
455 { "exit", "Exit from shell()", builtin_exit },
456 { "export", "Set environment variable", builtin_export },
458 { "fg", "Bring job into the foreground", builtin_fg_bg },
459 { "jobs", "Lists the active jobs", builtin_jobs },
461 { "pwd", "Print current directory", builtin_pwd },
462 { "read", "Input environment variable", builtin_read },
463 { "return", "Return from a function", builtin_not_written },
464 { "set", "Set/unset shell local variables", builtin_set },
465 { "shift", "Shift positional parameters", builtin_shift },
466 { "trap", "Trap signals", builtin_not_written },
467 { "ulimit","Controls resource limits", builtin_not_written },
468 { "umask","Sets file creation mask", builtin_umask },
469 { "unset", "Unset environment variable", builtin_unset },
470 { ".", "Source-in and run commands in a file", builtin_source },
471 { "help", "List shell built-in commands", builtin_help },
478 static void signal_SA_RESTART(int sig, void (*handler)(int))
481 sa.sa_handler = handler;
482 sa.sa_flags = SA_RESTART;
483 sigemptyset(&sa.sa_mask);
484 sigaction(sig, &sa, NULL);
487 /* Signals are grouped, we handle them in batches */
488 static void set_fatal_sighandler(void (*handler)(int))
490 signal(SIGILL , handler);
491 signal(SIGTRAP, handler);
492 signal(SIGABRT, handler);
493 signal(SIGFPE , handler);
494 signal(SIGBUS , handler);
495 signal(SIGSEGV, handler);
496 /* bash 3.2 seems to handle these just like 'fatal' ones */
497 signal(SIGHUP , handler);
498 signal(SIGPIPE, handler);
499 signal(SIGALRM, handler);
501 static void set_jobctrl_sighandler(void (*handler)(int))
503 signal(SIGTSTP, handler);
504 signal(SIGTTIN, handler);
505 signal(SIGTTOU, handler);
507 static void set_misc_sighandler(void (*handler)(int))
509 signal(SIGINT , handler);
510 signal(SIGQUIT, handler);
511 signal(SIGTERM, handler);
513 /* SIGCHLD is special and handled separately */
515 static void set_every_sighandler(void (*handler)(int))
517 set_fatal_sighandler(handler);
518 set_jobctrl_sighandler(handler);
519 set_misc_sighandler(handler);
520 signal(SIGCHLD, handler);
523 static struct pipe *toplevel_list;
524 static sigjmp_buf toplevel_jb;
525 smallint ctrl_z_flag;
526 #if ENABLE_FEATURE_SH_STANDALONE
527 struct nofork_save_area nofork_save;
530 static void handler_ctrl_c(int sig)
532 debug_printf_jobs("got sig %d\n", sig);
533 // as usual we can have all kinds of nasty problems with leaked malloc data here
534 siglongjmp(toplevel_jb, 1);
537 static void handler_ctrl_z(int sig)
541 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
543 if (pid < 0) /* can't fork. Pretend there were no ctrl-Z */
546 if (!pid) { /* child */
548 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
549 set_every_sighandler(SIG_DFL);
550 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
551 debug_printf_jobs("returning in child\n");
552 /* return to nofork, it will eventually exit now,
553 * not return back to shell */
557 /* finish filling up pipe info */
558 toplevel_list->pgrp = pid; /* child is in its own pgrp */
559 toplevel_list->progs[0].pid = pid;
560 /* parent needs to longjmp out of running nofork.
561 * we will "return" exitcode 0, with child put in background */
562 // as usual we can have all kinds of nasty problems with leaked malloc data here
563 debug_printf_jobs("siglongjmp in parent\n");
564 siglongjmp(toplevel_jb, 1);
567 /* Restores tty foreground process group, and exits.
568 * May be called as signal handler for fatal signal
569 * (will faithfully resend signal to itself, producing correct exit state)
570 * or called directly with -EXITCODE.
571 * We also call it if xfunc is exiting. */
572 static void sigexit(int sig) ATTRIBUTE_NORETURN;
573 static void sigexit(int sig)
577 /* Disable all signals: job control, SIGPIPE, etc. */
578 sigfillset(&block_all);
579 sigprocmask(SIG_SETMASK, &block_all, NULL);
582 tcsetpgrp(interactive_fd, saved_tty_pgrp);
584 /* Not a signal, just exit */
588 /* Enable only this sig and kill ourself with it */
589 signal(sig, SIG_DFL);
590 sigdelset(&block_all, sig);
591 sigprocmask(SIG_SETMASK, &block_all, NULL);
593 _exit(1); /* Should not reach it */
596 /* Restores tty foreground process group, and exits. */
597 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
598 static void hush_exit(int exitcode)
600 fflush(NULL); /* flush all streams */
601 sigexit(- (exitcode & 0xff));
606 #define set_fatal_sighandler(handler) ((void)0)
607 #define set_jobctrl_sighandler(handler) ((void)0)
608 #define set_misc_sighandler(handler) ((void)0)
609 #define hush_exit(e) exit(e)
614 static const char *set_cwd(void)
616 if (cwd == bb_msg_unknown)
617 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
618 cwd = xrealloc_getcwd_or_warn((char *)cwd);
620 cwd = bb_msg_unknown;
624 /* built-in 'eval' handler */
625 static int builtin_eval(char **argv)
628 int rcode = EXIT_SUCCESS;
631 str = make_string(argv + 1);
632 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
633 FLAG_PARSE_SEMICOLON);
635 rcode = last_return_code;
640 /* built-in 'cd <path>' handler */
641 static int builtin_cd(char **argv)
645 newdir = getenv("HOME");
649 printf("cd: %s: %s\n", newdir, strerror(errno));
656 /* built-in 'exec' handler */
657 static int builtin_exec(char **argv)
660 return EXIT_SUCCESS; /* Really? */
661 pseudo_exec_argv(argv + 1);
665 /* built-in 'exit' handler */
666 static int builtin_exit(char **argv)
668 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
669 //puts("exit"); /* bash does it */
670 // TODO: warn if we have background jobs: "There are stopped jobs"
671 // On second consecutive 'exit', exit anyway.
674 hush_exit(last_return_code);
675 /* mimic bash: exit 123abc == exit 255 + error msg */
676 xfunc_error_retval = 255;
677 /* bash: exit -2 == exit 254, no error msg */
678 hush_exit(xatoi(argv[1]) & 0xff);
681 /* built-in 'export VAR=value' handler */
682 static int builtin_export(char **argv)
685 char *name = argv[1];
689 // ash emits: export VAR='VAL'
690 // bash: declare -x VAR="VAL"
691 // (both also escape as needed (quotes, $, etc))
702 const char *value = strchr(name, '=');
706 /* They are exporting something without an =VALUE */
708 value = get_local_var(name);
710 size_t ln = strlen(name);
712 tmp = realloc(name, ln+strlen(value)+2);
716 sprintf(tmp+ln, "=%s", value);
720 /* bash does not return an error when trying to export
721 * an undefined variable. Do likewise. */
727 bb_perror_msg("export");
729 res = set_local_var(name, 1);
737 /* built-in 'fg' and 'bg' handler */
738 static int builtin_fg_bg(char **argv)
745 /* If they gave us no args, assume they want the last backgrounded task */
747 for (pi = job_list; pi; pi = pi->next) {
748 if (pi->jobid == last_jobid) {
752 bb_error_msg("%s: no current job", argv[0]);
755 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
756 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
759 for (pi = job_list; pi; pi = pi->next) {
760 if (pi->jobid == jobnum) {
764 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
767 // TODO: bash prints a string representation
768 // of job being foregrounded (like "sleep 1 | cat")
769 if (*argv[0] == 'f') {
770 /* Put the job into the foreground. */
771 tcsetpgrp(interactive_fd, pi->pgrp);
774 /* Restart the processes in the job */
775 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
776 for (i = 0; i < pi->num_progs; i++) {
777 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
778 pi->progs[i].is_stopped = 0;
780 pi->stopped_progs = 0;
782 i = kill(- pi->pgrp, SIGCONT);
784 if (errno == ESRCH) {
785 delete_finished_bg_job(pi);
788 bb_perror_msg("kill (SIGCONT)");
792 if (*argv[0] == 'f') {
794 return checkjobs_and_fg_shell(pi);
800 /* built-in 'help' handler */
801 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
803 const struct built_in_command *x;
805 printf("\nBuilt-in commands:\n");
806 printf("-------------------\n");
807 for (x = bltins; x->cmd; x++) {
808 if (x->descr == NULL)
810 printf("%s\t%s\n", x->cmd, x->descr);
817 /* built-in 'jobs' handler */
818 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
821 const char *status_string;
823 for (job = job_list; job; job = job->next) {
824 if (job->running_progs == job->stopped_progs)
825 status_string = "Stopped";
827 status_string = "Running";
829 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
835 /* built-in 'pwd' handler */
836 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
842 /* built-in 'read VAR' handler */
843 static int builtin_read(char **argv)
851 string[0] = '\0'; /* In case stdin has only EOF */
853 fgets(string, sizeof(string), stdin);
855 var = malloc(strlen(argv[1]) + strlen(string) + 2);
857 sprintf(var, "%s=%s", argv[1], string);
858 res = set_local_var(var, 0);
862 bb_perror_msg("read");
863 free(var); /* So not move up to avoid breaking errno */
866 do res = getchar(); while (res != '\n' && res != EOF);
870 /* built-in 'set VAR=value' handler */
871 static int builtin_set(char **argv)
873 char *temp = argv[1];
877 for (e = top_vars; e; e = e->next)
878 printf("%s=%s\n", e->name, e->value);
880 set_local_var(temp, 0);
886 /* Built-in 'shift' handler */
887 static int builtin_shift(char **argv)
893 if (n >= 0 && n < global_argc) {
894 /* XXX This probably breaks $0 */
902 /* Built-in '.' handler (read-in and execute commands from file) */
903 static int builtin_source(char **argv)
911 /* XXX search through $PATH is missing */
912 input = fopen(argv[1], "r");
914 bb_error_msg("cannot open '%s'", argv[1]);
918 /* Now run the file */
919 /* XXX argv and argc are broken; need to save old global_argv
920 * (pointer only is OK!) on this stack frame,
921 * set global_argv=argv+1, recurse, and restore. */
922 mark_open(fileno(input));
923 status = parse_file_outer(input);
924 mark_closed(fileno(input));
929 static int builtin_umask(char **argv)
932 const char *arg = argv[1];
935 new_umask = strtoul(arg, &end, 8);
936 if (*end != '\0' || end == arg) {
940 new_umask = umask(0);
941 printf("%.3o\n", (unsigned) new_umask);
947 /* built-in 'unset VAR' handler */
948 static int builtin_unset(char **argv)
950 /* bash returned already true */
951 unset_local_var(argv[1]);
955 static int builtin_not_written(char **argv)
957 printf("builtin_%s not written\n", argv[0]);
961 static int b_check_space(o_string *o, int len)
963 /* It would be easy to drop a more restrictive policy
964 * in here, such as setting a maximum string length */
965 if (o->length + len > o->maxlen) {
966 char *old_data = o->data;
967 /* assert(data == NULL || o->maxlen != 0); */
968 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
969 o->data = realloc(o->data, 1 + o->maxlen);
970 if (o->data == NULL) {
974 return o->data == NULL;
977 static int b_addchr(o_string *o, int ch)
979 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
980 if (b_check_space(o, 1))
982 o->data[o->length] = ch;
984 o->data[o->length] = '\0';
988 static void b_reset(o_string *o)
996 static void b_free(o_string *o)
1004 /* My analysis of quoting semantics tells me that state information
1005 * is associated with a destination, not a source.
1007 static int b_addqchr(o_string *o, int ch, int quote)
1009 if (quote && strchr("*?[\\", ch)) {
1011 rc = b_addchr(o, '\\');
1015 return b_addchr(o, ch);
1018 static int b_adduint(o_string *o, unsigned i)
1021 char buf[sizeof(unsigned)*3 + 1];
1023 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1024 /* no escape checking necessary */
1025 do r = b_addchr(o, *p++); while (r == 0 && *p);
1029 static int static_get(struct in_str *i)
1032 if (ch == '\0') return EOF;
1036 static int static_peek(struct in_str *i)
1041 #if ENABLE_HUSH_INTERACTIVE
1042 #if ENABLE_FEATURE_EDITING
1043 static void cmdedit_set_initial_prompt(void)
1045 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1048 PS1 = getenv("PS1");
1053 #endif /* EDITING */
1055 static const char* setup_prompt_string(int promptmode)
1057 const char *prompt_str;
1058 debug_printf("setup_prompt_string %d ", promptmode);
1059 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1060 /* Set up the prompt */
1061 if (promptmode == 1) {
1064 ns = xmalloc(strlen(cwd)+4);
1065 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1072 prompt_str = (promptmode == 1) ? PS1 : PS2;
1074 debug_printf("result %s\n", prompt_str);
1078 #if ENABLE_FEATURE_EDITING
1079 static line_input_t *line_input_state;
1082 static int get_user_input(struct in_str *i)
1084 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1087 const char *prompt_str;
1088 prompt_str = setup_prompt_string(i->promptmode);
1089 #if ENABLE_FEATURE_EDITING
1091 ** enable command line editing only while a command line
1092 ** is actually being read; otherwise, we'll end up bequeathing
1093 ** atexit() handlers and other unwanted stuff to our
1094 ** child processes (rob@sysgo.de)
1096 r = read_line_input(prompt_str, the_command, BUFSIZ-1, line_input_state);
1098 fputs(prompt_str, stdout);
1100 the_command[0] = r = fgetc(i->file);
1101 /*the_command[1] = '\0'; - already is and never changed */
1105 return r; /* < 0 == EOF. Not meaningful otherwise */
1107 #endif /* INTERACTIVE */
1109 /* This is the magic location that prints prompts
1110 * and gets data back from the user */
1111 static int file_get(struct in_str *i)
1116 /* If there is data waiting, eat it up */
1118 ch = i->cached_ch ^ 0x100;
1122 /* need to double check i->file because we might be doing something
1123 * more complicated by now, like sourcing or substituting. */
1124 #if ENABLE_HUSH_INTERACTIVE
1125 if (interactive_fd && i->__promptme && i->file == stdin) {
1126 while (!i->p || !(interactive_fd && i->p[0])) {
1127 if (get_user_input(i) < 0)
1132 if (i->p && *i->p) {
1138 ch = fgetc(i->file);
1140 debug_printf("file_get: got a %d\n", ch);
1142 #if ENABLE_HUSH_INTERACTIVE
1149 /* All the callers guarantee this routine will never be
1150 * used right after a newline, so prompting is not needed.
1152 static int file_peek(struct in_str *i)
1156 return i->cached_ch ^ 0x100;
1158 ch = fgetc(i->file);
1159 i->cached_ch = ch ^ 0x100; /* ^ 0x100 so that it is never 0 */
1160 debug_printf("file_peek: got a %d '%c'\n", ch, ch);
1164 static void setup_file_in_str(struct in_str *i, FILE *f)
1166 i->peek = file_peek;
1168 #if ENABLE_HUSH_INTERACTIVE
1176 static void setup_string_in_str(struct in_str *i, const char *s)
1178 i->peek = static_peek;
1179 i->get = static_get;
1180 #if ENABLE_HUSH_INTERACTIVE
1187 static void mark_open(int fd)
1189 struct close_me *new = xmalloc(sizeof(struct close_me));
1191 new->next = close_me_head;
1192 close_me_head = new;
1195 static void mark_closed(int fd)
1197 struct close_me *tmp;
1198 if (close_me_head == NULL || close_me_head->fd != fd)
1199 bb_error_msg_and_die("corrupt close_me");
1200 tmp = close_me_head;
1201 close_me_head = close_me_head->next;
1205 static void close_all(void)
1208 for (c = close_me_head; c; c = c->next) {
1211 close_me_head = NULL;
1214 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1215 * and stderr if they are redirected. */
1216 static int setup_redirects(struct child_prog *prog, int squirrel[])
1219 struct redir_struct *redir;
1221 for (redir = prog->redirects; redir; redir = redir->next) {
1222 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1223 /* something went wrong in the parse. Pretend it didn't happen */
1226 if (redir->dup == -1) {
1227 mode = redir_table[redir->type].mode;
1228 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1230 /* this could get lost if stderr has been redirected, but
1231 bash and ash both lose it as well (though zsh doesn't!) */
1235 openfd = redir->dup;
1238 if (openfd != redir->fd) {
1239 if (squirrel && redir->fd < 3) {
1240 squirrel[redir->fd] = dup(redir->fd);
1245 dup2(openfd, redir->fd);
1246 if (redir->dup == -1)
1254 static void restore_redirects(int squirrel[])
1257 for (i = 0; i < 3; i++) {
1260 /* No error checking. I sure wouldn't know what
1261 * to do with an error if I found one! */
1269 /* XXX no exit() here. If you don't exec, use _exit instead.
1270 * The at_exit handlers apparently confuse the calling process,
1271 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1272 static void pseudo_exec_argv(char **argv)
1276 const struct built_in_command *x;
1278 for (i = 0; is_assignment(argv[i]); i++) {
1279 debug_printf("pid %d environment modification: %s\n",
1281 // FIXME: vfork case??
1282 p = insert_var_value(argv[i]);
1288 /* If a variable is assigned in a forest, and nobody listens,
1289 * was it ever really set?
1291 if (argv[0] == NULL) {
1292 _exit(EXIT_SUCCESS);
1296 * Check if the command matches any of the builtins.
1297 * Depending on context, this might be redundant. But it's
1298 * easier to waste a few CPU cycles than it is to figure out
1299 * if this is one of those cases.
1301 for (x = bltins; x->cmd; x++) {
1302 if (strcmp(argv[0], x->cmd) == 0) {
1303 debug_printf("builtin exec %s\n", argv[0]);
1304 rcode = x->function(argv);
1310 /* Check if the command matches any busybox internal commands
1312 * FIXME: This feature is not 100% safe, since
1313 * BusyBox is not fully reentrant, so we have no guarantee the things
1314 * from the .bss are still zeroed, or that things from .data are still
1315 * at their defaults. We could exec ourself from /proc/self/exe, but I
1316 * really dislike relying on /proc for things. We could exec ourself
1317 * from global_argv[0], but if we are in a chroot, we may not be able
1318 * to find ourself... */
1319 #if ENABLE_FEATURE_SH_STANDALONE
1320 debug_printf("running applet %s\n", argv[0]);
1321 run_applet_and_exit(argv[0], argv);
1322 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1323 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1325 debug_printf("exec of %s\n", argv[0]);
1326 execvp(argv[0], argv);
1327 bb_perror_msg("cannot exec '%s'", argv[0]);
1331 static void pseudo_exec(struct child_prog *child)
1333 // FIXME: buggy wrt NOMMU! Must not modify any global data
1334 // until it does exec/_exit, but currently it does.
1338 pseudo_exec_argv(child->argv);
1342 // FIXME: do not modify globals! Think vfork!
1343 #if ENABLE_HUSH_INTERACTIVE
1344 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1345 interactive_fd = 0; /* crucial!!!! */
1347 debug_printf_exec("pseudo_exec: run_list_real\n");
1348 rcode = run_list_real(child->group);
1349 /* OK to leak memory by not calling free_pipe_list,
1350 * since this process is about to exit */
1354 /* Can happen. See what bash does with ">foo" by itself. */
1355 debug_printf("trying to pseudo_exec null command\n");
1356 _exit(EXIT_SUCCESS);
1360 static const char *get_cmdtext(struct pipe *pi)
1366 /* This is subtle. ->cmdtext is created only on first backgrounding.
1367 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1368 * On subsequent bg argv is trashed, but we won't use it */
1371 argv = pi->progs[0].argv;
1372 if (!argv || !argv[0])
1373 return (pi->cmdtext = xzalloc(1));
1376 do len += strlen(*argv) + 1; while (*++argv);
1377 pi->cmdtext = p = xmalloc(len);
1378 argv = pi->progs[0].argv;
1380 len = strlen(*argv);
1381 memcpy(p, *argv, len);
1389 static void insert_bg_job(struct pipe *pi)
1391 struct pipe *thejob;
1394 /* Linear search for the ID of the job to use */
1396 for (thejob = job_list; thejob; thejob = thejob->next)
1397 if (thejob->jobid >= pi->jobid)
1398 pi->jobid = thejob->jobid + 1;
1400 /* Add thejob to the list of running jobs */
1402 thejob = job_list = xmalloc(sizeof(*thejob));
1404 for (thejob = job_list; thejob->next; thejob = thejob->next)
1406 thejob->next = xmalloc(sizeof(*thejob));
1407 thejob = thejob->next;
1410 /* Physically copy the struct job */
1411 memcpy(thejob, pi, sizeof(struct pipe));
1412 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1413 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1414 for (i = 0; i < pi->num_progs; i++) {
1415 // TODO: do we really need to have so many fields which are just dead weight
1416 // at execution stage?
1417 thejob->progs[i].pid = pi->progs[i].pid;
1419 //char **argv; /* program name and arguments */
1420 //struct pipe *group; /* if non-NULL, first in group or subshell */
1421 //int subshell; /* flag, non-zero if group must be forked */
1422 //struct redir_struct *redirects; /* I/O redirections */
1423 //glob_t glob_result; /* result of parameter globbing */
1424 //int is_stopped; /* is the program currently running? */
1425 //struct pipe *family; /* pointer back to the child's parent pipe */
1426 //int sp; /* number of SPECIAL_VAR_SYMBOL */
1429 thejob->next = NULL;
1430 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1432 /* We don't wait for background thejobs to return -- append it
1433 to the list of backgrounded thejobs and leave it alone */
1434 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1435 last_bg_pid = thejob->progs[0].pid;
1436 last_jobid = thejob->jobid;
1439 static void remove_bg_job(struct pipe *pi)
1441 struct pipe *prev_pipe;
1443 if (pi == job_list) {
1444 job_list = pi->next;
1446 prev_pipe = job_list;
1447 while (prev_pipe->next != pi)
1448 prev_pipe = prev_pipe->next;
1449 prev_pipe->next = pi->next;
1452 last_jobid = job_list->jobid;
1457 /* remove a backgrounded job */
1458 static void delete_finished_bg_job(struct pipe *pi)
1461 pi->stopped_progs = 0;
1467 /* Checks to see if any processes have exited -- if they
1468 have, figure out why and see if a job has completed */
1469 static int checkjobs(struct pipe* fg_pipe)
1480 attributes = WUNTRACED;
1481 if (fg_pipe == NULL) {
1482 attributes |= WNOHANG;
1485 /* Do we do this right?
1486 * bash-3.00# sleep 20 | false
1488 * [3]+ Stopped sleep 20 | false
1489 * bash-3.00# echo $?
1490 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1493 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1494 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1495 // + killall -STOP cat
1498 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1499 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1501 #ifdef DEBUG_SHELL_JOBS
1502 if (WIFSTOPPED(status))
1503 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1504 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1505 if (WIFSIGNALED(status))
1506 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1507 childpid, WTERMSIG(status), WEXITSTATUS(status));
1508 if (WIFEXITED(status))
1509 debug_printf_jobs("pid %d exited, exitcode %d\n",
1510 childpid, WEXITSTATUS(status));
1512 /* Were we asked to wait for fg pipe? */
1515 for (i = 0; i < fg_pipe->num_progs; i++) {
1516 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1517 if (fg_pipe->progs[i].pid == childpid) {
1518 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1520 fg_pipe->progs[i].pid = 0;
1521 fg_pipe->running_progs--;
1522 if (i == fg_pipe->num_progs-1)
1523 /* last process gives overall exitstatus */
1524 rcode = WEXITSTATUS(status);
1526 fg_pipe->progs[i].is_stopped = 1;
1527 fg_pipe->stopped_progs++;
1529 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1530 fg_pipe->running_progs, fg_pipe->stopped_progs);
1531 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1532 /* All processes in fg pipe have exited/stopped */
1534 if (fg_pipe->running_progs)
1535 insert_bg_job(fg_pipe);
1539 /* There are still running processes in the fg pipe */
1543 /* fall through to searching process in bg pipes */
1547 /* We asked to wait for bg or orphaned children */
1548 /* No need to remember exitcode in this case */
1549 for (pi = job_list; pi; pi = pi->next) {
1551 while (prognum < pi->num_progs) {
1552 if (pi->progs[prognum].pid == childpid)
1553 goto found_pi_and_prognum;
1559 /* Happens when shell is used as init process (init=/bin/sh) */
1560 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1564 found_pi_and_prognum:
1567 pi->progs[prognum].pid = 0;
1568 pi->running_progs--;
1569 if (!pi->running_progs) {
1570 printf(JOB_STATUS_FORMAT, pi->jobid,
1571 "Done", pi->cmdtext);
1572 delete_finished_bg_job(pi);
1576 pi->stopped_progs++;
1577 pi->progs[prognum].is_stopped = 1;
1582 /* wait found no children or failed */
1584 if (childpid && errno != ECHILD)
1585 bb_perror_msg("waitpid");
1587 /* move the shell to the foreground */
1588 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1589 // bb_perror_msg("tcsetpgrp-2");
1594 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1597 int rcode = checkjobs(fg_pipe);
1598 /* Job finished, move the shell to the foreground */
1600 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1601 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1602 bb_perror_msg("tcsetpgrp-4a");
1607 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1608 * to finish. See checkjobs().
1610 * return code is normally -1, when the caller has to wait for children
1611 * to finish to determine the exit status of the pipe. If the pipe
1612 * is a simple builtin command, however, the action is done by the
1613 * time run_pipe_real returns, and the exit code is provided as the
1616 * The input of the pipe is always stdin, the output is always
1617 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1618 * because it tries to avoid running the command substitution in
1619 * subshell, when that is in fact necessary. The subshell process
1620 * now has its stdout directed to the input of the appropriate pipe,
1621 * so this routine is noticeably simpler.
1623 static int run_pipe_real(struct pipe *pi)
1626 int nextin, nextout;
1627 int pipefds[2]; /* pipefds[0] is for reading */
1628 struct child_prog *child;
1629 const struct built_in_command *x;
1631 /* it is not always needed, but we aim to smaller code */
1632 int squirrel[] = { -1, -1, -1 };
1634 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1636 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1642 pi->running_progs = 1;
1643 pi->stopped_progs = 0;
1645 /* Check if this is a simple builtin (not part of a pipe).
1646 * Builtins within pipes have to fork anyway, and are handled in
1647 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1649 child = &(pi->progs[0]);
1650 if (single_fg && child->group && child->subshell == 0) {
1651 debug_printf("non-subshell grouping\n");
1652 setup_redirects(child, squirrel);
1653 debug_printf_exec(": run_list_real\n");
1654 rcode = run_list_real(child->group);
1655 restore_redirects(squirrel);
1656 debug_printf_exec("run_pipe_real return %d\n", rcode);
1660 if (single_fg && child->argv != NULL) {
1661 char **argv = child->argv;
1663 for (i = 0; is_assignment(argv[i]); i++)
1665 if (i != 0 && argv[i] == NULL) {
1666 /* assignments, but no command: set the local environment */
1667 for (i = 0; argv[i] != NULL; i++) {
1668 /* Ok, this case is tricky. We have to decide if this is a
1669 * local variable, or an already exported variable. If it is
1670 * already exported, we have to export the new value. If it is
1671 * not exported, we need only set this as a local variable.
1672 * This junk is all to decide whether or not to export this
1676 name = xstrdup(argv[i]);
1677 debug_printf("local environment set: %s\n", name);
1678 value = strchr(name, '=');
1681 if (get_local_var(name)) {
1685 p = insert_var_value(argv[i]);
1686 set_local_var(p, export_me);
1690 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1692 for (i = 0; is_assignment(argv[i]); i++) {
1693 p = insert_var_value(argv[i]);
1703 str = make_string(argv + i);
1704 debug_printf_exec(": parse_string_outer '%s'\n", str);
1705 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1707 debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1708 return last_return_code;
1710 for (x = bltins; x->cmd; x++) {
1711 if (strcmp(argv[i], x->cmd) == 0) {
1712 if (x->function == builtin_exec && argv[i+1] == NULL) {
1713 debug_printf("magic exec\n");
1714 setup_redirects(child, NULL);
1715 return EXIT_SUCCESS;
1717 debug_printf("builtin inline %s\n", argv[0]);
1718 /* XXX setup_redirects acts on file descriptors, not FILEs.
1719 * This is perfect for work that comes after exec().
1720 * Is it really safe for inline use? Experimentally,
1721 * things seem to work with glibc. */
1722 // TODO: fflush(NULL)?
1723 setup_redirects(child, squirrel);
1724 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1725 rcode = x->function(argv + i);
1726 restore_redirects(squirrel);
1727 debug_printf_exec("run_pipe_real return %d\n", rcode);
1731 #if ENABLE_FEATURE_SH_STANDALONE
1733 const struct bb_applet *a = find_applet_by_name(argv[i]);
1734 if (a && a->nofork) {
1735 setup_redirects(child, squirrel);
1736 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv[i], argv[i+1]);
1737 save_nofork_data(&nofork_save);
1738 rcode = run_nofork_applet_prime(&nofork_save, a, argv + i);
1739 restore_redirects(squirrel);
1740 debug_printf_exec("run_pipe_real return %d\n", rcode);
1747 /* Going to fork a child per each pipe member */
1748 pi->running_progs = 0;
1750 /* Disable job control signals for shell (parent) and
1751 * for initial child code after fork */
1752 set_jobctrl_sighandler(SIG_IGN);
1754 for (i = 0; i < pi->num_progs; i++) {
1755 child = &(pi->progs[i]);
1757 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1759 debug_printf_exec(": pipe member with no argv\n");
1761 /* pipes are inserted between pairs of commands */
1762 if ((i + 1) < pi->num_progs) {
1763 if (pipe(pipefds) < 0)
1764 bb_perror_msg_and_die("pipe");
1765 nextout = pipefds[1];
1771 /* XXX test for failed fork()? */
1773 child->pid = fork();
1775 child->pid = vfork();
1777 if (!child->pid) { /* child */
1778 /* Every child adds itself to new process group
1779 * with pgid == pid of first child in pipe */
1781 if (interactive_fd) {
1782 /* Don't do pgrp restore anymore on fatal signals */
1783 set_fatal_sighandler(SIG_DFL);
1784 if (pi->pgrp < 0) /* true for 1st process only */
1785 pi->pgrp = getpid();
1786 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1787 /* We do it in *every* child, not just first,
1789 tcsetpgrp(interactive_fd, pi->pgrp);
1793 // in non-interactive case fatal sigs are already SIG_DFL
1803 if (pipefds[0] != -1) {
1804 close(pipefds[0]); /* opposite end of our output pipe */
1806 /* Like bash, explicit redirects override pipes,
1807 * and the pipe fd is available for dup'ing. */
1808 setup_redirects(child, NULL);
1810 /* Restore default handlers just prior to exec */
1811 set_jobctrl_sighandler(SIG_DFL);
1812 set_misc_sighandler(SIG_DFL);
1813 signal(SIGCHLD, SIG_DFL);
1817 pi->running_progs++;
1820 /* Second and next children need to know pid of first one */
1822 pi->pgrp = child->pid;
1825 /* Don't check for errors. The child may be dead already,
1826 * in which case setpgid returns error code EACCES. */
1827 //why we do it at all?? child does it itself
1828 //if (interactive_fd)
1829 // setpgid(child->pid, pi->pgrp);
1836 /* If there isn't another process, nextin is garbage
1837 but it doesn't matter */
1838 nextin = pipefds[0];
1840 debug_printf_exec("run_pipe_real return -1\n");
1844 #ifndef debug_print_tree
1845 static void debug_print_tree(struct pipe *pi, int lvl)
1847 static const char *PIPE[] = {
1853 static const char *RES[] = {
1854 [RES_NONE ] = "NONE" ,
1856 [RES_THEN ] = "THEN" ,
1857 [RES_ELIF ] = "ELIF" ,
1858 [RES_ELSE ] = "ELSE" ,
1860 [RES_FOR ] = "FOR" ,
1861 [RES_WHILE] = "WHILE",
1862 [RES_UNTIL] = "UNTIL",
1864 [RES_DONE ] = "DONE" ,
1865 [RES_XXXX ] = "XXXX" ,
1867 [RES_SNTX ] = "SNTX" ,
1873 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1874 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1876 while (prn < pi->num_progs) {
1877 struct child_prog *child = &pi->progs[prn];
1878 char **argv = child->argv;
1880 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1882 fprintf(stderr, " group %s: (argv=%p)\n",
1883 (child->subshell ? "()" : "{}"),
1885 debug_print_tree(child->group, lvl+1);
1889 if (argv) while (*argv) {
1890 fprintf(stderr, " '%s'", *argv);
1893 fprintf(stderr, "\n");
1902 // NB: called by pseudo_exec, and therefore must not modify any
1903 // global data until exec/_exit (we can be a child after vfork!)
1904 static int run_list_real(struct pipe *pi)
1912 char *save_name = NULL;
1914 char **save_list = NULL;
1919 int rcode = 0; /* probably for gcc only */
1920 int flag_restore = 0;
1921 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1922 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1924 debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1926 /* check syntax for "for" */
1927 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1928 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1929 && (rpipe->next == NULL)
1931 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1932 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1935 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1936 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1938 /* TODO: what is tested in the first condition? */
1939 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1940 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1946 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1947 * We are saving state before entering outermost list ("while...done")
1948 * so that ctrl-Z will correctly background _entire_ outermost list,
1949 * not just a part of it (like "sleep 1 | exit 2") */
1950 if (++level == 1 && interactive_fd) {
1951 if (sigsetjmp(toplevel_jb, 1)) {
1952 /* ctrl-Z forked and we are parent; or ctrl-C.
1953 * Sighandler has longjmped us here */
1954 signal(SIGINT, SIG_IGN);
1955 signal(SIGTSTP, SIG_IGN);
1956 /* Restore level (we can be coming from deep inside
1959 #if ENABLE_FEATURE_SH_STANDALONE
1960 if (nofork_save.saved) { /* if save area is valid */
1961 debug_printf_jobs("exiting nofork early\n");
1962 restore_nofork_data(&nofork_save);
1966 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1967 * Remember this child as background job */
1970 /* ctrl-C. We just stop doing whatever we were doing */
1976 /* ctrl-Z handler will store pid etc in pi */
1979 #if ENABLE_FEATURE_SH_STANDALONE
1980 nofork_save.saved = 0; /* in case we will run a nofork later */
1982 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1983 signal(SIGINT, handler_ctrl_c);
1987 for (; pi; pi = flag_restore ? rpipe : pi->next) {
1989 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
1996 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1997 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1998 if (rmode == skip_more_in_this_rmode && flag_skip) {
1999 if (pi->followup == PIPE_SEQ)
2004 skip_more_in_this_rmode = RES_XXXX;
2005 if (rmode == RES_THEN || rmode == RES_ELSE)
2006 if_code = next_if_code;
2007 if (rmode == RES_THEN && if_code)
2009 if (rmode == RES_ELSE && !if_code)
2011 if (rmode == RES_ELIF && !if_code)
2013 if (rmode == RES_FOR && pi->num_progs) {
2015 /* if no variable values after "in" we skip "for" */
2016 if (!pi->next->progs->argv)
2018 /* create list of variable values */
2019 list = make_list_in(pi->next->progs->argv,
2020 pi->progs->argv[0]);
2022 save_name = pi->progs->argv[0];
2023 pi->progs->argv[0] = NULL;
2027 free(pi->progs->argv[0]);
2031 pi->progs->argv[0] = save_name;
2032 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2035 /* insert new value from list for variable */
2036 free(pi->progs->argv[0]);
2037 pi->progs->argv[0] = *list++;
2038 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2040 if (rmode == RES_IN)
2042 if (rmode == RES_DO) {
2046 if (rmode == RES_DONE) {
2053 if (pi->num_progs == 0)
2055 save_num_progs = pi->num_progs; /* save number of programs */
2056 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2057 rcode = run_pipe_real(pi);
2059 /* We only ran a builtin: rcode was set by the return value
2060 * of run_pipe_real(), and we don't need to wait for anything. */
2061 } else if (pi->followup == PIPE_BG) {
2062 /* What does bash do with attempts to background builtins? */
2064 /* Even bash 3.2 doesn't do that well with nested bg:
2065 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2066 * I'm considering NOT treating inner bgs as jobs -
2067 * thus maybe "if (level == 1 && pi->followup == PIPE_BG)"
2072 rcode = EXIT_SUCCESS;
2075 /* Paranoia, just "interactive_fd" should be enough */
2076 if (level == 1 && interactive_fd) {
2077 rcode = checkjobs_and_fg_shell(pi);
2081 rcode = checkjobs(pi);
2083 debug_printf_exec(": checkjobs returned %d\n", rcode);
2085 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2086 last_return_code = rcode;
2087 pi->num_progs = save_num_progs; /* restore number of programs */
2088 if (rmode == RES_IF || rmode == RES_ELIF)
2089 next_if_code = rcode; /* can be overwritten a number of times */
2090 if (rmode == RES_WHILE)
2091 flag_rep = !last_return_code;
2092 if (rmode == RES_UNTIL)
2093 flag_rep = last_return_code;
2094 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2095 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2097 skip_more_in_this_rmode = rmode;
2104 /* ctrl-Z forked somewhere in the past, we are the child,
2105 * and now we completed running the list. Exit. */
2111 debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2115 /* return code is the exit status of the pipe */
2116 static int free_pipe(struct pipe *pi, int indent)
2119 struct child_prog *child;
2120 struct redir_struct *r, *rnext;
2121 int a, i, ret_code = 0;
2123 if (pi->stopped_progs > 0)
2125 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2126 for (i = 0; i < pi->num_progs; i++) {
2127 child = &pi->progs[i];
2128 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2130 for (a = 0, p = child->argv; *p; a++, p++) {
2131 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2133 globfree(&child->glob_result);
2135 } else if (child->group) {
2136 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2137 ret_code = free_pipe_list(child->group, indent+3);
2138 debug_printf_clean("%s end group\n", indenter(indent));
2140 debug_printf_clean("%s (nil)\n", indenter(indent));
2142 for (r = child->redirects; r; r = rnext) {
2143 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2145 /* guard against the case >$FOO, where foo is unset or blank */
2146 if (r->word.gl_pathv) {
2147 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2151 debug_printf_clean("&%d\n", r->dup);
2156 child->redirects = NULL;
2158 free(pi->progs); /* children are an array, they get freed all at once */
2167 static int free_pipe_list(struct pipe *head, int indent)
2169 int rcode = 0; /* if list has no members */
2170 struct pipe *pi, *next;
2172 for (pi = head; pi; pi = next) {
2173 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2174 rcode = free_pipe(pi, indent);
2175 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2177 /*pi->next = NULL;*/
2183 /* Select which version we will use */
2184 static int run_list(struct pipe *pi)
2187 debug_printf_exec("run_list entered\n");
2188 if (fake_mode == 0) {
2189 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2190 rcode = run_list_real(pi);
2192 /* free_pipe_list has the side effect of clearing memory.
2193 * In the long run that function can be merged with run_list_real,
2194 * but doing that now would hobble the debugging effort. */
2195 free_pipe_list(pi, 0);
2196 debug_printf_exec("run_list return %d\n", rcode);
2200 /* The API for glob is arguably broken. This routine pushes a non-matching
2201 * string into the output structure, removing non-backslashed backslashes.
2202 * If someone can prove me wrong, by performing this function within the
2203 * original glob(3) api, feel free to rewrite this routine into oblivion.
2204 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2205 * XXX broken if the last character is '\\', check that before calling.
2207 static int globhack(const char *src, int flags, glob_t *pglob)
2212 for (cnt = 1, s = src; s && *s; s++) {
2213 if (*s == '\\') s++;
2218 return GLOB_NOSPACE;
2219 if (!(flags & GLOB_APPEND)) {
2220 pglob->gl_pathv = NULL;
2221 pglob->gl_pathc = 0;
2225 pathc = ++pglob->gl_pathc;
2226 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2227 if (pglob->gl_pathv == NULL)
2228 return GLOB_NOSPACE;
2229 pglob->gl_pathv[pathc-1] = dest;
2230 pglob->gl_pathv[pathc] = NULL;
2231 for (s = src; s && *s; s++, dest++) {
2232 if (*s == '\\') s++;
2239 /* XXX broken if the last character is '\\', check that before calling */
2240 static int glob_needed(const char *s)
2243 if (*s == '\\') s++;
2244 if (strchr("*[?", *s)) return 1;
2249 static int xglob(o_string *dest, int flags, glob_t *pglob)
2253 /* short-circuit for null word */
2254 /* we can code this better when the debug_printf's are gone */
2255 if (dest->length == 0) {
2256 if (dest->nonnull) {
2257 /* bash man page calls this an "explicit" null */
2258 gr = globhack(dest->data, flags, pglob);
2259 debug_printf("globhack returned %d\n", gr);
2263 } else if (glob_needed(dest->data)) {
2264 gr = glob(dest->data, flags, NULL, pglob);
2265 debug_printf("glob returned %d\n", gr);
2266 if (gr == GLOB_NOMATCH) {
2267 /* quote removal, or more accurately, backslash removal */
2268 gr = globhack(dest->data, flags, pglob);
2269 debug_printf("globhack returned %d\n", gr);
2272 gr = globhack(dest->data, flags, pglob);
2273 debug_printf("globhack returned %d\n", gr);
2275 if (gr == GLOB_NOSPACE)
2276 bb_error_msg_and_die("out of memory during glob");
2277 if (gr != 0) { /* GLOB_ABORTED ? */
2278 bb_error_msg("glob(3) error %d", gr);
2280 /* globprint(glob_target); */
2284 static char **make_list_in(char **inp, char *name)
2287 int name_len = strlen(name);
2292 /* create list of variable values */
2293 list = xmalloc(sizeof(*list));
2294 for (i = 0; inp[i]; i++) {
2295 p3 = insert_var_value(inp[i]);
2302 p2 = strchr(p1, ' ');
2309 /* we use n + 2 in realloc for list, because we add
2310 * new element and then we will add NULL element */
2311 list = xrealloc(list, sizeof(*list) * (n + 2));
2312 list[n] = xmalloc(2 + name_len + len);
2313 strcpy(list[n], name);
2314 strcat(list[n], "=");
2315 strncat(list[n], p1, len);
2316 list[n++][name_len + len + 1] = '\0';
2319 if (p3 != inp[i]) free(p3);
2325 static char *insert_var_value(char *inp)
2327 int res_str_len = 0;
2330 char *p, *res_str = NULL;
2333 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2336 res_str = xrealloc(res_str, (res_str_len + len));
2337 strncpy((res_str + res_str_len), inp, len);
2341 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2343 p1 = lookup_param(inp);
2345 len = res_str_len + strlen(p1);
2346 res_str = xrealloc(res_str, (1 + len));
2347 strcpy((res_str + res_str_len), p1);
2350 *p = SPECIAL_VAR_SYMBOL;
2355 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2356 strcpy((res_str + res_str_len), inp);
2357 while ((p = strchr(res_str, '\n'))) {
2361 return (res_str == NULL) ? inp : res_str;
2364 /* This is used to get/check local shell variables */
2365 static const char *get_local_var(const char *s)
2367 struct variables *cur;
2371 for (cur = top_vars; cur; cur = cur->next) {
2372 if (strcmp(cur->name, s) == 0)
2378 /* This is used to set local shell variables
2379 flg_export == 0 if only local (not exporting) variable
2380 flg_export == 1 if "new" exporting environ
2381 flg_export > 1 if current startup environ (not call putenv()) */
2382 static int set_local_var(const char *s, int flg_export)
2386 struct variables *cur;
2390 /* Assume when we enter this function that we are already in
2391 * NAME=VALUE format. So the first order of business is to
2392 * split 's' on the '=' into 'name' and 'value' */
2393 value = strchr(name, '=');
2394 /*if (value == 0 && ++value == 0) ??? -vda */
2395 if (value == NULL || value[1] == '\0') {
2401 for (cur = top_vars; cur; cur = cur->next) {
2402 if (strcmp(cur->name, name) == 0) {
2403 if (strcmp(cur->value, value) == 0) {
2404 if (flg_export > 0 && cur->flg_export == 0)
2405 cur->flg_export = flg_export;
2408 } else if (cur->flg_read_only) {
2409 bb_error_msg("%s: readonly variable", name);
2412 if (flg_export > 0 || cur->flg_export > 1)
2413 cur->flg_export = 1;
2414 free((char*)cur->value);
2415 cur->value = strdup(value);
2421 // TODO: need simpler/generic rollback on malloc failure - see ash
2422 cur = malloc(sizeof(*cur));
2426 cur->name = strdup(name);
2431 struct variables *bottom = top_vars;
2432 cur->value = strdup(value);
2434 cur->flg_export = flg_export;
2435 cur->flg_read_only = 0;
2436 while (bottom->next)
2437 bottom = bottom->next;
2442 if (result == 0 && cur->flg_export == 1) {
2444 result = putenv(name);
2447 if (result > 0) /* equivalent to previous set */
2453 static void unset_local_var(const char *name)
2455 struct variables *cur, *next;
2459 for (cur = top_vars; cur; cur = cur->next) {
2460 if (strcmp(cur->name, name) == 0) {
2461 if (cur->flg_read_only) {
2462 bb_error_msg("%s: readonly variable", name);
2465 if (cur->flg_export)
2466 unsetenv(cur->name);
2467 free((char*)cur->name);
2468 free((char*)cur->value);
2470 while (next->next != cur)
2472 next->next = cur->next;
2479 static int is_assignment(const char *s)
2481 if (!s || !isalpha(*s))
2484 while (isalnum(*s) || *s == '_')
2489 /* the src parameter allows us to peek forward to a possible &n syntax
2490 * for file descriptor duplication, e.g., "2>&1".
2491 * Return code is 0 normally, 1 if a syntax error is detected in src.
2492 * Resource errors (in xmalloc) cause the process to exit */
2493 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2494 struct in_str *input)
2496 struct child_prog *child = ctx->child;
2497 struct redir_struct *redir = child->redirects;
2498 struct redir_struct *last_redir = NULL;
2500 /* Create a new redir_struct and drop it onto the end of the linked list */
2503 redir = redir->next;
2505 redir = xmalloc(sizeof(struct redir_struct));
2507 redir->word.gl_pathv = NULL;
2509 last_redir->next = redir;
2511 child->redirects = redir;
2514 redir->type = style;
2515 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2517 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2519 /* Check for a '2>&1' type redirect */
2520 redir->dup = redirect_dup_num(input);
2521 if (redir->dup == -2) return 1; /* syntax error */
2522 if (redir->dup != -1) {
2523 /* Erik had a check here that the file descriptor in question
2524 * is legit; I postpone that to "run time"
2525 * A "-" representation of "close me" shows up as a -3 here */
2526 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2528 /* We do _not_ try to open the file that src points to,
2529 * since we need to return and let src be expanded first.
2530 * Set ctx->pending_redirect, so we know what to do at the
2531 * end of the next parsed word.
2533 ctx->pending_redirect = redir;
2538 static struct pipe *new_pipe(void)
2541 pi = xzalloc(sizeof(struct pipe));
2542 /*pi->num_progs = 0;*/
2543 /*pi->progs = NULL;*/
2544 /*pi->next = NULL;*/
2545 /*pi->followup = 0; invalid */
2547 pi->r_mode = RES_NONE;
2551 static void initialize_context(struct p_context *ctx)
2554 ctx->pending_redirect = NULL;
2556 ctx->list_head = new_pipe();
2557 ctx->pipe = ctx->list_head;
2558 ctx->res_w = RES_NONE;
2561 done_command(ctx); /* creates the memory for working child */
2564 /* normal return is 0
2565 * if a reserved word is found, and processed, return 1
2566 * should handle if, then, elif, else, fi, for, while, until, do, done.
2567 * case, function, and select are obnoxious, save those for later.
2569 static int reserved_word(o_string *dest, struct p_context *ctx)
2571 struct reserved_combo {
2576 /* Mostly a list of accepted follow-up reserved words.
2577 * FLAG_END means we are done with the sequence, and are ready
2578 * to turn the compound list into a command.
2579 * FLAG_START means the word must start a new compound list.
2581 static const struct reserved_combo reserved_list[] = {
2582 { "if", RES_IF, FLAG_THEN | FLAG_START },
2583 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2584 { "elif", RES_ELIF, FLAG_THEN },
2585 { "else", RES_ELSE, FLAG_FI },
2586 { "fi", RES_FI, FLAG_END },
2587 { "for", RES_FOR, FLAG_IN | FLAG_START },
2588 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2589 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2590 { "in", RES_IN, FLAG_DO },
2591 { "do", RES_DO, FLAG_DONE },
2592 { "done", RES_DONE, FLAG_END }
2594 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2595 const struct reserved_combo *r;
2597 for (r = reserved_list; r < reserved_list + NRES; r++) {
2598 if (strcmp(dest->data, r->literal) == 0) {
2599 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2600 if (r->flag & FLAG_START) {
2601 struct p_context *new = xmalloc(sizeof(struct p_context));
2602 debug_printf("push stack\n");
2603 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2606 ctx->res_w = RES_SNTX;
2610 *new = *ctx; /* physical copy */
2611 initialize_context(ctx);
2613 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2615 ctx->res_w = RES_SNTX;
2619 ctx->res_w = r->code;
2620 ctx->old_flag = r->flag;
2621 if (ctx->old_flag & FLAG_END) {
2622 struct p_context *old;
2623 debug_printf("pop stack\n");
2624 done_pipe(ctx, PIPE_SEQ);
2626 old->child->group = ctx->list_head;
2627 old->child->subshell = 0;
2628 *ctx = *old; /* physical copy */
2638 /* Normal return is 0.
2639 * Syntax or xglob errors return 1. */
2640 static int done_word(o_string *dest, struct p_context *ctx)
2642 struct child_prog *child = ctx->child;
2643 glob_t *glob_target;
2646 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2647 if (dest->length == 0 && !dest->nonnull) {
2648 debug_printf_parse("done_word return 0: true null, ignored\n");
2651 if (ctx->pending_redirect) {
2652 glob_target = &ctx->pending_redirect->word;
2656 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2659 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2660 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2661 if (reserved_word(dest, ctx)) {
2662 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2663 return (ctx->res_w == RES_SNTX);
2666 glob_target = &child->glob_result;
2668 flags |= GLOB_APPEND;
2670 gr = xglob(dest, flags, glob_target);
2672 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2677 if (ctx->pending_redirect) {
2678 ctx->pending_redirect = NULL;
2679 if (glob_target->gl_pathc != 1) {
2680 bb_error_msg("ambiguous redirect");
2681 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2685 child->argv = glob_target->gl_pathv;
2687 if (ctx->res_w == RES_FOR) {
2688 done_word(dest, ctx);
2689 done_pipe(ctx, PIPE_SEQ);
2691 debug_printf_parse("done_word return 0\n");
2695 /* The only possible error here is out of memory, in which case
2697 static int done_command(struct p_context *ctx)
2699 /* The child is really already in the pipe structure, so
2700 * advance the pipe counter and make a new, null child. */
2701 struct pipe *pi = ctx->pipe;
2702 struct child_prog *child = ctx->child;
2705 if (child->group == NULL
2706 && child->argv == NULL
2707 && child->redirects == NULL
2709 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2710 return pi->num_progs;
2713 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2715 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2718 /* Only real trickiness here is that the uncommitted
2719 * child structure is not counted in pi->num_progs. */
2720 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2721 child = &pi->progs[pi->num_progs];
2723 memset(child, 0, sizeof(*child));
2724 /*child->redirects = NULL;*/
2725 /*child->argv = NULL;*/
2726 /*child->is_stopped = 0;*/
2727 /*child->group = NULL;*/
2728 /*child->glob_result.gl_pathv = NULL;*/
2731 child->type = ctx->parse_type;
2734 /* but ctx->pipe and ctx->list_head remain unchanged */
2736 return pi->num_progs; /* used only for 0/nonzero check */
2739 static int done_pipe(struct p_context *ctx, pipe_style type)
2744 debug_printf_parse("done_pipe entered, followup %d\n", type);
2745 not_null = done_command(ctx); /* implicit closure of previous command */
2746 ctx->pipe->followup = type;
2747 ctx->pipe->r_mode = ctx->res_w;
2748 /* Without this check, even just <enter> on command line generates
2749 * tree of three NOPs (!). Which is harmless but annoying.
2750 * IOW: it is safe to do it unconditionally. */
2753 ctx->pipe->next = new_p;
2756 done_command(ctx); /* set up new pipe to accept commands */
2758 debug_printf_parse("done_pipe return 0\n");
2762 /* peek ahead in the in_str to find out if we have a "&n" construct,
2763 * as in "2>&1", that represents duplicating a file descriptor.
2764 * returns either -2 (syntax error), -1 (no &), or the number found.
2766 static int redirect_dup_num(struct in_str *input)
2768 int ch, d = 0, ok = 0;
2770 if (ch != '&') return -1;
2772 b_getch(input); /* get the & */
2776 return -3; /* "-" represents "close me" */
2778 while (isdigit(ch)) {
2779 d = d*10 + (ch-'0');
2786 bb_error_msg("ambiguous redirect");
2790 /* If a redirect is immediately preceded by a number, that number is
2791 * supposed to tell which file descriptor to redirect. This routine
2792 * looks for such preceding numbers. In an ideal world this routine
2793 * needs to handle all the following classes of redirects...
2794 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2795 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2796 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2797 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2798 * A -1 output from this program means no valid number was found, so the
2799 * caller should use the appropriate default for this redirection.
2801 static int redirect_opt_num(o_string *o)
2807 for (num = 0; num < o->length; num++) {
2808 if (!isdigit(*(o->data + num))) {
2812 /* reuse num (and save an int) */
2813 num = atoi(o->data);
2818 static FILE *generate_stream_from_list(struct pipe *head)
2821 int pid, channel[2];
2822 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2829 bb_perror_msg_and_die("fork");
2830 } else if (pid == 0) {
2832 if (channel[1] != 1) {
2833 dup2(channel[1], 1);
2836 _exit(run_list_real(head)); /* leaks memory */
2838 debug_printf("forked child %d\n", pid);
2840 pf = fdopen(channel[0], "r");
2841 debug_printf("pipe on FILE *%p\n", pf);
2845 /* Return code is exit status of the process that is run. */
2846 static int process_command_subs(o_string *dest, struct p_context *ctx,
2847 struct in_str *input, const char *subst_end)
2850 o_string result = NULL_O_STRING;
2851 struct p_context inner;
2853 struct in_str pipe_str;
2854 initialize_context(&inner);
2856 /* recursion to generate command */
2857 retcode = parse_stream(&result, &inner, input, subst_end);
2858 if (retcode != 0) return retcode; /* syntax error or EOF */
2859 done_word(&result, &inner);
2860 done_pipe(&inner, PIPE_SEQ);
2863 p = generate_stream_from_list(inner.list_head);
2864 if (p == NULL) return 1;
2865 mark_open(fileno(p));
2866 // FIXME: need to flag pipe_str to somehow discard all trailing newlines.
2867 // Example: echo "TEST`date;echo;echo`BEST"
2868 // must produce one line: TEST<date>BEST
2869 setup_file_in_str(&pipe_str, p);
2871 /* now send results of command back into original context */
2872 // FIXME: must not do quote parsing of the output!
2873 // Example: echo "TEST`echo '$(echo ZZ)'`BEST"
2874 // must produce TEST$(echo ZZ)BEST, not TESTZZBEST.
2875 // Example: echo "TEST`echo "'"`BEST"
2876 // must produce TEST'BEST
2877 // (maybe by setting all chars flagged as literals in map[]?)
2879 retcode = parse_stream(dest, ctx, &pipe_str, NULL);
2880 /* XXX In case of a syntax error, should we try to kill the child?
2881 * That would be tough to do right, so just read until EOF. */
2883 while (b_getch(&pipe_str) != EOF)
2887 debug_printf("done reading from pipe, pclose()ing\n");
2888 /* This is the step that wait()s for the child. Should be pretty
2889 * safe, since we just read an EOF from its stdout. We could try
2890 * to better, by using wait(), and keeping track of background jobs
2891 * at the same time. That would be a lot of work, and contrary
2892 * to the KISS philosophy of this program. */
2893 mark_closed(fileno(p));
2894 retcode = pclose(p);
2895 free_pipe_list(inner.list_head, 0);
2896 debug_printf("pclosed, retcode=%d\n", retcode);
2900 static int parse_group(o_string *dest, struct p_context *ctx,
2901 struct in_str *input, int ch)
2904 const char *endch = NULL;
2905 struct p_context sub;
2906 struct child_prog *child = ctx->child;
2908 debug_printf_parse("parse_group entered\n");
2911 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
2914 initialize_context(&sub);
2918 child->subshell = 1;
2924 syntax(); /* really logic error */
2926 rcode = parse_stream(dest, &sub, input, endch);
2927 done_word(dest, &sub); /* finish off the final word in the subcontext */
2928 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2929 child->group = sub.list_head;
2931 debug_printf_parse("parse_group return %d\n", rcode);
2933 /* child remains "open", available for possible redirects */
2936 /* Basically useful version until someone wants to get fancier,
2937 * see the bash man page under "Parameter Expansion" */
2938 static const char *lookup_param(const char *src)
2940 const char *p = NULL;
2944 p = get_local_var(src);
2949 /* Make new string for parser */
2950 static char* make_string(char ** inp)
2957 for (n = 0; inp[n]; n++) {
2958 p = insert_var_value(inp[n]);
2959 str = xrealloc(str, (len + strlen(p)));
2966 len = strlen(str) + 3;
2967 if (p != inp[n]) free(p);
2975 /* return code: 0 for OK, 1 for syntax error */
2976 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2980 int ch = input->peek(input); /* first character after the $ */
2982 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
2984 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2988 if (!isalnum(ch) && ch != '_')
2990 debug_printf_parse(": '%c'\n", ch);
2994 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2995 } else if (isdigit(ch)) {
2996 i = ch - '0'; /* XXX is $0 special? */
2997 if (i < global_argc) {
2998 parse_string(dest, ctx, global_argv[i]); /* recursion */
3001 } else switch (ch) {
3003 b_adduint(dest, getpid());
3007 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
3011 b_adduint(dest, last_return_code);
3015 b_adduint(dest, global_argc ? global_argc-1 : 0);
3019 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3022 /* XXX maybe someone will try to escape the '}' */
3024 ch = b_getch(input);
3027 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3032 debug_printf_parse(": '%c'\n", ch);
3035 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3039 process_command_subs(dest, ctx, input, ")");
3043 for (i = 1; i < global_argc; i++) {
3044 parse_string(dest, ctx, global_argv[i]);
3045 if (i+1 < global_argc)
3046 parse_string(dest, ctx, sep);
3052 /* still unhandled, but should be eventually */
3053 bb_error_msg("unhandled syntax: $%c", ch);
3057 b_addqchr(dest,'$', dest->quote);
3059 /* Eat the character if the flag was set. If the compiler
3060 * is smart enough, we could substitute "b_getch(input);"
3061 * for all the "advance = 1;" above, and also end up with
3062 * a nice size-optimized program. Hah! That'll be the day.
3064 if (advance) b_getch(input);
3065 debug_printf_parse("handle_dollar return 0\n");
3069 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
3072 setup_string_in_str(&foo, src);
3073 return parse_stream(dest, ctx, &foo, NULL);
3076 /* return code is 0 for normal exit, 1 for syntax error */
3077 static int parse_stream(o_string *dest, struct p_context *ctx,
3078 struct in_str *input, const char *end_trigger)
3082 redir_type redir_style;
3085 /* Only double-quote state is handled in the state variable dest->quote.
3086 * A single-quote triggers a bypass of the main loop until its mate is
3087 * found. When recursing, quote state is passed in via dest->quote. */
3089 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3091 while ((ch = b_getch(input)) != EOF) {
3093 next = (ch == '\n') ? '\0' : b_peek(input);
3094 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3095 ch, ch, m, dest->quote);
3096 if (m == MAP_ORDINARY
3097 || (m != MAP_NEVER_FLOWTROUGH && dest->quote)
3099 b_addqchr(dest, ch, dest->quote);
3102 if (m == MAP_IFS_IF_UNQUOTED) {
3103 if (done_word(dest, ctx)) {
3104 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3107 /* If we aren't performing a substitution, treat
3108 * a newline as a command separator.
3109 * [why we don't handle it exactly like ';'? --vda] */
3110 if (end_trigger && ch == '\n') {
3111 done_pipe(ctx, PIPE_SEQ);
3114 if ((end_trigger && strchr(end_trigger, ch))
3115 && !dest->quote && ctx->res_w == RES_NONE
3117 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3120 if (m == MAP_IFS_IF_UNQUOTED)
3124 if (dest->length == 0 && !dest->quote) {
3127 if (ch == EOF || ch == '\n')
3132 b_addqchr(dest, ch, dest->quote);
3138 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3141 b_addqchr(dest, '\\', dest->quote);
3142 b_addqchr(dest, b_getch(input), dest->quote);
3145 if (handle_dollar(dest, ctx, input) != 0) {
3146 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3153 ch = b_getch(input);
3154 if (ch == EOF || ch == '\'')
3160 debug_printf_parse("parse_stream return 1: unterminated '\n");
3166 dest->quote = !dest->quote;
3169 process_command_subs(dest, ctx, input, "`");
3172 redir_fd = redirect_opt_num(dest);
3173 done_word(dest, ctx);
3174 redir_style = REDIRECT_OVERWRITE;
3176 redir_style = REDIRECT_APPEND;
3178 } else if (next == '(') {
3179 syntax(); /* until we support >(list) Process Substitution */
3180 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3183 setup_redirect(ctx, redir_fd, redir_style, input);
3186 redir_fd = redirect_opt_num(dest);
3187 done_word(dest, ctx);
3188 redir_style = REDIRECT_INPUT;
3190 redir_style = REDIRECT_HEREIS;
3192 } else if (next == '>') {
3193 redir_style = REDIRECT_IO;
3195 } else if (next == '(') {
3196 syntax(); /* until we support <(list) Process Substitution */
3197 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3200 setup_redirect(ctx, redir_fd, redir_style, input);
3203 done_word(dest, ctx);
3204 done_pipe(ctx, PIPE_SEQ);
3207 done_word(dest, ctx);
3210 done_pipe(ctx, PIPE_AND);
3212 done_pipe(ctx, PIPE_BG);
3216 done_word(dest, ctx);
3219 done_pipe(ctx, PIPE_OR);
3221 /* we could pick up a file descriptor choice here
3222 * with redirect_opt_num(), but bash doesn't do it.
3223 * "echo foo 2| cat" yields "foo 2". */
3229 if (parse_group(dest, ctx, input, ch) != 0) {
3230 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3236 syntax(); /* Proper use of this character is caught by end_trigger */
3237 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3240 syntax(); /* this is really an internal logic error */
3241 debug_printf_parse("parse_stream return 1: internal logic error\n");
3245 /* Complain if quote? No, maybe we just finished a command substitution
3246 * that was quoted. Example:
3247 * $ echo "`cat foo` plus more"
3248 * and we just got the EOF generated by the subshell that ran "cat foo"
3249 * The only real complaint is if we got an EOF when end_trigger != NULL,
3250 * that is, we were really supposed to get end_trigger, and never got
3251 * one before the EOF. Can't use the standard "syntax error" return code,
3252 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3253 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3259 static void mapset(const char *set, int code)
3262 map[(unsigned char)*set++] = code;
3265 static void update_ifs_map(void)
3267 /* char *ifs and char map[256] are both globals. */
3268 ifs = getenv("IFS");
3271 /* Precompute a list of 'flow through' behavior so it can be treated
3272 * quickly up front. Computation is necessary because of IFS.
3273 * Special case handling of IFS == " \t\n" is not implemented.
3274 * The map[] array only really needs two bits each, and on most machines
3275 * that would be faster because of the reduced L1 cache footprint.
3277 memset(map, MAP_ORDINARY, sizeof(map)); /* most chars flow through always */
3278 mapset("\\$'\"`", MAP_NEVER_FLOWTROUGH);
3279 mapset("<>;&|(){}#", MAP_FLOWTROUGH_IF_QUOTED);
3280 mapset(ifs, MAP_IFS_IF_UNQUOTED); /* also flow through if quoted */
3283 /* most recursion does not come through here, the exception is
3284 * from builtin_source() */
3285 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3287 // FIXME: '{ true | exit 3; echo $? }' is parsed as a whole,
3288 // as a result $? is replaced by 0, not 3!
3290 struct p_context ctx;
3291 o_string temp = NULL_O_STRING;
3294 ctx.parse_type = parse_flag;
3295 initialize_context(&ctx);
3297 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3298 mapset(";$&|", MAP_ORDINARY);
3299 #if ENABLE_HUSH_INTERACTIVE
3300 inp->promptmode = 1;
3302 /* We will stop & execute after each ';' or '\n'.
3303 * Example: "sleep 9999; echo TEST" + ctrl-C:
3304 * TEST should be printed */
3305 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3306 if (rcode != 1 && ctx.old_flag != 0) {
3309 if (rcode != 1 && ctx.old_flag == 0) {
3310 done_word(&temp, &ctx);
3311 done_pipe(&ctx, PIPE_SEQ);
3312 debug_print_tree(ctx.list_head, 0);
3313 debug_printf_exec("parse_stream_outer: run_list\n");
3314 run_list(ctx.list_head);
3316 if (ctx.old_flag != 0) {
3323 free_pipe_list(ctx.list_head, 0);
3326 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3330 static int parse_string_outer(const char *s, int parse_flag)
3332 struct in_str input;
3333 setup_string_in_str(&input, s);
3334 return parse_stream_outer(&input, parse_flag);
3337 static int parse_file_outer(FILE *f)
3340 struct in_str input;
3341 setup_file_in_str(&input, f);
3342 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3347 /* Make sure we have a controlling tty. If we get started under a job
3348 * aware app (like bash for example), make sure we are now in charge so
3349 * we don't fight over who gets the foreground */
3350 static void setup_job_control(void)
3354 saved_task_pgrp = shell_pgrp = getpgrp();
3355 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3356 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3358 /* If we were ran as 'hush &',
3359 * sleep until we are in the foreground. */
3360 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3361 /* Send TTIN to ourself (should stop us) */
3362 kill(- shell_pgrp, SIGTTIN);
3363 shell_pgrp = getpgrp();
3366 /* Ignore job-control and misc signals. */
3367 set_jobctrl_sighandler(SIG_IGN);
3368 set_misc_sighandler(SIG_IGN);
3369 //huh? signal(SIGCHLD, SIG_IGN);
3371 /* We _must_ restore tty pgrp on fatal signals */
3372 set_fatal_sighandler(sigexit);
3374 /* Put ourselves in our own process group. */
3375 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3376 /* Grab control of the terminal. */
3377 tcsetpgrp(interactive_fd, getpid());
3381 int hush_main(int argc, char **argv);
3382 int hush_main(int argc, char **argv)
3388 #if ENABLE_FEATURE_EDITING
3389 line_input_state = new_line_input_t(FOR_SHELL);
3392 /* XXX what should these be while sourcing /etc/profile? */
3396 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3397 * hush_main(), therefore we cannot rely on the BSS to zero out this
3398 * stuff. Reset these to 0 every time. */
3400 /* map[] is taken care of with call to update_ifs_map() */
3402 close_me_head = NULL;
3403 #if ENABLE_HUSH_INTERACTIVE
3412 /* Initialize some more globals to non-zero values */
3414 #if ENABLE_HUSH_INTERACTIVE
3415 #if ENABLE_FEATURE_EDITING
3416 cmdedit_set_initial_prompt();
3422 /* initialize our shell local variables with the values
3423 * currently living in the environment */
3427 set_local_var(*e++, 2); /* without call putenv() */
3429 last_return_code = EXIT_SUCCESS;
3431 if (argv[0] && argv[0][0] == '-') {
3432 debug_printf("sourcing /etc/profile\n");
3433 input = fopen("/etc/profile", "r");
3434 if (input != NULL) {
3435 mark_open(fileno(input));
3436 parse_file_outer(input);
3437 mark_closed(fileno(input));
3443 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3446 global_argv = argv + optind;
3447 global_argc = argc - optind;
3448 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3451 // Well, we cannot just declare interactiveness,
3452 // we have to have some stuff (ctty, etc)
3453 /*interactive_fd++;*/
3460 fprintf(stderr, "Usage: sh [FILE]...\n"
3461 " or: sh -c command [args]...\n\n");
3469 /* A shell is interactive if the '-i' flag was given, or if all of
3470 * the following conditions are met:
3472 * no arguments remaining or the -s flag given
3473 * standard input is a terminal
3474 * standard output is a terminal
3475 * Refer to Posix.2, the description of the 'sh' utility. */
3476 if (argv[optind] == NULL && input == stdin
3477 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3479 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3480 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3481 if (saved_tty_pgrp >= 0) {
3482 /* try to dup to high fd#, >= 255 */
3483 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3484 if (interactive_fd < 0) {
3485 /* try to dup to any fd */
3486 interactive_fd = dup(STDIN_FILENO);
3487 if (interactive_fd < 0)
3491 // TODO: track & disallow any attempts of user
3492 // to (inadvertently) close/redirect it
3495 debug_printf("interactive_fd=%d\n", interactive_fd);
3496 if (interactive_fd) {
3497 /* Looks like they want an interactive shell */
3498 setup_job_control();
3499 /* Make xfuncs do cleanup on exit */
3500 die_sleep = -1; /* flag */
3501 // FIXME: should we reset die_sleep = 0 whereever we fork?
3502 if (setjmp(die_jmp)) {
3503 /* xfunc has failed! die die die */
3504 hush_exit(xfunc_error_retval);
3506 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3507 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3508 printf("Enter 'help' for a list of built-in commands.\n\n");
3511 #elif ENABLE_HUSH_INTERACTIVE
3512 /* no job control compiled, only prompt/line editing */
3513 if (argv[optind] == NULL && input == stdin
3514 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3516 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3517 if (interactive_fd < 0) {
3518 /* try to dup to any fd */
3519 interactive_fd = dup(STDIN_FILENO);
3520 if (interactive_fd < 0)
3528 if (argv[optind] == NULL) {
3529 opt = parse_file_outer(stdin);
3533 debug_printf("\nrunning script '%s'\n", argv[optind]);
3534 global_argv = argv + optind;
3535 global_argc = argc - optind;
3536 input = xfopen(argv[optind], "r");
3537 opt = parse_file_outer(input);
3539 #if ENABLE_FEATURE_CLEAN_UP
3541 if (cwd != bb_msg_unknown)
3544 struct variables *cur, *tmp;
3545 for (cur = top_vars; cur; cur = tmp) {
3547 if (!cur->flg_read_only) {
3548 free((char*)cur->name);
3549 free((char*)cur->value);
3557 hush_exit(opt ? opt : last_return_code);