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 charmap[] 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_expand(...) do {} while (0)
95 #define debug_printf_clean(...) do {} while (0)
98 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
101 #ifndef debug_printf_parse
102 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
105 #ifndef debug_printf_exec
106 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
109 #ifndef debug_printf_jobs
110 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
111 #define DEBUG_SHELL_JOBS 1
114 #ifndef debug_printf_expand
115 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
116 #define DEBUG_EXPAND 1
119 #ifndef debug_printf_clean
120 /* broken, of course, but OK for testing */
121 static const char *indenter(int i)
123 static const char blanks[] = " ";
124 return &blanks[sizeof(blanks) - i - 1];
126 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
127 #define DEBUG_CLEAN 1
131 #if !ENABLE_HUSH_INTERACTIVE
132 #undef ENABLE_FEATURE_EDITING
133 #define ENABLE_FEATURE_EDITING 0
134 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
135 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
138 #define SPECIAL_VAR_SYMBOL 3
139 #define FLAG_EXIT_FROM_LOOP 1
140 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
141 #define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
145 REDIRECT_OVERWRITE = 2,
151 /* The descrip member of this structure is only used to make debugging
153 static const struct {
155 signed char default_fd;
159 { O_RDONLY, 0, "<" },
160 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
161 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
162 { O_RDONLY, -1, "<<" },
173 /* might eventually control execution */
191 FLAG_END = (1 << RES_NONE ),
192 FLAG_IF = (1 << RES_IF ),
193 FLAG_THEN = (1 << RES_THEN ),
194 FLAG_ELIF = (1 << RES_ELIF ),
195 FLAG_ELSE = (1 << RES_ELSE ),
196 FLAG_FI = (1 << RES_FI ),
197 FLAG_FOR = (1 << RES_FOR ),
198 FLAG_WHILE = (1 << RES_WHILE),
199 FLAG_UNTIL = (1 << RES_UNTIL),
200 FLAG_DO = (1 << RES_DO ),
201 FLAG_DONE = (1 << RES_DONE ),
202 FLAG_IN = (1 << RES_IN ),
203 FLAG_START = (1 << RES_XXXX ),
206 /* This holds pointers to the various results of parsing */
208 struct child_prog *child;
209 struct pipe *list_head;
211 struct redir_struct *pending_redirect;
212 reserved_style res_w;
213 int old_flag; /* for figuring out valid reserved words */
214 struct p_context *stack;
215 int parse_type; /* define type of parser : ";$" common or special symbol */
216 /* How about quoting status? */
219 struct redir_struct {
220 struct redir_struct *next; /* pointer to the next redirect in the list */
221 redir_type type; /* type of redirection */
222 int fd; /* file descriptor being redirected */
223 int dup; /* -1, or file descriptor being duplicated */
224 glob_t word; /* *word.gl_pathv is the filename */
228 pid_t pid; /* 0 if exited */
229 char **argv; /* program name and arguments */
230 struct pipe *group; /* if non-NULL, first in group or subshell */
231 int subshell; /* flag, non-zero if group must be forked */
232 struct redir_struct *redirects; /* I/O redirections */
233 glob_t glob_result; /* result of parameter globbing */
234 int is_stopped; /* is the program currently running? */
235 struct pipe *family; /* pointer back to the child's parent pipe */
236 //sp counting seems to be broken... so commented out, grep for '//sp:'
237 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
240 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
241 * and on execution these are substituted with their values.
242 * Substitution can make _several_ words out of one argv[n]!
243 * Example: argv[0]=='.^C*^C.' here: echo .$*.
248 int num_progs; /* total number of programs in job */
249 int running_progs; /* number of programs running (not exited) */
250 char *cmdbuf; /* buffer various argv's point into */
252 int jobid; /* job number */
253 char *cmdtext; /* name of job */
254 pid_t pgrp; /* process group ID for the job */
256 struct child_prog *progs; /* array of commands in pipe */
257 int stopped_progs; /* number of programs alive, but stopped */
258 int job_context; /* bitmask defining current context */
259 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
260 reserved_style r_mode; /* supports if, for, while, until */
264 struct close_me *next;
269 struct variables *next;
276 /* globals, connect us to the outside world
277 * the first three support $?, $#, and $1 */
278 static char **global_argv;
279 static int global_argc;
280 static int last_return_code;
281 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
283 /* "globals" within this file */
286 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
287 CHAR_IFS = 2, /* treated as ordinary if quoted */
288 CHAR_SPECIAL = 3, /* example: $ */
290 static unsigned char charmap[256];
291 static const char *ifs;
292 static int fake_mode;
293 static struct close_me *close_me_head;
294 static const char *cwd;
295 static unsigned last_bg_pid;
296 #if !ENABLE_HUSH_INTERACTIVE
297 enum { interactive_fd = 0 };
299 /* 'interactive_fd' is a fd# open to ctty, if we have one
300 * _AND_ if we decided to act interactively */
301 static int interactive_fd;
303 static pid_t saved_task_pgrp;
304 static pid_t saved_tty_pgrp;
305 static int last_jobid;
306 static struct pipe *job_list;
308 static const char *PS1;
309 static const char *PS2;
312 #define HUSH_VER_STR "0.02"
313 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
314 static struct variables *top_vars = &shell_ver;
326 #define NULL_O_STRING {NULL,0,0,0,0}
327 /* used for initialization:
328 o_string foo = NULL_O_STRING; */
330 /* I can almost use ordinary FILE *. Is open_memstream() universally
331 * available? Where is it documented? */
334 /* eof_flag=1: last char in ->p is really an EOF */
335 char eof_flag; /* meaningless if ->p == NULL */
337 #if ENABLE_HUSH_INTERACTIVE
342 int (*get) (struct in_str *);
343 int (*peek) (struct in_str *);
345 #define b_getch(input) ((input)->get(input))
346 #define b_peek(input) ((input)->peek(input))
348 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
350 struct built_in_command {
351 const char *cmd; /* name */
352 const char *descr; /* description */
353 int (*function) (char **argv); /* function ptr */
356 static void __syntax(int line)
358 bb_error_msg("syntax error hush.c:%d", line);
360 #define syntax() __syntax(__LINE__)
362 /* Index of subroutines: */
363 /* function prototypes for builtins */
364 static int builtin_cd(char **argv);
365 static int builtin_eval(char **argv);
366 static int builtin_exec(char **argv);
367 static int builtin_exit(char **argv);
368 static int builtin_export(char **argv);
370 static int builtin_fg_bg(char **argv);
371 static int builtin_jobs(char **argv);
373 static int builtin_help(char **argv);
374 static int builtin_pwd(char **argv);
375 static int builtin_read(char **argv);
376 static int builtin_set(char **argv);
377 static int builtin_shift(char **argv);
378 static int builtin_source(char **argv);
379 static int builtin_umask(char **argv);
380 static int builtin_unset(char **argv);
381 static int builtin_not_written(char **argv);
382 /* o_string manipulation: */
383 static int b_check_space(o_string *o, int len);
384 static int b_addchr(o_string *o, int ch);
385 static void b_reset(o_string *o);
386 static int b_addqchr(o_string *o, int ch, int quote);
387 /* in_str manipulations: */
388 static int static_get(struct in_str *i);
389 static int static_peek(struct in_str *i);
390 static int file_get(struct in_str *i);
391 static int file_peek(struct in_str *i);
392 static void setup_file_in_str(struct in_str *i, FILE *f);
393 static void setup_string_in_str(struct in_str *i, const char *s);
394 /* close_me manipulations: */
395 static void mark_open(int fd);
396 static void mark_closed(int fd);
397 static void close_all(void);
398 /* "run" the final data structures: */
399 #if !defined(DEBUG_CLEAN)
400 #define free_pipe_list(head, indent) free_pipe_list(head)
401 #define free_pipe(pi, indent) free_pipe(pi)
403 static int free_pipe_list(struct pipe *head, int indent);
404 static int free_pipe(struct pipe *pi, int indent);
405 /* really run the final data structures: */
406 static int setup_redirects(struct child_prog *prog, int squirrel[]);
407 static int run_list_real(struct pipe *pi);
408 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
409 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
410 static int run_pipe_real(struct pipe *pi);
411 /* extended glob support: */
412 static int globhack(const char *src, int flags, glob_t *pglob);
413 static int glob_needed(const char *s);
414 static int xglob(o_string *dest, int flags, glob_t *pglob);
415 /* variable assignment: */
416 static int is_assignment(const char *s);
417 /* data structure manipulation: */
418 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
419 static void initialize_context(struct p_context *ctx);
420 static int done_word(o_string *dest, struct p_context *ctx);
421 static int done_command(struct p_context *ctx);
422 static int done_pipe(struct p_context *ctx, pipe_style type);
423 /* primary string parsing: */
424 static int redirect_dup_num(struct in_str *input);
425 static int redirect_opt_num(o_string *o);
426 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
427 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
428 static const char *lookup_param(const char *src);
429 static char *make_string(char **inp);
430 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
431 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
433 static int parse_stream_outer(struct in_str *inp, int parse_flag);
434 static int parse_string_outer(const char *s, int parse_flag);
435 static int parse_file_outer(FILE *f);
436 /* job management: */
437 static int checkjobs(struct pipe* fg_pipe);
439 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
440 static void insert_bg_job(struct pipe *pi);
441 static void remove_bg_job(struct pipe *pi);
442 static void delete_finished_bg_job(struct pipe *pi);
444 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
446 /* local variable support */
447 static char **expand_variables_to_list(char **argv);
448 /* used for expansion of right hand of assignments */
449 static char *expand_variables_to_string(const char *str);
450 static const char *get_local_var(const char *var);
451 static int set_local_var(const char *s, int flg_export);
452 static void unset_local_var(const char *name);
454 /* Table of built-in functions. They can be forked or not, depending on
455 * context: within pipes, they fork. As simple commands, they do not.
456 * When used in non-forking context, they can change global variables
457 * in the parent shell process. If forked, of course they cannot.
458 * For example, 'unset foo | whatever' will parse and run, but foo will
459 * still be set at the end. */
460 static const struct built_in_command bltins[] = {
462 { "bg", "Resume a job in the background", builtin_fg_bg },
464 { "break", "Exit for, while or until loop", builtin_not_written },
465 { "cd", "Change working directory", builtin_cd },
466 { "continue", "Continue for, while or until loop", builtin_not_written },
467 { "eval", "Construct and run shell command", builtin_eval },
468 { "exec", "Exec command, replacing this shell with the exec'd process",
470 { "exit", "Exit from shell()", builtin_exit },
471 { "export", "Set environment variable", builtin_export },
473 { "fg", "Bring job into the foreground", builtin_fg_bg },
474 { "jobs", "Lists the active jobs", builtin_jobs },
476 { "pwd", "Print current directory", builtin_pwd },
477 { "read", "Input environment variable", builtin_read },
478 { "return", "Return from a function", builtin_not_written },
479 { "set", "Set/unset shell local variables", builtin_set },
480 { "shift", "Shift positional parameters", builtin_shift },
481 { "trap", "Trap signals", builtin_not_written },
482 { "ulimit","Controls resource limits", builtin_not_written },
483 { "umask","Sets file creation mask", builtin_umask },
484 { "unset", "Unset environment variable", builtin_unset },
485 { ".", "Source-in and run commands in a file", builtin_source },
486 { "help", "List shell built-in commands", builtin_help },
490 #if ENABLE_FEATURE_SH_STANDALONE
491 struct nofork_save_area nofork_save;
497 static void signal_SA_RESTART(int sig, void (*handler)(int))
500 sa.sa_handler = handler;
501 sa.sa_flags = SA_RESTART;
502 sigemptyset(&sa.sa_mask);
503 sigaction(sig, &sa, NULL);
506 /* Signals are grouped, we handle them in batches */
507 static void set_fatal_sighandler(void (*handler)(int))
509 signal(SIGILL , handler);
510 signal(SIGTRAP, handler);
511 signal(SIGABRT, handler);
512 signal(SIGFPE , handler);
513 signal(SIGBUS , handler);
514 signal(SIGSEGV, handler);
515 /* bash 3.2 seems to handle these just like 'fatal' ones */
516 signal(SIGHUP , handler);
517 signal(SIGPIPE, handler);
518 signal(SIGALRM, handler);
520 static void set_jobctrl_sighandler(void (*handler)(int))
522 signal(SIGTSTP, handler);
523 signal(SIGTTIN, handler);
524 signal(SIGTTOU, handler);
526 static void set_misc_sighandler(void (*handler)(int))
528 signal(SIGINT , handler);
529 signal(SIGQUIT, handler);
530 signal(SIGTERM, handler);
532 /* SIGCHLD is special and handled separately */
534 static void set_every_sighandler(void (*handler)(int))
536 set_fatal_sighandler(handler);
537 set_jobctrl_sighandler(handler);
538 set_misc_sighandler(handler);
539 signal(SIGCHLD, handler);
542 static struct pipe *toplevel_list;
543 static sigjmp_buf toplevel_jb;
544 smallint ctrl_z_flag;
545 static void handler_ctrl_c(int sig)
547 debug_printf_jobs("got sig %d\n", sig);
548 // as usual we can have all kinds of nasty problems with leaked malloc data here
549 siglongjmp(toplevel_jb, 1);
552 static void handler_ctrl_z(int sig)
556 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
558 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
561 if (!pid) { /* child */
563 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
564 set_every_sighandler(SIG_DFL);
565 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
566 debug_printf_jobs("returning in child\n");
567 /* return to nofork, it will eventually exit now,
568 * not return back to shell */
572 /* finish filling up pipe info */
573 toplevel_list->pgrp = pid; /* child is in its own pgrp */
574 toplevel_list->progs[0].pid = pid;
575 /* parent needs to longjmp out of running nofork.
576 * we will "return" exitcode 0, with child put in background */
577 // as usual we can have all kinds of nasty problems with leaked malloc data here
578 debug_printf_jobs("siglongjmp in parent\n");
579 siglongjmp(toplevel_jb, 1);
582 /* Restores tty foreground process group, and exits.
583 * May be called as signal handler for fatal signal
584 * (will faithfully resend signal to itself, producing correct exit state)
585 * or called directly with -EXITCODE.
586 * We also call it if xfunc is exiting. */
587 static void sigexit(int sig) ATTRIBUTE_NORETURN;
588 static void sigexit(int sig)
592 /* Disable all signals: job control, SIGPIPE, etc. */
593 sigfillset(&block_all);
594 sigprocmask(SIG_SETMASK, &block_all, NULL);
597 tcsetpgrp(interactive_fd, saved_tty_pgrp);
599 /* Not a signal, just exit */
603 /* Enable only this sig and kill ourself with it */
604 signal(sig, SIG_DFL);
605 sigdelset(&block_all, sig);
606 sigprocmask(SIG_SETMASK, &block_all, NULL);
608 _exit(1); /* Should not reach it */
611 /* Restores tty foreground process group, and exits. */
612 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
613 static void hush_exit(int exitcode)
615 fflush(NULL); /* flush all streams */
616 sigexit(- (exitcode & 0xff));
621 #define set_fatal_sighandler(handler) ((void)0)
622 #define set_jobctrl_sighandler(handler) ((void)0)
623 #define set_misc_sighandler(handler) ((void)0)
624 #define hush_exit(e) exit(e)
629 static const char *set_cwd(void)
631 if (cwd == bb_msg_unknown)
632 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
633 cwd = xrealloc_getcwd_or_warn((char *)cwd);
635 cwd = bb_msg_unknown;
639 /* built-in 'eval' handler */
640 static int builtin_eval(char **argv)
643 int rcode = EXIT_SUCCESS;
646 str = make_string(argv + 1);
647 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
648 FLAG_PARSE_SEMICOLON);
650 rcode = last_return_code;
655 /* built-in 'cd <path>' handler */
656 static int builtin_cd(char **argv)
660 newdir = getenv("HOME");
664 printf("cd: %s: %s\n", newdir, strerror(errno));
671 /* built-in 'exec' handler */
672 static int builtin_exec(char **argv)
675 return EXIT_SUCCESS; /* Really? */
676 pseudo_exec_argv(argv + 1);
680 /* built-in 'exit' handler */
681 static int builtin_exit(char **argv)
683 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
684 //puts("exit"); /* bash does it */
685 // TODO: warn if we have background jobs: "There are stopped jobs"
686 // On second consecutive 'exit', exit anyway.
689 hush_exit(last_return_code);
690 /* mimic bash: exit 123abc == exit 255 + error msg */
691 xfunc_error_retval = 255;
692 /* bash: exit -2 == exit 254, no error msg */
693 hush_exit(xatoi(argv[1]) & 0xff);
696 /* built-in 'export VAR=value' handler */
697 static int builtin_export(char **argv)
700 char *name = argv[1];
704 // ash emits: export VAR='VAL'
705 // bash: declare -x VAR="VAL"
706 // (both also escape as needed (quotes, $, etc))
714 name = xstrdup(name);
716 const char *value = strchr(name, '=');
720 /* They are exporting something without an =VALUE */
722 value = get_local_var(name);
724 size_t ln = strlen(name);
726 tmp = xrealloc(name, ln+strlen(value)+2);
727 sprintf(tmp+ln, "=%s", value);
730 /* bash does not return an error when trying to export
731 * an undefined variable. Do likewise. */
737 bb_perror_msg("export");
739 res = set_local_var(name, 1);
747 /* built-in 'fg' and 'bg' handler */
748 static int builtin_fg_bg(char **argv)
755 /* If they gave us no args, assume they want the last backgrounded task */
757 for (pi = job_list; pi; pi = pi->next) {
758 if (pi->jobid == last_jobid) {
762 bb_error_msg("%s: no current job", argv[0]);
765 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
766 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
769 for (pi = job_list; pi; pi = pi->next) {
770 if (pi->jobid == jobnum) {
774 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
777 // TODO: bash prints a string representation
778 // of job being foregrounded (like "sleep 1 | cat")
779 if (*argv[0] == 'f') {
780 /* Put the job into the foreground. */
781 tcsetpgrp(interactive_fd, pi->pgrp);
784 /* Restart the processes in the job */
785 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
786 for (i = 0; i < pi->num_progs; i++) {
787 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
788 pi->progs[i].is_stopped = 0;
790 pi->stopped_progs = 0;
792 i = kill(- pi->pgrp, SIGCONT);
794 if (errno == ESRCH) {
795 delete_finished_bg_job(pi);
798 bb_perror_msg("kill (SIGCONT)");
802 if (*argv[0] == 'f') {
804 return checkjobs_and_fg_shell(pi);
810 /* built-in 'help' handler */
811 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
813 const struct built_in_command *x;
815 printf("\nBuilt-in commands:\n");
816 printf("-------------------\n");
817 for (x = bltins; x->cmd; x++) {
818 if (x->descr == NULL)
820 printf("%s\t%s\n", x->cmd, x->descr);
827 /* built-in 'jobs' handler */
828 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
831 const char *status_string;
833 for (job = job_list; job; job = job->next) {
834 if (job->running_progs == job->stopped_progs)
835 status_string = "Stopped";
837 status_string = "Running";
839 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
845 /* built-in 'pwd' handler */
846 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
852 /* built-in 'read VAR' handler */
853 static int builtin_read(char **argv)
857 const char *name = argv[1] ? argv[1] : "REPLY";
858 int name_len = strlen(name);
860 if (name_len >= sizeof(string) - 2)
862 strcpy(string, name);
863 p = string + name_len;
865 *p = '\0'; /* In case stdin has only EOF */
866 /* read string. name_len+1 chars are already used by 'name=' */
867 fgets(p, sizeof(string) - 1 - name_len, stdin);
869 return set_local_var(string, 0);
872 /* built-in 'set [VAR=value]' handler */
873 static int builtin_set(char **argv)
875 char *temp = argv[1];
879 for (e = top_vars; e; e = e->next)
880 printf("%s=%s\n", e->name, e->value);
882 set_local_var(temp, 0);
888 /* Built-in 'shift' handler */
889 static int builtin_shift(char **argv)
895 if (n >= 0 && n < global_argc) {
896 /* XXX This probably breaks $0 */
904 /* Built-in '.' handler (read-in and execute commands from file) */
905 static int builtin_source(char **argv)
913 /* XXX search through $PATH is missing */
914 input = fopen(argv[1], "r");
916 bb_error_msg("cannot open '%s'", argv[1]);
920 /* Now run the file */
921 /* XXX argv and argc are broken; need to save old global_argv
922 * (pointer only is OK!) on this stack frame,
923 * set global_argv=argv+1, recurse, and restore. */
924 mark_open(fileno(input));
925 status = parse_file_outer(input);
926 mark_closed(fileno(input));
931 static int builtin_umask(char **argv)
934 const char *arg = argv[1];
937 new_umask = strtoul(arg, &end, 8);
938 if (*end != '\0' || end == arg) {
942 new_umask = umask(0);
943 printf("%.3o\n", (unsigned) new_umask);
949 /* built-in 'unset VAR' handler */
950 static int builtin_unset(char **argv)
952 /* bash always returns true */
953 unset_local_var(argv[1]);
957 static int builtin_not_written(char **argv)
959 printf("builtin_%s not written\n", argv[0]);
963 static int b_check_space(o_string *o, int len)
965 /* It would be easy to drop a more restrictive policy
966 * in here, such as setting a maximum string length */
967 if (o->length + len > o->maxlen) {
968 /* assert(data == NULL || o->maxlen != 0); */
969 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
970 o->data = xrealloc(o->data, 1 + o->maxlen);
972 return o->data == NULL;
975 static int b_addchr(o_string *o, int ch)
977 debug_printf("b_addchr: '%c' o->length=%d o=%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 static_get(struct in_str *i)
1019 if (ch == '\0') return EOF;
1023 static int static_peek(struct in_str *i)
1028 #if ENABLE_HUSH_INTERACTIVE
1029 #if ENABLE_FEATURE_EDITING
1030 static void cmdedit_set_initial_prompt(void)
1032 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1035 PS1 = getenv("PS1");
1040 #endif /* EDITING */
1042 static const char* setup_prompt_string(int promptmode)
1044 const char *prompt_str;
1045 debug_printf("setup_prompt_string %d ", promptmode);
1046 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1047 /* Set up the prompt */
1048 if (promptmode == 1) {
1051 ns = xmalloc(strlen(cwd)+4);
1052 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1059 prompt_str = (promptmode == 1) ? PS1 : PS2;
1061 debug_printf("result %s\n", prompt_str);
1065 #if ENABLE_FEATURE_EDITING
1066 static line_input_t *line_input_state;
1069 static void get_user_input(struct in_str *i)
1071 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1074 const char *prompt_str;
1076 prompt_str = setup_prompt_string(i->promptmode);
1077 #if ENABLE_FEATURE_EDITING
1079 ** enable command line editing only while a command line
1080 ** is actually being read; otherwise, we'll end up bequeathing
1081 ** atexit() handlers and other unwanted stuff to our
1082 ** child processes (rob@sysgo.de)
1084 r = read_line_input(prompt_str, the_command, BUFSIZ-1, line_input_state);
1085 i->eof_flag = (r < 0);
1086 if (i->eof_flag) { /* EOF/error detected */
1087 the_command[0] = EOF; /* yes, it will be truncated, it's ok */
1088 the_command[1] = '\0';
1091 fputs(prompt_str, stdout);
1093 the_command[0] = r = fgetc(i->file);
1094 /*the_command[1] = '\0'; - already is and never changed */
1095 i->eof_flag = (r == EOF);
1099 #endif /* INTERACTIVE */
1101 /* This is the magic location that prints prompts
1102 * and gets data back from the user */
1103 static int file_get(struct in_str *i)
1107 /* If there is data waiting, eat it up */
1108 if (i->p && *i->p) {
1109 #if ENABLE_HUSH_INTERACTIVE
1113 if (i->eof_flag && !*i->p)
1116 /* need to double check i->file because we might be doing something
1117 * more complicated by now, like sourcing or substituting. */
1118 #if ENABLE_HUSH_INTERACTIVE
1119 if (interactive_fd && i->__promptme && i->file == stdin) {
1122 } while (!*i->p); /* need non-empty line */
1128 ch = fgetc(i->file);
1130 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1131 #if ENABLE_HUSH_INTERACTIVE
1138 /* All the callers guarantee this routine will never be
1139 * used right after a newline, so prompting is not needed.
1141 static int file_peek(struct in_str *i)
1144 if (i->p && *i->p) {
1145 if (i->eof_flag && !i->p[1])
1149 ch = fgetc(i->file);
1150 i->eof_flag = (ch == EOF);
1151 i->peek_buf[0] = ch;
1152 i->peek_buf[1] = '\0';
1154 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1158 static void setup_file_in_str(struct in_str *i, FILE *f)
1160 i->peek = file_peek;
1162 #if ENABLE_HUSH_INTERACTIVE
1170 static void setup_string_in_str(struct in_str *i, const char *s)
1172 i->peek = static_peek;
1173 i->get = static_get;
1174 #if ENABLE_HUSH_INTERACTIVE
1182 static void mark_open(int fd)
1184 struct close_me *new = xmalloc(sizeof(struct close_me));
1186 new->next = close_me_head;
1187 close_me_head = new;
1190 static void mark_closed(int fd)
1192 struct close_me *tmp;
1193 if (close_me_head == NULL || close_me_head->fd != fd)
1194 bb_error_msg_and_die("corrupt close_me");
1195 tmp = close_me_head;
1196 close_me_head = close_me_head->next;
1200 static void close_all(void)
1203 for (c = close_me_head; c; c = c->next) {
1206 close_me_head = NULL;
1209 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1210 * and stderr if they are redirected. */
1211 static int setup_redirects(struct child_prog *prog, int squirrel[])
1214 struct redir_struct *redir;
1216 for (redir = prog->redirects; redir; redir = redir->next) {
1217 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1218 /* something went wrong in the parse. Pretend it didn't happen */
1221 if (redir->dup == -1) {
1222 mode = redir_table[redir->type].mode;
1223 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1225 /* this could get lost if stderr has been redirected, but
1226 bash and ash both lose it as well (though zsh doesn't!) */
1230 openfd = redir->dup;
1233 if (openfd != redir->fd) {
1234 if (squirrel && redir->fd < 3) {
1235 squirrel[redir->fd] = dup(redir->fd);
1240 dup2(openfd, redir->fd);
1241 if (redir->dup == -1)
1249 static void restore_redirects(int squirrel[])
1252 for (i = 0; i < 3; i++) {
1255 /* We simply die on error */
1262 /* XXX no exit() here. If you don't exec, use _exit instead.
1263 * The at_exit handlers apparently confuse the calling process,
1264 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1265 static void pseudo_exec_argv(char **argv)
1269 const struct built_in_command *x;
1271 for (i = 0; is_assignment(argv[i]); i++) {
1272 debug_printf_exec("pid %d environment modification: %s\n",
1274 // FIXME: vfork case??
1275 p = expand_variables_to_string(argv[i]);
1276 putenv(p == argv[i] ? xstrdup(p) : p);
1279 /* If a variable is assigned in a forest, and nobody listens,
1280 * was it ever really set?
1282 if (argv[0] == NULL) {
1283 _exit(EXIT_SUCCESS);
1286 argv = expand_variables_to_list(argv);
1289 * Check if the command matches any of the builtins.
1290 * Depending on context, this might be redundant. But it's
1291 * easier to waste a few CPU cycles than it is to figure out
1292 * if this is one of those cases.
1294 for (x = bltins; x->cmd; x++) {
1295 if (strcmp(argv[0], x->cmd) == 0) {
1296 debug_printf_exec("running builtin '%s'\n", argv[0]);
1297 rcode = x->function(argv);
1303 /* Check if the command matches any busybox applets */
1304 #if ENABLE_FEATURE_SH_STANDALONE
1305 if (strchr(argv[0], '/') == NULL) {
1306 const struct bb_applet *a = find_applet_by_name(argv[0]);
1310 debug_printf_exec("running applet '%s'\n", argv[0]);
1311 // is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1312 run_current_applet_and_exit(argv);
1314 /* re-exec ourselves with the new arguments */
1315 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1316 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1317 /* If they called chroot or otherwise made the binary no longer
1318 * executable, fall through */
1323 debug_printf_exec("execing '%s'\n", argv[0]);
1324 execvp(argv[0], argv);
1325 bb_perror_msg("cannot exec '%s'", argv[0]);
1329 static void pseudo_exec(struct child_prog *child)
1331 // FIXME: buggy wrt NOMMU! Must not modify any global data
1332 // until it does exec/_exit, but currently it does.
1336 pseudo_exec_argv(child->argv);
1340 // FIXME: do not modify globals! Think vfork!
1341 #if ENABLE_HUSH_INTERACTIVE
1342 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1343 interactive_fd = 0; /* crucial!!!! */
1345 debug_printf_exec("pseudo_exec: run_list_real\n");
1346 rcode = run_list_real(child->group);
1347 /* OK to leak memory by not calling free_pipe_list,
1348 * since this process is about to exit */
1352 /* Can happen. See what bash does with ">foo" by itself. */
1353 debug_printf("trying to pseudo_exec null command\n");
1354 _exit(EXIT_SUCCESS);
1358 static const char *get_cmdtext(struct pipe *pi)
1364 /* This is subtle. ->cmdtext is created only on first backgrounding.
1365 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1366 * On subsequent bg argv is trashed, but we won't use it */
1369 argv = pi->progs[0].argv;
1370 if (!argv || !argv[0])
1371 return (pi->cmdtext = xzalloc(1));
1374 do len += strlen(*argv) + 1; while (*++argv);
1375 pi->cmdtext = p = xmalloc(len);
1376 argv = pi->progs[0].argv;
1378 len = strlen(*argv);
1379 memcpy(p, *argv, len);
1387 static void insert_bg_job(struct pipe *pi)
1389 struct pipe *thejob;
1392 /* Linear search for the ID of the job to use */
1394 for (thejob = job_list; thejob; thejob = thejob->next)
1395 if (thejob->jobid >= pi->jobid)
1396 pi->jobid = thejob->jobid + 1;
1398 /* Add thejob to the list of running jobs */
1400 thejob = job_list = xmalloc(sizeof(*thejob));
1402 for (thejob = job_list; thejob->next; thejob = thejob->next)
1404 thejob->next = xmalloc(sizeof(*thejob));
1405 thejob = thejob->next;
1408 /* Physically copy the struct job */
1409 memcpy(thejob, pi, sizeof(struct pipe));
1410 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1411 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1412 for (i = 0; i < pi->num_progs; i++) {
1413 // TODO: do we really need to have so many fields which are just dead weight
1414 // at execution stage?
1415 thejob->progs[i].pid = pi->progs[i].pid;
1416 /* all other fields are not used and stay zero */
1418 thejob->next = NULL;
1419 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1421 /* We don't wait for background thejobs to return -- append it
1422 to the list of backgrounded thejobs and leave it alone */
1423 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1424 last_bg_pid = thejob->progs[0].pid;
1425 last_jobid = thejob->jobid;
1428 static void remove_bg_job(struct pipe *pi)
1430 struct pipe *prev_pipe;
1432 if (pi == job_list) {
1433 job_list = pi->next;
1435 prev_pipe = job_list;
1436 while (prev_pipe->next != pi)
1437 prev_pipe = prev_pipe->next;
1438 prev_pipe->next = pi->next;
1441 last_jobid = job_list->jobid;
1446 /* remove a backgrounded job */
1447 static void delete_finished_bg_job(struct pipe *pi)
1450 pi->stopped_progs = 0;
1456 /* Checks to see if any processes have exited -- if they
1457 have, figure out why and see if a job has completed */
1458 static int checkjobs(struct pipe* fg_pipe)
1469 attributes = WUNTRACED;
1470 if (fg_pipe == NULL) {
1471 attributes |= WNOHANG;
1474 /* Do we do this right?
1475 * bash-3.00# sleep 20 | false
1477 * [3]+ Stopped sleep 20 | false
1478 * bash-3.00# echo $?
1479 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1482 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1483 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1484 // + killall -STOP cat
1487 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1488 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1490 #ifdef DEBUG_SHELL_JOBS
1491 if (WIFSTOPPED(status))
1492 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1493 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1494 if (WIFSIGNALED(status))
1495 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1496 childpid, WTERMSIG(status), WEXITSTATUS(status));
1497 if (WIFEXITED(status))
1498 debug_printf_jobs("pid %d exited, exitcode %d\n",
1499 childpid, WEXITSTATUS(status));
1501 /* Were we asked to wait for fg pipe? */
1504 for (i = 0; i < fg_pipe->num_progs; i++) {
1505 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1506 if (fg_pipe->progs[i].pid == childpid) {
1507 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1509 fg_pipe->progs[i].pid = 0;
1510 fg_pipe->running_progs--;
1511 if (i == fg_pipe->num_progs-1)
1512 /* last process gives overall exitstatus */
1513 rcode = WEXITSTATUS(status);
1515 fg_pipe->progs[i].is_stopped = 1;
1516 fg_pipe->stopped_progs++;
1518 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1519 fg_pipe->running_progs, fg_pipe->stopped_progs);
1520 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1521 /* All processes in fg pipe have exited/stopped */
1523 if (fg_pipe->running_progs)
1524 insert_bg_job(fg_pipe);
1528 /* There are still running processes in the fg pipe */
1532 /* fall through to searching process in bg pipes */
1536 /* We asked to wait for bg or orphaned children */
1537 /* No need to remember exitcode in this case */
1538 for (pi = job_list; pi; pi = pi->next) {
1540 while (prognum < pi->num_progs) {
1541 if (pi->progs[prognum].pid == childpid)
1542 goto found_pi_and_prognum;
1548 /* Happens when shell is used as init process (init=/bin/sh) */
1549 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1553 found_pi_and_prognum:
1556 pi->progs[prognum].pid = 0;
1557 pi->running_progs--;
1558 if (!pi->running_progs) {
1559 printf(JOB_STATUS_FORMAT, pi->jobid,
1560 "Done", pi->cmdtext);
1561 delete_finished_bg_job(pi);
1565 pi->stopped_progs++;
1566 pi->progs[prognum].is_stopped = 1;
1571 /* wait found no children or failed */
1573 if (childpid && errno != ECHILD)
1574 bb_perror_msg("waitpid");
1579 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1582 int rcode = checkjobs(fg_pipe);
1583 /* Job finished, move the shell to the foreground */
1585 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1586 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1587 bb_perror_msg("tcsetpgrp-4a");
1592 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1593 * to finish. See checkjobs().
1595 * return code is normally -1, when the caller has to wait for children
1596 * to finish to determine the exit status of the pipe. If the pipe
1597 * is a simple builtin command, however, the action is done by the
1598 * time run_pipe_real returns, and the exit code is provided as the
1601 * The input of the pipe is always stdin, the output is always
1602 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1603 * because it tries to avoid running the command substitution in
1604 * subshell, when that is in fact necessary. The subshell process
1605 * now has its stdout directed to the input of the appropriate pipe,
1606 * so this routine is noticeably simpler.
1608 static int run_pipe_real(struct pipe *pi)
1611 int nextin, nextout;
1612 int pipefds[2]; /* pipefds[0] is for reading */
1613 struct child_prog *child;
1614 const struct built_in_command *x;
1616 /* it is not always needed, but we aim to smaller code */
1617 int squirrel[] = { -1, -1, -1 };
1619 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1621 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1627 pi->running_progs = 1;
1628 pi->stopped_progs = 0;
1630 /* Check if this is a simple builtin (not part of a pipe).
1631 * Builtins within pipes have to fork anyway, and are handled in
1632 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1634 child = &(pi->progs[0]);
1635 if (single_fg && child->group && child->subshell == 0) {
1636 debug_printf("non-subshell grouping\n");
1637 setup_redirects(child, squirrel);
1638 debug_printf_exec(": run_list_real\n");
1639 rcode = run_list_real(child->group);
1640 restore_redirects(squirrel);
1641 debug_printf_exec("run_pipe_real return %d\n", rcode);
1645 if (single_fg && child->argv != NULL) {
1646 char **argv_expanded;
1647 char **argv = child->argv;
1649 for (i = 0; is_assignment(argv[i]); i++)
1651 if (i != 0 && argv[i] == NULL) {
1652 /* assignments, but no command: set the local environment */
1653 for (i = 0; argv[i] != NULL; i++) {
1654 /* Ok, this case is tricky. We have to decide if this is a
1655 * local variable, or an already exported variable. If it is
1656 * already exported, we have to export the new value. If it is
1657 * not exported, we need only set this as a local variable.
1658 * This junk is all to decide whether or not to export this
1662 name = xstrdup(argv[i]);
1663 debug_printf("local environment set: %s\n", name);
1664 value = strchr(name, '=');
1667 if (get_local_var(name)) {
1671 p = expand_variables_to_string(argv[i]);
1672 set_local_var(p, export_me);
1676 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1678 for (i = 0; is_assignment(argv[i]); i++) {
1679 p = expand_variables_to_string(argv[i]);
1687 for (x = bltins; x->cmd; x++) {
1688 if (strcmp(argv[i], x->cmd) == 0) {
1689 if (x->function == builtin_exec && argv[i+1] == NULL) {
1690 debug_printf("magic exec\n");
1691 setup_redirects(child, NULL);
1692 return EXIT_SUCCESS;
1694 debug_printf("builtin inline %s\n", argv[0]);
1695 /* XXX setup_redirects acts on file descriptors, not FILEs.
1696 * This is perfect for work that comes after exec().
1697 * Is it really safe for inline use? Experimentally,
1698 * things seem to work with glibc. */
1699 setup_redirects(child, squirrel);
1700 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1701 //sp: if (child->sp) /* btw we can do it unconditionally... */
1702 argv_expanded = expand_variables_to_list(argv + i);
1703 rcode = x->function(argv_expanded);
1704 free(argv_expanded);
1705 restore_redirects(squirrel);
1706 debug_printf_exec("run_pipe_real return %d\n", rcode);
1710 #if ENABLE_FEATURE_SH_STANDALONE
1712 const struct bb_applet *a = find_applet_by_name(argv[i]);
1713 if (a && a->nofork) {
1714 setup_redirects(child, squirrel);
1715 save_nofork_data(&nofork_save);
1716 argv_expanded = argv + i;
1717 //sp: if (child->sp)
1718 argv_expanded = expand_variables_to_list(argv + i);
1719 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1720 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
1721 free(argv_expanded);
1722 restore_redirects(squirrel);
1723 debug_printf_exec("run_pipe_real return %d\n", rcode);
1730 /* Going to fork a child per each pipe member */
1731 pi->running_progs = 0;
1733 /* Disable job control signals for shell (parent) and
1734 * for initial child code after fork */
1735 set_jobctrl_sighandler(SIG_IGN);
1737 for (i = 0; i < pi->num_progs; i++) {
1738 child = &(pi->progs[i]);
1740 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1742 debug_printf_exec(": pipe member with no argv\n");
1744 /* pipes are inserted between pairs of commands */
1745 if ((i + 1) < pi->num_progs) {
1746 if (pipe(pipefds) < 0)
1747 bb_perror_msg_and_die("pipe");
1748 nextout = pipefds[1];
1754 /* XXX test for failed fork()? */
1756 child->pid = fork();
1758 child->pid = vfork();
1760 if (!child->pid) { /* child */
1761 /* Every child adds itself to new process group
1762 * with pgid == pid of first child in pipe */
1764 if (interactive_fd) {
1765 /* Don't do pgrp restore anymore on fatal signals */
1766 set_fatal_sighandler(SIG_DFL);
1767 if (pi->pgrp < 0) /* true for 1st process only */
1768 pi->pgrp = getpid();
1769 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1770 /* We do it in *every* child, not just first,
1772 tcsetpgrp(interactive_fd, pi->pgrp);
1776 /* in non-interactive case fatal sigs are already SIG_DFL */
1786 if (pipefds[0] != -1) {
1787 close(pipefds[0]); /* opposite end of our output pipe */
1789 /* Like bash, explicit redirects override pipes,
1790 * and the pipe fd is available for dup'ing. */
1791 setup_redirects(child, NULL);
1793 /* Restore default handlers just prior to exec */
1794 set_jobctrl_sighandler(SIG_DFL);
1795 set_misc_sighandler(SIG_DFL);
1796 signal(SIGCHLD, SIG_DFL);
1800 pi->running_progs++;
1803 /* Second and next children need to know pid of first one */
1805 pi->pgrp = child->pid;
1812 /* If there isn't another process, nextin is garbage
1813 but it doesn't matter */
1814 nextin = pipefds[0];
1816 debug_printf_exec("run_pipe_real return -1\n");
1820 #ifndef debug_print_tree
1821 static void debug_print_tree(struct pipe *pi, int lvl)
1823 static const char *PIPE[] = {
1829 static const char *RES[] = {
1830 [RES_NONE ] = "NONE" ,
1832 [RES_THEN ] = "THEN" ,
1833 [RES_ELIF ] = "ELIF" ,
1834 [RES_ELSE ] = "ELSE" ,
1836 [RES_FOR ] = "FOR" ,
1837 [RES_WHILE] = "WHILE",
1838 [RES_UNTIL] = "UNTIL",
1840 [RES_DONE ] = "DONE" ,
1841 [RES_XXXX ] = "XXXX" ,
1843 [RES_SNTX ] = "SNTX" ,
1849 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1850 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1852 while (prn < pi->num_progs) {
1853 struct child_prog *child = &pi->progs[prn];
1854 char **argv = child->argv;
1856 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1858 fprintf(stderr, " group %s: (argv=%p)\n",
1859 (child->subshell ? "()" : "{}"),
1861 debug_print_tree(child->group, lvl+1);
1865 if (argv) while (*argv) {
1866 fprintf(stderr, " '%s'", *argv);
1869 fprintf(stderr, "\n");
1878 /* NB: called by pseudo_exec, and therefore must not modify any
1879 * global data until exec/_exit (we can be a child after vfork!) */
1880 static int run_list_real(struct pipe *pi)
1888 char *for_varname = NULL;
1889 char **for_lcur = NULL;
1890 char **for_list = NULL;
1895 int rcode = 0; /* probably for gcc only */
1896 int flag_restore = 0;
1897 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1898 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1900 debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1902 /* check syntax for "for" */
1903 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1904 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1905 && (rpipe->next == NULL)
1907 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1908 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1911 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1912 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1914 /* TODO: what is tested in the first condition? */
1915 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1916 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1922 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1923 * We are saving state before entering outermost list ("while...done")
1924 * so that ctrl-Z will correctly background _entire_ outermost list,
1925 * not just a part of it (like "sleep 1 | exit 2") */
1926 if (++level == 1 && interactive_fd) {
1927 if (sigsetjmp(toplevel_jb, 1)) {
1928 /* ctrl-Z forked and we are parent; or ctrl-C.
1929 * Sighandler has longjmped us here */
1930 signal(SIGINT, SIG_IGN);
1931 signal(SIGTSTP, SIG_IGN);
1932 /* Restore level (we can be coming from deep inside
1935 #if ENABLE_FEATURE_SH_STANDALONE
1936 if (nofork_save.saved) { /* if save area is valid */
1937 debug_printf_jobs("exiting nofork early\n");
1938 restore_nofork_data(&nofork_save);
1942 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1943 * Remember this child as background job */
1946 /* ctrl-C. We just stop doing whatever we were doing */
1952 /* ctrl-Z handler will store pid etc in pi */
1955 #if ENABLE_FEATURE_SH_STANDALONE
1956 nofork_save.saved = 0; /* in case we will run a nofork later */
1958 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1959 signal(SIGINT, handler_ctrl_c);
1963 for (; pi; pi = flag_restore ? rpipe : pi->next) {
1965 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
1972 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1973 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1974 if (rmode == skip_more_in_this_rmode && flag_skip) {
1975 if (pi->followup == PIPE_SEQ)
1980 skip_more_in_this_rmode = RES_XXXX;
1981 if (rmode == RES_THEN || rmode == RES_ELSE)
1982 if_code = next_if_code;
1983 if (rmode == RES_THEN && if_code)
1985 if (rmode == RES_ELSE && !if_code)
1987 if (rmode == RES_ELIF && !if_code)
1989 if (rmode == RES_FOR && pi->num_progs) {
1991 /* if no variable values after "in" we skip "for" */
1992 if (!pi->next->progs->argv)
1994 /* create list of variable values */
1995 for_list = expand_variables_to_list(pi->next->progs->argv);
1996 for_lcur = for_list;
1997 for_varname = pi->progs->argv[0];
1998 pi->progs->argv[0] = NULL;
2001 free(pi->progs->argv[0]);
2006 pi->progs->argv[0] = for_varname;
2007 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2010 /* insert next value from for_lcur */
2011 /* vda: does it need escaping? */
2012 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2013 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2015 if (rmode == RES_IN)
2017 if (rmode == RES_DO) {
2021 if (rmode == RES_DONE) {
2028 if (pi->num_progs == 0)
2030 save_num_progs = pi->num_progs; /* save number of programs */
2031 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2032 rcode = run_pipe_real(pi);
2034 /* We only ran a builtin: rcode was set by the return value
2035 * of run_pipe_real(), and we don't need to wait for anything. */
2036 } else if (pi->followup == PIPE_BG) {
2037 /* What does bash do with attempts to background builtins? */
2039 /* Even bash 3.2 doesn't do that well with nested bg:
2040 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2041 * I'm considering NOT treating inner bgs as jobs -
2042 * thus maybe "if (level == 1 && pi->followup == PIPE_BG)"
2047 rcode = EXIT_SUCCESS;
2050 /* Paranoia, just "interactive_fd" should be enough */
2051 if (level == 1 && interactive_fd) {
2052 rcode = checkjobs_and_fg_shell(pi);
2056 rcode = checkjobs(pi);
2058 debug_printf_exec(": checkjobs returned %d\n", rcode);
2060 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2061 last_return_code = rcode;
2062 pi->num_progs = save_num_progs; /* restore number of programs */
2063 if (rmode == RES_IF || rmode == RES_ELIF)
2064 next_if_code = rcode; /* can be overwritten a number of times */
2065 if (rmode == RES_WHILE)
2066 flag_rep = !last_return_code;
2067 if (rmode == RES_UNTIL)
2068 flag_rep = last_return_code;
2069 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2070 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2072 skip_more_in_this_rmode = rmode;
2079 /* ctrl-Z forked somewhere in the past, we are the child,
2080 * and now we completed running the list. Exit. */
2086 debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2090 /* return code is the exit status of the pipe */
2091 static int free_pipe(struct pipe *pi, int indent)
2094 struct child_prog *child;
2095 struct redir_struct *r, *rnext;
2096 int a, i, ret_code = 0;
2098 if (pi->stopped_progs > 0)
2100 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2101 for (i = 0; i < pi->num_progs; i++) {
2102 child = &pi->progs[i];
2103 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2105 for (a = 0, p = child->argv; *p; a++, p++) {
2106 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2108 globfree(&child->glob_result);
2110 } else if (child->group) {
2111 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2112 ret_code = free_pipe_list(child->group, indent+3);
2113 debug_printf_clean("%s end group\n", indenter(indent));
2115 debug_printf_clean("%s (nil)\n", indenter(indent));
2117 for (r = child->redirects; r; r = rnext) {
2118 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2120 /* guard against the case >$FOO, where foo is unset or blank */
2121 if (r->word.gl_pathv) {
2122 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2126 debug_printf_clean("&%d\n", r->dup);
2131 child->redirects = NULL;
2133 free(pi->progs); /* children are an array, they get freed all at once */
2142 static int free_pipe_list(struct pipe *head, int indent)
2144 int rcode = 0; /* if list has no members */
2145 struct pipe *pi, *next;
2147 for (pi = head; pi; pi = next) {
2148 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2149 rcode = free_pipe(pi, indent);
2150 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2152 /*pi->next = NULL;*/
2158 /* Select which version we will use */
2159 static int run_list(struct pipe *pi)
2162 debug_printf_exec("run_list entered\n");
2163 if (fake_mode == 0) {
2164 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2165 rcode = run_list_real(pi);
2167 /* free_pipe_list has the side effect of clearing memory.
2168 * In the long run that function can be merged with run_list_real,
2169 * but doing that now would hobble the debugging effort. */
2170 free_pipe_list(pi, 0);
2171 debug_printf_exec("run_list return %d\n", rcode);
2175 /* The API for glob is arguably broken. This routine pushes a non-matching
2176 * string into the output structure, removing non-backslashed backslashes.
2177 * If someone can prove me wrong, by performing this function within the
2178 * original glob(3) api, feel free to rewrite this routine into oblivion.
2179 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2180 * XXX broken if the last character is '\\', check that before calling.
2182 static int globhack(const char *src, int flags, glob_t *pglob)
2187 for (cnt = 1, s = src; s && *s; s++) {
2188 if (*s == '\\') s++;
2191 dest = xmalloc(cnt);
2192 if (!(flags & GLOB_APPEND)) {
2193 pglob->gl_pathv = NULL;
2194 pglob->gl_pathc = 0;
2198 pathc = ++pglob->gl_pathc;
2199 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2200 pglob->gl_pathv[pathc-1] = dest;
2201 pglob->gl_pathv[pathc] = NULL;
2202 for (s = src; s && *s; s++, dest++) {
2203 if (*s == '\\') s++;
2210 /* XXX broken if the last character is '\\', check that before calling */
2211 static int glob_needed(const char *s)
2214 if (*s == '\\') s++;
2215 if (strchr("*[?", *s)) return 1;
2220 static int xglob(o_string *dest, int flags, glob_t *pglob)
2224 /* short-circuit for null word */
2225 /* we can code this better when the debug_printf's are gone */
2226 if (dest->length == 0) {
2227 if (dest->nonnull) {
2228 /* bash man page calls this an "explicit" null */
2229 gr = globhack(dest->data, flags, pglob);
2230 debug_printf("globhack returned %d\n", gr);
2234 } else if (glob_needed(dest->data)) {
2235 gr = glob(dest->data, flags, NULL, pglob);
2236 debug_printf("glob returned %d\n", gr);
2237 if (gr == GLOB_NOMATCH) {
2238 /* quote removal, or more accurately, backslash removal */
2239 gr = globhack(dest->data, flags, pglob);
2240 debug_printf("globhack returned %d\n", gr);
2243 gr = globhack(dest->data, flags, pglob);
2244 debug_printf("globhack returned %d\n", gr);
2246 if (gr == GLOB_NOSPACE)
2247 bb_error_msg_and_die("out of memory during glob");
2248 if (gr != 0) { /* GLOB_ABORTED ? */
2249 bb_error_msg("glob(3) error %d", gr);
2251 /* globprint(glob_target); */
2255 /* expand_variables_to_list() takes a list of strings, expands
2256 * all variable references within and returns a pointer to
2257 * a list of expanded strings, possibly with larger number
2258 * of strings. (Think VAR="a b"; echo $VAR).
2259 * This new list is allocated as a single malloc block.
2260 * NULL-terminated list of char* pointers is at the beginning of it,
2261 * followed by strings themself.
2262 * Caller can deallocate entire list by single free(list). */
2265 * count_XXX estimates size of the block we need. It's okay
2266 * to over-estimate sizes a bit, if it makes code simpler */
2267 static int count_ifs(const char *str)
2270 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2272 str += strcspn(str, ifs);
2274 str++; /* str += strspn(str, ifs); */
2275 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2277 debug_printf_expand(" return %d\n", cnt);
2281 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2286 int count = *countp;
2290 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2293 p = strchr(p, SPECIAL_VAR_SYMBOL);
2296 switch (first_ch & 0x7f) {
2297 /* high bit in 1st_ch indicates that var is double-quoted */
2299 case '!': /* bg pid */
2300 case '?': /* exitcode */
2301 case '#': /* argc */
2302 len += sizeof(int)*3 + 1; /* enough for int */
2306 for (i = 1; i < global_argc; i++) {
2307 len += strlen(global_argv[i]) + 1;
2309 if (!(first_ch & 0x80))
2310 count += count_ifs(global_argv[i]);
2315 arg[0] = first_ch & 0x7f;
2316 if (isdigit(arg[0])) {
2319 if (i < global_argc)
2320 val = global_argv[i];
2322 val = lookup_param(arg);
2324 *p = SPECIAL_VAR_SYMBOL;
2327 len += strlen(val) + 1;
2328 if (!(first_ch & 0x80))
2329 count += count_ifs(val);
2335 len += strlen(arg) + 1;
2341 /* Store given string, finalizing the word and starting new one whenever
2342 * we encounter ifs char(s). This is used for expanding variable values.
2343 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2344 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2348 int word_len = strcspn(str, ifs);
2350 memcpy(pos, str, word_len); /* store non-ifs chars */
2354 if (!*str) /* EOL - do not finalize word */
2357 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2358 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2359 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2361 str += strspn(str, ifs); /* skip ifs chars */
2367 /* Expand all variable references in given string, adding words to list[]
2368 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2369 * to be filled). This routine is extremely tricky: has to deal with
2370 * variables/parameters with whitespace, $* and $@, and constructs like
2371 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2372 /* NB: another bug is that we cannot detect empty strings yet:
2373 * "" or $empty"" expands to zero words, has to expand to empty word */
2374 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2376 /* or_mask is either 0 (normal case) or 0x80
2377 * (expansion of right-hand side of assignment == 1-element expand) */
2379 char first_ch, ored_ch;
2387 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2388 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2389 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2392 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2393 memcpy(pos, arg, p - arg);
2396 p = strchr(p, SPECIAL_VAR_SYMBOL);
2398 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2399 ored_ch |= first_ch;
2401 switch (first_ch & 0x7f) {
2402 /* Highest bit in first_ch indicates that var is double-quoted */
2404 /* FIXME: (echo $$) should still print pid of main shell */
2405 val = utoa(getpid());
2407 case '!': /* bg pid */
2408 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2410 case '?': /* exitcode */
2411 val = utoa(last_return_code);
2413 case '#': /* argc */
2414 val = utoa(global_argc ? global_argc-1 : 0);
2419 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2420 while (i < global_argc) {
2421 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2422 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2423 if (global_argv[i++][0] && i < global_argc) {
2424 /* this argv[] is not empty and not last:
2425 * put terminating NUL, start new word */
2427 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2428 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2429 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2434 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2435 * and in this case should theat it like '$*' */
2436 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2438 strcpy(pos, global_argv[i]);
2439 pos += strlen(global_argv[i]);
2440 if (++i >= global_argc)
2443 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2444 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2445 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2448 } else { /* quoted $*: add as one word */
2450 strcpy(pos, global_argv[i]);
2451 pos += strlen(global_argv[i]);
2452 if (++i >= global_argc)
2461 arg[0] = first_ch & 0x7f;
2462 if (isdigit(arg[0])) {
2465 if (i < global_argc)
2466 val = global_argv[i];
2468 val = lookup_param(arg);
2470 *p = SPECIAL_VAR_SYMBOL;
2471 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2473 n = expand_on_ifs(list, n, &pos, val);
2476 } /* else: quoted $VAR, val will be appended at pos */
2484 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2486 pos += strlen(arg) + 1;
2487 if (pos == list[n-1] + 1) { /* expansion is empty */
2488 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2489 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2499 static char **expand_variables(char **argv, char or_mask)
2504 char *pos, **v, **list;
2507 if (!*v) debug_printf_expand("count_var_expansion_space: "
2508 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2509 count, len, sizeof(char*) * count + len);
2511 count_var_expansion_space(&count, &len, *v);
2512 debug_printf_expand("count_var_expansion_space: "
2513 "'%s' count=%d len=%d alloc_space=%d\n",
2514 *v, count, len, sizeof(char*) * count + len);
2517 len += sizeof(char*) * count; /* total to alloc */
2518 list = xmalloc(len);
2519 pos = (char*)(list + count);
2520 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2524 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2526 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2527 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2528 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2535 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2538 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2541 /* To be removed / made conditional later. */
2542 if (pos - (char*)list > len)
2543 bb_error_msg_and_die("BUG in varexp");
2547 static char **expand_variables_to_list(char **argv)
2549 return expand_variables(argv, 0);
2552 static char *expand_variables_to_string(const char *str)
2554 char *argv[2], **list;
2556 argv[0] = (char*)str;
2558 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2559 /* To be removed / made conditional later. */
2560 if (!list[0] || list[1])
2561 bb_error_msg_and_die("BUG in varexp");
2562 /* actually, just move string 2*sizeof(char*) bytes back */
2563 strcpy((char*)list, list[0]);
2567 /* This is used to get/check local shell variables */
2568 static const char *get_local_var(const char *s)
2570 struct variables *cur;
2574 for (cur = top_vars; cur; cur = cur->next) {
2575 if (strcmp(cur->name, s) == 0)
2581 /* This is used to set local shell variables
2582 flg_export == 0 if only local (not exporting) variable
2583 flg_export == 1 if "new" exporting environ
2584 flg_export > 1 if current startup environ (not call putenv()) */
2585 static int set_local_var(const char *s, int flg_export)
2589 struct variables *cur;
2593 /* Assume when we enter this function that we are already in
2594 * NAME=VALUE format. So the first order of business is to
2595 * split 's' on the '=' into 'name' and 'value' */
2596 value = strchr(name, '=');
2597 /*if (value == 0 && ++value == 0) ??? -vda */
2598 if (value == NULL || value[1] == '\0') {
2604 for (cur = top_vars; cur; cur = cur->next) {
2605 if (strcmp(cur->name, name) == 0) {
2606 if (strcmp(cur->value, value) == 0) {
2607 if (flg_export && !cur->flg_export)
2608 cur->flg_export = flg_export;
2611 } else if (cur->flg_read_only) {
2612 bb_error_msg("%s: readonly variable", name);
2615 if (flg_export > 0 || cur->flg_export > 1)
2616 cur->flg_export = 1;
2617 free((char*)cur->value);
2618 cur->value = xstrdup(value);
2624 cur = xzalloc(sizeof(*cur));
2625 cur->name = xstrdup(name);
2626 cur->value = xstrdup(value);
2628 cur->flg_export = flg_export;
2629 /*cur->flg_read_only = 0;*/
2631 struct variables *bottom = top_vars;
2632 while (bottom->next)
2633 bottom = bottom->next;
2637 if (result == 0 && cur->flg_export == 1) {
2639 result = putenv(name);
2642 if (result > 0) /* equivalent to previous set */
2648 static void unset_local_var(const char *name)
2650 struct variables *cur, *next;
2654 for (cur = top_vars; cur; cur = cur->next) {
2655 if (strcmp(cur->name, name) == 0) {
2656 if (cur->flg_read_only) {
2657 bb_error_msg("%s: readonly variable", name);
2660 if (cur->flg_export)
2661 unsetenv(cur->name);
2662 free((char*)cur->name);
2663 free((char*)cur->value);
2665 while (next->next != cur)
2667 next->next = cur->next;
2674 static int is_assignment(const char *s)
2676 if (!s || !isalpha(*s))
2679 while (isalnum(*s) || *s == '_')
2684 /* the src parameter allows us to peek forward to a possible &n syntax
2685 * for file descriptor duplication, e.g., "2>&1".
2686 * Return code is 0 normally, 1 if a syntax error is detected in src.
2687 * Resource errors (in xmalloc) cause the process to exit */
2688 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2689 struct in_str *input)
2691 struct child_prog *child = ctx->child;
2692 struct redir_struct *redir = child->redirects;
2693 struct redir_struct *last_redir = NULL;
2695 /* Create a new redir_struct and drop it onto the end of the linked list */
2698 redir = redir->next;
2700 redir = xmalloc(sizeof(struct redir_struct));
2702 redir->word.gl_pathv = NULL;
2704 last_redir->next = redir;
2706 child->redirects = redir;
2709 redir->type = style;
2710 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2712 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2714 /* Check for a '2>&1' type redirect */
2715 redir->dup = redirect_dup_num(input);
2716 if (redir->dup == -2) return 1; /* syntax error */
2717 if (redir->dup != -1) {
2718 /* Erik had a check here that the file descriptor in question
2719 * is legit; I postpone that to "run time"
2720 * A "-" representation of "close me" shows up as a -3 here */
2721 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2723 /* We do _not_ try to open the file that src points to,
2724 * since we need to return and let src be expanded first.
2725 * Set ctx->pending_redirect, so we know what to do at the
2726 * end of the next parsed word.
2728 ctx->pending_redirect = redir;
2733 static struct pipe *new_pipe(void)
2736 pi = xzalloc(sizeof(struct pipe));
2737 /*pi->num_progs = 0;*/
2738 /*pi->progs = NULL;*/
2739 /*pi->next = NULL;*/
2740 /*pi->followup = 0; invalid */
2742 pi->r_mode = RES_NONE;
2746 static void initialize_context(struct p_context *ctx)
2749 ctx->pending_redirect = NULL;
2751 ctx->list_head = new_pipe();
2752 ctx->pipe = ctx->list_head;
2753 ctx->res_w = RES_NONE;
2756 done_command(ctx); /* creates the memory for working child */
2759 /* normal return is 0
2760 * if a reserved word is found, and processed, return 1
2761 * should handle if, then, elif, else, fi, for, while, until, do, done.
2762 * case, function, and select are obnoxious, save those for later.
2764 static int reserved_word(o_string *dest, struct p_context *ctx)
2766 struct reserved_combo {
2771 /* Mostly a list of accepted follow-up reserved words.
2772 * FLAG_END means we are done with the sequence, and are ready
2773 * to turn the compound list into a command.
2774 * FLAG_START means the word must start a new compound list.
2776 static const struct reserved_combo reserved_list[] = {
2777 { "if", RES_IF, FLAG_THEN | FLAG_START },
2778 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2779 { "elif", RES_ELIF, FLAG_THEN },
2780 { "else", RES_ELSE, FLAG_FI },
2781 { "fi", RES_FI, FLAG_END },
2782 { "for", RES_FOR, FLAG_IN | FLAG_START },
2783 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2784 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2785 { "in", RES_IN, FLAG_DO },
2786 { "do", RES_DO, FLAG_DONE },
2787 { "done", RES_DONE, FLAG_END }
2789 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2790 const struct reserved_combo *r;
2792 for (r = reserved_list; r < reserved_list + NRES; r++) {
2793 if (strcmp(dest->data, r->literal) == 0) {
2794 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2795 if (r->flag & FLAG_START) {
2796 struct p_context *new = xmalloc(sizeof(struct p_context));
2797 debug_printf("push stack\n");
2798 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2801 ctx->res_w = RES_SNTX;
2805 *new = *ctx; /* physical copy */
2806 initialize_context(ctx);
2808 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2810 ctx->res_w = RES_SNTX;
2814 ctx->res_w = r->code;
2815 ctx->old_flag = r->flag;
2816 if (ctx->old_flag & FLAG_END) {
2817 struct p_context *old;
2818 debug_printf("pop stack\n");
2819 done_pipe(ctx, PIPE_SEQ);
2821 old->child->group = ctx->list_head;
2822 old->child->subshell = 0;
2823 *ctx = *old; /* physical copy */
2833 /* Normal return is 0.
2834 * Syntax or xglob errors return 1. */
2835 static int done_word(o_string *dest, struct p_context *ctx)
2837 struct child_prog *child = ctx->child;
2838 glob_t *glob_target;
2841 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2842 if (dest->length == 0 && !dest->nonnull) {
2843 debug_printf_parse("done_word return 0: true null, ignored\n");
2846 if (ctx->pending_redirect) {
2847 glob_target = &ctx->pending_redirect->word;
2851 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2854 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2855 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2856 if (reserved_word(dest, ctx)) {
2857 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2858 return (ctx->res_w == RES_SNTX);
2861 glob_target = &child->glob_result;
2863 flags |= GLOB_APPEND;
2865 gr = xglob(dest, flags, glob_target);
2867 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2872 if (ctx->pending_redirect) {
2873 ctx->pending_redirect = NULL;
2874 if (glob_target->gl_pathc != 1) {
2875 bb_error_msg("ambiguous redirect");
2876 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2880 child->argv = glob_target->gl_pathv;
2882 if (ctx->res_w == RES_FOR) {
2883 done_word(dest, ctx);
2884 done_pipe(ctx, PIPE_SEQ);
2886 debug_printf_parse("done_word return 0\n");
2890 /* The only possible error here is out of memory, in which case
2892 static int done_command(struct p_context *ctx)
2894 /* The child is really already in the pipe structure, so
2895 * advance the pipe counter and make a new, null child. */
2896 struct pipe *pi = ctx->pipe;
2897 struct child_prog *child = ctx->child;
2900 if (child->group == NULL
2901 && child->argv == NULL
2902 && child->redirects == NULL
2904 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2905 return pi->num_progs;
2908 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2910 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2913 /* Only real trickiness here is that the uncommitted
2914 * child structure is not counted in pi->num_progs. */
2915 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2916 child = &pi->progs[pi->num_progs];
2918 memset(child, 0, sizeof(*child));
2919 /*child->redirects = NULL;*/
2920 /*child->argv = NULL;*/
2921 /*child->is_stopped = 0;*/
2922 /*child->group = NULL;*/
2923 /*child->glob_result.gl_pathv = NULL;*/
2925 //sp: /*child->sp = 0;*/
2926 child->type = ctx->parse_type;
2929 /* but ctx->pipe and ctx->list_head remain unchanged */
2931 return pi->num_progs; /* used only for 0/nonzero check */
2934 static int done_pipe(struct p_context *ctx, pipe_style type)
2939 debug_printf_parse("done_pipe entered, followup %d\n", type);
2940 not_null = done_command(ctx); /* implicit closure of previous command */
2941 ctx->pipe->followup = type;
2942 ctx->pipe->r_mode = ctx->res_w;
2943 /* Without this check, even just <enter> on command line generates
2944 * tree of three NOPs (!). Which is harmless but annoying.
2945 * IOW: it is safe to do it unconditionally. */
2948 ctx->pipe->next = new_p;
2951 done_command(ctx); /* set up new pipe to accept commands */
2953 debug_printf_parse("done_pipe return 0\n");
2957 /* peek ahead in the in_str to find out if we have a "&n" construct,
2958 * as in "2>&1", that represents duplicating a file descriptor.
2959 * returns either -2 (syntax error), -1 (no &), or the number found.
2961 static int redirect_dup_num(struct in_str *input)
2963 int ch, d = 0, ok = 0;
2965 if (ch != '&') return -1;
2967 b_getch(input); /* get the & */
2971 return -3; /* "-" represents "close me" */
2973 while (isdigit(ch)) {
2974 d = d*10 + (ch-'0');
2981 bb_error_msg("ambiguous redirect");
2985 /* If a redirect is immediately preceded by a number, that number is
2986 * supposed to tell which file descriptor to redirect. This routine
2987 * looks for such preceding numbers. In an ideal world this routine
2988 * needs to handle all the following classes of redirects...
2989 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2990 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2991 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2992 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2993 * A -1 output from this program means no valid number was found, so the
2994 * caller should use the appropriate default for this redirection.
2996 static int redirect_opt_num(o_string *o)
3002 for (num = 0; num < o->length; num++) {
3003 if (!isdigit(*(o->data + num))) {
3007 /* reuse num (and save an int) */
3008 num = atoi(o->data);
3013 static FILE *generate_stream_from_list(struct pipe *head)
3016 int pid, channel[2];
3017 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
3024 bb_perror_msg_and_die("fork");
3025 } else if (pid == 0) {
3027 if (channel[1] != 1) {
3028 dup2(channel[1], 1);
3031 _exit(run_list_real(head)); /* leaks memory */
3033 debug_printf("forked child %d\n", pid);
3035 pf = fdopen(channel[0], "r");
3036 debug_printf("pipe on FILE *%p\n", pf);
3040 /* Return code is exit status of the process that is run. */
3041 static int process_command_subs(o_string *dest, struct p_context *ctx,
3042 struct in_str *input, const char *subst_end)
3044 int retcode, ch, eol_cnt;
3045 o_string result = NULL_O_STRING;
3046 struct p_context inner;
3048 struct in_str pipe_str;
3050 initialize_context(&inner);
3052 /* recursion to generate command */
3053 retcode = parse_stream(&result, &inner, input, subst_end);
3054 if (retcode != 0) return retcode; /* syntax error or EOF */
3055 done_word(&result, &inner);
3056 done_pipe(&inner, PIPE_SEQ);
3059 p = generate_stream_from_list(inner.list_head);
3060 if (p == NULL) return 1;
3061 mark_open(fileno(p));
3062 setup_file_in_str(&pipe_str, p);
3064 /* now send results of command back into original context */
3066 while ((ch = b_getch(&pipe_str)) != EOF) {
3072 b_addqchr(dest, '\n', dest->quote);
3075 b_addqchr(dest, ch, dest->quote);
3078 debug_printf("done reading from pipe, pclose()ing\n");
3079 /* This is the step that wait()s for the child. Should be pretty
3080 * safe, since we just read an EOF from its stdout. We could try
3081 * to better, by using wait(), and keeping track of background jobs
3082 * at the same time. That would be a lot of work, and contrary
3083 * to the KISS philosophy of this program. */
3084 mark_closed(fileno(p));
3085 retcode = pclose(p);
3086 free_pipe_list(inner.list_head, 0);
3087 debug_printf("pclosed, retcode=%d\n", retcode);
3091 static int parse_group(o_string *dest, struct p_context *ctx,
3092 struct in_str *input, int ch)
3095 const char *endch = NULL;
3096 struct p_context sub;
3097 struct child_prog *child = ctx->child;
3099 debug_printf_parse("parse_group entered\n");
3102 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3105 initialize_context(&sub);
3109 child->subshell = 1;
3115 syntax(); /* really logic error */
3117 rcode = parse_stream(dest, &sub, input, endch);
3118 done_word(dest, &sub); /* finish off the final word in the subcontext */
3119 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3120 child->group = sub.list_head;
3122 debug_printf_parse("parse_group return %d\n", rcode);
3124 /* child remains "open", available for possible redirects */
3127 /* Basically useful version until someone wants to get fancier,
3128 * see the bash man page under "Parameter Expansion" */
3129 static const char *lookup_param(const char *src)
3131 const char *p = NULL;
3135 p = get_local_var(src);
3140 /* Make new string for parser */
3141 static char* make_string(char **inp)
3149 for (n = 0; inp[n]; n++) {
3150 p = expand_variables_to_string(inp[n]);
3151 val_len = strlen(p);
3152 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3154 strcpy(str + len, p);
3156 if (p != inp[n]) free(p);
3158 /* We do not check for case where loop had no iterations at all
3159 * - cannot happen? */
3165 /* return code: 0 for OK, 1 for syntax error */
3166 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3168 int ch = b_peek(input); /* first character after the $ */
3169 unsigned char quote_mask = dest->quote ? 0x80 : 0;
3171 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3173 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3174 //sp: ctx->child->sp++;
3176 debug_printf_parse(": '%c'\n", ch);
3178 b_addchr(dest, ch | quote_mask);
3181 if (!isalnum(ch) && ch != '_')
3184 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3185 } else if (isdigit(ch)) {
3187 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3188 //sp: ctx->child->sp++;
3189 debug_printf_parse(": '%c'\n", ch);
3191 b_addchr(dest, ch | quote_mask);
3192 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3193 } else switch (ch) {
3195 case '!': /* last bg pid */
3196 case '?': /* last exit code */
3197 case '#': /* number of args */
3198 case '*': /* args */
3199 case '@': /* args */
3200 goto make_one_char_var;
3202 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3203 //sp: ctx->child->sp++;
3205 /* XXX maybe someone will try to escape the '}' */
3207 ch = b_getch(input);
3210 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3215 debug_printf_parse(": '%c'\n", ch);
3216 b_addchr(dest, ch | quote_mask);
3219 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3223 process_command_subs(dest, ctx, input, ")");
3227 /* still unhandled, but should be eventually */
3228 bb_error_msg("unhandled syntax: $%c", ch);
3232 b_addqchr(dest, '$', dest->quote);
3234 debug_printf_parse("handle_dollar return 0\n");
3238 /* return code is 0 for normal exit, 1 for syntax error */
3239 static int parse_stream(o_string *dest, struct p_context *ctx,
3240 struct in_str *input, const char *end_trigger)
3244 redir_type redir_style;
3247 /* Only double-quote state is handled in the state variable dest->quote.
3248 * A single-quote triggers a bypass of the main loop until its mate is
3249 * found. When recursing, quote state is passed in via dest->quote. */
3251 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3253 while ((ch = b_getch(input)) != EOF) {
3255 next = (ch == '\n') ? '\0' : b_peek(input);
3256 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3257 ch, ch, m, dest->quote);
3258 if (m == CHAR_ORDINARY
3259 || (m != CHAR_SPECIAL && dest->quote)
3261 b_addqchr(dest, ch, dest->quote);
3264 if (m == CHAR_IFS) {
3265 if (done_word(dest, ctx)) {
3266 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3269 /* If we aren't performing a substitution, treat
3270 * a newline as a command separator.
3271 * [why we don't handle it exactly like ';'? --vda] */
3272 if (end_trigger && ch == '\n') {
3273 done_pipe(ctx, PIPE_SEQ);
3276 if ((end_trigger && strchr(end_trigger, ch))
3277 && !dest->quote && ctx->res_w == RES_NONE
3279 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3286 if (dest->length == 0 && !dest->quote) {
3289 if (ch == EOF || ch == '\n')
3294 b_addqchr(dest, ch, dest->quote);
3300 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3303 b_addqchr(dest, '\\', dest->quote);
3304 b_addqchr(dest, b_getch(input), dest->quote);
3307 if (handle_dollar(dest, ctx, input) != 0) {
3308 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3315 ch = b_getch(input);
3316 if (ch == EOF || ch == '\'')
3322 debug_printf_parse("parse_stream return 1: unterminated '\n");
3328 dest->quote = !dest->quote;
3331 process_command_subs(dest, ctx, input, "`");
3334 redir_fd = redirect_opt_num(dest);
3335 done_word(dest, ctx);
3336 redir_style = REDIRECT_OVERWRITE;
3338 redir_style = REDIRECT_APPEND;
3340 } else if (next == '(') {
3341 syntax(); /* until we support >(list) Process Substitution */
3342 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3345 setup_redirect(ctx, redir_fd, redir_style, input);
3348 redir_fd = redirect_opt_num(dest);
3349 done_word(dest, ctx);
3350 redir_style = REDIRECT_INPUT;
3352 redir_style = REDIRECT_HEREIS;
3354 } else if (next == '>') {
3355 redir_style = REDIRECT_IO;
3357 } else if (next == '(') {
3358 syntax(); /* until we support <(list) Process Substitution */
3359 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3362 setup_redirect(ctx, redir_fd, redir_style, input);
3365 done_word(dest, ctx);
3366 done_pipe(ctx, PIPE_SEQ);
3369 done_word(dest, ctx);
3372 done_pipe(ctx, PIPE_AND);
3374 done_pipe(ctx, PIPE_BG);
3378 done_word(dest, ctx);
3381 done_pipe(ctx, PIPE_OR);
3383 /* we could pick up a file descriptor choice here
3384 * with redirect_opt_num(), but bash doesn't do it.
3385 * "echo foo 2| cat" yields "foo 2". */
3391 if (parse_group(dest, ctx, input, ch) != 0) {
3392 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3398 syntax(); /* Proper use of this character is caught by end_trigger */
3399 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3402 syntax(); /* this is really an internal logic error */
3403 debug_printf_parse("parse_stream return 1: internal logic error\n");
3407 /* Complain if quote? No, maybe we just finished a command substitution
3408 * that was quoted. Example:
3409 * $ echo "`cat foo` plus more"
3410 * and we just got the EOF generated by the subshell that ran "cat foo"
3411 * The only real complaint is if we got an EOF when end_trigger != NULL,
3412 * that is, we were really supposed to get end_trigger, and never got
3413 * one before the EOF. Can't use the standard "syntax error" return code,
3414 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3415 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3421 static void set_in_charmap(const char *set, int code)
3424 charmap[(unsigned char)*set++] = code;
3427 static void update_charmap(void)
3429 /* char *ifs and char charmap[256] are both globals. */
3430 ifs = getenv("IFS");
3433 /* Precompute a list of 'flow through' behavior so it can be treated
3434 * quickly up front. Computation is necessary because of IFS.
3435 * Special case handling of IFS == " \t\n" is not implemented.
3436 * The charmap[] array only really needs two bits each,
3437 * and on most machines that would be faster (reduced L1 cache use).
3439 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3440 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3441 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3442 set_in_charmap(ifs, CHAR_IFS); /* also flow through if quoted */
3445 /* most recursion does not come through here, the exception is
3446 * from builtin_source() */
3447 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3449 struct p_context ctx;
3450 o_string temp = NULL_O_STRING;
3453 ctx.parse_type = parse_flag;
3454 initialize_context(&ctx);
3456 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3457 set_in_charmap(";$&|", CHAR_ORDINARY);
3458 #if ENABLE_HUSH_INTERACTIVE
3459 inp->promptmode = 1;
3461 /* We will stop & execute after each ';' or '\n'.
3462 * Example: "sleep 9999; echo TEST" + ctrl-C:
3463 * TEST should be printed */
3464 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3465 if (rcode != 1 && ctx.old_flag != 0) {
3468 if (rcode != 1 && ctx.old_flag == 0) {
3469 done_word(&temp, &ctx);
3470 done_pipe(&ctx, PIPE_SEQ);
3471 debug_print_tree(ctx.list_head, 0);
3472 debug_printf_exec("parse_stream_outer: run_list\n");
3473 run_list(ctx.list_head);
3475 if (ctx.old_flag != 0) {
3482 free_pipe_list(ctx.list_head, 0);
3485 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3489 static int parse_string_outer(const char *s, int parse_flag)
3491 struct in_str input;
3492 setup_string_in_str(&input, s);
3493 return parse_stream_outer(&input, parse_flag);
3496 static int parse_file_outer(FILE *f)
3499 struct in_str input;
3500 setup_file_in_str(&input, f);
3501 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3506 /* Make sure we have a controlling tty. If we get started under a job
3507 * aware app (like bash for example), make sure we are now in charge so
3508 * we don't fight over who gets the foreground */
3509 static void setup_job_control(void)
3513 saved_task_pgrp = shell_pgrp = getpgrp();
3514 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3515 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3517 /* If we were ran as 'hush &',
3518 * sleep until we are in the foreground. */
3519 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3520 /* Send TTIN to ourself (should stop us) */
3521 kill(- shell_pgrp, SIGTTIN);
3522 shell_pgrp = getpgrp();
3525 /* Ignore job-control and misc signals. */
3526 set_jobctrl_sighandler(SIG_IGN);
3527 set_misc_sighandler(SIG_IGN);
3528 //huh? signal(SIGCHLD, SIG_IGN);
3530 /* We _must_ restore tty pgrp on fatal signals */
3531 set_fatal_sighandler(sigexit);
3533 /* Put ourselves in our own process group. */
3534 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3535 /* Grab control of the terminal. */
3536 tcsetpgrp(interactive_fd, getpid());
3540 int hush_main(int argc, char **argv);
3541 int hush_main(int argc, char **argv)
3547 #if ENABLE_FEATURE_EDITING
3548 line_input_state = new_line_input_t(FOR_SHELL);
3551 /* XXX what should these be while sourcing /etc/profile? */
3555 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3556 * hush_main(), therefore we cannot rely on the BSS to zero out this
3557 * stuff. Reset these to 0 every time. */
3559 /* charmap[] is taken care of with call to update_charmap() */
3561 close_me_head = NULL;
3562 #if ENABLE_HUSH_INTERACTIVE
3571 /* Initialize some more globals to non-zero values */
3573 #if ENABLE_HUSH_INTERACTIVE
3574 #if ENABLE_FEATURE_EDITING
3575 cmdedit_set_initial_prompt();
3581 /* initialize our shell local variables with the values
3582 * currently living in the environment */
3586 set_local_var(*e++, 2); /* without call putenv() */
3588 last_return_code = EXIT_SUCCESS;
3590 if (argv[0] && argv[0][0] == '-') {
3591 debug_printf("sourcing /etc/profile\n");
3592 input = fopen("/etc/profile", "r");
3593 if (input != NULL) {
3594 mark_open(fileno(input));
3595 parse_file_outer(input);
3596 mark_closed(fileno(input));
3602 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3605 global_argv = argv + optind;
3606 global_argc = argc - optind;
3607 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3610 /* Well, we cannot just declare interactiveness,
3611 * we have to have some stuff (ctty, etc) */
3612 /* interactive_fd++; */
3619 fprintf(stderr, "Usage: sh [FILE]...\n"
3620 " or: sh -c command [args]...\n\n");
3628 /* A shell is interactive if the '-i' flag was given, or if all of
3629 * the following conditions are met:
3631 * no arguments remaining or the -s flag given
3632 * standard input is a terminal
3633 * standard output is a terminal
3634 * Refer to Posix.2, the description of the 'sh' utility. */
3635 if (argv[optind] == NULL && input == stdin
3636 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3638 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3639 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3640 if (saved_tty_pgrp >= 0) {
3641 /* try to dup to high fd#, >= 255 */
3642 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3643 if (interactive_fd < 0) {
3644 /* try to dup to any fd */
3645 interactive_fd = dup(STDIN_FILENO);
3646 if (interactive_fd < 0)
3650 // TODO: track & disallow any attempts of user
3651 // to (inadvertently) close/redirect it
3654 debug_printf("interactive_fd=%d\n", interactive_fd);
3655 if (interactive_fd) {
3656 /* Looks like they want an interactive shell */
3657 setup_job_control();
3658 /* Make xfuncs do cleanup on exit */
3659 die_sleep = -1; /* flag */
3660 // FIXME: should we reset die_sleep = 0 whereever we fork?
3661 if (setjmp(die_jmp)) {
3662 /* xfunc has failed! die die die */
3663 hush_exit(xfunc_error_retval);
3665 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3666 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3667 printf("Enter 'help' for a list of built-in commands.\n\n");
3670 #elif ENABLE_HUSH_INTERACTIVE
3671 /* no job control compiled, only prompt/line editing */
3672 if (argv[optind] == NULL && input == stdin
3673 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3675 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3676 if (interactive_fd < 0) {
3677 /* try to dup to any fd */
3678 interactive_fd = dup(STDIN_FILENO);
3679 if (interactive_fd < 0)
3687 if (argv[optind] == NULL) {
3688 opt = parse_file_outer(stdin);
3692 debug_printf("\nrunning script '%s'\n", argv[optind]);
3693 global_argv = argv + optind;
3694 global_argc = argc - optind;
3695 input = xfopen(argv[optind], "r");
3696 opt = parse_file_outer(input);
3698 #if ENABLE_FEATURE_CLEAN_UP
3700 if (cwd != bb_msg_unknown)
3703 struct variables *cur, *tmp;
3704 for (cur = top_vars; cur; cur = tmp) {
3706 if (!cur->flg_read_only) {
3707 free((char*)cur->name);
3708 free((char*)cur->value);
3716 hush_exit(opt ? opt : last_return_code);