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
141 #define PARSEFLAG_EXIT_FROM_LOOP 1
142 #define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
143 #define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
147 REDIRECT_OVERWRITE = 2,
153 /* The descrip member of this structure is only used to make debugging
155 static const struct {
157 signed char default_fd;
161 { O_RDONLY, 0, "<" },
162 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
163 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
164 { O_RDONLY, -1, "<<" },
175 /* might eventually control execution */
193 FLAG_END = (1 << RES_NONE ),
194 FLAG_IF = (1 << RES_IF ),
195 FLAG_THEN = (1 << RES_THEN ),
196 FLAG_ELIF = (1 << RES_ELIF ),
197 FLAG_ELSE = (1 << RES_ELSE ),
198 FLAG_FI = (1 << RES_FI ),
199 FLAG_FOR = (1 << RES_FOR ),
200 FLAG_WHILE = (1 << RES_WHILE),
201 FLAG_UNTIL = (1 << RES_UNTIL),
202 FLAG_DO = (1 << RES_DO ),
203 FLAG_DONE = (1 << RES_DONE ),
204 FLAG_IN = (1 << RES_IN ),
205 FLAG_START = (1 << RES_XXXX ),
208 /* This holds pointers to the various results of parsing */
210 struct child_prog *child;
211 struct pipe *list_head;
213 struct redir_struct *pending_redirect;
215 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
216 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
217 struct p_context *stack;
218 /* How about quoting status? */
221 struct redir_struct {
222 struct redir_struct *next; /* pointer to the next redirect in the list */
223 redir_type type; /* type of redirection */
224 int fd; /* file descriptor being redirected */
225 int dup; /* -1, or file descriptor being duplicated */
226 glob_t word; /* *word.gl_pathv is the filename */
230 pid_t pid; /* 0 if exited */
231 char **argv; /* program name and arguments */
232 struct pipe *group; /* if non-NULL, first in group or subshell */
233 smallint subshell; /* flag, non-zero if group must be forked */
234 smallint is_stopped; /* is the program currently running? */
235 struct redir_struct *redirects; /* I/O redirections */
236 glob_t glob_result; /* result of parameter globbing */
237 struct pipe *family; /* pointer back to the child's parent pipe */
238 //sp counting seems to be broken... so commented out, grep for '//sp:'
239 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
240 //seems to be unused, grep for '//pt:'
241 //pt: int parse_type;
243 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
244 * and on execution these are substituted with their values.
245 * Substitution can make _several_ words out of one argv[n]!
246 * Example: argv[0]=='.^C*^C.' here: echo .$*.
251 int num_progs; /* total number of programs in job */
252 int running_progs; /* number of programs running (not exited) */
253 int stopped_progs; /* number of programs alive, but stopped */
255 int jobid; /* job number */
256 pid_t pgrp; /* process group ID for the job */
257 char *cmdtext; /* name of job */
259 char *cmdbuf; /* buffer various argv's point into */
260 struct child_prog *progs; /* array of commands in pipe */
261 int job_context; /* bitmask defining current context */
262 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
263 smallint res_word; /* needed for if, for, while, until... */
267 struct close_me *next;
272 struct variables *next;
276 smallint flg_read_only;
286 #define NULL_O_STRING {NULL,0,0,0,0}
287 /* used for initialization: o_string foo = NULL_O_STRING; */
289 /* I can almost use ordinary FILE *. Is open_memstream() universally
290 * available? Where is it documented? */
293 /* eof_flag=1: last char in ->p is really an EOF */
294 char eof_flag; /* meaningless if ->p == NULL */
296 #if ENABLE_HUSH_INTERACTIVE
301 int (*get) (struct in_str *);
302 int (*peek) (struct in_str *);
304 #define b_getch(input) ((input)->get(input))
305 #define b_peek(input) ((input)->peek(input))
309 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
310 CHAR_IFS = 2, /* treated as ordinary if quoted */
311 CHAR_SPECIAL = 3, /* example: $ */
315 /* "Globals" within this file */
317 #define HUSH_VER_STR "0.02"
318 static const struct variables const_shell_ver = {
319 NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1
322 /* Sorted roughly by size (smaller offsets == smaller code) */
324 #if ENABLE_HUSH_INTERACTIVE
325 /* 'interactive_fd' is a fd# open to ctty, if we have one
326 * _AND_ if we decided to act interactively */
331 #if ENABLE_FEATURE_EDITING
332 line_input_t *line_input_state;
336 pid_t saved_task_pgrp;
337 pid_t saved_tty_pgrp;
339 struct pipe *job_list;
340 struct pipe *toplevel_list;
341 smallint ctrl_z_flag;
344 /* these three support $?, $#, and $1 */
347 int last_return_code;
349 struct close_me *close_me_head;
351 unsigned last_bg_pid;
352 struct variables *top_vars; /* = &shell_ver (both are set in main()) */
353 struct variables shell_ver; /* = const_shell_ver */
354 #if ENABLE_FEATURE_SH_STANDALONE
355 struct nofork_save_area nofork_save;
358 sigjmp_buf toplevel_jb;
360 unsigned char charmap[256];
361 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
364 #define G (*ptr_to_globals)
366 #if !ENABLE_HUSH_INTERACTIVE
367 enum { interactive_fd = 0 };
370 enum { run_list_level = 0 };
373 #if ENABLE_HUSH_INTERACTIVE
374 #define interactive_fd (G.interactive_fd )
378 #if ENABLE_FEATURE_EDITING
379 #define line_input_state (G.line_input_state)
382 #define run_list_level (G.run_list_level )
383 #define saved_task_pgrp (G.saved_task_pgrp )
384 #define saved_tty_pgrp (G.saved_tty_pgrp )
385 #define last_jobid (G.last_jobid )
386 #define job_list (G.job_list )
387 #define toplevel_list (G.toplevel_list )
388 #define toplevel_jb (G.toplevel_jb )
389 #define ctrl_z_flag (G.ctrl_z_flag )
391 #define global_argv (G.global_argv )
392 #define global_argc (G.global_argc )
393 #define last_return_code (G.last_return_code)
395 #define fake_mode (G.fake_mode )
396 #define close_me_head (G.close_me_head )
398 #define last_bg_pid (G.last_bg_pid )
399 #define top_vars (G.top_vars )
400 #define shell_ver (G.shell_ver )
401 #if ENABLE_FEATURE_SH_STANDALONE
402 #define nofork_save (G.nofork_save )
405 #define toplevel_jb (G.toplevel_jb )
407 #define charmap (G.charmap )
408 #define user_input_buf (G.user_input_buf )
413 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
415 static void __syntax(int line)
417 bb_error_msg("syntax error hush.c:%d", line);
419 #define syntax() __syntax(__LINE__)
421 /* Index of subroutines: */
422 /* function prototypes for builtins */
423 static int builtin_cd(char **argv);
424 static int builtin_eval(char **argv);
425 static int builtin_exec(char **argv);
426 static int builtin_exit(char **argv);
427 static int builtin_export(char **argv);
429 static int builtin_fg_bg(char **argv);
430 static int builtin_jobs(char **argv);
432 static int builtin_help(char **argv);
433 static int builtin_pwd(char **argv);
434 static int builtin_read(char **argv);
435 static int builtin_set(char **argv);
436 static int builtin_shift(char **argv);
437 static int builtin_source(char **argv);
438 static int builtin_umask(char **argv);
439 static int builtin_unset(char **argv);
440 static int builtin_not_written(char **argv);
441 /* o_string manipulation: */
442 static int b_check_space(o_string *o, int len);
443 static int b_addchr(o_string *o, int ch);
444 static void b_reset(o_string *o);
445 static int b_addqchr(o_string *o, int ch, int quote);
446 /* in_str manipulations: */
447 static int static_get(struct in_str *i);
448 static int static_peek(struct in_str *i);
449 static int file_get(struct in_str *i);
450 static int file_peek(struct in_str *i);
451 static void setup_file_in_str(struct in_str *i, FILE *f);
452 static void setup_string_in_str(struct in_str *i, const char *s);
453 /* close_me manipulations: */
454 static void mark_open(int fd);
455 static void mark_closed(int fd);
456 static void close_all(void);
457 /* "run" the final data structures: */
458 #if !defined(DEBUG_CLEAN)
459 #define free_pipe_list(head, indent) free_pipe_list(head)
460 #define free_pipe(pi, indent) free_pipe(pi)
462 static int free_pipe_list(struct pipe *head, int indent);
463 static int free_pipe(struct pipe *pi, int indent);
464 /* really run the final data structures: */
465 static int setup_redirects(struct child_prog *prog, int squirrel[]);
466 static int run_list_real(struct pipe *pi);
467 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
468 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
469 static int run_pipe_real(struct pipe *pi);
470 /* extended glob support: */
471 static int globhack(const char *src, int flags, glob_t *pglob);
472 static int glob_needed(const char *s);
473 static int xglob(o_string *dest, int flags, glob_t *pglob);
474 /* variable assignment: */
475 static int is_assignment(const char *s);
476 /* data structure manipulation: */
477 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
478 static void initialize_context(struct p_context *ctx);
479 static int done_word(o_string *dest, struct p_context *ctx);
480 static int done_command(struct p_context *ctx);
481 static int done_pipe(struct p_context *ctx, pipe_style type);
482 /* primary string parsing: */
483 static int redirect_dup_num(struct in_str *input);
484 static int redirect_opt_num(o_string *o);
486 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
488 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
489 static const char *lookup_param(const char *src);
490 static char *make_string(char **inp);
491 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
492 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
494 static int parse_stream_outer(struct in_str *inp, int parse_flag);
495 static int parse_string_outer(const char *s, int parse_flag);
496 static int parse_file_outer(FILE *f);
497 /* job management: */
498 static int checkjobs(struct pipe* fg_pipe);
500 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
501 static void insert_bg_job(struct pipe *pi);
502 static void remove_bg_job(struct pipe *pi);
503 static void delete_finished_bg_job(struct pipe *pi);
505 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
507 /* local variable support */
508 static char **expand_variables_to_list(char **argv);
509 /* used for expansion of right hand of assignments */
510 static char *expand_variables_to_string(const char *str);
511 static const char *get_local_var(const char *var);
512 static int set_local_var(const char *s, int flg_export);
513 static void unset_local_var(const char *name);
515 /* Table of built-in functions. They can be forked or not, depending on
516 * context: within pipes, they fork. As simple commands, they do not.
517 * When used in non-forking context, they can change global variables
518 * in the parent shell process. If forked, of course they cannot.
519 * For example, 'unset foo | whatever' will parse and run, but foo will
520 * still be set at the end. */
521 struct built_in_command {
522 const char *cmd; /* name */
523 const char *descr; /* description */
524 int (*function) (char **argv); /* function ptr */
527 static const struct built_in_command bltins[] = {
529 { "bg", "Resume a job in the background", builtin_fg_bg },
531 { "break", "Exit for, while or until loop", builtin_not_written },
532 { "cd", "Change working directory", builtin_cd },
533 { "continue", "Continue for, while or until loop", builtin_not_written },
534 { "eval", "Construct and run shell command", builtin_eval },
535 { "exec", "Exec command, replacing this shell with the exec'd process",
537 { "exit", "Exit from shell()", builtin_exit },
538 { "export", "Set environment variable", builtin_export },
540 { "fg", "Bring job into the foreground", builtin_fg_bg },
541 { "jobs", "Lists the active jobs", builtin_jobs },
543 { "pwd", "Print current directory", builtin_pwd },
544 { "read", "Input environment variable", builtin_read },
545 { "return", "Return from a function", builtin_not_written },
546 { "set", "Set/unset shell local variables", builtin_set },
547 { "shift", "Shift positional parameters", builtin_shift },
548 { "trap", "Trap signals", builtin_not_written },
549 { "ulimit","Controls resource limits", builtin_not_written },
550 { "umask","Sets file creation mask", builtin_umask },
551 { "unset", "Unset environment variable", builtin_unset },
552 { ".", "Source-in and run commands in a file", builtin_source },
553 { "help", "List shell built-in commands", builtin_help },
560 static void signal_SA_RESTART(int sig, void (*handler)(int))
563 sa.sa_handler = handler;
564 sa.sa_flags = SA_RESTART;
565 sigemptyset(&sa.sa_mask);
566 sigaction(sig, &sa, NULL);
569 /* Signals are grouped, we handle them in batches */
570 static void set_fatal_sighandler(void (*handler)(int))
572 signal(SIGILL , handler);
573 signal(SIGTRAP, handler);
574 signal(SIGABRT, handler);
575 signal(SIGFPE , handler);
576 signal(SIGBUS , handler);
577 signal(SIGSEGV, handler);
578 /* bash 3.2 seems to handle these just like 'fatal' ones */
579 signal(SIGHUP , handler);
580 signal(SIGPIPE, handler);
581 signal(SIGALRM, handler);
583 static void set_jobctrl_sighandler(void (*handler)(int))
585 signal(SIGTSTP, handler);
586 signal(SIGTTIN, handler);
587 signal(SIGTTOU, handler);
589 static void set_misc_sighandler(void (*handler)(int))
591 signal(SIGINT , handler);
592 signal(SIGQUIT, handler);
593 signal(SIGTERM, handler);
595 /* SIGCHLD is special and handled separately */
597 static void set_every_sighandler(void (*handler)(int))
599 set_fatal_sighandler(handler);
600 set_jobctrl_sighandler(handler);
601 set_misc_sighandler(handler);
602 signal(SIGCHLD, handler);
605 static void handler_ctrl_c(int sig)
607 debug_printf_jobs("got sig %d\n", sig);
608 // as usual we can have all kinds of nasty problems with leaked malloc data here
609 siglongjmp(toplevel_jb, 1);
612 static void handler_ctrl_z(int sig)
616 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
618 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
621 if (!pid) { /* child */
623 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
624 set_every_sighandler(SIG_DFL);
625 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
626 debug_printf_jobs("returning in child\n");
627 /* return to nofork, it will eventually exit now,
628 * not return back to shell */
632 /* finish filling up pipe info */
633 toplevel_list->pgrp = pid; /* child is in its own pgrp */
634 toplevel_list->progs[0].pid = pid;
635 /* parent needs to longjmp out of running nofork.
636 * we will "return" exitcode 0, with child put in background */
637 // as usual we can have all kinds of nasty problems with leaked malloc data here
638 debug_printf_jobs("siglongjmp in parent\n");
639 siglongjmp(toplevel_jb, 1);
642 /* Restores tty foreground process group, and exits.
643 * May be called as signal handler for fatal signal
644 * (will faithfully resend signal to itself, producing correct exit state)
645 * or called directly with -EXITCODE.
646 * We also call it if xfunc is exiting. */
647 static void sigexit(int sig) ATTRIBUTE_NORETURN;
648 static void sigexit(int sig)
652 /* Disable all signals: job control, SIGPIPE, etc. */
653 sigfillset(&block_all);
654 sigprocmask(SIG_SETMASK, &block_all, NULL);
657 tcsetpgrp(interactive_fd, saved_tty_pgrp);
659 /* Not a signal, just exit */
663 /* Enable only this sig and kill ourself with it */
664 signal(sig, SIG_DFL);
665 sigdelset(&block_all, sig);
666 sigprocmask(SIG_SETMASK, &block_all, NULL);
668 _exit(1); /* Should not reach it */
671 /* Restores tty foreground process group, and exits. */
672 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
673 static void hush_exit(int exitcode)
675 fflush(NULL); /* flush all streams */
676 sigexit(- (exitcode & 0xff));
681 #define set_fatal_sighandler(handler) ((void)0)
682 #define set_jobctrl_sighandler(handler) ((void)0)
683 #define set_misc_sighandler(handler) ((void)0)
684 #define hush_exit(e) exit(e)
689 static const char *set_cwd(void)
691 if (cwd == bb_msg_unknown)
692 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
693 cwd = xrealloc_getcwd_or_warn((char *)cwd);
695 cwd = bb_msg_unknown;
699 /* built-in 'eval' handler */
700 static int builtin_eval(char **argv)
703 int rcode = EXIT_SUCCESS;
706 str = make_string(argv + 1);
707 parse_string_outer(str, PARSEFLAG_EXIT_FROM_LOOP |
708 PARSEFLAG_SEMICOLON);
710 rcode = last_return_code;
715 /* built-in 'cd <path>' handler */
716 static int builtin_cd(char **argv)
720 newdir = getenv("HOME");
724 printf("cd: %s: %s\n", newdir, strerror(errno));
731 /* built-in 'exec' handler */
732 static int builtin_exec(char **argv)
735 return EXIT_SUCCESS; /* Really? */
736 pseudo_exec_argv(argv + 1);
740 /* built-in 'exit' handler */
741 static int builtin_exit(char **argv)
743 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
744 //puts("exit"); /* bash does it */
745 // TODO: warn if we have background jobs: "There are stopped jobs"
746 // On second consecutive 'exit', exit anyway.
749 hush_exit(last_return_code);
750 /* mimic bash: exit 123abc == exit 255 + error msg */
751 xfunc_error_retval = 255;
752 /* bash: exit -2 == exit 254, no error msg */
753 hush_exit(xatoi(argv[1]) & 0xff);
756 /* built-in 'export VAR=value' handler */
757 static int builtin_export(char **argv)
760 char *name = argv[1];
764 // ash emits: export VAR='VAL'
765 // bash: declare -x VAR="VAL"
766 // (both also escape as needed (quotes, $, etc))
774 name = xstrdup(name);
776 const char *value = strchr(name, '=');
780 /* They are exporting something without an =VALUE */
782 value = get_local_var(name);
784 size_t ln = strlen(name);
786 tmp = xrealloc(name, ln+strlen(value)+2);
787 sprintf(tmp+ln, "=%s", value);
790 /* bash does not return an error when trying to export
791 * an undefined variable. Do likewise. */
797 bb_perror_msg("export");
799 res = set_local_var(name, 1);
807 /* built-in 'fg' and 'bg' handler */
808 static int builtin_fg_bg(char **argv)
815 /* If they gave us no args, assume they want the last backgrounded task */
817 for (pi = job_list; pi; pi = pi->next) {
818 if (pi->jobid == last_jobid) {
822 bb_error_msg("%s: no current job", argv[0]);
825 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
826 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
829 for (pi = job_list; pi; pi = pi->next) {
830 if (pi->jobid == jobnum) {
834 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
837 // TODO: bash prints a string representation
838 // of job being foregrounded (like "sleep 1 | cat")
839 if (*argv[0] == 'f') {
840 /* Put the job into the foreground. */
841 tcsetpgrp(interactive_fd, pi->pgrp);
844 /* Restart the processes in the job */
845 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
846 for (i = 0; i < pi->num_progs; i++) {
847 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
848 pi->progs[i].is_stopped = 0;
850 pi->stopped_progs = 0;
852 i = kill(- pi->pgrp, SIGCONT);
854 if (errno == ESRCH) {
855 delete_finished_bg_job(pi);
858 bb_perror_msg("kill (SIGCONT)");
862 if (*argv[0] == 'f') {
864 return checkjobs_and_fg_shell(pi);
870 /* built-in 'help' handler */
871 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
873 const struct built_in_command *x;
875 printf("\nBuilt-in commands:\n");
876 printf("-------------------\n");
877 for (x = bltins; x->cmd; x++) {
878 if (x->descr == NULL)
880 printf("%s\t%s\n", x->cmd, x->descr);
887 /* built-in 'jobs' handler */
888 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
891 const char *status_string;
893 for (job = job_list; job; job = job->next) {
894 if (job->running_progs == job->stopped_progs)
895 status_string = "Stopped";
897 status_string = "Running";
899 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
905 /* built-in 'pwd' handler */
906 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
912 /* built-in 'read VAR' handler */
913 static int builtin_read(char **argv)
917 const char *name = argv[1] ? argv[1] : "REPLY";
918 int name_len = strlen(name);
920 if (name_len >= sizeof(string) - 2)
922 strcpy(string, name);
923 p = string + name_len;
925 *p = '\0'; /* In case stdin has only EOF */
926 /* read string. name_len+1 chars are already used by 'name=' */
927 fgets(p, sizeof(string) - 1 - name_len, stdin);
929 return set_local_var(string, 0);
932 /* built-in 'set [VAR=value]' handler */
933 static int builtin_set(char **argv)
935 char *temp = argv[1];
939 for (e = top_vars; e; e = e->next)
940 printf("%s=%s\n", e->name, e->value);
942 set_local_var(temp, 0);
948 /* Built-in 'shift' handler */
949 static int builtin_shift(char **argv)
955 if (n >= 0 && n < global_argc) {
956 global_argv[n] = global_argv[0];
964 /* Built-in '.' handler (read-in and execute commands from file) */
965 static int builtin_source(char **argv)
973 /* XXX search through $PATH is missing */
974 input = fopen(argv[1], "r");
976 bb_error_msg("cannot open '%s'", argv[1]);
980 /* Now run the file */
981 /* XXX argv and argc are broken; need to save old global_argv
982 * (pointer only is OK!) on this stack frame,
983 * set global_argv=argv+1, recurse, and restore. */
984 mark_open(fileno(input));
985 status = parse_file_outer(input);
986 mark_closed(fileno(input));
991 static int builtin_umask(char **argv)
994 const char *arg = argv[1];
997 new_umask = strtoul(arg, &end, 8);
998 if (*end != '\0' || end == arg) {
1002 new_umask = umask(0);
1003 printf("%.3o\n", (unsigned) new_umask);
1006 return EXIT_SUCCESS;
1009 /* built-in 'unset VAR' handler */
1010 static int builtin_unset(char **argv)
1012 /* bash always returns true */
1013 unset_local_var(argv[1]);
1014 return EXIT_SUCCESS;
1017 static int builtin_not_written(char **argv)
1019 printf("builtin_%s not written\n", argv[0]);
1020 return EXIT_FAILURE;
1023 static int b_check_space(o_string *o, int len)
1025 /* It would be easy to drop a more restrictive policy
1026 * in here, such as setting a maximum string length */
1027 if (o->length + len > o->maxlen) {
1028 /* assert(data == NULL || o->maxlen != 0); */
1029 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1030 o->data = xrealloc(o->data, 1 + o->maxlen);
1032 return o->data == NULL;
1035 static int b_addchr(o_string *o, int ch)
1037 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1038 if (b_check_space(o, 1))
1040 o->data[o->length] = ch;
1042 o->data[o->length] = '\0';
1046 static void b_reset(o_string *o)
1050 if (o->data != NULL)
1054 static void b_free(o_string *o)
1062 /* My analysis of quoting semantics tells me that state information
1063 * is associated with a destination, not a source.
1065 static int b_addqchr(o_string *o, int ch, int quote)
1067 if (quote && strchr("*?[\\", ch)) {
1069 rc = b_addchr(o, '\\');
1073 return b_addchr(o, ch);
1076 static int static_get(struct in_str *i)
1079 if (ch == '\0') return EOF;
1083 static int static_peek(struct in_str *i)
1088 #if ENABLE_HUSH_INTERACTIVE
1089 #if ENABLE_FEATURE_EDITING
1090 static void cmdedit_set_initial_prompt(void)
1092 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1095 PS1 = getenv("PS1");
1100 #endif /* EDITING */
1102 static const char* setup_prompt_string(int promptmode)
1104 const char *prompt_str;
1105 debug_printf("setup_prompt_string %d ", promptmode);
1106 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1107 /* Set up the prompt */
1108 if (promptmode == 1) {
1111 ns = xmalloc(strlen(cwd)+4);
1112 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1119 prompt_str = (promptmode == 1) ? PS1 : PS2;
1121 debug_printf("result %s\n", prompt_str);
1125 static void get_user_input(struct in_str *i)
1128 const char *prompt_str;
1130 prompt_str = setup_prompt_string(i->promptmode);
1131 #if ENABLE_FEATURE_EDITING
1133 ** enable command line editing only while a command line
1134 ** is actually being read; otherwise, we'll end up bequeathing
1135 ** atexit() handlers and other unwanted stuff to our
1136 ** child processes (rob@sysgo.de)
1138 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1139 i->eof_flag = (r < 0);
1140 if (i->eof_flag) { /* EOF/error detected */
1141 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1142 user_input_buf[1] = '\0';
1145 fputs(prompt_str, stdout);
1147 user_input_buf[0] = r = fgetc(i->file);
1148 /*user_input_buf[1] = '\0'; - already is and never changed */
1149 i->eof_flag = (r == EOF);
1151 i->p = user_input_buf;
1153 #endif /* INTERACTIVE */
1155 /* This is the magic location that prints prompts
1156 * and gets data back from the user */
1157 static int file_get(struct in_str *i)
1161 /* If there is data waiting, eat it up */
1162 if (i->p && *i->p) {
1163 #if ENABLE_HUSH_INTERACTIVE
1167 if (i->eof_flag && !*i->p)
1170 /* need to double check i->file because we might be doing something
1171 * more complicated by now, like sourcing or substituting. */
1172 #if ENABLE_HUSH_INTERACTIVE
1173 if (interactive_fd && i->__promptme && i->file == stdin) {
1176 } while (!*i->p); /* need non-empty line */
1182 ch = fgetc(i->file);
1184 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1185 #if ENABLE_HUSH_INTERACTIVE
1192 /* All the callers guarantee this routine will never be
1193 * used right after a newline, so prompting is not needed.
1195 static int file_peek(struct in_str *i)
1198 if (i->p && *i->p) {
1199 if (i->eof_flag && !i->p[1])
1203 ch = fgetc(i->file);
1204 i->eof_flag = (ch == EOF);
1205 i->peek_buf[0] = ch;
1206 i->peek_buf[1] = '\0';
1208 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1212 static void setup_file_in_str(struct in_str *i, FILE *f)
1214 i->peek = file_peek;
1216 #if ENABLE_HUSH_INTERACTIVE
1224 static void setup_string_in_str(struct in_str *i, const char *s)
1226 i->peek = static_peek;
1227 i->get = static_get;
1228 #if ENABLE_HUSH_INTERACTIVE
1236 static void mark_open(int fd)
1238 struct close_me *new = xmalloc(sizeof(struct close_me));
1240 new->next = close_me_head;
1241 close_me_head = new;
1244 static void mark_closed(int fd)
1246 struct close_me *tmp;
1247 if (close_me_head == NULL || close_me_head->fd != fd)
1248 bb_error_msg_and_die("corrupt close_me");
1249 tmp = close_me_head;
1250 close_me_head = close_me_head->next;
1254 static void close_all(void)
1257 for (c = close_me_head; c; c = c->next) {
1260 close_me_head = NULL;
1263 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1264 * and stderr if they are redirected. */
1265 static int setup_redirects(struct child_prog *prog, int squirrel[])
1268 struct redir_struct *redir;
1270 for (redir = prog->redirects; redir; redir = redir->next) {
1271 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1272 /* something went wrong in the parse. Pretend it didn't happen */
1275 if (redir->dup == -1) {
1276 mode = redir_table[redir->type].mode;
1277 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1279 /* this could get lost if stderr has been redirected, but
1280 bash and ash both lose it as well (though zsh doesn't!) */
1284 openfd = redir->dup;
1287 if (openfd != redir->fd) {
1288 if (squirrel && redir->fd < 3) {
1289 squirrel[redir->fd] = dup(redir->fd);
1294 dup2(openfd, redir->fd);
1295 if (redir->dup == -1)
1303 static void restore_redirects(int squirrel[])
1306 for (i = 0; i < 3; i++) {
1309 /* We simply die on error */
1316 /* XXX no exit() here. If you don't exec, use _exit instead.
1317 * The at_exit handlers apparently confuse the calling process,
1318 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1319 static void pseudo_exec_argv(char **argv)
1323 const struct built_in_command *x;
1325 for (i = 0; is_assignment(argv[i]); i++) {
1326 debug_printf_exec("pid %d environment modification: %s\n",
1328 // FIXME: vfork case??
1329 p = expand_variables_to_string(argv[i]);
1330 putenv(p == argv[i] ? xstrdup(p) : p);
1333 /* If a variable is assigned in a forest, and nobody listens,
1334 * was it ever really set?
1336 if (argv[0] == NULL) {
1337 _exit(EXIT_SUCCESS);
1340 argv = expand_variables_to_list(argv);
1343 * Check if the command matches any of the builtins.
1344 * Depending on context, this might be redundant. But it's
1345 * easier to waste a few CPU cycles than it is to figure out
1346 * if this is one of those cases.
1348 for (x = bltins; x->cmd; x++) {
1349 if (strcmp(argv[0], x->cmd) == 0) {
1350 debug_printf_exec("running builtin '%s'\n", argv[0]);
1351 rcode = x->function(argv);
1357 /* Check if the command matches any busybox applets */
1358 #if ENABLE_FEATURE_SH_STANDALONE
1359 if (strchr(argv[0], '/') == NULL) {
1360 const struct bb_applet *a = find_applet_by_name(argv[0]);
1364 debug_printf_exec("running applet '%s'\n", argv[0]);
1365 // is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1366 run_current_applet_and_exit(argv);
1368 /* re-exec ourselves with the new arguments */
1369 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1370 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1371 /* If they called chroot or otherwise made the binary no longer
1372 * executable, fall through */
1377 debug_printf_exec("execing '%s'\n", argv[0]);
1378 execvp(argv[0], argv);
1379 bb_perror_msg("cannot exec '%s'", argv[0]);
1383 static void pseudo_exec(struct child_prog *child)
1385 // FIXME: buggy wrt NOMMU! Must not modify any global data
1386 // until it does exec/_exit, but currently it does.
1390 pseudo_exec_argv(child->argv);
1394 // FIXME: do not modify globals! Think vfork!
1395 #if ENABLE_HUSH_INTERACTIVE
1396 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1397 interactive_fd = 0; /* crucial!!!! */
1399 debug_printf_exec("pseudo_exec: run_list_real\n");
1400 rcode = run_list_real(child->group);
1401 /* OK to leak memory by not calling free_pipe_list,
1402 * since this process is about to exit */
1406 /* Can happen. See what bash does with ">foo" by itself. */
1407 debug_printf("trying to pseudo_exec null command\n");
1408 _exit(EXIT_SUCCESS);
1412 static const char *get_cmdtext(struct pipe *pi)
1418 /* This is subtle. ->cmdtext is created only on first backgrounding.
1419 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1420 * On subsequent bg argv is trashed, but we won't use it */
1423 argv = pi->progs[0].argv;
1424 if (!argv || !argv[0])
1425 return (pi->cmdtext = xzalloc(1));
1428 do len += strlen(*argv) + 1; while (*++argv);
1429 pi->cmdtext = p = xmalloc(len);
1430 argv = pi->progs[0].argv;
1432 len = strlen(*argv);
1433 memcpy(p, *argv, len);
1441 static void insert_bg_job(struct pipe *pi)
1443 struct pipe *thejob;
1446 /* Linear search for the ID of the job to use */
1448 for (thejob = job_list; thejob; thejob = thejob->next)
1449 if (thejob->jobid >= pi->jobid)
1450 pi->jobid = thejob->jobid + 1;
1452 /* Add thejob to the list of running jobs */
1454 thejob = job_list = xmalloc(sizeof(*thejob));
1456 for (thejob = job_list; thejob->next; thejob = thejob->next)
1458 thejob->next = xmalloc(sizeof(*thejob));
1459 thejob = thejob->next;
1462 /* Physically copy the struct job */
1463 memcpy(thejob, pi, sizeof(struct pipe));
1464 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1465 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1466 for (i = 0; i < pi->num_progs; i++) {
1467 // TODO: do we really need to have so many fields which are just dead weight
1468 // at execution stage?
1469 thejob->progs[i].pid = pi->progs[i].pid;
1470 /* all other fields are not used and stay zero */
1472 thejob->next = NULL;
1473 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1475 /* We don't wait for background thejobs to return -- append it
1476 to the list of backgrounded thejobs and leave it alone */
1477 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1478 last_bg_pid = thejob->progs[0].pid;
1479 last_jobid = thejob->jobid;
1482 static void remove_bg_job(struct pipe *pi)
1484 struct pipe *prev_pipe;
1486 if (pi == job_list) {
1487 job_list = pi->next;
1489 prev_pipe = job_list;
1490 while (prev_pipe->next != pi)
1491 prev_pipe = prev_pipe->next;
1492 prev_pipe->next = pi->next;
1495 last_jobid = job_list->jobid;
1500 /* remove a backgrounded job */
1501 static void delete_finished_bg_job(struct pipe *pi)
1504 pi->stopped_progs = 0;
1510 /* Checks to see if any processes have exited -- if they
1511 have, figure out why and see if a job has completed */
1512 static int checkjobs(struct pipe* fg_pipe)
1523 attributes = WUNTRACED;
1524 if (fg_pipe == NULL) {
1525 attributes |= WNOHANG;
1528 /* Do we do this right?
1529 * bash-3.00# sleep 20 | false
1531 * [3]+ Stopped sleep 20 | false
1532 * bash-3.00# echo $?
1533 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1536 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1537 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1538 // + killall -STOP cat
1541 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1542 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1544 #ifdef DEBUG_SHELL_JOBS
1545 if (WIFSTOPPED(status))
1546 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1547 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1548 if (WIFSIGNALED(status))
1549 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1550 childpid, WTERMSIG(status), WEXITSTATUS(status));
1551 if (WIFEXITED(status))
1552 debug_printf_jobs("pid %d exited, exitcode %d\n",
1553 childpid, WEXITSTATUS(status));
1555 /* Were we asked to wait for fg pipe? */
1558 for (i = 0; i < fg_pipe->num_progs; i++) {
1559 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1560 if (fg_pipe->progs[i].pid == childpid) {
1561 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1563 fg_pipe->progs[i].pid = 0;
1564 fg_pipe->running_progs--;
1565 if (i == fg_pipe->num_progs-1)
1566 /* last process gives overall exitstatus */
1567 rcode = WEXITSTATUS(status);
1569 fg_pipe->progs[i].is_stopped = 1;
1570 fg_pipe->stopped_progs++;
1572 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1573 fg_pipe->running_progs, fg_pipe->stopped_progs);
1574 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1575 /* All processes in fg pipe have exited/stopped */
1577 if (fg_pipe->running_progs)
1578 insert_bg_job(fg_pipe);
1582 /* There are still running processes in the fg pipe */
1586 /* fall through to searching process in bg pipes */
1590 /* We asked to wait for bg or orphaned children */
1591 /* No need to remember exitcode in this case */
1592 for (pi = job_list; pi; pi = pi->next) {
1594 while (prognum < pi->num_progs) {
1595 if (pi->progs[prognum].pid == childpid)
1596 goto found_pi_and_prognum;
1602 /* Happens when shell is used as init process (init=/bin/sh) */
1603 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1607 found_pi_and_prognum:
1610 pi->progs[prognum].pid = 0;
1611 pi->running_progs--;
1612 if (!pi->running_progs) {
1613 printf(JOB_STATUS_FORMAT, pi->jobid,
1614 "Done", pi->cmdtext);
1615 delete_finished_bg_job(pi);
1619 pi->stopped_progs++;
1620 pi->progs[prognum].is_stopped = 1;
1625 /* wait found no children or failed */
1627 if (childpid && errno != ECHILD)
1628 bb_perror_msg("waitpid");
1633 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1636 int rcode = checkjobs(fg_pipe);
1637 /* Job finished, move the shell to the foreground */
1639 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1640 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1641 bb_perror_msg("tcsetpgrp-4a");
1646 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1647 * to finish. See checkjobs().
1649 * return code is normally -1, when the caller has to wait for children
1650 * to finish to determine the exit status of the pipe. If the pipe
1651 * is a simple builtin command, however, the action is done by the
1652 * time run_pipe_real returns, and the exit code is provided as the
1655 * The input of the pipe is always stdin, the output is always
1656 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1657 * because it tries to avoid running the command substitution in
1658 * subshell, when that is in fact necessary. The subshell process
1659 * now has its stdout directed to the input of the appropriate pipe,
1660 * so this routine is noticeably simpler.
1662 static int run_pipe_real(struct pipe *pi)
1665 int nextin, nextout;
1666 int pipefds[2]; /* pipefds[0] is for reading */
1667 struct child_prog *child;
1668 const struct built_in_command *x;
1670 /* it is not always needed, but we aim to smaller code */
1671 int squirrel[] = { -1, -1, -1 };
1673 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1675 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1681 pi->running_progs = 1;
1682 pi->stopped_progs = 0;
1684 /* Check if this is a simple builtin (not part of a pipe).
1685 * Builtins within pipes have to fork anyway, and are handled in
1686 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1688 child = &(pi->progs[0]);
1689 if (single_fg && child->group && child->subshell == 0) {
1690 debug_printf("non-subshell grouping\n");
1691 setup_redirects(child, squirrel);
1692 debug_printf_exec(": run_list_real\n");
1693 rcode = run_list_real(child->group);
1694 restore_redirects(squirrel);
1695 debug_printf_exec("run_pipe_real return %d\n", rcode);
1699 if (single_fg && child->argv != NULL) {
1700 char **argv_expanded;
1701 char **argv = child->argv;
1703 for (i = 0; is_assignment(argv[i]); i++)
1705 if (i != 0 && argv[i] == NULL) {
1706 /* assignments, but no command: set the local environment */
1707 for (i = 0; argv[i] != NULL; i++) {
1708 /* Ok, this case is tricky. We have to decide if this is a
1709 * local variable, or an already exported variable. If it is
1710 * already exported, we have to export the new value. If it is
1711 * not exported, we need only set this as a local variable.
1712 * This junk is all to decide whether or not to export this
1716 name = xstrdup(argv[i]);
1717 debug_printf("local environment set: %s\n", name);
1718 value = strchr(name, '=');
1721 if (get_local_var(name)) {
1725 p = expand_variables_to_string(argv[i]);
1726 set_local_var(p, export_me);
1730 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1732 for (i = 0; is_assignment(argv[i]); i++) {
1733 p = expand_variables_to_string(argv[i]);
1741 for (x = bltins; x->cmd; x++) {
1742 if (strcmp(argv[i], x->cmd) == 0) {
1743 if (x->function == builtin_exec && argv[i+1] == NULL) {
1744 debug_printf("magic exec\n");
1745 setup_redirects(child, NULL);
1746 return EXIT_SUCCESS;
1748 debug_printf("builtin inline %s\n", argv[0]);
1749 /* XXX setup_redirects acts on file descriptors, not FILEs.
1750 * This is perfect for work that comes after exec().
1751 * Is it really safe for inline use? Experimentally,
1752 * things seem to work with glibc. */
1753 setup_redirects(child, squirrel);
1754 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1755 //sp: if (child->sp) /* btw we can do it unconditionally... */
1756 argv_expanded = expand_variables_to_list(argv + i);
1757 rcode = x->function(argv_expanded);
1758 free(argv_expanded);
1759 restore_redirects(squirrel);
1760 debug_printf_exec("run_pipe_real return %d\n", rcode);
1764 #if ENABLE_FEATURE_SH_STANDALONE
1766 const struct bb_applet *a = find_applet_by_name(argv[i]);
1767 if (a && a->nofork) {
1768 setup_redirects(child, squirrel);
1769 save_nofork_data(&nofork_save);
1770 argv_expanded = argv + i;
1771 //sp: if (child->sp)
1772 argv_expanded = expand_variables_to_list(argv + i);
1773 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1774 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
1775 free(argv_expanded);
1776 restore_redirects(squirrel);
1777 debug_printf_exec("run_pipe_real return %d\n", rcode);
1784 /* Going to fork a child per each pipe member */
1785 pi->running_progs = 0;
1787 /* Disable job control signals for shell (parent) and
1788 * for initial child code after fork */
1789 set_jobctrl_sighandler(SIG_IGN);
1791 for (i = 0; i < pi->num_progs; i++) {
1792 child = &(pi->progs[i]);
1794 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1796 debug_printf_exec(": pipe member with no argv\n");
1798 /* pipes are inserted between pairs of commands */
1799 if ((i + 1) < pi->num_progs) {
1800 if (pipe(pipefds) < 0)
1801 bb_perror_msg_and_die("pipe");
1802 nextout = pipefds[1];
1808 /* XXX test for failed fork()? */
1810 child->pid = fork();
1812 child->pid = vfork();
1814 if (!child->pid) { /* child */
1815 /* Every child adds itself to new process group
1816 * with pgid == pid of first child in pipe */
1818 if (interactive_fd) {
1819 /* Don't do pgrp restore anymore on fatal signals */
1820 set_fatal_sighandler(SIG_DFL);
1821 if (pi->pgrp < 0) /* true for 1st process only */
1822 pi->pgrp = getpid();
1823 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1824 /* We do it in *every* child, not just first,
1826 tcsetpgrp(interactive_fd, pi->pgrp);
1830 /* in non-interactive case fatal sigs are already SIG_DFL */
1840 if (pipefds[0] != -1) {
1841 close(pipefds[0]); /* opposite end of our output pipe */
1843 /* Like bash, explicit redirects override pipes,
1844 * and the pipe fd is available for dup'ing. */
1845 setup_redirects(child, NULL);
1847 /* Restore default handlers just prior to exec */
1848 set_jobctrl_sighandler(SIG_DFL);
1849 set_misc_sighandler(SIG_DFL);
1850 signal(SIGCHLD, SIG_DFL);
1854 pi->running_progs++;
1857 /* Second and next children need to know pid of first one */
1859 pi->pgrp = child->pid;
1866 /* If there isn't another process, nextin is garbage
1867 but it doesn't matter */
1868 nextin = pipefds[0];
1870 debug_printf_exec("run_pipe_real return -1\n");
1874 #ifndef debug_print_tree
1875 static void debug_print_tree(struct pipe *pi, int lvl)
1877 static const char *PIPE[] = {
1883 static const char *RES[] = {
1884 [RES_NONE ] = "NONE" ,
1886 [RES_THEN ] = "THEN" ,
1887 [RES_ELIF ] = "ELIF" ,
1888 [RES_ELSE ] = "ELSE" ,
1890 [RES_FOR ] = "FOR" ,
1891 [RES_WHILE] = "WHILE",
1892 [RES_UNTIL] = "UNTIL",
1894 [RES_DONE ] = "DONE" ,
1895 [RES_XXXX ] = "XXXX" ,
1897 [RES_SNTX ] = "SNTX" ,
1904 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1905 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
1907 while (prn < pi->num_progs) {
1908 struct child_prog *child = &pi->progs[prn];
1909 char **argv = child->argv;
1911 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1913 fprintf(stderr, " group %s: (argv=%p)\n",
1914 (child->subshell ? "()" : "{}"),
1916 debug_print_tree(child->group, lvl+1);
1920 if (argv) while (*argv) {
1921 fprintf(stderr, " '%s'", *argv);
1924 fprintf(stderr, "\n");
1933 /* NB: called by pseudo_exec, and therefore must not modify any
1934 * global data until exec/_exit (we can be a child after vfork!) */
1935 static int run_list_real(struct pipe *pi)
1937 char *for_varname = NULL;
1938 char **for_lcur = NULL;
1939 char **for_list = NULL;
1944 int rcode = 0; /* probably for gcc only */
1945 int flag_restore = 0;
1946 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1947 reserved_style rword;
1948 reserved_style skip_more_for_this_rword = RES_XXXX;
1950 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
1952 /* check syntax for "for" */
1953 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1954 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
1955 && (rpipe->next == NULL)
1957 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1958 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1961 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1962 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
1964 /* TODO: what is tested in the first condition? */
1965 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1966 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1972 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1973 * We are saving state before entering outermost list ("while...done")
1974 * so that ctrl-Z will correctly background _entire_ outermost list,
1975 * not just a part of it (like "sleep 1 | exit 2") */
1976 if (++run_list_level == 1 && interactive_fd) {
1977 if (sigsetjmp(toplevel_jb, 1)) {
1978 /* ctrl-Z forked and we are parent; or ctrl-C.
1979 * Sighandler has longjmped us here */
1980 signal(SIGINT, SIG_IGN);
1981 signal(SIGTSTP, SIG_IGN);
1982 /* Restore level (we can be coming from deep inside
1985 #if ENABLE_FEATURE_SH_STANDALONE
1986 if (nofork_save.saved) { /* if save area is valid */
1987 debug_printf_jobs("exiting nofork early\n");
1988 restore_nofork_data(&nofork_save);
1992 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1993 * Remember this child as background job */
1996 /* ctrl-C. We just stop doing whatever we were doing */
2002 /* ctrl-Z handler will store pid etc in pi */
2005 #if ENABLE_FEATURE_SH_STANDALONE
2006 nofork_save.saved = 0; /* in case we will run a nofork later */
2008 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2009 signal(SIGINT, handler_ctrl_c);
2013 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2014 rword = pi->res_word;
2015 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2022 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2023 rword, if_code, next_if_code, skip_more_for_this_rword);
2024 if (rword == skip_more_for_this_rword && flag_skip) {
2025 if (pi->followup == PIPE_SEQ)
2030 skip_more_for_this_rword = RES_XXXX;
2031 if (rword == RES_THEN || rword == RES_ELSE)
2032 if_code = next_if_code;
2033 if (rword == RES_THEN && if_code)
2035 if (rword == RES_ELSE && !if_code)
2037 if (rword == RES_ELIF && !if_code)
2039 if (rword == RES_FOR && pi->num_progs) {
2041 /* if no variable values after "in" we skip "for" */
2042 if (!pi->next->progs->argv)
2044 /* create list of variable values */
2045 for_list = expand_variables_to_list(pi->next->progs->argv);
2046 for_lcur = for_list;
2047 for_varname = pi->progs->argv[0];
2048 pi->progs->argv[0] = NULL;
2051 free(pi->progs->argv[0]);
2056 pi->progs->argv[0] = for_varname;
2057 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2060 /* insert next value from for_lcur */
2061 /* vda: does it need escaping? */
2062 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2063 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2065 if (rword == RES_IN)
2067 if (rword == RES_DO) {
2071 if (rword == RES_DONE) {
2078 if (pi->num_progs == 0)
2080 save_num_progs = pi->num_progs; /* save number of programs */
2081 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2082 rcode = run_pipe_real(pi);
2084 /* We only ran a builtin: rcode was set by the return value
2085 * of run_pipe_real(), and we don't need to wait for anything. */
2086 } else if (pi->followup == PIPE_BG) {
2087 /* What does bash do with attempts to background builtins? */
2089 /* Even bash 3.2 doesn't do that well with nested bg:
2090 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2091 * I'm considering NOT treating inner bgs as jobs -
2092 * thus maybe "if (run_list_level == 1 && pi->followup == PIPE_BG)"
2097 rcode = EXIT_SUCCESS;
2100 /* Paranoia, just "interactive_fd" should be enough */
2101 if (run_list_level == 1 && interactive_fd) {
2102 rcode = checkjobs_and_fg_shell(pi);
2106 rcode = checkjobs(pi);
2108 debug_printf_exec(": checkjobs returned %d\n", rcode);
2110 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2111 last_return_code = rcode;
2112 pi->num_progs = save_num_progs; /* restore number of programs */
2113 if (rword == RES_IF || rword == RES_ELIF)
2114 next_if_code = rcode; /* can be overwritten a number of times */
2115 if (rword == RES_WHILE)
2116 flag_rep = !last_return_code;
2117 if (rword == RES_UNTIL)
2118 flag_rep = last_return_code;
2119 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2120 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2122 skip_more_for_this_rword = rword;
2129 /* ctrl-Z forked somewhere in the past, we are the child,
2130 * and now we completed running the list. Exit. */
2136 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
2140 /* return code is the exit status of the pipe */
2141 static int free_pipe(struct pipe *pi, int indent)
2144 struct child_prog *child;
2145 struct redir_struct *r, *rnext;
2146 int a, i, ret_code = 0;
2148 if (pi->stopped_progs > 0)
2150 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2151 for (i = 0; i < pi->num_progs; i++) {
2152 child = &pi->progs[i];
2153 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2155 for (a = 0, p = child->argv; *p; a++, p++) {
2156 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2158 globfree(&child->glob_result);
2160 } else if (child->group) {
2161 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2162 ret_code = free_pipe_list(child->group, indent+3);
2163 debug_printf_clean("%s end group\n", indenter(indent));
2165 debug_printf_clean("%s (nil)\n", indenter(indent));
2167 for (r = child->redirects; r; r = rnext) {
2168 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2170 /* guard against the case >$FOO, where foo is unset or blank */
2171 if (r->word.gl_pathv) {
2172 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2176 debug_printf_clean("&%d\n", r->dup);
2181 child->redirects = NULL;
2183 free(pi->progs); /* children are an array, they get freed all at once */
2192 static int free_pipe_list(struct pipe *head, int indent)
2194 int rcode = 0; /* if list has no members */
2195 struct pipe *pi, *next;
2197 for (pi = head; pi; pi = next) {
2198 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2199 rcode = free_pipe(pi, indent);
2200 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2202 /*pi->next = NULL;*/
2208 /* Select which version we will use */
2209 static int run_list(struct pipe *pi)
2212 debug_printf_exec("run_list entered\n");
2213 if (fake_mode == 0) {
2214 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2215 rcode = run_list_real(pi);
2217 /* free_pipe_list has the side effect of clearing memory.
2218 * In the long run that function can be merged with run_list_real,
2219 * but doing that now would hobble the debugging effort. */
2220 free_pipe_list(pi, 0);
2221 debug_printf_exec("run_list return %d\n", rcode);
2225 /* The API for glob is arguably broken. This routine pushes a non-matching
2226 * string into the output structure, removing non-backslashed backslashes.
2227 * If someone can prove me wrong, by performing this function within the
2228 * original glob(3) api, feel free to rewrite this routine into oblivion.
2229 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2230 * XXX broken if the last character is '\\', check that before calling.
2232 static int globhack(const char *src, int flags, glob_t *pglob)
2237 for (cnt = 1, s = src; s && *s; s++) {
2238 if (*s == '\\') s++;
2241 dest = xmalloc(cnt);
2242 if (!(flags & GLOB_APPEND)) {
2243 pglob->gl_pathv = NULL;
2244 pglob->gl_pathc = 0;
2248 pathc = ++pglob->gl_pathc;
2249 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2250 pglob->gl_pathv[pathc-1] = dest;
2251 pglob->gl_pathv[pathc] = NULL;
2252 for (s = src; s && *s; s++, dest++) {
2253 if (*s == '\\') s++;
2260 /* XXX broken if the last character is '\\', check that before calling */
2261 static int glob_needed(const char *s)
2264 if (*s == '\\') s++;
2265 if (strchr("*[?", *s)) return 1;
2270 static int xglob(o_string *dest, int flags, glob_t *pglob)
2274 /* short-circuit for null word */
2275 /* we can code this better when the debug_printf's are gone */
2276 if (dest->length == 0) {
2277 if (dest->nonnull) {
2278 /* bash man page calls this an "explicit" null */
2279 gr = globhack(dest->data, flags, pglob);
2280 debug_printf("globhack returned %d\n", gr);
2284 } else if (glob_needed(dest->data)) {
2285 gr = glob(dest->data, flags, NULL, pglob);
2286 debug_printf("glob returned %d\n", gr);
2287 if (gr == GLOB_NOMATCH) {
2288 /* quote removal, or more accurately, backslash removal */
2289 gr = globhack(dest->data, flags, pglob);
2290 debug_printf("globhack returned %d\n", gr);
2293 gr = globhack(dest->data, flags, pglob);
2294 debug_printf("globhack returned %d\n", gr);
2296 if (gr == GLOB_NOSPACE)
2297 bb_error_msg_and_die("out of memory during glob");
2298 if (gr != 0) { /* GLOB_ABORTED ? */
2299 bb_error_msg("glob(3) error %d", gr);
2301 /* globprint(glob_target); */
2305 /* expand_variables_to_list() takes a list of strings, expands
2306 * all variable references within and returns a pointer to
2307 * a list of expanded strings, possibly with larger number
2308 * of strings. (Think VAR="a b"; echo $VAR).
2309 * This new list is allocated as a single malloc block.
2310 * NULL-terminated list of char* pointers is at the beginning of it,
2311 * followed by strings themself.
2312 * Caller can deallocate entire list by single free(list). */
2315 * count_XXX estimates size of the block we need. It's okay
2316 * to over-estimate sizes a bit, if it makes code simpler */
2317 static int count_ifs(const char *str)
2320 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2322 str += strcspn(str, ifs);
2324 str++; /* str += strspn(str, ifs); */
2325 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2327 debug_printf_expand(" return %d\n", cnt);
2331 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2336 int count = *countp;
2340 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2343 p = strchr(p, SPECIAL_VAR_SYMBOL);
2346 switch (first_ch & 0x7f) {
2347 /* high bit in 1st_ch indicates that var is double-quoted */
2349 case '!': /* bg pid */
2350 case '?': /* exitcode */
2351 case '#': /* argc */
2352 len += sizeof(int)*3 + 1; /* enough for int */
2356 for (i = 1; i < global_argc; i++) {
2357 len += strlen(global_argv[i]) + 1;
2359 if (!(first_ch & 0x80))
2360 count += count_ifs(global_argv[i]);
2365 arg[0] = first_ch & 0x7f;
2366 if (isdigit(arg[0])) {
2369 if (i < global_argc)
2370 val = global_argv[i];
2372 val = lookup_param(arg);
2374 *p = SPECIAL_VAR_SYMBOL;
2377 len += strlen(val) + 1;
2378 if (!(first_ch & 0x80))
2379 count += count_ifs(val);
2385 len += strlen(arg) + 1;
2391 /* Store given string, finalizing the word and starting new one whenever
2392 * we encounter ifs char(s). This is used for expanding variable values.
2393 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2394 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2398 int word_len = strcspn(str, ifs);
2400 memcpy(pos, str, word_len); /* store non-ifs chars */
2404 if (!*str) /* EOL - do not finalize word */
2407 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2408 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2409 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2411 str += strspn(str, ifs); /* skip ifs chars */
2417 /* Expand all variable references in given string, adding words to list[]
2418 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2419 * to be filled). This routine is extremely tricky: has to deal with
2420 * variables/parameters with whitespace, $* and $@, and constructs like
2421 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2422 /* NB: another bug is that we cannot detect empty strings yet:
2423 * "" or $empty"" expands to zero words, has to expand to empty word */
2424 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2426 /* or_mask is either 0 (normal case) or 0x80
2427 * (expansion of right-hand side of assignment == 1-element expand) */
2429 char first_ch, ored_ch;
2437 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2438 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2439 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2442 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2443 memcpy(pos, arg, p - arg);
2446 p = strchr(p, SPECIAL_VAR_SYMBOL);
2448 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2449 ored_ch |= first_ch;
2451 switch (first_ch & 0x7f) {
2452 /* Highest bit in first_ch indicates that var is double-quoted */
2454 /* FIXME: (echo $$) should still print pid of main shell */
2455 val = utoa(getpid());
2457 case '!': /* bg pid */
2458 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2460 case '?': /* exitcode */
2461 val = utoa(last_return_code);
2463 case '#': /* argc */
2464 val = utoa(global_argc ? global_argc-1 : 0);
2469 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2470 while (i < global_argc) {
2471 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2472 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2473 if (global_argv[i++][0] && i < global_argc) {
2474 /* this argv[] is not empty and not last:
2475 * put terminating NUL, start new word */
2477 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2478 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2479 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2484 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2485 * and in this case should theat it like '$*' */
2486 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2488 strcpy(pos, global_argv[i]);
2489 pos += strlen(global_argv[i]);
2490 if (++i >= global_argc)
2493 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2494 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2495 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2498 } else { /* quoted $*: add as one word */
2500 strcpy(pos, global_argv[i]);
2501 pos += strlen(global_argv[i]);
2502 if (++i >= global_argc)
2511 arg[0] = first_ch & 0x7f;
2512 if (isdigit(arg[0])) {
2515 if (i < global_argc)
2516 val = global_argv[i];
2518 val = lookup_param(arg);
2520 *p = SPECIAL_VAR_SYMBOL;
2521 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2523 n = expand_on_ifs(list, n, &pos, val);
2526 } /* else: quoted $VAR, val will be appended at pos */
2534 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2536 pos += strlen(arg) + 1;
2537 if (pos == list[n-1] + 1) { /* expansion is empty */
2538 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2539 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2549 static char **expand_variables(char **argv, char or_mask)
2554 char *pos, **v, **list;
2557 if (!*v) debug_printf_expand("count_var_expansion_space: "
2558 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2559 count, len, sizeof(char*) * count + len);
2561 count_var_expansion_space(&count, &len, *v);
2562 debug_printf_expand("count_var_expansion_space: "
2563 "'%s' count=%d len=%d alloc_space=%d\n",
2564 *v, count, len, sizeof(char*) * count + len);
2567 len += sizeof(char*) * count; /* total to alloc */
2568 list = xmalloc(len);
2569 pos = (char*)(list + count);
2570 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2574 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2576 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2577 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2578 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2585 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2588 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2591 /* To be removed / made conditional later. */
2592 if (pos - (char*)list > len)
2593 bb_error_msg_and_die("BUG in varexp");
2597 static char **expand_variables_to_list(char **argv)
2599 return expand_variables(argv, 0);
2602 static char *expand_variables_to_string(const char *str)
2604 char *argv[2], **list;
2606 argv[0] = (char*)str;
2608 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2609 /* To be removed / made conditional later. */
2610 if (!list[0] || list[1])
2611 bb_error_msg_and_die("BUG in varexp");
2612 /* actually, just move string 2*sizeof(char*) bytes back */
2613 strcpy((char*)list, list[0]);
2617 /* This is used to get/check local shell variables */
2618 static const char *get_local_var(const char *s)
2620 struct variables *cur;
2624 for (cur = top_vars; cur; cur = cur->next) {
2625 if (strcmp(cur->name, s) == 0)
2631 /* This is used to set local shell variables
2632 flg_export == 0 if only local (not exporting) variable
2633 flg_export == 1 if "new" exporting environ
2634 flg_export > 1 if current startup environ (not call putenv()) */
2635 static int set_local_var(const char *s, int flg_export)
2639 struct variables *cur;
2643 /* Assume when we enter this function that we are already in
2644 * NAME=VALUE format. So the first order of business is to
2645 * split 's' on the '=' into 'name' and 'value' */
2646 value = strchr(name, '=');
2647 /*if (value == 0 && ++value == 0) ??? -vda */
2648 if (value == NULL || value[1] == '\0') {
2654 for (cur = top_vars; cur; cur = cur->next) {
2655 if (strcmp(cur->name, name) == 0) {
2656 if (strcmp(cur->value, value) == 0) {
2657 if (flg_export && !cur->flg_export)
2658 cur->flg_export = flg_export;
2661 } else if (cur->flg_read_only) {
2662 bb_error_msg("%s: readonly variable", name);
2665 if (flg_export > 0 || cur->flg_export > 1)
2666 cur->flg_export = 1;
2667 free((char*)cur->value);
2668 cur->value = xstrdup(value);
2674 cur = xzalloc(sizeof(*cur));
2675 cur->name = xstrdup(name);
2676 cur->value = xstrdup(value);
2678 cur->flg_export = flg_export;
2679 /*cur->flg_read_only = 0;*/
2681 struct variables *bottom = top_vars;
2682 while (bottom->next)
2683 bottom = bottom->next;
2687 if (result == 0 && cur->flg_export == 1) {
2689 result = putenv(name);
2692 if (result > 0) /* equivalent to previous set */
2698 static void unset_local_var(const char *name)
2700 struct variables *cur, *next;
2704 for (cur = top_vars; cur; cur = cur->next) {
2705 if (strcmp(cur->name, name) == 0) {
2706 if (cur->flg_read_only) {
2707 bb_error_msg("%s: readonly variable", name);
2710 if (cur->flg_export)
2711 unsetenv(cur->name);
2712 free((char*)cur->name);
2713 free((char*)cur->value);
2715 while (next->next != cur)
2717 next->next = cur->next;
2724 static int is_assignment(const char *s)
2726 if (!s || !isalpha(*s))
2729 while (isalnum(*s) || *s == '_')
2734 /* the src parameter allows us to peek forward to a possible &n syntax
2735 * for file descriptor duplication, e.g., "2>&1".
2736 * Return code is 0 normally, 1 if a syntax error is detected in src.
2737 * Resource errors (in xmalloc) cause the process to exit */
2738 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2739 struct in_str *input)
2741 struct child_prog *child = ctx->child;
2742 struct redir_struct *redir = child->redirects;
2743 struct redir_struct *last_redir = NULL;
2745 /* Create a new redir_struct and drop it onto the end of the linked list */
2748 redir = redir->next;
2750 redir = xmalloc(sizeof(struct redir_struct));
2752 redir->word.gl_pathv = NULL;
2754 last_redir->next = redir;
2756 child->redirects = redir;
2759 redir->type = style;
2760 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2762 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2764 /* Check for a '2>&1' type redirect */
2765 redir->dup = redirect_dup_num(input);
2766 if (redir->dup == -2) return 1; /* syntax error */
2767 if (redir->dup != -1) {
2768 /* Erik had a check here that the file descriptor in question
2769 * is legit; I postpone that to "run time"
2770 * A "-" representation of "close me" shows up as a -3 here */
2771 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2773 /* We do _not_ try to open the file that src points to,
2774 * since we need to return and let src be expanded first.
2775 * Set ctx->pending_redirect, so we know what to do at the
2776 * end of the next parsed word.
2778 ctx->pending_redirect = redir;
2783 static struct pipe *new_pipe(void)
2786 pi = xzalloc(sizeof(struct pipe));
2787 /*pi->num_progs = 0;*/
2788 /*pi->progs = NULL;*/
2789 /*pi->next = NULL;*/
2790 /*pi->followup = 0; invalid */
2792 pi->res_word = RES_NONE;
2796 static void initialize_context(struct p_context *ctx)
2799 ctx->pending_redirect = NULL;
2801 ctx->list_head = new_pipe();
2802 ctx->pipe = ctx->list_head;
2803 ctx->res_w = RES_NONE;
2806 done_command(ctx); /* creates the memory for working child */
2809 /* normal return is 0
2810 * if a reserved word is found, and processed, return 1
2811 * should handle if, then, elif, else, fi, for, while, until, do, done.
2812 * case, function, and select are obnoxious, save those for later.
2814 static int reserved_word(o_string *dest, struct p_context *ctx)
2816 struct reserved_combo {
2821 /* Mostly a list of accepted follow-up reserved words.
2822 * FLAG_END means we are done with the sequence, and are ready
2823 * to turn the compound list into a command.
2824 * FLAG_START means the word must start a new compound list.
2826 static const struct reserved_combo reserved_list[] = {
2827 { "if", RES_IF, FLAG_THEN | FLAG_START },
2828 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2829 { "elif", RES_ELIF, FLAG_THEN },
2830 { "else", RES_ELSE, FLAG_FI },
2831 { "fi", RES_FI, FLAG_END },
2832 { "for", RES_FOR, FLAG_IN | FLAG_START },
2833 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2834 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2835 { "in", RES_IN, FLAG_DO },
2836 { "do", RES_DO, FLAG_DONE },
2837 { "done", RES_DONE, FLAG_END }
2839 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2840 const struct reserved_combo *r;
2842 for (r = reserved_list; r < reserved_list + NRES; r++) {
2843 if (strcmp(dest->data, r->literal) == 0) {
2844 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2845 if (r->flag & FLAG_START) {
2846 struct p_context *new = xmalloc(sizeof(struct p_context));
2847 debug_printf("push stack\n");
2848 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2851 ctx->res_w = RES_SNTX;
2855 *new = *ctx; /* physical copy */
2856 initialize_context(ctx);
2858 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2860 ctx->res_w = RES_SNTX;
2864 ctx->res_w = r->code;
2865 ctx->old_flag = r->flag;
2866 if (ctx->old_flag & FLAG_END) {
2867 struct p_context *old;
2868 debug_printf("pop stack\n");
2869 done_pipe(ctx, PIPE_SEQ);
2871 old->child->group = ctx->list_head;
2872 old->child->subshell = 0;
2873 *ctx = *old; /* physical copy */
2883 /* Normal return is 0.
2884 * Syntax or xglob errors return 1. */
2885 static int done_word(o_string *dest, struct p_context *ctx)
2887 struct child_prog *child = ctx->child;
2888 glob_t *glob_target;
2891 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2892 if (dest->length == 0 && !dest->nonnull) {
2893 debug_printf_parse("done_word return 0: true null, ignored\n");
2896 if (ctx->pending_redirect) {
2897 glob_target = &ctx->pending_redirect->word;
2901 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2904 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
2905 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2906 if (reserved_word(dest, ctx)) {
2907 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2908 return (ctx->res_w == RES_SNTX);
2911 glob_target = &child->glob_result;
2913 flags |= GLOB_APPEND;
2915 gr = xglob(dest, flags, glob_target);
2917 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2922 if (ctx->pending_redirect) {
2923 ctx->pending_redirect = NULL;
2924 if (glob_target->gl_pathc != 1) {
2925 bb_error_msg("ambiguous redirect");
2926 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2930 child->argv = glob_target->gl_pathv;
2932 if (ctx->res_w == RES_FOR) {
2933 done_word(dest, ctx);
2934 done_pipe(ctx, PIPE_SEQ);
2936 debug_printf_parse("done_word return 0\n");
2940 /* The only possible error here is out of memory, in which case
2942 static int done_command(struct p_context *ctx)
2944 /* The child is really already in the pipe structure, so
2945 * advance the pipe counter and make a new, null child. */
2946 struct pipe *pi = ctx->pipe;
2947 struct child_prog *child = ctx->child;
2950 if (child->group == NULL
2951 && child->argv == NULL
2952 && child->redirects == NULL
2954 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2955 return pi->num_progs;
2958 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
2960 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
2963 /* Only real trickiness here is that the uncommitted
2964 * child structure is not counted in pi->num_progs. */
2965 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2966 child = &pi->progs[pi->num_progs];
2968 memset(child, 0, sizeof(*child));
2969 /*child->redirects = NULL;*/
2970 /*child->argv = NULL;*/
2971 /*child->is_stopped = 0;*/
2972 /*child->group = NULL;*/
2973 /*child->glob_result.gl_pathv = NULL;*/
2975 //sp: /*child->sp = 0;*/
2976 //pt: child->parse_type = ctx->parse_type;
2979 /* but ctx->pipe and ctx->list_head remain unchanged */
2981 return pi->num_progs; /* used only for 0/nonzero check */
2984 static int done_pipe(struct p_context *ctx, pipe_style type)
2989 debug_printf_parse("done_pipe entered, followup %d\n", type);
2990 not_null = done_command(ctx); /* implicit closure of previous command */
2991 ctx->pipe->followup = type;
2992 ctx->pipe->res_word = ctx->res_w;
2993 /* Without this check, even just <enter> on command line generates
2994 * tree of three NOPs (!). Which is harmless but annoying.
2995 * IOW: it is safe to do it unconditionally. */
2998 ctx->pipe->next = new_p;
3001 done_command(ctx); /* set up new pipe to accept commands */
3003 debug_printf_parse("done_pipe return 0\n");
3007 /* peek ahead in the in_str to find out if we have a "&n" construct,
3008 * as in "2>&1", that represents duplicating a file descriptor.
3009 * returns either -2 (syntax error), -1 (no &), or the number found.
3011 static int redirect_dup_num(struct in_str *input)
3013 int ch, d = 0, ok = 0;
3015 if (ch != '&') return -1;
3017 b_getch(input); /* get the & */
3021 return -3; /* "-" represents "close me" */
3023 while (isdigit(ch)) {
3024 d = d*10 + (ch-'0');
3031 bb_error_msg("ambiguous redirect");
3035 /* If a redirect is immediately preceded by a number, that number is
3036 * supposed to tell which file descriptor to redirect. This routine
3037 * looks for such preceding numbers. In an ideal world this routine
3038 * needs to handle all the following classes of redirects...
3039 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3040 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3041 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3042 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3043 * A -1 output from this program means no valid number was found, so the
3044 * caller should use the appropriate default for this redirection.
3046 static int redirect_opt_num(o_string *o)
3052 for (num = 0; num < o->length; num++) {
3053 if (!isdigit(*(o->data + num))) {
3057 /* reuse num (and save an int) */
3058 num = atoi(o->data);
3063 #if ENABLE_HUSH_TICK
3064 static FILE *generate_stream_from_list(struct pipe *head)
3067 int pid, channel[2];
3068 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
3075 bb_perror_msg_and_die("fork");
3076 } else if (pid == 0) {
3078 if (channel[1] != 1) {
3079 dup2(channel[1], 1);
3082 _exit(run_list_real(head)); /* leaks memory */
3084 debug_printf("forked child %d\n", pid);
3086 pf = fdopen(channel[0], "r");
3087 debug_printf("pipe on FILE *%p\n", pf);
3091 /* Return code is exit status of the process that is run. */
3092 static int process_command_subs(o_string *dest, struct p_context *ctx,
3093 struct in_str *input, const char *subst_end)
3095 int retcode, ch, eol_cnt;
3096 o_string result = NULL_O_STRING;
3097 struct p_context inner;
3099 struct in_str pipe_str;
3101 initialize_context(&inner);
3103 /* recursion to generate command */
3104 retcode = parse_stream(&result, &inner, input, subst_end);
3105 if (retcode != 0) return retcode; /* syntax error or EOF */
3106 done_word(&result, &inner);
3107 done_pipe(&inner, PIPE_SEQ);
3110 p = generate_stream_from_list(inner.list_head);
3111 if (p == NULL) return 1;
3112 mark_open(fileno(p));
3113 setup_file_in_str(&pipe_str, p);
3115 /* now send results of command back into original context */
3117 while ((ch = b_getch(&pipe_str)) != EOF) {
3123 b_addqchr(dest, '\n', dest->quote);
3126 b_addqchr(dest, ch, dest->quote);
3129 debug_printf("done reading from pipe, pclose()ing\n");
3130 /* This is the step that wait()s for the child. Should be pretty
3131 * safe, since we just read an EOF from its stdout. We could try
3132 * to do better, by using wait(), and keeping track of background jobs
3133 * at the same time. That would be a lot of work, and contrary
3134 * to the KISS philosophy of this program. */
3135 mark_closed(fileno(p));
3136 retcode = pclose(p);
3137 free_pipe_list(inner.list_head, 0);
3138 debug_printf("pclosed, retcode=%d\n", retcode);
3143 static int parse_group(o_string *dest, struct p_context *ctx,
3144 struct in_str *input, int ch)
3147 const char *endch = NULL;
3148 struct p_context sub;
3149 struct child_prog *child = ctx->child;
3151 debug_printf_parse("parse_group entered\n");
3154 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3157 initialize_context(&sub);
3161 child->subshell = 1;
3167 syntax(); /* really logic error */
3169 rcode = parse_stream(dest, &sub, input, endch);
3170 done_word(dest, &sub); /* finish off the final word in the subcontext */
3171 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3172 child->group = sub.list_head;
3174 debug_printf_parse("parse_group return %d\n", rcode);
3176 /* child remains "open", available for possible redirects */
3179 /* Basically useful version until someone wants to get fancier,
3180 * see the bash man page under "Parameter Expansion" */
3181 static const char *lookup_param(const char *src)
3183 const char *p = NULL;
3187 p = get_local_var(src);
3192 /* Make new string for parser */
3193 static char* make_string(char **inp)
3201 for (n = 0; inp[n]; n++) {
3202 p = expand_variables_to_string(inp[n]);
3203 val_len = strlen(p);
3204 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3206 strcpy(str + len, p);
3208 if (p != inp[n]) free(p);
3210 /* We do not check for case where loop had no iterations at all
3211 * - cannot happen? */
3217 /* return code: 0 for OK, 1 for syntax error */
3218 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3220 int ch = b_peek(input); /* first character after the $ */
3221 unsigned char quote_mask = dest->quote ? 0x80 : 0;
3223 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3225 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3226 //sp: ctx->child->sp++;
3228 debug_printf_parse(": '%c'\n", ch);
3230 b_addchr(dest, ch | quote_mask);
3233 if (!isalnum(ch) && ch != '_')
3236 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3237 } else if (isdigit(ch)) {
3239 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3240 //sp: ctx->child->sp++;
3241 debug_printf_parse(": '%c'\n", ch);
3243 b_addchr(dest, ch | quote_mask);
3244 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3245 } else switch (ch) {
3247 case '!': /* last bg pid */
3248 case '?': /* last exit code */
3249 case '#': /* number of args */
3250 case '*': /* args */
3251 case '@': /* args */
3252 goto make_one_char_var;
3254 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3255 //sp: ctx->child->sp++;
3257 /* XXX maybe someone will try to escape the '}' */
3259 ch = b_getch(input);
3262 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3267 debug_printf_parse(": '%c'\n", ch);
3268 b_addchr(dest, ch | quote_mask);
3271 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3273 #if ENABLE_HUSH_TICK
3276 process_command_subs(dest, ctx, input, ")");
3281 /* still unhandled, but should be eventually */
3282 bb_error_msg("unhandled syntax: $%c", ch);
3286 b_addqchr(dest, '$', dest->quote);
3288 debug_printf_parse("handle_dollar return 0\n");
3292 /* return code is 0 for normal exit, 1 for syntax error */
3293 static int parse_stream(o_string *dest, struct p_context *ctx,
3294 struct in_str *input, const char *end_trigger)
3298 redir_type redir_style;
3301 /* Only double-quote state is handled in the state variable dest->quote.
3302 * A single-quote triggers a bypass of the main loop until its mate is
3303 * found. When recursing, quote state is passed in via dest->quote. */
3305 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3307 while ((ch = b_getch(input)) != EOF) {
3309 next = (ch == '\n') ? '\0' : b_peek(input);
3310 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3311 ch, ch, m, dest->quote);
3312 if (m == CHAR_ORDINARY
3313 || (m != CHAR_SPECIAL && dest->quote)
3315 b_addqchr(dest, ch, dest->quote);
3318 if (m == CHAR_IFS) {
3319 if (done_word(dest, ctx)) {
3320 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3323 /* If we aren't performing a substitution, treat
3324 * a newline as a command separator.
3325 * [why we don't handle it exactly like ';'? --vda] */
3326 if (end_trigger && ch == '\n') {
3327 done_pipe(ctx, PIPE_SEQ);
3330 if ((end_trigger && strchr(end_trigger, ch))
3331 && !dest->quote && ctx->res_w == RES_NONE
3333 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3340 if (dest->length == 0 && !dest->quote) {
3343 if (ch == EOF || ch == '\n')
3348 b_addqchr(dest, ch, dest->quote);
3354 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3357 b_addqchr(dest, '\\', dest->quote);
3358 b_addqchr(dest, b_getch(input), dest->quote);
3361 if (handle_dollar(dest, ctx, input) != 0) {
3362 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3369 ch = b_getch(input);
3370 if (ch == EOF || ch == '\'')
3376 debug_printf_parse("parse_stream return 1: unterminated '\n");
3382 dest->quote = !dest->quote;
3384 #if ENABLE_HUSH_TICK
3386 process_command_subs(dest, ctx, input, "`");
3390 redir_fd = redirect_opt_num(dest);
3391 done_word(dest, ctx);
3392 redir_style = REDIRECT_OVERWRITE;
3394 redir_style = REDIRECT_APPEND;
3396 } else if (next == '(') {
3397 syntax(); /* until we support >(list) Process Substitution */
3398 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3401 setup_redirect(ctx, redir_fd, redir_style, input);
3404 redir_fd = redirect_opt_num(dest);
3405 done_word(dest, ctx);
3406 redir_style = REDIRECT_INPUT;
3408 redir_style = REDIRECT_HEREIS;
3410 } else if (next == '>') {
3411 redir_style = REDIRECT_IO;
3413 } else if (next == '(') {
3414 syntax(); /* until we support <(list) Process Substitution */
3415 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3418 setup_redirect(ctx, redir_fd, redir_style, input);
3421 done_word(dest, ctx);
3422 done_pipe(ctx, PIPE_SEQ);
3425 done_word(dest, ctx);
3428 done_pipe(ctx, PIPE_AND);
3430 done_pipe(ctx, PIPE_BG);
3434 done_word(dest, ctx);
3437 done_pipe(ctx, PIPE_OR);
3439 /* we could pick up a file descriptor choice here
3440 * with redirect_opt_num(), but bash doesn't do it.
3441 * "echo foo 2| cat" yields "foo 2". */
3447 if (parse_group(dest, ctx, input, ch) != 0) {
3448 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3454 syntax(); /* Proper use of this character is caught by end_trigger */
3455 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3458 syntax(); /* this is really an internal logic error */
3459 debug_printf_parse("parse_stream return 1: internal logic error\n");
3463 /* Complain if quote? No, maybe we just finished a command substitution
3464 * that was quoted. Example:
3465 * $ echo "`cat foo` plus more"
3466 * and we just got the EOF generated by the subshell that ran "cat foo"
3467 * The only real complaint is if we got an EOF when end_trigger != NULL,
3468 * that is, we were really supposed to get end_trigger, and never got
3469 * one before the EOF. Can't use the standard "syntax error" return code,
3470 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3471 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3477 static void set_in_charmap(const char *set, int code)
3480 charmap[(unsigned char)*set++] = code;
3483 static void update_charmap(void)
3485 /* char *ifs and char charmap[256] are both globals. */
3486 ifs = getenv("IFS");
3489 /* Precompute a list of 'flow through' behavior so it can be treated
3490 * quickly up front. Computation is necessary because of IFS.
3491 * Special case handling of IFS == " \t\n" is not implemented.
3492 * The charmap[] array only really needs two bits each,
3493 * and on most machines that would be faster (reduced L1 cache use).
3495 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3496 #if ENABLE_HUSH_TICK
3497 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3499 set_in_charmap("\\$\"", CHAR_SPECIAL);
3501 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3502 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3505 /* most recursion does not come through here, the exception is
3506 * from builtin_source() */
3507 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3509 struct p_context ctx;
3510 o_string temp = NULL_O_STRING;
3513 ctx.parse_type = parse_flag;
3514 initialize_context(&ctx);
3516 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3517 set_in_charmap(";$&|", CHAR_ORDINARY);
3518 #if ENABLE_HUSH_INTERACTIVE
3519 inp->promptmode = 1;
3521 /* We will stop & execute after each ';' or '\n'.
3522 * Example: "sleep 9999; echo TEST" + ctrl-C:
3523 * TEST should be printed */
3524 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3525 if (rcode != 1 && ctx.old_flag != 0) {
3528 if (rcode != 1 && ctx.old_flag == 0) {
3529 done_word(&temp, &ctx);
3530 done_pipe(&ctx, PIPE_SEQ);
3531 debug_print_tree(ctx.list_head, 0);
3532 debug_printf_exec("parse_stream_outer: run_list\n");
3533 run_list(ctx.list_head);
3535 if (ctx.old_flag != 0) {
3542 free_pipe_list(ctx.list_head, 0);
3545 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3549 static int parse_string_outer(const char *s, int parse_flag)
3551 struct in_str input;
3552 setup_string_in_str(&input, s);
3553 return parse_stream_outer(&input, parse_flag);
3556 static int parse_file_outer(FILE *f)
3559 struct in_str input;
3560 setup_file_in_str(&input, f);
3561 rcode = parse_stream_outer(&input, PARSEFLAG_SEMICOLON);
3566 /* Make sure we have a controlling tty. If we get started under a job
3567 * aware app (like bash for example), make sure we are now in charge so
3568 * we don't fight over who gets the foreground */
3569 static void setup_job_control(void)
3573 saved_task_pgrp = shell_pgrp = getpgrp();
3574 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3575 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3577 /* If we were ran as 'hush &',
3578 * sleep until we are in the foreground. */
3579 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3580 /* Send TTIN to ourself (should stop us) */
3581 kill(- shell_pgrp, SIGTTIN);
3582 shell_pgrp = getpgrp();
3585 /* Ignore job-control and misc signals. */
3586 set_jobctrl_sighandler(SIG_IGN);
3587 set_misc_sighandler(SIG_IGN);
3588 //huh? signal(SIGCHLD, SIG_IGN);
3590 /* We _must_ restore tty pgrp on fatal signals */
3591 set_fatal_sighandler(sigexit);
3593 /* Put ourselves in our own process group. */
3594 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3595 /* Grab control of the terminal. */
3596 tcsetpgrp(interactive_fd, getpid());
3600 int hush_main(int argc, char **argv);
3601 int hush_main(int argc, char **argv)
3607 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3608 top_vars = &shell_ver;
3609 shell_ver = const_shell_ver; /* copying struct here */
3611 #if ENABLE_FEATURE_EDITING
3612 line_input_state = new_line_input_t(FOR_SHELL);
3614 /* XXX what should these be while sourcing /etc/profile? */
3617 /* Initialize some more globals to non-zero values */
3619 #if ENABLE_HUSH_INTERACTIVE
3620 #if ENABLE_FEATURE_EDITING
3621 cmdedit_set_initial_prompt();
3626 /* initialize our shell local variables with the values
3627 * currently living in the environment */
3631 set_local_var(*e++, 2); /* without call putenv() */
3633 last_return_code = EXIT_SUCCESS;
3635 if (argv[0] && argv[0][0] == '-') {
3636 debug_printf("sourcing /etc/profile\n");
3637 input = fopen("/etc/profile", "r");
3638 if (input != NULL) {
3639 mark_open(fileno(input));
3640 parse_file_outer(input);
3641 mark_closed(fileno(input));
3647 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3650 global_argv = argv + optind;
3651 global_argc = argc - optind;
3652 opt = parse_string_outer(optarg, PARSEFLAG_SEMICOLON);
3655 /* Well, we cannot just declare interactiveness,
3656 * we have to have some stuff (ctty, etc) */
3657 /* interactive_fd++; */
3664 fprintf(stderr, "Usage: sh [FILE]...\n"
3665 " or: sh -c command [args]...\n\n");
3673 /* A shell is interactive if the '-i' flag was given, or if all of
3674 * the following conditions are met:
3676 * no arguments remaining or the -s flag given
3677 * standard input is a terminal
3678 * standard output is a terminal
3679 * Refer to Posix.2, the description of the 'sh' utility. */
3680 if (argv[optind] == NULL && input == stdin
3681 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3683 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3684 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3685 if (saved_tty_pgrp >= 0) {
3686 /* try to dup to high fd#, >= 255 */
3687 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3688 if (interactive_fd < 0) {
3689 /* try to dup to any fd */
3690 interactive_fd = dup(STDIN_FILENO);
3691 if (interactive_fd < 0)
3695 // TODO: track & disallow any attempts of user
3696 // to (inadvertently) close/redirect it
3699 debug_printf("interactive_fd=%d\n", interactive_fd);
3700 if (interactive_fd) {
3701 /* Looks like they want an interactive shell */
3702 setup_job_control();
3703 /* Make xfuncs do cleanup on exit */
3704 die_sleep = -1; /* flag */
3705 // FIXME: should we reset die_sleep = 0 whereever we fork?
3706 if (setjmp(die_jmp)) {
3707 /* xfunc has failed! die die die */
3708 hush_exit(xfunc_error_retval);
3710 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3711 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3712 printf("Enter 'help' for a list of built-in commands.\n\n");
3715 #elif ENABLE_HUSH_INTERACTIVE
3716 /* no job control compiled, only prompt/line editing */
3717 if (argv[optind] == NULL && input == stdin
3718 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3720 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3721 if (interactive_fd < 0) {
3722 /* try to dup to any fd */
3723 interactive_fd = dup(STDIN_FILENO);
3724 if (interactive_fd < 0)
3732 if (argv[optind] == NULL) {
3733 opt = parse_file_outer(stdin);
3737 debug_printf("\nrunning script '%s'\n", argv[optind]);
3738 global_argv = argv + optind;
3739 global_argc = argc - optind;
3740 input = xfopen(argv[optind], "r");
3741 opt = parse_file_outer(input);
3743 #if ENABLE_FEATURE_CLEAN_UP
3745 if (cwd != bb_msg_unknown)
3748 struct variables *cur, *tmp;
3749 for (cur = top_vars; cur; cur = tmp) {
3751 if (!cur->flg_read_only) {
3752 free((char*)cur->name);
3753 free((char*)cur->value);
3761 hush_exit(opt ? opt : last_return_code);