1 /* vi: set sw=4 ts=4: */
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen
26 * miscellaneous bugfixes from Matt Kraai
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy (improved --vda)
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change map[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
83 /* #include <dmalloc.h> */
86 /* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
88 #define debug_printf(...) do {} while (0)
89 /* Finer-grained debug switches */
90 #define debug_printf_jobs(...) do {} while (0)
91 #define debug_printf_exec(...) do {} while (0)
92 #define debug_printf_parse(...) do {} while (0)
93 #define debug_print_tree(a, b) do {} while (0)
97 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
98 /* broken, of course, but OK for testing */
99 static const char *indenter(int i)
101 static const char blanks[] = " ";
102 return &blanks[sizeof(blanks) - i - 1];
105 #define final_printf debug_printf
107 #ifndef debug_printf_jobs
108 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
109 #define DEBUG_SHELL_JOBS 1
112 #ifndef debug_printf_exec
113 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
116 #ifndef debug_printf_parse
117 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
121 #if !ENABLE_HUSH_INTERACTIVE
122 #undef ENABLE_FEATURE_EDITING
123 #define ENABLE_FEATURE_EDITING 0
124 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
125 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
128 #define SPECIAL_VAR_SYMBOL 03
129 #define FLAG_EXIT_FROM_LOOP 1
130 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
131 #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
135 REDIRECT_OVERWRITE = 2,
141 /* The descrip member of this structure is only used to make debugging
143 static const struct {
145 signed char default_fd;
149 { O_RDONLY, 0, "<" },
150 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
151 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
152 { O_RDONLY, -1, "<<" },
163 /* might eventually control execution */
181 FLAG_END = (1 << RES_NONE ),
182 FLAG_IF = (1 << RES_IF ),
183 FLAG_THEN = (1 << RES_THEN ),
184 FLAG_ELIF = (1 << RES_ELIF ),
185 FLAG_ELSE = (1 << RES_ELSE ),
186 FLAG_FI = (1 << RES_FI ),
187 FLAG_FOR = (1 << RES_FOR ),
188 FLAG_WHILE = (1 << RES_WHILE),
189 FLAG_UNTIL = (1 << RES_UNTIL),
190 FLAG_DO = (1 << RES_DO ),
191 FLAG_DONE = (1 << RES_DONE ),
192 FLAG_IN = (1 << RES_IN ),
193 FLAG_START = (1 << RES_XXXX ),
196 /* This holds pointers to the various results of parsing */
198 struct child_prog *child;
199 struct pipe *list_head;
201 struct redir_struct *pending_redirect;
203 int old_flag; /* for figuring out valid reserved words */
204 struct p_context *stack;
205 int type; /* define type of parser : ";$" common or special symbol */
206 /* How about quoting status? */
209 struct redir_struct {
210 struct redir_struct *next; /* pointer to the next redirect in the list */
211 redir_type type; /* type of redirection */
212 int fd; /* file descriptor being redirected */
213 int dup; /* -1, or file descriptor being duplicated */
214 glob_t word; /* *word.gl_pathv is the filename */
218 pid_t pid; /* 0 if exited */
219 char **argv; /* program name and arguments */
220 struct pipe *group; /* if non-NULL, first in group or subshell */
221 int subshell; /* flag, non-zero if group must be forked */
222 struct redir_struct *redirects; /* I/O redirections */
223 glob_t glob_result; /* result of parameter globbing */
224 int is_stopped; /* is the program currently running? */
225 struct pipe *family; /* pointer back to the child's parent pipe */
226 int sp; /* number of SPECIAL_VAR_SYMBOL */
232 int num_progs; /* total number of programs in job */
233 int running_progs; /* number of programs running (not exited) */
234 char *cmdbuf; /* buffer various argv's point into */
236 int jobid; /* job number */
237 char *cmdtext; /* name of job */
238 pid_t pgrp; /* process group ID for the job */
240 struct child_prog *progs; /* array of commands in pipe */
241 int stopped_progs; /* number of programs alive, but stopped */
242 int job_context; /* bitmask defining current context */
243 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
244 reserved_style r_mode; /* supports if, for, while, until */
248 struct close_me *next;
253 struct variables *next;
260 /* globals, connect us to the outside world
261 * the first three support $?, $#, and $1 */
262 static char **global_argv;
263 static int global_argc;
264 static int last_return_code;
265 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
267 /* "globals" within this file */
270 MAP_FLOWTROUGH_IF_QUOTED = 1,
271 MAP_IFS_IF_UNQUOTED = 2, /* flow through if quoted too */
272 MAP_NEVER_FLOWTROUGH = 3,
274 static unsigned char map[256];
275 static const char *ifs;
276 static int fake_mode;
277 static struct close_me *close_me_head;
278 static const char *cwd;
279 static unsigned last_bg_pid;
280 #if !ENABLE_HUSH_INTERACTIVE
281 enum { interactive_fd = 0 };
283 /* 'interactive_fd' is a fd# open to ctty, if we have one
284 * _AND_ if we decided to mess with job control */
285 static int interactive_fd;
287 static pid_t saved_task_pgrp;
288 static pid_t saved_tty_pgrp;
289 static int last_jobid;
290 static struct pipe *job_list;
292 static const char *PS1;
293 static const char *PS2;
296 #define HUSH_VER_STR "0.02"
297 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
298 static struct variables *top_vars = &shell_ver;
310 #define NULL_O_STRING {NULL,0,0,0,0}
311 /* used for initialization:
312 o_string foo = NULL_O_STRING; */
314 /* I can almost use ordinary FILE *. Is open_memstream() universally
315 * available? Where is it documented? */
319 #if ENABLE_HUSH_INTERACTIVE
324 int (*get) (struct in_str *);
325 int (*peek) (struct in_str *);
327 #define b_getch(input) ((input)->get(input))
328 #define b_peek(input) ((input)->peek(input))
330 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
332 struct built_in_command {
333 const char *cmd; /* name */
334 const char *descr; /* description */
335 int (*function) (char **argv); /* function ptr */
338 static void __syntax(int line)
340 bb_error_msg("syntax error hush.c:%d", line);
342 #define syntax() __syntax(__LINE__)
344 /* Index of subroutines: */
345 /* function prototypes for builtins */
346 static int builtin_cd(char **argv);
347 static int builtin_eval(char **argv);
348 static int builtin_exec(char **argv);
349 static int builtin_exit(char **argv);
350 static int builtin_export(char **argv);
352 static int builtin_fg_bg(char **argv);
353 static int builtin_jobs(char **argv);
355 static int builtin_help(char **argv);
356 static int builtin_pwd(char **argv);
357 static int builtin_read(char **argv);
358 static int builtin_set(char **argv);
359 static int builtin_shift(char **argv);
360 static int builtin_source(char **argv);
361 static int builtin_umask(char **argv);
362 static int builtin_unset(char **argv);
363 static int builtin_not_written(char **argv);
364 /* o_string manipulation: */
365 static int b_check_space(o_string *o, int len);
366 static int b_addchr(o_string *o, int ch);
367 static void b_reset(o_string *o);
368 static int b_addqchr(o_string *o, int ch, int quote);
369 static int b_adduint(o_string *o, unsigned i);
370 /* in_str manipulations: */
371 static int static_get(struct in_str *i);
372 static int static_peek(struct in_str *i);
373 static int file_get(struct in_str *i);
374 static int file_peek(struct in_str *i);
375 static void setup_file_in_str(struct in_str *i, FILE *f);
376 static void setup_string_in_str(struct in_str *i, const char *s);
377 /* close_me manipulations: */
378 static void mark_open(int fd);
379 static void mark_closed(int fd);
380 static void close_all(void);
381 /* "run" the final data structures: */
382 static int free_pipe_list(struct pipe *head, int indent);
383 static int free_pipe(struct pipe *pi, int indent);
384 /* really run the final data structures: */
385 static int setup_redirects(struct child_prog *prog, int squirrel[]);
386 static int run_list_real(struct pipe *pi);
387 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
388 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
389 static int run_pipe_real(struct pipe *pi);
390 /* extended glob support: */
391 static int globhack(const char *src, int flags, glob_t *pglob);
392 static int glob_needed(const char *s);
393 static int xglob(o_string *dest, int flags, glob_t *pglob);
394 /* variable assignment: */
395 static int is_assignment(const char *s);
396 /* data structure manipulation: */
397 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
398 static void initialize_context(struct p_context *ctx);
399 static int done_word(o_string *dest, struct p_context *ctx);
400 static int done_command(struct p_context *ctx);
401 static int done_pipe(struct p_context *ctx, pipe_style type);
402 /* primary string parsing: */
403 static int redirect_dup_num(struct in_str *input);
404 static int redirect_opt_num(o_string *o);
405 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
406 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
407 static const char *lookup_param(const char *src);
408 static char *make_string(char **inp);
409 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
410 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
411 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
413 static int parse_stream_outer(struct in_str *inp, int flag);
414 static int parse_string_outer(const char *s, int flag);
415 static int parse_file_outer(FILE *f);
416 /* job management: */
417 static int checkjobs(struct pipe* fg_pipe);
419 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
420 static void insert_bg_job(struct pipe *pi);
421 static void remove_bg_job(struct pipe *pi);
422 static void delete_finished_bg_job(struct pipe *pi);
424 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
426 /* local variable support */
427 static char **make_list_in(char **inp, char *name);
428 static char *insert_var_value(char *inp);
429 static const char *get_local_var(const char *var);
430 static int set_local_var(const char *s, int flg_export);
431 static void unset_local_var(const char *name);
433 /* Table of built-in functions. They can be forked or not, depending on
434 * context: within pipes, they fork. As simple commands, they do not.
435 * When used in non-forking context, they can change global variables
436 * in the parent shell process. If forked, of course they cannot.
437 * For example, 'unset foo | whatever' will parse and run, but foo will
438 * still be set at the end. */
439 static const struct built_in_command bltins[] = {
441 { "bg", "Resume a job in the background", builtin_fg_bg },
443 { "break", "Exit for, while or until loop", builtin_not_written },
444 { "cd", "Change working directory", builtin_cd },
445 { "continue", "Continue for, while or until loop", builtin_not_written },
446 { "eval", "Construct and run shell command", builtin_eval },
447 { "exec", "Exec command, replacing this shell with the exec'd process",
449 { "exit", "Exit from shell()", builtin_exit },
450 { "export", "Set environment variable", builtin_export },
452 { "fg", "Bring job into the foreground", builtin_fg_bg },
453 { "jobs", "Lists the active jobs", builtin_jobs },
455 { "pwd", "Print current directory", builtin_pwd },
456 { "read", "Input environment variable", builtin_read },
457 { "return", "Return from a function", builtin_not_written },
458 { "set", "Set/unset shell local variables", builtin_set },
459 { "shift", "Shift positional parameters", builtin_shift },
460 { "trap", "Trap signals", builtin_not_written },
461 { "ulimit","Controls resource limits", builtin_not_written },
462 { "umask","Sets file creation mask", builtin_umask },
463 { "unset", "Unset environment variable", builtin_unset },
464 { ".", "Source-in and run commands in a file", builtin_source },
465 { "help", "List shell built-in commands", builtin_help },
472 static void signal_SA_RESTART(int sig, void (*handler)(int))
475 sa.sa_handler = handler;
476 sa.sa_flags = SA_RESTART;
477 sigemptyset(&sa.sa_mask);
478 sigaction(sig, &sa, NULL);
481 /* Signals are grouped, we handle them in batches */
482 static void set_fatal_sighandler(void (*handler)(int))
484 signal(SIGILL , handler);
485 signal(SIGTRAP, handler);
486 signal(SIGABRT, handler);
487 signal(SIGFPE , handler);
488 signal(SIGBUS , handler);
489 signal(SIGSEGV, handler);
490 /* bash 3.2 seems to handle these just like 'fatal' ones */
491 signal(SIGHUP , handler);
492 signal(SIGPIPE, handler);
493 signal(SIGALRM, handler);
495 static void set_jobctrl_sighandler(void (*handler)(int))
497 signal(SIGTSTP, handler);
498 signal(SIGTTIN, handler);
499 signal(SIGTTOU, handler);
501 static void set_misc_sighandler(void (*handler)(int))
503 signal(SIGINT , handler);
504 signal(SIGQUIT, handler);
505 signal(SIGTERM, handler);
507 /* SIGCHLD is special and handled separately */
509 static void set_every_sighandler(void (*handler)(int))
511 set_fatal_sighandler(handler);
512 set_jobctrl_sighandler(handler);
513 set_misc_sighandler(handler);
514 signal(SIGCHLD, handler);
517 static struct pipe *toplevel_list;
518 static sigjmp_buf toplevel_jb;
519 smallint ctrl_z_flag;
520 #if ENABLE_FEATURE_SH_STANDALONE
521 struct nofork_save_area nofork_save;
524 static void handler_ctrl_c(int sig)
526 debug_printf_jobs("got sig %d\n", sig);
527 // as usual we can have all kinds of nasty problems with leaked malloc data here
528 siglongjmp(toplevel_jb, 1);
531 static void handler_ctrl_z(int sig)
535 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
537 if (pid < 0) /* can't fork. Pretend there were no ctrl-Z */
541 // toplevel_list->running_progs = 1;
542 // toplevel_list->stopped_progs = 0;
544 if (!pid) { /* child */
546 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
547 set_every_sighandler(SIG_DFL);
548 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
549 debug_printf_jobs("returning in child\n");
550 /* return to nofork, it will eventually exit now,
551 * not return back to shell */
555 /* finish filling up pipe info */
556 toplevel_list->pgrp = pid; /* child is in its own pgrp */
557 toplevel_list->progs[0].pid = pid;
559 // toplevel_list->running_progs = 1;
560 // toplevel_list->stopped_progs = 0;
561 /* parent needs to longjmp out of running nofork.
562 * we will "return" exitcode 0, with child put in background */
563 // as usual we can have all kinds of nasty problems with leaked malloc data here
564 debug_printf_jobs("siglongjmp in parent\n");
565 siglongjmp(toplevel_jb, 1);
568 /* Restores tty foreground process group, and exits.
569 * May be called as signal handler for fatal signal
570 * (will faithfully resend signal to itself, producing correct exit state)
571 * or called directly with -EXITCODE.
572 * We also call it if xfunc is exiting. */
573 static void sigexit(int sig) ATTRIBUTE_NORETURN;
574 static void sigexit(int sig)
578 /* Disable all signals: job control, SIGPIPE, etc. */
579 sigfillset(&block_all);
580 sigprocmask(SIG_SETMASK, &block_all, NULL);
583 tcsetpgrp(interactive_fd, saved_tty_pgrp);
585 /* Not a signal, just exit */
589 /* Enable only this sig and kill ourself with it */
590 signal(sig, SIG_DFL);
591 sigdelset(&block_all, sig);
592 sigprocmask(SIG_SETMASK, &block_all, NULL);
594 _exit(1); /* Should not reach it */
597 /* Restores tty foreground process group, and exits. */
598 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
599 static void hush_exit(int exitcode)
601 fflush(NULL); /* flush all streams */
602 sigexit(- (exitcode & 0xff));
607 #define set_fatal_sighandler(handler) ((void)0)
608 #define set_jobctrl_sighandler(handler) ((void)0)
609 #define set_misc_sighandler(handler) ((void)0)
610 #define hush_exit(e) exit(e)
615 static const char *set_cwd(void)
617 if (cwd == bb_msg_unknown)
618 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
619 cwd = xrealloc_getcwd_or_warn((char *)cwd);
621 cwd = bb_msg_unknown;
625 /* built-in 'eval' handler */
626 static int builtin_eval(char **argv)
629 int rcode = EXIT_SUCCESS;
632 str = make_string(argv + 1);
633 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
634 FLAG_PARSE_SEMICOLON);
636 rcode = last_return_code;
641 /* built-in 'cd <path>' handler */
642 static int builtin_cd(char **argv)
646 newdir = getenv("HOME");
650 printf("cd: %s: %s\n", newdir, strerror(errno));
657 /* built-in 'exec' handler */
658 static int builtin_exec(char **argv)
661 return EXIT_SUCCESS; /* Really? */
662 pseudo_exec_argv(argv + 1);
666 /* built-in 'exit' handler */
667 static int builtin_exit(char **argv)
669 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
670 //puts("exit"); /* bash does it */
671 // TODO: warn if we have background jobs: "There are stopped jobs"
672 // On second consecutive 'exit', exit anyway.
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]) & 0xff);
682 /* built-in 'export VAR=value' handler */
683 static int builtin_export(char **argv)
686 char *name = argv[1];
690 // ash emits: export VAR='VAL'
691 // bash: declare -x VAR="VAL"
692 // (both also escape as needed (quotes, $, etc))
703 const char *value = strchr(name, '=');
707 /* They are exporting something without an =VALUE */
709 value = get_local_var(name);
711 size_t ln = strlen(name);
713 tmp = realloc(name, ln+strlen(value)+2);
717 sprintf(tmp+ln, "=%s", value);
721 /* bash does not return an error when trying to export
722 * an undefined variable. Do likewise. */
728 bb_perror_msg("export");
730 res = set_local_var(name, 1);
738 /* built-in 'fg' and 'bg' handler */
739 static int builtin_fg_bg(char **argv)
746 /* If they gave us no args, assume they want the last backgrounded task */
748 for (pi = job_list; pi; pi = pi->next) {
749 if (pi->jobid == last_jobid) {
753 bb_error_msg("%s: no current job", argv[0]);
756 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
757 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
760 for (pi = job_list; pi; pi = pi->next) {
761 if (pi->jobid == jobnum) {
765 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
768 // TODO: bash prints a string representation
769 // of job being foregrounded (like "sleep 1 | cat")
770 if (*argv[0] == 'f') {
771 /* Put the job into the foreground. */
772 tcsetpgrp(interactive_fd, pi->pgrp);
775 /* Restart the processes in the job */
776 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
777 for (i = 0; i < pi->num_progs; i++) {
778 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
779 pi->progs[i].is_stopped = 0;
781 pi->stopped_progs = 0;
783 i = kill(- pi->pgrp, SIGCONT);
785 if (errno == ESRCH) {
786 delete_finished_bg_job(pi);
789 bb_perror_msg("kill (SIGCONT)");
793 if (*argv[0] == 'f') {
795 return checkjobs_and_fg_shell(pi);
801 /* built-in 'help' handler */
802 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
804 const struct built_in_command *x;
806 printf("\nBuilt-in commands:\n");
807 printf("-------------------\n");
808 for (x = bltins; x->cmd; x++) {
809 if (x->descr == NULL)
811 printf("%s\t%s\n", x->cmd, x->descr);
818 /* built-in 'jobs' handler */
819 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
822 const char *status_string;
824 for (job = job_list; job; job = job->next) {
825 if (job->running_progs == job->stopped_progs)
826 status_string = "Stopped";
828 status_string = "Running";
830 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
836 /* built-in 'pwd' handler */
837 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
843 /* built-in 'read VAR' handler */
844 static int builtin_read(char **argv)
852 string[0] = '\0'; /* In case stdin has only EOF */
854 fgets(string, sizeof(string), stdin);
856 var = malloc(strlen(argv[1]) + strlen(string) + 2);
858 sprintf(var, "%s=%s", argv[1], string);
859 res = set_local_var(var, 0);
863 bb_perror_msg("read");
864 free(var); /* So not move up to avoid breaking errno */
867 do res = getchar(); while (res != '\n' && res != EOF);
871 /* built-in 'set VAR=value' handler */
872 static int builtin_set(char **argv)
874 char *temp = argv[1];
878 for (e = top_vars; e; e = e->next)
879 printf("%s=%s\n", e->name, e->value);
881 set_local_var(temp, 0);
887 /* Built-in 'shift' handler */
888 static int builtin_shift(char **argv)
894 if (n >= 0 && n < global_argc) {
895 /* XXX This probably breaks $0 */
903 /* Built-in '.' handler (read-in and execute commands from file) */
904 static int builtin_source(char **argv)
912 /* XXX search through $PATH is missing */
913 input = fopen(argv[1], "r");
915 bb_error_msg("cannot open '%s'", argv[1]);
919 /* Now run the file */
920 /* XXX argv and argc are broken; need to save old global_argv
921 * (pointer only is OK!) on this stack frame,
922 * set global_argv=argv+1, recurse, and restore. */
923 mark_open(fileno(input));
924 status = parse_file_outer(input);
925 mark_closed(fileno(input));
930 static int builtin_umask(char **argv)
933 const char *arg = argv[1];
936 new_umask = strtoul(arg, &end, 8);
937 if (*end != '\0' || end == arg) {
941 new_umask = umask(0);
942 printf("%.3o\n", (unsigned) new_umask);
948 /* built-in 'unset VAR' handler */
949 static int builtin_unset(char **argv)
951 /* bash returned already true */
952 unset_local_var(argv[1]);
956 static int builtin_not_written(char **argv)
958 printf("builtin_%s not written\n", argv[0]);
962 static int b_check_space(o_string *o, int len)
964 /* It would be easy to drop a more restrictive policy
965 * in here, such as setting a maximum string length */
966 if (o->length + len > o->maxlen) {
967 char *old_data = o->data;
968 /* assert(data == NULL || o->maxlen != 0); */
969 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
970 o->data = realloc(o->data, 1 + o->maxlen);
971 if (o->data == NULL) {
975 return o->data == NULL;
978 static int b_addchr(o_string *o, int ch)
980 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
981 if (b_check_space(o, 1))
983 o->data[o->length] = ch;
985 o->data[o->length] = '\0';
989 static void b_reset(o_string *o)
997 static void b_free(o_string *o)
1005 /* My analysis of quoting semantics tells me that state information
1006 * is associated with a destination, not a source.
1008 static int b_addqchr(o_string *o, int ch, int quote)
1010 if (quote && strchr("*?[\\", ch)) {
1012 rc = b_addchr(o, '\\');
1016 return b_addchr(o, ch);
1019 static int b_adduint(o_string *o, unsigned i)
1022 char buf[sizeof(unsigned)*3 + 1];
1024 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1025 /* no escape checking necessary */
1026 do r = b_addchr(o, *p++); while (r == 0 && *p);
1030 static int static_get(struct in_str *i)
1033 if (ch == '\0') return EOF;
1037 static int static_peek(struct in_str *i)
1042 #if ENABLE_HUSH_INTERACTIVE
1043 #if ENABLE_FEATURE_EDITING
1044 static void cmdedit_set_initial_prompt(void)
1046 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1049 PS1 = getenv("PS1");
1056 static const char* setup_prompt_string(int promptmode)
1058 const char *prompt_str;
1059 debug_printf("setup_prompt_string %d ", promptmode);
1060 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1061 /* Set up the prompt */
1062 if (promptmode == 1) {
1065 ns = xmalloc(strlen(cwd)+4);
1066 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1073 prompt_str = (promptmode == 1) ? PS1 : PS2;
1075 debug_printf("result %s\n", prompt_str);
1078 #endif /* ENABLE_HUSH_INTERACTIVE */
1080 #if ENABLE_FEATURE_EDITING
1081 static line_input_t *line_input_state;
1084 #if ENABLE_HUSH_INTERACTIVE
1085 static int get_user_input(struct in_str *i)
1087 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1090 const char *prompt_str;
1091 prompt_str = setup_prompt_string(i->promptmode);
1092 #if ENABLE_FEATURE_EDITING
1094 ** enable command line editing only while a command line
1095 ** is actually being read; otherwise, we'll end up bequeathing
1096 ** atexit() handlers and other unwanted stuff to our
1097 ** child processes (rob@sysgo.de)
1099 r = read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
1101 fputs(prompt_str, stdout);
1103 the_command[0] = r = fgetc(i->file);
1104 the_command[1] = '\0';
1108 return r; /* < 0 == EOF. Not meaningful otherwise */
1112 /* This is the magic location that prints prompts
1113 * and gets data back from the user */
1114 static int file_get(struct in_str *i)
1119 /* If there is data waiting, eat it up */
1120 if (i->p && *i->p) {
1123 /* need to double check i->file because we might be doing something
1124 * more complicated by now, like sourcing or substituting. */
1125 #if ENABLE_HUSH_INTERACTIVE
1126 if (interactive_fd && i->__promptme && i->file == stdin) {
1127 while (!i->p || !(interactive_fd && i->p[0])) {
1128 if (get_user_input(i) < 0)
1133 if (i->p && *i->p) {
1139 ch = fgetc(i->file);
1141 debug_printf("b_getch: got a %d\n", ch);
1143 #if ENABLE_HUSH_INTERACTIVE
1150 /* All the callers guarantee this routine will never be
1151 * used right after a newline, so prompting is not needed.
1153 static int file_peek(struct in_str *i)
1155 if (i->p && *i->p) {
1158 i->peek_buf[0] = fgetc(i->file);
1159 i->peek_buf[1] = '\0';
1161 debug_printf("b_peek: got a %d\n", *i->p);
1165 static void setup_file_in_str(struct in_str *i, FILE *f)
1167 i->peek = file_peek;
1169 #if ENABLE_HUSH_INTERACTIVE
1177 static void setup_string_in_str(struct in_str *i, const char *s)
1179 i->peek = static_peek;
1180 i->get = static_get;
1181 #if ENABLE_HUSH_INTERACTIVE
1188 static void mark_open(int fd)
1190 struct close_me *new = xmalloc(sizeof(struct close_me));
1192 new->next = close_me_head;
1193 close_me_head = new;
1196 static void mark_closed(int fd)
1198 struct close_me *tmp;
1199 if (close_me_head == NULL || close_me_head->fd != fd)
1200 bb_error_msg_and_die("corrupt close_me");
1201 tmp = close_me_head;
1202 close_me_head = close_me_head->next;
1206 static void close_all(void)
1209 for (c = close_me_head; c; c = c->next) {
1212 close_me_head = NULL;
1215 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1216 * and stderr if they are redirected. */
1217 static int setup_redirects(struct child_prog *prog, int squirrel[])
1220 struct redir_struct *redir;
1222 for (redir = prog->redirects; redir; redir = redir->next) {
1223 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1224 /* something went wrong in the parse. Pretend it didn't happen */
1227 if (redir->dup == -1) {
1228 mode = redir_table[redir->type].mode;
1229 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1231 /* this could get lost if stderr has been redirected, but
1232 bash and ash both lose it as well (though zsh doesn't!) */
1236 openfd = redir->dup;
1239 if (openfd != redir->fd) {
1240 if (squirrel && redir->fd < 3) {
1241 squirrel[redir->fd] = dup(redir->fd);
1246 dup2(openfd, redir->fd);
1247 if (redir->dup == -1)
1255 static void restore_redirects(int squirrel[])
1258 for (i = 0; i < 3; i++) {
1261 /* No error checking. I sure wouldn't know what
1262 * to do with an error if I found one! */
1270 /* XXX no exit() here. If you don't exec, use _exit instead.
1271 * The at_exit handlers apparently confuse the calling process,
1272 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1273 static void pseudo_exec_argv(char **argv)
1277 const struct built_in_command *x;
1279 for (i = 0; is_assignment(argv[i]); i++) {
1280 debug_printf("pid %d environment modification: %s\n",
1282 // FIXME: vfork case??
1283 p = insert_var_value(argv[i]);
1289 /* If a variable is assigned in a forest, and nobody listens,
1290 * was it ever really set?
1292 if (argv[0] == NULL) {
1293 _exit(EXIT_SUCCESS);
1297 * Check if the command matches any of the builtins.
1298 * Depending on context, this might be redundant. But it's
1299 * easier to waste a few CPU cycles than it is to figure out
1300 * if this is one of those cases.
1302 for (x = bltins; x->cmd; x++) {
1303 if (strcmp(argv[0], x->cmd) == 0) {
1304 debug_printf("builtin exec %s\n", argv[0]);
1305 rcode = x->function(argv);
1311 /* Check if the command matches any busybox internal commands
1313 * FIXME: This feature is not 100% safe, since
1314 * BusyBox is not fully reentrant, so we have no guarantee the things
1315 * from the .bss are still zeroed, or that things from .data are still
1316 * at their defaults. We could exec ourself from /proc/self/exe, but I
1317 * really dislike relying on /proc for things. We could exec ourself
1318 * from global_argv[0], but if we are in a chroot, we may not be able
1319 * to find ourself... */
1320 #if ENABLE_FEATURE_SH_STANDALONE
1321 debug_printf("running applet %s\n", argv[0]);
1322 run_applet_and_exit(argv[0], argv);
1323 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1324 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1326 debug_printf("exec of %s\n", argv[0]);
1327 execvp(argv[0], argv);
1328 bb_perror_msg("cannot exec '%s'", argv[0]);
1332 static void pseudo_exec(struct child_prog *child)
1334 // FIXME: buggy wrt NOMMU! Must not modify any global data
1335 // until it does exec/_exit, but currently it does.
1339 pseudo_exec_argv(child->argv);
1343 // FIXME: do not modify globals! Think vfork!
1344 #if ENABLE_HUSH_INTERACTIVE
1345 interactive_fd = 0; /* crucial!!!! */
1347 debug_printf_exec("pseudo_exec: run_list_real\n");
1348 rcode = run_list_real(child->group);
1349 /* OK to leak memory by not calling free_pipe_list,
1350 * since this process is about to exit */
1354 /* Can happen. See what bash does with ">foo" by itself. */
1355 debug_printf("trying to pseudo_exec null command\n");
1356 _exit(EXIT_SUCCESS);
1360 static const char *get_cmdtext(struct pipe *pi)
1366 /* This is subtle. ->cmdtext is created only on first backgrounding.
1367 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1368 * On subsequent bg argv can be trashed, but we won't use it */
1371 argv = pi->progs[0].argv;
1372 if (!argv || !argv[0])
1373 return (pi->cmdtext = xzalloc(1));
1376 do len += strlen(*argv) + 1; while (*++argv);
1377 pi->cmdtext = p = xmalloc(len);
1378 argv = pi->progs[0].argv;
1380 len = strlen(*argv);
1381 memcpy(p, *argv, len);
1391 static void insert_bg_job(struct pipe *pi)
1393 struct pipe *thejob;
1395 /* Linear search for the ID of the job to use */
1397 for (thejob = job_list; thejob; thejob = thejob->next)
1398 if (thejob->jobid >= pi->jobid)
1399 pi->jobid = thejob->jobid + 1;
1401 /* add thejob to the list of running jobs */
1403 thejob = job_list = xmalloc(sizeof(*thejob));
1405 for (thejob = job_list; thejob->next; thejob = thejob->next)
1407 thejob->next = xmalloc(sizeof(*thejob));
1408 thejob = thejob->next;
1411 /* physically copy the struct job */
1412 memcpy(thejob, pi, sizeof(struct pipe));
1413 thejob->progs = xmalloc(sizeof(pi->progs[0]) * pi->num_progs);
1414 memcpy(thejob->progs, pi->progs, sizeof(pi->progs[0]) * pi->num_progs);
1415 thejob->next = NULL;
1416 /*seems to be wrong:*/
1417 /*thejob->running_progs = thejob->num_progs;*/
1418 /*thejob->stopped_progs = 0;*/
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");
1576 /* move the shell to the foreground */
1577 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1578 // bb_perror_msg("tcsetpgrp-2");
1583 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1586 int rcode = checkjobs(fg_pipe);
1587 /* Job finished, move the shell to the foreground */
1589 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1590 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1591 bb_perror_msg("tcsetpgrp-4a");
1596 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1597 * to finish. See checkjobs().
1599 * return code is normally -1, when the caller has to wait for children
1600 * to finish to determine the exit status of the pipe. If the pipe
1601 * is a simple builtin command, however, the action is done by the
1602 * time run_pipe_real returns, and the exit code is provided as the
1605 * The input of the pipe is always stdin, the output is always
1606 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1607 * because it tries to avoid running the command substitution in
1608 * subshell, when that is in fact necessary. The subshell process
1609 * now has its stdout directed to the input of the appropriate pipe,
1610 * so this routine is noticeably simpler.
1612 static int run_pipe_real(struct pipe *pi)
1615 int nextin, nextout;
1616 int pipefds[2]; /* pipefds[0] is for reading */
1617 struct child_prog *child;
1618 const struct built_in_command *x;
1620 /* it is not always needed, but we aim to smaller code */
1621 int squirrel[] = { -1, -1, -1 };
1623 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1625 debug_printf_exec("run_pipe_real start:\n");
1631 pi->running_progs = 1;
1632 pi->stopped_progs = 0;
1634 /* Check if this is a simple builtin (not part of a pipe).
1635 * Builtins within pipes have to fork anyway, and are handled in
1636 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1638 child = &(pi->progs[0]);
1639 if (single_fg && child->group && child->subshell == 0) {
1640 debug_printf("non-subshell grouping\n");
1641 setup_redirects(child, squirrel);
1642 debug_printf_exec(": run_list_real\n");
1643 rcode = run_list_real(child->group);
1644 restore_redirects(squirrel);
1645 debug_printf_exec("run_pipe_real return %d\n", rcode);
1649 if (single_fg && child->argv != NULL) {
1650 char **argv = child->argv;
1652 for (i = 0; is_assignment(argv[i]); i++)
1654 if (i != 0 && argv[i] == NULL) {
1655 /* assignments, but no command: set the local environment */
1656 for (i = 0; argv[i] != NULL; i++) {
1657 /* Ok, this case is tricky. We have to decide if this is a
1658 * local variable, or an already exported variable. If it is
1659 * already exported, we have to export the new value. If it is
1660 * not exported, we need only set this as a local variable.
1661 * This junk is all to decide whether or not to export this
1665 name = xstrdup(argv[i]);
1666 debug_printf("Local environment set: %s\n", name);
1667 value = strchr(name, '=');
1670 if (get_local_var(name)) {
1674 p = insert_var_value(argv[i]);
1675 set_local_var(p, export_me);
1679 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1681 for (i = 0; is_assignment(argv[i]); i++) {
1682 p = insert_var_value(argv[i]);
1692 str = make_string(argv + i);
1693 debug_printf_exec(": parse_string_outer '%s'\n", str);
1694 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1696 debug_printf_exec("run_pipe_real return %d\n", last_return_code);
1697 return last_return_code;
1699 for (x = bltins; x->cmd; x++) {
1700 if (strcmp(argv[i], x->cmd) == 0) {
1701 if (x->function == builtin_exec && argv[i+1] == NULL) {
1702 debug_printf("magic exec\n");
1703 setup_redirects(child, NULL);
1704 return EXIT_SUCCESS;
1706 debug_printf("builtin inline %s\n", argv[0]);
1707 /* XXX setup_redirects acts on file descriptors, not FILEs.
1708 * This is perfect for work that comes after exec().
1709 * Is it really safe for inline use? Experimentally,
1710 * things seem to work with glibc. */
1711 // TODO: fflush(NULL)?
1712 setup_redirects(child, squirrel);
1713 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1714 rcode = x->function(argv + i);
1715 restore_redirects(squirrel);
1716 debug_printf_exec("run_pipe_real return %d\n", rcode);
1720 #if ENABLE_FEATURE_SH_STANDALONE
1722 const struct bb_applet *a = find_applet_by_name(argv[i]);
1723 if (a && a->nofork) {
1724 setup_redirects(child, squirrel);
1725 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv[i], argv[i+1]);
1726 save_nofork_data(&nofork_save);
1727 rcode = run_nofork_applet_prime(&nofork_save, a, argv);
1728 restore_redirects(squirrel);
1729 debug_printf_exec("run_pipe_real return %d\n", rcode);
1736 /* Going to fork a child per each pipe member */
1737 pi->running_progs = 0;
1739 /* Disable job control signals for shell (parent) and
1740 * for initial child code after fork */
1741 set_jobctrl_sighandler(SIG_IGN);
1743 for (i = 0; i < pi->num_progs; i++) {
1744 child = &(pi->progs[i]);
1745 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1747 /* pipes are inserted between pairs of commands */
1748 if ((i + 1) < pi->num_progs) {
1749 if (pipe(pipefds) < 0)
1750 bb_perror_msg_and_die("pipe");
1751 nextout = pipefds[1];
1757 /* XXX test for failed fork()? */
1759 child->pid = fork();
1761 child->pid = vfork();
1763 if (!child->pid) { /* child */
1764 /* Every child adds itself to new process group
1765 * with pgid == pid of first child in pipe */
1767 if (interactive_fd) {
1768 /* Don't do pgrp restore anymore on fatal signals */
1769 set_fatal_sighandler(SIG_DFL);
1770 if (pi->pgrp < 0) /* true for 1st process only */
1771 pi->pgrp = getpid();
1772 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1773 /* We do it in *every* child, not just first,
1775 tcsetpgrp(interactive_fd, pi->pgrp);
1779 // in non-interactive case fatal sigs are already SIG_DFL
1789 if (pipefds[0] != -1) {
1790 close(pipefds[0]); /* opposite end of our output pipe */
1792 /* Like bash, explicit redirects override pipes,
1793 * and the pipe fd is available for dup'ing. */
1794 setup_redirects(child, NULL);
1796 /* Restore default handlers just prior to exec */
1797 set_jobctrl_sighandler(SIG_DFL);
1798 set_misc_sighandler(SIG_DFL);
1799 signal(SIGCHLD, SIG_DFL);
1803 pi->running_progs++;
1806 /* Second and next children need to know pid of first one */
1808 pi->pgrp = child->pid;
1811 /* Don't check for errors. The child may be dead already,
1812 * in which case setpgid returns error code EACCES. */
1813 //why we do it at all?? child does it itself
1814 //if (interactive_fd)
1815 // setpgid(child->pid, pi->pgrp);
1822 /* If there isn't another process, nextin is garbage
1823 but it doesn't matter */
1824 nextin = pipefds[0];
1826 debug_printf_exec("run_pipe_real return -1\n");
1830 #ifndef debug_print_tree
1831 static void debug_print_tree(struct pipe *pi, int lvl)
1833 static const char *PIPE[] = {
1839 static const char *RES[] = {
1840 [RES_NONE ] = "NONE" ,
1842 [RES_THEN ] = "THEN" ,
1843 [RES_ELIF ] = "ELIF" ,
1844 [RES_ELSE ] = "ELSE" ,
1846 [RES_FOR ] = "FOR" ,
1847 [RES_WHILE] = "WHILE",
1848 [RES_UNTIL] = "UNTIL",
1850 [RES_DONE ] = "DONE" ,
1851 [RES_XXXX ] = "XXXX" ,
1853 [RES_SNTX ] = "SNTX" ,
1860 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1861 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1863 while (prn < pi->num_progs) {
1864 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1865 if (pi->progs[prn].group) {
1866 fprintf(stderr, " group %s: (argv=%p)\n",
1867 (pi->subshell ? "()" : "{}"),
1868 pi->progs[prn].argv);
1869 debug_print_tree(pi->progs[prn].group, lvl+1);
1873 argv = pi->progs[prn].argv;
1874 if (argv) while (*argv) {
1875 fprintf(stderr, " '%s'", *argv);
1878 fprintf(stderr, "\n");
1887 // NB: called by pseudo_exec, and therefore must not modify any
1888 // global data until exec/_exit (we can be a child after vfork!)
1889 static int run_list_real(struct pipe *pi)
1897 char *save_name = NULL;
1899 char **save_list = NULL;
1904 int rcode = 0; /* probaly for gcc only */
1905 int flag_restore = 0;
1906 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1907 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1909 debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1911 /* check syntax for "for" */
1912 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1913 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1914 && (rpipe->next == NULL)
1917 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1920 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1921 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1924 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1930 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1931 * We are saving state before entering outermost list ("while...done")
1932 * so that ctrl-Z will correctly background _entire_ outermost list,
1933 * not just a part of it (like "sleep 1 | exit 2") */
1934 if (++level == 1 && interactive_fd) {
1935 if (sigsetjmp(toplevel_jb, 1)) {
1936 /* ctrl-Z forked and we are parent; or ctrl-C.
1937 * Sighandler has longjmped us here */
1938 signal(SIGINT, SIG_IGN);
1939 signal(SIGTSTP, SIG_IGN);
1940 /* Restore level (we can be coming from deep inside
1943 #if ENABLE_FEATURE_SH_STANDALONE
1944 if (nofork_save.saved) { /* if save area is valid */
1945 debug_printf_jobs("exiting nofork early\n");
1946 restore_nofork_data(&nofork_save);
1950 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1951 * Remember this child as background job */
1954 /* ctrl-C. We just stop doing whatever we was doing */
1960 /* ctrl-Z handler will store pid etc in pi */
1963 #if ENABLE_FEATURE_SH_STANDALONE
1964 nofork_save.saved = 0; /* in case we will run a nofork later */
1966 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1967 signal(SIGINT, handler_ctrl_c);
1971 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1972 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1973 || pi->r_mode == RES_FOR
1982 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1983 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1984 if (rmode == skip_more_in_this_rmode && flag_skip) {
1985 if (pi->followup == PIPE_SEQ)
1990 skip_more_in_this_rmode = RES_XXXX;
1991 if (rmode == RES_THEN || rmode == RES_ELSE)
1992 if_code = next_if_code;
1993 if (rmode == RES_THEN && if_code)
1995 if (rmode == RES_ELSE && !if_code)
1997 if (rmode == RES_ELIF && !if_code)
1999 if (rmode == RES_FOR && pi->num_progs) {
2001 /* if no variable values after "in" we skip "for" */
2002 if (!pi->next->progs->argv)
2004 /* create list of variable values */
2005 list = make_list_in(pi->next->progs->argv,
2006 pi->progs->argv[0]);
2008 save_name = pi->progs->argv[0];
2009 pi->progs->argv[0] = NULL;
2013 free(pi->progs->argv[0]);
2017 pi->progs->argv[0] = save_name;
2018 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2021 /* insert new value from list for variable */
2022 if (pi->progs->argv[0])
2023 free(pi->progs->argv[0]);
2024 pi->progs->argv[0] = *list++;
2025 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2027 if (rmode == RES_IN)
2029 if (rmode == RES_DO) {
2033 if (rmode == RES_DONE) {
2040 if (pi->num_progs == 0)
2042 save_num_progs = pi->num_progs; /* save number of programs */
2043 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2044 rcode = run_pipe_real(pi);
2046 /* We only ran a builtin: rcode was set by the return value
2047 * of run_pipe_real(), and we don't need to wait for anything. */
2048 } else if (pi->followup == PIPE_BG) {
2049 /* XXX check bash's behavior with nontrivial pipes */
2050 /* XXX compute jobid */
2051 /* XXX what does bash do with attempts to background builtins? */
2055 rcode = EXIT_SUCCESS;
2058 if (interactive_fd) {
2059 rcode = checkjobs_and_fg_shell(pi);
2063 rcode = checkjobs(pi);
2065 debug_printf_exec(": checkjobs returned %d\n", rcode);
2067 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2068 last_return_code = rcode;
2069 pi->num_progs = save_num_progs; /* restore number of programs */
2070 if (rmode == RES_IF || rmode == RES_ELIF)
2071 next_if_code = rcode; /* can be overwritten a number of times */
2072 if (rmode == RES_WHILE)
2073 flag_rep = !last_return_code;
2074 if (rmode == RES_UNTIL)
2075 flag_rep = last_return_code;
2076 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2077 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2079 skip_more_in_this_rmode = rmode;
2086 /* ctrl-Z forked somewhere in the past, we are the child,
2087 * and now we completed running the list. Exit. */
2093 debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2097 /* return code is the exit status of the pipe */
2098 static int free_pipe(struct pipe *pi, int indent)
2101 struct child_prog *child;
2102 struct redir_struct *r, *rnext;
2103 int a, i, ret_code = 0;
2105 if (pi->stopped_progs > 0)
2107 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2108 for (i = 0; i < pi->num_progs; i++) {
2109 child = &pi->progs[i];
2110 final_printf("%s command %d:\n", indenter(indent), i);
2112 for (a = 0, p = child->argv; *p; a++, p++) {
2113 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
2115 globfree(&child->glob_result);
2117 } else if (child->group) {
2118 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2119 ret_code = free_pipe_list(child->group, indent+3);
2120 final_printf("%s end group\n", indenter(indent));
2122 final_printf("%s (nil)\n", indenter(indent));
2124 for (r = child->redirects; r; r = rnext) {
2125 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2127 /* guard against the case >$FOO, where foo is unset or blank */
2128 if (r->word.gl_pathv) {
2129 final_printf(" %s\n", *r->word.gl_pathv);
2133 final_printf("&%d\n", r->dup);
2138 child->redirects = NULL;
2140 free(pi->progs); /* children are an array, they get freed all at once */
2149 static int free_pipe_list(struct pipe *head, int indent)
2151 int rcode = 0; /* if list has no members */
2152 struct pipe *pi, *next;
2153 for (pi = head; pi; pi = next) {
2154 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2155 rcode = free_pipe(pi, indent);
2156 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
2158 /*pi->next = NULL;*/
2164 /* Select which version we will use */
2165 static int run_list(struct pipe *pi)
2168 if (fake_mode == 0) {
2169 debug_printf_exec("run_list: run_list_real with %d members\n", pi->num_progs);
2170 rcode = run_list_real(pi);
2172 /* free_pipe_list has the side effect of clearing memory
2173 * In the long run that function can be merged with run_list_real,
2174 * but doing that now would hobble the debugging effort. */
2175 free_pipe_list(pi, 0);
2179 /* The API for glob is arguably broken. This routine pushes a non-matching
2180 * string into the output structure, removing non-backslashed backslashes.
2181 * If someone can prove me wrong, by performing this function within the
2182 * original glob(3) api, feel free to rewrite this routine into oblivion.
2183 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2184 * XXX broken if the last character is '\\', check that before calling.
2186 static int globhack(const char *src, int flags, glob_t *pglob)
2191 for (cnt = 1, s = src; s && *s; s++) {
2192 if (*s == '\\') s++;
2197 return GLOB_NOSPACE;
2198 if (!(flags & GLOB_APPEND)) {
2199 pglob->gl_pathv = NULL;
2200 pglob->gl_pathc = 0;
2204 pathc = ++pglob->gl_pathc;
2205 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
2206 if (pglob->gl_pathv == NULL)
2207 return GLOB_NOSPACE;
2208 pglob->gl_pathv[pathc-1] = dest;
2209 pglob->gl_pathv[pathc] = NULL;
2210 for (s = src; s && *s; s++, dest++) {
2211 if (*s == '\\') s++;
2218 /* XXX broken if the last character is '\\', check that before calling */
2219 static int glob_needed(const char *s)
2222 if (*s == '\\') s++;
2223 if (strchr("*[?", *s)) return 1;
2228 static int xglob(o_string *dest, int flags, glob_t *pglob)
2232 /* short-circuit for null word */
2233 /* we can code this better when the debug_printf's are gone */
2234 if (dest->length == 0) {
2235 if (dest->nonnull) {
2236 /* bash man page calls this an "explicit" null */
2237 gr = globhack(dest->data, flags, pglob);
2238 debug_printf("globhack returned %d\n", gr);
2242 } else if (glob_needed(dest->data)) {
2243 gr = glob(dest->data, flags, NULL, pglob);
2244 debug_printf("glob returned %d\n", gr);
2245 if (gr == GLOB_NOMATCH) {
2246 /* quote removal, or more accurately, backslash removal */
2247 gr = globhack(dest->data, flags, pglob);
2248 debug_printf("globhack returned %d\n", gr);
2251 gr = globhack(dest->data, flags, pglob);
2252 debug_printf("globhack returned %d\n", gr);
2254 if (gr == GLOB_NOSPACE)
2255 bb_error_msg_and_die("out of memory during glob");
2256 if (gr != 0) { /* GLOB_ABORTED ? */
2257 bb_error_msg("glob(3) error %d", gr);
2259 /* globprint(glob_target); */
2263 static char **make_list_in(char **inp, char *name)
2266 int name_len = strlen(name);
2271 /* create list of variable values */
2272 list = xmalloc(sizeof(*list));
2273 for (i = 0; inp[i]; i++) {
2274 p3 = insert_var_value(inp[i]);
2281 p2 = strchr(p1, ' ');
2288 /* we use n + 2 in realloc for list, because we add
2289 * new element and then we will add NULL element */
2290 list = xrealloc(list, sizeof(*list) * (n + 2));
2291 list[n] = xmalloc(2 + name_len + len);
2292 strcpy(list[n], name);
2293 strcat(list[n], "=");
2294 strncat(list[n], p1, len);
2295 list[n++][name_len + len + 1] = '\0';
2298 if (p3 != inp[i]) free(p3);
2304 static char *insert_var_value(char *inp)
2306 int res_str_len = 0;
2309 char *p, *res_str = NULL;
2312 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2315 res_str = xrealloc(res_str, (res_str_len + len));
2316 strncpy((res_str + res_str_len), inp, len);
2320 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2322 p1 = lookup_param(inp);
2324 len = res_str_len + strlen(p1);
2325 res_str = xrealloc(res_str, (1 + len));
2326 strcpy((res_str + res_str_len), p1);
2329 *p = SPECIAL_VAR_SYMBOL;
2334 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2335 strcpy((res_str + res_str_len), inp);
2336 while ((p = strchr(res_str, '\n'))) {
2340 return (res_str == NULL) ? inp : res_str;
2343 /* This is used to get/check local shell variables */
2344 static const char *get_local_var(const char *s)
2346 struct variables *cur;
2350 for (cur = top_vars; cur; cur = cur->next)
2351 if (strcmp(cur->name, s) == 0)
2356 /* This is used to set local shell variables
2357 flg_export == 0 if only local (not exporting) variable
2358 flg_export == 1 if "new" exporting environ
2359 flg_export > 1 if current startup environ (not call putenv()) */
2360 static int set_local_var(const char *s, int flg_export)
2364 struct variables *cur;
2368 /* Assume when we enter this function that we are already in
2369 * NAME=VALUE format. So the first order of business is to
2370 * split 's' on the '=' into 'name' and 'value' */
2371 value = strchr(name, '=');
2372 /*if (value == 0 && ++value == 0) ??? -vda */
2373 if (value == NULL || value[1] == '\0') {
2379 for (cur = top_vars; cur; cur = cur->next) {
2380 if (strcmp(cur->name, name) == 0)
2385 if (strcmp(cur->value, value) == 0) {
2386 if (flg_export > 0 && cur->flg_export == 0)
2387 cur->flg_export = flg_export;
2390 } else if (cur->flg_read_only) {
2391 bb_error_msg("%s: readonly variable", name);
2394 if (flg_export > 0 || cur->flg_export > 1)
2395 cur->flg_export = 1;
2396 free((char*)cur->value);
2398 cur->value = strdup(value);
2401 cur = malloc(sizeof(struct variables));
2405 cur->name = strdup(name);
2410 struct variables *bottom = top_vars;
2411 cur->value = strdup(value);
2413 cur->flg_export = flg_export;
2414 cur->flg_read_only = 0;
2415 while (bottom->next)
2416 bottom = bottom->next;
2422 if (result == 0 && cur->flg_export == 1) {
2424 result = putenv(name);
2427 if (result > 0) /* equivalent to previous set */
2433 static void unset_local_var(const char *name)
2435 struct variables *cur, *next;
2439 for (cur = top_vars; cur; cur = cur->next) {
2440 if (strcmp(cur->name, name) == 0) {
2441 if (cur->flg_read_only) {
2442 bb_error_msg("%s: readonly variable", name);
2445 if (cur->flg_export)
2446 unsetenv(cur->name);
2447 free((char*)cur->name);
2448 free((char*)cur->value);
2450 while (next->next != cur)
2452 next->next = cur->next;
2459 static int is_assignment(const char *s)
2461 if (!s || !isalpha(*s))
2464 while (isalnum(*s) || *s == '_')
2469 /* the src parameter allows us to peek forward to a possible &n syntax
2470 * for file descriptor duplication, e.g., "2>&1".
2471 * Return code is 0 normally, 1 if a syntax error is detected in src.
2472 * Resource errors (in xmalloc) cause the process to exit */
2473 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2474 struct in_str *input)
2476 struct child_prog *child = ctx->child;
2477 struct redir_struct *redir = child->redirects;
2478 struct redir_struct *last_redir = NULL;
2480 /* Create a new redir_struct and drop it onto the end of the linked list */
2483 redir = redir->next;
2485 redir = xmalloc(sizeof(struct redir_struct));
2487 redir->word.gl_pathv = NULL;
2489 last_redir->next = redir;
2491 child->redirects = redir;
2494 redir->type = style;
2495 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2497 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2499 /* Check for a '2>&1' type redirect */
2500 redir->dup = redirect_dup_num(input);
2501 if (redir->dup == -2) return 1; /* syntax error */
2502 if (redir->dup != -1) {
2503 /* Erik had a check here that the file descriptor in question
2504 * is legit; I postpone that to "run time"
2505 * A "-" representation of "close me" shows up as a -3 here */
2506 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2508 /* We do _not_ try to open the file that src points to,
2509 * since we need to return and let src be expanded first.
2510 * Set ctx->pending_redirect, so we know what to do at the
2511 * end of the next parsed word.
2513 ctx->pending_redirect = redir;
2518 static struct pipe *new_pipe(void)
2521 pi = xzalloc(sizeof(struct pipe));
2522 /*pi->num_progs = 0;*/
2523 /*pi->progs = NULL;*/
2524 /*pi->next = NULL;*/
2525 /*pi->followup = 0; invalid */
2527 pi->r_mode = RES_NONE;
2531 static void initialize_context(struct p_context *ctx)
2534 ctx->pending_redirect = NULL;
2536 ctx->list_head = new_pipe();
2537 ctx->pipe = ctx->list_head;
2541 done_command(ctx); /* creates the memory for working child */
2544 /* normal return is 0
2545 * if a reserved word is found, and processed, return 1
2546 * should handle if, then, elif, else, fi, for, while, until, do, done.
2547 * case, function, and select are obnoxious, save those for later.
2549 static int reserved_word(o_string *dest, struct p_context *ctx)
2551 struct reserved_combo {
2556 /* Mostly a list of accepted follow-up reserved words.
2557 * FLAG_END means we are done with the sequence, and are ready
2558 * to turn the compound list into a command.
2559 * FLAG_START means the word must start a new compound list.
2561 static const struct reserved_combo reserved_list[] = {
2562 { "if", RES_IF, FLAG_THEN | FLAG_START },
2563 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2564 { "elif", RES_ELIF, FLAG_THEN },
2565 { "else", RES_ELSE, FLAG_FI },
2566 { "fi", RES_FI, FLAG_END },
2567 { "for", RES_FOR, FLAG_IN | FLAG_START },
2568 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2569 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2570 { "in", RES_IN, FLAG_DO },
2571 { "do", RES_DO, FLAG_DONE },
2572 { "done", RES_DONE, FLAG_END }
2574 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2575 const struct reserved_combo *r;
2577 for (r = reserved_list; r < reserved_list+NRES; r++) {
2578 if (strcmp(dest->data, r->literal) == 0) {
2579 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2580 if (r->flag & FLAG_START) {
2581 struct p_context *new = xmalloc(sizeof(struct p_context));
2582 debug_printf("push stack\n");
2583 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2590 *new = *ctx; /* physical copy */
2591 initialize_context(ctx);
2593 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2600 ctx->old_flag = r->flag;
2601 if (ctx->old_flag & FLAG_END) {
2602 struct p_context *old;
2603 debug_printf("pop stack\n");
2604 done_pipe(ctx, PIPE_SEQ);
2606 old->child->group = ctx->list_head;
2607 old->child->subshell = 0;
2608 *ctx = *old; /* physical copy */
2618 /* Normal return is 0.
2619 * Syntax or xglob errors return 1. */
2620 static int done_word(o_string *dest, struct p_context *ctx)
2622 struct child_prog *child = ctx->child;
2623 glob_t *glob_target;
2626 debug_printf_parse("done_word: '%s' %p\n", dest->data, child);
2627 if (dest->length == 0 && !dest->nonnull) {
2628 debug_printf_parse("done_word return 0: true null, ignored\n");
2631 if (ctx->pending_redirect) {
2632 glob_target = &ctx->pending_redirect->word;
2636 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2639 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2640 debug_printf_parse(": checking %s for reserved-ness\n", dest->data);
2641 if (reserved_word(dest, ctx)) {
2642 debug_printf_parse("done_word return %d\n", (ctx->w == RES_SNTX));
2643 return (ctx->w == RES_SNTX);
2646 glob_target = &child->glob_result;
2647 if (child->argv) flags |= GLOB_APPEND;
2649 gr = xglob(dest, flags, glob_target);
2651 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2656 if (ctx->pending_redirect) {
2657 ctx->pending_redirect = NULL;
2658 if (glob_target->gl_pathc != 1) {
2659 bb_error_msg("ambiguous redirect");
2660 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2664 child->argv = glob_target->gl_pathv;
2666 if (ctx->w == RES_FOR) {
2667 done_word(dest, ctx);
2668 done_pipe(ctx, PIPE_SEQ);
2670 debug_printf_parse("done_word return 0\n");
2674 /* The only possible error here is out of memory, in which case
2676 static int done_command(struct p_context *ctx)
2678 /* The child is really already in the pipe structure, so
2679 * advance the pipe counter and make a new, null child.
2680 * Only real trickiness here is that the uncommitted
2681 * child structure, to which ctx->child points, is not
2682 * counted in pi->num_progs. */
2683 struct pipe *pi = ctx->pipe;
2684 struct child_prog *prog = ctx->child;
2686 if (prog && prog->group == NULL
2687 && prog->argv == NULL
2688 && prog->redirects == NULL
2690 debug_printf("done_command: skipping null command\n");
2695 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2697 debug_printf("done_command: initializing\n");
2699 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2701 prog = pi->progs + pi->num_progs;
2702 memset(prog, 0, sizeof(*prog));
2703 /*prog->redirects = NULL;*/
2704 /*prog->argv = NULL; */
2705 /*prog->is_stopped = 0;*/
2706 /*prog->group = NULL;*/
2707 /*prog->glob_result.gl_pathv = NULL;*/
2711 prog->type = ctx->type;
2713 /* but ctx->pipe and ctx->list_head remain unchanged */
2717 static int done_pipe(struct p_context *ctx, pipe_style type)
2720 done_command(ctx); /* implicit closure of previous command */
2721 debug_printf_parse("done_pipe, type %d\n", type);
2722 ctx->pipe->followup = type;
2723 ctx->pipe->r_mode = ctx->w;
2725 ctx->pipe->next = new_p;
2728 done_command(ctx); /* set up new pipe to accept commands */
2732 /* peek ahead in the in_str to find out if we have a "&n" construct,
2733 * as in "2>&1", that represents duplicating a file descriptor.
2734 * returns either -2 (syntax error), -1 (no &), or the number found.
2736 static int redirect_dup_num(struct in_str *input)
2738 int ch, d = 0, ok = 0;
2740 if (ch != '&') return -1;
2742 b_getch(input); /* get the & */
2746 return -3; /* "-" represents "close me" */
2748 while (isdigit(ch)) {
2749 d = d*10 + (ch-'0');
2756 bb_error_msg("ambiguous redirect");
2760 /* If a redirect is immediately preceded by a number, that number is
2761 * supposed to tell which file descriptor to redirect. This routine
2762 * looks for such preceding numbers. In an ideal world this routine
2763 * needs to handle all the following classes of redirects...
2764 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2765 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2766 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2767 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2768 * A -1 output from this program means no valid number was found, so the
2769 * caller should use the appropriate default for this redirection.
2771 static int redirect_opt_num(o_string *o)
2777 for (num = 0; num < o->length; num++) {
2778 if (!isdigit(*(o->data + num))) {
2782 /* reuse num (and save an int) */
2783 num = atoi(o->data);
2788 static FILE *generate_stream_from_list(struct pipe *head)
2791 int pid, channel[2];
2792 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2799 bb_perror_msg_and_die("fork");
2800 } else if (pid == 0) {
2802 if (channel[1] != 1) {
2803 dup2(channel[1], 1);
2806 _exit(run_list_real(head)); /* leaks memory */
2808 debug_printf("forked child %d\n", pid);
2810 pf = fdopen(channel[0], "r");
2811 debug_printf("pipe on FILE *%p\n", pf);
2815 /* this version hacked for testing purposes */
2816 /* return code is exit status of the process that is run. */
2817 static int process_command_subs(o_string *dest, struct p_context *ctx,
2818 struct in_str *input, const char *subst_end)
2821 o_string result = NULL_O_STRING;
2822 struct p_context inner;
2824 struct in_str pipe_str;
2825 initialize_context(&inner);
2827 /* recursion to generate command */
2828 retcode = parse_stream(&result, &inner, input, subst_end);
2829 if (retcode != 0) return retcode; /* syntax error or EOF */
2830 done_word(&result, &inner);
2831 done_pipe(&inner, PIPE_SEQ);
2834 p = generate_stream_from_list(inner.list_head);
2835 if (p == NULL) return 1;
2836 mark_open(fileno(p));
2837 setup_file_in_str(&pipe_str, p);
2839 /* now send results of command back into original context */
2840 retcode = parse_stream(dest, ctx, &pipe_str, NULL);
2841 /* XXX In case of a syntax error, should we try to kill the child?
2842 * That would be tough to do right, so just read until EOF. */
2844 while (b_getch(&pipe_str) != EOF)
2848 debug_printf("done reading from pipe, pclose()ing\n");
2849 /* This is the step that wait()s for the child. Should be pretty
2850 * safe, since we just read an EOF from its stdout. We could try
2851 * to better, by using wait(), and keeping track of background jobs
2852 * at the same time. That would be a lot of work, and contrary
2853 * to the KISS philosophy of this program. */
2854 mark_closed(fileno(p));
2855 retcode = pclose(p);
2856 free_pipe_list(inner.list_head, 0);
2857 debug_printf("pclosed, retcode=%d\n", retcode);
2858 /* XXX this process fails to trim a single trailing newline */
2862 static int parse_group(o_string *dest, struct p_context *ctx,
2863 struct in_str *input, int ch)
2866 const char *endch = NULL;
2867 struct p_context sub;
2868 struct child_prog *child = ctx->child;
2870 debug_printf_parse("parse_group entered\n");
2873 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
2876 initialize_context(&sub);
2880 child->subshell = 1;
2886 syntax(); /* really logic error */
2888 rcode = parse_stream(dest, &sub, input, endch);
2889 done_word(dest, &sub); /* finish off the final word in the subcontext */
2890 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2891 child->group = sub.list_head;
2893 debug_printf_parse("parse_group return %d\n", rcode);
2895 /* child remains "open", available for possible redirects */
2898 /* basically useful version until someone wants to get fancier,
2899 * see the bash man page under "Parameter Expansion" */
2900 static const char *lookup_param(const char *src)
2902 const char *p = NULL;
2906 p = get_local_var(src);
2911 /* Make new string for parser */
2912 static char* make_string(char ** inp)
2919 for (n = 0; inp[n]; n++) {
2920 p = insert_var_value(inp[n]);
2921 str = xrealloc(str, (len + strlen(p)));
2928 len = strlen(str) + 3;
2929 if (p != inp[n]) free(p);
2937 /* return code: 0 for OK, 1 for syntax error */
2938 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2942 int ch = input->peek(input); /* first character after the $ */
2943 debug_printf("handle_dollar: ch=%c\n", ch);
2945 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2947 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2951 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2952 } else if (isdigit(ch)) {
2953 i = ch - '0'; /* XXX is $0 special? */
2954 if (i < global_argc) {
2955 parse_string(dest, ctx, global_argv[i]); /* recursion */
2958 } else switch (ch) {
2960 b_adduint(dest, getpid());
2964 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2968 b_adduint(dest, last_return_code);
2972 b_adduint(dest, global_argc ? global_argc-1 : 0);
2976 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2979 /* XXX maybe someone will try to escape the '}' */
2981 ch = b_getch(input);
2982 if (ch == EOF || ch == '}')
2990 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2994 process_command_subs(dest, ctx, input, ")");
2998 for (i = 1; i < global_argc; i++) {
2999 parse_string(dest, ctx, global_argv[i]);
3000 if (i+1 < global_argc)
3001 parse_string(dest, ctx, sep);
3007 /* still unhandled, but should be eventually */
3008 bb_error_msg("unhandled syntax: $%c", ch);
3012 b_addqchr(dest,'$', dest->quote);
3014 /* Eat the character if the flag was set. If the compiler
3015 * is smart enough, we could substitute "b_getch(input);"
3016 * for all the "advance = 1;" above, and also end up with
3017 * a nice size-optimized program. Hah! That'll be the day.
3019 if (advance) b_getch(input);
3023 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
3026 setup_string_in_str(&foo, src);
3027 return parse_stream(dest, ctx, &foo, NULL);
3030 /* return code is 0 for normal exit, 1 for syntax error */
3031 static int parse_stream(o_string *dest, struct p_context *ctx,
3032 struct in_str *input, const char *end_trigger)
3036 redir_type redir_style;
3039 /* Only double-quote state is handled in the state variable dest->quote.
3040 * A single-quote triggers a bypass of the main loop until its mate is
3041 * found. When recursing, quote state is passed in via dest->quote. */
3043 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3045 while ((ch = b_getch(input)) != EOF) {
3047 next = (ch == '\n') ? 0 : b_peek(input);
3048 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3049 ch, ch, m, dest->quote);
3050 if (m == MAP_ORDINARY
3051 || (m != MAP_NEVER_FLOWTROUGH && dest->quote)
3053 b_addqchr(dest, ch, dest->quote);
3056 if (m == MAP_IFS_IF_UNQUOTED) {
3057 if (done_word(dest, ctx)) {
3058 debug_printf_parse("parse_stream return 1\n");
3061 /* If we aren't performing a substitution, treat
3062 * a newline as a command separator.
3063 * [why we don't handle it exactly like ';'? --vda] */
3064 if (end_trigger && ch == '\n') {
3065 done_pipe(ctx, PIPE_SEQ);
3068 if ((end_trigger && strchr(end_trigger, ch))
3069 && !dest->quote && ctx->w == RES_NONE
3071 debug_printf_parse("parse_stream return 0\n");
3074 if (m == MAP_IFS_IF_UNQUOTED)
3078 if (dest->length == 0 && !dest->quote) {
3081 if (ch == EOF || ch == '\n')
3086 b_addqchr(dest, ch, dest->quote);
3092 debug_printf_parse("parse_stream return 1\n");
3095 b_addqchr(dest, '\\', dest->quote);
3096 b_addqchr(dest, b_getch(input), dest->quote);
3099 if (handle_dollar(dest, ctx, input) != 0) {
3100 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3107 ch = b_getch(input);
3108 if (ch == EOF || ch == '\'')
3114 debug_printf_parse("parse_stream return 1\n");
3120 dest->quote = !dest->quote;
3123 process_command_subs(dest, ctx, input, "`");
3126 redir_fd = redirect_opt_num(dest);
3127 done_word(dest, ctx);
3128 redir_style = REDIRECT_OVERWRITE;
3130 redir_style = REDIRECT_APPEND;
3132 } else if (next == '(') {
3133 syntax(); /* until we support >(list) Process Substitution */
3134 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3137 setup_redirect(ctx, redir_fd, redir_style, input);
3140 redir_fd = redirect_opt_num(dest);
3141 done_word(dest, ctx);
3142 redir_style = REDIRECT_INPUT;
3144 redir_style = REDIRECT_HEREIS;
3146 } else if (next == '>') {
3147 redir_style = REDIRECT_IO;
3149 } else if (next == '(') {
3150 syntax(); /* until we support <(list) Process Substitution */
3151 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3154 setup_redirect(ctx, redir_fd, redir_style, input);
3157 done_word(dest, ctx);
3158 done_pipe(ctx, PIPE_SEQ);
3161 done_word(dest, ctx);
3164 done_pipe(ctx, PIPE_AND);
3166 done_pipe(ctx, PIPE_BG);
3170 done_word(dest, ctx);
3173 done_pipe(ctx, PIPE_OR);
3175 /* we could pick up a file descriptor choice here
3176 * with redirect_opt_num(), but bash doesn't do it.
3177 * "echo foo 2| cat" yields "foo 2". */
3183 if (parse_group(dest, ctx, input, ch) != 0) {
3184 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3190 syntax(); /* Proper use of this character is caught by end_trigger */
3191 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3194 syntax(); /* this is really an internal logic error */
3195 debug_printf_parse("parse_stream return 1: internal logic error\n");
3199 /* Complain if quote? No, maybe we just finished a command substitution
3200 * that was quoted. Example:
3201 * $ echo "`cat foo` plus more"
3202 * and we just got the EOF generated by the subshell that ran "cat foo"
3203 * The only real complaint is if we got an EOF when end_trigger != NULL,
3204 * that is, we were really supposed to get end_trigger, and never got
3205 * one before the EOF. Can't use the standard "syntax error" return code,
3206 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3207 debug_printf_parse("parse_stream return -%d\n", end_trigger != NULL);
3213 static void mapset(const char *set, int code)
3216 map[(unsigned char)*set++] = code;
3219 static void update_ifs_map(void)
3221 /* char *ifs and char map[256] are both globals. */
3222 ifs = getenv("IFS");
3223 if (ifs == NULL) ifs = " \t\n";
3224 /* Precompute a list of 'flow through' behavior so it can be treated
3225 * quickly up front. Computation is necessary because of IFS.
3226 * Special case handling of IFS == " \t\n" is not implemented.
3227 * The map[] array only really needs two bits each, and on most machines
3228 * that would be faster because of the reduced L1 cache footprint.
3230 memset(map, MAP_ORDINARY, sizeof(map)); /* most chars flow through always */
3231 mapset("\\$'\"`", MAP_NEVER_FLOWTROUGH);
3232 mapset("<>;&|(){}#", MAP_FLOWTROUGH_IF_QUOTED);
3233 mapset(ifs, MAP_IFS_IF_UNQUOTED); /* also flow through if quoted */
3236 /* most recursion does not come through here, the exception is
3237 * from builtin_source() */
3238 static int parse_stream_outer(struct in_str *inp, int flag)
3240 // FIXME: '{ true | exit 3; echo $? }' is parsed as a whole,
3241 // as a result $? is replaced by 0, not 3!
3242 // Need to stop & execute stuff at ';', not parse till EOL!
3244 struct p_context ctx;
3245 o_string temp = NULL_O_STRING;
3249 initialize_context(&ctx);
3251 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
3252 mapset(";$&|", MAP_ORDINARY);
3253 #if ENABLE_HUSH_INTERACTIVE
3254 inp->promptmode = 1;
3256 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3257 if (rcode != 1 && ctx.old_flag != 0) {
3260 if (rcode != 1 && ctx.old_flag == 0) {
3261 done_word(&temp, &ctx);
3262 done_pipe(&ctx, PIPE_SEQ);
3263 debug_printf_exec("parse_stream_outer: run_list\n");
3264 debug_print_tree(ctx.list_head, 0);
3265 run_list(ctx.list_head);
3267 if (ctx.old_flag != 0) {
3274 free_pipe_list(ctx.list_head, 0);
3277 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3281 static int parse_string_outer(const char *s, int flag)
3283 struct in_str input;
3284 setup_string_in_str(&input, s);
3285 return parse_stream_outer(&input, flag);
3288 static int parse_file_outer(FILE *f)
3291 struct in_str input;
3292 setup_file_in_str(&input, f);
3293 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3298 /* Make sure we have a controlling tty. If we get started under a job
3299 * aware app (like bash for example), make sure we are now in charge so
3300 * we don't fight over who gets the foreground */
3301 static void setup_job_control(void)
3305 saved_task_pgrp = shell_pgrp = getpgrp();
3306 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
3307 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3309 /* If we were ran as 'hush &',
3310 * sleep until we are in the foreground. */
3311 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3312 /* Send TTIN to ourself (should stop us) */
3313 kill(- shell_pgrp, SIGTTIN);
3314 shell_pgrp = getpgrp();
3317 /* Ignore job-control and misc signals. */
3318 set_jobctrl_sighandler(SIG_IGN);
3319 set_misc_sighandler(SIG_IGN);
3320 //huh? signal(SIGCHLD, SIG_IGN);
3322 /* We _must_ restore tty pgrp fatal signals */
3323 set_fatal_sighandler(sigexit);
3325 /* Put ourselves in our own process group. */
3326 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3327 /* Grab control of the terminal. */
3328 tcsetpgrp(interactive_fd, getpid());
3332 int hush_main(int argc, char **argv);
3333 int hush_main(int argc, char **argv)
3339 #if ENABLE_FEATURE_EDITING
3340 line_input_state = new_line_input_t(FOR_SHELL);
3343 /* XXX what should these be while sourcing /etc/profile? */
3347 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3348 * hush_main(), therefore we cannot rely on the BSS to zero out this
3349 * stuff. Reset these to 0 every time. */
3351 /* map[] is taken care of with call to update_ifs_map() */
3353 close_me_head = NULL;
3354 #if ENABLE_HUSH_INTERACTIVE
3363 /* Initialize some more globals to non-zero values */
3365 #if ENABLE_HUSH_INTERACTIVE
3366 #if ENABLE_FEATURE_EDITING
3367 cmdedit_set_initial_prompt();
3373 /* initialize our shell local variables with the values
3374 * currently living in the environment */
3378 set_local_var(*e++, 2); /* without call putenv() */
3380 last_return_code = EXIT_SUCCESS;
3382 if (argv[0] && argv[0][0] == '-') {
3383 debug_printf("\nsourcing /etc/profile\n");
3384 input = fopen("/etc/profile", "r");
3385 if (input != NULL) {
3386 mark_open(fileno(input));
3387 parse_file_outer(input);
3388 mark_closed(fileno(input));
3394 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3397 global_argv = argv + optind;
3398 global_argc = argc - optind;
3399 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3402 // Well, we cannot just declare interactiveness,
3403 // we have to have some stuff (ctty, etc)
3404 /*interactive_fd++;*/
3411 fprintf(stderr, "Usage: sh [FILE]...\n"
3412 " or: sh -c command [args]...\n\n");
3420 /* A shell is interactive if the '-i' flag was given, or if all of
3421 * the following conditions are met:
3423 * no arguments remaining or the -s flag given
3424 * standard input is a terminal
3425 * standard output is a terminal
3426 * Refer to Posix.2, the description of the 'sh' utility. */
3427 if (argv[optind] == NULL && input == stdin
3428 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3430 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3431 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3432 if (saved_tty_pgrp >= 0) {
3433 /* try to dup to high fd#, >= 255 */
3434 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3435 if (interactive_fd < 0) {
3436 /* try to dup to any fd */
3437 interactive_fd = dup(STDIN_FILENO);
3438 if (interactive_fd < 0)
3442 // TODO: track & disallow any attempts of user
3443 // to (inadvertently) close/redirect it
3446 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3447 if (interactive_fd) {
3448 /* Looks like they want an interactive shell */
3449 setup_job_control();
3450 /* Make xfuncs do cleanup on exit */
3451 die_sleep = -1; /* flag */
3452 if (setjmp(die_jmp)) {
3453 /* xfunc has failed! die die die */
3454 hush_exit(xfunc_error_retval);
3456 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3457 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3458 printf("Enter 'help' for a list of built-in commands.\n\n");
3461 #elif ENABLE_HUSH_INTERACTIVE
3462 /* no job control compiled, only prompt/line editing */
3463 if (argv[optind] == NULL && input == stdin
3464 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3466 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3467 if (interactive_fd < 0) {
3468 /* try to dup to any fd */
3469 interactive_fd = dup(STDIN_FILENO);
3470 if (interactive_fd < 0)
3478 if (argv[optind] == NULL) {
3479 opt = parse_file_outer(stdin);
3483 debug_printf("\nrunning script '%s'\n", argv[optind]);
3484 global_argv = argv + optind;
3485 global_argc = argc - optind;
3486 input = xfopen(argv[optind], "r");
3487 opt = parse_file_outer(input);
3489 #if ENABLE_FEATURE_CLEAN_UP
3491 if (cwd != bb_msg_unknown)
3494 struct variables *cur, *tmp;
3495 for (cur = top_vars; cur; cur = tmp) {
3497 if (!cur->flg_read_only) {
3498 free((char*)cur->name);
3499 free((char*)cur->value);
3507 hush_exit(opt ? opt : last_return_code);