1 /* vi: set sw=4 ts=4: */
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen
26 * miscellaneous bugfixes from Matt Kraai
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy (improved --vda)
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change charmap[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
83 /* #include <dmalloc.h> */
84 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
87 /* If you comment out one of these below, it will be #defined later
88 * to perform debug printfs to stderr: */
89 #define debug_printf(...) do {} while (0)
90 /* Finer-grained debug switches */
91 #define debug_printf_parse(...) do {} while (0)
92 #define debug_print_tree(a, b) do {} while (0)
93 #define debug_printf_exec(...) do {} while (0)
94 #define debug_printf_jobs(...) do {} while (0)
95 #define debug_printf_expand(...) do {} while (0)
96 #define debug_printf_clean(...) do {} while (0)
99 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
102 #ifndef debug_printf_parse
103 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
106 #ifndef debug_printf_exec
107 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
110 #ifndef debug_printf_jobs
111 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
112 #define DEBUG_SHELL_JOBS 1
115 #ifndef debug_printf_expand
116 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
117 #define DEBUG_EXPAND 1
120 #ifndef debug_printf_clean
121 /* broken, of course, but OK for testing */
122 static const char *indenter(int i)
124 static const char blanks[] = " ";
125 return &blanks[sizeof(blanks) - i - 1];
127 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
128 #define DEBUG_CLEAN 1
132 #if !ENABLE_HUSH_INTERACTIVE
133 #undef ENABLE_FEATURE_EDITING
134 #define ENABLE_FEATURE_EDITING 0
135 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
136 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
139 #define SPECIAL_VAR_SYMBOL 3
140 #define FLAG_EXIT_FROM_LOOP 1
141 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
142 #define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
146 REDIRECT_OVERWRITE = 2,
152 /* The descrip member of this structure is only used to make debugging
154 static const struct {
156 signed char default_fd;
160 { O_RDONLY, 0, "<" },
161 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
162 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
163 { O_RDONLY, -1, "<<" },
174 /* might eventually control execution */
192 FLAG_END = (1 << RES_NONE ),
193 FLAG_IF = (1 << RES_IF ),
194 FLAG_THEN = (1 << RES_THEN ),
195 FLAG_ELIF = (1 << RES_ELIF ),
196 FLAG_ELSE = (1 << RES_ELSE ),
197 FLAG_FI = (1 << RES_FI ),
198 FLAG_FOR = (1 << RES_FOR ),
199 FLAG_WHILE = (1 << RES_WHILE),
200 FLAG_UNTIL = (1 << RES_UNTIL),
201 FLAG_DO = (1 << RES_DO ),
202 FLAG_DONE = (1 << RES_DONE ),
203 FLAG_IN = (1 << RES_IN ),
204 FLAG_START = (1 << RES_XXXX ),
207 /* This holds pointers to the various results of parsing */
209 struct child_prog *child;
210 struct pipe *list_head;
212 struct redir_struct *pending_redirect;
213 reserved_style res_w;
214 int old_flag; /* for figuring out valid reserved words */
215 struct p_context *stack;
216 int parse_type; /* define type of parser : ";$" common or special symbol */
217 /* How about quoting status? */
220 struct redir_struct {
221 struct redir_struct *next; /* pointer to the next redirect in the list */
222 redir_type type; /* type of redirection */
223 int fd; /* file descriptor being redirected */
224 int dup; /* -1, or file descriptor being duplicated */
225 glob_t word; /* *word.gl_pathv is the filename */
229 pid_t pid; /* 0 if exited */
230 char **argv; /* program name and arguments */
231 struct pipe *group; /* if non-NULL, first in group or subshell */
232 int subshell; /* flag, non-zero if group must be forked */
233 struct redir_struct *redirects; /* I/O redirections */
234 glob_t glob_result; /* result of parameter globbing */
235 int is_stopped; /* is the program currently running? */
236 struct pipe *family; /* pointer back to the child's parent pipe */
237 //sp counting seems to be broken... so commented out, grep for '//sp:'
238 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
241 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
242 * and on execution these are substituted with their values.
243 * Substitution can make _several_ words out of one argv[n]!
244 * Example: argv[0]=='.^C*^C.' here: echo .$*.
249 int num_progs; /* total number of programs in job */
250 int running_progs; /* number of programs running (not exited) */
251 char *cmdbuf; /* buffer various argv's point into */
253 int jobid; /* job number */
254 char *cmdtext; /* name of job */
255 pid_t pgrp; /* process group ID for the job */
257 struct child_prog *progs; /* array of commands in pipe */
258 int stopped_progs; /* number of programs alive, but stopped */
259 int job_context; /* bitmask defining current context */
260 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
261 reserved_style r_mode; /* supports if, for, while, until */
265 struct close_me *next;
270 struct variables *next;
284 #define NULL_O_STRING {NULL,0,0,0,0}
285 /* used for initialization: o_string foo = NULL_O_STRING; */
287 /* I can almost use ordinary FILE *. Is open_memstream() universally
288 * available? Where is it documented? */
291 /* eof_flag=1: last char in ->p is really an EOF */
292 char eof_flag; /* meaningless if ->p == NULL */
294 #if ENABLE_HUSH_INTERACTIVE
299 int (*get) (struct in_str *);
300 int (*peek) (struct in_str *);
302 #define b_getch(input) ((input)->get(input))
303 #define b_peek(input) ((input)->peek(input))
307 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
308 CHAR_IFS = 2, /* treated as ordinary if quoted */
309 CHAR_SPECIAL = 3, /* example: $ */
313 /* "Globals" within this file */
315 #define HUSH_VER_STR "0.02"
316 static const struct variables const_shell_ver = {
317 NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1
320 /* Sorted roughly by size (smaller offsets == smaller code) */
322 #if ENABLE_HUSH_INTERACTIVE
323 /* 'interactive_fd' is a fd# open to ctty, if we have one
324 * _AND_ if we decided to act interactively */
329 #if ENABLE_FEATURE_EDITING
330 line_input_t *line_input_state;
334 pid_t saved_task_pgrp;
335 pid_t saved_tty_pgrp;
337 struct pipe *job_list;
338 struct pipe *toplevel_list;
339 smallint ctrl_z_flag;
342 /* these three support $?, $#, and $1 */
345 int last_return_code;
347 struct close_me *close_me_head;
349 unsigned last_bg_pid;
350 struct variables *top_vars; /* = &shell_ver (both are set in main()) */
351 struct variables shell_ver; /* = const_shell_ver */
352 #if ENABLE_FEATURE_SH_STANDALONE
353 struct nofork_save_area nofork_save;
356 sigjmp_buf toplevel_jb;
358 unsigned char charmap[256];
359 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
362 #define G (*ptr_to_globals)
364 #if !ENABLE_HUSH_INTERACTIVE
365 enum { interactive_fd = 0 };
368 enum { run_list_level = 0 };
371 #if ENABLE_HUSH_INTERACTIVE
372 #define interactive_fd (G.interactive_fd )
376 #if ENABLE_FEATURE_EDITING
377 #define line_input_state (G.line_input_state)
380 #define run_list_level (G.run_list_level )
381 #define saved_task_pgrp (G.saved_task_pgrp )
382 #define saved_tty_pgrp (G.saved_tty_pgrp )
383 #define last_jobid (G.last_jobid )
384 #define job_list (G.job_list )
385 #define toplevel_list (G.toplevel_list )
386 #define toplevel_jb (G.toplevel_jb )
387 #define ctrl_z_flag (G.ctrl_z_flag )
389 #define global_argv (G.global_argv )
390 #define global_argc (G.global_argc )
391 #define last_return_code (G.last_return_code)
393 #define fake_mode (G.fake_mode )
394 #define close_me_head (G.close_me_head )
396 #define last_bg_pid (G.last_bg_pid )
397 #define top_vars (G.top_vars )
398 #define shell_ver (G.shell_ver )
399 #if ENABLE_FEATURE_SH_STANDALONE
400 #define nofork_save (G.nofork_save )
403 #define toplevel_jb (G.toplevel_jb )
405 #define charmap (G.charmap )
406 #define user_input_buf (G.user_input_buf )
411 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
413 static void __syntax(int line)
415 bb_error_msg("syntax error hush.c:%d", line);
417 #define syntax() __syntax(__LINE__)
419 /* Index of subroutines: */
420 /* function prototypes for builtins */
421 static int builtin_cd(char **argv);
422 static int builtin_eval(char **argv);
423 static int builtin_exec(char **argv);
424 static int builtin_exit(char **argv);
425 static int builtin_export(char **argv);
427 static int builtin_fg_bg(char **argv);
428 static int builtin_jobs(char **argv);
430 static int builtin_help(char **argv);
431 static int builtin_pwd(char **argv);
432 static int builtin_read(char **argv);
433 static int builtin_set(char **argv);
434 static int builtin_shift(char **argv);
435 static int builtin_source(char **argv);
436 static int builtin_umask(char **argv);
437 static int builtin_unset(char **argv);
438 static int builtin_not_written(char **argv);
439 /* o_string manipulation: */
440 static int b_check_space(o_string *o, int len);
441 static int b_addchr(o_string *o, int ch);
442 static void b_reset(o_string *o);
443 static int b_addqchr(o_string *o, int ch, int quote);
444 /* in_str manipulations: */
445 static int static_get(struct in_str *i);
446 static int static_peek(struct in_str *i);
447 static int file_get(struct in_str *i);
448 static int file_peek(struct in_str *i);
449 static void setup_file_in_str(struct in_str *i, FILE *f);
450 static void setup_string_in_str(struct in_str *i, const char *s);
451 /* close_me manipulations: */
452 static void mark_open(int fd);
453 static void mark_closed(int fd);
454 static void close_all(void);
455 /* "run" the final data structures: */
456 #if !defined(DEBUG_CLEAN)
457 #define free_pipe_list(head, indent) free_pipe_list(head)
458 #define free_pipe(pi, indent) free_pipe(pi)
460 static int free_pipe_list(struct pipe *head, int indent);
461 static int free_pipe(struct pipe *pi, int indent);
462 /* really run the final data structures: */
463 static int setup_redirects(struct child_prog *prog, int squirrel[]);
464 static int run_list_real(struct pipe *pi);
465 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
466 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
467 static int run_pipe_real(struct pipe *pi);
468 /* extended glob support: */
469 static int globhack(const char *src, int flags, glob_t *pglob);
470 static int glob_needed(const char *s);
471 static int xglob(o_string *dest, int flags, glob_t *pglob);
472 /* variable assignment: */
473 static int is_assignment(const char *s);
474 /* data structure manipulation: */
475 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
476 static void initialize_context(struct p_context *ctx);
477 static int done_word(o_string *dest, struct p_context *ctx);
478 static int done_command(struct p_context *ctx);
479 static int done_pipe(struct p_context *ctx, pipe_style type);
480 /* primary string parsing: */
481 static int redirect_dup_num(struct in_str *input);
482 static int redirect_opt_num(o_string *o);
483 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
484 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
485 static const char *lookup_param(const char *src);
486 static char *make_string(char **inp);
487 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
488 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
490 static int parse_stream_outer(struct in_str *inp, int parse_flag);
491 static int parse_string_outer(const char *s, int parse_flag);
492 static int parse_file_outer(FILE *f);
493 /* job management: */
494 static int checkjobs(struct pipe* fg_pipe);
496 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
497 static void insert_bg_job(struct pipe *pi);
498 static void remove_bg_job(struct pipe *pi);
499 static void delete_finished_bg_job(struct pipe *pi);
501 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
503 /* local variable support */
504 static char **expand_variables_to_list(char **argv);
505 /* used for expansion of right hand of assignments */
506 static char *expand_variables_to_string(const char *str);
507 static const char *get_local_var(const char *var);
508 static int set_local_var(const char *s, int flg_export);
509 static void unset_local_var(const char *name);
511 /* Table of built-in functions. They can be forked or not, depending on
512 * context: within pipes, they fork. As simple commands, they do not.
513 * When used in non-forking context, they can change global variables
514 * in the parent shell process. If forked, of course they cannot.
515 * For example, 'unset foo | whatever' will parse and run, but foo will
516 * still be set at the end. */
517 struct built_in_command {
518 const char *cmd; /* name */
519 const char *descr; /* description */
520 int (*function) (char **argv); /* function ptr */
523 static const struct built_in_command bltins[] = {
525 { "bg", "Resume a job in the background", builtin_fg_bg },
527 { "break", "Exit for, while or until loop", builtin_not_written },
528 { "cd", "Change working directory", builtin_cd },
529 { "continue", "Continue for, while or until loop", builtin_not_written },
530 { "eval", "Construct and run shell command", builtin_eval },
531 { "exec", "Exec command, replacing this shell with the exec'd process",
533 { "exit", "Exit from shell()", builtin_exit },
534 { "export", "Set environment variable", builtin_export },
536 { "fg", "Bring job into the foreground", builtin_fg_bg },
537 { "jobs", "Lists the active jobs", builtin_jobs },
539 { "pwd", "Print current directory", builtin_pwd },
540 { "read", "Input environment variable", builtin_read },
541 { "return", "Return from a function", builtin_not_written },
542 { "set", "Set/unset shell local variables", builtin_set },
543 { "shift", "Shift positional parameters", builtin_shift },
544 { "trap", "Trap signals", builtin_not_written },
545 { "ulimit","Controls resource limits", builtin_not_written },
546 { "umask","Sets file creation mask", builtin_umask },
547 { "unset", "Unset environment variable", builtin_unset },
548 { ".", "Source-in and run commands in a file", builtin_source },
549 { "help", "List shell built-in commands", builtin_help },
556 static void signal_SA_RESTART(int sig, void (*handler)(int))
559 sa.sa_handler = handler;
560 sa.sa_flags = SA_RESTART;
561 sigemptyset(&sa.sa_mask);
562 sigaction(sig, &sa, NULL);
565 /* Signals are grouped, we handle them in batches */
566 static void set_fatal_sighandler(void (*handler)(int))
568 signal(SIGILL , handler);
569 signal(SIGTRAP, handler);
570 signal(SIGABRT, handler);
571 signal(SIGFPE , handler);
572 signal(SIGBUS , handler);
573 signal(SIGSEGV, handler);
574 /* bash 3.2 seems to handle these just like 'fatal' ones */
575 signal(SIGHUP , handler);
576 signal(SIGPIPE, handler);
577 signal(SIGALRM, handler);
579 static void set_jobctrl_sighandler(void (*handler)(int))
581 signal(SIGTSTP, handler);
582 signal(SIGTTIN, handler);
583 signal(SIGTTOU, handler);
585 static void set_misc_sighandler(void (*handler)(int))
587 signal(SIGINT , handler);
588 signal(SIGQUIT, handler);
589 signal(SIGTERM, handler);
591 /* SIGCHLD is special and handled separately */
593 static void set_every_sighandler(void (*handler)(int))
595 set_fatal_sighandler(handler);
596 set_jobctrl_sighandler(handler);
597 set_misc_sighandler(handler);
598 signal(SIGCHLD, handler);
601 static void handler_ctrl_c(int sig)
603 debug_printf_jobs("got sig %d\n", sig);
604 // as usual we can have all kinds of nasty problems with leaked malloc data here
605 siglongjmp(toplevel_jb, 1);
608 static void handler_ctrl_z(int sig)
612 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
614 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
617 if (!pid) { /* child */
619 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
620 set_every_sighandler(SIG_DFL);
621 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
622 debug_printf_jobs("returning in child\n");
623 /* return to nofork, it will eventually exit now,
624 * not return back to shell */
628 /* finish filling up pipe info */
629 toplevel_list->pgrp = pid; /* child is in its own pgrp */
630 toplevel_list->progs[0].pid = pid;
631 /* parent needs to longjmp out of running nofork.
632 * we will "return" exitcode 0, with child put in background */
633 // as usual we can have all kinds of nasty problems with leaked malloc data here
634 debug_printf_jobs("siglongjmp in parent\n");
635 siglongjmp(toplevel_jb, 1);
638 /* Restores tty foreground process group, and exits.
639 * May be called as signal handler for fatal signal
640 * (will faithfully resend signal to itself, producing correct exit state)
641 * or called directly with -EXITCODE.
642 * We also call it if xfunc is exiting. */
643 static void sigexit(int sig) ATTRIBUTE_NORETURN;
644 static void sigexit(int sig)
648 /* Disable all signals: job control, SIGPIPE, etc. */
649 sigfillset(&block_all);
650 sigprocmask(SIG_SETMASK, &block_all, NULL);
653 tcsetpgrp(interactive_fd, saved_tty_pgrp);
655 /* Not a signal, just exit */
659 /* Enable only this sig and kill ourself with it */
660 signal(sig, SIG_DFL);
661 sigdelset(&block_all, sig);
662 sigprocmask(SIG_SETMASK, &block_all, NULL);
664 _exit(1); /* Should not reach it */
667 /* Restores tty foreground process group, and exits. */
668 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
669 static void hush_exit(int exitcode)
671 fflush(NULL); /* flush all streams */
672 sigexit(- (exitcode & 0xff));
677 #define set_fatal_sighandler(handler) ((void)0)
678 #define set_jobctrl_sighandler(handler) ((void)0)
679 #define set_misc_sighandler(handler) ((void)0)
680 #define hush_exit(e) exit(e)
685 static const char *set_cwd(void)
687 if (cwd == bb_msg_unknown)
688 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
689 cwd = xrealloc_getcwd_or_warn((char *)cwd);
691 cwd = bb_msg_unknown;
695 /* built-in 'eval' handler */
696 static int builtin_eval(char **argv)
699 int rcode = EXIT_SUCCESS;
702 str = make_string(argv + 1);
703 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
704 FLAG_PARSE_SEMICOLON);
706 rcode = last_return_code;
711 /* built-in 'cd <path>' handler */
712 static int builtin_cd(char **argv)
716 newdir = getenv("HOME");
720 printf("cd: %s: %s\n", newdir, strerror(errno));
727 /* built-in 'exec' handler */
728 static int builtin_exec(char **argv)
731 return EXIT_SUCCESS; /* Really? */
732 pseudo_exec_argv(argv + 1);
736 /* built-in 'exit' handler */
737 static int builtin_exit(char **argv)
739 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
740 //puts("exit"); /* bash does it */
741 // TODO: warn if we have background jobs: "There are stopped jobs"
742 // On second consecutive 'exit', exit anyway.
745 hush_exit(last_return_code);
746 /* mimic bash: exit 123abc == exit 255 + error msg */
747 xfunc_error_retval = 255;
748 /* bash: exit -2 == exit 254, no error msg */
749 hush_exit(xatoi(argv[1]) & 0xff);
752 /* built-in 'export VAR=value' handler */
753 static int builtin_export(char **argv)
756 char *name = argv[1];
760 // ash emits: export VAR='VAL'
761 // bash: declare -x VAR="VAL"
762 // (both also escape as needed (quotes, $, etc))
770 name = xstrdup(name);
772 const char *value = strchr(name, '=');
776 /* They are exporting something without an =VALUE */
778 value = get_local_var(name);
780 size_t ln = strlen(name);
782 tmp = xrealloc(name, ln+strlen(value)+2);
783 sprintf(tmp+ln, "=%s", value);
786 /* bash does not return an error when trying to export
787 * an undefined variable. Do likewise. */
793 bb_perror_msg("export");
795 res = set_local_var(name, 1);
803 /* built-in 'fg' and 'bg' handler */
804 static int builtin_fg_bg(char **argv)
811 /* If they gave us no args, assume they want the last backgrounded task */
813 for (pi = job_list; pi; pi = pi->next) {
814 if (pi->jobid == last_jobid) {
818 bb_error_msg("%s: no current job", argv[0]);
821 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
822 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
825 for (pi = job_list; pi; pi = pi->next) {
826 if (pi->jobid == jobnum) {
830 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
833 // TODO: bash prints a string representation
834 // of job being foregrounded (like "sleep 1 | cat")
835 if (*argv[0] == 'f') {
836 /* Put the job into the foreground. */
837 tcsetpgrp(interactive_fd, pi->pgrp);
840 /* Restart the processes in the job */
841 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
842 for (i = 0; i < pi->num_progs; i++) {
843 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
844 pi->progs[i].is_stopped = 0;
846 pi->stopped_progs = 0;
848 i = kill(- pi->pgrp, SIGCONT);
850 if (errno == ESRCH) {
851 delete_finished_bg_job(pi);
854 bb_perror_msg("kill (SIGCONT)");
858 if (*argv[0] == 'f') {
860 return checkjobs_and_fg_shell(pi);
866 /* built-in 'help' handler */
867 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
869 const struct built_in_command *x;
871 printf("\nBuilt-in commands:\n");
872 printf("-------------------\n");
873 for (x = bltins; x->cmd; x++) {
874 if (x->descr == NULL)
876 printf("%s\t%s\n", x->cmd, x->descr);
883 /* built-in 'jobs' handler */
884 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
887 const char *status_string;
889 for (job = job_list; job; job = job->next) {
890 if (job->running_progs == job->stopped_progs)
891 status_string = "Stopped";
893 status_string = "Running";
895 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
901 /* built-in 'pwd' handler */
902 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
908 /* built-in 'read VAR' handler */
909 static int builtin_read(char **argv)
913 const char *name = argv[1] ? argv[1] : "REPLY";
914 int name_len = strlen(name);
916 if (name_len >= sizeof(string) - 2)
918 strcpy(string, name);
919 p = string + name_len;
921 *p = '\0'; /* In case stdin has only EOF */
922 /* read string. name_len+1 chars are already used by 'name=' */
923 fgets(p, sizeof(string) - 1 - name_len, stdin);
925 return set_local_var(string, 0);
928 /* built-in 'set [VAR=value]' handler */
929 static int builtin_set(char **argv)
931 char *temp = argv[1];
935 for (e = top_vars; e; e = e->next)
936 printf("%s=%s\n", e->name, e->value);
938 set_local_var(temp, 0);
944 /* Built-in 'shift' handler */
945 static int builtin_shift(char **argv)
951 if (n >= 0 && n < global_argc) {
952 /* XXX This probably breaks $0 */
960 /* Built-in '.' handler (read-in and execute commands from file) */
961 static int builtin_source(char **argv)
969 /* XXX search through $PATH is missing */
970 input = fopen(argv[1], "r");
972 bb_error_msg("cannot open '%s'", argv[1]);
976 /* Now run the file */
977 /* XXX argv and argc are broken; need to save old global_argv
978 * (pointer only is OK!) on this stack frame,
979 * set global_argv=argv+1, recurse, and restore. */
980 mark_open(fileno(input));
981 status = parse_file_outer(input);
982 mark_closed(fileno(input));
987 static int builtin_umask(char **argv)
990 const char *arg = argv[1];
993 new_umask = strtoul(arg, &end, 8);
994 if (*end != '\0' || end == arg) {
998 new_umask = umask(0);
999 printf("%.3o\n", (unsigned) new_umask);
1002 return EXIT_SUCCESS;
1005 /* built-in 'unset VAR' handler */
1006 static int builtin_unset(char **argv)
1008 /* bash always returns true */
1009 unset_local_var(argv[1]);
1010 return EXIT_SUCCESS;
1013 static int builtin_not_written(char **argv)
1015 printf("builtin_%s not written\n", argv[0]);
1016 return EXIT_FAILURE;
1019 static int b_check_space(o_string *o, int len)
1021 /* It would be easy to drop a more restrictive policy
1022 * in here, such as setting a maximum string length */
1023 if (o->length + len > o->maxlen) {
1024 /* assert(data == NULL || o->maxlen != 0); */
1025 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1026 o->data = xrealloc(o->data, 1 + o->maxlen);
1028 return o->data == NULL;
1031 static int b_addchr(o_string *o, int ch)
1033 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1034 if (b_check_space(o, 1))
1036 o->data[o->length] = ch;
1038 o->data[o->length] = '\0';
1042 static void b_reset(o_string *o)
1046 if (o->data != NULL)
1050 static void b_free(o_string *o)
1058 /* My analysis of quoting semantics tells me that state information
1059 * is associated with a destination, not a source.
1061 static int b_addqchr(o_string *o, int ch, int quote)
1063 if (quote && strchr("*?[\\", ch)) {
1065 rc = b_addchr(o, '\\');
1069 return b_addchr(o, ch);
1072 static int static_get(struct in_str *i)
1075 if (ch == '\0') return EOF;
1079 static int static_peek(struct in_str *i)
1084 #if ENABLE_HUSH_INTERACTIVE
1085 #if ENABLE_FEATURE_EDITING
1086 static void cmdedit_set_initial_prompt(void)
1088 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1091 PS1 = getenv("PS1");
1096 #endif /* EDITING */
1098 static const char* setup_prompt_string(int promptmode)
1100 const char *prompt_str;
1101 debug_printf("setup_prompt_string %d ", promptmode);
1102 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1103 /* Set up the prompt */
1104 if (promptmode == 1) {
1107 ns = xmalloc(strlen(cwd)+4);
1108 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1115 prompt_str = (promptmode == 1) ? PS1 : PS2;
1117 debug_printf("result %s\n", prompt_str);
1121 static void get_user_input(struct in_str *i)
1124 const char *prompt_str;
1126 prompt_str = setup_prompt_string(i->promptmode);
1127 #if ENABLE_FEATURE_EDITING
1129 ** enable command line editing only while a command line
1130 ** is actually being read; otherwise, we'll end up bequeathing
1131 ** atexit() handlers and other unwanted stuff to our
1132 ** child processes (rob@sysgo.de)
1134 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1135 i->eof_flag = (r < 0);
1136 if (i->eof_flag) { /* EOF/error detected */
1137 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1138 user_input_buf[1] = '\0';
1141 fputs(prompt_str, stdout);
1143 user_input_buf[0] = r = fgetc(i->file);
1144 /*user_input_buf[1] = '\0'; - already is and never changed */
1145 i->eof_flag = (r == EOF);
1147 i->p = user_input_buf;
1149 #endif /* INTERACTIVE */
1151 /* This is the magic location that prints prompts
1152 * and gets data back from the user */
1153 static int file_get(struct in_str *i)
1157 /* If there is data waiting, eat it up */
1158 if (i->p && *i->p) {
1159 #if ENABLE_HUSH_INTERACTIVE
1163 if (i->eof_flag && !*i->p)
1166 /* need to double check i->file because we might be doing something
1167 * more complicated by now, like sourcing or substituting. */
1168 #if ENABLE_HUSH_INTERACTIVE
1169 if (interactive_fd && i->__promptme && i->file == stdin) {
1172 } while (!*i->p); /* need non-empty line */
1178 ch = fgetc(i->file);
1180 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1181 #if ENABLE_HUSH_INTERACTIVE
1188 /* All the callers guarantee this routine will never be
1189 * used right after a newline, so prompting is not needed.
1191 static int file_peek(struct in_str *i)
1194 if (i->p && *i->p) {
1195 if (i->eof_flag && !i->p[1])
1199 ch = fgetc(i->file);
1200 i->eof_flag = (ch == EOF);
1201 i->peek_buf[0] = ch;
1202 i->peek_buf[1] = '\0';
1204 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1208 static void setup_file_in_str(struct in_str *i, FILE *f)
1210 i->peek = file_peek;
1212 #if ENABLE_HUSH_INTERACTIVE
1220 static void setup_string_in_str(struct in_str *i, const char *s)
1222 i->peek = static_peek;
1223 i->get = static_get;
1224 #if ENABLE_HUSH_INTERACTIVE
1232 static void mark_open(int fd)
1234 struct close_me *new = xmalloc(sizeof(struct close_me));
1236 new->next = close_me_head;
1237 close_me_head = new;
1240 static void mark_closed(int fd)
1242 struct close_me *tmp;
1243 if (close_me_head == NULL || close_me_head->fd != fd)
1244 bb_error_msg_and_die("corrupt close_me");
1245 tmp = close_me_head;
1246 close_me_head = close_me_head->next;
1250 static void close_all(void)
1253 for (c = close_me_head; c; c = c->next) {
1256 close_me_head = NULL;
1259 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1260 * and stderr if they are redirected. */
1261 static int setup_redirects(struct child_prog *prog, int squirrel[])
1264 struct redir_struct *redir;
1266 for (redir = prog->redirects; redir; redir = redir->next) {
1267 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1268 /* something went wrong in the parse. Pretend it didn't happen */
1271 if (redir->dup == -1) {
1272 mode = redir_table[redir->type].mode;
1273 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1275 /* this could get lost if stderr has been redirected, but
1276 bash and ash both lose it as well (though zsh doesn't!) */
1280 openfd = redir->dup;
1283 if (openfd != redir->fd) {
1284 if (squirrel && redir->fd < 3) {
1285 squirrel[redir->fd] = dup(redir->fd);
1290 dup2(openfd, redir->fd);
1291 if (redir->dup == -1)
1299 static void restore_redirects(int squirrel[])
1302 for (i = 0; i < 3; i++) {
1305 /* We simply die on error */
1312 /* XXX no exit() here. If you don't exec, use _exit instead.
1313 * The at_exit handlers apparently confuse the calling process,
1314 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1315 static void pseudo_exec_argv(char **argv)
1319 const struct built_in_command *x;
1321 for (i = 0; is_assignment(argv[i]); i++) {
1322 debug_printf_exec("pid %d environment modification: %s\n",
1324 // FIXME: vfork case??
1325 p = expand_variables_to_string(argv[i]);
1326 putenv(p == argv[i] ? xstrdup(p) : p);
1329 /* If a variable is assigned in a forest, and nobody listens,
1330 * was it ever really set?
1332 if (argv[0] == NULL) {
1333 _exit(EXIT_SUCCESS);
1336 argv = expand_variables_to_list(argv);
1339 * Check if the command matches any of the builtins.
1340 * Depending on context, this might be redundant. But it's
1341 * easier to waste a few CPU cycles than it is to figure out
1342 * if this is one of those cases.
1344 for (x = bltins; x->cmd; x++) {
1345 if (strcmp(argv[0], x->cmd) == 0) {
1346 debug_printf_exec("running builtin '%s'\n", argv[0]);
1347 rcode = x->function(argv);
1353 /* Check if the command matches any busybox applets */
1354 #if ENABLE_FEATURE_SH_STANDALONE
1355 if (strchr(argv[0], '/') == NULL) {
1356 const struct bb_applet *a = find_applet_by_name(argv[0]);
1360 debug_printf_exec("running applet '%s'\n", argv[0]);
1361 // is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1362 run_current_applet_and_exit(argv);
1364 /* re-exec ourselves with the new arguments */
1365 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1366 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1367 /* If they called chroot or otherwise made the binary no longer
1368 * executable, fall through */
1373 debug_printf_exec("execing '%s'\n", argv[0]);
1374 execvp(argv[0], argv);
1375 bb_perror_msg("cannot exec '%s'", argv[0]);
1379 static void pseudo_exec(struct child_prog *child)
1381 // FIXME: buggy wrt NOMMU! Must not modify any global data
1382 // until it does exec/_exit, but currently it does.
1386 pseudo_exec_argv(child->argv);
1390 // FIXME: do not modify globals! Think vfork!
1391 #if ENABLE_HUSH_INTERACTIVE
1392 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1393 interactive_fd = 0; /* crucial!!!! */
1395 debug_printf_exec("pseudo_exec: run_list_real\n");
1396 rcode = run_list_real(child->group);
1397 /* OK to leak memory by not calling free_pipe_list,
1398 * since this process is about to exit */
1402 /* Can happen. See what bash does with ">foo" by itself. */
1403 debug_printf("trying to pseudo_exec null command\n");
1404 _exit(EXIT_SUCCESS);
1408 static const char *get_cmdtext(struct pipe *pi)
1414 /* This is subtle. ->cmdtext is created only on first backgrounding.
1415 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1416 * On subsequent bg argv is trashed, but we won't use it */
1419 argv = pi->progs[0].argv;
1420 if (!argv || !argv[0])
1421 return (pi->cmdtext = xzalloc(1));
1424 do len += strlen(*argv) + 1; while (*++argv);
1425 pi->cmdtext = p = xmalloc(len);
1426 argv = pi->progs[0].argv;
1428 len = strlen(*argv);
1429 memcpy(p, *argv, len);
1437 static void insert_bg_job(struct pipe *pi)
1439 struct pipe *thejob;
1442 /* Linear search for the ID of the job to use */
1444 for (thejob = job_list; thejob; thejob = thejob->next)
1445 if (thejob->jobid >= pi->jobid)
1446 pi->jobid = thejob->jobid + 1;
1448 /* Add thejob to the list of running jobs */
1450 thejob = job_list = xmalloc(sizeof(*thejob));
1452 for (thejob = job_list; thejob->next; thejob = thejob->next)
1454 thejob->next = xmalloc(sizeof(*thejob));
1455 thejob = thejob->next;
1458 /* Physically copy the struct job */
1459 memcpy(thejob, pi, sizeof(struct pipe));
1460 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1461 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1462 for (i = 0; i < pi->num_progs; i++) {
1463 // TODO: do we really need to have so many fields which are just dead weight
1464 // at execution stage?
1465 thejob->progs[i].pid = pi->progs[i].pid;
1466 /* all other fields are not used and stay zero */
1468 thejob->next = NULL;
1469 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1471 /* We don't wait for background thejobs to return -- append it
1472 to the list of backgrounded thejobs and leave it alone */
1473 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1474 last_bg_pid = thejob->progs[0].pid;
1475 last_jobid = thejob->jobid;
1478 static void remove_bg_job(struct pipe *pi)
1480 struct pipe *prev_pipe;
1482 if (pi == job_list) {
1483 job_list = pi->next;
1485 prev_pipe = job_list;
1486 while (prev_pipe->next != pi)
1487 prev_pipe = prev_pipe->next;
1488 prev_pipe->next = pi->next;
1491 last_jobid = job_list->jobid;
1496 /* remove a backgrounded job */
1497 static void delete_finished_bg_job(struct pipe *pi)
1500 pi->stopped_progs = 0;
1506 /* Checks to see if any processes have exited -- if they
1507 have, figure out why and see if a job has completed */
1508 static int checkjobs(struct pipe* fg_pipe)
1519 attributes = WUNTRACED;
1520 if (fg_pipe == NULL) {
1521 attributes |= WNOHANG;
1524 /* Do we do this right?
1525 * bash-3.00# sleep 20 | false
1527 * [3]+ Stopped sleep 20 | false
1528 * bash-3.00# echo $?
1529 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1532 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1533 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1534 // + killall -STOP cat
1537 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1538 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1540 #ifdef DEBUG_SHELL_JOBS
1541 if (WIFSTOPPED(status))
1542 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1543 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1544 if (WIFSIGNALED(status))
1545 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1546 childpid, WTERMSIG(status), WEXITSTATUS(status));
1547 if (WIFEXITED(status))
1548 debug_printf_jobs("pid %d exited, exitcode %d\n",
1549 childpid, WEXITSTATUS(status));
1551 /* Were we asked to wait for fg pipe? */
1554 for (i = 0; i < fg_pipe->num_progs; i++) {
1555 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1556 if (fg_pipe->progs[i].pid == childpid) {
1557 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1559 fg_pipe->progs[i].pid = 0;
1560 fg_pipe->running_progs--;
1561 if (i == fg_pipe->num_progs-1)
1562 /* last process gives overall exitstatus */
1563 rcode = WEXITSTATUS(status);
1565 fg_pipe->progs[i].is_stopped = 1;
1566 fg_pipe->stopped_progs++;
1568 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1569 fg_pipe->running_progs, fg_pipe->stopped_progs);
1570 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1571 /* All processes in fg pipe have exited/stopped */
1573 if (fg_pipe->running_progs)
1574 insert_bg_job(fg_pipe);
1578 /* There are still running processes in the fg pipe */
1582 /* fall through to searching process in bg pipes */
1586 /* We asked to wait for bg or orphaned children */
1587 /* No need to remember exitcode in this case */
1588 for (pi = job_list; pi; pi = pi->next) {
1590 while (prognum < pi->num_progs) {
1591 if (pi->progs[prognum].pid == childpid)
1592 goto found_pi_and_prognum;
1598 /* Happens when shell is used as init process (init=/bin/sh) */
1599 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1603 found_pi_and_prognum:
1606 pi->progs[prognum].pid = 0;
1607 pi->running_progs--;
1608 if (!pi->running_progs) {
1609 printf(JOB_STATUS_FORMAT, pi->jobid,
1610 "Done", pi->cmdtext);
1611 delete_finished_bg_job(pi);
1615 pi->stopped_progs++;
1616 pi->progs[prognum].is_stopped = 1;
1621 /* wait found no children or failed */
1623 if (childpid && errno != ECHILD)
1624 bb_perror_msg("waitpid");
1629 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1632 int rcode = checkjobs(fg_pipe);
1633 /* Job finished, move the shell to the foreground */
1635 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1636 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1637 bb_perror_msg("tcsetpgrp-4a");
1642 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1643 * to finish. See checkjobs().
1645 * return code is normally -1, when the caller has to wait for children
1646 * to finish to determine the exit status of the pipe. If the pipe
1647 * is a simple builtin command, however, the action is done by the
1648 * time run_pipe_real returns, and the exit code is provided as the
1651 * The input of the pipe is always stdin, the output is always
1652 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1653 * because it tries to avoid running the command substitution in
1654 * subshell, when that is in fact necessary. The subshell process
1655 * now has its stdout directed to the input of the appropriate pipe,
1656 * so this routine is noticeably simpler.
1658 static int run_pipe_real(struct pipe *pi)
1661 int nextin, nextout;
1662 int pipefds[2]; /* pipefds[0] is for reading */
1663 struct child_prog *child;
1664 const struct built_in_command *x;
1666 /* it is not always needed, but we aim to smaller code */
1667 int squirrel[] = { -1, -1, -1 };
1669 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1671 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1677 pi->running_progs = 1;
1678 pi->stopped_progs = 0;
1680 /* Check if this is a simple builtin (not part of a pipe).
1681 * Builtins within pipes have to fork anyway, and are handled in
1682 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1684 child = &(pi->progs[0]);
1685 if (single_fg && child->group && child->subshell == 0) {
1686 debug_printf("non-subshell grouping\n");
1687 setup_redirects(child, squirrel);
1688 debug_printf_exec(": run_list_real\n");
1689 rcode = run_list_real(child->group);
1690 restore_redirects(squirrel);
1691 debug_printf_exec("run_pipe_real return %d\n", rcode);
1695 if (single_fg && child->argv != NULL) {
1696 char **argv_expanded;
1697 char **argv = child->argv;
1699 for (i = 0; is_assignment(argv[i]); i++)
1701 if (i != 0 && argv[i] == NULL) {
1702 /* assignments, but no command: set the local environment */
1703 for (i = 0; argv[i] != NULL; i++) {
1704 /* Ok, this case is tricky. We have to decide if this is a
1705 * local variable, or an already exported variable. If it is
1706 * already exported, we have to export the new value. If it is
1707 * not exported, we need only set this as a local variable.
1708 * This junk is all to decide whether or not to export this
1712 name = xstrdup(argv[i]);
1713 debug_printf("local environment set: %s\n", name);
1714 value = strchr(name, '=');
1717 if (get_local_var(name)) {
1721 p = expand_variables_to_string(argv[i]);
1722 set_local_var(p, export_me);
1726 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1728 for (i = 0; is_assignment(argv[i]); i++) {
1729 p = expand_variables_to_string(argv[i]);
1737 for (x = bltins; x->cmd; x++) {
1738 if (strcmp(argv[i], x->cmd) == 0) {
1739 if (x->function == builtin_exec && argv[i+1] == NULL) {
1740 debug_printf("magic exec\n");
1741 setup_redirects(child, NULL);
1742 return EXIT_SUCCESS;
1744 debug_printf("builtin inline %s\n", argv[0]);
1745 /* XXX setup_redirects acts on file descriptors, not FILEs.
1746 * This is perfect for work that comes after exec().
1747 * Is it really safe for inline use? Experimentally,
1748 * things seem to work with glibc. */
1749 setup_redirects(child, squirrel);
1750 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1751 //sp: if (child->sp) /* btw we can do it unconditionally... */
1752 argv_expanded = expand_variables_to_list(argv + i);
1753 rcode = x->function(argv_expanded);
1754 free(argv_expanded);
1755 restore_redirects(squirrel);
1756 debug_printf_exec("run_pipe_real return %d\n", rcode);
1760 #if ENABLE_FEATURE_SH_STANDALONE
1762 const struct bb_applet *a = find_applet_by_name(argv[i]);
1763 if (a && a->nofork) {
1764 setup_redirects(child, squirrel);
1765 save_nofork_data(&nofork_save);
1766 argv_expanded = argv + i;
1767 //sp: if (child->sp)
1768 argv_expanded = expand_variables_to_list(argv + i);
1769 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1770 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
1771 free(argv_expanded);
1772 restore_redirects(squirrel);
1773 debug_printf_exec("run_pipe_real return %d\n", rcode);
1780 /* Going to fork a child per each pipe member */
1781 pi->running_progs = 0;
1783 /* Disable job control signals for shell (parent) and
1784 * for initial child code after fork */
1785 set_jobctrl_sighandler(SIG_IGN);
1787 for (i = 0; i < pi->num_progs; i++) {
1788 child = &(pi->progs[i]);
1790 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1792 debug_printf_exec(": pipe member with no argv\n");
1794 /* pipes are inserted between pairs of commands */
1795 if ((i + 1) < pi->num_progs) {
1796 if (pipe(pipefds) < 0)
1797 bb_perror_msg_and_die("pipe");
1798 nextout = pipefds[1];
1804 /* XXX test for failed fork()? */
1806 child->pid = fork();
1808 child->pid = vfork();
1810 if (!child->pid) { /* child */
1811 /* Every child adds itself to new process group
1812 * with pgid == pid of first child in pipe */
1814 if (interactive_fd) {
1815 /* Don't do pgrp restore anymore on fatal signals */
1816 set_fatal_sighandler(SIG_DFL);
1817 if (pi->pgrp < 0) /* true for 1st process only */
1818 pi->pgrp = getpid();
1819 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1820 /* We do it in *every* child, not just first,
1822 tcsetpgrp(interactive_fd, pi->pgrp);
1826 /* in non-interactive case fatal sigs are already SIG_DFL */
1836 if (pipefds[0] != -1) {
1837 close(pipefds[0]); /* opposite end of our output pipe */
1839 /* Like bash, explicit redirects override pipes,
1840 * and the pipe fd is available for dup'ing. */
1841 setup_redirects(child, NULL);
1843 /* Restore default handlers just prior to exec */
1844 set_jobctrl_sighandler(SIG_DFL);
1845 set_misc_sighandler(SIG_DFL);
1846 signal(SIGCHLD, SIG_DFL);
1850 pi->running_progs++;
1853 /* Second and next children need to know pid of first one */
1855 pi->pgrp = child->pid;
1862 /* If there isn't another process, nextin is garbage
1863 but it doesn't matter */
1864 nextin = pipefds[0];
1866 debug_printf_exec("run_pipe_real return -1\n");
1870 #ifndef debug_print_tree
1871 static void debug_print_tree(struct pipe *pi, int lvl)
1873 static const char *PIPE[] = {
1879 static const char *RES[] = {
1880 [RES_NONE ] = "NONE" ,
1882 [RES_THEN ] = "THEN" ,
1883 [RES_ELIF ] = "ELIF" ,
1884 [RES_ELSE ] = "ELSE" ,
1886 [RES_FOR ] = "FOR" ,
1887 [RES_WHILE] = "WHILE",
1888 [RES_UNTIL] = "UNTIL",
1890 [RES_DONE ] = "DONE" ,
1891 [RES_XXXX ] = "XXXX" ,
1893 [RES_SNTX ] = "SNTX" ,
1899 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1900 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1902 while (prn < pi->num_progs) {
1903 struct child_prog *child = &pi->progs[prn];
1904 char **argv = child->argv;
1906 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1908 fprintf(stderr, " group %s: (argv=%p)\n",
1909 (child->subshell ? "()" : "{}"),
1911 debug_print_tree(child->group, lvl+1);
1915 if (argv) while (*argv) {
1916 fprintf(stderr, " '%s'", *argv);
1919 fprintf(stderr, "\n");
1928 /* NB: called by pseudo_exec, and therefore must not modify any
1929 * global data until exec/_exit (we can be a child after vfork!) */
1930 static int run_list_real(struct pipe *pi)
1932 char *for_varname = NULL;
1933 char **for_lcur = NULL;
1934 char **for_list = NULL;
1939 int rcode = 0; /* probably for gcc only */
1940 int flag_restore = 0;
1941 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1942 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1944 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
1946 /* check syntax for "for" */
1947 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1948 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1949 && (rpipe->next == NULL)
1951 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1952 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1955 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1956 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1958 /* TODO: what is tested in the first condition? */
1959 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1960 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1966 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1967 * We are saving state before entering outermost list ("while...done")
1968 * so that ctrl-Z will correctly background _entire_ outermost list,
1969 * not just a part of it (like "sleep 1 | exit 2") */
1970 if (++run_list_level == 1 && interactive_fd) {
1971 if (sigsetjmp(toplevel_jb, 1)) {
1972 /* ctrl-Z forked and we are parent; or ctrl-C.
1973 * Sighandler has longjmped us here */
1974 signal(SIGINT, SIG_IGN);
1975 signal(SIGTSTP, SIG_IGN);
1976 /* Restore level (we can be coming from deep inside
1979 #if ENABLE_FEATURE_SH_STANDALONE
1980 if (nofork_save.saved) { /* if save area is valid */
1981 debug_printf_jobs("exiting nofork early\n");
1982 restore_nofork_data(&nofork_save);
1986 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1987 * Remember this child as background job */
1990 /* ctrl-C. We just stop doing whatever we were doing */
1996 /* ctrl-Z handler will store pid etc in pi */
1999 #if ENABLE_FEATURE_SH_STANDALONE
2000 nofork_save.saved = 0; /* in case we will run a nofork later */
2002 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2003 signal(SIGINT, handler_ctrl_c);
2007 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2009 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
2016 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
2017 rmode, if_code, next_if_code, skip_more_in_this_rmode);
2018 if (rmode == skip_more_in_this_rmode && flag_skip) {
2019 if (pi->followup == PIPE_SEQ)
2024 skip_more_in_this_rmode = RES_XXXX;
2025 if (rmode == RES_THEN || rmode == RES_ELSE)
2026 if_code = next_if_code;
2027 if (rmode == RES_THEN && if_code)
2029 if (rmode == RES_ELSE && !if_code)
2031 if (rmode == RES_ELIF && !if_code)
2033 if (rmode == RES_FOR && pi->num_progs) {
2035 /* if no variable values after "in" we skip "for" */
2036 if (!pi->next->progs->argv)
2038 /* create list of variable values */
2039 for_list = expand_variables_to_list(pi->next->progs->argv);
2040 for_lcur = for_list;
2041 for_varname = pi->progs->argv[0];
2042 pi->progs->argv[0] = NULL;
2045 free(pi->progs->argv[0]);
2050 pi->progs->argv[0] = for_varname;
2051 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2054 /* insert next value from for_lcur */
2055 /* vda: does it need escaping? */
2056 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2057 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2059 if (rmode == RES_IN)
2061 if (rmode == RES_DO) {
2065 if (rmode == RES_DONE) {
2072 if (pi->num_progs == 0)
2074 save_num_progs = pi->num_progs; /* save number of programs */
2075 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2076 rcode = run_pipe_real(pi);
2078 /* We only ran a builtin: rcode was set by the return value
2079 * of run_pipe_real(), and we don't need to wait for anything. */
2080 } else if (pi->followup == PIPE_BG) {
2081 /* What does bash do with attempts to background builtins? */
2083 /* Even bash 3.2 doesn't do that well with nested bg:
2084 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2085 * I'm considering NOT treating inner bgs as jobs -
2086 * thus maybe "if (run_list_level == 1 && pi->followup == PIPE_BG)"
2091 rcode = EXIT_SUCCESS;
2094 /* Paranoia, just "interactive_fd" should be enough */
2095 if (run_list_level == 1 && interactive_fd) {
2096 rcode = checkjobs_and_fg_shell(pi);
2100 rcode = checkjobs(pi);
2102 debug_printf_exec(": checkjobs returned %d\n", rcode);
2104 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2105 last_return_code = rcode;
2106 pi->num_progs = save_num_progs; /* restore number of programs */
2107 if (rmode == RES_IF || rmode == RES_ELIF)
2108 next_if_code = rcode; /* can be overwritten a number of times */
2109 if (rmode == RES_WHILE)
2110 flag_rep = !last_return_code;
2111 if (rmode == RES_UNTIL)
2112 flag_rep = last_return_code;
2113 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2114 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2116 skip_more_in_this_rmode = rmode;
2123 /* ctrl-Z forked somewhere in the past, we are the child,
2124 * and now we completed running the list. Exit. */
2130 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
2134 /* return code is the exit status of the pipe */
2135 static int free_pipe(struct pipe *pi, int indent)
2138 struct child_prog *child;
2139 struct redir_struct *r, *rnext;
2140 int a, i, ret_code = 0;
2142 if (pi->stopped_progs > 0)
2144 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2145 for (i = 0; i < pi->num_progs; i++) {
2146 child = &pi->progs[i];
2147 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2149 for (a = 0, p = child->argv; *p; a++, p++) {
2150 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2152 globfree(&child->glob_result);
2154 } else if (child->group) {
2155 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2156 ret_code = free_pipe_list(child->group, indent+3);
2157 debug_printf_clean("%s end group\n", indenter(indent));
2159 debug_printf_clean("%s (nil)\n", indenter(indent));
2161 for (r = child->redirects; r; r = rnext) {
2162 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2164 /* guard against the case >$FOO, where foo is unset or blank */
2165 if (r->word.gl_pathv) {
2166 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2170 debug_printf_clean("&%d\n", r->dup);
2175 child->redirects = NULL;
2177 free(pi->progs); /* children are an array, they get freed all at once */
2186 static int free_pipe_list(struct pipe *head, int indent)
2188 int rcode = 0; /* if list has no members */
2189 struct pipe *pi, *next;
2191 for (pi = head; pi; pi = next) {
2192 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2193 rcode = free_pipe(pi, indent);
2194 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2196 /*pi->next = NULL;*/
2202 /* Select which version we will use */
2203 static int run_list(struct pipe *pi)
2206 debug_printf_exec("run_list entered\n");
2207 if (fake_mode == 0) {
2208 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2209 rcode = run_list_real(pi);
2211 /* free_pipe_list has the side effect of clearing memory.
2212 * In the long run that function can be merged with run_list_real,
2213 * but doing that now would hobble the debugging effort. */
2214 free_pipe_list(pi, 0);
2215 debug_printf_exec("run_list return %d\n", rcode);
2219 /* The API for glob is arguably broken. This routine pushes a non-matching
2220 * string into the output structure, removing non-backslashed backslashes.
2221 * If someone can prove me wrong, by performing this function within the
2222 * original glob(3) api, feel free to rewrite this routine into oblivion.
2223 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2224 * XXX broken if the last character is '\\', check that before calling.
2226 static int globhack(const char *src, int flags, glob_t *pglob)
2231 for (cnt = 1, s = src; s && *s; s++) {
2232 if (*s == '\\') s++;
2235 dest = xmalloc(cnt);
2236 if (!(flags & GLOB_APPEND)) {
2237 pglob->gl_pathv = NULL;
2238 pglob->gl_pathc = 0;
2242 pathc = ++pglob->gl_pathc;
2243 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2244 pglob->gl_pathv[pathc-1] = dest;
2245 pglob->gl_pathv[pathc] = NULL;
2246 for (s = src; s && *s; s++, dest++) {
2247 if (*s == '\\') s++;
2254 /* XXX broken if the last character is '\\', check that before calling */
2255 static int glob_needed(const char *s)
2258 if (*s == '\\') s++;
2259 if (strchr("*[?", *s)) return 1;
2264 static int xglob(o_string *dest, int flags, glob_t *pglob)
2268 /* short-circuit for null word */
2269 /* we can code this better when the debug_printf's are gone */
2270 if (dest->length == 0) {
2271 if (dest->nonnull) {
2272 /* bash man page calls this an "explicit" null */
2273 gr = globhack(dest->data, flags, pglob);
2274 debug_printf("globhack returned %d\n", gr);
2278 } else if (glob_needed(dest->data)) {
2279 gr = glob(dest->data, flags, NULL, pglob);
2280 debug_printf("glob returned %d\n", gr);
2281 if (gr == GLOB_NOMATCH) {
2282 /* quote removal, or more accurately, backslash removal */
2283 gr = globhack(dest->data, flags, pglob);
2284 debug_printf("globhack returned %d\n", gr);
2287 gr = globhack(dest->data, flags, pglob);
2288 debug_printf("globhack returned %d\n", gr);
2290 if (gr == GLOB_NOSPACE)
2291 bb_error_msg_and_die("out of memory during glob");
2292 if (gr != 0) { /* GLOB_ABORTED ? */
2293 bb_error_msg("glob(3) error %d", gr);
2295 /* globprint(glob_target); */
2299 /* expand_variables_to_list() takes a list of strings, expands
2300 * all variable references within and returns a pointer to
2301 * a list of expanded strings, possibly with larger number
2302 * of strings. (Think VAR="a b"; echo $VAR).
2303 * This new list is allocated as a single malloc block.
2304 * NULL-terminated list of char* pointers is at the beginning of it,
2305 * followed by strings themself.
2306 * Caller can deallocate entire list by single free(list). */
2309 * count_XXX estimates size of the block we need. It's okay
2310 * to over-estimate sizes a bit, if it makes code simpler */
2311 static int count_ifs(const char *str)
2314 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2316 str += strcspn(str, ifs);
2318 str++; /* str += strspn(str, ifs); */
2319 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2321 debug_printf_expand(" return %d\n", cnt);
2325 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2330 int count = *countp;
2334 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2337 p = strchr(p, SPECIAL_VAR_SYMBOL);
2340 switch (first_ch & 0x7f) {
2341 /* high bit in 1st_ch indicates that var is double-quoted */
2343 case '!': /* bg pid */
2344 case '?': /* exitcode */
2345 case '#': /* argc */
2346 len += sizeof(int)*3 + 1; /* enough for int */
2350 for (i = 1; i < global_argc; i++) {
2351 len += strlen(global_argv[i]) + 1;
2353 if (!(first_ch & 0x80))
2354 count += count_ifs(global_argv[i]);
2359 arg[0] = first_ch & 0x7f;
2360 if (isdigit(arg[0])) {
2363 if (i < global_argc)
2364 val = global_argv[i];
2366 val = lookup_param(arg);
2368 *p = SPECIAL_VAR_SYMBOL;
2371 len += strlen(val) + 1;
2372 if (!(first_ch & 0x80))
2373 count += count_ifs(val);
2379 len += strlen(arg) + 1;
2385 /* Store given string, finalizing the word and starting new one whenever
2386 * we encounter ifs char(s). This is used for expanding variable values.
2387 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2388 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2392 int word_len = strcspn(str, ifs);
2394 memcpy(pos, str, word_len); /* store non-ifs chars */
2398 if (!*str) /* EOL - do not finalize word */
2401 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2402 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2403 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2405 str += strspn(str, ifs); /* skip ifs chars */
2411 /* Expand all variable references in given string, adding words to list[]
2412 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2413 * to be filled). This routine is extremely tricky: has to deal with
2414 * variables/parameters with whitespace, $* and $@, and constructs like
2415 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2416 /* NB: another bug is that we cannot detect empty strings yet:
2417 * "" or $empty"" expands to zero words, has to expand to empty word */
2418 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2420 /* or_mask is either 0 (normal case) or 0x80
2421 * (expansion of right-hand side of assignment == 1-element expand) */
2423 char first_ch, ored_ch;
2431 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2432 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2433 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2436 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2437 memcpy(pos, arg, p - arg);
2440 p = strchr(p, SPECIAL_VAR_SYMBOL);
2442 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2443 ored_ch |= first_ch;
2445 switch (first_ch & 0x7f) {
2446 /* Highest bit in first_ch indicates that var is double-quoted */
2448 /* FIXME: (echo $$) should still print pid of main shell */
2449 val = utoa(getpid());
2451 case '!': /* bg pid */
2452 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2454 case '?': /* exitcode */
2455 val = utoa(last_return_code);
2457 case '#': /* argc */
2458 val = utoa(global_argc ? global_argc-1 : 0);
2463 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2464 while (i < global_argc) {
2465 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2466 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2467 if (global_argv[i++][0] && i < global_argc) {
2468 /* this argv[] is not empty and not last:
2469 * put terminating NUL, start new word */
2471 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2472 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2473 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2478 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2479 * and in this case should theat it like '$*' */
2480 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2482 strcpy(pos, global_argv[i]);
2483 pos += strlen(global_argv[i]);
2484 if (++i >= global_argc)
2487 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2488 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2489 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2492 } else { /* quoted $*: add as one word */
2494 strcpy(pos, global_argv[i]);
2495 pos += strlen(global_argv[i]);
2496 if (++i >= global_argc)
2505 arg[0] = first_ch & 0x7f;
2506 if (isdigit(arg[0])) {
2509 if (i < global_argc)
2510 val = global_argv[i];
2512 val = lookup_param(arg);
2514 *p = SPECIAL_VAR_SYMBOL;
2515 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2517 n = expand_on_ifs(list, n, &pos, val);
2520 } /* else: quoted $VAR, val will be appended at pos */
2528 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2530 pos += strlen(arg) + 1;
2531 if (pos == list[n-1] + 1) { /* expansion is empty */
2532 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2533 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2543 static char **expand_variables(char **argv, char or_mask)
2548 char *pos, **v, **list;
2551 if (!*v) debug_printf_expand("count_var_expansion_space: "
2552 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2553 count, len, sizeof(char*) * count + len);
2555 count_var_expansion_space(&count, &len, *v);
2556 debug_printf_expand("count_var_expansion_space: "
2557 "'%s' count=%d len=%d alloc_space=%d\n",
2558 *v, count, len, sizeof(char*) * count + len);
2561 len += sizeof(char*) * count; /* total to alloc */
2562 list = xmalloc(len);
2563 pos = (char*)(list + count);
2564 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2568 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2570 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2571 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2572 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2579 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2582 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2585 /* To be removed / made conditional later. */
2586 if (pos - (char*)list > len)
2587 bb_error_msg_and_die("BUG in varexp");
2591 static char **expand_variables_to_list(char **argv)
2593 return expand_variables(argv, 0);
2596 static char *expand_variables_to_string(const char *str)
2598 char *argv[2], **list;
2600 argv[0] = (char*)str;
2602 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2603 /* To be removed / made conditional later. */
2604 if (!list[0] || list[1])
2605 bb_error_msg_and_die("BUG in varexp");
2606 /* actually, just move string 2*sizeof(char*) bytes back */
2607 strcpy((char*)list, list[0]);
2611 /* This is used to get/check local shell variables */
2612 static const char *get_local_var(const char *s)
2614 struct variables *cur;
2618 for (cur = top_vars; cur; cur = cur->next) {
2619 if (strcmp(cur->name, s) == 0)
2625 /* This is used to set local shell variables
2626 flg_export == 0 if only local (not exporting) variable
2627 flg_export == 1 if "new" exporting environ
2628 flg_export > 1 if current startup environ (not call putenv()) */
2629 static int set_local_var(const char *s, int flg_export)
2633 struct variables *cur;
2637 /* Assume when we enter this function that we are already in
2638 * NAME=VALUE format. So the first order of business is to
2639 * split 's' on the '=' into 'name' and 'value' */
2640 value = strchr(name, '=');
2641 /*if (value == 0 && ++value == 0) ??? -vda */
2642 if (value == NULL || value[1] == '\0') {
2648 for (cur = top_vars; cur; cur = cur->next) {
2649 if (strcmp(cur->name, name) == 0) {
2650 if (strcmp(cur->value, value) == 0) {
2651 if (flg_export && !cur->flg_export)
2652 cur->flg_export = flg_export;
2655 } else if (cur->flg_read_only) {
2656 bb_error_msg("%s: readonly variable", name);
2659 if (flg_export > 0 || cur->flg_export > 1)
2660 cur->flg_export = 1;
2661 free((char*)cur->value);
2662 cur->value = xstrdup(value);
2668 cur = xzalloc(sizeof(*cur));
2669 cur->name = xstrdup(name);
2670 cur->value = xstrdup(value);
2672 cur->flg_export = flg_export;
2673 /*cur->flg_read_only = 0;*/
2675 struct variables *bottom = top_vars;
2676 while (bottom->next)
2677 bottom = bottom->next;
2681 if (result == 0 && cur->flg_export == 1) {
2683 result = putenv(name);
2686 if (result > 0) /* equivalent to previous set */
2692 static void unset_local_var(const char *name)
2694 struct variables *cur, *next;
2698 for (cur = top_vars; cur; cur = cur->next) {
2699 if (strcmp(cur->name, name) == 0) {
2700 if (cur->flg_read_only) {
2701 bb_error_msg("%s: readonly variable", name);
2704 if (cur->flg_export)
2705 unsetenv(cur->name);
2706 free((char*)cur->name);
2707 free((char*)cur->value);
2709 while (next->next != cur)
2711 next->next = cur->next;
2718 static int is_assignment(const char *s)
2720 if (!s || !isalpha(*s))
2723 while (isalnum(*s) || *s == '_')
2728 /* the src parameter allows us to peek forward to a possible &n syntax
2729 * for file descriptor duplication, e.g., "2>&1".
2730 * Return code is 0 normally, 1 if a syntax error is detected in src.
2731 * Resource errors (in xmalloc) cause the process to exit */
2732 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2733 struct in_str *input)
2735 struct child_prog *child = ctx->child;
2736 struct redir_struct *redir = child->redirects;
2737 struct redir_struct *last_redir = NULL;
2739 /* Create a new redir_struct and drop it onto the end of the linked list */
2742 redir = redir->next;
2744 redir = xmalloc(sizeof(struct redir_struct));
2746 redir->word.gl_pathv = NULL;
2748 last_redir->next = redir;
2750 child->redirects = redir;
2753 redir->type = style;
2754 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2756 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2758 /* Check for a '2>&1' type redirect */
2759 redir->dup = redirect_dup_num(input);
2760 if (redir->dup == -2) return 1; /* syntax error */
2761 if (redir->dup != -1) {
2762 /* Erik had a check here that the file descriptor in question
2763 * is legit; I postpone that to "run time"
2764 * A "-" representation of "close me" shows up as a -3 here */
2765 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2767 /* We do _not_ try to open the file that src points to,
2768 * since we need to return and let src be expanded first.
2769 * Set ctx->pending_redirect, so we know what to do at the
2770 * end of the next parsed word.
2772 ctx->pending_redirect = redir;
2777 static struct pipe *new_pipe(void)
2780 pi = xzalloc(sizeof(struct pipe));
2781 /*pi->num_progs = 0;*/
2782 /*pi->progs = NULL;*/
2783 /*pi->next = NULL;*/
2784 /*pi->followup = 0; invalid */
2786 pi->r_mode = RES_NONE;
2790 static void initialize_context(struct p_context *ctx)
2793 ctx->pending_redirect = NULL;
2795 ctx->list_head = new_pipe();
2796 ctx->pipe = ctx->list_head;
2797 ctx->res_w = RES_NONE;
2800 done_command(ctx); /* creates the memory for working child */
2803 /* normal return is 0
2804 * if a reserved word is found, and processed, return 1
2805 * should handle if, then, elif, else, fi, for, while, until, do, done.
2806 * case, function, and select are obnoxious, save those for later.
2808 static int reserved_word(o_string *dest, struct p_context *ctx)
2810 struct reserved_combo {
2815 /* Mostly a list of accepted follow-up reserved words.
2816 * FLAG_END means we are done with the sequence, and are ready
2817 * to turn the compound list into a command.
2818 * FLAG_START means the word must start a new compound list.
2820 static const struct reserved_combo reserved_list[] = {
2821 { "if", RES_IF, FLAG_THEN | FLAG_START },
2822 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2823 { "elif", RES_ELIF, FLAG_THEN },
2824 { "else", RES_ELSE, FLAG_FI },
2825 { "fi", RES_FI, FLAG_END },
2826 { "for", RES_FOR, FLAG_IN | FLAG_START },
2827 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2828 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2829 { "in", RES_IN, FLAG_DO },
2830 { "do", RES_DO, FLAG_DONE },
2831 { "done", RES_DONE, FLAG_END }
2833 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2834 const struct reserved_combo *r;
2836 for (r = reserved_list; r < reserved_list + NRES; r++) {
2837 if (strcmp(dest->data, r->literal) == 0) {
2838 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2839 if (r->flag & FLAG_START) {
2840 struct p_context *new = xmalloc(sizeof(struct p_context));
2841 debug_printf("push stack\n");
2842 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2845 ctx->res_w = RES_SNTX;
2849 *new = *ctx; /* physical copy */
2850 initialize_context(ctx);
2852 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2854 ctx->res_w = RES_SNTX;
2858 ctx->res_w = r->code;
2859 ctx->old_flag = r->flag;
2860 if (ctx->old_flag & FLAG_END) {
2861 struct p_context *old;
2862 debug_printf("pop stack\n");
2863 done_pipe(ctx, PIPE_SEQ);
2865 old->child->group = ctx->list_head;
2866 old->child->subshell = 0;
2867 *ctx = *old; /* physical copy */
2877 /* Normal return is 0.
2878 * Syntax or xglob errors return 1. */
2879 static int done_word(o_string *dest, struct p_context *ctx)
2881 struct child_prog *child = ctx->child;
2882 glob_t *glob_target;
2885 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2886 if (dest->length == 0 && !dest->nonnull) {
2887 debug_printf_parse("done_word return 0: true null, ignored\n");
2890 if (ctx->pending_redirect) {
2891 glob_target = &ctx->pending_redirect->word;
2895 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2898 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2899 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2900 if (reserved_word(dest, ctx)) {
2901 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2902 return (ctx->res_w == RES_SNTX);
2905 glob_target = &child->glob_result;
2907 flags |= GLOB_APPEND;
2909 gr = xglob(dest, flags, glob_target);
2911 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2916 if (ctx->pending_redirect) {
2917 ctx->pending_redirect = NULL;
2918 if (glob_target->gl_pathc != 1) {
2919 bb_error_msg("ambiguous redirect");
2920 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2924 child->argv = glob_target->gl_pathv;
2926 if (ctx->res_w == RES_FOR) {
2927 done_word(dest, ctx);
2928 done_pipe(ctx, PIPE_SEQ);
2930 debug_printf_parse("done_word return 0\n");
2934 /* The only possible error here is out of memory, in which case
2936 static int done_command(struct p_context *ctx)
2938 /* The child is really already in the pipe structure, so
2939 * advance the pipe counter and make a new, null child. */
2940 struct pipe *pi = ctx->pipe;
2941 struct child_prog *child = ctx->child;
2944 if (child->group == NULL
2945 && child->argv == NULL
2946 && child->redirects == NULL
2948 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2949 return pi->num_progs;
2952 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2954 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2957 /* Only real trickiness here is that the uncommitted
2958 * child structure is not counted in pi->num_progs. */
2959 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2960 child = &pi->progs[pi->num_progs];
2962 memset(child, 0, sizeof(*child));
2963 /*child->redirects = NULL;*/
2964 /*child->argv = NULL;*/
2965 /*child->is_stopped = 0;*/
2966 /*child->group = NULL;*/
2967 /*child->glob_result.gl_pathv = NULL;*/
2969 //sp: /*child->sp = 0;*/
2970 child->type = ctx->parse_type;
2973 /* but ctx->pipe and ctx->list_head remain unchanged */
2975 return pi->num_progs; /* used only for 0/nonzero check */
2978 static int done_pipe(struct p_context *ctx, pipe_style type)
2983 debug_printf_parse("done_pipe entered, followup %d\n", type);
2984 not_null = done_command(ctx); /* implicit closure of previous command */
2985 ctx->pipe->followup = type;
2986 ctx->pipe->r_mode = ctx->res_w;
2987 /* Without this check, even just <enter> on command line generates
2988 * tree of three NOPs (!). Which is harmless but annoying.
2989 * IOW: it is safe to do it unconditionally. */
2992 ctx->pipe->next = new_p;
2995 done_command(ctx); /* set up new pipe to accept commands */
2997 debug_printf_parse("done_pipe return 0\n");
3001 /* peek ahead in the in_str to find out if we have a "&n" construct,
3002 * as in "2>&1", that represents duplicating a file descriptor.
3003 * returns either -2 (syntax error), -1 (no &), or the number found.
3005 static int redirect_dup_num(struct in_str *input)
3007 int ch, d = 0, ok = 0;
3009 if (ch != '&') return -1;
3011 b_getch(input); /* get the & */
3015 return -3; /* "-" represents "close me" */
3017 while (isdigit(ch)) {
3018 d = d*10 + (ch-'0');
3025 bb_error_msg("ambiguous redirect");
3029 /* If a redirect is immediately preceded by a number, that number is
3030 * supposed to tell which file descriptor to redirect. This routine
3031 * looks for such preceding numbers. In an ideal world this routine
3032 * needs to handle all the following classes of redirects...
3033 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3034 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3035 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3036 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3037 * A -1 output from this program means no valid number was found, so the
3038 * caller should use the appropriate default for this redirection.
3040 static int redirect_opt_num(o_string *o)
3046 for (num = 0; num < o->length; num++) {
3047 if (!isdigit(*(o->data + num))) {
3051 /* reuse num (and save an int) */
3052 num = atoi(o->data);
3057 static FILE *generate_stream_from_list(struct pipe *head)
3060 int pid, channel[2];
3061 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
3068 bb_perror_msg_and_die("fork");
3069 } else if (pid == 0) {
3071 if (channel[1] != 1) {
3072 dup2(channel[1], 1);
3075 _exit(run_list_real(head)); /* leaks memory */
3077 debug_printf("forked child %d\n", pid);
3079 pf = fdopen(channel[0], "r");
3080 debug_printf("pipe on FILE *%p\n", pf);
3084 /* Return code is exit status of the process that is run. */
3085 static int process_command_subs(o_string *dest, struct p_context *ctx,
3086 struct in_str *input, const char *subst_end)
3088 int retcode, ch, eol_cnt;
3089 o_string result = NULL_O_STRING;
3090 struct p_context inner;
3092 struct in_str pipe_str;
3094 initialize_context(&inner);
3096 /* recursion to generate command */
3097 retcode = parse_stream(&result, &inner, input, subst_end);
3098 if (retcode != 0) return retcode; /* syntax error or EOF */
3099 done_word(&result, &inner);
3100 done_pipe(&inner, PIPE_SEQ);
3103 p = generate_stream_from_list(inner.list_head);
3104 if (p == NULL) return 1;
3105 mark_open(fileno(p));
3106 setup_file_in_str(&pipe_str, p);
3108 /* now send results of command back into original context */
3110 while ((ch = b_getch(&pipe_str)) != EOF) {
3116 b_addqchr(dest, '\n', dest->quote);
3119 b_addqchr(dest, ch, dest->quote);
3122 debug_printf("done reading from pipe, pclose()ing\n");
3123 /* This is the step that wait()s for the child. Should be pretty
3124 * safe, since we just read an EOF from its stdout. We could try
3125 * to better, by using wait(), and keeping track of background jobs
3126 * at the same time. That would be a lot of work, and contrary
3127 * to the KISS philosophy of this program. */
3128 mark_closed(fileno(p));
3129 retcode = pclose(p);
3130 free_pipe_list(inner.list_head, 0);
3131 debug_printf("pclosed, retcode=%d\n", retcode);
3135 static int parse_group(o_string *dest, struct p_context *ctx,
3136 struct in_str *input, int ch)
3139 const char *endch = NULL;
3140 struct p_context sub;
3141 struct child_prog *child = ctx->child;
3143 debug_printf_parse("parse_group entered\n");
3146 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3149 initialize_context(&sub);
3153 child->subshell = 1;
3159 syntax(); /* really logic error */
3161 rcode = parse_stream(dest, &sub, input, endch);
3162 done_word(dest, &sub); /* finish off the final word in the subcontext */
3163 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3164 child->group = sub.list_head;
3166 debug_printf_parse("parse_group return %d\n", rcode);
3168 /* child remains "open", available for possible redirects */
3171 /* Basically useful version until someone wants to get fancier,
3172 * see the bash man page under "Parameter Expansion" */
3173 static const char *lookup_param(const char *src)
3175 const char *p = NULL;
3179 p = get_local_var(src);
3184 /* Make new string for parser */
3185 static char* make_string(char **inp)
3193 for (n = 0; inp[n]; n++) {
3194 p = expand_variables_to_string(inp[n]);
3195 val_len = strlen(p);
3196 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3198 strcpy(str + len, p);
3200 if (p != inp[n]) free(p);
3202 /* We do not check for case where loop had no iterations at all
3203 * - cannot happen? */
3209 /* return code: 0 for OK, 1 for syntax error */
3210 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3212 int ch = b_peek(input); /* first character after the $ */
3213 unsigned char quote_mask = dest->quote ? 0x80 : 0;
3215 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3217 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3218 //sp: ctx->child->sp++;
3220 debug_printf_parse(": '%c'\n", ch);
3222 b_addchr(dest, ch | quote_mask);
3225 if (!isalnum(ch) && ch != '_')
3228 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3229 } else if (isdigit(ch)) {
3231 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3232 //sp: ctx->child->sp++;
3233 debug_printf_parse(": '%c'\n", ch);
3235 b_addchr(dest, ch | quote_mask);
3236 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3237 } else switch (ch) {
3239 case '!': /* last bg pid */
3240 case '?': /* last exit code */
3241 case '#': /* number of args */
3242 case '*': /* args */
3243 case '@': /* args */
3244 goto make_one_char_var;
3246 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3247 //sp: ctx->child->sp++;
3249 /* XXX maybe someone will try to escape the '}' */
3251 ch = b_getch(input);
3254 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3259 debug_printf_parse(": '%c'\n", ch);
3260 b_addchr(dest, ch | quote_mask);
3263 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3267 process_command_subs(dest, ctx, input, ")");
3271 /* still unhandled, but should be eventually */
3272 bb_error_msg("unhandled syntax: $%c", ch);
3276 b_addqchr(dest, '$', dest->quote);
3278 debug_printf_parse("handle_dollar return 0\n");
3282 /* return code is 0 for normal exit, 1 for syntax error */
3283 static int parse_stream(o_string *dest, struct p_context *ctx,
3284 struct in_str *input, const char *end_trigger)
3288 redir_type redir_style;
3291 /* Only double-quote state is handled in the state variable dest->quote.
3292 * A single-quote triggers a bypass of the main loop until its mate is
3293 * found. When recursing, quote state is passed in via dest->quote. */
3295 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3297 while ((ch = b_getch(input)) != EOF) {
3299 next = (ch == '\n') ? '\0' : b_peek(input);
3300 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3301 ch, ch, m, dest->quote);
3302 if (m == CHAR_ORDINARY
3303 || (m != CHAR_SPECIAL && dest->quote)
3305 b_addqchr(dest, ch, dest->quote);
3308 if (m == CHAR_IFS) {
3309 if (done_word(dest, ctx)) {
3310 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3313 /* If we aren't performing a substitution, treat
3314 * a newline as a command separator.
3315 * [why we don't handle it exactly like ';'? --vda] */
3316 if (end_trigger && ch == '\n') {
3317 done_pipe(ctx, PIPE_SEQ);
3320 if ((end_trigger && strchr(end_trigger, ch))
3321 && !dest->quote && ctx->res_w == RES_NONE
3323 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3330 if (dest->length == 0 && !dest->quote) {
3333 if (ch == EOF || ch == '\n')
3338 b_addqchr(dest, ch, dest->quote);
3344 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3347 b_addqchr(dest, '\\', dest->quote);
3348 b_addqchr(dest, b_getch(input), dest->quote);
3351 if (handle_dollar(dest, ctx, input) != 0) {
3352 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3359 ch = b_getch(input);
3360 if (ch == EOF || ch == '\'')
3366 debug_printf_parse("parse_stream return 1: unterminated '\n");
3372 dest->quote = !dest->quote;
3375 process_command_subs(dest, ctx, input, "`");
3378 redir_fd = redirect_opt_num(dest);
3379 done_word(dest, ctx);
3380 redir_style = REDIRECT_OVERWRITE;
3382 redir_style = REDIRECT_APPEND;
3384 } else if (next == '(') {
3385 syntax(); /* until we support >(list) Process Substitution */
3386 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3389 setup_redirect(ctx, redir_fd, redir_style, input);
3392 redir_fd = redirect_opt_num(dest);
3393 done_word(dest, ctx);
3394 redir_style = REDIRECT_INPUT;
3396 redir_style = REDIRECT_HEREIS;
3398 } else if (next == '>') {
3399 redir_style = REDIRECT_IO;
3401 } else if (next == '(') {
3402 syntax(); /* until we support <(list) Process Substitution */
3403 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3406 setup_redirect(ctx, redir_fd, redir_style, input);
3409 done_word(dest, ctx);
3410 done_pipe(ctx, PIPE_SEQ);
3413 done_word(dest, ctx);
3416 done_pipe(ctx, PIPE_AND);
3418 done_pipe(ctx, PIPE_BG);
3422 done_word(dest, ctx);
3425 done_pipe(ctx, PIPE_OR);
3427 /* we could pick up a file descriptor choice here
3428 * with redirect_opt_num(), but bash doesn't do it.
3429 * "echo foo 2| cat" yields "foo 2". */
3435 if (parse_group(dest, ctx, input, ch) != 0) {
3436 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3442 syntax(); /* Proper use of this character is caught by end_trigger */
3443 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3446 syntax(); /* this is really an internal logic error */
3447 debug_printf_parse("parse_stream return 1: internal logic error\n");
3451 /* Complain if quote? No, maybe we just finished a command substitution
3452 * that was quoted. Example:
3453 * $ echo "`cat foo` plus more"
3454 * and we just got the EOF generated by the subshell that ran "cat foo"
3455 * The only real complaint is if we got an EOF when end_trigger != NULL,
3456 * that is, we were really supposed to get end_trigger, and never got
3457 * one before the EOF. Can't use the standard "syntax error" return code,
3458 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3459 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3465 static void set_in_charmap(const char *set, int code)
3468 charmap[(unsigned char)*set++] = code;
3471 static void update_charmap(void)
3473 /* char *ifs and char charmap[256] are both globals. */
3474 ifs = getenv("IFS");
3477 /* Precompute a list of 'flow through' behavior so it can be treated
3478 * quickly up front. Computation is necessary because of IFS.
3479 * Special case handling of IFS == " \t\n" is not implemented.
3480 * The charmap[] array only really needs two bits each,
3481 * and on most machines that would be faster (reduced L1 cache use).
3483 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3484 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3485 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3486 set_in_charmap(ifs, CHAR_IFS); /* also flow through if quoted */
3489 /* most recursion does not come through here, the exception is
3490 * from builtin_source() */
3491 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3493 struct p_context ctx;
3494 o_string temp = NULL_O_STRING;
3497 ctx.parse_type = parse_flag;
3498 initialize_context(&ctx);
3500 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3501 set_in_charmap(";$&|", CHAR_ORDINARY);
3502 #if ENABLE_HUSH_INTERACTIVE
3503 inp->promptmode = 1;
3505 /* We will stop & execute after each ';' or '\n'.
3506 * Example: "sleep 9999; echo TEST" + ctrl-C:
3507 * TEST should be printed */
3508 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3509 if (rcode != 1 && ctx.old_flag != 0) {
3512 if (rcode != 1 && ctx.old_flag == 0) {
3513 done_word(&temp, &ctx);
3514 done_pipe(&ctx, PIPE_SEQ);
3515 debug_print_tree(ctx.list_head, 0);
3516 debug_printf_exec("parse_stream_outer: run_list\n");
3517 run_list(ctx.list_head);
3519 if (ctx.old_flag != 0) {
3526 free_pipe_list(ctx.list_head, 0);
3529 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3533 static int parse_string_outer(const char *s, int parse_flag)
3535 struct in_str input;
3536 setup_string_in_str(&input, s);
3537 return parse_stream_outer(&input, parse_flag);
3540 static int parse_file_outer(FILE *f)
3543 struct in_str input;
3544 setup_file_in_str(&input, f);
3545 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3550 /* Make sure we have a controlling tty. If we get started under a job
3551 * aware app (like bash for example), make sure we are now in charge so
3552 * we don't fight over who gets the foreground */
3553 static void setup_job_control(void)
3557 saved_task_pgrp = shell_pgrp = getpgrp();
3558 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3559 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3561 /* If we were ran as 'hush &',
3562 * sleep until we are in the foreground. */
3563 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3564 /* Send TTIN to ourself (should stop us) */
3565 kill(- shell_pgrp, SIGTTIN);
3566 shell_pgrp = getpgrp();
3569 /* Ignore job-control and misc signals. */
3570 set_jobctrl_sighandler(SIG_IGN);
3571 set_misc_sighandler(SIG_IGN);
3572 //huh? signal(SIGCHLD, SIG_IGN);
3574 /* We _must_ restore tty pgrp on fatal signals */
3575 set_fatal_sighandler(sigexit);
3577 /* Put ourselves in our own process group. */
3578 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3579 /* Grab control of the terminal. */
3580 tcsetpgrp(interactive_fd, getpid());
3584 int hush_main(int argc, char **argv);
3585 int hush_main(int argc, char **argv)
3591 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3592 top_vars = &shell_ver;
3593 shell_ver = const_shell_ver; /* copying struct here */
3595 #if ENABLE_FEATURE_EDITING
3596 line_input_state = new_line_input_t(FOR_SHELL);
3598 /* XXX what should these be while sourcing /etc/profile? */
3601 /* Initialize some more globals to non-zero values */
3603 #if ENABLE_HUSH_INTERACTIVE
3604 #if ENABLE_FEATURE_EDITING
3605 cmdedit_set_initial_prompt();
3610 /* initialize our shell local variables with the values
3611 * currently living in the environment */
3615 set_local_var(*e++, 2); /* without call putenv() */
3617 last_return_code = EXIT_SUCCESS;
3619 if (argv[0] && argv[0][0] == '-') {
3620 debug_printf("sourcing /etc/profile\n");
3621 input = fopen("/etc/profile", "r");
3622 if (input != NULL) {
3623 mark_open(fileno(input));
3624 parse_file_outer(input);
3625 mark_closed(fileno(input));
3631 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3634 global_argv = argv + optind;
3635 global_argc = argc - optind;
3636 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3639 /* Well, we cannot just declare interactiveness,
3640 * we have to have some stuff (ctty, etc) */
3641 /* interactive_fd++; */
3648 fprintf(stderr, "Usage: sh [FILE]...\n"
3649 " or: sh -c command [args]...\n\n");
3657 /* A shell is interactive if the '-i' flag was given, or if all of
3658 * the following conditions are met:
3660 * no arguments remaining or the -s flag given
3661 * standard input is a terminal
3662 * standard output is a terminal
3663 * Refer to Posix.2, the description of the 'sh' utility. */
3664 if (argv[optind] == NULL && input == stdin
3665 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3667 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3668 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3669 if (saved_tty_pgrp >= 0) {
3670 /* try to dup to high fd#, >= 255 */
3671 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3672 if (interactive_fd < 0) {
3673 /* try to dup to any fd */
3674 interactive_fd = dup(STDIN_FILENO);
3675 if (interactive_fd < 0)
3679 // TODO: track & disallow any attempts of user
3680 // to (inadvertently) close/redirect it
3683 debug_printf("interactive_fd=%d\n", interactive_fd);
3684 if (interactive_fd) {
3685 /* Looks like they want an interactive shell */
3686 setup_job_control();
3687 /* Make xfuncs do cleanup on exit */
3688 die_sleep = -1; /* flag */
3689 // FIXME: should we reset die_sleep = 0 whereever we fork?
3690 if (setjmp(die_jmp)) {
3691 /* xfunc has failed! die die die */
3692 hush_exit(xfunc_error_retval);
3694 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3695 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3696 printf("Enter 'help' for a list of built-in commands.\n\n");
3699 #elif ENABLE_HUSH_INTERACTIVE
3700 /* no job control compiled, only prompt/line editing */
3701 if (argv[optind] == NULL && input == stdin
3702 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3704 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3705 if (interactive_fd < 0) {
3706 /* try to dup to any fd */
3707 interactive_fd = dup(STDIN_FILENO);
3708 if (interactive_fd < 0)
3716 if (argv[optind] == NULL) {
3717 opt = parse_file_outer(stdin);
3721 debug_printf("\nrunning script '%s'\n", argv[optind]);
3722 global_argv = argv + optind;
3723 global_argc = argc - optind;
3724 input = xfopen(argv[optind], "r");
3725 opt = parse_file_outer(input);
3727 #if ENABLE_FEATURE_CLEAN_UP
3729 if (cwd != bb_msg_unknown)
3732 struct variables *cur, *tmp;
3733 for (cur = top_vars; cur; cur = tmp) {
3735 if (!cur->flg_read_only) {
3736 free((char*)cur->name);
3737 free((char*)cur->value);
3745 hush_exit(opt ? opt : last_return_code);