1 /* vi: set sw=4 ts=4: */
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen
26 * miscellaneous bugfixes from Matt Kraai
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy (improved --vda)
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change map[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
83 /* #include <dmalloc.h> */
86 /* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
88 #define debug_printf(...) do {} while (0)
89 /* Finer-grained debug switch */
90 #define debug_printf_jobs(...) do {} while (0)
91 #define debug_printf_exec(...) do {} while (0)
95 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
96 /* broken, of course, but OK for testing */
97 static const char *indenter(int i)
99 static const char blanks[] = " ";
100 return &blanks[sizeof(blanks) - i - 1];
103 #define final_printf debug_printf
105 #ifndef debug_printf_jobs
106 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
107 #define DEBUG_SHELL_JOBS 1
110 #ifndef debug_printf_exec
111 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
115 #if !ENABLE_HUSH_INTERACTIVE
116 #undef ENABLE_FEATURE_EDITING
117 #define ENABLE_FEATURE_EDITING 0
118 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
119 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
122 #define SPECIAL_VAR_SYMBOL 03
123 #define FLAG_EXIT_FROM_LOOP 1
124 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
125 #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
129 REDIRECT_OVERWRITE = 2,
135 /* The descrip member of this structure is only used to make debugging
137 static const struct {
139 signed char default_fd;
143 { O_RDONLY, 0, "<" },
144 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
145 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
146 { O_RDONLY, -1, "<<" },
157 /* might eventually control execution */
175 FLAG_END = (1 << RES_NONE ),
176 FLAG_IF = (1 << RES_IF ),
177 FLAG_THEN = (1 << RES_THEN ),
178 FLAG_ELIF = (1 << RES_ELIF ),
179 FLAG_ELSE = (1 << RES_ELSE ),
180 FLAG_FI = (1 << RES_FI ),
181 FLAG_FOR = (1 << RES_FOR ),
182 FLAG_WHILE = (1 << RES_WHILE),
183 FLAG_UNTIL = (1 << RES_UNTIL),
184 FLAG_DO = (1 << RES_DO ),
185 FLAG_DONE = (1 << RES_DONE ),
186 FLAG_IN = (1 << RES_IN ),
187 FLAG_START = (1 << RES_XXXX ),
190 /* This holds pointers to the various results of parsing */
192 struct child_prog *child;
193 struct pipe *list_head;
195 struct redir_struct *pending_redirect;
197 int old_flag; /* for figuring out valid reserved words */
198 struct p_context *stack;
199 int type; /* define type of parser : ";$" common or special symbol */
200 /* How about quoting status? */
203 struct redir_struct {
204 struct redir_struct *next; /* pointer to the next redirect in the list */
205 redir_type type; /* type of redirection */
206 int fd; /* file descriptor being redirected */
207 int dup; /* -1, or file descriptor being duplicated */
208 glob_t word; /* *word.gl_pathv is the filename */
212 pid_t pid; /* 0 if exited */
213 char **argv; /* program name and arguments */
214 struct pipe *group; /* if non-NULL, first in group or subshell */
215 int subshell; /* flag, non-zero if group must be forked */
216 struct redir_struct *redirects; /* I/O redirections */
217 glob_t glob_result; /* result of parameter globbing */
218 int is_stopped; /* is the program currently running? */
219 struct pipe *family; /* pointer back to the child's parent pipe */
220 int sp; /* number of SPECIAL_VAR_SYMBOL */
226 int num_progs; /* total number of programs in job */
227 int running_progs; /* number of programs running (not exited) */
228 char *cmdbuf; /* buffer various argv's point into */
230 int jobid; /* job number */
231 char *cmdtext; /* name of job */
232 pid_t pgrp; /* process group ID for the job */
234 struct child_prog *progs; /* array of commands in pipe */
235 int stopped_progs; /* number of programs alive, but stopped */
236 int job_context; /* bitmask defining current context */
237 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
238 reserved_style r_mode; /* supports if, for, while, until */
242 struct close_me *next;
247 struct variables *next;
254 /* globals, connect us to the outside world
255 * the first three support $?, $#, and $1 */
256 static char **global_argv;
257 static int global_argc;
258 static int last_return_code;
259 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
261 /* "globals" within this file */
262 static const char *ifs;
263 static unsigned char map[256];
264 static int fake_mode;
265 static struct close_me *close_me_head;
266 static const char *cwd;
267 static unsigned last_bg_pid;
268 #if !ENABLE_HUSH_INTERACTIVE
269 enum { interactive_fd = 0 };
271 /* 'interactive_fd' is a fd# open to ctty, if we have one
272 * _AND_ if we decided to mess with job control */
273 static int interactive_fd;
275 static pid_t saved_task_pgrp;
276 static pid_t saved_tty_pgrp;
277 static int last_jobid;
278 static struct pipe *job_list;
280 static const char *PS1;
281 static const char *PS2;
284 #define HUSH_VER_STR "0.02"
285 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
286 static struct variables *top_vars = &shell_ver;
298 #define NULL_O_STRING {NULL,0,0,0,0}
299 /* used for initialization:
300 o_string foo = NULL_O_STRING; */
302 /* I can almost use ordinary FILE *. Is open_memstream() universally
303 * available? Where is it documented? */
307 #if ENABLE_HUSH_INTERACTIVE
312 int (*get) (struct in_str *);
313 int (*peek) (struct in_str *);
315 #define b_getch(input) ((input)->get(input))
316 #define b_peek(input) ((input)->peek(input))
318 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
320 struct built_in_command {
321 const char *cmd; /* name */
322 const char *descr; /* description */
323 int (*function) (char **argv); /* function ptr */
326 static void __syntax(int line)
328 bb_error_msg("syntax error hush.c:%d", line);
330 #define syntax() __syntax(__LINE__)
332 /* Index of subroutines: */
333 /* function prototypes for builtins */
334 static int builtin_cd(char **argv);
335 static int builtin_env(char **argv);
336 static int builtin_eval(char **argv);
337 static int builtin_exec(char **argv);
338 static int builtin_exit(char **argv);
339 static int builtin_export(char **argv);
341 static int builtin_fg_bg(char **argv);
342 static int builtin_jobs(char **argv);
344 static int builtin_help(char **argv);
345 static int builtin_pwd(char **argv);
346 static int builtin_read(char **argv);
347 static int builtin_set(char **argv);
348 static int builtin_shift(char **argv);
349 static int builtin_source(char **argv);
350 static int builtin_umask(char **argv);
351 static int builtin_unset(char **argv);
352 static int builtin_not_written(char **argv);
353 /* o_string manipulation: */
354 static int b_check_space(o_string *o, int len);
355 static int b_addchr(o_string *o, int ch);
356 static void b_reset(o_string *o);
357 static int b_addqchr(o_string *o, int ch, int quote);
358 static int b_adduint(o_string *o, unsigned i);
359 /* in_str manipulations: */
360 static int static_get(struct in_str *i);
361 static int static_peek(struct in_str *i);
362 static int file_get(struct in_str *i);
363 static int file_peek(struct in_str *i);
364 static void setup_file_in_str(struct in_str *i, FILE *f);
365 static void setup_string_in_str(struct in_str *i, const char *s);
366 /* close_me manipulations: */
367 static void mark_open(int fd);
368 static void mark_closed(int fd);
369 static void close_all(void);
370 /* "run" the final data structures: */
371 static int free_pipe_list(struct pipe *head, int indent);
372 static int free_pipe(struct pipe *pi, int indent);
373 /* really run the final data structures: */
374 static int setup_redirects(struct child_prog *prog, int squirrel[]);
375 static int run_list_real(struct pipe *pi);
376 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
377 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
378 static int run_pipe_real(struct pipe *pi);
379 /* extended glob support: */
380 static int globhack(const char *src, int flags, glob_t *pglob);
381 static int glob_needed(const char *s);
382 static int xglob(o_string *dest, int flags, glob_t *pglob);
383 /* variable assignment: */
384 static int is_assignment(const char *s);
385 /* data structure manipulation: */
386 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
387 static void initialize_context(struct p_context *ctx);
388 static int done_word(o_string *dest, struct p_context *ctx);
389 static int done_command(struct p_context *ctx);
390 static int done_pipe(struct p_context *ctx, pipe_style type);
391 /* primary string parsing: */
392 static int redirect_dup_num(struct in_str *input);
393 static int redirect_opt_num(o_string *o);
394 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
395 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
396 static const char *lookup_param(const char *src);
397 static char *make_string(char **inp);
398 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
399 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
400 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
402 static int parse_stream_outer(struct in_str *inp, int flag);
403 static int parse_string_outer(const char *s, int flag);
404 static int parse_file_outer(FILE *f);
405 /* job management: */
406 static int checkjobs(struct pipe* fg_pipe);
408 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
409 static void insert_bg_job(struct pipe *pi);
410 static void remove_bg_job(struct pipe *pi);
411 static void delete_finished_bg_job(struct pipe *pi);
413 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
415 /* local variable support */
416 static char **make_list_in(char **inp, char *name);
417 static char *insert_var_value(char *inp);
418 static const char *get_local_var(const char *var);
419 static int set_local_var(const char *s, int flg_export);
420 static void unset_local_var(const char *name);
422 /* Table of built-in functions. They can be forked or not, depending on
423 * context: within pipes, they fork. As simple commands, they do not.
424 * When used in non-forking context, they can change global variables
425 * in the parent shell process. If forked, of course they cannot.
426 * For example, 'unset foo | whatever' will parse and run, but foo will
427 * still be set at the end. */
428 static const struct built_in_command bltins[] = {
430 { "bg", "Resume a job in the background", builtin_fg_bg },
432 { "break", "Exit for, while or until loop", builtin_not_written },
433 { "cd", "Change working directory", builtin_cd },
434 { "continue", "Continue for, while or until loop", builtin_not_written },
435 { "env", "Print all environment variables", builtin_env },
436 { "eval", "Construct and run shell command", builtin_eval },
437 { "exec", "Exec command, replacing this shell with the exec'd process",
439 { "exit", "Exit from shell()", builtin_exit },
440 { "export", "Set environment variable", builtin_export },
442 { "fg", "Bring job into the foreground", builtin_fg_bg },
443 { "jobs", "Lists the active jobs", builtin_jobs },
445 { "pwd", "Print current directory", builtin_pwd },
446 { "read", "Input environment variable", builtin_read },
447 { "return", "Return from a function", builtin_not_written },
448 { "set", "Set/unset shell local variables", builtin_set },
449 { "shift", "Shift positional parameters", builtin_shift },
450 { "trap", "Trap signals", builtin_not_written },
451 { "ulimit","Controls resource limits", builtin_not_written },
452 { "umask","Sets file creation mask", builtin_umask },
453 { "unset", "Unset environment variable", builtin_unset },
454 { ".", "Source-in and run commands in a file", builtin_source },
455 { "help", "List shell built-in commands", builtin_help },
461 #if ENABLE_FEATURE_SH_STANDALONE
463 static void signal_SA_RESTART(int sig, void (*handler)(int))
466 sa.sa_handler = handler;
467 sa.sa_flags = SA_RESTART;
468 sigemptyset(&sa.sa_mask);
469 sigaction(sig, &sa, NULL);
473 /* Signals are grouped, we handle them in batches */
474 static void set_fatal_sighandler(void (*handler)(int))
476 signal(SIGILL , handler);
477 signal(SIGTRAP, handler);
478 signal(SIGABRT, handler);
479 signal(SIGFPE , handler);
480 signal(SIGBUS , handler);
481 signal(SIGSEGV, handler);
482 /* bash 3.2 seems to handle these just like 'fatal' ones */
483 signal(SIGHUP , handler);
484 signal(SIGPIPE, handler);
485 signal(SIGALRM, handler);
487 static void set_jobctrl_sighandler(void (*handler)(int))
489 signal(SIGTSTP, handler);
490 signal(SIGTTIN, handler);
491 signal(SIGTTOU, handler);
493 static void set_misc_sighandler(void (*handler)(int))
495 signal(SIGINT , handler);
496 signal(SIGQUIT, handler);
497 signal(SIGTERM, handler);
499 /* SIGCHLD is special and handled separately */
501 #if ENABLE_FEATURE_SH_STANDALONE
502 static void set_every_sighandler(void (*handler)(int))
504 set_fatal_sighandler(handler);
505 set_jobctrl_sighandler(handler);
506 set_misc_sighandler(handler);
507 signal(SIGCHLD, handler);
510 static struct pipe *nofork_pipe;
511 struct nofork_save_area nofork_save;
512 static sigjmp_buf nofork_jb;
514 static void handler_ctrl_c(int sig)
516 debug_printf_jobs("got sig %d\n", sig);
517 // as usual we can have all kinds of nasty problems with leaked malloc data here
518 siglongjmp(nofork_jb, 1);
521 static void handler_ctrl_z(int sig)
525 debug_printf_jobs("got tty sig %d\n", sig);
527 if (pid < 0) /* can't fork. Pretend there were no Ctrl-Z */
529 debug_printf_jobs("bg'ing nofork\n");
530 nofork_save.saved = 0; /* flag the fact that Ctrl-Z was handled */
531 nofork_pipe->running_progs = 1;
532 nofork_pipe->stopped_progs = 0;
533 if (!pid) { /* child */
534 debug_printf_jobs("setting pgrp for child\n");
536 set_every_sighandler(SIG_DFL);
537 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
538 debug_printf_jobs("returning to child\n");
539 /* return to nofork, it will eventually exit now,
540 * not return back to shell */
544 /* finish filling up pipe info */
545 nofork_pipe->pgrp = pid; /* child is in its own pgrp */
546 nofork_pipe->progs[0].pid = pid;
547 nofork_pipe->running_progs = 1;
548 nofork_pipe->stopped_progs = 0;
549 /* parent needs to longjmp out of running nofork.
550 * we will "return" exitcode 0, with child put in background */
551 // as usual we can have all kinds of nasty problems with leaked malloc data here
552 siglongjmp(nofork_jb, 1);
557 /* Restores tty foreground process group, and exits.
558 * May be called as signal handler for fatal signal
559 * (will faithfully resend signal to itself, producing correct exit state)
560 * or called directly with -EXITCODE.
561 * We also call it if xfunc is exiting. */
562 static void sigexit(int sig) ATTRIBUTE_NORETURN;
563 static void sigexit(int sig)
567 /* Disable all signals: job control, SIGPIPE, etc. */
568 sigfillset(&block_all);
569 sigprocmask(SIG_SETMASK, &block_all, NULL);
572 tcsetpgrp(interactive_fd, saved_tty_pgrp);
574 /* Not a signal, just exit */
578 /* Enable only this sig and kill ourself with it */
579 signal(sig, SIG_DFL);
580 sigdelset(&block_all, sig);
581 sigprocmask(SIG_SETMASK, &block_all, NULL);
583 _exit(1); /* Should not reach it */
586 /* Restores tty foreground process group, and exits. */
587 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
588 static void hush_exit(int exitcode)
590 fflush(NULL); /* flush all streams */
591 sigexit(- (exitcode & 0xff));
596 #define set_fatal_sighandler(handler) ((void)0)
597 #define set_jobctrl_sighandler(handler) ((void)0)
598 #define set_misc_sighandler(handler) ((void)0)
599 #define hush_exit(e) exit(e)
604 static const char *set_cwd(void)
606 if (cwd == bb_msg_unknown)
607 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
608 cwd = xrealloc_getcwd_or_warn((char *)cwd);
610 cwd = bb_msg_unknown;
614 /* built-in 'eval' handler */
615 static int builtin_eval(char **argv)
618 int rcode = EXIT_SUCCESS;
621 str = make_string(argv + 1);
622 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
623 FLAG_PARSE_SEMICOLON);
625 rcode = last_return_code;
630 /* built-in 'cd <path>' handler */
631 static int builtin_cd(char **argv)
635 newdir = getenv("HOME");
639 printf("cd: %s: %s\n", newdir, strerror(errno));
646 /* built-in 'env' handler */
647 static int builtin_env(char **argv ATTRIBUTE_UNUSED)
649 /* TODO: call env applet's code instead */
659 /* built-in 'exec' handler */
660 static int builtin_exec(char **argv)
663 return EXIT_SUCCESS; /* Really? */
664 pseudo_exec_argv(argv + 1);
668 /* built-in 'exit' handler */
669 static int builtin_exit(char **argv)
671 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
672 //puts("exit"); /* bash does it */
675 hush_exit(last_return_code);
676 /* mimic bash: exit 123abc == exit 255 + error msg */
677 xfunc_error_retval = 255;
678 /* bash: exit -2 == exit 254, no error msg */
679 hush_exit(xatoi(argv[1]));
682 /* built-in 'export VAR=value' handler */
683 static int builtin_export(char **argv)
686 char *name = argv[1];
689 return builtin_env(argv);
695 const char *value = strchr(name, '=');
699 /* They are exporting something without an =VALUE */
701 value = get_local_var(name);
703 size_t ln = strlen(name);
705 tmp = realloc(name, ln+strlen(value)+2);
709 sprintf(tmp+ln, "=%s", value);
713 /* bash does not return an error when trying to export
714 * an undefined variable. Do likewise. */
720 bb_perror_msg("export");
722 res = set_local_var(name, 1);
730 /* built-in 'fg' and 'bg' handler */
731 static int builtin_fg_bg(char **argv)
738 /* If they gave us no args, assume they want the last backgrounded task */
740 for (pi = job_list; pi; pi = pi->next) {
741 if (pi->jobid == last_jobid) {
745 bb_error_msg("%s: no current job", argv[0]);
748 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
749 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
752 for (pi = job_list; pi; pi = pi->next) {
753 if (pi->jobid == jobnum) {
757 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
760 // TODO: bash prints a string representation
761 // of job being foregrounded (like "sleep 1 | cat")
762 if (*argv[0] == 'f') {
763 /* Put the job into the foreground. */
764 tcsetpgrp(interactive_fd, pi->pgrp);
767 /* Restart the processes in the job */
768 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
769 for (i = 0; i < pi->num_progs; i++) {
770 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
771 pi->progs[i].is_stopped = 0;
773 pi->stopped_progs = 0;
775 i = kill(- pi->pgrp, SIGCONT);
777 if (errno == ESRCH) {
778 delete_finished_bg_job(pi);
781 bb_perror_msg("kill (SIGCONT)");
785 if (*argv[0] == 'f') {
787 return checkjobs_and_fg_shell(pi);
793 /* built-in 'help' handler */
794 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
796 const struct built_in_command *x;
798 printf("\nBuilt-in commands:\n");
799 printf("-------------------\n");
800 for (x = bltins; x->cmd; x++) {
801 if (x->descr == NULL)
803 printf("%s\t%s\n", x->cmd, x->descr);
810 /* built-in 'jobs' handler */
811 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
814 const char *status_string;
816 for (job = job_list; job; job = job->next) {
817 if (job->running_progs == job->stopped_progs)
818 status_string = "Stopped";
820 status_string = "Running";
822 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
828 /* built-in 'pwd' handler */
829 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
835 /* built-in 'read VAR' handler */
836 static int builtin_read(char **argv)
844 string[0] = '\0'; /* In case stdin has only EOF */
846 fgets(string, sizeof(string), stdin);
848 var = malloc(strlen(argv[1]) + strlen(string) + 2);
850 sprintf(var, "%s=%s", argv[1], string);
851 res = set_local_var(var, 0);
855 bb_perror_msg("read");
856 free(var); /* So not move up to avoid breaking errno */
859 do res = getchar(); while (res != '\n' && res != EOF);
863 /* built-in 'set VAR=value' handler */
864 static int builtin_set(char **argv)
866 char *temp = argv[1];
870 for (e = top_vars; e; e = e->next)
871 printf("%s=%s\n", e->name, e->value);
873 set_local_var(temp, 0);
879 /* Built-in 'shift' handler */
880 static int builtin_shift(char **argv)
886 if (n >= 0 && n < global_argc) {
887 /* XXX This probably breaks $0 */
895 /* Built-in '.' handler (read-in and execute commands from file) */
896 static int builtin_source(char **argv)
904 /* XXX search through $PATH is missing */
905 input = fopen(argv[1], "r");
907 bb_error_msg("cannot open '%s'", argv[1]);
911 /* Now run the file */
912 /* XXX argv and argc are broken; need to save old global_argv
913 * (pointer only is OK!) on this stack frame,
914 * set global_argv=argv+1, recurse, and restore. */
915 mark_open(fileno(input));
916 status = parse_file_outer(input);
917 mark_closed(fileno(input));
922 static int builtin_umask(char **argv)
925 const char *arg = argv[1];
928 new_umask = strtoul(arg, &end, 8);
929 if (*end != '\0' || end == arg) {
933 new_umask = umask(0);
934 printf("%.3o\n", (unsigned) new_umask);
940 /* built-in 'unset VAR' handler */
941 static int builtin_unset(char **argv)
943 /* bash returned already true */
944 unset_local_var(argv[1]);
948 static int builtin_not_written(char **argv)
950 printf("builtin_%s not written\n", argv[0]);
954 static int b_check_space(o_string *o, int len)
956 /* It would be easy to drop a more restrictive policy
957 * in here, such as setting a maximum string length */
958 if (o->length + len > o->maxlen) {
959 char *old_data = o->data;
960 /* assert(data == NULL || o->maxlen != 0); */
961 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
962 o->data = realloc(o->data, 1 + o->maxlen);
963 if (o->data == NULL) {
967 return o->data == NULL;
970 static int b_addchr(o_string *o, int ch)
972 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
973 if (b_check_space(o, 1))
975 o->data[o->length] = ch;
977 o->data[o->length] = '\0';
981 static void b_reset(o_string *o)
989 static void b_free(o_string *o)
997 /* My analysis of quoting semantics tells me that state information
998 * is associated with a destination, not a source.
1000 static int b_addqchr(o_string *o, int ch, int quote)
1002 if (quote && strchr("*?[\\", ch)) {
1004 rc = b_addchr(o, '\\');
1008 return b_addchr(o, ch);
1011 static int b_adduint(o_string *o, unsigned i)
1014 char buf[sizeof(unsigned)*3 + 1];
1016 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1017 /* no escape checking necessary */
1018 do r = b_addchr(o, *p++); while (r == 0 && *p);
1022 static int static_get(struct in_str *i)
1025 if (ch == '\0') return EOF;
1029 static int static_peek(struct in_str *i)
1034 #if ENABLE_HUSH_INTERACTIVE
1035 static void cmdedit_set_initial_prompt(void)
1037 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1040 PS1 = getenv("PS1");
1046 static const char* setup_prompt_string(int promptmode)
1048 const char *prompt_str;
1049 debug_printf("setup_prompt_string %d ", promptmode);
1050 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1051 /* Set up the prompt */
1052 if (promptmode == 1) {
1055 ns = xmalloc(strlen(cwd)+4);
1056 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1063 prompt_str = (promptmode == 1) ? PS1 : PS2;
1065 debug_printf("result %s\n", prompt_str);
1070 #if ENABLE_FEATURE_EDITING
1071 static line_input_t *line_input_state;
1074 #if ENABLE_HUSH_INTERACTIVE
1075 static int get_user_input(struct in_str *i)
1077 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1080 const char *prompt_str;
1081 prompt_str = setup_prompt_string(i->promptmode);
1082 #if ENABLE_FEATURE_EDITING
1084 ** enable command line editing only while a command line
1085 ** is actually being read; otherwise, we'll end up bequeathing
1086 ** atexit() handlers and other unwanted stuff to our
1087 ** child processes (rob@sysgo.de)
1089 r = read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
1091 fputs(prompt_str, stdout);
1093 the_command[0] = r = fgetc(i->file);
1094 the_command[1] = '\0';
1098 return r; /* < 0 == EOF. Not meaningful otherwise */
1102 /* This is the magic location that prints prompts
1103 * and gets data back from the user */
1104 static int file_get(struct in_str *i)
1109 /* If there is data waiting, eat it up */
1110 if (i->p && *i->p) {
1113 /* need to double check i->file because we might be doing something
1114 * more complicated by now, like sourcing or substituting. */
1115 #if ENABLE_HUSH_INTERACTIVE
1116 if (interactive_fd && i->__promptme && i->file == stdin) {
1117 while (!i->p || !(interactive_fd && i->p[0])) {
1118 if (get_user_input(i) < 0)
1123 if (i->p && *i->p) {
1129 ch = fgetc(i->file);
1131 debug_printf("b_getch: got a %d\n", ch);
1133 #if ENABLE_HUSH_INTERACTIVE
1140 /* All the callers guarantee this routine will never be
1141 * used right after a newline, so prompting is not needed.
1143 static int file_peek(struct in_str *i)
1145 if (i->p && *i->p) {
1148 i->peek_buf[0] = fgetc(i->file);
1149 i->peek_buf[1] = '\0';
1151 debug_printf("b_peek: got a %d\n", *i->p);
1155 static void setup_file_in_str(struct in_str *i, FILE *f)
1157 i->peek = file_peek;
1159 #if ENABLE_HUSH_INTERACTIVE
1167 static void setup_string_in_str(struct in_str *i, const char *s)
1169 i->peek = static_peek;
1170 i->get = static_get;
1171 #if ENABLE_HUSH_INTERACTIVE
1178 static void mark_open(int fd)
1180 struct close_me *new = xmalloc(sizeof(struct close_me));
1182 new->next = close_me_head;
1183 close_me_head = new;
1186 static void mark_closed(int fd)
1188 struct close_me *tmp;
1189 if (close_me_head == NULL || close_me_head->fd != fd)
1190 bb_error_msg_and_die("corrupt close_me");
1191 tmp = close_me_head;
1192 close_me_head = close_me_head->next;
1196 static void close_all(void)
1199 for (c = close_me_head; c; c = c->next) {
1202 close_me_head = NULL;
1205 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1206 * and stderr if they are redirected. */
1207 static int setup_redirects(struct child_prog *prog, int squirrel[])
1210 struct redir_struct *redir;
1212 for (redir = prog->redirects; redir; redir = redir->next) {
1213 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1214 /* something went wrong in the parse. Pretend it didn't happen */
1217 if (redir->dup == -1) {
1218 mode = redir_table[redir->type].mode;
1219 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1221 /* this could get lost if stderr has been redirected, but
1222 bash and ash both lose it as well (though zsh doesn't!) */
1226 openfd = redir->dup;
1229 if (openfd != redir->fd) {
1230 if (squirrel && redir->fd < 3) {
1231 squirrel[redir->fd] = dup(redir->fd);
1236 dup2(openfd, redir->fd);
1237 if (redir->dup == -1)
1245 static void restore_redirects(int squirrel[])
1248 for (i = 0; i < 3; i++) {
1251 /* No error checking. I sure wouldn't know what
1252 * to do with an error if I found one! */
1260 /* XXX no exit() here. If you don't exec, use _exit instead.
1261 * The at_exit handlers apparently confuse the calling process,
1262 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1263 static void pseudo_exec_argv(char **argv)
1267 const struct built_in_command *x;
1269 for (i = 0; is_assignment(argv[i]); i++) {
1270 debug_printf("pid %d environment modification: %s\n",
1272 // FIXME: vfork case??
1273 p = insert_var_value(argv[i]);
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);
1287 * Check if the command matches any of the builtins.
1288 * Depending on context, this might be redundant. But it's
1289 * easier to waste a few CPU cycles than it is to figure out
1290 * if this is one of those cases.
1292 for (x = bltins; x->cmd; x++) {
1293 if (strcmp(argv[0], x->cmd) == 0) {
1294 debug_printf("builtin exec %s\n", argv[0]);
1295 rcode = x->function(argv);
1301 /* Check if the command matches any busybox internal commands
1303 * FIXME: This feature is not 100% safe, since
1304 * BusyBox is not fully reentrant, so we have no guarantee the things
1305 * from the .bss are still zeroed, or that things from .data are still
1306 * at their defaults. We could exec ourself from /proc/self/exe, but I
1307 * really dislike relying on /proc for things. We could exec ourself
1308 * from global_argv[0], but if we are in a chroot, we may not be able
1309 * to find ourself... */
1310 #if ENABLE_FEATURE_SH_STANDALONE
1311 debug_printf("running applet %s\n", argv[0]);
1312 run_applet_and_exit(argv[0], argv);
1313 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1314 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1316 debug_printf("exec of %s\n", argv[0]);
1317 execvp(argv[0], argv);
1318 bb_perror_msg("cannot exec '%s'", argv[0]);
1322 static void pseudo_exec(struct child_prog *child)
1327 pseudo_exec_argv(child->argv);
1331 // FIXME: do not modify globals! Think vfork!
1332 #if ENABLE_HUSH_INTERACTIVE
1333 interactive_fd = 0; /* crucial!!!! */
1335 debug_printf_exec("pseudo_exec: run_list_real\n");
1336 rcode = run_list_real(child->group);
1337 /* OK to leak memory by not calling free_pipe_list,
1338 * since this process is about to exit */
1342 /* Can happen. See what bash does with ">foo" by itself. */
1343 debug_printf("trying to pseudo_exec null command\n");
1344 _exit(EXIT_SUCCESS);
1348 static const char *get_cmdtext(struct pipe *pi)
1354 /* This is subtle. ->cmdtext is created only on first backgrounding.
1355 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1356 * On subsequent bg argv can be trashed, but we won't use it */
1359 argv = pi->progs[0].argv;
1360 if (!argv || !argv[0])
1361 return (pi->cmdtext = xzalloc(1));
1364 do len += strlen(*argv) + 1; while (*++argv);
1365 pi->cmdtext = p = xmalloc(len);
1366 argv = pi->progs[0].argv;
1368 len = strlen(*argv);
1369 memcpy(p, *argv, len);
1379 static void insert_bg_job(struct pipe *pi)
1381 struct pipe *thejob;
1383 /* Linear search for the ID of the job to use */
1385 for (thejob = job_list; thejob; thejob = thejob->next)
1386 if (thejob->jobid >= pi->jobid)
1387 pi->jobid = thejob->jobid + 1;
1389 /* add thejob to the list of running jobs */
1391 thejob = job_list = xmalloc(sizeof(*thejob));
1393 for (thejob = job_list; thejob->next; thejob = thejob->next)
1395 thejob->next = xmalloc(sizeof(*thejob));
1396 thejob = thejob->next;
1399 /* physically copy the struct job */
1400 memcpy(thejob, pi, sizeof(struct pipe));
1401 thejob->progs = xmalloc(sizeof(pi->progs[0]) * pi->num_progs);
1402 memcpy(thejob->progs, pi->progs, sizeof(pi->progs[0]) * pi->num_progs);
1403 thejob->next = NULL;
1404 /*seems to be wrong:*/
1405 /*thejob->running_progs = thejob->num_progs;*/
1406 /*thejob->stopped_progs = 0;*/
1407 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1409 /* we don't wait for background thejobs to return -- append it
1410 to the list of backgrounded thejobs and leave it alone */
1411 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1412 last_bg_pid = thejob->progs[0].pid;
1413 last_jobid = thejob->jobid;
1416 static void remove_bg_job(struct pipe *pi)
1418 struct pipe *prev_pipe;
1420 if (pi == job_list) {
1421 job_list = pi->next;
1423 prev_pipe = job_list;
1424 while (prev_pipe->next != pi)
1425 prev_pipe = prev_pipe->next;
1426 prev_pipe->next = pi->next;
1429 last_jobid = job_list->jobid;
1434 /* remove a backgrounded job */
1435 static void delete_finished_bg_job(struct pipe *pi)
1438 pi->stopped_progs = 0;
1444 /* Checks to see if any processes have exited -- if they
1445 have, figure out why and see if a job has completed */
1446 static int checkjobs(struct pipe* fg_pipe)
1457 attributes = WUNTRACED;
1458 if (fg_pipe == NULL) {
1459 attributes |= WNOHANG;
1462 /* Do we do this right?
1463 * bash-3.00# sleep 20 | false
1465 * [3]+ Stopped sleep 20 | false
1466 * bash-3.00# echo $?
1467 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1470 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1471 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1472 // + killall -STOP cat
1475 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1476 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1478 #ifdef DEBUG_SHELL_JOBS
1479 if (WIFSTOPPED(status))
1480 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1481 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1482 if (WIFSIGNALED(status))
1483 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1484 childpid, WTERMSIG(status), WEXITSTATUS(status));
1485 if (WIFEXITED(status))
1486 debug_printf_jobs("pid %d exited, exitcode %d\n",
1487 childpid, WEXITSTATUS(status));
1489 /* Were we asked to wait for fg pipe? */
1492 for (i = 0; i < fg_pipe->num_progs; i++) {
1493 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1494 if (fg_pipe->progs[i].pid == childpid) {
1495 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1497 fg_pipe->progs[i].pid = 0;
1498 fg_pipe->running_progs--;
1499 if (i == fg_pipe->num_progs-1)
1500 /* last process gives overall exitstatus */
1501 rcode = WEXITSTATUS(status);
1503 fg_pipe->progs[i].is_stopped = 1;
1504 fg_pipe->stopped_progs++;
1506 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1507 fg_pipe->running_progs, fg_pipe->stopped_progs);
1508 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1509 /* All processes in fg pipe have exited/stopped */
1511 if (fg_pipe->running_progs)
1512 insert_bg_job(fg_pipe);
1516 /* There are still running processes in the fg pipe */
1520 /* fall through to searching process in bg pipes */
1524 /* We asked to wait for bg or orphaned children */
1525 /* No need to remember exitcode in this case */
1526 for (pi = job_list; pi; pi = pi->next) {
1528 while (prognum < pi->num_progs) {
1529 if (pi->progs[prognum].pid == childpid)
1530 goto found_pi_and_prognum;
1536 /* Happens when shell is used as init process (init=/bin/sh) */
1537 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1541 found_pi_and_prognum:
1544 pi->progs[prognum].pid = 0;
1545 pi->running_progs--;
1546 if (!pi->running_progs) {
1547 printf(JOB_STATUS_FORMAT, pi->jobid,
1548 "Done", pi->cmdtext);
1549 delete_finished_bg_job(pi);
1553 pi->stopped_progs++;
1554 pi->progs[prognum].is_stopped = 1;
1559 /* wait found no children or failed */
1561 if (childpid && errno != ECHILD)
1562 bb_perror_msg("waitpid");
1564 /* move the shell to the foreground */
1565 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1566 // bb_perror_msg("tcsetpgrp-2");
1571 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1574 int rcode = checkjobs(fg_pipe);
1575 /* Job finished, move the shell to the foreground */
1577 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1578 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1579 bb_perror_msg("tcsetpgrp-4a");
1584 #if ENABLE_FEATURE_SH_STANDALONE
1585 /* run_pipe_real's helper */
1586 static int run_single_fg_nofork(struct pipe *pi, const struct bb_applet *a,
1591 /* TSTP handler will store pid etc in pi */
1593 save_nofork_data(&nofork_save);
1594 if (sigsetjmp(nofork_jb, 1) == 0) {
1595 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1596 signal(SIGINT, handler_ctrl_c);
1597 rcode = run_nofork_applet_prime(&nofork_save, a, argv);
1598 if (--nofork_save.saved != 0) {
1599 /* Ctrl-Z forked, we are child */
1604 /* Ctrl-Z forked, we are parent; or Ctrl-C.
1605 * Sighandler has longjmped us here */
1606 signal(SIGINT, SIG_IGN);
1607 signal(SIGTSTP, SIG_IGN);
1608 debug_printf_jobs("Exiting nofork early\n");
1609 restore_nofork_data(&nofork_save);
1610 if (nofork_save.saved == 0) /* Ctrl-Z, not Ctrl-C */
1613 putchar('\n'); /* bash does this on Ctrl-C */
1616 return run_nofork_applet(a, argv);
1621 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1622 * to finish. See checkjobs().
1624 * return code is normally -1, when the caller has to wait for children
1625 * to finish to determine the exit status of the pipe. If the pipe
1626 * is a simple builtin command, however, the action is done by the
1627 * time run_pipe_real returns, and the exit code is provided as the
1630 * The input of the pipe is always stdin, the output is always
1631 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1632 * because it tries to avoid running the command substitution in
1633 * subshell, when that is in fact necessary. The subshell process
1634 * now has its stdout directed to the input of the appropriate pipe,
1635 * so this routine is noticeably simpler.
1637 static int run_pipe_real(struct pipe *pi)
1640 int nextin, nextout;
1641 int pipefds[2]; /* pipefds[0] is for reading */
1642 struct child_prog *child;
1643 const struct built_in_command *x;
1645 /* it is not always needed, but we aim to smaller code */
1646 int squirrel[] = { -1, -1, -1 };
1648 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1650 debug_printf_exec("run_pipe_real start:\n");
1656 pi->running_progs = 0;
1657 pi->stopped_progs = 0;
1659 /* Check if this is a simple builtin (not part of a pipe).
1660 * Builtins within pipes have to fork anyway, and are handled in
1661 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1663 child = &(pi->progs[0]);
1664 if (single_fg && child->group && child->subshell == 0) {
1665 debug_printf("non-subshell grouping\n");
1666 setup_redirects(child, squirrel);
1667 /* XXX could we merge code with following builtin case,
1668 * by creating a pseudo builtin that calls run_list_real? */
1669 debug_printf_exec(": run_list_real\n");
1670 rcode = run_list_real(child->group);
1671 restore_redirects(squirrel);
1672 debug_printf_exec("run_pipe_real return %d\n", rcode);
1676 if (single_fg && child->argv != NULL) {
1677 char **argv = child->argv;
1679 for (i = 0; is_assignment(argv[i]); i++)
1681 if (i != 0 && argv[i] == NULL) {
1682 /* assignments, but no command: set the local environment */
1683 for (i = 0; argv[i] != NULL; i++) {
1684 /* Ok, this case is tricky. We have to decide if this is a
1685 * local variable, or an already exported variable. If it is
1686 * already exported, we have to export the new value. If it is
1687 * not exported, we need only set this as a local variable.
1688 * This junk is all to decide whether or not to export this
1692 name = xstrdup(argv[i]);
1693 debug_printf("Local environment set: %s\n", name);
1694 value = strchr(name, '=');
1697 if (get_local_var(name)) {
1701 p = insert_var_value(argv[i]);
1702 set_local_var(p, export_me);
1706 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1708 for (i = 0; is_assignment(argv[i]); i++) {
1709 p = insert_var_value(argv[i]);
1719 str = make_string(argv + i);
1720 debug_printf_exec(": parse_string_outer '%s'\n", str);
1721 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1723 debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1724 return last_return_code;
1726 for (x = bltins; x->cmd; x++) {
1727 if (strcmp(argv[i], x->cmd) == 0) {
1728 if (x->function == builtin_exec && argv[i+1] == NULL) {
1729 debug_printf("magic exec\n");
1730 setup_redirects(child, NULL);
1731 return EXIT_SUCCESS;
1733 debug_printf("builtin inline %s\n", argv[0]);
1734 /* XXX setup_redirects acts on file descriptors, not FILEs.
1735 * This is perfect for work that comes after exec().
1736 * Is it really safe for inline use? Experimentally,
1737 * things seem to work with glibc. */
1738 // TODO: fflush(NULL)?
1739 setup_redirects(child, squirrel);
1740 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1741 rcode = x->function(argv + i);
1742 restore_redirects(squirrel);
1743 debug_printf_exec("run_pipe_real return %d\n", rcode);
1747 #if ENABLE_FEATURE_SH_STANDALONE
1749 const struct bb_applet *a = find_applet_by_name(argv[i]);
1750 if (a && a->nofork) {
1751 setup_redirects(child, squirrel);
1752 debug_printf_exec(": run_single_fg_nofork '%s' '%s'...\n", argv[i], argv[i+1]);
1753 rcode = run_single_fg_nofork(pi, a, argv + i);
1754 restore_redirects(squirrel);
1755 debug_printf_exec("run_pipe_real return %d\n", rcode);
1762 /* Going to fork a child per each pipe member */
1764 /* Disable job control signals for shell (parent) and
1765 * for initial child code after fork */
1766 set_jobctrl_sighandler(SIG_IGN);
1768 for (i = 0; i < pi->num_progs; i++) {
1769 child = &(pi->progs[i]);
1770 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1772 /* pipes are inserted between pairs of commands */
1773 if ((i + 1) < pi->num_progs) {
1774 if (pipe(pipefds) < 0)
1775 bb_perror_msg_and_die("pipe");
1776 nextout = pipefds[1];
1782 /* XXX test for failed fork()? */
1784 child->pid = fork();
1786 child->pid = vfork();
1788 if (!child->pid) { /* child */
1789 /* Every child adds itself to new process group
1790 * with pgid == pid of first child in pipe */
1792 if (interactive_fd) {
1793 /* Don't do pgrp restore anymore on fatal signals */
1794 set_fatal_sighandler(SIG_DFL);
1795 if (pi->pgrp < 0) /* true for 1st process only */
1796 pi->pgrp = getpid();
1797 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1798 /* We do it in *every* child, not just first,
1800 tcsetpgrp(interactive_fd, pi->pgrp);
1804 // in non-interactive case fatal sigs are already SIG_DFL
1814 if (pipefds[0] != -1) {
1815 close(pipefds[0]); /* opposite end of our output pipe */
1817 /* Like bash, explicit redirects override pipes,
1818 * and the pipe fd is available for dup'ing. */
1819 setup_redirects(child, NULL);
1821 /* Restore default handlers just prior to exec */
1822 set_jobctrl_sighandler(SIG_DFL);
1823 set_misc_sighandler(SIG_DFL);
1824 signal(SIGCHLD, SIG_DFL);
1828 pi->running_progs++;
1831 /* Second and next children need to know pid of first one */
1833 pi->pgrp = child->pid;
1836 /* Don't check for errors. The child may be dead already,
1837 * in which case setpgid returns error code EACCES. */
1838 //why we do it at all?? child does it itself
1839 //if (interactive_fd)
1840 // setpgid(child->pid, pi->pgrp);
1847 /* If there isn't another process, nextin is garbage
1848 but it doesn't matter */
1849 nextin = pipefds[0];
1851 debug_printf_exec("run_pipe_real return -1\n");
1855 static int run_list_real(struct pipe *pi)
1857 char *save_name = NULL;
1859 char **save_list = NULL;
1863 int rcode = 0, flag_skip = 1;
1864 int flag_restore = 0;
1865 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1866 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1868 debug_printf_exec("run_list_real start:\n");
1870 /* check syntax for "for" */
1871 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1872 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1873 && (rpipe->next == NULL)
1876 debug_printf_exec("run_list_real return 1\n");
1879 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1880 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1883 debug_printf_exec("run_list_real return 1\n");
1887 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1888 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1889 || pi->r_mode == RES_FOR
1898 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1899 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1900 if (rmode == skip_more_in_this_rmode && flag_skip) {
1901 if (pi->followup == PIPE_SEQ)
1906 skip_more_in_this_rmode = RES_XXXX;
1907 if (rmode == RES_THEN || rmode == RES_ELSE)
1908 if_code = next_if_code;
1909 if (rmode == RES_THEN && if_code)
1911 if (rmode == RES_ELSE && !if_code)
1913 if (rmode == RES_ELIF && !if_code)
1915 if (rmode == RES_FOR && pi->num_progs) {
1917 /* if no variable values after "in" we skip "for" */
1918 if (!pi->next->progs->argv)
1920 /* create list of variable values */
1921 list = make_list_in(pi->next->progs->argv,
1922 pi->progs->argv[0]);
1924 save_name = pi->progs->argv[0];
1925 pi->progs->argv[0] = NULL;
1929 free(pi->progs->argv[0]);
1933 pi->progs->argv[0] = save_name;
1934 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1937 /* insert new value from list for variable */
1938 if (pi->progs->argv[0])
1939 free(pi->progs->argv[0]);
1940 pi->progs->argv[0] = *list++;
1941 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1943 if (rmode == RES_IN)
1945 if (rmode == RES_DO) {
1949 if (rmode == RES_DONE) {
1956 if (pi->num_progs == 0)
1958 save_num_progs = pi->num_progs; /* save number of programs */
1959 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
1960 rcode = run_pipe_real(pi);
1962 /* We only ran a builtin: rcode was set by the return value
1963 * of run_pipe_real(), and we don't need to wait for anything. */
1964 } else if (pi->followup == PIPE_BG) {
1965 /* XXX check bash's behavior with nontrivial pipes */
1966 /* XXX compute jobid */
1967 /* XXX what does bash do with attempts to background builtins? */
1971 rcode = EXIT_SUCCESS;
1974 if (interactive_fd) {
1975 rcode = checkjobs_and_fg_shell(pi);
1979 rcode = checkjobs(pi);
1981 debug_printf("checkjobs returned %d\n", rcode);
1983 last_return_code = rcode;
1984 pi->num_progs = save_num_progs; /* restore number of programs */
1985 if (rmode == RES_IF || rmode == RES_ELIF)
1986 next_if_code = rcode; /* can be overwritten a number of times */
1987 if (rmode == RES_WHILE)
1988 flag_rep = !last_return_code;
1989 if (rmode == RES_UNTIL)
1990 flag_rep = last_return_code;
1991 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1992 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1994 skip_more_in_this_rmode = rmode;
1998 debug_printf_exec("run_list_real return %d\n", rcode);
2002 /* return code is the exit status of the pipe */
2003 static int free_pipe(struct pipe *pi, int indent)
2006 struct child_prog *child;
2007 struct redir_struct *r, *rnext;
2008 int a, i, ret_code = 0;
2010 if (pi->stopped_progs > 0)
2012 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2013 for (i = 0; i < pi->num_progs; i++) {
2014 child = &pi->progs[i];
2015 final_printf("%s command %d:\n", indenter(indent), i);
2017 for (a = 0, p = child->argv; *p; a++, p++) {
2018 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
2020 globfree(&child->glob_result);
2022 } else if (child->group) {
2023 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2024 ret_code = free_pipe_list(child->group, indent+3);
2025 final_printf("%s end group\n", indenter(indent));
2027 final_printf("%s (nil)\n", indenter(indent));
2029 for (r = child->redirects; r; r = rnext) {
2030 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2032 /* guard against the case >$FOO, where foo is unset or blank */
2033 if (r->word.gl_pathv) {
2034 final_printf(" %s\n", *r->word.gl_pathv);
2038 final_printf("&%d\n", r->dup);
2043 child->redirects = NULL;
2045 free(pi->progs); /* children are an array, they get freed all at once */
2054 static int free_pipe_list(struct pipe *head, int indent)
2056 int rcode = 0; /* if list has no members */
2057 struct pipe *pi, *next;
2058 for (pi = head; pi; pi = next) {
2059 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2060 rcode = free_pipe(pi, indent);
2061 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
2063 /*pi->next = NULL;*/
2069 /* Select which version we will use */
2070 static int run_list(struct pipe *pi)
2073 if (fake_mode == 0) {
2074 debug_printf_exec("run_list: run_list_real with %d members\n", pi->num_progs);
2075 rcode = run_list_real(pi);
2077 /* free_pipe_list has the side effect of clearing memory
2078 * In the long run that function can be merged with run_list_real,
2079 * but doing that now would hobble the debugging effort. */
2080 free_pipe_list(pi,0);
2084 /* The API for glob is arguably broken. This routine pushes a non-matching
2085 * string into the output structure, removing non-backslashed backslashes.
2086 * If someone can prove me wrong, by performing this function within the
2087 * original glob(3) api, feel free to rewrite this routine into oblivion.
2088 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2089 * XXX broken if the last character is '\\', check that before calling.
2091 static int globhack(const char *src, int flags, glob_t *pglob)
2096 for (cnt = 1, s = src; s && *s; s++) {
2097 if (*s == '\\') s++;
2102 return GLOB_NOSPACE;
2103 if (!(flags & GLOB_APPEND)) {
2104 pglob->gl_pathv = NULL;
2105 pglob->gl_pathc = 0;
2109 pathc = ++pglob->gl_pathc;
2110 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
2111 if (pglob->gl_pathv == NULL)
2112 return GLOB_NOSPACE;
2113 pglob->gl_pathv[pathc-1] = dest;
2114 pglob->gl_pathv[pathc] = NULL;
2115 for (s = src; s && *s; s++, dest++) {
2116 if (*s == '\\') s++;
2123 /* XXX broken if the last character is '\\', check that before calling */
2124 static int glob_needed(const char *s)
2127 if (*s == '\\') s++;
2128 if (strchr("*[?", *s)) return 1;
2133 static int xglob(o_string *dest, int flags, glob_t *pglob)
2137 /* short-circuit for null word */
2138 /* we can code this better when the debug_printf's are gone */
2139 if (dest->length == 0) {
2140 if (dest->nonnull) {
2141 /* bash man page calls this an "explicit" null */
2142 gr = globhack(dest->data, flags, pglob);
2143 debug_printf("globhack returned %d\n", gr);
2147 } else if (glob_needed(dest->data)) {
2148 gr = glob(dest->data, flags, NULL, pglob);
2149 debug_printf("glob returned %d\n", gr);
2150 if (gr == GLOB_NOMATCH) {
2151 /* quote removal, or more accurately, backslash removal */
2152 gr = globhack(dest->data, flags, pglob);
2153 debug_printf("globhack returned %d\n", gr);
2156 gr = globhack(dest->data, flags, pglob);
2157 debug_printf("globhack returned %d\n", gr);
2159 if (gr == GLOB_NOSPACE)
2160 bb_error_msg_and_die("out of memory during glob");
2161 if (gr != 0) { /* GLOB_ABORTED ? */
2162 bb_error_msg("glob(3) error %d", gr);
2164 /* globprint(glob_target); */
2168 static char **make_list_in(char **inp, char *name)
2171 int name_len = strlen(name);
2176 /* create list of variable values */
2177 list = xmalloc(sizeof(*list));
2178 for (i = 0; inp[i]; i++) {
2179 p3 = insert_var_value(inp[i]);
2186 p2 = strchr(p1, ' ');
2193 /* we use n + 2 in realloc for list, because we add
2194 * new element and then we will add NULL element */
2195 list = xrealloc(list, sizeof(*list) * (n + 2));
2196 list[n] = xmalloc(2 + name_len + len);
2197 strcpy(list[n], name);
2198 strcat(list[n], "=");
2199 strncat(list[n], p1, len);
2200 list[n++][name_len + len + 1] = '\0';
2203 if (p3 != inp[i]) free(p3);
2209 static char *insert_var_value(char *inp)
2211 int res_str_len = 0;
2214 char *p, *res_str = NULL;
2217 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2220 res_str = xrealloc(res_str, (res_str_len + len));
2221 strncpy((res_str + res_str_len), inp, len);
2225 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2227 p1 = lookup_param(inp);
2229 len = res_str_len + strlen(p1);
2230 res_str = xrealloc(res_str, (1 + len));
2231 strcpy((res_str + res_str_len), p1);
2234 *p = SPECIAL_VAR_SYMBOL;
2239 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2240 strcpy((res_str + res_str_len), inp);
2241 while ((p = strchr(res_str, '\n'))) {
2245 return (res_str == NULL) ? inp : res_str;
2248 /* This is used to get/check local shell variables */
2249 static const char *get_local_var(const char *s)
2251 struct variables *cur;
2255 for (cur = top_vars; cur; cur = cur->next)
2256 if (strcmp(cur->name, s) == 0)
2261 /* This is used to set local shell variables
2262 flg_export == 0 if only local (not exporting) variable
2263 flg_export == 1 if "new" exporting environ
2264 flg_export > 1 if current startup environ (not call putenv()) */
2265 static int set_local_var(const char *s, int flg_export)
2269 struct variables *cur;
2273 /* Assume when we enter this function that we are already in
2274 * NAME=VALUE format. So the first order of business is to
2275 * split 's' on the '=' into 'name' and 'value' */
2276 value = strchr(name, '=');
2277 /*if (value == 0 && ++value == 0) ??? -vda */
2278 if (value == NULL || value[1] == '\0') {
2284 for (cur = top_vars; cur; cur = cur->next) {
2285 if (strcmp(cur->name, name) == 0)
2290 if (strcmp(cur->value, value) == 0) {
2291 if (flg_export > 0 && cur->flg_export == 0)
2292 cur->flg_export = flg_export;
2295 } else if (cur->flg_read_only) {
2296 bb_error_msg("%s: readonly variable", name);
2299 if (flg_export > 0 || cur->flg_export > 1)
2300 cur->flg_export = 1;
2301 free((char*)cur->value);
2303 cur->value = strdup(value);
2306 cur = malloc(sizeof(struct variables));
2310 cur->name = strdup(name);
2315 struct variables *bottom = top_vars;
2316 cur->value = strdup(value);
2318 cur->flg_export = flg_export;
2319 cur->flg_read_only = 0;
2320 while (bottom->next)
2321 bottom = bottom->next;
2327 if (result == 0 && cur->flg_export == 1) {
2329 result = putenv(name);
2332 if (result > 0) /* equivalent to previous set */
2338 static void unset_local_var(const char *name)
2340 struct variables *cur, *next;
2344 for (cur = top_vars; cur; cur = cur->next) {
2345 if (strcmp(cur->name, name) == 0) {
2346 if (cur->flg_read_only) {
2347 bb_error_msg("%s: readonly variable", name);
2350 if (cur->flg_export)
2351 unsetenv(cur->name);
2352 free((char*)cur->name);
2353 free((char*)cur->value);
2355 while (next->next != cur)
2357 next->next = cur->next;
2364 static int is_assignment(const char *s)
2366 if (!s || !isalpha(*s))
2369 while (isalnum(*s) || *s == '_')
2374 /* the src parameter allows us to peek forward to a possible &n syntax
2375 * for file descriptor duplication, e.g., "2>&1".
2376 * Return code is 0 normally, 1 if a syntax error is detected in src.
2377 * Resource errors (in xmalloc) cause the process to exit */
2378 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2379 struct in_str *input)
2381 struct child_prog *child = ctx->child;
2382 struct redir_struct *redir = child->redirects;
2383 struct redir_struct *last_redir = NULL;
2385 /* Create a new redir_struct and drop it onto the end of the linked list */
2388 redir = redir->next;
2390 redir = xmalloc(sizeof(struct redir_struct));
2392 redir->word.gl_pathv = NULL;
2394 last_redir->next = redir;
2396 child->redirects = redir;
2399 redir->type = style;
2400 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2402 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2404 /* Check for a '2>&1' type redirect */
2405 redir->dup = redirect_dup_num(input);
2406 if (redir->dup == -2) return 1; /* syntax error */
2407 if (redir->dup != -1) {
2408 /* Erik had a check here that the file descriptor in question
2409 * is legit; I postpone that to "run time"
2410 * A "-" representation of "close me" shows up as a -3 here */
2411 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2413 /* We do _not_ try to open the file that src points to,
2414 * since we need to return and let src be expanded first.
2415 * Set ctx->pending_redirect, so we know what to do at the
2416 * end of the next parsed word.
2418 ctx->pending_redirect = redir;
2423 static struct pipe *new_pipe(void)
2426 pi = xzalloc(sizeof(struct pipe));
2427 /*pi->num_progs = 0;*/
2428 /*pi->progs = NULL;*/
2429 /*pi->next = NULL;*/
2430 /*pi->followup = 0; invalid */
2432 pi->r_mode = RES_NONE;
2436 static void initialize_context(struct p_context *ctx)
2439 ctx->pending_redirect = NULL;
2441 ctx->list_head = new_pipe();
2442 ctx->pipe = ctx->list_head;
2446 done_command(ctx); /* creates the memory for working child */
2449 /* normal return is 0
2450 * if a reserved word is found, and processed, return 1
2451 * should handle if, then, elif, else, fi, for, while, until, do, done.
2452 * case, function, and select are obnoxious, save those for later.
2454 static int reserved_word(o_string *dest, struct p_context *ctx)
2456 struct reserved_combo {
2461 /* Mostly a list of accepted follow-up reserved words.
2462 * FLAG_END means we are done with the sequence, and are ready
2463 * to turn the compound list into a command.
2464 * FLAG_START means the word must start a new compound list.
2466 static const struct reserved_combo reserved_list[] = {
2467 { "if", RES_IF, FLAG_THEN | FLAG_START },
2468 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2469 { "elif", RES_ELIF, FLAG_THEN },
2470 { "else", RES_ELSE, FLAG_FI },
2471 { "fi", RES_FI, FLAG_END },
2472 { "for", RES_FOR, FLAG_IN | FLAG_START },
2473 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2474 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2475 { "in", RES_IN, FLAG_DO },
2476 { "do", RES_DO, FLAG_DONE },
2477 { "done", RES_DONE, FLAG_END }
2479 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2480 const struct reserved_combo *r;
2482 for (r = reserved_list; r < reserved_list+NRES; r++) {
2483 if (strcmp(dest->data, r->literal) == 0) {
2484 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2485 if (r->flag & FLAG_START) {
2486 struct p_context *new = xmalloc(sizeof(struct p_context));
2487 debug_printf("push stack\n");
2488 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2495 *new = *ctx; /* physical copy */
2496 initialize_context(ctx);
2498 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2505 ctx->old_flag = r->flag;
2506 if (ctx->old_flag & FLAG_END) {
2507 struct p_context *old;
2508 debug_printf("pop stack\n");
2509 done_pipe(ctx, PIPE_SEQ);
2511 old->child->group = ctx->list_head;
2512 old->child->subshell = 0;
2513 *ctx = *old; /* physical copy */
2523 /* normal return is 0.
2524 * Syntax or xglob errors return 1. */
2525 static int done_word(o_string *dest, struct p_context *ctx)
2527 struct child_prog *child = ctx->child;
2528 glob_t *glob_target;
2531 debug_printf("done_word: %s %p\n", dest->data, child);
2532 if (dest->length == 0 && !dest->nonnull) {
2533 debug_printf(" true null, ignored\n");
2536 if (ctx->pending_redirect) {
2537 glob_target = &ctx->pending_redirect->word;
2541 return 1; /* syntax error, groups and arglists don't mix */
2543 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2544 debug_printf("checking %s for reserved-ness\n", dest->data);
2545 if (reserved_word(dest, ctx))
2546 return (ctx->w == RES_SNTX);
2548 glob_target = &child->glob_result;
2549 if (child->argv) flags |= GLOB_APPEND;
2551 gr = xglob(dest, flags, glob_target);
2552 if (gr != 0) return 1;
2555 if (ctx->pending_redirect) {
2556 ctx->pending_redirect = NULL;
2557 if (glob_target->gl_pathc != 1) {
2558 bb_error_msg("ambiguous redirect");
2562 child->argv = glob_target->gl_pathv;
2564 if (ctx->w == RES_FOR) {
2565 done_word(dest, ctx);
2566 done_pipe(ctx, PIPE_SEQ);
2571 /* The only possible error here is out of memory, in which case
2573 static int done_command(struct p_context *ctx)
2575 /* The child is really already in the pipe structure, so
2576 * advance the pipe counter and make a new, null child.
2577 * Only real trickiness here is that the uncommitted
2578 * child structure, to which ctx->child points, is not
2579 * counted in pi->num_progs. */
2580 struct pipe *pi = ctx->pipe;
2581 struct child_prog *prog = ctx->child;
2583 if (prog && prog->group == NULL
2584 && prog->argv == NULL
2585 && prog->redirects == NULL
2587 debug_printf("done_command: skipping null command\n");
2592 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2594 debug_printf("done_command: initializing\n");
2596 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2598 prog = pi->progs + pi->num_progs;
2599 memset(prog, 0, sizeof(*prog));
2600 /*prog->redirects = NULL;*/
2601 /*prog->argv = NULL; */
2602 /*prog->is_stopped = 0;*/
2603 /*prog->group = NULL;*/
2604 /*prog->glob_result.gl_pathv = NULL;*/
2608 prog->type = ctx->type;
2610 /* but ctx->pipe and ctx->list_head remain unchanged */
2614 static int done_pipe(struct p_context *ctx, pipe_style type)
2617 done_command(ctx); /* implicit closure of previous command */
2618 debug_printf("done_pipe, type %d\n", type);
2619 ctx->pipe->followup = type;
2620 ctx->pipe->r_mode = ctx->w;
2622 ctx->pipe->next = new_p;
2625 done_command(ctx); /* set up new pipe to accept commands */
2629 /* peek ahead in the in_str to find out if we have a "&n" construct,
2630 * as in "2>&1", that represents duplicating a file descriptor.
2631 * returns either -2 (syntax error), -1 (no &), or the number found.
2633 static int redirect_dup_num(struct in_str *input)
2635 int ch, d = 0, ok = 0;
2637 if (ch != '&') return -1;
2639 b_getch(input); /* get the & */
2643 return -3; /* "-" represents "close me" */
2645 while (isdigit(ch)) {
2646 d = d*10 + (ch-'0');
2653 bb_error_msg("ambiguous redirect");
2657 /* If a redirect is immediately preceded by a number, that number is
2658 * supposed to tell which file descriptor to redirect. This routine
2659 * looks for such preceding numbers. In an ideal world this routine
2660 * needs to handle all the following classes of redirects...
2661 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2662 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2663 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2664 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2665 * A -1 output from this program means no valid number was found, so the
2666 * caller should use the appropriate default for this redirection.
2668 static int redirect_opt_num(o_string *o)
2674 for (num = 0; num < o->length; num++) {
2675 if (!isdigit(*(o->data + num))) {
2679 /* reuse num (and save an int) */
2680 num = atoi(o->data);
2685 static FILE *generate_stream_from_list(struct pipe *head)
2688 int pid, channel[2];
2689 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2696 bb_perror_msg_and_die("fork");
2697 } else if (pid == 0) {
2699 if (channel[1] != 1) {
2700 dup2(channel[1], 1);
2703 _exit(run_list_real(head)); /* leaks memory */
2705 debug_printf("forked child %d\n", pid);
2707 pf = fdopen(channel[0], "r");
2708 debug_printf("pipe on FILE *%p\n", pf);
2712 /* this version hacked for testing purposes */
2713 /* return code is exit status of the process that is run. */
2714 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2717 o_string result = NULL_O_STRING;
2718 struct p_context inner;
2720 struct in_str pipe_str;
2721 initialize_context(&inner);
2723 /* recursion to generate command */
2724 retcode = parse_stream(&result, &inner, input, subst_end);
2725 if (retcode != 0) return retcode; /* syntax error or EOF */
2726 done_word(&result, &inner);
2727 done_pipe(&inner, PIPE_SEQ);
2730 p = generate_stream_from_list(inner.list_head);
2731 if (p == NULL) return 1;
2732 mark_open(fileno(p));
2733 setup_file_in_str(&pipe_str, p);
2735 /* now send results of command back into original context */
2736 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2737 /* XXX In case of a syntax error, should we try to kill the child?
2738 * That would be tough to do right, so just read until EOF. */
2740 while (b_getch(&pipe_str) != EOF)
2744 debug_printf("done reading from pipe, pclose()ing\n");
2745 /* This is the step that wait()s for the child. Should be pretty
2746 * safe, since we just read an EOF from its stdout. We could try
2747 * to better, by using wait(), and keeping track of background jobs
2748 * at the same time. That would be a lot of work, and contrary
2749 * to the KISS philosophy of this program. */
2750 mark_closed(fileno(p));
2751 retcode = pclose(p);
2752 free_pipe_list(inner.list_head, 0);
2753 debug_printf("pclosed, retcode=%d\n", retcode);
2754 /* XXX this process fails to trim a single trailing newline */
2758 static int parse_group(o_string *dest, struct p_context *ctx,
2759 struct in_str *input, int ch)
2761 int rcode, endch = 0;
2762 struct p_context sub;
2763 struct child_prog *child = ctx->child;
2766 return 1; /* syntax error, groups and arglists don't mix */
2768 initialize_context(&sub);
2772 child->subshell = 1;
2778 syntax(); /* really logic error */
2780 rcode = parse_stream(dest, &sub, input, endch);
2781 done_word(dest, &sub); /* finish off the final word in the subcontext */
2782 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2783 child->group = sub.list_head;
2785 /* child remains "open", available for possible redirects */
2788 /* basically useful version until someone wants to get fancier,
2789 * see the bash man page under "Parameter Expansion" */
2790 static const char *lookup_param(const char *src)
2792 const char *p = NULL;
2796 p = get_local_var(src);
2801 /* Make new string for parser */
2802 static char* make_string(char ** inp)
2809 for (n = 0; inp[n]; n++) {
2810 p = insert_var_value(inp[n]);
2811 str = xrealloc(str, (len + strlen(p)));
2818 len = strlen(str) + 3;
2819 if (p != inp[n]) free(p);
2827 /* return code: 0 for OK, 1 for syntax error */
2828 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2832 int ch = input->peek(input); /* first character after the $ */
2833 debug_printf("handle_dollar: ch=%c\n", ch);
2835 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2837 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2841 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2842 } else if (isdigit(ch)) {
2843 i = ch - '0'; /* XXX is $0 special? */
2844 if (i < global_argc) {
2845 parse_string(dest, ctx, global_argv[i]); /* recursion */
2848 } else switch (ch) {
2850 b_adduint(dest, getpid());
2854 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2858 b_adduint(dest, last_return_code);
2862 b_adduint(dest, global_argc ? global_argc-1 : 0);
2866 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2869 /* XXX maybe someone will try to escape the '}' */
2871 ch = b_getch(input);
2872 if (ch == EOF || ch == '}')
2880 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2884 process_command_subs(dest, ctx, input, ')');
2888 for (i = 1; i < global_argc; i++) {
2889 parse_string(dest, ctx, global_argv[i]);
2890 if (i+1 < global_argc)
2891 parse_string(dest, ctx, sep);
2897 /* still unhandled, but should be eventually */
2898 bb_error_msg("unhandled syntax: $%c", ch);
2902 b_addqchr(dest,'$', dest->quote);
2904 /* Eat the character if the flag was set. If the compiler
2905 * is smart enough, we could substitute "b_getch(input);"
2906 * for all the "advance = 1;" above, and also end up with
2907 * a nice size-optimized program. Hah! That'll be the day.
2909 if (advance) b_getch(input);
2913 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2916 setup_string_in_str(&foo, src);
2917 return parse_stream(dest, ctx, &foo, '\0');
2920 /* return code is 0 for normal exit, 1 for syntax error */
2921 static int parse_stream(o_string *dest, struct p_context *ctx,
2922 struct in_str *input, int end_trigger)
2926 redir_type redir_style;
2929 /* Only double-quote state is handled in the state variable dest->quote.
2930 * A single-quote triggers a bypass of the main loop until its mate is
2931 * found. When recursing, quote state is passed in via dest->quote. */
2933 debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2934 while ((ch = b_getch(input)) != EOF) {
2936 next = (ch == '\n') ? 0 : b_peek(input);
2937 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2938 ch, ch, m, dest->quote);
2939 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2940 b_addqchr(dest, ch, dest->quote);
2943 if (m == 2) { /* unquoted IFS */
2944 if (done_word(dest, ctx)) {
2947 /* If we aren't performing a substitution, treat a newline as a
2948 * command separator. */
2949 if (end_trigger != '\0' && ch == '\n')
2950 done_pipe(ctx, PIPE_SEQ);
2952 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2953 debug_printf("leaving parse_stream (triggered)\n");
2960 if (dest->length == 0 && !dest->quote) {
2963 if (ch == EOF || ch == '\n')
2968 b_addqchr(dest, ch, dest->quote);
2976 b_addqchr(dest, '\\', dest->quote);
2977 b_addqchr(dest, b_getch(input), dest->quote);
2980 if (handle_dollar(dest, ctx, input) != 0) return 1;
2985 ch = b_getch(input);
2986 if (ch == EOF || ch == '\'')
2997 dest->quote = !dest->quote;
3000 process_command_subs(dest, ctx, input, '`');
3003 redir_fd = redirect_opt_num(dest);
3004 done_word(dest, ctx);
3005 redir_style = REDIRECT_OVERWRITE;
3007 redir_style = REDIRECT_APPEND;
3009 } else if (next == '(') {
3010 syntax(); /* until we support >(list) Process Substitution */
3013 setup_redirect(ctx, redir_fd, redir_style, input);
3016 redir_fd = redirect_opt_num(dest);
3017 done_word(dest, ctx);
3018 redir_style = REDIRECT_INPUT;
3020 redir_style = REDIRECT_HEREIS;
3022 } else if (next == '>') {
3023 redir_style = REDIRECT_IO;
3025 } else if (next == '(') {
3026 syntax(); /* until we support <(list) Process Substitution */
3029 setup_redirect(ctx, redir_fd, redir_style, input);
3032 done_word(dest, ctx);
3033 done_pipe(ctx, PIPE_SEQ);
3036 done_word(dest, ctx);
3039 done_pipe(ctx, PIPE_AND);
3041 done_pipe(ctx, PIPE_BG);
3045 done_word(dest, ctx);
3048 done_pipe(ctx, PIPE_OR);
3050 /* we could pick up a file descriptor choice here
3051 * with redirect_opt_num(), but bash doesn't do it.
3052 * "echo foo 2| cat" yields "foo 2". */
3058 if (parse_group(dest, ctx, input, ch) != 0)
3063 syntax(); /* Proper use of this character caught by end_trigger */
3066 syntax(); /* this is really an internal logic error */
3070 /* complain if quote? No, maybe we just finished a command substitution
3071 * that was quoted. Example:
3072 * $ echo "`cat foo` plus more"
3073 * and we just got the EOF generated by the subshell that ran "cat foo"
3074 * The only real complaint is if we got an EOF when end_trigger != '\0',
3075 * that is, we were really supposed to get end_trigger, and never got
3076 * one before the EOF. Can't use the standard "syntax error" return code,
3077 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3078 debug_printf("leaving parse_stream (EOF)\n");
3079 if (end_trigger != '\0')
3084 static void mapset(const char *set, int code)
3087 map[(unsigned char)*set++] = code;
3090 static void update_ifs_map(void)
3092 /* char *ifs and char map[256] are both globals. */
3093 ifs = getenv("IFS");
3094 if (ifs == NULL) ifs = " \t\n";
3095 /* Precompute a list of 'flow through' behavior so it can be treated
3096 * quickly up front. Computation is necessary because of IFS.
3097 * Special case handling of IFS == " \t\n" is not implemented.
3098 * The map[] array only really needs two bits each, and on most machines
3099 * that would be faster because of the reduced L1 cache footprint.
3101 memset(map, 0, sizeof(map)); /* most characters flow through always */
3102 mapset("\\$'\"`", 3); /* never flow through */
3103 mapset("<>;&|(){}#", 1); /* flow through if quoted */
3104 mapset(ifs, 2); /* also flow through if quoted */
3107 /* most recursion does not come through here, the exception is
3108 * from builtin_source() */
3109 static int parse_stream_outer(struct in_str *inp, int flag)
3111 // FIXME: 'true | exit 3; echo $?' is parsed as a whole,
3112 // as a result $? is replaced by 0, not 3!
3113 // Need to stop & execute stuff at ';', not parse till EOL!
3115 struct p_context ctx;
3116 o_string temp = NULL_O_STRING;
3120 initialize_context(&ctx);
3122 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
3124 #if ENABLE_HUSH_INTERACTIVE
3125 inp->promptmode = 1;
3127 rcode = parse_stream(&temp, &ctx, inp, '\n');
3128 if (rcode != 1 && ctx.old_flag != 0) {
3131 if (rcode != 1 && ctx.old_flag == 0) {
3132 done_word(&temp, &ctx);
3133 done_pipe(&ctx, PIPE_SEQ);
3134 debug_printf_exec("parse_stream_outer: run_list\n");
3135 run_list(ctx.list_head);
3137 if (ctx.old_flag != 0) {
3144 free_pipe_list(ctx.list_head, 0);
3147 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3151 static int parse_string_outer(const char *s, int flag)
3153 struct in_str input;
3154 setup_string_in_str(&input, s);
3155 return parse_stream_outer(&input, flag);
3158 static int parse_file_outer(FILE *f)
3161 struct in_str input;
3162 setup_file_in_str(&input, f);
3163 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3168 /* Make sure we have a controlling tty. If we get started under a job
3169 * aware app (like bash for example), make sure we are now in charge so
3170 * we don't fight over who gets the foreground */
3171 static void setup_job_control(void)
3175 saved_task_pgrp = shell_pgrp = getpgrp();
3176 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
3177 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3179 /* If we were ran as 'hush &',
3180 * sleep until we are in the foreground. */
3181 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3182 /* Send TTIN to ourself (should stop us) */
3183 kill(- shell_pgrp, SIGTTIN);
3184 shell_pgrp = getpgrp();
3187 /* Ignore job-control and misc signals. */
3188 set_jobctrl_sighandler(SIG_IGN);
3189 set_misc_sighandler(SIG_IGN);
3190 //huh? signal(SIGCHLD, SIG_IGN);
3192 /* We _must_ restore tty pgrp fatal signals */
3193 set_fatal_sighandler(sigexit);
3195 /* Put ourselves in our own process group. */
3196 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3197 /* Grab control of the terminal. */
3198 tcsetpgrp(interactive_fd, getpid());
3202 int hush_main(int argc, char **argv);
3203 int hush_main(int argc, char **argv)
3209 #if ENABLE_FEATURE_EDITING
3210 line_input_state = new_line_input_t(FOR_SHELL);
3213 /* XXX what should these be while sourcing /etc/profile? */
3217 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3218 * hush_main(), therefore we cannot rely on the BSS to zero out this
3219 * stuff. Reset these to 0 every time. */
3221 /* map[] is taken care of with call to update_ifs_map() */
3223 close_me_head = NULL;
3224 #if ENABLE_HUSH_INTERACTIVE
3233 /* Initialize some more globals to non-zero values */
3235 #if ENABLE_HUSH_INTERACTIVE
3236 #if ENABLE_FEATURE_EDITING
3237 cmdedit_set_initial_prompt();
3243 /* initialize our shell local variables with the values
3244 * currently living in the environment */
3248 set_local_var(*e++, 2); /* without call putenv() */
3250 last_return_code = EXIT_SUCCESS;
3252 if (argv[0] && argv[0][0] == '-') {
3253 debug_printf("\nsourcing /etc/profile\n");
3254 input = fopen("/etc/profile", "r");
3255 if (input != NULL) {
3256 mark_open(fileno(input));
3257 parse_file_outer(input);
3258 mark_closed(fileno(input));
3264 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3267 global_argv = argv + optind;
3268 global_argc = argc - optind;
3269 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3272 // Well, we cannot just declare interactiveness,
3273 // we have to have some stuff (ctty, etc)
3274 /*interactive_fd++;*/
3281 fprintf(stderr, "Usage: sh [FILE]...\n"
3282 " or: sh -c command [args]...\n\n");
3290 /* A shell is interactive if the '-i' flag was given, or if all of
3291 * the following conditions are met:
3293 * no arguments remaining or the -s flag given
3294 * standard input is a terminal
3295 * standard output is a terminal
3296 * Refer to Posix.2, the description of the 'sh' utility. */
3297 if (argv[optind] == NULL && input == stdin
3298 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3300 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3301 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3302 if (saved_tty_pgrp >= 0) {
3303 /* try to dup to high fd#, >= 255 */
3304 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3305 if (interactive_fd < 0) {
3306 /* try to dup to any fd */
3307 interactive_fd = dup(STDIN_FILENO);
3308 if (interactive_fd < 0)
3312 // TODO: track & disallow any attempts of user
3313 // to (inadvertently) close/redirect it
3316 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3317 if (interactive_fd) {
3318 /* Looks like they want an interactive shell */
3319 setup_job_control();
3320 /* Make xfuncs do cleanup on exit */
3321 die_sleep = -1; /* flag */
3322 if (setjmp(die_jmp)) {
3323 /* xfunc has failed! die die die */
3324 hush_exit(xfunc_error_retval);
3326 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3327 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3328 printf("Enter 'help' for a list of built-in commands.\n\n");
3331 #elif ENABLE_HUSH_INTERACTIVE
3332 /* no job control compiled, only prompt/line editing */
3333 if (argv[optind] == NULL && input == stdin
3334 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3336 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3337 if (interactive_fd < 0) {
3338 /* try to dup to any fd */
3339 interactive_fd = dup(STDIN_FILENO);
3340 if (interactive_fd < 0)
3348 if (argv[optind] == NULL) {
3349 opt = parse_file_outer(stdin);
3353 debug_printf("\nrunning script '%s'\n", argv[optind]);
3354 global_argv = argv + optind;
3355 global_argc = argc - optind;
3356 input = xfopen(argv[optind], "r");
3357 opt = parse_file_outer(input);
3359 #if ENABLE_FEATURE_CLEAN_UP
3361 if (cwd != bb_msg_unknown)
3364 struct variables *cur, *tmp;
3365 for (cur = top_vars; cur; cur = tmp) {
3367 if (!cur->flg_read_only) {
3368 free((char*)cur->name);
3369 free((char*)cur->value);
3377 hush_exit(opt ? opt : last_return_code);