1 /* vi: set sw=4 ts=4: */
3 * 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>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * subst operator: ${var/[/]expr/expr}
54 * brace expansion: one/{two,three,four}
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
67 * export builtin should be special, its arguments are assignments
68 * and therefore expansion of them should be "one-word" expansion:
69 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
71 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
72 * ls: cannot access i=a: No such file or directory
73 * ls: cannot access b: No such file or directory
74 * Note1: same applies to local builtin.
75 * Note2: bash 3.2.33(1) does this only if export word itself
77 * $ export i=`echo 'aaa bbb'`; echo "$i"
79 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #include <malloc.h> /* for malloc_trim */
87 /* #include <dmalloc.h> */
92 #include "shell_common.h"
95 #if ENABLE_HUSH_RANDOM_SUPPORT
98 # define CLEAR_RANDOM_T(rnd) ((void)0)
101 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
104 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_LASH(APPLET(lash, _BB_DIR_BIN, _BB_SUID_DROP))
107 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
108 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
110 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
111 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, brace expansion,
125 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_HELP
135 //config: bool "help builtin"
137 //config: depends on HUSH
139 //config: Enable help builtin in hush. Code size + ~1 kbyte.
141 //config:config HUSH_INTERACTIVE
142 //config: bool "Interactive mode"
144 //config: depends on HUSH
146 //config: Enable interactive mode (prompt and command editing).
147 //config: Without this, hush simply reads and executes commands
148 //config: from stdin just like a shell script from a file.
149 //config: No prompt, no PS1/PS2 magic shell variables.
151 //config:config HUSH_JOB
152 //config: bool "Job control"
154 //config: depends on HUSH_INTERACTIVE
156 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
157 //config: command (not entire shell), fg/bg builtins work. Without this option,
158 //config: "cmd &" still works by simply spawning a process and immediately
159 //config: prompting for next command (or executing next command in a script),
160 //config: but no separate process group is formed.
162 //config:config HUSH_TICK
163 //config: bool "Process substitution"
165 //config: depends on HUSH
167 //config: Enable process substitution `command` and $(command) in hush.
169 //config:config HUSH_IF
170 //config: bool "Support if/then/elif/else/fi"
172 //config: depends on HUSH
174 //config: Enable if/then/elif/else/fi in hush.
176 //config:config HUSH_LOOPS
177 //config: bool "Support for, while and until loops"
179 //config: depends on HUSH
181 //config: Enable for, while and until loops in hush.
183 //config:config HUSH_CASE
184 //config: bool "Support case ... esac statement"
186 //config: depends on HUSH
188 //config: Enable case ... esac statement in hush. +400 bytes.
190 //config:config HUSH_FUNCTIONS
191 //config: bool "Support funcname() { commands; } syntax"
193 //config: depends on HUSH
195 //config: Enable support for shell functions in hush. +800 bytes.
197 //config:config HUSH_LOCAL
198 //config: bool "Support local builtin"
200 //config: depends on HUSH_FUNCTIONS
202 //config: Enable support for local variables in functions.
204 //config:config HUSH_RANDOM_SUPPORT
205 //config: bool "Pseudorandom generator and $RANDOM variable"
207 //config: depends on HUSH
209 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
210 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
212 //config:config HUSH_EXPORT_N
213 //config: bool "Support 'export -n' option"
215 //config: depends on HUSH
217 //config: export -n unexports variables. It is a bash extension.
219 //config:config HUSH_MODE_X
220 //config: bool "Support 'hush -x' option and 'set -x' command"
222 //config: depends on HUSH
224 //config: This instructs hush to print commands before execution.
225 //config: Adds ~300 bytes.
228 //usage:#define hush_trivial_usage NOUSAGE_STR
229 //usage:#define hush_full_usage ""
230 //usage:#define lash_trivial_usage NOUSAGE_STR
231 //usage:#define lash_full_usage ""
232 //usage:#define msh_trivial_usage NOUSAGE_STR
233 //usage:#define msh_full_usage ""
237 #define LEAK_HUNTING 0
238 #define BUILD_AS_NOMMU 0
239 /* Enable/disable sanity checks. Ok to enable in production,
240 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
241 * Keeping 1 for now even in released versions.
244 /* Slightly bigger (+200 bytes), but faster hush.
245 * So far it only enables a trick with counting SIGCHLDs and forks,
246 * which allows us to do fewer waitpid's.
247 * (we can detect a case where neither forks were done nor SIGCHLDs happened
248 * and therefore waitpid will return the same result as last time)
250 #define ENABLE_HUSH_FAST 0
251 /* TODO: implement simplified code for users which do not need ${var%...} ops
252 * So far ${var%...} ops are always enabled:
254 #define ENABLE_HUSH_DOLLAR_OPS 1
259 # undef USE_FOR_NOMMU
262 # define USE_FOR_NOMMU(...) __VA_ARGS__
263 # define USE_FOR_MMU(...)
266 #include "NUM_APPLETS.h"
268 /* STANDALONE does not make sense, and won't compile */
269 # undef CONFIG_FEATURE_SH_STANDALONE
270 # undef ENABLE_FEATURE_SH_STANDALONE
271 # undef IF_FEATURE_SH_STANDALONE
272 # undef IF_NOT_FEATURE_SH_STANDALONE
273 # define ENABLE_FEATURE_SH_STANDALONE 0
274 # define IF_FEATURE_SH_STANDALONE(...)
275 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
278 #if !ENABLE_HUSH_INTERACTIVE
279 # undef ENABLE_FEATURE_EDITING
280 # define ENABLE_FEATURE_EDITING 0
281 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
282 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
285 /* Do we support ANY keywords? */
286 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
287 # define HAS_KEYWORDS 1
288 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
289 # define IF_HAS_NO_KEYWORDS(...)
291 # define HAS_KEYWORDS 0
292 # define IF_HAS_KEYWORDS(...)
293 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
296 /* If you comment out one of these below, it will be #defined later
297 * to perform debug printfs to stderr: */
298 #define debug_printf(...) do {} while (0)
299 /* Finer-grained debug switches */
300 #define debug_printf_parse(...) do {} while (0)
301 #define debug_print_tree(a, b) do {} while (0)
302 #define debug_printf_exec(...) do {} while (0)
303 #define debug_printf_env(...) do {} while (0)
304 #define debug_printf_jobs(...) do {} while (0)
305 #define debug_printf_expand(...) do {} while (0)
306 #define debug_printf_varexp(...) do {} while (0)
307 #define debug_printf_glob(...) do {} while (0)
308 #define debug_printf_list(...) do {} while (0)
309 #define debug_printf_subst(...) do {} while (0)
310 #define debug_printf_clean(...) do {} while (0)
312 #define ERR_PTR ((void*)(long)1)
314 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
316 #define _SPECIAL_VARS_STR "_*@$!?#"
317 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
318 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
320 #define SPECIAL_VAR_SYMBOL 3
324 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
326 /* This supports saving pointers malloced in vfork child,
327 * to be freed in the parent.
330 typedef struct nommu_save_t {
332 struct variable *old_vars;
334 char **argv_from_re_execing;
338 typedef enum reserved_style {
347 #if ENABLE_HUSH_LOOPS
354 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
359 /* three pseudo-keywords support contrived "case" syntax: */
360 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
361 RES_MATCH , /* "word)" */
362 RES_CASE_BODY, /* "this command is inside CASE" */
369 typedef struct o_string {
371 int length; /* position where data is appended */
373 /* Protect newly added chars against globbing
374 * (by prepending \ to *, ?, [, \) */
377 /* At least some part of the string was inside '' or "",
378 * possibly empty one: word"", wo''rd etc. */
380 smallint has_empty_slot;
381 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
384 MAYBE_ASSIGNMENT = 0,
385 DEFINITELY_ASSIGNMENT = 1,
387 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
389 /* Used for initialization: o_string foo = NULL_O_STRING; */
390 #define NULL_O_STRING { NULL }
392 /* I can almost use ordinary FILE*. Is open_memstream() universally
393 * available? Where is it documented? */
394 typedef struct in_str {
396 /* eof_flag=1: last char in ->p is really an EOF */
397 char eof_flag; /* meaningless if ->p == NULL */
399 #if ENABLE_HUSH_INTERACTIVE
401 smallint promptmode; /* 0: PS1, 1: PS2 */
404 int (*get) (struct in_str *) FAST_FUNC;
405 int (*peek) (struct in_str *) FAST_FUNC;
407 #define i_getch(input) ((input)->get(input))
408 #define i_peek(input) ((input)->peek(input))
410 /* The descrip member of this structure is only used to make
411 * debugging output pretty */
412 static const struct {
414 signed char default_fd;
417 { O_RDONLY, 0, "<" },
418 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
419 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
420 { O_CREAT|O_RDWR, 1, "<>" },
421 { O_RDONLY, 0, "<<" },
422 /* Should not be needed. Bogus default_fd helps in debugging */
423 /* { O_RDONLY, 77, "<<" }, */
426 struct redir_struct {
427 struct redir_struct *next;
428 char *rd_filename; /* filename */
429 int rd_fd; /* fd to redirect */
430 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
432 smallint rd_type; /* (enum redir_type) */
433 /* note: for heredocs, rd_filename contains heredoc delimiter,
434 * and subsequently heredoc itself; and rd_dup is a bitmask:
435 * bit 0: do we need to trim leading tabs?
436 * bit 1: is heredoc quoted (<<'delim' syntax) ?
439 typedef enum redir_type {
441 REDIRECT_OVERWRITE = 1,
444 REDIRECT_HEREDOC = 4,
445 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
448 REDIRFD_SYNTAX_ERR = -2,
449 REDIRFD_TO_FILE = -1,
450 /* otherwise, rd_fd is redirected to rd_dup */
452 HEREDOC_SKIPTABS = 1,
458 pid_t pid; /* 0 if exited */
459 int assignment_cnt; /* how many argv[i] are assignments? */
460 smallint is_stopped; /* is the command currently running? */
461 smallint cmd_type; /* CMD_xxx */
463 #define CMD_SUBSHELL 1
465 /* used for "[[ EXPR ]]" */
466 #if ENABLE_HUSH_BASH_COMPAT
467 # define CMD_SINGLEWORD_NOGLOB 2
470 /* used for "export noglob=* glob* a=`echo a b`" */
471 //#define CMD_SINGLEWORD_NOGLOB_COND 3
472 // It is hard to implement correctly, it adds significant amounts of tricky code,
473 // and all this is only useful for really obscure export statements
474 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
475 // guards the code which implements it, but I have doubts it works
476 // in all cases (especially with mixed globbed/non-globbed arguments)
478 #if ENABLE_HUSH_FUNCTIONS
479 # define CMD_FUNCDEF 3
482 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
485 char *group_as_string;
487 #if ENABLE_HUSH_FUNCTIONS
488 struct function *child_func;
489 /* This field is used to prevent a bug here:
490 * while...do f1() {a;}; f1; f1() {b;}; f1; done
491 * When we execute "f1() {a;}" cmd, we create new function and clear
492 * cmd->group, cmd->group_as_string, cmd->argv[0].
493 * When we execute "f1() {b;}", we notice that f1 exists,
494 * and that its "parent cmd" struct is still "alive",
495 * we put those fields back into cmd->xxx
496 * (struct function has ->parent_cmd ptr to facilitate that).
497 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
498 * Without this trick, loop would execute a;b;b;b;...
499 * instead of correct sequence a;b;a;b;...
500 * When command is freed, it severs the link
501 * (sets ->child_func->parent_cmd to NULL).
504 char **argv; /* command name and arguments */
505 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
506 * and on execution these are substituted with their values.
507 * Substitution can make _several_ words out of one argv[n]!
508 * Example: argv[0]=='.^C*^C.' here: echo .$*.
509 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
511 struct redir_struct *redirects; /* I/O redirections */
513 /* Is there anything in this command at all? */
514 #define IS_NULL_CMD(cmd) \
515 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
520 int num_cmds; /* total number of commands in pipe */
521 int alive_cmds; /* number of commands running (not exited) */
522 int stopped_cmds; /* number of commands alive, but stopped */
524 int jobid; /* job number */
525 pid_t pgrp; /* process group ID for the job */
526 char *cmdtext; /* name of job */
528 struct command *cmds; /* array of commands in pipe */
529 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
530 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
531 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
533 typedef enum pipe_style {
539 /* Is there anything in this pipe at all? */
540 #define IS_NULL_PIPE(pi) \
541 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
543 /* This holds pointers to the various results of parsing */
544 struct parse_context {
545 /* linked list of pipes */
546 struct pipe *list_head;
547 /* last pipe (being constructed right now) */
549 /* last command in pipe (being constructed right now) */
550 struct command *command;
551 /* last redirect in command->redirects list */
552 struct redir_struct *pending_redirect;
558 smallint ctx_inverted; /* "! cmd | cmd" */
560 smallint ctx_dsemicolon; /* ";;" seen */
562 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
564 /* group we are enclosed in:
565 * example: "if pipe1; pipe2; then pipe3; fi"
566 * when we see "if" or "then", we malloc and copy current context,
567 * and make ->stack point to it. then we parse pipeN.
568 * when closing "then" / fi" / whatever is found,
569 * we move list_head into ->stack->command->group,
570 * copy ->stack into current context, and delete ->stack.
571 * (parsing of { list } and ( list ) doesn't use this method)
573 struct parse_context *stack;
577 /* On program start, environ points to initial environment.
578 * putenv adds new pointers into it, unsetenv removes them.
579 * Neither of these (de)allocates the strings.
580 * setenv allocates new strings in malloc space and does putenv,
581 * and thus setenv is unusable (leaky) for shell's purposes */
582 #define setenv(...) setenv_is_leaky_dont_use()
584 struct variable *next;
585 char *varstr; /* points to "name=" portion */
586 #if ENABLE_HUSH_LOCAL
587 unsigned func_nest_level;
589 int max_len; /* if > 0, name is part of initial env; else name is malloced */
590 smallint flg_export; /* putenv should be done on this var */
591 smallint flg_read_only;
599 #if ENABLE_HUSH_FUNCTIONS
601 struct function *next;
603 struct command *parent_cmd;
606 char *body_as_string;
612 /* "Globals" within this file */
613 /* Sorted roughly by size (smaller offsets == smaller code) */
615 /* interactive_fd != 0 means we are an interactive shell.
616 * If we are, then saved_tty_pgrp can also be != 0, meaning
617 * that controlling tty is available. With saved_tty_pgrp == 0,
618 * job control still works, but terminal signals
619 * (^C, ^Z, ^Y, ^\) won't work at all, and background
620 * process groups can only be created with "cmd &".
621 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
622 * to give tty to the foreground process group,
623 * and will take it back when the group is stopped (^Z)
626 #if ENABLE_HUSH_INTERACTIVE
627 /* 'interactive_fd' is a fd# open to ctty, if we have one
628 * _AND_ if we decided to act interactively */
632 # define G_interactive_fd (G.interactive_fd)
634 # define G_interactive_fd 0
636 #if ENABLE_FEATURE_EDITING
637 line_input_t *line_input_state;
642 #if ENABLE_HUSH_RANDOM_SUPPORT
648 pid_t saved_tty_pgrp;
649 struct pipe *job_list;
650 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
652 # define G_saved_tty_pgrp 0
654 smallint flag_SIGINT;
655 #if ENABLE_HUSH_LOOPS
656 smallint flag_break_continue;
658 #if ENABLE_HUSH_FUNCTIONS
659 /* 0: outside of a function (or sourced file)
660 * -1: inside of a function, ok to use return builtin
661 * 1: return is invoked, skip all till end of func
663 smallint flag_return_in_progress;
666 #if ENABLE_HUSH_MODE_X
668 # define G_x_mode (G.x_mode)
672 smallint exiting; /* used to prevent EXIT trap recursion */
673 /* These four support $?, $#, and $1 */
674 smalluint last_exitcode;
675 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
676 smalluint global_args_malloced;
677 smalluint inherited_set_is_saved;
678 /* how many non-NULL argv's we have. NB: $# + 1 */
682 char *argv0_for_re_execing;
684 #if ENABLE_HUSH_LOOPS
685 unsigned depth_break_continue;
686 unsigned depth_of_loop;
690 struct variable *top_var; /* = &G.shell_ver (set in main()) */
691 struct variable shell_ver;
692 char **expanded_assignments;
693 #if ENABLE_HUSH_FUNCTIONS
694 struct function *top_func;
695 # if ENABLE_HUSH_LOCAL
696 struct variable **shadowed_vars_pp;
697 unsigned func_nest_level;
700 /* Signal and trap handling */
702 unsigned count_SIGCHLD;
703 unsigned handled_SIGCHLD;
704 smallint we_have_children;
706 /* which signals have non-DFL handler (even with no traps set)? */
707 unsigned non_DFL_mask;
708 char **traps; /* char *traps[NSIG] */
709 sigset_t blocked_set;
710 sigset_t inherited_set;
712 unsigned long memleak_value;
715 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
717 #define G (*ptr_to_globals)
718 /* Not #defining name to G.name - this quickly gets unwieldy
719 * (too many defines). Also, I actually prefer to see when a variable
720 * is global, thus "G." prefix is a useful hint */
721 #define INIT_G() do { \
722 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
726 /* Function prototypes for builtins */
727 static int builtin_cd(char **argv) FAST_FUNC;
728 static int builtin_echo(char **argv) FAST_FUNC;
729 static int builtin_eval(char **argv) FAST_FUNC;
730 static int builtin_exec(char **argv) FAST_FUNC;
731 static int builtin_exit(char **argv) FAST_FUNC;
732 static int builtin_export(char **argv) FAST_FUNC;
734 static int builtin_fg_bg(char **argv) FAST_FUNC;
735 static int builtin_jobs(char **argv) FAST_FUNC;
738 static int builtin_help(char **argv) FAST_FUNC;
740 #if ENABLE_HUSH_LOCAL
741 static int builtin_local(char **argv) FAST_FUNC;
744 static int builtin_memleak(char **argv) FAST_FUNC;
747 static int builtin_printf(char **argv) FAST_FUNC;
749 static int builtin_pwd(char **argv) FAST_FUNC;
750 static int builtin_read(char **argv) FAST_FUNC;
751 static int builtin_set(char **argv) FAST_FUNC;
752 static int builtin_shift(char **argv) FAST_FUNC;
753 static int builtin_source(char **argv) FAST_FUNC;
754 static int builtin_test(char **argv) FAST_FUNC;
755 static int builtin_trap(char **argv) FAST_FUNC;
756 static int builtin_type(char **argv) FAST_FUNC;
757 static int builtin_true(char **argv) FAST_FUNC;
758 static int builtin_umask(char **argv) FAST_FUNC;
759 static int builtin_unset(char **argv) FAST_FUNC;
760 static int builtin_wait(char **argv) FAST_FUNC;
761 #if ENABLE_HUSH_LOOPS
762 static int builtin_break(char **argv) FAST_FUNC;
763 static int builtin_continue(char **argv) FAST_FUNC;
765 #if ENABLE_HUSH_FUNCTIONS
766 static int builtin_return(char **argv) FAST_FUNC;
769 /* Table of built-in functions. They can be forked or not, depending on
770 * context: within pipes, they fork. As simple commands, they do not.
771 * When used in non-forking context, they can change global variables
772 * in the parent shell process. If forked, of course they cannot.
773 * For example, 'unset foo | whatever' will parse and run, but foo will
774 * still be set at the end. */
775 struct built_in_command {
777 int (*b_function)(char **argv) FAST_FUNC;
780 # define BLTIN(cmd, func, help) { cmd, func, help }
782 # define BLTIN(cmd, func, help) { cmd, func }
786 static const struct built_in_command bltins1[] = {
787 BLTIN("." , builtin_source , "Run commands in a file"),
788 BLTIN(":" , builtin_true , NULL),
790 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
792 #if ENABLE_HUSH_LOOPS
793 BLTIN("break" , builtin_break , "Exit from a loop"),
795 BLTIN("cd" , builtin_cd , "Change directory"),
796 #if ENABLE_HUSH_LOOPS
797 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
799 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
800 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
801 BLTIN("exit" , builtin_exit , "Exit"),
802 BLTIN("export" , builtin_export , "Set environment variables"),
804 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
807 BLTIN("help" , builtin_help , NULL),
810 BLTIN("jobs" , builtin_jobs , "List jobs"),
812 #if ENABLE_HUSH_LOCAL
813 BLTIN("local" , builtin_local , "Set local variables"),
816 BLTIN("memleak" , builtin_memleak , NULL),
818 BLTIN("read" , builtin_read , "Input into variable"),
819 #if ENABLE_HUSH_FUNCTIONS
820 BLTIN("return" , builtin_return , "Return from a function"),
822 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
823 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
824 #if ENABLE_HUSH_BASH_COMPAT
825 BLTIN("source" , builtin_source , "Run commands in a file"),
827 BLTIN("trap" , builtin_trap , "Trap signals"),
828 BLTIN("type" , builtin_type , "Show command type"),
829 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
830 BLTIN("umask" , builtin_umask , "Set file creation mask"),
831 BLTIN("unset" , builtin_unset , "Unset variables"),
832 BLTIN("wait" , builtin_wait , "Wait for process"),
834 /* For now, echo and test are unconditionally enabled.
835 * Maybe make it configurable? */
836 static const struct built_in_command bltins2[] = {
837 BLTIN("[" , builtin_test , NULL),
838 BLTIN("echo" , builtin_echo , NULL),
840 BLTIN("printf" , builtin_printf , NULL),
842 BLTIN("pwd" , builtin_pwd , NULL),
843 BLTIN("test" , builtin_test , NULL),
850 /* prevent disasters with G.debug_indent < 0 */
851 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
852 # define debug_enter() (G.debug_indent++)
853 # define debug_leave() (G.debug_indent--)
855 # define indent() ((void)0)
856 # define debug_enter() ((void)0)
857 # define debug_leave() ((void)0)
861 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
864 #ifndef debug_printf_parse
865 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
868 #ifndef debug_printf_exec
869 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
872 #ifndef debug_printf_env
873 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
876 #ifndef debug_printf_jobs
877 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
878 # define DEBUG_JOBS 1
880 # define DEBUG_JOBS 0
883 #ifndef debug_printf_expand
884 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
885 # define DEBUG_EXPAND 1
887 # define DEBUG_EXPAND 0
890 #ifndef debug_printf_varexp
891 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
894 #ifndef debug_printf_glob
895 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
896 # define DEBUG_GLOB 1
898 # define DEBUG_GLOB 0
901 #ifndef debug_printf_list
902 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
905 #ifndef debug_printf_subst
906 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 #ifndef debug_printf_clean
910 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
911 # define DEBUG_CLEAN 1
913 # define DEBUG_CLEAN 0
917 static void debug_print_strings(const char *prefix, char **vv)
920 fprintf(stderr, "%s:\n", prefix);
922 fprintf(stderr, " '%s'\n", *vv++);
925 # define debug_print_strings(prefix, vv) ((void)0)
929 /* Leak hunting. Use hush_leaktool.sh for post-processing.
932 static void *xxmalloc(int lineno, size_t size)
934 void *ptr = xmalloc((size + 0xff) & ~0xff);
935 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
938 static void *xxrealloc(int lineno, void *ptr, size_t size)
940 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
941 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
944 static char *xxstrdup(int lineno, const char *str)
946 char *ptr = xstrdup(str);
947 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
950 static void xxfree(void *ptr)
952 fdprintf(2, "free %p\n", ptr);
955 # define xmalloc(s) xxmalloc(__LINE__, s)
956 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
957 # define xstrdup(s) xxstrdup(__LINE__, s)
958 # define free(p) xxfree(p)
962 /* Syntax and runtime errors. They always abort scripts.
963 * In interactive use they usually discard unparsed and/or unexecuted commands
964 * and return to the prompt.
965 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
968 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
969 # define syntax_error(lineno, msg) syntax_error(msg)
970 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
971 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
972 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
973 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
976 static void die_if_script(unsigned lineno, const char *fmt, ...)
981 bb_error_msg("hush.c:%u", lineno);
984 bb_verror_msg(fmt, p, NULL);
986 if (!G_interactive_fd)
990 static void syntax_error(unsigned lineno, const char *msg)
993 die_if_script(lineno, "syntax error: %s", msg);
995 die_if_script(lineno, "syntax error", NULL);
998 static void syntax_error_at(unsigned lineno, const char *msg)
1000 die_if_script(lineno, "syntax error at '%s'", msg);
1003 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1005 die_if_script(lineno, "syntax error: unterminated %s", s);
1008 /* It so happens that all such cases are totally fatal
1009 * even if shell is interactive: EOF while looking for closing
1010 * delimiter. There is nowhere to read stuff from after that,
1011 * it's EOF! The only choice is to terminate.
1013 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1014 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1016 char msg[2] = { ch, '\0' };
1017 syntax_error_unterm_str(lineno, msg);
1021 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1026 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1030 # undef die_if_script
1031 # undef syntax_error
1032 # undef syntax_error_at
1033 # undef syntax_error_unterm_ch
1034 # undef syntax_error_unterm_str
1035 # undef syntax_error_unexpected_ch
1037 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1038 # define syntax_error(msg) syntax_error(__LINE__, msg)
1039 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1040 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1041 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1042 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1046 #if ENABLE_HUSH_INTERACTIVE
1047 static void cmdedit_update_prompt(void);
1049 # define cmdedit_update_prompt() ((void)0)
1053 /* Utility functions
1055 /* Replace each \x with x in place, return ptr past NUL. */
1056 static char *unbackslash(char *src)
1058 char *dst = src = strchrnul(src, '\\');
1062 if ((*dst++ = *src++) == '\0')
1068 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1089 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1090 v[count1 + count2] = NULL;
1093 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1097 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1099 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1100 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1103 #define add_strings_to_strings(strings, add, need_to_dup) \
1104 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1107 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1108 static char **add_string_to_strings(char **strings, char *add)
1113 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1116 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1118 char **ptr = add_string_to_strings(strings, add);
1119 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1122 #define add_string_to_strings(strings, add) \
1123 xx_add_string_to_strings(__LINE__, strings, add)
1126 static void free_strings(char **strings)
1141 /* Helpers for setting new $n and restoring them back
1143 typedef struct save_arg_t {
1147 smallint sv_g_malloced;
1150 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1154 sv->sv_argv0 = argv[0];
1155 sv->sv_g_argv = G.global_argv;
1156 sv->sv_g_argc = G.global_argc;
1157 sv->sv_g_malloced = G.global_args_malloced;
1159 argv[0] = G.global_argv[0]; /* retain $0 */
1160 G.global_argv = argv;
1161 G.global_args_malloced = 0;
1169 static void restore_G_args(save_arg_t *sv, char **argv)
1173 if (G.global_args_malloced) {
1174 /* someone ran "set -- arg1 arg2 ...", undo */
1176 while (*++pp) /* note: does not free $0 */
1178 free(G.global_argv);
1180 argv[0] = sv->sv_argv0;
1181 G.global_argv = sv->sv_g_argv;
1182 G.global_argc = sv->sv_g_argc;
1183 G.global_args_malloced = sv->sv_g_malloced;
1187 /* Basic theory of signal handling in shell
1188 * ========================================
1189 * This does not describe what hush does, rather, it is current understanding
1190 * what it _should_ do. If it doesn't, it's a bug.
1191 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1193 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1194 * is finished or backgrounded. It is the same in interactive and
1195 * non-interactive shells, and is the same regardless of whether
1196 * a user trap handler is installed or a shell special one is in effect.
1197 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1198 * backgrounds (i.e. stops) or kills all members of currently running
1201 * Wait builtin in interruptible by signals for which user trap is set
1202 * or by SIGINT in interactive shell.
1204 * Trap handlers will execute even within trap handlers. (right?)
1206 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1207 * except for handlers set to '' (empty string).
1209 * If job control is off, backgrounded commands ("cmd &")
1210 * have SIGINT, SIGQUIT set to SIG_IGN.
1212 * Commands which are run in command substitution ("`cmd`")
1213 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1215 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1216 * by the shell from its parent.
1218 * Signals which differ from SIG_DFL action
1219 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1222 * SIGTERM (interactive): ignore
1223 * SIGHUP (interactive):
1224 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1225 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1226 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1227 * that all pipe members are stopped. Try this in bash:
1228 * while :; do :; done - ^Z does not background it
1229 * (while :; do :; done) - ^Z backgrounds it
1230 * SIGINT (interactive): wait for last pipe, ignore the rest
1231 * of the command line, show prompt. NB: ^C does not send SIGINT
1232 * to interactive shell while shell is waiting for a pipe,
1233 * since shell is bg'ed (is not in foreground process group).
1234 * Example 1: this waits 5 sec, but does not execute ls:
1235 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1236 * Example 2: this does not wait and does not execute ls:
1237 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1238 * Example 3: this does not wait 5 sec, but executes ls:
1239 * "sleep 5; ls -l" + press ^C
1241 * (What happens to signals which are IGN on shell start?)
1242 * (What happens with signal mask on shell start?)
1244 * Implementation in hush
1245 * ======================
1246 * We use in-kernel pending signal mask to determine which signals were sent.
1247 * We block all signals which we don't want to take action immediately,
1248 * i.e. we block all signals which need to have special handling as described
1249 * above, and all signals which have traps set.
1250 * After each pipe execution, we extract any pending signals via sigtimedwait()
1253 * unsigned non_DFL_mask: a mask of such "special" signals
1254 * sigset_t blocked_set: current blocked signal set
1257 * clear bit in blocked_set unless it is also in non_DFL_mask
1258 * "trap 'cmd' SIGxxx":
1259 * set bit in blocked_set (even if 'cmd' is '')
1260 * after [v]fork, if we plan to be a shell:
1261 * unblock signals with special interactive handling
1262 * (child shell is not interactive),
1263 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1264 * after [v]fork, if we plan to exec:
1265 * POSIX says fork clears pending signal mask in child - no need to clear it.
1266 * Restore blocked signal set to one inherited by shell just prior to exec.
1268 * Note: as a result, we do not use signal handlers much. The only uses
1269 * are to count SIGCHLDs
1270 * and to restore tty pgrp on signal-induced exit.
1273 * Standard says "When a subshell is entered, traps that are not being ignored
1274 * are set to the default actions". bash interprets it so that traps which
1275 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1278 SPECIAL_INTERACTIVE_SIGS = 0
1283 SPECIAL_JOB_SIGS = 0
1291 #if ENABLE_HUSH_FAST
1292 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1295 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1301 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1302 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1303 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1304 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1306 /* Restores tty foreground process group, and exits.
1307 * May be called as signal handler for fatal signal
1308 * (will resend signal to itself, producing correct exit state)
1309 * or called directly with -EXITCODE.
1310 * We also call it if xfunc is exiting. */
1311 static void sigexit(int sig) NORETURN;
1312 static void sigexit(int sig)
1314 /* Disable all signals: job control, SIGPIPE, etc. */
1315 sigprocmask_allsigs(SIG_BLOCK);
1317 /* Careful: we can end up here after [v]fork. Do not restore
1318 * tty pgrp then, only top-level shell process does that */
1319 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1320 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1322 /* Not a signal, just exit */
1326 kill_myself_with_sig(sig); /* does not return */
1330 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1331 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1335 /* Restores tty foreground process group, and exits. */
1336 static void hush_exit(int exitcode) NORETURN;
1337 static void hush_exit(int exitcode)
1339 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1340 /* Prevent recursion:
1341 * trap "echo Hi; exit" EXIT; exit
1343 char *argv[] = { NULL, G.traps[0], NULL };
1352 sigexit(- (exitcode & 0xff));
1358 static int check_and_run_traps(int sig)
1360 static const struct timespec zero_timespec;
1361 smalluint save_rcode;
1367 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1372 if (G.traps && G.traps[sig]) {
1373 if (G.traps[sig][0]) {
1374 /* We have user-defined handler */
1375 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1376 save_rcode = G.last_exitcode;
1379 G.last_exitcode = save_rcode;
1380 } /* else: "" trap, ignoring signal */
1383 /* not a trap: special action */
1385 #if ENABLE_HUSH_FAST
1388 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1392 /* Builtin was ^C'ed, make it look prettier: */
1399 /* bash is observed to signal whole process groups,
1400 * not individual processes */
1401 for (job = G.job_list; job; job = job->next) {
1404 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1405 if (kill(- job->pgrp, SIGHUP) == 0)
1406 kill(- job->pgrp, SIGCONT);
1411 default: /* ignored: */
1412 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1420 static const char *get_cwd(int force)
1422 if (force || G.cwd == NULL) {
1423 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1424 * we must not try to free(bb_msg_unknown) */
1425 if (G.cwd == bb_msg_unknown)
1427 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1429 G.cwd = bb_msg_unknown;
1436 * Shell and environment variable support
1438 static struct variable **get_ptr_to_local_var(const char *name)
1440 struct variable **pp;
1441 struct variable *cur;
1446 while ((cur = *pp) != NULL) {
1447 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1454 static struct variable *get_local_var(const char *name)
1456 struct variable **pp = get_ptr_to_local_var(name);
1462 static const char* FAST_FUNC get_local_var_value(const char *name)
1464 struct variable **vpp;
1466 if (G.expanded_assignments) {
1467 char **cpp = G.expanded_assignments;
1468 int len = strlen(name);
1471 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1472 return cp + len + 1;
1477 vpp = get_ptr_to_local_var(name);
1479 return strchr((*vpp)->varstr, '=') + 1;
1481 if (strcmp(name, "PPID") == 0)
1482 return utoa(G.root_ppid);
1483 // bash compat: UID? EUID?
1484 #if ENABLE_HUSH_RANDOM_SUPPORT
1485 if (strcmp(name, "RANDOM") == 0) {
1486 return utoa(next_random(&G.random_gen));
1492 /* str holds "NAME=VAL" and is expected to be malloced.
1493 * We take ownership of it.
1495 * 0: do not change export flag
1496 * (if creating new variable, flag will be 0)
1497 * 1: set export flag and putenv the variable
1498 * -1: clear export flag and unsetenv the variable
1499 * flg_read_only is set only when we handle -R var=val
1501 #if !BB_MMU && ENABLE_HUSH_LOCAL
1502 /* all params are used */
1503 #elif BB_MMU && ENABLE_HUSH_LOCAL
1504 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1505 set_local_var(str, flg_export, local_lvl)
1506 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1507 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1508 set_local_var(str, flg_export)
1509 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1510 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1511 set_local_var(str, flg_export, flg_read_only)
1513 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1515 struct variable **var_pp;
1516 struct variable *cur;
1520 eq_sign = strchr(str, '=');
1521 if (!eq_sign) { /* not expected to ever happen? */
1526 name_len = eq_sign - str + 1; /* including '=' */
1527 var_pp = &G.top_var;
1528 while ((cur = *var_pp) != NULL) {
1529 if (strncmp(cur->varstr, str, name_len) != 0) {
1530 var_pp = &cur->next;
1533 /* We found an existing var with this name */
1534 if (cur->flg_read_only) {
1538 bb_error_msg("%s: readonly variable", str);
1542 if (flg_export == -1) { // "&& cur->flg_export" ?
1543 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1548 #if ENABLE_HUSH_LOCAL
1549 if (cur->func_nest_level < local_lvl) {
1550 /* New variable is declared as local,
1551 * and existing one is global, or local
1552 * from enclosing function.
1553 * Remove and save old one: */
1554 *var_pp = cur->next;
1555 cur->next = *G.shadowed_vars_pp;
1556 *G.shadowed_vars_pp = cur;
1557 /* bash 3.2.33(1) and exported vars:
1559 * # f() { local z=a; env | grep ^z; }
1565 if (cur->flg_export)
1570 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1575 if (cur->max_len != 0) {
1576 if (cur->max_len >= strlen(str)) {
1577 /* This one is from startup env, reuse space */
1578 strcpy(cur->varstr, str);
1582 /* max_len == 0 signifies "malloced" var, which we can
1583 * (and has to) free */
1587 goto set_str_and_exp;
1590 /* Not found - create new variable struct */
1591 cur = xzalloc(sizeof(*cur));
1592 #if ENABLE_HUSH_LOCAL
1593 cur->func_nest_level = local_lvl;
1595 cur->next = *var_pp;
1601 cur->flg_read_only = flg_read_only;
1604 if (flg_export == 1)
1605 cur->flg_export = 1;
1606 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1607 cmdedit_update_prompt();
1608 if (cur->flg_export) {
1609 if (flg_export == -1) {
1610 cur->flg_export = 0;
1611 /* unsetenv was already done */
1613 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1614 return putenv(cur->varstr);
1620 /* Used at startup and after each cd */
1621 static void set_pwd_var(int exp)
1623 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1624 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1627 static int unset_local_var_len(const char *name, int name_len)
1629 struct variable *cur;
1630 struct variable **var_pp;
1633 return EXIT_SUCCESS;
1634 var_pp = &G.top_var;
1635 while ((cur = *var_pp) != NULL) {
1636 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1637 if (cur->flg_read_only) {
1638 bb_error_msg("%s: readonly variable", name);
1639 return EXIT_FAILURE;
1641 *var_pp = cur->next;
1642 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1643 bb_unsetenv(cur->varstr);
1644 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1645 cmdedit_update_prompt();
1649 return EXIT_SUCCESS;
1651 var_pp = &cur->next;
1653 return EXIT_SUCCESS;
1656 static int unset_local_var(const char *name)
1658 return unset_local_var_len(name, strlen(name));
1661 static void unset_vars(char **strings)
1669 const char *eq = strchrnul(*v, '=');
1670 unset_local_var_len(*v, (int)(eq - *v));
1676 #if ENABLE_SH_MATH_SUPPORT
1677 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1678 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1679 static char* FAST_FUNC endofname(const char *name)
1687 if (!is_in_name(*p))
1694 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1696 char *var = xasprintf("%s=%s", name, val);
1697 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1702 * Helpers for "var1=val1 var2=val2 cmd" feature
1704 static void add_vars(struct variable *var)
1706 struct variable *next;
1710 var->next = G.top_var;
1712 if (var->flg_export) {
1713 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1714 putenv(var->varstr);
1716 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1722 static struct variable *set_vars_and_save_old(char **strings)
1725 struct variable *old = NULL;
1731 struct variable *var_p;
1732 struct variable **var_pp;
1735 eq = strchr(*s, '=');
1738 var_pp = get_ptr_to_local_var(*s);
1741 /* Remove variable from global linked list */
1743 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1744 *var_pp = var_p->next;
1745 /* Add it to returned list */
1749 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1760 static int FAST_FUNC static_get(struct in_str *i)
1770 static int FAST_FUNC static_peek(struct in_str *i)
1775 #if ENABLE_HUSH_INTERACTIVE
1777 static void cmdedit_update_prompt(void)
1779 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1780 G.PS1 = get_local_var_value("PS1");
1783 G.PS2 = get_local_var_value("PS2");
1791 static const char* setup_prompt_string(int promptmode)
1793 const char *prompt_str;
1794 debug_printf("setup_prompt_string %d ", promptmode);
1795 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1796 /* Set up the prompt */
1797 if (promptmode == 0) { /* PS1 */
1799 /* bash uses $PWD value, even if it is set by user.
1800 * It uses current dir only if PWD is unset.
1801 * We always use current dir. */
1802 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1807 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1808 debug_printf("result '%s'\n", prompt_str);
1812 static void get_user_input(struct in_str *i)
1815 const char *prompt_str;
1817 prompt_str = setup_prompt_string(i->promptmode);
1818 # if ENABLE_FEATURE_EDITING
1819 /* Enable command line editing only while a command line
1820 * is actually being read */
1823 /* buglet: SIGINT will not make new prompt to appear _at once_,
1824 * only after <Enter>. (^C will work) */
1825 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1826 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1827 check_and_run_traps(0);
1828 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1829 i->eof_flag = (r < 0);
1830 if (i->eof_flag) { /* EOF/error detected */
1831 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1832 G.user_input_buf[1] = '\0';
1837 fputs(prompt_str, stdout);
1839 G.user_input_buf[0] = r = fgetc(i->file);
1840 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1841 //do we need check_and_run_traps(0)? (maybe only if stdin)
1842 } while (G.flag_SIGINT);
1843 i->eof_flag = (r == EOF);
1845 i->p = G.user_input_buf;
1848 #endif /* INTERACTIVE */
1850 /* This is the magic location that prints prompts
1851 * and gets data back from the user */
1852 static int FAST_FUNC file_get(struct in_str *i)
1856 /* If there is data waiting, eat it up */
1857 if (i->p && *i->p) {
1858 #if ENABLE_HUSH_INTERACTIVE
1862 if (i->eof_flag && !*i->p)
1864 /* note: ch is never NUL */
1866 /* need to double check i->file because we might be doing something
1867 * more complicated by now, like sourcing or substituting. */
1868 #if ENABLE_HUSH_INTERACTIVE
1869 if (G_interactive_fd && i->promptme && i->file == stdin) {
1872 } while (!*i->p); /* need non-empty line */
1873 i->promptmode = 1; /* PS2 */
1878 do ch = fgetc(i->file); while (ch == '\0');
1880 debug_printf("file_get: got '%c' %d\n", ch, ch);
1881 #if ENABLE_HUSH_INTERACTIVE
1888 /* All callers guarantee this routine will never
1889 * be used right after a newline, so prompting is not needed.
1891 static int FAST_FUNC file_peek(struct in_str *i)
1894 if (i->p && *i->p) {
1895 if (i->eof_flag && !i->p[1])
1898 /* note: ch is never NUL */
1900 do ch = fgetc(i->file); while (ch == '\0');
1901 i->eof_flag = (ch == EOF);
1902 i->peek_buf[0] = ch;
1903 i->peek_buf[1] = '\0';
1905 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1909 static void setup_file_in_str(struct in_str *i, FILE *f)
1911 i->peek = file_peek;
1913 #if ENABLE_HUSH_INTERACTIVE
1915 i->promptmode = 0; /* PS1 */
1921 static void setup_string_in_str(struct in_str *i, const char *s)
1923 i->peek = static_peek;
1924 i->get = static_get;
1925 #if ENABLE_HUSH_INTERACTIVE
1927 i->promptmode = 0; /* PS1 */
1937 #define B_CHUNK (32 * sizeof(char*))
1939 static void o_reset_to_empty_unquoted(o_string *o)
1947 static void o_free(o_string *o)
1950 memset(o, 0, sizeof(*o));
1953 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1958 static void o_grow_by(o_string *o, int len)
1960 if (o->length + len > o->maxlen) {
1961 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1962 o->data = xrealloc(o->data, 1 + o->maxlen);
1966 static void o_addchr(o_string *o, int ch)
1968 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1970 o->data[o->length] = ch;
1972 o->data[o->length] = '\0';
1975 static void o_addblock(o_string *o, const char *str, int len)
1978 memcpy(&o->data[o->length], str, len);
1980 o->data[o->length] = '\0';
1983 static void o_addstr(o_string *o, const char *str)
1985 o_addblock(o, str, strlen(str));
1989 static void nommu_addchr(o_string *o, int ch)
1995 # define nommu_addchr(o, str) ((void)0)
1998 static void o_addstr_with_NUL(o_string *o, const char *str)
2000 o_addblock(o, str, strlen(str) + 1);
2003 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2008 && (*str != '*' && *str != '?' && *str != '[')
2016 #undef HUSH_BRACE_EXP
2018 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2019 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2020 * Apparently, on unquoted $v bash still does globbing
2021 * ("v='*.txt'; echo $v" prints all .txt files),
2022 * but NOT brace expansion! Thus, there should be TWO independent
2023 * quoting mechanisms on $v expansion side: one protects
2024 * $v from brace expansion, and other additionally protects "$v" against globbing.
2025 * We have only second one.
2028 #ifdef HUSH_BRACE_EXP
2029 # define MAYBE_BRACES "{}"
2031 # define MAYBE_BRACES ""
2034 /* My analysis of quoting semantics tells me that state information
2035 * is associated with a destination, not a source.
2037 static void o_addqchr(o_string *o, int ch)
2040 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2045 o->data[o->length] = '\\';
2048 o->data[o->length] = ch;
2050 o->data[o->length] = '\0';
2053 static void o_addQchr(o_string *o, int ch)
2056 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2058 o->data[o->length] = '\\';
2062 o->data[o->length] = ch;
2064 o->data[o->length] = '\0';
2067 static void o_addQstr(o_string *o, const char *str, int len)
2070 o_addblock(o, str, len);
2076 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2077 if (ordinary_cnt > len) /* paranoia */
2079 o_addblock(o, str, ordinary_cnt);
2080 if (ordinary_cnt == len)
2082 str += ordinary_cnt;
2083 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2087 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2089 o->data[o->length] = '\\';
2093 o->data[o->length] = ch;
2095 o->data[o->length] = '\0';
2099 /* A special kind of o_string for $VAR and `cmd` expansion.
2100 * It contains char* list[] at the beginning, which is grown in 16 element
2101 * increments. Actual string data starts at the next multiple of 16 * (char*).
2102 * list[i] contains an INDEX (int!) into this string data.
2103 * It means that if list[] needs to grow, data needs to be moved higher up
2104 * but list[i]'s need not be modified.
2105 * NB: remembering how many list[i]'s you have there is crucial.
2106 * o_finalize_list() operation post-processes this structure - calculates
2107 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2109 #if DEBUG_EXPAND || DEBUG_GLOB
2110 static void debug_print_list(const char *prefix, o_string *o, int n)
2112 char **list = (char**)o->data;
2113 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2117 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2118 prefix, list, n, string_start, o->length, o->maxlen);
2121 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2122 o->data + (int)list[i] + string_start,
2123 o->data + (int)list[i] + string_start);
2127 const char *p = o->data + (int)list[n - 1] + string_start;
2129 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2133 # define debug_print_list(prefix, o, n) ((void)0)
2136 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2137 * in list[n] so that it points past last stored byte so far.
2138 * It returns n+1. */
2139 static int o_save_ptr_helper(o_string *o, int n)
2141 char **list = (char**)o->data;
2145 if (!o->has_empty_slot) {
2146 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2147 string_len = o->length - string_start;
2148 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2149 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2150 /* list[n] points to string_start, make space for 16 more pointers */
2151 o->maxlen += 0x10 * sizeof(list[0]);
2152 o->data = xrealloc(o->data, o->maxlen + 1);
2153 list = (char**)o->data;
2154 memmove(list + n + 0x10, list + n, string_len);
2155 o->length += 0x10 * sizeof(list[0]);
2157 debug_printf_list("list[%d]=%d string_start=%d\n",
2158 n, string_len, string_start);
2161 /* We have empty slot at list[n], reuse without growth */
2162 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2163 string_len = o->length - string_start;
2164 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2165 n, string_len, string_start);
2166 o->has_empty_slot = 0;
2168 list[n] = (char*)(ptrdiff_t)string_len;
2172 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2173 static int o_get_last_ptr(o_string *o, int n)
2175 char **list = (char**)o->data;
2176 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2178 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2181 #ifdef HUSH_BRACE_EXP
2182 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2183 * first, it processes even {a} (no commas), second,
2184 * I didn't manage to make it return strings when they don't match
2185 * existing files. Need to re-implement it.
2189 static int glob_needed(const char *s)
2198 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2204 /* Return pointer to next closing brace or to comma */
2205 static const char *next_brace_sub(const char *cp)
2209 while (*cp != '\0') {
2216 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2218 if (*cp++ == '{') /*}*/
2222 return *cp != '\0' ? cp : NULL;
2224 /* Recursive brace globber. Note: may garble pattern[]. */
2225 static int glob_brace(char *pattern, o_string *o, int n)
2227 char *new_pattern_buf;
2234 debug_printf_glob("glob_brace('%s')\n", pattern);
2240 if (*begin == '{') /*}*/ {
2241 /* Find the first sub-pattern and at the same time
2242 * find the rest after the closing brace */
2243 next = next_brace_sub(begin);
2245 /* An illegal expression */
2248 /*{*/ if (*next == '}') {
2249 /* "{abc}" with no commas - illegal
2250 * brace expr, disregard and skip it */
2256 if (*begin == '\\' && begin[1] != '\0')
2260 debug_printf_glob("begin:%s\n", begin);
2261 debug_printf_glob("next:%s\n", next);
2263 /* Now find the end of the whole brace expression */
2265 /*{*/ while (*rest != '}') {
2266 rest = next_brace_sub(rest);
2268 /* An illegal expression */
2271 debug_printf_glob("rest:%s\n", rest);
2273 rest_len = strlen(++rest) + 1;
2275 /* We are sure the brace expression is well-formed */
2277 /* Allocate working buffer large enough for our work */
2278 new_pattern_buf = xmalloc(strlen(pattern));
2280 /* We have a brace expression. BEGIN points to the opening {,
2281 * NEXT points past the terminator of the first element, and REST
2282 * points past the final }. We will accumulate result names from
2283 * recursive runs for each brace alternative in the buffer using
2288 /* Construct the new glob expression */
2291 mempcpy(new_pattern_buf,
2292 /* We know the prefix for all sub-patterns */
2293 pattern, begin - pattern),
2297 /* Note: glob_brace() may garble new_pattern_buf[].
2298 * That's why we re-copy prefix every time (1st memcpy above).
2300 n = glob_brace(new_pattern_buf, o, n);
2301 /*{*/ if (*next == '}') {
2302 /* We saw the last entry */
2306 next = next_brace_sub(next);
2308 free(new_pattern_buf);
2316 memset(&globdata, 0, sizeof(globdata));
2317 gr = glob(pattern, 0, NULL, &globdata);
2318 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2320 if (gr == GLOB_NOMATCH) {
2321 globfree(&globdata);
2322 /* NB: garbles parameter */
2323 unbackslash(pattern);
2324 o_addstr_with_NUL(o, pattern);
2325 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2326 return o_save_ptr_helper(o, n);
2328 if (gr == GLOB_NOSPACE)
2329 bb_error_msg_and_die(bb_msg_memory_exhausted);
2330 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2331 * but we didn't specify it. Paranoia again. */
2332 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2334 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2335 char **argv = globdata.gl_pathv;
2337 o_addstr_with_NUL(o, *argv);
2338 n = o_save_ptr_helper(o, n);
2344 globfree(&globdata);
2348 /* Performs globbing on last list[],
2349 * saving each result as a new list[].
2351 static int o_glob(o_string *o, int n)
2353 char *pattern, *copy;
2355 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2357 return o_save_ptr_helper(o, n);
2358 pattern = o->data + o_get_last_ptr(o, n);
2359 debug_printf_glob("glob pattern '%s'\n", pattern);
2360 if (!glob_needed(pattern)) {
2361 /* unbackslash last string in o in place, fix length */
2362 o->length = unbackslash(pattern) - o->data;
2363 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2364 return o_save_ptr_helper(o, n);
2367 copy = xstrdup(pattern);
2368 /* "forget" pattern in o */
2369 o->length = pattern - o->data;
2370 n = glob_brace(copy, o, n);
2373 debug_print_list("o_glob returning", o, n);
2377 #else /* !HUSH_BRACE_EXP */
2380 static int glob_needed(const char *s)
2389 if (*s == '*' || *s == '[' || *s == '?')
2395 /* Performs globbing on last list[],
2396 * saving each result as a new list[].
2398 static int o_glob(o_string *o, int n)
2404 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2406 return o_save_ptr_helper(o, n);
2407 pattern = o->data + o_get_last_ptr(o, n);
2408 debug_printf_glob("glob pattern '%s'\n", pattern);
2409 if (!glob_needed(pattern)) {
2411 /* unbackslash last string in o in place, fix length */
2412 o->length = unbackslash(pattern) - o->data;
2413 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2414 return o_save_ptr_helper(o, n);
2417 memset(&globdata, 0, sizeof(globdata));
2418 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2419 * If we glob "*.\*" and don't find anything, we need
2420 * to fall back to using literal "*.*", but GLOB_NOCHECK
2421 * will return "*.\*"!
2423 gr = glob(pattern, 0, NULL, &globdata);
2424 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2426 if (gr == GLOB_NOMATCH) {
2427 globfree(&globdata);
2430 if (gr == GLOB_NOSPACE)
2431 bb_error_msg_and_die(bb_msg_memory_exhausted);
2432 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2433 * but we didn't specify it. Paranoia again. */
2434 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2436 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2437 char **argv = globdata.gl_pathv;
2438 /* "forget" pattern in o */
2439 o->length = pattern - o->data;
2441 o_addstr_with_NUL(o, *argv);
2442 n = o_save_ptr_helper(o, n);
2448 globfree(&globdata);
2450 debug_print_list("o_glob returning", o, n);
2454 #endif /* !HUSH_BRACE_EXP */
2456 /* If o->o_glob == 1, glob the string so far remembered.
2457 * Otherwise, just finish current list[] and start new */
2458 static int o_save_ptr(o_string *o, int n)
2460 if (o->o_glob) { /* if globbing is requested */
2461 /* If o->has_empty_slot, list[n] was already globbed
2462 * (if it was requested back then when it was filled)
2463 * so don't do that again! */
2464 if (!o->has_empty_slot)
2465 return o_glob(o, n); /* o_save_ptr_helper is inside */
2467 return o_save_ptr_helper(o, n);
2470 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2471 static char **o_finalize_list(o_string *o, int n)
2476 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2478 debug_print_list("finalized", o, n);
2479 debug_printf_expand("finalized n:%d\n", n);
2480 list = (char**)o->data;
2481 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2485 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2491 /* Expansion can recurse */
2492 #if ENABLE_HUSH_TICK
2493 static int process_command_subs(o_string *dest, const char *s);
2495 static char *expand_string_to_string(const char *str);
2497 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2498 parse_stream_dquoted(dest, input, dquote_end)
2500 static int parse_stream_dquoted(o_string *as_string,
2502 struct in_str *input,
2505 /* expand_strvec_to_strvec() takes a list of strings, expands
2506 * all variable references within and returns a pointer to
2507 * a list of expanded strings, possibly with larger number
2508 * of strings. (Think VAR="a b"; echo $VAR).
2509 * This new list is allocated as a single malloc block.
2510 * NULL-terminated list of char* pointers is at the beginning of it,
2511 * followed by strings themself.
2512 * Caller can deallocate entire list by single free(list). */
2514 /* Store given string, finalizing the word and starting new one whenever
2515 * we encounter IFS char(s). This is used for expanding variable values.
2516 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2517 static int expand_on_ifs(o_string *output, int n, const char *str)
2520 int word_len = strcspn(str, G.ifs);
2522 if (output->o_escape || !output->o_glob)
2523 o_addQstr(output, str, word_len);
2524 else /* protect backslashes against globbing up :) */
2525 o_addblock_duplicate_backslash(output, str, word_len);
2528 if (!*str) /* EOL - do not finalize word */
2530 o_addchr(output, '\0');
2531 debug_print_list("expand_on_ifs", output, n);
2532 n = o_save_ptr(output, n);
2533 str += strspn(str, G.ifs); /* skip ifs chars */
2535 debug_print_list("expand_on_ifs[1]", output, n);
2539 /* Helper to expand $((...)) and heredoc body. These act as if
2540 * they are in double quotes, with the exception that they are not :).
2541 * Just the rules are similar: "expand only $var and `cmd`"
2543 * Returns malloced string.
2544 * As an optimization, we return NULL if expansion is not needed.
2546 static char *expand_pseudo_dquoted(const char *str)
2549 struct in_str input;
2550 o_string dest = NULL_O_STRING;
2552 if (strchr(str, '$') == NULL
2553 #if ENABLE_HUSH_TICK
2554 && strchr(str, '`') == NULL
2560 /* We need to expand. Example:
2561 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2563 setup_string_in_str(&input, str);
2564 parse_stream_dquoted(NULL, &dest, &input, EOF);
2565 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2566 exp_str = expand_string_to_string(dest.data);
2567 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2568 o_free_unsafe(&dest);
2572 #if ENABLE_SH_MATH_SUPPORT
2573 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2575 arith_eval_hooks_t hooks;
2579 hooks.lookupvar = get_local_var_value;
2580 hooks.setvar = set_local_var_from_halves;
2581 hooks.endofname = endofname;
2582 exp_str = expand_pseudo_dquoted(arg);
2583 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2589 /* Expand all variable references in given string, adding words to list[]
2590 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2591 * to be filled). This routine is extremely tricky: has to deal with
2592 * variables/parameters with whitespace, $* and $@, and constructs like
2593 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2594 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2596 /* or_mask is either 0 (normal case) or 0x80 -
2597 * expansion of right-hand side of assignment == 1-element expand.
2598 * It will also do no globbing, and thus we must not backslash-quote!
2605 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2606 debug_print_list("expand_vars_to_list", output, n);
2607 n = o_save_ptr(output, n);
2608 debug_print_list("expand_vars_to_list[0]", output, n);
2610 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2613 char *to_be_freed = NULL;
2614 const char *val = NULL;
2615 #if ENABLE_HUSH_TICK
2616 o_string subst_result = NULL_O_STRING;
2618 #if ENABLE_SH_MATH_SUPPORT
2619 char arith_buf[sizeof(arith_t)*3 + 2];
2621 o_addblock(output, arg, p - arg);
2622 debug_print_list("expand_vars_to_list[1]", output, n);
2624 p = strchr(p, SPECIAL_VAR_SYMBOL);
2626 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2627 /* "$@" is special. Even if quoted, it can still
2628 * expand to nothing (not even an empty string) */
2629 if ((first_ch & 0x7f) != '@')
2630 ored_ch |= first_ch;
2632 switch (first_ch & 0x7f) {
2633 /* Highest bit in first_ch indicates that var is double-quoted */
2637 if (!G.global_argv[i])
2639 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2640 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2641 smallint sv = output->o_escape;
2642 /* unquoted var's contents should be globbed, so don't escape */
2643 output->o_escape = 0;
2644 while (G.global_argv[i]) {
2645 n = expand_on_ifs(output, n, G.global_argv[i]);
2646 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2647 if (G.global_argv[i++][0] && G.global_argv[i]) {
2648 /* this argv[] is not empty and not last:
2649 * put terminating NUL, start new word */
2650 o_addchr(output, '\0');
2651 debug_print_list("expand_vars_to_list[2]", output, n);
2652 n = o_save_ptr(output, n);
2653 debug_print_list("expand_vars_to_list[3]", output, n);
2656 output->o_escape = sv;
2658 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2659 * and in this case should treat it like '$*' - see 'else...' below */
2660 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2662 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2663 if (++i >= G.global_argc)
2665 o_addchr(output, '\0');
2666 debug_print_list("expand_vars_to_list[4]", output, n);
2667 n = o_save_ptr(output, n);
2669 } else { /* quoted $*: add as one word */
2671 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2672 if (!G.global_argv[++i])
2675 o_addchr(output, G.ifs[0]);
2679 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2680 /* "Empty variable", used to make "" etc to not disappear */
2684 #if ENABLE_HUSH_TICK
2685 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2688 /* Can't just stuff it into output o_string,
2689 * expanded result may need to be globbed
2690 * and $IFS-splitted */
2691 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2692 G.last_exitcode = process_command_subs(&subst_result, arg);
2693 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
2694 val = subst_result.data;
2697 #if ENABLE_SH_MATH_SUPPORT
2698 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2702 arg++; /* skip '+' */
2703 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2704 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2705 res = expand_and_evaluate_arith(arg, &errcode);
2708 const char *msg = "error in arithmetic";
2711 msg = "exponent less than 0";
2714 msg = "divide by 0";
2717 msg = "expression recursion loop detected";
2722 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2723 sprintf(arith_buf, arith_t_fmt, res);
2728 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2732 char exp_save = exp_save; /* for compiler */
2733 char *exp_saveptr; /* points to expansion operator */
2734 char *exp_word = exp_word; /* for compiler */
2738 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2739 first_char = arg[0] = first_ch & 0x7f;
2742 if (first_char == '#' && arg[1] && !exp_saveptr) {
2743 /* handle length expansion ${#var} */
2747 /* maybe handle parameter expansion */
2748 if (exp_saveptr /* if 2nd char is one of expansion operators */
2749 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2751 /* ${?:0}, ${#[:]%0} etc */
2752 exp_saveptr = var + 1;
2754 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2755 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2757 exp_op = exp_save = *exp_saveptr;
2759 exp_word = exp_saveptr + 1;
2760 if (exp_op == ':') {
2761 exp_op = *exp_word++;
2762 if (ENABLE_HUSH_BASH_COMPAT
2763 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2765 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2770 *exp_saveptr = '\0';
2771 } /* else: it's not an expansion op, but bare ${var} */
2774 /* lookup the variable in question */
2775 if (isdigit(var[0])) {
2776 /* parse_dollar() should have vetted var for us */
2778 if (i < G.global_argc)
2779 val = G.global_argv[i];
2780 /* else val remains NULL: $N with too big N */
2784 val = utoa(G.root_pid);
2786 case '!': /* bg pid */
2787 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2789 case '?': /* exitcode */
2790 val = utoa(G.last_exitcode);
2792 case '#': /* argc */
2793 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2796 val = get_local_var_value(var);
2800 /* handle any expansions */
2801 if (exp_op == 'L') {
2802 debug_printf_expand("expand: length(%s)=", val);
2803 val = utoa(val ? strlen(val) : 0);
2804 debug_printf_expand("%s\n", val);
2805 } else if (exp_op) {
2806 if (exp_op == '%' || exp_op == '#') {
2807 /* Standard-mandated substring removal ops:
2808 * ${parameter%word} - remove smallest suffix pattern
2809 * ${parameter%%word} - remove largest suffix pattern
2810 * ${parameter#word} - remove smallest prefix pattern
2811 * ${parameter##word} - remove largest prefix pattern
2813 * Word is expanded to produce a glob pattern.
2814 * Then var's value is matched to it and matching part removed.
2819 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2820 if (exp_op == *exp_word) /* ## or %% */
2822 val = to_be_freed = xstrdup(val);
2824 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2826 exp_word = exp_exp_word;
2827 loc = scan(to_be_freed, exp_word, match_at_left);
2828 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2829 // exp_op, to_be_freed, exp_word, loc);
2832 if (loc) { /* match was found */
2833 if (match_at_left) /* # or ## */
2839 } else if (exp_op == ':') {
2840 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2841 /* It's ${var:N[:M]} bashism.
2842 * Note that in encoded form it has TWO parts:
2843 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2848 beg = expand_and_evaluate_arith(exp_word, &errcode);
2849 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2850 *p++ = SPECIAL_VAR_SYMBOL;
2852 p = strchr(p, SPECIAL_VAR_SYMBOL);
2854 len = expand_and_evaluate_arith(exp_word, &errcode);
2855 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2857 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2858 if (beg < 0) /* bash compat */
2860 debug_printf_varexp("from val:'%s'\n", val);
2861 if (len == 0 || !val || beg >= strlen(val))
2864 /* Paranoia. What if user entered 9999999999999
2865 * which fits in arith_t but not int? */
2868 val = to_be_freed = xstrndup(val + beg, len);
2870 debug_printf_varexp("val:'%s'\n", val);
2874 die_if_script("malformed ${%s:...}", var);
2877 } else { /* one of "-=+?" */
2878 /* Standard-mandated substitution ops:
2879 * ${var?word} - indicate error if unset
2880 * If var is unset, word (or a message indicating it is unset
2881 * if word is null) is written to standard error
2882 * and the shell exits with a non-zero exit status.
2883 * Otherwise, the value of var is substituted.
2884 * ${var-word} - use default value
2885 * If var is unset, word is substituted.
2886 * ${var=word} - assign and use default value
2887 * If var is unset, word is assigned to var.
2888 * In all cases, final value of var is substituted.
2889 * ${var+word} - use alternative value
2890 * If var is unset, null is substituted.
2891 * Otherwise, word is substituted.
2893 * Word is subjected to tilde expansion, parameter expansion,
2894 * command substitution, and arithmetic expansion.
2895 * If word is not needed, it is not expanded.
2897 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2898 * but also treat null var as if it is unset.
2900 int use_word = (!val || ((exp_save == ':') && !val[0]));
2902 use_word = !use_word;
2903 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2904 (exp_save == ':') ? "true" : "false", use_word);
2906 to_be_freed = expand_pseudo_dquoted(exp_word);
2908 exp_word = to_be_freed;
2909 if (exp_op == '?') {
2910 /* mimic bash message */
2911 die_if_script("%s: %s",
2913 exp_word[0] ? exp_word : "parameter null or not set"
2915 //TODO: how interactive bash aborts expansion mid-command?
2920 if (exp_op == '=') {
2921 /* ${var=[word]} or ${var:=[word]} */
2922 if (isdigit(var[0]) || var[0] == '#') {
2923 /* mimic bash message */
2924 die_if_script("$%s: cannot assign in this way", var);
2927 char *new_var = xasprintf("%s=%s", var, val);
2928 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2932 } /* one of "-=+?" */
2934 *exp_saveptr = exp_save;
2938 #if ENABLE_HUSH_TICK
2941 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2942 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2944 /* unquoted var's contents should be globbed, so don't escape */
2945 smallint sv = output->o_escape;
2946 output->o_escape = 0;
2947 n = expand_on_ifs(output, n, val);
2949 output->o_escape = sv;
2951 } else { /* quoted $VAR, val will be appended below */
2952 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2955 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2958 o_addQstr(output, val, strlen(val));
2961 /* Do the check to avoid writing to a const string */
2962 if (*p != SPECIAL_VAR_SYMBOL)
2963 *p = SPECIAL_VAR_SYMBOL;
2965 #if ENABLE_HUSH_TICK
2966 o_free(&subst_result);
2969 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2972 debug_print_list("expand_vars_to_list[a]", output, n);
2973 /* this part is literal, and it was already pre-quoted
2974 * if needed (much earlier), do not use o_addQstr here! */
2975 o_addstr_with_NUL(output, arg);
2976 debug_print_list("expand_vars_to_list[b]", output, n);
2977 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2978 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2981 /* allow to reuse list[n] later without re-growth */
2982 output->has_empty_slot = 1;
2984 o_addchr(output, '\0');
2989 static char **expand_variables(char **argv, int or_mask)
2994 o_string output = NULL_O_STRING;
2996 if (or_mask & 0x100) {
2997 output.o_escape = 1; /* protect against globbing for "$var" */
2998 /* (unquoted $var will temporarily switch it off) */
3005 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
3008 debug_print_list("expand_variables", &output, n);
3010 /* output.data (malloced in one block) gets returned in "list" */
3011 list = o_finalize_list(&output, n);
3012 debug_print_strings("expand_variables[1]", list);
3016 static char **expand_strvec_to_strvec(char **argv)
3018 return expand_variables(argv, 0x100);
3021 #if ENABLE_HUSH_BASH_COMPAT
3022 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3024 return expand_variables(argv, 0x80);
3028 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3029 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3034 o_string output = NULL_O_STRING;
3039 int is_var = is_well_formed_var_name(*v, '=');
3040 /* is_var * 0x80: singleword expansion for vars */
3041 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3043 /* Subtle! expand_vars_to_list did not glob last word yet.
3044 * It does this only when fed with further data.
3045 * Therefore we set globbing flags AFTER it, not before:
3048 /* if it is not recognizably abc=...; then: */
3049 output.o_escape = !is_var; /* protect against globbing for "$var" */
3050 /* (unquoted $var will temporarily switch it off) */
3051 output.o_glob = !is_var; /* and indeed do globbing */
3054 debug_print_list("expand_cond", &output, n);
3056 /* output.data (malloced in one block) gets returned in "list" */
3057 list = o_finalize_list(&output, n);
3058 debug_print_strings("expand_cond[1]", list);
3063 /* Used for expansion of right hand of assignments */
3064 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3066 static char *expand_string_to_string(const char *str)
3068 char *argv[2], **list;
3070 argv[0] = (char*)str;
3072 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
3074 if (!list[0] || list[1])
3075 bb_error_msg_and_die("BUG in varexp2");
3076 /* actually, just move string 2*sizeof(char*) bytes back */
3077 overlapping_strcpy((char*)list, list[0]);
3078 unbackslash((char*)list);
3079 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3083 /* Used for "eval" builtin */
3084 static char* expand_strvec_to_string(char **argv)
3088 list = expand_variables(argv, 0x80);
3089 /* Convert all NULs to spaces */
3094 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3095 bb_error_msg_and_die("BUG in varexp3");
3096 /* bash uses ' ' regardless of $IFS contents */
3101 overlapping_strcpy((char*)list, list[0]);
3102 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3106 static char **expand_assignments(char **argv, int count)
3111 G.expanded_assignments = p = NULL;
3112 /* Expand assignments into one string each */
3113 for (i = 0; i < count; i++) {
3114 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3116 G.expanded_assignments = NULL;
3123 void re_execute_shell(char ***to_free, const char *s,
3124 char *g_argv0, char **g_argv,
3125 char **builtin_argv) NORETURN;
3127 static void reset_traps_to_defaults(void)
3129 /* This function is always called in a child shell
3130 * after fork (not vfork, NOMMU doesn't use this function).
3135 /* Child shells are not interactive.
3136 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3137 * Testcase: (while :; do :; done) + ^Z should background.
3138 * Same goes for SIGTERM, SIGHUP, SIGINT.
3140 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3141 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3143 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3144 * Stupid. It can be done with *single* &= op, but we can't use
3145 * the fact that G.blocked_set is implemented as a bitmask
3147 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3151 /* Careful. Only if no trap or trap is not "" */
3152 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3153 sigdelset(&G.blocked_set, sig);
3160 /* Our homegrown sig mask is saner to work with :) */
3161 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3163 /* Resetting all traps to default except empty ones */
3164 mask = G.non_DFL_mask;
3165 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3166 if (!G.traps[sig] || !G.traps[sig][0])
3169 G.traps[sig] = NULL;
3170 /* There is no signal for 0 (EXIT) */
3173 /* There was a trap handler, we just removed it.
3174 * But if sig still has non-DFL handling,
3175 * we should not unblock the sig. */
3178 sigdelset(&G.blocked_set, sig);
3180 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3185 static void re_execute_shell(char ***to_free, const char *s,
3186 char *g_argv0, char **g_argv,
3187 char **builtin_argv) NORETURN;
3188 static void re_execute_shell(char ***to_free, const char *s,
3189 char *g_argv0, char **g_argv,
3190 char **builtin_argv)
3192 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3193 /* delims + 2 * (number of bytes in printed hex numbers) */
3194 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3195 char *heredoc_argv[4];
3196 struct variable *cur;
3197 # if ENABLE_HUSH_FUNCTIONS
3198 struct function *funcp;
3202 unsigned long long empty_trap_mask;
3204 if (!g_argv0) { /* heredoc */
3205 argv = heredoc_argv;
3206 argv[0] = (char *) G.argv0_for_re_execing;
3207 argv[1] = (char *) "-<";
3208 argv[2] = (char *) s;
3210 pp = &argv[3]; /* used as pointer to empty environment */
3216 if (pp) while (*pp++)
3219 empty_trap_mask = 0;
3222 for (sig = 1; sig < NSIG; sig++) {
3223 if (G.traps[sig] && !G.traps[sig][0])
3224 empty_trap_mask |= 1LL << sig;
3228 sprintf(param_buf, NOMMU_HACK_FMT
3229 , (unsigned) G.root_pid
3230 , (unsigned) G.root_ppid
3231 , (unsigned) G.last_bg_pid
3232 , (unsigned) G.last_exitcode
3235 IF_HUSH_LOOPS(, G.depth_of_loop)
3237 # undef NOMMU_HACK_FMT
3238 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3239 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3242 for (cur = G.top_var; cur; cur = cur->next) {
3243 if (!cur->flg_export || cur->flg_read_only)
3246 # if ENABLE_HUSH_FUNCTIONS
3247 for (funcp = G.top_func; funcp; funcp = funcp->next)
3253 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3254 *pp++ = (char *) G.argv0_for_re_execing;
3256 for (cur = G.top_var; cur; cur = cur->next) {
3257 if (cur->varstr == hush_version_str)
3259 if (cur->flg_read_only) {
3260 *pp++ = (char *) "-R";
3261 *pp++ = cur->varstr;
3262 } else if (!cur->flg_export) {
3263 *pp++ = (char *) "-V";
3264 *pp++ = cur->varstr;
3267 # if ENABLE_HUSH_FUNCTIONS
3268 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3269 *pp++ = (char *) "-F";
3270 *pp++ = funcp->name;
3271 *pp++ = funcp->body_as_string;
3274 /* We can pass activated traps here. Say, -Tnn:trap_string
3276 * However, POSIX says that subshells reset signals with traps
3278 * I tested bash-3.2 and it not only does that with true subshells
3279 * of the form ( list ), but with any forked children shells.
3280 * I set trap "echo W" WINCH; and then tried:
3282 * { echo 1; sleep 20; echo 2; } &
3283 * while true; do echo 1; sleep 20; echo 2; break; done &
3284 * true | { echo 1; sleep 20; echo 2; } | cat
3286 * In all these cases sending SIGWINCH to the child shell
3287 * did not run the trap. If I add trap "echo V" WINCH;
3288 * _inside_ group (just before echo 1), it works.
3290 * I conclude it means we don't need to pass active traps here.
3291 * Even if we would use signal handlers instead of signal masking
3292 * in order to implement trap handling,
3293 * exec syscall below resets signals to SIG_DFL for us.
3295 *pp++ = (char *) "-c";
3298 while (*++builtin_argv)
3299 *pp++ = *builtin_argv;
3300 *pp++ = (char *) "";
3305 /* *pp = NULL; - is already there */
3309 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3310 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3311 execve(bb_busybox_exec_path, argv, pp);
3312 /* Fallback. Useful for init=/bin/hush usage etc */
3313 if (argv[0][0] == '/')
3314 execve(argv[0], argv, pp);
3315 xfunc_error_retval = 127;
3316 bb_error_msg_and_die("can't re-execute the shell");
3318 #endif /* !BB_MMU */
3321 static void setup_heredoc(struct redir_struct *redir)
3323 struct fd_pair pair;
3326 /* the _body_ of heredoc (misleading field name) */
3327 const char *heredoc = redir->rd_filename;
3334 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3335 expanded = expand_pseudo_dquoted(heredoc);
3339 len = strlen(heredoc);
3341 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3343 xmove_fd(pair.rd, redir->rd_fd);
3345 /* Try writing without forking. Newer kernels have
3346 * dynamically growing pipes. Must use non-blocking write! */
3349 written = write(pair.wr, heredoc, len);
3360 ndelay_off(pair.wr);
3362 /* Okay, pipe buffer was not big enough */
3363 /* Note: we must not create a stray child (bastard? :)
3364 * for the unsuspecting parent process. Child creates a grandchild
3365 * and exits before parent execs the process which consumes heredoc
3366 * (that exec happens after we return from this function) */
3373 disable_restore_tty_pgrp_on_exit();
3374 pid = BB_MMU ? xfork() : xvfork();
3378 close(redir->rd_fd); /* read side of the pipe */
3380 full_write(pair.wr, heredoc, len); /* may loop or block */
3383 /* Delegate blocking writes to another process */
3384 xmove_fd(pair.wr, STDOUT_FILENO);
3385 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3389 #if ENABLE_HUSH_FAST
3391 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3393 enable_restore_tty_pgrp_on_exit();
3399 wait(NULL); /* wait till child has died */
3402 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3403 * and stderr if they are redirected. */
3404 static int setup_redirects(struct command *prog, int squirrel[])
3407 struct redir_struct *redir;
3409 for (redir = prog->redirects; redir; redir = redir->next) {
3410 if (redir->rd_type == REDIRECT_HEREDOC2) {
3411 /* rd_fd<<HERE case */
3412 if (squirrel && redir->rd_fd < 3
3413 && squirrel[redir->rd_fd] < 0
3415 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3417 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3419 debug_printf_parse("set heredoc '%s'\n",
3420 redir->rd_filename);
3421 setup_heredoc(redir);
3425 if (redir->rd_dup == REDIRFD_TO_FILE) {
3426 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3428 if (redir->rd_filename == NULL) {
3429 /* Something went wrong in the parse.
3430 * Pretend it didn't happen */
3431 bb_error_msg("bug in redirect parse");
3434 mode = redir_table[redir->rd_type].mode;
3435 p = expand_string_to_string(redir->rd_filename);
3436 openfd = open_or_warn(p, mode);
3439 /* this could get lost if stderr has been redirected, but
3440 * bash and ash both lose it as well (though zsh doesn't!) */
3441 //what the above comment tries to say?
3445 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3446 openfd = redir->rd_dup;
3449 if (openfd != redir->rd_fd) {
3450 if (squirrel && redir->rd_fd < 3
3451 && squirrel[redir->rd_fd] < 0
3453 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3455 if (openfd == REDIRFD_CLOSE) {
3456 /* "n>-" means "close me" */
3457 close(redir->rd_fd);
3459 xdup2(openfd, redir->rd_fd);
3460 if (redir->rd_dup == REDIRFD_TO_FILE)
3468 static void restore_redirects(int squirrel[])
3471 for (i = 0; i < 3; i++) {
3474 /* We simply die on error */
3481 static void free_pipe_list(struct pipe *head);
3483 /* Return code is the exit status of the pipe */
3484 static void free_pipe(struct pipe *pi)
3487 struct command *command;
3488 struct redir_struct *r, *rnext;
3491 if (pi->stopped_cmds > 0) /* why? */
3493 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3494 for (i = 0; i < pi->num_cmds; i++) {
3495 command = &pi->cmds[i];
3496 debug_printf_clean(" command %d:\n", i);
3497 if (command->argv) {
3498 for (a = 0, p = command->argv; *p; a++, p++) {
3499 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3501 free_strings(command->argv);
3502 command->argv = NULL;
3504 /* not "else if": on syntax error, we may have both! */
3505 if (command->group) {
3506 debug_printf_clean(" begin group (cmd_type:%d)\n",
3508 free_pipe_list(command->group);
3509 debug_printf_clean(" end group\n");
3510 command->group = NULL;
3512 /* else is crucial here.
3513 * If group != NULL, child_func is meaningless */
3514 #if ENABLE_HUSH_FUNCTIONS
3515 else if (command->child_func) {
3516 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3517 command->child_func->parent_cmd = NULL;
3521 free(command->group_as_string);
3522 command->group_as_string = NULL;
3524 for (r = command->redirects; r; r = rnext) {
3525 debug_printf_clean(" redirect %d%s",
3526 r->rd_fd, redir_table[r->rd_type].descrip);
3527 /* guard against the case >$FOO, where foo is unset or blank */
3528 if (r->rd_filename) {
3529 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3530 free(r->rd_filename);
3531 r->rd_filename = NULL;
3533 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3537 command->redirects = NULL;
3539 free(pi->cmds); /* children are an array, they get freed all at once */
3547 static void free_pipe_list(struct pipe *head)
3549 struct pipe *pi, *next;
3551 for (pi = head; pi; pi = next) {
3553 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3556 debug_printf_clean("pipe followup code %d\n", pi->followup);
3558 /*pi->next = NULL;*/
3564 static int run_list(struct pipe *pi);
3566 #define parse_stream(pstring, input, end_trigger) \
3567 parse_stream(input, end_trigger)
3569 static struct pipe *parse_stream(char **pstring,
3570 struct in_str *input,
3572 static void parse_and_run_string(const char *s);
3575 static char *find_in_path(const char *arg)
3578 const char *PATH = get_local_var_value("PATH");
3584 const char *end = strchrnul(PATH, ':');
3585 int sz = end - PATH; /* must be int! */
3589 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3591 /* We have xxx::yyyy in $PATH,
3592 * it means "use current dir" */
3595 if (access(ret, F_OK) == 0)
3608 static const struct built_in_command* find_builtin_helper(const char *name,
3609 const struct built_in_command *x,
3610 const struct built_in_command *end)
3613 if (strcmp(name, x->b_cmd) != 0) {
3617 debug_printf_exec("found builtin '%s'\n", name);
3622 static const struct built_in_command* find_builtin1(const char *name)
3624 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3626 static const struct built_in_command* find_builtin(const char *name)
3628 const struct built_in_command *x = find_builtin1(name);
3631 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3634 #if ENABLE_HUSH_FUNCTIONS
3635 static struct function **find_function_slot(const char *name)
3637 struct function **funcpp = &G.top_func;
3639 if (strcmp(name, (*funcpp)->name) == 0) {
3642 funcpp = &(*funcpp)->next;
3647 static const struct function *find_function(const char *name)
3649 const struct function *funcp = *find_function_slot(name);
3651 debug_printf_exec("found function '%s'\n", name);
3655 /* Note: takes ownership on name ptr */
3656 static struct function *new_function(char *name)
3658 struct function **funcpp = find_function_slot(name);
3659 struct function *funcp = *funcpp;
3661 if (funcp != NULL) {
3662 struct command *cmd = funcp->parent_cmd;
3663 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3665 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3667 /* Note: if !funcp->body, do not free body_as_string!
3668 * This is a special case of "-F name body" function:
3669 * body_as_string was not malloced! */
3671 free_pipe_list(funcp->body);
3673 free(funcp->body_as_string);
3677 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3678 cmd->argv[0] = funcp->name;
3679 cmd->group = funcp->body;
3681 cmd->group_as_string = funcp->body_as_string;
3685 debug_printf_exec("remembering new function '%s'\n", name);
3686 funcp = *funcpp = xzalloc(sizeof(*funcp));
3687 /*funcp->next = NULL;*/
3694 static void unset_func(const char *name)
3696 struct function **funcpp = find_function_slot(name);
3697 struct function *funcp = *funcpp;
3699 if (funcp != NULL) {
3700 debug_printf_exec("freeing function '%s'\n", funcp->name);
3701 *funcpp = funcp->next;
3702 /* funcp is unlinked now, deleting it.
3703 * Note: if !funcp->body, the function was created by
3704 * "-F name body", do not free ->body_as_string
3705 * and ->name as they were not malloced. */
3707 free_pipe_list(funcp->body);
3710 free(funcp->body_as_string);
3718 #define exec_function(to_free, funcp, argv) \
3719 exec_function(funcp, argv)
3721 static void exec_function(char ***to_free,
3722 const struct function *funcp,
3723 char **argv) NORETURN;
3724 static void exec_function(char ***to_free,
3725 const struct function *funcp,
3731 argv[0] = G.global_argv[0];
3732 G.global_argv = argv;
3736 /* On MMU, funcp->body is always non-NULL */
3737 n = run_list(funcp->body);
3741 re_execute_shell(to_free,
3742 funcp->body_as_string,
3749 static int run_function(const struct function *funcp, char **argv)
3755 save_and_replace_G_args(&sv, argv);
3757 /* "we are in function, ok to use return" */
3758 sv_flg = G.flag_return_in_progress;
3759 G.flag_return_in_progress = -1;
3760 # if ENABLE_HUSH_LOCAL
3761 G.func_nest_level++;
3764 /* On MMU, funcp->body is always non-NULL */
3767 /* Function defined by -F */
3768 parse_and_run_string(funcp->body_as_string);
3769 rc = G.last_exitcode;
3773 rc = run_list(funcp->body);
3776 # if ENABLE_HUSH_LOCAL
3778 struct variable *var;
3779 struct variable **var_pp;
3781 var_pp = &G.top_var;
3782 while ((var = *var_pp) != NULL) {
3783 if (var->func_nest_level < G.func_nest_level) {
3784 var_pp = &var->next;
3788 if (var->flg_export)
3789 bb_unsetenv(var->varstr);
3790 /* Remove from global list */
3791 *var_pp = var->next;
3797 G.func_nest_level--;
3800 G.flag_return_in_progress = sv_flg;
3802 restore_G_args(&sv, argv);
3806 #endif /* ENABLE_HUSH_FUNCTIONS */
3810 #define exec_builtin(to_free, x, argv) \
3811 exec_builtin(x, argv)
3813 #define exec_builtin(to_free, x, argv) \
3814 exec_builtin(to_free, argv)
3816 static void exec_builtin(char ***to_free,
3817 const struct built_in_command *x,
3818 char **argv) NORETURN;
3819 static void exec_builtin(char ***to_free,
3820 const struct built_in_command *x,
3824 int rcode = x->b_function(argv);
3828 /* On NOMMU, we must never block!
3829 * Example: { sleep 99 | read line; } & echo Ok
3831 re_execute_shell(to_free,
3840 static void execvp_or_die(char **argv) NORETURN;
3841 static void execvp_or_die(char **argv)
3843 debug_printf_exec("execing '%s'\n", argv[0]);
3844 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3845 execvp(argv[0], argv);
3846 bb_perror_msg("can't execute '%s'", argv[0]);
3847 _exit(127); /* bash compat */
3850 #if ENABLE_HUSH_MODE_X
3851 static void dump_cmd_in_x_mode(char **argv)
3853 if (G_x_mode && argv) {
3854 /* We want to output the line in one write op */
3862 len += strlen(argv[n++]) + 1;
3868 p += sprintf(p, " %s", argv[n++]);
3876 # define dump_cmd_in_x_mode(argv) ((void)0)
3880 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3881 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3882 #define pseudo_exec(nommu_save, command, argv_expanded) \
3883 pseudo_exec(command, argv_expanded)
3886 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3888 * Don't exit() here. If you don't exec, use _exit instead.
3889 * The at_exit handlers apparently confuse the calling process,
3890 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3891 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3892 char **argv, int assignment_cnt,
3893 char **argv_expanded) NORETURN;
3894 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3895 char **argv, int assignment_cnt,
3896 char **argv_expanded)
3900 new_env = expand_assignments(argv, assignment_cnt);
3901 dump_cmd_in_x_mode(new_env);
3903 if (!argv[assignment_cnt]) {
3904 /* Case when we are here: ... | var=val | ...
3905 * (note that we do not exit early, i.e., do not optimize out
3906 * expand_assignments(): think about ... | var=`sleep 1` | ...
3908 free_strings(new_env);
3909 _exit(EXIT_SUCCESS);
3913 set_vars_and_save_old(new_env);
3914 free(new_env); /* optional */
3915 /* we can also destroy set_vars_and_save_old's return value,
3918 nommu_save->new_env = new_env;
3919 nommu_save->old_vars = set_vars_and_save_old(new_env);
3922 if (argv_expanded) {
3923 argv = argv_expanded;
3925 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3927 nommu_save->argv = argv;
3930 dump_cmd_in_x_mode(argv);
3932 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3933 if (strchr(argv[0], '/') != NULL)
3937 /* Check if the command matches any of the builtins.
3938 * Depending on context, this might be redundant. But it's
3939 * easier to waste a few CPU cycles than it is to figure out
3940 * if this is one of those cases.
3943 /* On NOMMU, it is more expensive to re-execute shell
3944 * just in order to run echo or test builtin.
3945 * It's better to skip it here and run corresponding
3946 * non-builtin later. */
3947 const struct built_in_command *x;
3948 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3950 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3953 #if ENABLE_HUSH_FUNCTIONS
3954 /* Check if the command matches any functions */
3956 const struct function *funcp = find_function(argv[0]);
3958 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3963 #if ENABLE_FEATURE_SH_STANDALONE
3964 /* Check if the command matches any busybox applets */
3966 int a = find_applet_by_name(argv[0]);
3968 # if BB_MMU /* see above why on NOMMU it is not allowed */
3969 if (APPLET_IS_NOEXEC(a)) {
3970 debug_printf_exec("running applet '%s'\n", argv[0]);
3971 run_applet_no_and_exit(a, argv);
3974 /* Re-exec ourselves */
3975 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3976 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3977 execv(bb_busybox_exec_path, argv);
3978 /* If they called chroot or otherwise made the binary no longer
3979 * executable, fall through */
3984 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3987 execvp_or_die(argv);
3990 /* Called after [v]fork() in run_pipe
3992 static void pseudo_exec(nommu_save_t *nommu_save,
3993 struct command *command,
3994 char **argv_expanded) NORETURN;
3995 static void pseudo_exec(nommu_save_t *nommu_save,
3996 struct command *command,
3997 char **argv_expanded)
3999 if (command->argv) {
4000 pseudo_exec_argv(nommu_save, command->argv,
4001 command->assignment_cnt, argv_expanded);
4004 if (command->group) {
4005 /* Cases when we are here:
4008 * ... | ( list ) | ...
4009 * ... | { list } | ...
4013 debug_printf_exec("pseudo_exec: run_list\n");
4014 reset_traps_to_defaults();
4015 rcode = run_list(command->group);
4016 /* OK to leak memory by not calling free_pipe_list,
4017 * since this process is about to exit */
4020 re_execute_shell(&nommu_save->argv_from_re_execing,
4021 command->group_as_string,
4028 /* Case when we are here: ... | >file */
4029 debug_printf_exec("pseudo_exec'ed null command\n");
4030 _exit(EXIT_SUCCESS);
4034 static const char *get_cmdtext(struct pipe *pi)
4040 /* This is subtle. ->cmdtext is created only on first backgrounding.
4041 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4042 * On subsequent bg argv is trashed, but we won't use it */
4045 argv = pi->cmds[0].argv;
4046 if (!argv || !argv[0]) {
4047 pi->cmdtext = xzalloc(1);
4053 len += strlen(*argv) + 1;
4057 argv = pi->cmds[0].argv;
4059 len = strlen(*argv);
4060 memcpy(p, *argv, len);
4068 static void insert_bg_job(struct pipe *pi)
4070 struct pipe *job, **jobp;
4073 /* Linear search for the ID of the job to use */
4075 for (job = G.job_list; job; job = job->next)
4076 if (job->jobid >= pi->jobid)
4077 pi->jobid = job->jobid + 1;
4079 /* Add job to the list of running jobs */
4081 while ((job = *jobp) != NULL)
4083 job = *jobp = xmalloc(sizeof(*job));
4085 *job = *pi; /* physical copy */
4087 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4088 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4089 for (i = 0; i < pi->num_cmds; i++) {
4090 job->cmds[i].pid = pi->cmds[i].pid;
4091 /* all other fields are not used and stay zero */
4093 job->cmdtext = xstrdup(get_cmdtext(pi));
4095 if (G_interactive_fd)
4096 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4097 /* Last command's pid goes to $! */
4098 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
4099 G.last_jobid = job->jobid;
4102 static void remove_bg_job(struct pipe *pi)
4104 struct pipe *prev_pipe;
4106 if (pi == G.job_list) {
4107 G.job_list = pi->next;
4109 prev_pipe = G.job_list;
4110 while (prev_pipe->next != pi)
4111 prev_pipe = prev_pipe->next;
4112 prev_pipe->next = pi->next;
4115 G.last_jobid = G.job_list->jobid;
4120 /* Remove a backgrounded job */
4121 static void delete_finished_bg_job(struct pipe *pi)
4124 pi->stopped_cmds = 0;
4130 /* Check to see if any processes have exited -- if they
4131 * have, figure out why and see if a job has completed */
4132 static int checkjobs(struct pipe* fg_pipe)
4142 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4144 attributes = WUNTRACED;
4145 if (fg_pipe == NULL)
4146 attributes |= WNOHANG;
4149 #if ENABLE_HUSH_FAST
4150 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4151 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4152 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4153 /* There was neither fork nor SIGCHLD since last waitpid */
4154 /* Avoid doing waitpid syscall if possible */
4155 if (!G.we_have_children) {
4159 if (fg_pipe == NULL) { /* is WNOHANG set? */
4160 /* We have children, but they did not exit
4161 * or stop yet (we saw no SIGCHLD) */
4164 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4168 /* Do we do this right?
4169 * bash-3.00# sleep 20 | false
4171 * [3]+ Stopped sleep 20 | false
4172 * bash-3.00# echo $?
4173 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4174 * [hush 1.14.0: yes we do it right]
4181 #if ENABLE_HUSH_FAST
4182 i = G.count_SIGCHLD;
4184 childpid = waitpid(-1, &status, attributes);
4185 if (childpid <= 0) {
4186 if (childpid && errno != ECHILD)
4187 bb_perror_msg("waitpid");
4188 #if ENABLE_HUSH_FAST
4189 else { /* Until next SIGCHLD, waitpid's are useless */
4190 G.we_have_children = (childpid == 0);
4191 G.handled_SIGCHLD = i;
4192 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4197 dead = WIFEXITED(status) || WIFSIGNALED(status);
4200 if (WIFSTOPPED(status))
4201 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4202 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4203 if (WIFSIGNALED(status))
4204 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4205 childpid, WTERMSIG(status), WEXITSTATUS(status));
4206 if (WIFEXITED(status))
4207 debug_printf_jobs("pid %d exited, exitcode %d\n",
4208 childpid, WEXITSTATUS(status));
4210 /* Were we asked to wait for fg pipe? */
4212 for (i = 0; i < fg_pipe->num_cmds; i++) {
4213 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4214 if (fg_pipe->cmds[i].pid != childpid)
4217 fg_pipe->cmds[i].pid = 0;
4218 fg_pipe->alive_cmds--;
4219 if (i == fg_pipe->num_cmds - 1) {
4220 /* last process gives overall exitstatus */
4221 rcode = WEXITSTATUS(status);
4222 /* bash prints killer signal's name for *last*
4223 * process in pipe (prints just newline for SIGINT).
4224 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4226 if (WIFSIGNALED(status)) {
4227 int sig = WTERMSIG(status);
4228 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4229 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4230 * Maybe we need to use sig | 128? */
4233 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4236 fg_pipe->cmds[i].is_stopped = 1;
4237 fg_pipe->stopped_cmds++;
4239 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4240 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4241 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4242 /* All processes in fg pipe have exited or stopped */
4243 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4244 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4245 * and "killall -STOP cat" */
4246 if (G_interactive_fd) {
4248 if (fg_pipe->alive_cmds)
4249 insert_bg_job(fg_pipe);
4253 if (!fg_pipe->alive_cmds)
4256 /* There are still running processes in the fg pipe */
4257 goto wait_more; /* do waitpid again */
4259 /* it wasnt fg_pipe, look for process in bg pipes */
4263 /* We asked to wait for bg or orphaned children */
4264 /* No need to remember exitcode in this case */
4265 for (pi = G.job_list; pi; pi = pi->next) {
4266 for (i = 0; i < pi->num_cmds; i++) {
4267 if (pi->cmds[i].pid == childpid)
4268 goto found_pi_and_prognum;
4271 /* Happens when shell is used as init process (init=/bin/sh) */
4272 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4273 continue; /* do waitpid again */
4275 found_pi_and_prognum:
4278 pi->cmds[i].pid = 0;
4280 if (!pi->alive_cmds) {
4281 if (G_interactive_fd)
4282 printf(JOB_STATUS_FORMAT, pi->jobid,
4283 "Done", pi->cmdtext);
4284 delete_finished_bg_job(pi);
4288 pi->cmds[i].is_stopped = 1;
4292 } /* while (waitpid succeeds)... */
4298 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4301 int rcode = checkjobs(fg_pipe);
4302 if (G_saved_tty_pgrp) {
4303 /* Job finished, move the shell to the foreground */
4304 p = getpgrp(); /* our process group id */
4305 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4306 tcsetpgrp(G_interactive_fd, p);
4312 /* Start all the jobs, but don't wait for anything to finish.
4315 * Return code is normally -1, when the caller has to wait for children
4316 * to finish to determine the exit status of the pipe. If the pipe
4317 * is a simple builtin command, however, the action is done by the
4318 * time run_pipe returns, and the exit code is provided as the
4321 * Returns -1 only if started some children. IOW: we have to
4322 * mask out retvals of builtins etc with 0xff!
4324 * The only case when we do not need to [v]fork is when the pipe
4325 * is single, non-backgrounded, non-subshell command. Examples:
4326 * cmd ; ... { list } ; ...
4327 * cmd && ... { list } && ...
4328 * cmd || ... { list } || ...
4329 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4330 * or (if SH_STANDALONE) an applet, and we can run the { list }
4331 * with run_list. If it isn't one of these, we fork and exec cmd.
4333 * Cases when we must fork:
4334 * non-single: cmd | cmd
4335 * backgrounded: cmd & { list } &
4336 * subshell: ( list ) [&]
4338 #if !ENABLE_HUSH_MODE_X
4339 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4340 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4342 static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4344 /* setup_redirects acts on file descriptors, not FILEs.
4345 * This is perfect for work that comes after exec().
4346 * Is it really safe for inline use? Experimentally,
4347 * things seem to work. */
4348 int rcode = setup_redirects(command, squirrel);
4350 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4351 *new_env_p = new_env;
4352 dump_cmd_in_x_mode(new_env);
4353 dump_cmd_in_x_mode(argv_expanded);
4355 *old_vars_p = set_vars_and_save_old(new_env);
4359 static NOINLINE int run_pipe(struct pipe *pi)
4361 static const char *const null_ptr = NULL;
4365 struct command *command;
4366 char **argv_expanded;
4368 /* it is not always needed, but we aim to smaller code */
4369 int squirrel[] = { -1, -1, -1 };
4372 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4375 IF_HUSH_JOB(pi->pgrp = -1;)
4376 pi->stopped_cmds = 0;
4377 command = &pi->cmds[0];
4378 argv_expanded = NULL;
4380 if (pi->num_cmds != 1
4381 || pi->followup == PIPE_BG
4382 || command->cmd_type == CMD_SUBSHELL
4389 debug_printf_exec(": group:%p argv:'%s'\n",
4390 command->group, command->argv ? command->argv[0] : "NONE");
4392 if (command->group) {
4393 #if ENABLE_HUSH_FUNCTIONS
4394 if (command->cmd_type == CMD_FUNCDEF) {
4395 /* "executing" func () { list } */
4396 struct function *funcp;
4398 funcp = new_function(command->argv[0]);
4399 /* funcp->name is already set to argv[0] */
4400 funcp->body = command->group;
4402 funcp->body_as_string = command->group_as_string;
4403 command->group_as_string = NULL;
4405 command->group = NULL;
4406 command->argv[0] = NULL;
4407 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4408 funcp->parent_cmd = command;
4409 command->child_func = funcp;
4411 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4413 return EXIT_SUCCESS;
4417 debug_printf("non-subshell group\n");
4418 rcode = 1; /* exitcode if redir failed */
4419 if (setup_redirects(command, squirrel) == 0) {
4420 debug_printf_exec(": run_list\n");
4421 rcode = run_list(command->group) & 0xff;
4423 restore_redirects(squirrel);
4424 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4426 debug_printf_exec("run_pipe: return %d\n", rcode);
4430 argv = command->argv ? command->argv : (char **) &null_ptr;
4432 const struct built_in_command *x;
4433 #if ENABLE_HUSH_FUNCTIONS
4434 const struct function *funcp;
4438 char **new_env = NULL;
4439 struct variable *old_vars = NULL;
4441 if (argv[command->assignment_cnt] == NULL) {
4442 /* Assignments, but no command */
4443 /* Ensure redirects take effect (that is, create files).
4444 * Try "a=t >file" */
4445 #if 0 /* A few cases in testsuite fail with this code. FIXME */
4446 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4447 /* Set shell variables */
4451 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4452 /* Do we need to flag set_local_var() errors?
4453 * "assignment to readonly var" and "putenv error"
4458 /* Redirect error sets $? to 1. Otherwise,
4459 * if evaluating assignment value set $?, retain it.
4460 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4462 rcode = G.last_exitcode;
4463 /* Exit, _skipping_ variable restoring code: */
4464 goto clean_up_and_ret0;
4466 #else /* Older, bigger, but more correct code */
4468 rcode = setup_redirects(command, squirrel);
4469 restore_redirects(squirrel);
4470 /* Set shell variables */
4472 bb_putchar_stderr('+');
4474 char *p = expand_string_to_string(*argv);
4476 fprintf(stderr, " %s", p);
4477 debug_printf_exec("set shell var:'%s'->'%s'\n",
4479 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4480 /* Do we need to flag set_local_var() errors?
4481 * "assignment to readonly var" and "putenv error"
4486 bb_putchar_stderr('\n');
4487 /* Redirect error sets $? to 1. Otherwise,
4488 * if evaluating assignment value set $?, retain it.
4489 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4491 rcode = G.last_exitcode;
4492 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4494 debug_printf_exec("run_pipe: return %d\n", rcode);
4499 /* Expand the rest into (possibly) many strings each */
4501 #if ENABLE_HUSH_BASH_COMPAT
4502 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4503 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4506 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4507 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4508 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4513 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4516 /* if someone gives us an empty string: `cmd with empty output` */
4517 if (!argv_expanded[0]) {
4518 free(argv_expanded);
4520 return G.last_exitcode;
4523 x = find_builtin(argv_expanded[0]);
4524 #if ENABLE_HUSH_FUNCTIONS
4527 funcp = find_function(argv_expanded[0]);
4531 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4532 debug_printf("exec with redirects only\n");
4533 rcode = setup_redirects(command, NULL);
4534 goto clean_up_and_ret1;
4537 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4540 debug_printf_exec(": builtin '%s' '%s'...\n",
4541 x->b_cmd, argv_expanded[1]);
4542 rcode = x->b_function(argv_expanded) & 0xff;
4545 #if ENABLE_HUSH_FUNCTIONS
4547 # if ENABLE_HUSH_LOCAL
4548 struct variable **sv;
4549 sv = G.shadowed_vars_pp;
4550 G.shadowed_vars_pp = &old_vars;
4552 debug_printf_exec(": function '%s' '%s'...\n",
4553 funcp->name, argv_expanded[1]);
4554 rcode = run_function(funcp, argv_expanded) & 0xff;
4555 # if ENABLE_HUSH_LOCAL
4556 G.shadowed_vars_pp = sv;
4562 unset_vars(new_env);
4564 /* clean_up_and_ret0: */
4565 restore_redirects(squirrel);
4567 free(argv_expanded);
4568 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4570 debug_printf_exec("run_pipe return %d\n", rcode);
4574 if (ENABLE_FEATURE_SH_STANDALONE) {
4575 int n = find_applet_by_name(argv_expanded[0]);
4576 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4577 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4579 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4580 argv_expanded[0], argv_expanded[1]);
4581 rcode = run_nofork_applet(n, argv_expanded);
4583 goto clean_up_and_ret;
4586 /* It is neither builtin nor applet. We must fork. */
4590 /* NB: argv_expanded may already be created, and that
4591 * might include `cmd` runs! Do not rerun it! We *must*
4592 * use argv_expanded if it's non-NULL */
4594 /* Going to fork a child per each pipe member */
4599 while (cmd_no < pi->num_cmds) {
4600 struct fd_pair pipefds;
4602 volatile nommu_save_t nommu_save;
4603 nommu_save.new_env = NULL;
4604 nommu_save.old_vars = NULL;
4605 nommu_save.argv = NULL;
4606 nommu_save.argv_from_re_execing = NULL;
4608 command = &pi->cmds[cmd_no];
4610 if (command->argv) {
4611 debug_printf_exec(": pipe member '%s' '%s'...\n",
4612 command->argv[0], command->argv[1]);
4614 debug_printf_exec(": pipe member with no argv\n");
4617 /* pipes are inserted between pairs of commands */
4620 if (cmd_no < pi->num_cmds)
4621 xpiped_pair(pipefds);
4623 command->pid = BB_MMU ? fork() : vfork();
4624 if (!command->pid) { /* child */
4626 disable_restore_tty_pgrp_on_exit();
4627 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4629 /* Every child adds itself to new process group
4630 * with pgid == pid_of_first_child_in_pipe */
4631 if (G.run_list_level == 1 && G_interactive_fd) {
4634 if (pgrp < 0) /* true for 1st process only */
4636 if (setpgid(0, pgrp) == 0
4637 && pi->followup != PIPE_BG
4638 && G_saved_tty_pgrp /* we have ctty */
4640 /* We do it in *every* child, not just first,
4642 tcsetpgrp(G_interactive_fd, pgrp);
4646 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4647 /* 1st cmd in backgrounded pipe
4648 * should have its stdin /dev/null'ed */
4650 if (open(bb_dev_null, O_RDONLY))
4651 xopen("/", O_RDONLY);
4653 xmove_fd(next_infd, 0);
4655 xmove_fd(pipefds.wr, 1);
4658 /* Like bash, explicit redirects override pipes,
4659 * and the pipe fd is available for dup'ing. */
4660 if (setup_redirects(command, NULL))
4663 /* Restore default handlers just prior to exec */
4664 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4666 /* Stores to nommu_save list of env vars putenv'ed
4667 * (NOMMU, on MMU we don't need that) */
4668 /* cast away volatility... */
4669 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4670 /* pseudo_exec() does not return */
4673 /* parent or error */
4674 #if ENABLE_HUSH_FAST
4676 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4678 enable_restore_tty_pgrp_on_exit();
4680 /* Clean up after vforked child */
4681 free(nommu_save.argv);
4682 free(nommu_save.argv_from_re_execing);
4683 unset_vars(nommu_save.new_env);
4684 add_vars(nommu_save.old_vars);
4686 free(argv_expanded);
4687 argv_expanded = NULL;
4688 if (command->pid < 0) { /* [v]fork failed */
4689 /* Clearly indicate, was it fork or vfork */
4690 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4694 /* Second and next children need to know pid of first one */
4696 pi->pgrp = command->pid;
4702 if (cmd_no < pi->num_cmds)
4704 /* Pass read (output) pipe end to next iteration */
4705 next_infd = pipefds.rd;
4708 if (!pi->alive_cmds) {
4710 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4715 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4719 #ifndef debug_print_tree
4720 static void debug_print_tree(struct pipe *pi, int lvl)
4722 static const char *const PIPE[] = {
4728 static const char *RES[] = {
4729 [RES_NONE ] = "NONE" ,
4732 [RES_THEN ] = "THEN" ,
4733 [RES_ELIF ] = "ELIF" ,
4734 [RES_ELSE ] = "ELSE" ,
4737 # if ENABLE_HUSH_LOOPS
4738 [RES_FOR ] = "FOR" ,
4739 [RES_WHILE] = "WHILE",
4740 [RES_UNTIL] = "UNTIL",
4742 [RES_DONE ] = "DONE" ,
4744 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4747 # if ENABLE_HUSH_CASE
4748 [RES_CASE ] = "CASE" ,
4749 [RES_CASE_IN ] = "CASE_IN" ,
4750 [RES_MATCH] = "MATCH",
4751 [RES_CASE_BODY] = "CASE_BODY",
4752 [RES_ESAC ] = "ESAC" ,
4754 [RES_XXXX ] = "XXXX" ,
4755 [RES_SNTX ] = "SNTX" ,
4757 static const char *const CMDTYPE[] = {
4761 # if ENABLE_HUSH_FUNCTIONS
4770 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4771 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4773 while (prn < pi->num_cmds) {
4774 struct command *command = &pi->cmds[prn];
4775 char **argv = command->argv;
4777 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4779 command->assignment_cnt);
4780 if (command->group) {
4781 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4782 CMDTYPE[command->cmd_type],
4785 , " group_as_string:", command->group_as_string
4790 debug_print_tree(command->group, lvl+1);
4794 if (argv) while (*argv) {
4795 fprintf(stderr, " '%s'", *argv);
4798 fprintf(stderr, "\n");
4805 #endif /* debug_print_tree */
4807 /* NB: called by pseudo_exec, and therefore must not modify any
4808 * global data until exec/_exit (we can be a child after vfork!) */
4809 static int run_list(struct pipe *pi)
4811 #if ENABLE_HUSH_CASE
4812 char *case_word = NULL;
4814 #if ENABLE_HUSH_LOOPS
4815 struct pipe *loop_top = NULL;
4816 char **for_lcur = NULL;
4817 char **for_list = NULL;
4819 smallint last_followup;
4821 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4822 smalluint cond_code = 0;
4824 enum { cond_code = 0 };
4827 smallint rword; /* enum reserved_style */
4828 smallint last_rword; /* ditto */
4831 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4834 #if ENABLE_HUSH_LOOPS
4835 /* Check syntax for "for" */
4836 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4837 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4839 /* current word is FOR or IN (BOLD in comments below) */
4840 if (cpipe->next == NULL) {
4841 syntax_error("malformed for");
4843 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4846 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4847 if (cpipe->next->res_word == RES_DO)
4849 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4850 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4851 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4853 syntax_error("malformed for");
4855 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4861 /* Past this point, all code paths should jump to ret: label
4862 * in order to return, no direct "return" statements please.
4863 * This helps to ensure that no memory is leaked. */
4871 last_rword = RES_XXXX;
4873 last_followup = PIPE_SEQ;
4874 rcode = G.last_exitcode;
4876 /* Go through list of pipes, (maybe) executing them. */
4877 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4881 IF_HAS_KEYWORDS(rword = pi->res_word;)
4882 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4883 rword, cond_code, last_rword);
4884 #if ENABLE_HUSH_LOOPS
4885 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4886 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4888 /* start of a loop: remember where loop starts */
4893 /* Still in the same "if...", "then..." or "do..." branch? */
4894 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4895 if ((rcode == 0 && last_followup == PIPE_OR)
4896 || (rcode != 0 && last_followup == PIPE_AND)
4898 /* It is "<true> || CMD" or "<false> && CMD"
4899 * and we should not execute CMD */
4900 debug_printf_exec("skipped cmd because of || or &&\n");
4901 last_followup = pi->followup;
4905 last_followup = pi->followup;
4906 IF_HAS_KEYWORDS(last_rword = rword;)
4909 if (rword == RES_THEN) {
4910 /* if false; then ... fi has exitcode 0! */
4911 G.last_exitcode = rcode = EXIT_SUCCESS;
4912 /* "if <false> THEN cmd": skip cmd */
4916 if (rword == RES_ELSE || rword == RES_ELIF) {
4917 /* "if <true> then ... ELSE/ELIF cmd":
4918 * skip cmd and all following ones */
4923 #if ENABLE_HUSH_LOOPS
4924 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4926 /* first loop through for */
4928 static const char encoded_dollar_at[] ALIGN1 = {
4929 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4930 }; /* encoded representation of "$@" */
4931 static const char *const encoded_dollar_at_argv[] = {
4932 encoded_dollar_at, NULL
4933 }; /* argv list with one element: "$@" */
4936 vals = (char**)encoded_dollar_at_argv;
4937 if (pi->next->res_word == RES_IN) {
4938 /* if no variable values after "in" we skip "for" */
4939 if (!pi->next->cmds[0].argv) {
4940 G.last_exitcode = rcode = EXIT_SUCCESS;
4941 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4944 vals = pi->next->cmds[0].argv;
4945 } /* else: "for var; do..." -> assume "$@" list */
4946 /* create list of variable values */
4947 debug_print_strings("for_list made from", vals);
4948 for_list = expand_strvec_to_strvec(vals);
4949 for_lcur = for_list;
4950 debug_print_strings("for_list", for_list);
4953 /* "for" loop is over, clean up */
4959 /* Insert next value from for_lcur */
4960 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4961 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4964 if (rword == RES_IN) {
4965 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4967 if (rword == RES_DONE) {
4968 continue; /* "done" has no cmds too */
4971 #if ENABLE_HUSH_CASE
4972 if (rword == RES_CASE) {
4973 case_word = expand_strvec_to_string(pi->cmds->argv);
4976 if (rword == RES_MATCH) {
4979 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4981 /* all prev words didn't match, does this one match? */
4982 argv = pi->cmds->argv;
4984 char *pattern = expand_string_to_string(*argv);
4985 /* TODO: which FNM_xxx flags to use? */
4986 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4988 if (cond_code == 0) { /* match! we will execute this branch */
4989 free(case_word); /* make future "word)" stop */
4997 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4999 continue; /* not matched yet, skip this pipe */
5002 /* Just pressing <enter> in shell should check for jobs.
5003 * OTOH, in non-interactive shell this is useless
5004 * and only leads to extra job checks */
5005 if (pi->num_cmds == 0) {
5006 if (G_interactive_fd)
5007 goto check_jobs_and_continue;
5011 /* After analyzing all keywords and conditions, we decided
5012 * to execute this pipe. NB: have to do checkjobs(NULL)
5013 * after run_pipe to collect any background children,
5014 * even if list execution is to be stopped. */
5015 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
5018 #if ENABLE_HUSH_LOOPS
5019 G.flag_break_continue = 0;
5021 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5023 /* We ran a builtin, function, or group.
5024 * rcode is already known
5025 * and we don't need to wait for anything. */
5026 G.last_exitcode = rcode;
5027 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
5028 check_and_run_traps(0);
5029 #if ENABLE_HUSH_LOOPS
5030 /* Was it "break" or "continue"? */
5031 if (G.flag_break_continue) {
5032 smallint fbc = G.flag_break_continue;
5033 /* We might fall into outer *loop*,
5034 * don't want to break it too */
5036 G.depth_break_continue--;
5037 if (G.depth_break_continue == 0)
5038 G.flag_break_continue = 0;
5039 /* else: e.g. "continue 2" should *break* once, *then* continue */
5040 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
5041 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
5042 goto check_jobs_and_break;
5043 /* "continue": simulate end of loop */
5048 #if ENABLE_HUSH_FUNCTIONS
5049 if (G.flag_return_in_progress == 1) {
5050 /* same as "goto check_jobs_and_break" */
5055 } else if (pi->followup == PIPE_BG) {
5056 /* What does bash do with attempts to background builtins? */
5057 /* even bash 3.2 doesn't do that well with nested bg:
5058 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5059 * I'm NOT treating inner &'s as jobs */
5060 check_and_run_traps(0);
5062 if (G.run_list_level == 1)
5065 G.last_exitcode = rcode = EXIT_SUCCESS;
5066 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5069 if (G.run_list_level == 1 && G_interactive_fd) {
5070 /* Waits for completion, then fg's main shell */
5071 rcode = checkjobs_and_fg_shell(pi);
5072 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5073 check_and_run_traps(0);
5076 { /* This one just waits for completion */
5077 rcode = checkjobs(pi);
5078 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5079 check_and_run_traps(0);
5081 G.last_exitcode = rcode;
5085 /* Analyze how result affects subsequent commands */
5087 if (rword == RES_IF || rword == RES_ELIF)
5090 #if ENABLE_HUSH_LOOPS
5091 /* Beware of "while false; true; do ..."! */
5092 if (pi->next && pi->next->res_word == RES_DO) {
5093 if (rword == RES_WHILE) {
5095 /* "while false; do...done" - exitcode 0 */
5096 G.last_exitcode = rcode = EXIT_SUCCESS;
5097 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5098 goto check_jobs_and_break;
5101 if (rword == RES_UNTIL) {
5103 debug_printf_exec(": until expr is true: breaking\n");
5104 check_jobs_and_break:
5112 check_jobs_and_continue:
5119 #if ENABLE_HUSH_LOOPS
5124 #if ENABLE_HUSH_CASE
5128 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5132 /* Select which version we will use */
5133 static int run_and_free_list(struct pipe *pi)
5136 debug_printf_exec("run_and_free_list entered\n");
5138 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5139 rcode = run_list(pi);
5141 /* free_pipe_list has the side effect of clearing memory.
5142 * In the long run that function can be merged with run_list,
5143 * but doing that now would hobble the debugging effort. */
5145 debug_printf_exec("run_and_free_list return %d\n", rcode);
5150 static struct pipe *new_pipe(void)
5153 pi = xzalloc(sizeof(struct pipe));
5154 /*pi->followup = 0; - deliberately invalid value */
5155 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5159 /* Command (member of a pipe) is complete, or we start a new pipe
5160 * if ctx->command is NULL.
5161 * No errors possible here.
5163 static int done_command(struct parse_context *ctx)
5165 /* The command is really already in the pipe structure, so
5166 * advance the pipe counter and make a new, null command. */
5167 struct pipe *pi = ctx->pipe;
5168 struct command *command = ctx->command;
5171 if (IS_NULL_CMD(command)) {
5172 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5176 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5177 //debug_print_tree(ctx->list_head, 20);
5179 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5182 /* Only real trickiness here is that the uncommitted
5183 * command structure is not counted in pi->num_cmds. */
5184 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5185 ctx->command = command = &pi->cmds[pi->num_cmds];
5187 memset(command, 0, sizeof(*command));
5188 return pi->num_cmds; /* used only for 0/nonzero check */
5191 static void done_pipe(struct parse_context *ctx, pipe_style type)
5195 debug_printf_parse("done_pipe entered, followup %d\n", type);
5196 /* Close previous command */
5197 not_null = done_command(ctx);
5198 ctx->pipe->followup = type;
5200 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5201 ctx->ctx_inverted = 0;
5202 ctx->pipe->res_word = ctx->ctx_res_w;
5205 /* Without this check, even just <enter> on command line generates
5206 * tree of three NOPs (!). Which is harmless but annoying.
5207 * IOW: it is safe to do it unconditionally. */
5210 || ctx->ctx_res_w == RES_FI
5212 #if ENABLE_HUSH_LOOPS
5213 || ctx->ctx_res_w == RES_DONE
5214 || ctx->ctx_res_w == RES_FOR
5215 || ctx->ctx_res_w == RES_IN
5217 #if ENABLE_HUSH_CASE
5218 || ctx->ctx_res_w == RES_ESAC
5222 debug_printf_parse("done_pipe: adding new pipe: "
5223 "not_null:%d ctx->ctx_res_w:%d\n",
5224 not_null, ctx->ctx_res_w);
5226 ctx->pipe->next = new_p;
5228 /* RES_THEN, RES_DO etc are "sticky" -
5229 * they remain set for pipes inside if/while.
5230 * This is used to control execution.
5231 * RES_FOR and RES_IN are NOT sticky (needed to support
5232 * cases where variable or value happens to match a keyword):
5234 #if ENABLE_HUSH_LOOPS
5235 if (ctx->ctx_res_w == RES_FOR
5236 || ctx->ctx_res_w == RES_IN)
5237 ctx->ctx_res_w = RES_NONE;
5239 #if ENABLE_HUSH_CASE
5240 if (ctx->ctx_res_w == RES_MATCH)
5241 ctx->ctx_res_w = RES_CASE_BODY;
5242 if (ctx->ctx_res_w == RES_CASE)
5243 ctx->ctx_res_w = RES_CASE_IN;
5245 ctx->command = NULL; /* trick done_command below */
5246 /* Create the memory for command, roughly:
5247 * ctx->pipe->cmds = new struct command;
5248 * ctx->command = &ctx->pipe->cmds[0];
5251 //debug_print_tree(ctx->list_head, 10);
5253 debug_printf_parse("done_pipe return\n");
5256 static void initialize_context(struct parse_context *ctx)
5258 memset(ctx, 0, sizeof(*ctx));
5259 ctx->pipe = ctx->list_head = new_pipe();
5260 /* Create the memory for command, roughly:
5261 * ctx->pipe->cmds = new struct command;
5262 * ctx->command = &ctx->pipe->cmds[0];
5267 /* If a reserved word is found and processed, parse context is modified
5268 * and 1 is returned.
5271 struct reserved_combo {
5274 unsigned char assignment_flag;
5278 FLAG_END = (1 << RES_NONE ),
5280 FLAG_IF = (1 << RES_IF ),
5281 FLAG_THEN = (1 << RES_THEN ),
5282 FLAG_ELIF = (1 << RES_ELIF ),
5283 FLAG_ELSE = (1 << RES_ELSE ),
5284 FLAG_FI = (1 << RES_FI ),
5286 # if ENABLE_HUSH_LOOPS
5287 FLAG_FOR = (1 << RES_FOR ),
5288 FLAG_WHILE = (1 << RES_WHILE),
5289 FLAG_UNTIL = (1 << RES_UNTIL),
5290 FLAG_DO = (1 << RES_DO ),
5291 FLAG_DONE = (1 << RES_DONE ),
5292 FLAG_IN = (1 << RES_IN ),
5294 # if ENABLE_HUSH_CASE
5295 FLAG_MATCH = (1 << RES_MATCH),
5296 FLAG_ESAC = (1 << RES_ESAC ),
5298 FLAG_START = (1 << RES_XXXX ),
5301 static const struct reserved_combo* match_reserved_word(o_string *word)
5303 /* Mostly a list of accepted follow-up reserved words.
5304 * FLAG_END means we are done with the sequence, and are ready
5305 * to turn the compound list into a command.
5306 * FLAG_START means the word must start a new compound list.
5308 static const struct reserved_combo reserved_list[] = {
5310 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5311 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5312 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5313 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5314 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5315 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5317 # if ENABLE_HUSH_LOOPS
5318 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5319 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5320 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5321 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5322 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5323 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5325 # if ENABLE_HUSH_CASE
5326 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5327 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5330 const struct reserved_combo *r;
5332 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5333 if (strcmp(word->data, r->literal) == 0)
5338 /* Return 0: not a keyword, 1: keyword
5340 static int reserved_word(o_string *word, struct parse_context *ctx)
5342 # if ENABLE_HUSH_CASE
5343 static const struct reserved_combo reserved_match = {
5344 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5347 const struct reserved_combo *r;
5351 r = match_reserved_word(word);
5355 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5356 # if ENABLE_HUSH_CASE
5357 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5358 /* "case word IN ..." - IN part starts first MATCH part */
5359 r = &reserved_match;
5362 if (r->flag == 0) { /* '!' */
5363 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5364 syntax_error("! ! command");
5365 ctx->ctx_res_w = RES_SNTX;
5367 ctx->ctx_inverted = 1;
5370 if (r->flag & FLAG_START) {
5371 struct parse_context *old;
5373 old = xmalloc(sizeof(*old));
5374 debug_printf_parse("push stack %p\n", old);
5375 *old = *ctx; /* physical copy */
5376 initialize_context(ctx);
5378 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5379 syntax_error_at(word->data);
5380 ctx->ctx_res_w = RES_SNTX;
5383 /* "{...} fi" is ok. "{...} if" is not
5385 * if { echo foo; } then { echo bar; } fi */
5386 if (ctx->command->group)
5387 done_pipe(ctx, PIPE_SEQ);
5390 ctx->ctx_res_w = r->res;
5391 ctx->old_flag = r->flag;
5392 word->o_assignment = r->assignment_flag;
5394 if (ctx->old_flag & FLAG_END) {
5395 struct parse_context *old;
5397 done_pipe(ctx, PIPE_SEQ);
5398 debug_printf_parse("pop stack %p\n", ctx->stack);
5400 old->command->group = ctx->list_head;
5401 old->command->cmd_type = CMD_NORMAL;
5403 o_addstr(&old->as_string, ctx->as_string.data);
5404 o_free_unsafe(&ctx->as_string);
5405 old->command->group_as_string = xstrdup(old->as_string.data);
5406 debug_printf_parse("pop, remembering as:'%s'\n",
5407 old->command->group_as_string);
5409 *ctx = *old; /* physical copy */
5414 #endif /* HAS_KEYWORDS */
5416 /* Word is complete, look at it and update parsing context.
5417 * Normal return is 0. Syntax errors return 1.
5418 * Note: on return, word is reset, but not o_free'd!
5420 static int done_word(o_string *word, struct parse_context *ctx)
5422 struct command *command = ctx->command;
5424 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5425 if (word->length == 0 && word->o_quoted == 0) {
5426 debug_printf_parse("done_word return 0: true null, ignored\n");
5430 if (ctx->pending_redirect) {
5431 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5432 * only if run as "bash", not "sh" */
5433 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5435 * ...the word that follows the redirection operator
5436 * shall be subjected to tilde expansion, parameter expansion,
5437 * command substitution, arithmetic expansion, and quote
5438 * removal. Pathname expansion shall not be performed
5439 * on the word by a non-interactive shell; an interactive
5440 * shell may perform it, but shall do so only when
5441 * the expansion would result in one word."
5443 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5444 /* Cater for >\file case:
5445 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5446 * Same with heredocs:
5447 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5449 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5450 unbackslash(ctx->pending_redirect->rd_filename);
5451 /* Is it <<"HEREDOC"? */
5452 if (word->o_quoted) {
5453 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5456 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5457 ctx->pending_redirect = NULL;
5459 /* If this word wasn't an assignment, next ones definitely
5460 * can't be assignments. Even if they look like ones. */
5461 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5462 && word->o_assignment != WORD_IS_KEYWORD
5464 word->o_assignment = NOT_ASSIGNMENT;
5466 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5467 command->assignment_cnt++;
5468 word->o_assignment = MAYBE_ASSIGNMENT;
5472 # if ENABLE_HUSH_CASE
5473 if (ctx->ctx_dsemicolon
5474 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5476 /* already done when ctx_dsemicolon was set to 1: */
5477 /* ctx->ctx_res_w = RES_MATCH; */
5478 ctx->ctx_dsemicolon = 0;
5481 if (!command->argv /* if it's the first word... */
5482 # if ENABLE_HUSH_LOOPS
5483 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5484 && ctx->ctx_res_w != RES_IN
5486 # if ENABLE_HUSH_CASE
5487 && ctx->ctx_res_w != RES_CASE
5490 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5491 if (reserved_word(word, ctx)) {
5492 o_reset_to_empty_unquoted(word);
5493 debug_printf_parse("done_word return %d\n",
5494 (ctx->ctx_res_w == RES_SNTX));
5495 return (ctx->ctx_res_w == RES_SNTX);
5497 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5498 if (strcmp(word->data, "export") == 0
5499 # if ENABLE_HUSH_LOCAL
5500 || strcmp(word->data, "local") == 0
5503 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5506 # if ENABLE_HUSH_BASH_COMPAT
5507 if (strcmp(word->data, "[[") == 0) {
5508 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5514 if (command->group) {
5515 /* "{ echo foo; } echo bar" - bad */
5516 syntax_error_at(word->data);
5517 debug_printf_parse("done_word return 1: syntax error, "
5518 "groups and arglists don't mix\n");
5521 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5522 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5523 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5524 /* (otherwise it's known to be not empty and is already safe) */
5526 /* exclude "$@" - it can expand to no word despite "" */
5527 char *p = word->data;
5528 while (p[0] == SPECIAL_VAR_SYMBOL
5529 && (p[1] & 0x7f) == '@'
5530 && p[2] == SPECIAL_VAR_SYMBOL
5534 if (p == word->data || p[0] != '\0') {
5535 /* saw no "$@", or not only "$@" but some
5536 * real text is there too */
5537 /* insert "empty variable" reference, this makes
5538 * e.g. "", $empty"" etc to not disappear */
5539 o_addchr(word, SPECIAL_VAR_SYMBOL);
5540 o_addchr(word, SPECIAL_VAR_SYMBOL);
5543 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5544 debug_print_strings("word appended to argv", command->argv);
5547 #if ENABLE_HUSH_LOOPS
5548 if (ctx->ctx_res_w == RES_FOR) {
5550 || !is_well_formed_var_name(command->argv[0], '\0')
5552 /* bash says just "not a valid identifier" */
5553 syntax_error("not a valid identifier in for");
5556 /* Force FOR to have just one word (variable name) */
5557 /* NB: basically, this makes hush see "for v in ..."
5558 * syntax as if it is "for v; in ...". FOR and IN become
5559 * two pipe structs in parse tree. */
5560 done_pipe(ctx, PIPE_SEQ);
5563 #if ENABLE_HUSH_CASE
5564 /* Force CASE to have just one word */
5565 if (ctx->ctx_res_w == RES_CASE) {
5566 done_pipe(ctx, PIPE_SEQ);
5570 o_reset_to_empty_unquoted(word);
5572 debug_printf_parse("done_word return 0\n");
5577 /* Peek ahead in the input to find out if we have a "&n" construct,
5578 * as in "2>&1", that represents duplicating a file descriptor.
5580 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5581 * REDIRFD_SYNTAX_ERR if syntax error,
5582 * REDIRFD_TO_FILE if no & was seen,
5583 * or the number found.
5586 #define parse_redir_right_fd(as_string, input) \
5587 parse_redir_right_fd(input)
5589 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5595 return REDIRFD_TO_FILE;
5597 ch = i_getch(input); /* get the & */
5598 nommu_addchr(as_string, ch);
5601 ch = i_getch(input);
5602 nommu_addchr(as_string, ch);
5603 return REDIRFD_CLOSE;
5607 while (ch != EOF && isdigit(ch)) {
5608 d = d*10 + (ch-'0');
5610 ch = i_getch(input);
5611 nommu_addchr(as_string, ch);
5616 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5618 bb_error_msg("ambiguous redirect");
5619 return REDIRFD_SYNTAX_ERR;
5622 /* Return code is 0 normal, 1 if a syntax error is detected
5624 static int parse_redirect(struct parse_context *ctx,
5627 struct in_str *input)
5629 struct command *command = ctx->command;
5630 struct redir_struct *redir;
5631 struct redir_struct **redirp;
5634 dup_num = REDIRFD_TO_FILE;
5635 if (style != REDIRECT_HEREDOC) {
5636 /* Check for a '>&1' type redirect */
5637 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5638 if (dup_num == REDIRFD_SYNTAX_ERR)
5641 int ch = i_peek(input);
5642 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5643 if (dup_num) { /* <<-... */
5644 ch = i_getch(input);
5645 nommu_addchr(&ctx->as_string, ch);
5650 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5651 int ch = i_peek(input);
5653 /* >|FILE redirect ("clobbering" >).
5654 * Since we do not support "set -o noclobber" yet,
5655 * >| and > are the same for now. Just eat |.
5657 ch = i_getch(input);
5658 nommu_addchr(&ctx->as_string, ch);
5662 /* Create a new redir_struct and append it to the linked list */
5663 redirp = &command->redirects;
5664 while ((redir = *redirp) != NULL) {
5665 redirp = &(redir->next);
5667 *redirp = redir = xzalloc(sizeof(*redir));
5668 /* redir->next = NULL; */
5669 /* redir->rd_filename = NULL; */
5670 redir->rd_type = style;
5671 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5673 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5674 redir_table[style].descrip);
5676 redir->rd_dup = dup_num;
5677 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5678 /* Erik had a check here that the file descriptor in question
5679 * is legit; I postpone that to "run time"
5680 * A "-" representation of "close me" shows up as a -3 here */
5681 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5682 redir->rd_fd, redir->rd_dup);
5684 /* Set ctx->pending_redirect, so we know what to do at the
5685 * end of the next parsed word. */
5686 ctx->pending_redirect = redir;
5691 /* If a redirect is immediately preceded by a number, that number is
5692 * supposed to tell which file descriptor to redirect. This routine
5693 * looks for such preceding numbers. In an ideal world this routine
5694 * needs to handle all the following classes of redirects...
5695 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5696 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5697 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5698 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5700 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5702 * ... If n is quoted, the number shall not be recognized as part of
5703 * the redirection expression. For example:
5705 * writes the character 2 into file a"
5706 * We are getting it right by setting ->o_quoted on any \<char>
5708 * A -1 return means no valid number was found,
5709 * the caller should use the appropriate default for this redirection.
5711 static int redirect_opt_num(o_string *o)
5715 if (o->data == NULL)
5717 num = bb_strtou(o->data, NULL, 10);
5718 if (errno || num < 0)
5720 o_reset_to_empty_unquoted(o);
5725 #define fetch_till_str(as_string, input, word, skip_tabs) \
5726 fetch_till_str(input, word, skip_tabs)
5728 static char *fetch_till_str(o_string *as_string,
5729 struct in_str *input,
5733 o_string heredoc = NULL_O_STRING;
5739 ch = i_getch(input);
5740 nommu_addchr(as_string, ch);
5742 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5743 heredoc.data[past_EOL] = '\0';
5744 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5745 return heredoc.data;
5748 o_addchr(&heredoc, ch);
5749 past_EOL = heredoc.length;
5752 ch = i_getch(input);
5753 nommu_addchr(as_string, ch);
5754 } while (skip_tabs && ch == '\t');
5755 } while (ch == '\n');
5758 o_free_unsafe(&heredoc);
5761 o_addchr(&heredoc, ch);
5762 nommu_addchr(as_string, ch);
5766 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5767 * and load them all. There should be exactly heredoc_cnt of them.
5769 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5771 struct pipe *pi = ctx->list_head;
5773 while (pi && heredoc_cnt) {
5775 struct command *cmd = pi->cmds;
5777 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5779 cmd->argv ? cmd->argv[0] : "NONE");
5780 for (i = 0; i < pi->num_cmds; i++) {
5781 struct redir_struct *redir = cmd->redirects;
5783 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5784 i, cmd->argv ? cmd->argv[0] : "NONE");
5786 if (redir->rd_type == REDIRECT_HEREDOC) {
5789 redir->rd_type = REDIRECT_HEREDOC2;
5790 /* redir->rd_dup is (ab)used to indicate <<- */
5791 p = fetch_till_str(&ctx->as_string, input,
5792 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5794 syntax_error("unexpected EOF in here document");
5797 free(redir->rd_filename);
5798 redir->rd_filename = p;
5801 redir = redir->next;
5808 /* Should be 0. If it isn't, it's a parse error */
5810 bb_error_msg_and_die("heredoc BUG 2");
5816 #if ENABLE_HUSH_TICK
5817 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5822 char **to_free = NULL;
5826 pid = BB_MMU ? xfork() : xvfork();
5827 if (pid == 0) { /* child */
5828 disable_restore_tty_pgrp_on_exit();
5829 /* Process substitution is not considered to be usual
5830 * 'command execution'.
5831 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5838 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5839 close(channel[0]); /* NB: close _first_, then move fd! */
5840 xmove_fd(channel[1], 1);
5841 /* Prevent it from trying to handle ctrl-z etc */
5842 IF_HUSH_JOB(G.run_list_level = 1;)
5843 /* Awful hack for `trap` or $(trap).
5845 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5846 * contains an example where "trap" is executed in a subshell:
5848 * save_traps=$(trap)
5850 * eval "$save_traps"
5852 * Standard does not say that "trap" in subshell shall print
5853 * parent shell's traps. It only says that its output
5854 * must have suitable form, but then, in the above example
5855 * (which is not supposed to be normative), it implies that.
5857 * bash (and probably other shell) does implement it
5858 * (traps are reset to defaults, but "trap" still shows them),
5859 * but as a result, "trap" logic is hopelessly messed up:
5862 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5863 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5864 * # true | trap <--- trap is in subshell - no output (ditto)
5865 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5866 * trap -- 'echo Ho' SIGWINCH
5867 * # echo `(trap)` <--- in subshell in subshell - output
5868 * trap -- 'echo Ho' SIGWINCH
5869 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5870 * trap -- 'echo Ho' SIGWINCH
5872 * The rules when to forget and when to not forget traps
5873 * get really complex and nonsensical.
5875 * Our solution: ONLY bare $(trap) or `trap` is special.
5877 s = skip_whitespace(s);
5878 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5880 static const char *const argv[] = { NULL, NULL };
5881 builtin_trap((char**)argv);
5882 exit(0); /* not _exit() - we need to fflush */
5885 reset_traps_to_defaults();
5886 parse_and_run_string(s);
5887 _exit(G.last_exitcode);
5889 /* We re-execute after vfork on NOMMU. This makes this script safe:
5890 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5891 * huge=`cat BIG` # was blocking here forever
5894 re_execute_shell(&to_free,
5904 # if ENABLE_HUSH_FAST
5906 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5908 enable_restore_tty_pgrp_on_exit();
5913 close_on_exec_on(channel[0]);
5914 return xfdopen_for_read(channel[0]);
5917 /* Return code is exit status of the process that is run. */
5918 static int process_command_subs(o_string *dest, const char *s)
5921 struct in_str pipe_str;
5923 int status, ch, eol_cnt;
5925 fp = generate_stream_from_string(s, &pid);
5927 /* Now send results of command back into original context */
5928 setup_file_in_str(&pipe_str, fp);
5930 while ((ch = i_getch(&pipe_str)) != EOF) {
5936 o_addchr(dest, '\n');
5939 o_addQchr(dest, ch);
5942 debug_printf("done reading from `cmd` pipe, closing it\n");
5944 /* We need to extract exitcode. Test case
5945 * "true; echo `sleep 1; false` $?"
5947 safe_waitpid(pid, &status, 0);
5948 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5949 return WEXITSTATUS(status);
5951 #endif /* ENABLE_HUSH_TICK */
5953 #if !ENABLE_HUSH_FUNCTIONS
5954 #define parse_group(dest, ctx, input, ch) \
5955 parse_group(ctx, input, ch)
5957 static int parse_group(o_string *dest, struct parse_context *ctx,
5958 struct in_str *input, int ch)
5960 /* dest contains characters seen prior to ( or {.
5961 * Typically it's empty, but for function defs,
5962 * it contains function name (without '()'). */
5963 struct pipe *pipe_list;
5965 struct command *command = ctx->command;
5967 debug_printf_parse("parse_group entered\n");
5968 #if ENABLE_HUSH_FUNCTIONS
5969 if (ch == '(' && !dest->o_quoted) {
5971 if (done_word(dest, ctx))
5974 goto skip; /* (... */
5975 if (command->argv[1]) { /* word word ... (... */
5976 syntax_error_unexpected_ch('(');
5979 /* it is "word(..." or "word (..." */
5981 ch = i_getch(input);
5982 while (ch == ' ' || ch == '\t');
5984 syntax_error_unexpected_ch(ch);
5987 nommu_addchr(&ctx->as_string, ch);
5989 ch = i_getch(input);
5990 while (ch == ' ' || ch == '\t' || ch == '\n');
5992 syntax_error_unexpected_ch(ch);
5995 nommu_addchr(&ctx->as_string, ch);
5996 command->cmd_type = CMD_FUNCDEF;
6001 #if 0 /* Prevented by caller */
6002 if (command->argv /* word [word]{... */
6003 || dest->length /* word{... */
6004 || dest->o_quoted /* ""{... */
6007 debug_printf_parse("parse_group return 1: "
6008 "syntax error, groups and arglists don't mix\n");
6013 #if ENABLE_HUSH_FUNCTIONS
6019 command->cmd_type = CMD_SUBSHELL;
6021 /* bash does not allow "{echo...", requires whitespace */
6022 ch = i_getch(input);
6023 if (ch != ' ' && ch != '\t' && ch != '\n') {
6024 syntax_error_unexpected_ch(ch);
6027 nommu_addchr(&ctx->as_string, ch);
6032 # define as_string NULL
6034 char *as_string = NULL;
6036 pipe_list = parse_stream(&as_string, input, endch);
6039 o_addstr(&ctx->as_string, as_string);
6041 /* empty ()/{} or parse error? */
6042 if (!pipe_list || pipe_list == ERR_PTR) {
6043 /* parse_stream already emitted error msg */
6046 debug_printf_parse("parse_group return 1: "
6047 "parse_stream returned %p\n", pipe_list);
6050 command->group = pipe_list;
6052 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6053 command->group_as_string = as_string;
6054 debug_printf_parse("end of group, remembering as:'%s'\n",
6055 command->group_as_string);
6059 debug_printf_parse("parse_group return 0\n");
6061 /* command remains "open", available for possible redirects */
6064 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6065 /* Subroutines for copying $(...) and `...` things */
6066 static void add_till_backquote(o_string *dest, struct in_str *input);
6068 static void add_till_single_quote(o_string *dest, struct in_str *input)
6071 int ch = i_getch(input);
6073 syntax_error_unterm_ch('\'');
6074 /*xfunc_die(); - redundant */
6081 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6082 static void add_till_double_quote(o_string *dest, struct in_str *input)
6085 int ch = i_getch(input);
6087 syntax_error_unterm_ch('"');
6088 /*xfunc_die(); - redundant */
6092 if (ch == '\\') { /* \x. Copy both chars. */
6094 ch = i_getch(input);
6098 add_till_backquote(dest, input);
6102 //if (ch == '$') ...
6105 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6107 * "Within the backquoted style of command substitution, backslash
6108 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6109 * The search for the matching backquote shall be satisfied by the first
6110 * backquote found without a preceding backslash; during this search,
6111 * if a non-escaped backquote is encountered within a shell comment,
6112 * a here-document, an embedded command substitution of the $(command)
6113 * form, or a quoted string, undefined results occur. A single-quoted
6114 * or double-quoted string that begins, but does not end, within the
6115 * "`...`" sequence produces undefined results."
6117 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6119 static void add_till_backquote(o_string *dest, struct in_str *input)
6122 int ch = i_getch(input);
6124 syntax_error_unterm_ch('`');
6125 /*xfunc_die(); - redundant */
6130 /* \x. Copy both chars unless it is \` */
6131 int ch2 = i_getch(input);
6133 syntax_error_unterm_ch('`');
6134 /*xfunc_die(); - redundant */
6136 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6143 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6144 * quoting and nested ()s.
6145 * "With the $(command) style of command substitution, all characters
6146 * following the open parenthesis to the matching closing parenthesis
6147 * constitute the command. Any valid shell script can be used for command,
6148 * except a script consisting solely of redirections which produces
6149 * unspecified results."
6151 * echo $(echo '(TEST)' BEST) (TEST) BEST
6152 * echo $(echo 'TEST)' BEST) TEST) BEST
6153 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6155 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6156 * can contain arbitrary constructs, just like $(cmd).
6157 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6158 * for ${var:N[:M]} parsing.
6160 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6161 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6164 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6165 # if ENABLE_HUSH_BASH_COMPAT
6166 char end_char2 = end_ch >> 8;
6168 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6171 ch = i_getch(input);
6173 syntax_error_unterm_ch(end_ch);
6174 /*xfunc_die(); - redundant */
6176 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6179 /* we look for closing )) of $((EXPR)) */
6180 if (i_peek(input) == end_ch) {
6181 i_getch(input); /* eat second ')' */
6186 if (ch == '(' || ch == '{') {
6187 ch = (ch == '(' ? ')' : '}');
6188 add_till_closing_bracket(dest, input, ch);
6193 add_till_single_quote(dest, input);
6198 add_till_double_quote(dest, input);
6203 add_till_backquote(dest, input);
6208 /* \x. Copy verbatim. Important for \(, \) */
6209 ch = i_getch(input);
6211 syntax_error_unterm_ch(')');
6212 /*xfunc_die(); - redundant */
6220 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6222 /* Return code: 0 for OK, 1 for syntax error */
6224 #define parse_dollar(as_string, dest, input) \
6225 parse_dollar(dest, input)
6226 #define as_string NULL
6228 static int parse_dollar(o_string *as_string,
6230 struct in_str *input)
6232 int ch = i_peek(input); /* first character after the $ */
6233 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6235 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6237 ch = i_getch(input);
6238 nommu_addchr(as_string, ch);
6240 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6242 debug_printf_parse(": '%c'\n", ch);
6243 o_addchr(dest, ch | quote_mask);
6246 if (!isalnum(ch) && ch != '_')
6248 ch = i_getch(input);
6249 nommu_addchr(as_string, ch);
6251 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6252 } else if (isdigit(ch)) {
6254 ch = i_getch(input);
6255 nommu_addchr(as_string, ch);
6256 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6257 debug_printf_parse(": '%c'\n", ch);
6258 o_addchr(dest, ch | quote_mask);
6259 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6260 } else switch (ch) {
6262 case '!': /* last bg pid */
6263 case '?': /* last exit code */
6264 case '#': /* number of args */
6265 case '*': /* args */
6266 case '@': /* args */
6267 goto make_one_char_var;
6269 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6271 ch = i_getch(input); /* eat '{' */
6272 nommu_addchr(as_string, ch);
6274 ch = i_getch(input); /* first char after '{' */
6275 nommu_addchr(as_string, ch);
6276 /* It should be ${?}, or ${#var},
6277 * or even ${?+subst} - operator acting on a special variable,
6278 * or the beginning of variable name.
6280 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6282 syntax_error_unterm_str("${name}");
6283 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6288 /* It's possible to just call add_till_closing_bracket() at this point.
6289 * However, this regresses some of our testsuite cases
6290 * which check invalid constructs like ${%}.
6291 * Oh well... let's check that the var name part is fine... */
6297 debug_printf_parse(": '%c'\n", ch);
6299 ch = i_getch(input);
6300 nommu_addchr(as_string, ch);
6304 if (!isalnum(ch) && ch != '_') {
6306 unsigned char last_ch;
6307 /* handle parameter expansions
6308 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6310 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6311 goto bad_dollar_syntax;
6314 /* Eat everything until closing '}' (or ':') */
6316 if (ENABLE_HUSH_BASH_COMPAT
6318 && !strchr("%#:-=+?"+3, i_peek(input))
6320 /* It's ${var:N[:M]} thing */
6321 end_ch = '}' * 0x100 + ':';
6326 #if ENABLE_HUSH_DOLLAR_OPS
6327 last_ch = add_till_closing_bracket(dest, input, end_ch);
6329 #error Simple code to only allow ${var} is not implemented
6332 o_addstr(as_string, dest->data + pos);
6333 o_addchr(as_string, last_ch);
6336 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6337 /* close the first block: */
6338 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6339 /* while parsing N from ${var:N[:M]}... */
6340 if ((end_ch & 0xff) == last_ch) {
6341 /* ...got ':' - parse the rest */
6345 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6346 o_addstr(dest, "999999999");
6351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6354 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6358 ch = i_getch(input);
6359 nommu_addchr(as_string, ch);
6360 # if ENABLE_SH_MATH_SUPPORT
6361 if (i_peek(input) == '(') {
6362 ch = i_getch(input);
6363 nommu_addchr(as_string, ch);
6364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6365 o_addchr(dest, /*quote_mask |*/ '+');
6368 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6370 o_addstr(as_string, dest->data + pos);
6371 o_addchr(as_string, ')');
6372 o_addchr(as_string, ')');
6374 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6378 # if ENABLE_HUSH_TICK
6379 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6380 o_addchr(dest, quote_mask | '`');
6383 add_till_closing_bracket(dest, input, ')');
6385 o_addstr(as_string, dest->data + pos);
6386 o_addchr(as_string, ')');
6388 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6394 ch = i_getch(input);
6395 nommu_addchr(as_string, ch);
6397 if (isalnum(ch)) { /* it's $_name or $_123 */
6402 /* TODO: $_ and $-: */
6403 /* $_ Shell or shell script name; or last argument of last command
6404 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6405 * but in command's env, set to full pathname used to invoke it */
6406 /* $- Option flags set by set builtin or shell options (-i etc) */
6408 o_addQchr(dest, '$');
6410 debug_printf_parse("parse_dollar return 0\n");
6416 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6417 parse_stream_dquoted(dest, input, dquote_end)
6418 #define as_string NULL
6420 static int parse_stream_dquoted(o_string *as_string,
6422 struct in_str *input,
6429 ch = i_getch(input);
6431 nommu_addchr(as_string, ch);
6432 if (ch == dquote_end) { /* may be only '"' or EOF */
6433 if (dest->o_assignment == NOT_ASSIGNMENT)
6434 dest->o_escape ^= 1;
6435 debug_printf_parse("parse_stream_dquoted return 0\n");
6438 /* note: can't move it above ch == dquote_end check! */
6440 syntax_error_unterm_ch('"');
6441 /*xfunc_die(); - redundant */
6445 next = i_peek(input);
6447 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6448 ch, ch, dest->o_escape);
6451 syntax_error("\\<eof>");
6455 * "The backslash retains its special meaning [in "..."]
6456 * only when followed by one of the following characters:
6457 * $, `, ", \, or <newline>. A double quote may be quoted
6458 * within double quotes by preceding it with a backslash."
6460 if (strchr("$`\"\\\n", next) != NULL) {
6461 ch = i_getch(input);
6463 o_addqchr(dest, ch);
6464 nommu_addchr(as_string, ch);
6467 o_addqchr(dest, '\\');
6468 nommu_addchr(as_string, '\\');
6473 if (parse_dollar(as_string, dest, input) != 0) {
6474 debug_printf_parse("parse_stream_dquoted return 1: "
6475 "parse_dollar returned non-0\n");
6480 #if ENABLE_HUSH_TICK
6482 //unsigned pos = dest->length;
6483 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6484 o_addchr(dest, 0x80 | '`');
6485 add_till_backquote(dest, input);
6486 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6487 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6491 o_addQchr(dest, ch);
6493 && (dest->o_assignment == MAYBE_ASSIGNMENT
6494 || dest->o_assignment == WORD_IS_KEYWORD)
6495 && is_well_formed_var_name(dest->data, '=')
6497 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6504 * Scan input until EOF or end_trigger char.
6505 * Return a list of pipes to execute, or NULL on EOF
6506 * or if end_trigger character is met.
6507 * On syntax error, exit is shell is not interactive,
6508 * reset parsing machinery and start parsing anew,
6509 * or return ERR_PTR.
6511 static struct pipe *parse_stream(char **pstring,
6512 struct in_str *input,
6515 struct parse_context ctx;
6516 o_string dest = NULL_O_STRING;
6520 /* Double-quote state is handled in the state variable is_in_dquote.
6521 * A single-quote triggers a bypass of the main loop until its mate is
6522 * found. When recursing, quote state is passed in via dest->o_escape.
6524 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6525 end_trigger ? end_trigger : 'X');
6528 /* If very first arg is "" or '', dest.data may end up NULL.
6529 * Preventing this: */
6530 o_addchr(&dest, '\0');
6533 G.ifs = get_local_var_value("IFS");
6538 #if ENABLE_HUSH_INTERACTIVE
6539 input->promptmode = 0; /* PS1 */
6541 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6542 initialize_context(&ctx);
6547 const char *is_special;
6551 redir_type redir_style;
6554 /* dest.o_quoted = 1; - already is (see below) */
6555 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6558 /* We reached closing '"' */
6561 ch = i_getch(input);
6562 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6563 ch, ch, dest.o_escape);
6568 syntax_error_unterm_str("here document");
6571 /* end_trigger == '}' case errors out earlier,
6572 * checking only ')' */
6573 if (end_trigger == ')') {
6574 syntax_error_unterm_ch('('); /* exits */
6575 /* goto parse_error; */
6578 if (done_word(&dest, &ctx)) {
6582 done_pipe(&ctx, PIPE_SEQ);
6584 /* If we got nothing... */
6585 /* (this makes bare "&" cmd a no-op.
6586 * bash says: "syntax error near unexpected token '&'") */
6587 if (pi->num_cmds == 0
6588 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6594 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6596 *pstring = ctx.as_string.data;
6598 o_free_unsafe(&ctx.as_string);
6601 debug_printf_parse("parse_stream return %p\n", pi);
6604 nommu_addchr(&ctx.as_string, ch);
6608 next = i_peek(input);
6610 is_special = "{}<>;&|()#'" /* special outside of "str" */
6611 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6612 /* Are { and } special here? */
6613 if (ctx.command->argv /* word [word]{... - non-special */
6614 || dest.length /* word{... - non-special */
6615 || dest.o_quoted /* ""{... - non-special */
6616 || (next != ';' /* }; - special */
6617 && next != ')' /* }) - special */
6618 && next != '&' /* }& and }&& ... - special */
6619 && next != '|' /* }|| ... - special */
6620 && !strchr(G.ifs, next) /* {word - non-special */
6623 /* They are not special, skip "{}" */
6626 is_special = strchr(is_special, ch);
6627 is_ifs = strchr(G.ifs, ch);
6629 if (!is_special && !is_ifs) { /* ordinary char */
6631 o_addQchr(&dest, ch);
6632 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6633 || dest.o_assignment == WORD_IS_KEYWORD)
6635 && is_well_formed_var_name(dest.data, '=')
6637 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6643 if (done_word(&dest, &ctx)) {
6647 #if ENABLE_HUSH_CASE
6648 /* "case ... in <newline> word) ..." -
6649 * newlines are ignored (but ';' wouldn't be) */
6650 if (ctx.command->argv == NULL
6651 && ctx.ctx_res_w == RES_MATCH
6656 /* Treat newline as a command separator. */
6657 done_pipe(&ctx, PIPE_SEQ);
6658 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6660 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6665 dest.o_assignment = MAYBE_ASSIGNMENT;
6667 /* note: if (is_ifs) continue;
6668 * will still trigger for us */
6672 /* "cmd}" or "cmd }..." without semicolon or &:
6673 * } is an ordinary char in this case, even inside { cmd; }
6674 * Pathological example: { ""}; } should exec "}" cmd
6677 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6678 || dest.length != 0 /* word} */
6679 || dest.o_quoted /* ""} */
6683 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6684 goto skip_end_trigger;
6685 /* else: } does terminate a group */
6688 if (end_trigger && end_trigger == ch
6689 && (ch != ';' || heredoc_cnt == 0)
6690 #if ENABLE_HUSH_CASE
6692 || ctx.ctx_res_w != RES_MATCH
6693 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6698 /* This is technically valid:
6699 * { cat <<HERE; }; echo Ok
6703 * but we don't support this.
6704 * We require heredoc to be in enclosing {}/(),
6707 syntax_error_unterm_str("here document");
6710 if (done_word(&dest, &ctx)) {
6713 done_pipe(&ctx, PIPE_SEQ);
6714 dest.o_assignment = MAYBE_ASSIGNMENT;
6715 /* Do we sit outside of any if's, loops or case's? */
6717 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6721 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6723 *pstring = ctx.as_string.data;
6725 o_free_unsafe(&ctx.as_string);
6728 debug_printf_parse("parse_stream return %p: "
6729 "end_trigger char found\n",
6731 return ctx.list_head;
6738 /* Catch <, > before deciding whether this word is
6739 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6742 redir_fd = redirect_opt_num(&dest);
6743 if (done_word(&dest, &ctx)) {
6746 redir_style = REDIRECT_OVERWRITE;
6748 redir_style = REDIRECT_APPEND;
6749 ch = i_getch(input);
6750 nommu_addchr(&ctx.as_string, ch);
6753 else if (next == '(') {
6754 syntax_error(">(process) not supported");
6758 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6760 continue; /* back to top of while (1) */
6762 redir_fd = redirect_opt_num(&dest);
6763 if (done_word(&dest, &ctx)) {
6766 redir_style = REDIRECT_INPUT;
6768 redir_style = REDIRECT_HEREDOC;
6770 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6771 ch = i_getch(input);
6772 nommu_addchr(&ctx.as_string, ch);
6773 } else if (next == '>') {
6774 redir_style = REDIRECT_IO;
6775 ch = i_getch(input);
6776 nommu_addchr(&ctx.as_string, ch);
6779 else if (next == '(') {
6780 syntax_error("<(process) not supported");
6784 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6786 continue; /* back to top of while (1) */
6789 if (dest.o_assignment == MAYBE_ASSIGNMENT
6790 /* check that we are not in word in "a=1 2>word b=1": */
6791 && !ctx.pending_redirect
6793 /* ch is a special char and thus this word
6794 * cannot be an assignment */
6795 dest.o_assignment = NOT_ASSIGNMENT;
6798 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6802 if (dest.length == 0) {
6805 if (ch == EOF || ch == '\n')
6808 /* note: we do not add it to &ctx.as_string */
6810 nommu_addchr(&ctx.as_string, '\n');
6812 o_addQchr(&dest, ch);
6817 syntax_error("\\<eof>");
6820 ch = i_getch(input);
6822 o_addchr(&dest, '\\');
6823 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6824 o_addchr(&dest, ch);
6825 nommu_addchr(&ctx.as_string, ch);
6826 /* Example: echo Hello \2>file
6827 * we need to know that word 2 is quoted */
6832 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6833 ctx.as_string.data[--ctx.as_string.length] = '\0';
6838 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6839 debug_printf_parse("parse_stream parse error: "
6840 "parse_dollar returned non-0\n");
6847 ch = i_getch(input);
6849 syntax_error_unterm_ch('\'');
6850 /*xfunc_die(); - redundant */
6852 nommu_addchr(&ctx.as_string, ch);
6855 o_addqchr(&dest, ch);
6860 is_in_dquote ^= 1; /* invert */
6861 if (dest.o_assignment == NOT_ASSIGNMENT)
6864 #if ENABLE_HUSH_TICK
6868 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6869 o_addchr(&dest, '`');
6871 add_till_backquote(&dest, input);
6873 o_addstr(&ctx.as_string, dest.data + pos);
6874 o_addchr(&ctx.as_string, '`');
6876 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6877 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6882 #if ENABLE_HUSH_CASE
6885 if (done_word(&dest, &ctx)) {
6888 done_pipe(&ctx, PIPE_SEQ);
6889 #if ENABLE_HUSH_CASE
6890 /* Eat multiple semicolons, detect
6891 * whether it means something special */
6896 ch = i_getch(input);
6897 nommu_addchr(&ctx.as_string, ch);
6898 if (ctx.ctx_res_w == RES_CASE_BODY) {
6899 ctx.ctx_dsemicolon = 1;
6900 ctx.ctx_res_w = RES_MATCH;
6906 /* We just finished a cmd. New one may start
6907 * with an assignment */
6908 dest.o_assignment = MAYBE_ASSIGNMENT;
6911 if (done_word(&dest, &ctx)) {
6915 ch = i_getch(input);
6916 nommu_addchr(&ctx.as_string, ch);
6917 done_pipe(&ctx, PIPE_AND);
6919 done_pipe(&ctx, PIPE_BG);
6923 if (done_word(&dest, &ctx)) {
6926 #if ENABLE_HUSH_CASE
6927 if (ctx.ctx_res_w == RES_MATCH)
6928 break; /* we are in case's "word | word)" */
6930 if (next == '|') { /* || */
6931 ch = i_getch(input);
6932 nommu_addchr(&ctx.as_string, ch);
6933 done_pipe(&ctx, PIPE_OR);
6935 /* we could pick up a file descriptor choice here
6936 * with redirect_opt_num(), but bash doesn't do it.
6937 * "echo foo 2| cat" yields "foo 2". */
6940 o_reset_to_empty_unquoted(&ctx.as_string);
6945 #if ENABLE_HUSH_CASE
6946 /* "case... in [(]word)..." - skip '(' */
6947 if (ctx.ctx_res_w == RES_MATCH
6948 && ctx.command->argv == NULL /* not (word|(... */
6949 && dest.length == 0 /* not word(... */
6950 && dest.o_quoted == 0 /* not ""(... */
6956 if (parse_group(&dest, &ctx, input, ch) != 0) {
6961 #if ENABLE_HUSH_CASE
6962 if (ctx.ctx_res_w == RES_MATCH)
6966 /* proper use of this character is caught by end_trigger:
6967 * if we see {, we call parse_group(..., end_trigger='}')
6968 * and it will match } earlier (not here). */
6969 syntax_error_unexpected_ch(ch);
6973 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6979 struct parse_context *pctx;
6980 IF_HAS_KEYWORDS(struct parse_context *p2;)
6982 /* Clean up allocated tree.
6983 * Sample for finding leaks on syntax error recovery path.
6984 * Run it from interactive shell, watch pmap `pidof hush`.
6985 * while if false; then false; fi; do break; fi
6986 * Samples to catch leaks at execution:
6987 * while if (true | {true;}); then echo ok; fi; do break; done
6988 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6992 /* Update pipe/command counts,
6993 * otherwise freeing may miss some */
6994 done_pipe(pctx, PIPE_SEQ);
6995 debug_printf_clean("freeing list %p from ctx %p\n",
6996 pctx->list_head, pctx);
6997 debug_print_tree(pctx->list_head, 0);
6998 free_pipe_list(pctx->list_head);
6999 debug_printf_clean("freed list %p\n", pctx->list_head);
7001 o_free_unsafe(&pctx->as_string);
7003 IF_HAS_KEYWORDS(p2 = pctx->stack;)
7007 IF_HAS_KEYWORDS(pctx = p2;)
7008 } while (HAS_KEYWORDS && pctx);
7009 /* Free text, clear all dest fields */
7011 /* If we are not in top-level parse, we return,
7012 * our caller will propagate error.
7014 if (end_trigger != ';') {
7022 /* Discard cached input, force prompt */
7024 IF_HUSH_INTERACTIVE(input->promptme = 1;)
7029 /* Executing from string: eval, sh -c '...'
7030 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7031 * end_trigger controls how often we stop parsing
7032 * NUL: parse all, execute, return
7033 * ';': parse till ';' or newline, execute, repeat till EOF
7035 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7037 /* Why we need empty flag?
7038 * An obscure corner case "false; ``; echo $?":
7039 * empty command in `` should still set $? to 0.
7040 * But we can't just set $? to 0 at the start,
7041 * this breaks "false; echo `echo $?`" case.
7045 struct pipe *pipe_list;
7047 pipe_list = parse_stream(NULL, inp, end_trigger);
7048 if (!pipe_list) { /* EOF */
7050 G.last_exitcode = 0;
7053 debug_print_tree(pipe_list, 0);
7054 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7055 run_and_free_list(pipe_list);
7060 static void parse_and_run_string(const char *s)
7062 struct in_str input;
7063 setup_string_in_str(&input, s);
7064 parse_and_run_stream(&input, '\0');
7067 static void parse_and_run_file(FILE *f)
7069 struct in_str input;
7070 setup_file_in_str(&input, f);
7071 parse_and_run_stream(&input, ';');
7074 /* Called a few times only (or even once if "sh -c") */
7075 static void init_sigmasks(void)
7079 sigset_t old_blocked_set;
7081 if (!G.inherited_set_is_saved) {
7082 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7083 G.inherited_set = G.blocked_set;
7085 old_blocked_set = G.blocked_set;
7087 mask = (1 << SIGQUIT);
7088 if (G_interactive_fd) {
7089 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7090 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7091 mask |= SPECIAL_JOB_SIGS;
7093 G.non_DFL_mask = mask;
7098 sigaddset(&G.blocked_set, sig);
7102 sigdelset(&G.blocked_set, SIGCHLD);
7104 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7105 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7107 /* POSIX allows shell to re-enable SIGCHLD
7108 * even if it was SIG_IGN on entry */
7109 #if ENABLE_HUSH_FAST
7110 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7111 if (!G.inherited_set_is_saved)
7112 signal(SIGCHLD, SIGCHLD_handler);
7114 if (!G.inherited_set_is_saved)
7115 signal(SIGCHLD, SIG_DFL);
7118 G.inherited_set_is_saved = 1;
7123 static void maybe_set_to_sigexit(int sig)
7125 void (*handler)(int);
7126 /* non_DFL_mask'ed signals are, well, masked,
7127 * no need to set handler for them.
7129 if (!((G.non_DFL_mask >> sig) & 1)) {
7130 handler = signal(sig, sigexit);
7131 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7132 signal(sig, handler);
7135 /* Set handlers to restore tty pgrp and exit */
7136 static void set_fatal_handlers(void)
7138 /* We _must_ restore tty pgrp on fatal signals */
7140 maybe_set_to_sigexit(SIGILL );
7141 maybe_set_to_sigexit(SIGFPE );
7142 maybe_set_to_sigexit(SIGBUS );
7143 maybe_set_to_sigexit(SIGSEGV);
7144 maybe_set_to_sigexit(SIGTRAP);
7145 } /* else: hush is perfect. what SEGV? */
7146 maybe_set_to_sigexit(SIGABRT);
7147 /* bash 3.2 seems to handle these just like 'fatal' ones */
7148 maybe_set_to_sigexit(SIGPIPE);
7149 maybe_set_to_sigexit(SIGALRM);
7150 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7151 * if we aren't interactive... but in this case
7152 * we never want to restore pgrp on exit, and this fn is not called */
7153 /*maybe_set_to_sigexit(SIGHUP );*/
7154 /*maybe_set_to_sigexit(SIGTERM);*/
7155 /*maybe_set_to_sigexit(SIGINT );*/
7159 static int set_mode(const char cstate, const char mode)
7161 int state = (cstate == '-' ? 1 : 0);
7163 case 'n': G.n_mode = state; break;
7164 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7165 default: return EXIT_FAILURE;
7167 return EXIT_SUCCESS;
7170 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7171 int hush_main(int argc, char **argv)
7173 static const struct variable const_shell_ver = {
7175 .varstr = (char*)hush_version_str,
7176 .max_len = 1, /* 0 can provoke free(name) */
7181 unsigned builtin_argc;
7183 struct variable *cur_var;
7186 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7187 G.last_exitcode = EXIT_SUCCESS;
7189 G.argv0_for_re_execing = argv[0];
7191 /* Deal with HUSH_VERSION */
7192 G.shell_ver = const_shell_ver; /* copying struct here */
7193 G.top_var = &G.shell_ver;
7194 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7195 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7196 /* Initialize our shell local variables with the values
7197 * currently living in the environment */
7198 cur_var = G.top_var;
7201 char *value = strchr(*e, '=');
7202 if (value) { /* paranoia */
7203 cur_var->next = xzalloc(sizeof(*cur_var));
7204 cur_var = cur_var->next;
7205 cur_var->varstr = *e;
7206 cur_var->max_len = strlen(*e);
7207 cur_var->flg_export = 1;
7211 /* reinstate HUSH_VERSION */
7212 debug_printf_env("putenv '%s'\n", hush_version_str);
7213 putenv((char *)hush_version_str);
7216 set_pwd_var(/*exp:*/ 1);
7217 /* bash also exports SHLVL and _,
7218 * and sets (but doesn't export) the following variables:
7220 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7221 * BASH_VERSION='3.2.0(1)-release'
7223 * MACHTYPE=i386-pc-linux-gnu
7225 * HOSTNAME=<xxxxxxxxxx>
7226 * PPID=<NNNNN> - we also do it elsewhere
7237 * PIPESTATUS=([0]="0")
7238 * HISTFILE=/<xxx>/.bash_history
7242 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7244 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7254 #if ENABLE_FEATURE_EDITING
7255 G.line_input_state = new_line_input_t(FOR_SHELL);
7257 G.global_argc = argc;
7258 G.global_argv = argv;
7259 /* Initialize some more globals to non-zero values */
7260 cmdedit_update_prompt();
7262 if (setjmp(die_jmp)) {
7263 /* xfunc has failed! die die die */
7264 /* no EXIT traps, this is an escape hatch! */
7266 hush_exit(xfunc_error_retval);
7269 /* Shell is non-interactive at first. We need to call
7270 * init_sigmasks() if we are going to execute "sh <script>",
7271 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7272 * If we later decide that we are interactive, we run init_sigmasks()
7273 * in order to intercept (more) signals.
7277 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7280 opt = getopt(argc, argv, "+c:xins"
7283 # if ENABLE_HUSH_FUNCTIONS
7293 * sh ... -c 'script'
7294 * sh ... -c 'script' ARG0 [ARG1...]
7295 * On NOMMU, if builtin_argc != 0,
7296 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7297 * "" needs to be replaced with NULL
7298 * and BARGV vector fed to builtin function.
7299 * Note: the form without ARG0 never happens:
7300 * sh ... -c 'builtin' BARGV... ""
7303 G.root_pid = getpid();
7304 G.root_ppid = getppid();
7306 G.global_argv = argv + optind;
7307 G.global_argc = argc - optind;
7309 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7310 const struct built_in_command *x;
7313 x = find_builtin(optarg);
7314 if (x) { /* paranoia */
7315 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7316 G.global_argv += builtin_argc;
7317 G.global_argv[-1] = NULL; /* replace "" */
7318 G.last_exitcode = x->b_function(argv + optind - 1);
7322 if (!G.global_argv[0]) {
7323 /* -c 'script' (no params): prevent empty $0 */
7324 G.global_argv--; /* points to argv[i] of 'script' */
7325 G.global_argv[0] = argv[0];
7327 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7329 parse_and_run_string(optarg);
7332 /* Well, we cannot just declare interactiveness,
7333 * we have to have some stuff (ctty, etc) */
7334 /* G_interactive_fd++; */
7337 /* "-s" means "read from stdin", but this is how we always
7338 * operate, so simply do nothing here. */
7341 case '<': /* "big heredoc" support */
7342 full_write1_str(optarg);
7345 unsigned long long empty_trap_mask;
7347 G.root_pid = bb_strtou(optarg, &optarg, 16);
7349 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7351 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7353 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7355 builtin_argc = bb_strtou(optarg, &optarg, 16);
7357 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7358 if (empty_trap_mask != 0) {
7361 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7362 for (sig = 1; sig < NSIG; sig++) {
7363 if (empty_trap_mask & (1LL << sig)) {
7364 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7365 sigaddset(&G.blocked_set, sig);
7368 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7370 # if ENABLE_HUSH_LOOPS
7372 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7378 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7380 # if ENABLE_HUSH_FUNCTIONS
7382 struct function *funcp = new_function(optarg);
7383 /* funcp->name is already set to optarg */
7384 /* funcp->body is set to NULL. It's a special case. */
7385 funcp->body_as_string = argv[optind];
7393 if (set_mode('-', opt) == 0) /* no error */
7397 fprintf(stderr, "Usage: sh [FILE]...\n"
7398 " or: sh -c command [args]...\n\n");
7404 } /* option parsing loop */
7407 G.root_pid = getpid();
7408 G.root_ppid = getppid();
7411 /* If we are login shell... */
7412 if (argv[0] && argv[0][0] == '-') {
7414 debug_printf("sourcing /etc/profile\n");
7415 input = fopen_for_read("/etc/profile");
7416 if (input != NULL) {
7417 close_on_exec_on(fileno(input));
7419 parse_and_run_file(input);
7422 /* bash: after sourcing /etc/profile,
7423 * tries to source (in the given order):
7424 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7425 * stopping on first found. --noprofile turns this off.
7426 * bash also sources ~/.bash_logout on exit.
7427 * If called as sh, skips .bash_XXX files.
7434 * "bash <script>" (which is never interactive (unless -i?))
7435 * sources $BASH_ENV here (without scanning $PATH).
7436 * If called as sh, does the same but with $ENV.
7438 debug_printf("running script '%s'\n", argv[optind]);
7439 G.global_argv = argv + optind;
7440 G.global_argc = argc - optind;
7441 input = xfopen_for_read(argv[optind]);
7442 close_on_exec_on(fileno(input));
7444 parse_and_run_file(input);
7445 #if ENABLE_FEATURE_CLEAN_UP
7451 /* Up to here, shell was non-interactive. Now it may become one.
7452 * NB: don't forget to (re)run init_sigmasks() as needed.
7455 /* A shell is interactive if the '-i' flag was given,
7456 * or if all of the following conditions are met:
7458 * no arguments remaining or the -s flag given
7459 * standard input is a terminal
7460 * standard output is a terminal
7461 * Refer to Posix.2, the description of the 'sh' utility.
7464 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7465 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7466 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7467 if (G_saved_tty_pgrp < 0)
7468 G_saved_tty_pgrp = 0;
7470 /* try to dup stdin to high fd#, >= 255 */
7471 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7472 if (G_interactive_fd < 0) {
7473 /* try to dup to any fd */
7474 G_interactive_fd = dup(STDIN_FILENO);
7475 if (G_interactive_fd < 0) {
7477 G_interactive_fd = 0;
7478 G_saved_tty_pgrp = 0;
7481 // TODO: track & disallow any attempts of user
7482 // to (inadvertently) close/redirect G_interactive_fd
7484 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7485 if (G_interactive_fd) {
7486 close_on_exec_on(G_interactive_fd);
7488 if (G_saved_tty_pgrp) {
7489 /* If we were run as 'hush &', sleep until we are
7490 * in the foreground (tty pgrp == our pgrp).
7491 * If we get started under a job aware app (like bash),
7492 * make sure we are now in charge so we don't fight over
7493 * who gets the foreground */
7495 pid_t shell_pgrp = getpgrp();
7496 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7497 if (G_saved_tty_pgrp == shell_pgrp)
7499 /* send TTIN to ourself (should stop us) */
7500 kill(- shell_pgrp, SIGTTIN);
7504 /* Block some signals */
7507 if (G_saved_tty_pgrp) {
7508 /* Set other signals to restore saved_tty_pgrp */
7509 set_fatal_handlers();
7510 /* Put ourselves in our own process group
7511 * (bash, too, does this only if ctty is available) */
7512 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7513 /* Grab control of the terminal */
7514 tcsetpgrp(G_interactive_fd, getpid());
7516 /* -1 is special - makes xfuncs longjmp, not exit
7517 * (we reset die_sleep = 0 whereever we [v]fork) */
7518 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7522 #elif ENABLE_HUSH_INTERACTIVE
7523 /* No job control compiled in, only prompt/line editing */
7524 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7525 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7526 if (G_interactive_fd < 0) {
7527 /* try to dup to any fd */
7528 G_interactive_fd = dup(STDIN_FILENO);
7529 if (G_interactive_fd < 0)
7531 G_interactive_fd = 0;
7534 if (G_interactive_fd) {
7535 close_on_exec_on(G_interactive_fd);
7539 /* We have interactiveness code disabled */
7543 * if interactive but not a login shell, sources ~/.bashrc
7544 * (--norc turns this off, --rcfile <file> overrides)
7547 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7548 /* note: ash and hush share this string */
7549 printf("\n\n%s %s\n"
7550 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7553 "hush - the humble shell"
7557 parse_and_run_file(stdin);
7560 #if ENABLE_FEATURE_CLEAN_UP
7561 if (G.cwd != bb_msg_unknown)
7563 cur_var = G.top_var->next;
7565 struct variable *tmp = cur_var;
7566 if (!cur_var->max_len)
7567 free(cur_var->varstr);
7568 cur_var = cur_var->next;
7572 hush_exit(G.last_exitcode);
7577 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7578 int lash_main(int argc, char **argv)
7580 bb_error_msg("lash is deprecated, please use hush instead");
7581 return hush_main(argc, argv);
7586 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7587 int msh_main(int argc, char **argv)
7589 //bb_error_msg("msh is deprecated, please use hush instead");
7590 return hush_main(argc, argv);
7598 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7603 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7610 return applet_main_func(argc, argv - argc);
7613 static int FAST_FUNC builtin_test(char **argv)
7615 return run_applet_main(argv, test_main);
7618 static int FAST_FUNC builtin_echo(char **argv)
7620 return run_applet_main(argv, echo_main);
7624 static int FAST_FUNC builtin_printf(char **argv)
7626 return run_applet_main(argv, printf_main);
7630 static char **skip_dash_dash(char **argv)
7633 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7638 static int FAST_FUNC builtin_eval(char **argv)
7640 int rcode = EXIT_SUCCESS;
7642 argv = skip_dash_dash(argv);
7644 char *str = expand_strvec_to_string(argv);
7646 * eval "echo Hi; done" ("done" is syntax error):
7647 * "echo Hi" will not execute too.
7649 parse_and_run_string(str);
7651 rcode = G.last_exitcode;
7656 static int FAST_FUNC builtin_cd(char **argv)
7660 argv = skip_dash_dash(argv);
7662 if (newdir == NULL) {
7663 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7664 * bash says "bash: cd: HOME not set" and does nothing
7667 const char *home = get_local_var_value("HOME");
7668 newdir = home ? home : "/";
7670 if (chdir(newdir)) {
7671 /* Mimic bash message exactly */
7672 bb_perror_msg("cd: %s", newdir);
7673 return EXIT_FAILURE;
7675 /* Read current dir (get_cwd(1) is inside) and set PWD.
7676 * Note: do not enforce exporting. If PWD was unset or unexported,
7677 * set it again, but do not export. bash does the same.
7679 set_pwd_var(/*exp:*/ 0);
7680 return EXIT_SUCCESS;
7683 static int FAST_FUNC builtin_exec(char **argv)
7685 argv = skip_dash_dash(argv);
7686 if (argv[0] == NULL)
7687 return EXIT_SUCCESS; /* bash does this */
7689 /* Careful: we can end up here after [v]fork. Do not restore
7690 * tty pgrp then, only top-level shell process does that */
7691 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7692 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7694 /* TODO: if exec fails, bash does NOT exit! We do.
7695 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7696 * and tcsetpgrp, and this is inherently racy.
7698 execvp_or_die(argv);
7701 static int FAST_FUNC builtin_exit(char **argv)
7703 debug_printf_exec("%s()\n", __func__);
7705 /* interactive bash:
7706 * # trap "echo EEE" EXIT
7709 * There are stopped jobs.
7710 * (if there are _stopped_ jobs, running ones don't count)
7713 # EEE (then bash exits)
7715 * we can use G.exiting = -1 as indicator "last cmd was exit"
7718 /* note: EXIT trap is run by hush_exit */
7719 argv = skip_dash_dash(argv);
7720 if (argv[0] == NULL)
7721 hush_exit(G.last_exitcode);
7722 /* mimic bash: exit 123abc == exit 255 + error msg */
7723 xfunc_error_retval = 255;
7724 /* bash: exit -2 == exit 254, no error msg */
7725 hush_exit(xatoi(argv[0]) & 0xff);
7728 static void print_escaped(const char *s)
7733 const char *p = strchrnul(s, '\'');
7734 /* print 'xxxx', possibly just '' */
7735 printf("'%.*s'", (int)(p - s), s);
7740 /* s points to '; print "'''...'''" */
7742 do putchar('\''); while (*++s == '\'');
7747 #if !ENABLE_HUSH_LOCAL
7748 #define helper_export_local(argv, exp, lvl) \
7749 helper_export_local(argv, exp)
7751 static void helper_export_local(char **argv, int exp, int lvl)
7756 /* So far we do not check that name is valid (TODO?) */
7758 if (strchr(name, '=') == NULL) {
7759 struct variable *var;
7761 var = get_local_var(name);
7762 if (exp == -1) { /* unexporting? */
7763 /* export -n NAME (without =VALUE) */
7765 var->flg_export = 0;
7766 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7768 } /* else: export -n NOT_EXISTING_VAR: no-op */
7771 if (exp == 1) { /* exporting? */
7772 /* export NAME (without =VALUE) */
7774 var->flg_export = 1;
7775 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7776 putenv(var->varstr);
7780 /* Exporting non-existing variable.
7781 * bash does not put it in environment,
7782 * but remembers that it is exported,
7783 * and does put it in env when it is set later.
7784 * We just set it to "" and export. */
7785 /* Or, it's "local NAME" (without =VALUE).
7786 * bash sets the value to "". */
7787 name = xasprintf("%s=", name);
7789 /* (Un)exporting/making local NAME=VALUE */
7790 name = xstrdup(name);
7792 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7796 static int FAST_FUNC builtin_export(char **argv)
7798 unsigned opt_unexport;
7800 #if ENABLE_HUSH_EXPORT_N
7801 /* "!": do not abort on errors */
7802 opt_unexport = getopt32(argv, "!n");
7803 if (opt_unexport == (uint32_t)-1)
7804 return EXIT_FAILURE;
7811 if (argv[0] == NULL) {
7818 /* ash emits: export VAR='VAL'
7819 * bash: declare -x VAR="VAL"
7820 * we follow ash example */
7821 const char *s = *e++;
7822 const char *p = strchr(s, '=');
7824 if (!p) /* wtf? take next variable */
7827 printf("export %.*s", (int)(p - s) + 1, s);
7828 print_escaped(p + 1);
7832 /*fflush_all(); - done after each builtin anyway */
7834 return EXIT_SUCCESS;
7837 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7839 return EXIT_SUCCESS;
7842 #if ENABLE_HUSH_LOCAL
7843 static int FAST_FUNC builtin_local(char **argv)
7845 if (G.func_nest_level == 0) {
7846 bb_error_msg("%s: not in a function", argv[0]);
7847 return EXIT_FAILURE; /* bash compat */
7849 helper_export_local(argv, 0, G.func_nest_level);
7850 return EXIT_SUCCESS;
7854 static int FAST_FUNC builtin_trap(char **argv)
7860 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7865 /* No args: print all trapped */
7866 for (i = 0; i < NSIG; ++i) {
7869 print_escaped(G.traps[i]);
7870 /* note: bash adds "SIG", but only if invoked
7871 * as "bash". If called as "sh", or if set -o posix,
7872 * then it prints short signal names.
7873 * We are printing short names: */
7874 printf(" %s\n", get_signame(i));
7877 /*fflush_all(); - done after each builtin anyway */
7878 return EXIT_SUCCESS;
7882 /* If first arg is a number: reset all specified signals */
7883 sig = bb_strtou(*argv, NULL, 10);
7889 sig = get_signum(*argv++);
7890 if (sig < 0 || sig >= NSIG) {
7892 /* Mimic bash message exactly */
7893 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7898 G.traps[sig] = xstrdup(new_cmd);
7900 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7901 get_signame(sig), sig, G.traps[sig]);
7903 /* There is no signal for 0 (EXIT) */
7908 sigaddset(&G.blocked_set, sig);
7910 /* There was a trap handler, we are removing it
7911 * (if sig has non-DFL handling,
7912 * we don't need to do anything) */
7913 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7915 sigdelset(&G.blocked_set, sig);
7918 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7922 if (!argv[1]) { /* no second arg */
7923 bb_error_msg("trap: invalid arguments");
7924 return EXIT_FAILURE;
7927 /* First arg is "-": reset all specified to default */
7928 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7929 /* Everything else: set arg as signal handler
7930 * (includes "" case, which ignores signal) */
7931 if (argv[0][0] == '-') {
7932 if (argv[0][1] == '\0') { /* "-" */
7933 /* new_cmd remains NULL: "reset these sigs" */
7936 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7939 /* else: "-something", no special meaning */
7944 goto process_sig_list;
7947 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7948 static int FAST_FUNC builtin_type(char **argv)
7950 int ret = EXIT_SUCCESS;
7956 if (0) {} /* make conditional compile easier below */
7957 /*else if (find_alias(*argv))
7958 type = "an alias";*/
7959 #if ENABLE_HUSH_FUNCTIONS
7960 else if (find_function(*argv))
7961 type = "a function";
7963 else if (find_builtin(*argv))
7964 type = "a shell builtin";
7965 else if ((path = find_in_path(*argv)) != NULL)
7968 bb_error_msg("type: %s: not found", *argv);
7973 printf("%s is %s\n", *argv, type);
7981 /* built-in 'fg' and 'bg' handler */
7982 static int FAST_FUNC builtin_fg_bg(char **argv)
7987 if (!G_interactive_fd)
7988 return EXIT_FAILURE;
7990 /* If they gave us no args, assume they want the last backgrounded task */
7992 for (pi = G.job_list; pi; pi = pi->next) {
7993 if (pi->jobid == G.last_jobid) {
7997 bb_error_msg("%s: no current job", argv[0]);
7998 return EXIT_FAILURE;
8000 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8001 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8002 return EXIT_FAILURE;
8004 for (pi = G.job_list; pi; pi = pi->next) {
8005 if (pi->jobid == jobnum) {
8009 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8010 return EXIT_FAILURE;
8012 /* TODO: bash prints a string representation
8013 * of job being foregrounded (like "sleep 1 | cat") */
8014 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8015 /* Put the job into the foreground. */
8016 tcsetpgrp(G_interactive_fd, pi->pgrp);
8019 /* Restart the processes in the job */
8020 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8021 for (i = 0; i < pi->num_cmds; i++) {
8022 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8023 pi->cmds[i].is_stopped = 0;
8025 pi->stopped_cmds = 0;
8027 i = kill(- pi->pgrp, SIGCONT);
8029 if (errno == ESRCH) {
8030 delete_finished_bg_job(pi);
8031 return EXIT_SUCCESS;
8033 bb_perror_msg("kill (SIGCONT)");
8036 if (argv[0][0] == 'f') {
8038 return checkjobs_and_fg_shell(pi);
8040 return EXIT_SUCCESS;
8044 #if ENABLE_HUSH_HELP
8045 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8047 const struct built_in_command *x;
8050 "Built-in commands:\n"
8051 "------------------\n");
8052 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8054 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8057 return EXIT_SUCCESS;
8062 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8065 const char *status_string;
8067 for (job = G.job_list; job; job = job->next) {
8068 if (job->alive_cmds == job->stopped_cmds)
8069 status_string = "Stopped";
8071 status_string = "Running";
8073 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8075 return EXIT_SUCCESS;
8080 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8085 # ifdef M_TRIM_THRESHOLD
8086 /* Optional. Reduces probability of false positives */
8089 /* Crude attempt to find where "free memory" starts,
8090 * sans fragmentation. */
8092 l = (unsigned long)p;
8095 if (l < (unsigned long)p) l = (unsigned long)p;
8098 if (!G.memleak_value)
8099 G.memleak_value = l;
8101 l -= G.memleak_value;
8108 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8113 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8116 return EXIT_SUCCESS;
8119 static int FAST_FUNC builtin_read(char **argv)
8128 /* "!": do not abort on errors.
8129 * Option string must start with "sr" to match BUILTIN_READ_xxx
8131 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8132 if (read_flags == (uint32_t)-1)
8133 return EXIT_FAILURE;
8136 r = shell_builtin_read(set_local_var_from_halves,
8138 get_local_var_value("IFS"), /* can be NULL */
8146 if ((uintptr_t)r > 1) {
8147 bb_error_msg("%s", r);
8148 r = (char*)(uintptr_t)1;
8151 return (uintptr_t)r;
8154 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8155 * built-in 'set' handler
8157 * set [-abCefhmnuvx] [-o option] [argument...]
8158 * set [+abCefhmnuvx] [+o option] [argument...]
8159 * set -- [argument...]
8162 * Implementations shall support the options in both their hyphen and
8163 * plus-sign forms. These options can also be specified as options to sh.
8165 * Write out all variables and their values: set
8166 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8167 * Turn on the -x and -v options: set -xv
8168 * Unset all positional parameters: set --
8169 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8170 * Set the positional parameters to the expansion of x, even if x expands
8171 * with a leading '-' or '+': set -- $x
8173 * So far, we only support "set -- [argument...]" and some of the short names.
8175 static int FAST_FUNC builtin_set(char **argv)
8178 char **pp, **g_argv;
8179 char *arg = *++argv;
8183 for (e = G.top_var; e; e = e->next)
8185 return EXIT_SUCCESS;
8189 if (!strcmp(arg, "--")) {
8193 if (arg[0] != '+' && arg[0] != '-')
8195 for (n = 1; arg[n]; ++n)
8196 if (set_mode(arg[0], arg[n]))
8198 } while ((arg = *++argv) != NULL);
8199 /* Now argv[0] is 1st argument */
8202 return EXIT_SUCCESS;
8205 /* NB: G.global_argv[0] ($0) is never freed/changed */
8206 g_argv = G.global_argv;
8207 if (G.global_args_malloced) {
8213 G.global_args_malloced = 1;
8214 pp = xzalloc(sizeof(pp[0]) * 2);
8215 pp[0] = g_argv[0]; /* retain $0 */
8218 /* This realloc's G.global_argv */
8219 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8226 return EXIT_SUCCESS;
8228 /* Nothing known, so abort */
8230 bb_error_msg("set: %s: invalid option", arg);
8231 return EXIT_FAILURE;
8234 static int FAST_FUNC builtin_shift(char **argv)
8237 argv = skip_dash_dash(argv);
8241 if (n >= 0 && n < G.global_argc) {
8242 if (G.global_args_malloced) {
8245 free(G.global_argv[m++]);
8248 memmove(&G.global_argv[1], &G.global_argv[n+1],
8249 G.global_argc * sizeof(G.global_argv[0]));
8250 return EXIT_SUCCESS;
8252 return EXIT_FAILURE;
8255 static int FAST_FUNC builtin_source(char **argv)
8257 char *arg_path, *filename;
8260 #if ENABLE_HUSH_FUNCTIONS
8264 argv = skip_dash_dash(argv);
8267 /* bash says: "bash: .: filename argument required" */
8268 return 2; /* bash compat */
8271 if (!strchr(filename, '/')) {
8272 arg_path = find_in_path(filename);
8274 filename = arg_path;
8276 input = fopen_or_warn(filename, "r");
8279 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8280 return EXIT_FAILURE;
8282 close_on_exec_on(fileno(input));
8284 #if ENABLE_HUSH_FUNCTIONS
8285 sv_flg = G.flag_return_in_progress;
8286 /* "we are inside sourced file, ok to use return" */
8287 G.flag_return_in_progress = -1;
8289 save_and_replace_G_args(&sv, argv);
8291 parse_and_run_file(input);
8294 restore_G_args(&sv, argv);
8295 #if ENABLE_HUSH_FUNCTIONS
8296 G.flag_return_in_progress = sv_flg;
8299 return G.last_exitcode;
8302 static int FAST_FUNC builtin_umask(char **argv)
8308 argv = skip_dash_dash(argv);
8310 mode_t old_mask = mask;
8313 rc = bb_parse_mode(argv[0], &mask);
8318 * bash: umask: 'q': invalid symbolic mode operator
8319 * bash: umask: 999: octal number out of range
8321 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8326 printf("%04o\n", (unsigned) mask);
8327 /* fall through and restore mask which we set to 0 */
8331 return !rc; /* rc != 0 - success */
8334 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8335 static int FAST_FUNC builtin_unset(char **argv)
8340 /* "!": do not abort on errors */
8341 /* "+": stop at 1st non-option */
8342 opts = getopt32(argv, "!+vf");
8343 if (opts == (unsigned)-1)
8344 return EXIT_FAILURE;
8346 bb_error_msg("unset: -v and -f are exclusive");
8347 return EXIT_FAILURE;
8353 if (!(opts & 2)) { /* not -f */
8354 if (unset_local_var(*argv)) {
8355 /* unset <nonexistent_var> doesn't fail.
8356 * Error is when one tries to unset RO var.
8357 * Message was printed by unset_local_var. */
8361 #if ENABLE_HUSH_FUNCTIONS
8371 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8372 static int FAST_FUNC builtin_wait(char **argv)
8374 int ret = EXIT_SUCCESS;
8377 argv = skip_dash_dash(argv);
8378 if (argv[0] == NULL) {
8379 /* Don't care about wait results */
8380 /* Note 1: must wait until there are no more children */
8381 /* Note 2: must be interruptible */
8383 * $ sleep 3 & sleep 6 & wait
8388 * $ sleep 3 & sleep 6 & wait
8392 * ^C <-- after ~4 sec from keyboard
8395 sigaddset(&G.blocked_set, SIGCHLD);
8396 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8399 if (errno == ECHILD)
8401 /* Wait for SIGCHLD or any other signal of interest */
8402 /* sigtimedwait with infinite timeout: */
8403 sig = sigwaitinfo(&G.blocked_set, NULL);
8405 sig = check_and_run_traps(sig);
8406 if (sig && sig != SIGCHLD) { /* see note 2 */
8412 sigdelset(&G.blocked_set, SIGCHLD);
8413 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8417 /* This is probably buggy wrt interruptible-ness */
8419 pid_t pid = bb_strtou(*argv, NULL, 10);
8421 /* mimic bash message */
8422 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8423 return EXIT_FAILURE;
8425 if (waitpid(pid, &status, 0) == pid) {
8426 if (WIFSIGNALED(status))
8427 ret = 128 + WTERMSIG(status);
8428 else if (WIFEXITED(status))
8429 ret = WEXITSTATUS(status);
8433 bb_perror_msg("wait %s", *argv);
8442 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8443 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8446 def = bb_strtou(argv[1], NULL, 10);
8447 if (errno || def < def_min || argv[2]) {
8448 bb_error_msg("%s: bad arguments", argv[0]);
8456 #if ENABLE_HUSH_LOOPS
8457 static int FAST_FUNC builtin_break(char **argv)
8460 if (G.depth_of_loop == 0) {
8461 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8462 return EXIT_SUCCESS; /* bash compat */
8464 G.flag_break_continue++; /* BC_BREAK = 1 */
8466 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8467 if (depth == UINT_MAX)
8468 G.flag_break_continue = BC_BREAK;
8469 if (G.depth_of_loop < depth)
8470 G.depth_break_continue = G.depth_of_loop;
8472 return EXIT_SUCCESS;
8475 static int FAST_FUNC builtin_continue(char **argv)
8477 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8478 return builtin_break(argv);
8482 #if ENABLE_HUSH_FUNCTIONS
8483 static int FAST_FUNC builtin_return(char **argv)
8487 if (G.flag_return_in_progress != -1) {
8488 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8489 return EXIT_FAILURE; /* bash compat */
8492 G.flag_return_in_progress = 1;
8495 * out of range: wraps around at 256, does not error out
8496 * non-numeric param:
8497 * f() { false; return qwe; }; f; echo $?
8498 * bash: return: qwe: numeric argument required <== we do this
8499 * 255 <== we also do this
8501 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);