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 (22k). 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. Adds ~300 bytes.
227 //usage:#define hush_trivial_usage NOUSAGE_STR
228 //usage:#define hush_full_usage ""
229 //usage:#define lash_trivial_usage NOUSAGE_STR
230 //usage:#define lash_full_usage ""
231 //usage:#define msh_trivial_usage NOUSAGE_STR
232 //usage:#define msh_full_usage ""
236 #define LEAK_HUNTING 0
237 #define BUILD_AS_NOMMU 0
238 /* Enable/disable sanity checks. Ok to enable in production,
239 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
240 * Keeping 1 for now even in released versions.
243 /* Slightly bigger (+200 bytes), but faster hush.
244 * So far it only enables a trick with counting SIGCHLDs and forks,
245 * which allows us to do fewer waitpid's.
246 * (we can detect a case where neither forks were done nor SIGCHLDs happened
247 * and therefore waitpid will return the same result as last time)
249 #define ENABLE_HUSH_FAST 0
250 /* TODO: implement simplified code for users which do not need ${var%...} ops
251 * So far ${var%...} ops are always enabled:
253 #define ENABLE_HUSH_DOLLAR_OPS 1
258 # undef USE_FOR_NOMMU
261 # define USE_FOR_NOMMU(...) __VA_ARGS__
262 # define USE_FOR_MMU(...)
265 #include "NUM_APPLETS.h"
267 /* STANDALONE does not make sense, and won't compile */
268 # undef CONFIG_FEATURE_SH_STANDALONE
269 # undef ENABLE_FEATURE_SH_STANDALONE
270 # undef IF_FEATURE_SH_STANDALONE
271 # undef IF_NOT_FEATURE_SH_STANDALONE
272 # define ENABLE_FEATURE_SH_STANDALONE 0
273 # define IF_FEATURE_SH_STANDALONE(...)
274 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
277 #if !ENABLE_HUSH_INTERACTIVE
278 # undef ENABLE_FEATURE_EDITING
279 # define ENABLE_FEATURE_EDITING 0
280 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
281 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
284 /* Do we support ANY keywords? */
285 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
286 # define HAS_KEYWORDS 1
287 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
288 # define IF_HAS_NO_KEYWORDS(...)
290 # define HAS_KEYWORDS 0
291 # define IF_HAS_KEYWORDS(...)
292 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
295 /* If you comment out one of these below, it will be #defined later
296 * to perform debug printfs to stderr: */
297 #define debug_printf(...) do {} while (0)
298 /* Finer-grained debug switches */
299 #define debug_printf_parse(...) do {} while (0)
300 #define debug_print_tree(a, b) do {} while (0)
301 #define debug_printf_exec(...) do {} while (0)
302 #define debug_printf_env(...) do {} while (0)
303 #define debug_printf_jobs(...) do {} while (0)
304 #define debug_printf_expand(...) do {} while (0)
305 #define debug_printf_varexp(...) do {} while (0)
306 #define debug_printf_glob(...) do {} while (0)
307 #define debug_printf_list(...) do {} while (0)
308 #define debug_printf_subst(...) do {} while (0)
309 #define debug_printf_clean(...) do {} while (0)
311 #define ERR_PTR ((void*)(long)1)
313 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
315 #define _SPECIAL_VARS_STR "_*@$!?#"
316 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
317 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
319 #define SPECIAL_VAR_SYMBOL 3
323 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
325 /* This supports saving pointers malloced in vfork child,
326 * to be freed in the parent.
329 typedef struct nommu_save_t {
331 struct variable *old_vars;
333 char **argv_from_re_execing;
337 typedef enum reserved_style {
346 #if ENABLE_HUSH_LOOPS
353 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
358 /* three pseudo-keywords support contrived "case" syntax: */
359 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
360 RES_MATCH , /* "word)" */
361 RES_CASE_BODY, /* "this command is inside CASE" */
368 typedef struct o_string {
370 int length; /* position where data is appended */
372 /* Protect newly added chars against globbing
373 * (by prepending \ to *, ?, [, \) */
376 /* At least some part of the string was inside '' or "",
377 * possibly empty one: word"", wo''rd etc. */
379 smallint has_empty_slot;
380 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
383 MAYBE_ASSIGNMENT = 0,
384 DEFINITELY_ASSIGNMENT = 1,
386 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
388 /* Used for initialization: o_string foo = NULL_O_STRING; */
389 #define NULL_O_STRING { NULL }
391 /* I can almost use ordinary FILE*. Is open_memstream() universally
392 * available? Where is it documented? */
393 typedef struct in_str {
395 /* eof_flag=1: last char in ->p is really an EOF */
396 char eof_flag; /* meaningless if ->p == NULL */
398 #if ENABLE_HUSH_INTERACTIVE
400 smallint promptmode; /* 0: PS1, 1: PS2 */
403 int (*get) (struct in_str *) FAST_FUNC;
404 int (*peek) (struct in_str *) FAST_FUNC;
406 #define i_getch(input) ((input)->get(input))
407 #define i_peek(input) ((input)->peek(input))
409 /* The descrip member of this structure is only used to make
410 * debugging output pretty */
411 static const struct {
413 signed char default_fd;
416 { O_RDONLY, 0, "<" },
417 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
418 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
419 { O_CREAT|O_RDWR, 1, "<>" },
420 { O_RDONLY, 0, "<<" },
421 /* Should not be needed. Bogus default_fd helps in debugging */
422 /* { O_RDONLY, 77, "<<" }, */
425 struct redir_struct {
426 struct redir_struct *next;
427 char *rd_filename; /* filename */
428 int rd_fd; /* fd to redirect */
429 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
431 smallint rd_type; /* (enum redir_type) */
432 /* note: for heredocs, rd_filename contains heredoc delimiter,
433 * and subsequently heredoc itself; and rd_dup is a bitmask:
434 * bit 0: do we need to trim leading tabs?
435 * bit 1: is heredoc quoted (<<'delim' syntax) ?
438 typedef enum redir_type {
440 REDIRECT_OVERWRITE = 1,
443 REDIRECT_HEREDOC = 4,
444 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
447 REDIRFD_SYNTAX_ERR = -2,
448 REDIRFD_TO_FILE = -1,
449 /* otherwise, rd_fd is redirected to rd_dup */
451 HEREDOC_SKIPTABS = 1,
457 pid_t pid; /* 0 if exited */
458 int assignment_cnt; /* how many argv[i] are assignments? */
459 smallint is_stopped; /* is the command currently running? */
460 smallint cmd_type; /* CMD_xxx */
462 #define CMD_SUBSHELL 1
464 /* used for "[[ EXPR ]]" */
465 #if ENABLE_HUSH_BASH_COMPAT
466 # define CMD_SINGLEWORD_NOGLOB 2
469 /* used for "export noglob=* glob* a=`echo a b`" */
470 //#define CMD_SINGLEWORD_NOGLOB_COND 3
471 // It is hard to implement correctly, it adds significant amounts of tricky code,
472 // and all this is only useful for really obscure export statements
473 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
474 // guards the code which implements it, but I have doubts it works
475 // in all cases (especially with mixed globbed/non-globbed arguments)
477 #if ENABLE_HUSH_FUNCTIONS
478 # define CMD_FUNCDEF 3
481 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
484 char *group_as_string;
486 #if ENABLE_HUSH_FUNCTIONS
487 struct function *child_func;
488 /* This field is used to prevent a bug here:
489 * while...do f1() {a;}; f1; f1() {b;}; f1; done
490 * When we execute "f1() {a;}" cmd, we create new function and clear
491 * cmd->group, cmd->group_as_string, cmd->argv[0].
492 * When we execute "f1() {b;}", we notice that f1 exists,
493 * and that its "parent cmd" struct is still "alive",
494 * we put those fields back into cmd->xxx
495 * (struct function has ->parent_cmd ptr to facilitate that).
496 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
497 * Without this trick, loop would execute a;b;b;b;...
498 * instead of correct sequence a;b;a;b;...
499 * When command is freed, it severs the link
500 * (sets ->child_func->parent_cmd to NULL).
503 char **argv; /* command name and arguments */
504 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
505 * and on execution these are substituted with their values.
506 * Substitution can make _several_ words out of one argv[n]!
507 * Example: argv[0]=='.^C*^C.' here: echo .$*.
508 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
510 struct redir_struct *redirects; /* I/O redirections */
512 /* Is there anything in this command at all? */
513 #define IS_NULL_CMD(cmd) \
514 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
519 int num_cmds; /* total number of commands in pipe */
520 int alive_cmds; /* number of commands running (not exited) */
521 int stopped_cmds; /* number of commands alive, but stopped */
523 int jobid; /* job number */
524 pid_t pgrp; /* process group ID for the job */
525 char *cmdtext; /* name of job */
527 struct command *cmds; /* array of commands in pipe */
528 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
529 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
530 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
532 typedef enum pipe_style {
538 /* Is there anything in this pipe at all? */
539 #define IS_NULL_PIPE(pi) \
540 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
542 /* This holds pointers to the various results of parsing */
543 struct parse_context {
544 /* linked list of pipes */
545 struct pipe *list_head;
546 /* last pipe (being constructed right now) */
548 /* last command in pipe (being constructed right now) */
549 struct command *command;
550 /* last redirect in command->redirects list */
551 struct redir_struct *pending_redirect;
557 smallint ctx_inverted; /* "! cmd | cmd" */
559 smallint ctx_dsemicolon; /* ";;" seen */
561 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
563 /* group we are enclosed in:
564 * example: "if pipe1; pipe2; then pipe3; fi"
565 * when we see "if" or "then", we malloc and copy current context,
566 * and make ->stack point to it. then we parse pipeN.
567 * when closing "then" / fi" / whatever is found,
568 * we move list_head into ->stack->command->group,
569 * copy ->stack into current context, and delete ->stack.
570 * (parsing of { list } and ( list ) doesn't use this method)
572 struct parse_context *stack;
576 /* On program start, environ points to initial environment.
577 * putenv adds new pointers into it, unsetenv removes them.
578 * Neither of these (de)allocates the strings.
579 * setenv allocates new strings in malloc space and does putenv,
580 * and thus setenv is unusable (leaky) for shell's purposes */
581 #define setenv(...) setenv_is_leaky_dont_use()
583 struct variable *next;
584 char *varstr; /* points to "name=" portion */
585 #if ENABLE_HUSH_LOCAL
586 unsigned func_nest_level;
588 int max_len; /* if > 0, name is part of initial env; else name is malloced */
589 smallint flg_export; /* putenv should be done on this var */
590 smallint flg_read_only;
598 #if ENABLE_HUSH_FUNCTIONS
600 struct function *next;
602 struct command *parent_cmd;
605 char *body_as_string;
611 /* "Globals" within this file */
612 /* Sorted roughly by size (smaller offsets == smaller code) */
614 /* interactive_fd != 0 means we are an interactive shell.
615 * If we are, then saved_tty_pgrp can also be != 0, meaning
616 * that controlling tty is available. With saved_tty_pgrp == 0,
617 * job control still works, but terminal signals
618 * (^C, ^Z, ^Y, ^\) won't work at all, and background
619 * process groups can only be created with "cmd &".
620 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
621 * to give tty to the foreground process group,
622 * and will take it back when the group is stopped (^Z)
625 #if ENABLE_HUSH_INTERACTIVE
626 /* 'interactive_fd' is a fd# open to ctty, if we have one
627 * _AND_ if we decided to act interactively */
631 # define G_interactive_fd (G.interactive_fd)
633 # define G_interactive_fd 0
635 #if ENABLE_FEATURE_EDITING
636 line_input_t *line_input_state;
641 #if ENABLE_HUSH_RANDOM_SUPPORT
647 pid_t saved_tty_pgrp;
648 struct pipe *job_list;
649 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
651 # define G_saved_tty_pgrp 0
653 smallint flag_SIGINT;
654 #if ENABLE_HUSH_LOOPS
655 smallint flag_break_continue;
657 #if ENABLE_HUSH_FUNCTIONS
658 /* 0: outside of a function (or sourced file)
659 * -1: inside of a function, ok to use return builtin
660 * 1: return is invoked, skip all till end of func
662 smallint flag_return_in_progress;
665 #if ENABLE_HUSH_MODE_X
667 # define G_x_mode G.x_mode
671 smallint exiting; /* used to prevent EXIT trap recursion */
672 /* These four support $?, $#, and $1 */
673 smalluint last_exitcode;
674 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
675 smalluint global_args_malloced;
676 smalluint inherited_set_is_saved;
677 /* how many non-NULL argv's we have. NB: $# + 1 */
681 char *argv0_for_re_execing;
683 #if ENABLE_HUSH_LOOPS
684 unsigned depth_break_continue;
685 unsigned depth_of_loop;
689 struct variable *top_var; /* = &G.shell_ver (set in main()) */
690 struct variable shell_ver;
691 #if ENABLE_HUSH_FUNCTIONS
692 struct function *top_func;
693 # if ENABLE_HUSH_LOCAL
694 struct variable **shadowed_vars_pp;
695 unsigned func_nest_level;
698 /* Signal and trap handling */
700 unsigned count_SIGCHLD;
701 unsigned handled_SIGCHLD;
702 smallint we_have_children;
704 /* which signals have non-DFL handler (even with no traps set)? */
705 unsigned non_DFL_mask;
706 char **traps; /* char *traps[NSIG] */
707 sigset_t blocked_set;
708 sigset_t inherited_set;
710 unsigned long memleak_value;
713 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
715 #define G (*ptr_to_globals)
716 /* Not #defining name to G.name - this quickly gets unwieldy
717 * (too many defines). Also, I actually prefer to see when a variable
718 * is global, thus "G." prefix is a useful hint */
719 #define INIT_G() do { \
720 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
724 /* Function prototypes for builtins */
725 static int builtin_cd(char **argv) FAST_FUNC;
726 static int builtin_echo(char **argv) FAST_FUNC;
727 static int builtin_eval(char **argv) FAST_FUNC;
728 static int builtin_exec(char **argv) FAST_FUNC;
729 static int builtin_exit(char **argv) FAST_FUNC;
730 static int builtin_export(char **argv) FAST_FUNC;
732 static int builtin_fg_bg(char **argv) FAST_FUNC;
733 static int builtin_jobs(char **argv) FAST_FUNC;
736 static int builtin_help(char **argv) FAST_FUNC;
738 #if ENABLE_HUSH_LOCAL
739 static int builtin_local(char **argv) FAST_FUNC;
742 static int builtin_memleak(char **argv) FAST_FUNC;
745 static int builtin_printf(char **argv) FAST_FUNC;
747 static int builtin_pwd(char **argv) FAST_FUNC;
748 static int builtin_read(char **argv) FAST_FUNC;
749 static int builtin_set(char **argv) FAST_FUNC;
750 static int builtin_shift(char **argv) FAST_FUNC;
751 static int builtin_source(char **argv) FAST_FUNC;
752 static int builtin_test(char **argv) FAST_FUNC;
753 static int builtin_trap(char **argv) FAST_FUNC;
754 static int builtin_type(char **argv) FAST_FUNC;
755 static int builtin_true(char **argv) FAST_FUNC;
756 static int builtin_umask(char **argv) FAST_FUNC;
757 static int builtin_unset(char **argv) FAST_FUNC;
758 static int builtin_wait(char **argv) FAST_FUNC;
759 #if ENABLE_HUSH_LOOPS
760 static int builtin_break(char **argv) FAST_FUNC;
761 static int builtin_continue(char **argv) FAST_FUNC;
763 #if ENABLE_HUSH_FUNCTIONS
764 static int builtin_return(char **argv) FAST_FUNC;
767 /* Table of built-in functions. They can be forked or not, depending on
768 * context: within pipes, they fork. As simple commands, they do not.
769 * When used in non-forking context, they can change global variables
770 * in the parent shell process. If forked, of course they cannot.
771 * For example, 'unset foo | whatever' will parse and run, but foo will
772 * still be set at the end. */
773 struct built_in_command {
775 int (*b_function)(char **argv) FAST_FUNC;
778 # define BLTIN(cmd, func, help) { cmd, func, help }
780 # define BLTIN(cmd, func, help) { cmd, func }
784 static const struct built_in_command bltins1[] = {
785 BLTIN("." , builtin_source , "Run commands in a file"),
786 BLTIN(":" , builtin_true , NULL),
788 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
790 #if ENABLE_HUSH_LOOPS
791 BLTIN("break" , builtin_break , "Exit from a loop"),
793 BLTIN("cd" , builtin_cd , "Change directory"),
794 #if ENABLE_HUSH_LOOPS
795 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
797 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
798 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
799 BLTIN("exit" , builtin_exit , "Exit"),
800 BLTIN("export" , builtin_export , "Set environment variables"),
802 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
805 BLTIN("help" , builtin_help , NULL),
808 BLTIN("jobs" , builtin_jobs , "List jobs"),
810 #if ENABLE_HUSH_LOCAL
811 BLTIN("local" , builtin_local , "Set local variables"),
814 BLTIN("memleak" , builtin_memleak , NULL),
816 BLTIN("read" , builtin_read , "Input into variable"),
817 #if ENABLE_HUSH_FUNCTIONS
818 BLTIN("return" , builtin_return , "Return from a function"),
820 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
821 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
822 #if ENABLE_HUSH_BASH_COMPAT
823 BLTIN("source" , builtin_source , "Run commands in a file"),
825 BLTIN("trap" , builtin_trap , "Trap signals"),
826 BLTIN("type" , builtin_type , "Show command type"),
827 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
828 BLTIN("umask" , builtin_umask , "Set file creation mask"),
829 BLTIN("unset" , builtin_unset , "Unset variables"),
830 BLTIN("wait" , builtin_wait , "Wait for process"),
832 /* For now, echo and test are unconditionally enabled.
833 * Maybe make it configurable? */
834 static const struct built_in_command bltins2[] = {
835 BLTIN("[" , builtin_test , NULL),
836 BLTIN("echo" , builtin_echo , NULL),
838 BLTIN("printf" , builtin_printf , NULL),
840 BLTIN("pwd" , builtin_pwd , NULL),
841 BLTIN("test" , builtin_test , NULL),
848 /* prevent disasters with G.debug_indent < 0 */
849 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
850 # define debug_enter() (G.debug_indent++)
851 # define debug_leave() (G.debug_indent--)
853 # define indent() ((void)0)
854 # define debug_enter() ((void)0)
855 # define debug_leave() ((void)0)
859 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
862 #ifndef debug_printf_parse
863 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
866 #ifndef debug_printf_exec
867 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
870 #ifndef debug_printf_env
871 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
874 #ifndef debug_printf_jobs
875 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
876 # define DEBUG_JOBS 1
878 # define DEBUG_JOBS 0
881 #ifndef debug_printf_expand
882 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
883 # define DEBUG_EXPAND 1
885 # define DEBUG_EXPAND 0
888 #ifndef debug_printf_varexp
889 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 #ifndef debug_printf_glob
893 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
894 # define DEBUG_GLOB 1
896 # define DEBUG_GLOB 0
899 #ifndef debug_printf_list
900 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
903 #ifndef debug_printf_subst
904 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
907 #ifndef debug_printf_clean
908 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 # define DEBUG_CLEAN 1
911 # define DEBUG_CLEAN 0
915 static void debug_print_strings(const char *prefix, char **vv)
918 fprintf(stderr, "%s:\n", prefix);
920 fprintf(stderr, " '%s'\n", *vv++);
923 # define debug_print_strings(prefix, vv) ((void)0)
927 /* Leak hunting. Use hush_leaktool.sh for post-processing.
930 static void *xxmalloc(int lineno, size_t size)
932 void *ptr = xmalloc((size + 0xff) & ~0xff);
933 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
936 static void *xxrealloc(int lineno, void *ptr, size_t size)
938 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
939 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
942 static char *xxstrdup(int lineno, const char *str)
944 char *ptr = xstrdup(str);
945 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
948 static void xxfree(void *ptr)
950 fdprintf(2, "free %p\n", ptr);
953 # define xmalloc(s) xxmalloc(__LINE__, s)
954 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
955 # define xstrdup(s) xxstrdup(__LINE__, s)
956 # define free(p) xxfree(p)
960 /* Syntax and runtime errors. They always abort scripts.
961 * In interactive use they usually discard unparsed and/or unexecuted commands
962 * and return to the prompt.
963 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
966 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
967 # define syntax_error(lineno, msg) syntax_error(msg)
968 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
969 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
970 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
971 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
974 static void die_if_script(unsigned lineno, const char *fmt, ...)
979 bb_error_msg("hush.c:%u", lineno);
982 bb_verror_msg(fmt, p, NULL);
984 if (!G_interactive_fd)
988 static void syntax_error(unsigned lineno, const char *msg)
991 die_if_script(lineno, "syntax error: %s", msg);
993 die_if_script(lineno, "syntax error", NULL);
996 static void syntax_error_at(unsigned lineno, const char *msg)
998 die_if_script(lineno, "syntax error at '%s'", msg);
1001 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1003 die_if_script(lineno, "syntax error: unterminated %s", s);
1006 /* It so happens that all such cases are totally fatal
1007 * even if shell is interactive: EOF while looking for closing
1008 * delimiter. There is nowhere to read stuff from after that,
1009 * it's EOF! The only choice is to terminate.
1011 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1012 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1014 char msg[2] = { ch, '\0' };
1015 syntax_error_unterm_str(lineno, msg);
1019 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1024 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1028 # undef die_if_script
1029 # undef syntax_error
1030 # undef syntax_error_at
1031 # undef syntax_error_unterm_ch
1032 # undef syntax_error_unterm_str
1033 # undef syntax_error_unexpected_ch
1035 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1036 # define syntax_error(msg) syntax_error(__LINE__, msg)
1037 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1038 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1039 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1040 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1044 #if ENABLE_HUSH_INTERACTIVE
1045 static void cmdedit_update_prompt(void);
1047 # define cmdedit_update_prompt() ((void)0)
1051 /* Utility functions
1053 /* Replace each \x with x in place, return ptr past NUL. */
1054 static char *unbackslash(char *src)
1056 char *dst = src = strchrnul(src, '\\');
1060 if ((*dst++ = *src++) == '\0')
1066 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1087 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1088 v[count1 + count2] = NULL;
1091 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1095 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1097 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1098 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1101 #define add_strings_to_strings(strings, add, need_to_dup) \
1102 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1105 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1106 static char **add_string_to_strings(char **strings, char *add)
1111 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1114 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1116 char **ptr = add_string_to_strings(strings, add);
1117 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1120 #define add_string_to_strings(strings, add) \
1121 xx_add_string_to_strings(__LINE__, strings, add)
1124 static void free_strings(char **strings)
1139 /* Helpers for setting new $n and restoring them back
1141 typedef struct save_arg_t {
1145 smallint sv_g_malloced;
1148 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1152 sv->sv_argv0 = argv[0];
1153 sv->sv_g_argv = G.global_argv;
1154 sv->sv_g_argc = G.global_argc;
1155 sv->sv_g_malloced = G.global_args_malloced;
1157 argv[0] = G.global_argv[0]; /* retain $0 */
1158 G.global_argv = argv;
1159 G.global_args_malloced = 0;
1167 static void restore_G_args(save_arg_t *sv, char **argv)
1171 if (G.global_args_malloced) {
1172 /* someone ran "set -- arg1 arg2 ...", undo */
1174 while (*++pp) /* note: does not free $0 */
1176 free(G.global_argv);
1178 argv[0] = sv->sv_argv0;
1179 G.global_argv = sv->sv_g_argv;
1180 G.global_argc = sv->sv_g_argc;
1181 G.global_args_malloced = sv->sv_g_malloced;
1185 /* Basic theory of signal handling in shell
1186 * ========================================
1187 * This does not describe what hush does, rather, it is current understanding
1188 * what it _should_ do. If it doesn't, it's a bug.
1189 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1191 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1192 * is finished or backgrounded. It is the same in interactive and
1193 * non-interactive shells, and is the same regardless of whether
1194 * a user trap handler is installed or a shell special one is in effect.
1195 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1196 * backgrounds (i.e. stops) or kills all members of currently running
1199 * Wait builtin in interruptible by signals for which user trap is set
1200 * or by SIGINT in interactive shell.
1202 * Trap handlers will execute even within trap handlers. (right?)
1204 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1205 * except for handlers set to '' (empty string).
1207 * If job control is off, backgrounded commands ("cmd &")
1208 * have SIGINT, SIGQUIT set to SIG_IGN.
1210 * Commands which are run in command substitution ("`cmd`")
1211 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1213 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1214 * by the shell from its parent.
1216 * Signals which differ from SIG_DFL action
1217 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1220 * SIGTERM (interactive): ignore
1221 * SIGHUP (interactive):
1222 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1223 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1224 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1225 * that all pipe members are stopped. Try this in bash:
1226 * while :; do :; done - ^Z does not background it
1227 * (while :; do :; done) - ^Z backgrounds it
1228 * SIGINT (interactive): wait for last pipe, ignore the rest
1229 * of the command line, show prompt. NB: ^C does not send SIGINT
1230 * to interactive shell while shell is waiting for a pipe,
1231 * since shell is bg'ed (is not in foreground process group).
1232 * Example 1: this waits 5 sec, but does not execute ls:
1233 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1234 * Example 2: this does not wait and does not execute ls:
1235 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1236 * Example 3: this does not wait 5 sec, but executes ls:
1237 * "sleep 5; ls -l" + press ^C
1239 * (What happens to signals which are IGN on shell start?)
1240 * (What happens with signal mask on shell start?)
1242 * Implementation in hush
1243 * ======================
1244 * We use in-kernel pending signal mask to determine which signals were sent.
1245 * We block all signals which we don't want to take action immediately,
1246 * i.e. we block all signals which need to have special handling as described
1247 * above, and all signals which have traps set.
1248 * After each pipe execution, we extract any pending signals via sigtimedwait()
1251 * unsigned non_DFL_mask: a mask of such "special" signals
1252 * sigset_t blocked_set: current blocked signal set
1255 * clear bit in blocked_set unless it is also in non_DFL_mask
1256 * "trap 'cmd' SIGxxx":
1257 * set bit in blocked_set (even if 'cmd' is '')
1258 * after [v]fork, if we plan to be a shell:
1259 * unblock signals with special interactive handling
1260 * (child shell is not interactive),
1261 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1262 * after [v]fork, if we plan to exec:
1263 * POSIX says fork clears pending signal mask in child - no need to clear it.
1264 * Restore blocked signal set to one inherited by shell just prior to exec.
1266 * Note: as a result, we do not use signal handlers much. The only uses
1267 * are to count SIGCHLDs
1268 * and to restore tty pgrp on signal-induced exit.
1271 * Standard says "When a subshell is entered, traps that are not being ignored
1272 * are set to the default actions". bash interprets it so that traps which
1273 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1276 SPECIAL_INTERACTIVE_SIGS = 0
1281 SPECIAL_JOB_SIGS = 0
1289 #if ENABLE_HUSH_FAST
1290 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1293 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1299 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1300 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1301 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1302 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1304 /* Restores tty foreground process group, and exits.
1305 * May be called as signal handler for fatal signal
1306 * (will resend signal to itself, producing correct exit state)
1307 * or called directly with -EXITCODE.
1308 * We also call it if xfunc is exiting. */
1309 static void sigexit(int sig) NORETURN;
1310 static void sigexit(int sig)
1312 /* Disable all signals: job control, SIGPIPE, etc. */
1313 sigprocmask_allsigs(SIG_BLOCK);
1315 /* Careful: we can end up here after [v]fork. Do not restore
1316 * tty pgrp then, only top-level shell process does that */
1317 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1318 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1320 /* Not a signal, just exit */
1324 kill_myself_with_sig(sig); /* does not return */
1328 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1329 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1333 /* Restores tty foreground process group, and exits. */
1334 static void hush_exit(int exitcode) NORETURN;
1335 static void hush_exit(int exitcode)
1337 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1338 /* Prevent recursion:
1339 * trap "echo Hi; exit" EXIT; exit
1341 char *argv[] = { NULL, G.traps[0], NULL };
1350 sigexit(- (exitcode & 0xff));
1356 static int check_and_run_traps(int sig)
1358 static const struct timespec zero_timespec;
1359 smalluint save_rcode;
1365 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1370 if (G.traps && G.traps[sig]) {
1371 if (G.traps[sig][0]) {
1372 /* We have user-defined handler */
1373 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1374 save_rcode = G.last_exitcode;
1377 G.last_exitcode = save_rcode;
1378 } /* else: "" trap, ignoring signal */
1381 /* not a trap: special action */
1383 #if ENABLE_HUSH_FAST
1386 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1390 /* Builtin was ^C'ed, make it look prettier: */
1397 /* bash is observed to signal whole process groups,
1398 * not individual processes */
1399 for (job = G.job_list; job; job = job->next) {
1402 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1403 if (kill(- job->pgrp, SIGHUP) == 0)
1404 kill(- job->pgrp, SIGCONT);
1409 default: /* ignored: */
1410 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1418 static const char *get_cwd(int force)
1420 if (force || G.cwd == NULL) {
1421 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1422 * we must not try to free(bb_msg_unknown) */
1423 if (G.cwd == bb_msg_unknown)
1425 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1427 G.cwd = bb_msg_unknown;
1434 * Shell and environment variable support
1436 static struct variable **get_ptr_to_local_var(const char *name)
1438 struct variable **pp;
1439 struct variable *cur;
1444 while ((cur = *pp) != NULL) {
1445 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1452 static struct variable *get_local_var(const char *name)
1454 struct variable **pp = get_ptr_to_local_var(name);
1460 static const char* FAST_FUNC get_local_var_value(const char *name)
1462 struct variable **pp = get_ptr_to_local_var(name);
1464 return strchr((*pp)->varstr, '=') + 1;
1465 if (strcmp(name, "PPID") == 0)
1466 return utoa(G.root_ppid);
1467 // bash compat: UID? EUID?
1468 #if ENABLE_HUSH_RANDOM_SUPPORT
1469 if (strcmp(name, "RANDOM") == 0) {
1470 return utoa(next_random(&G.random_gen));
1476 /* str holds "NAME=VAL" and is expected to be malloced.
1477 * We take ownership of it.
1479 * 0: do not change export flag
1480 * (if creating new variable, flag will be 0)
1481 * 1: set export flag and putenv the variable
1482 * -1: clear export flag and unsetenv the variable
1483 * flg_read_only is set only when we handle -R var=val
1485 #if !BB_MMU && ENABLE_HUSH_LOCAL
1486 /* all params are used */
1487 #elif BB_MMU && ENABLE_HUSH_LOCAL
1488 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1489 set_local_var(str, flg_export, local_lvl)
1490 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1491 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1492 set_local_var(str, flg_export)
1493 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1494 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1495 set_local_var(str, flg_export, flg_read_only)
1497 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1499 struct variable **var_pp;
1500 struct variable *cur;
1504 eq_sign = strchr(str, '=');
1505 if (!eq_sign) { /* not expected to ever happen? */
1510 name_len = eq_sign - str + 1; /* including '=' */
1511 var_pp = &G.top_var;
1512 while ((cur = *var_pp) != NULL) {
1513 if (strncmp(cur->varstr, str, name_len) != 0) {
1514 var_pp = &cur->next;
1517 /* We found an existing var with this name */
1518 if (cur->flg_read_only) {
1522 bb_error_msg("%s: readonly variable", str);
1526 if (flg_export == -1) { // "&& cur->flg_export" ?
1527 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1532 #if ENABLE_HUSH_LOCAL
1533 if (cur->func_nest_level < local_lvl) {
1534 /* New variable is declared as local,
1535 * and existing one is global, or local
1536 * from enclosing function.
1537 * Remove and save old one: */
1538 *var_pp = cur->next;
1539 cur->next = *G.shadowed_vars_pp;
1540 *G.shadowed_vars_pp = cur;
1541 /* bash 3.2.33(1) and exported vars:
1543 * # f() { local z=a; env | grep ^z; }
1549 if (cur->flg_export)
1554 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1559 if (cur->max_len != 0) {
1560 if (cur->max_len >= strlen(str)) {
1561 /* This one is from startup env, reuse space */
1562 strcpy(cur->varstr, str);
1566 /* max_len == 0 signifies "malloced" var, which we can
1567 * (and has to) free */
1571 goto set_str_and_exp;
1574 /* Not found - create new variable struct */
1575 cur = xzalloc(sizeof(*cur));
1576 #if ENABLE_HUSH_LOCAL
1577 cur->func_nest_level = local_lvl;
1579 cur->next = *var_pp;
1585 cur->flg_read_only = flg_read_only;
1588 if (flg_export == 1)
1589 cur->flg_export = 1;
1590 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1591 cmdedit_update_prompt();
1592 if (cur->flg_export) {
1593 if (flg_export == -1) {
1594 cur->flg_export = 0;
1595 /* unsetenv was already done */
1597 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1598 return putenv(cur->varstr);
1604 /* Used at startup and after each cd */
1605 static void set_pwd_var(int exp)
1607 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1608 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1611 static int unset_local_var_len(const char *name, int name_len)
1613 struct variable *cur;
1614 struct variable **var_pp;
1617 return EXIT_SUCCESS;
1618 var_pp = &G.top_var;
1619 while ((cur = *var_pp) != NULL) {
1620 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1621 if (cur->flg_read_only) {
1622 bb_error_msg("%s: readonly variable", name);
1623 return EXIT_FAILURE;
1625 *var_pp = cur->next;
1626 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1627 bb_unsetenv(cur->varstr);
1628 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1629 cmdedit_update_prompt();
1633 return EXIT_SUCCESS;
1635 var_pp = &cur->next;
1637 return EXIT_SUCCESS;
1640 static int unset_local_var(const char *name)
1642 return unset_local_var_len(name, strlen(name));
1645 static void unset_vars(char **strings)
1653 const char *eq = strchrnul(*v, '=');
1654 unset_local_var_len(*v, (int)(eq - *v));
1660 #if ENABLE_SH_MATH_SUPPORT
1661 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1662 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1663 static char* FAST_FUNC endofname(const char *name)
1671 if (!is_in_name(*p))
1678 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1680 char *var = xasprintf("%s=%s", name, val);
1681 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1686 * Helpers for "var1=val1 var2=val2 cmd" feature
1688 static void add_vars(struct variable *var)
1690 struct variable *next;
1694 var->next = G.top_var;
1696 if (var->flg_export) {
1697 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1698 putenv(var->varstr);
1700 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1706 static struct variable *set_vars_and_save_old(char **strings)
1709 struct variable *old = NULL;
1715 struct variable *var_p;
1716 struct variable **var_pp;
1719 eq = strchr(*s, '=');
1722 var_pp = get_ptr_to_local_var(*s);
1725 /* Remove variable from global linked list */
1727 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1728 *var_pp = var_p->next;
1729 /* Add it to returned list */
1733 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1744 static int FAST_FUNC static_get(struct in_str *i)
1754 static int FAST_FUNC static_peek(struct in_str *i)
1759 #if ENABLE_HUSH_INTERACTIVE
1761 static void cmdedit_update_prompt(void)
1763 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1764 G.PS1 = get_local_var_value("PS1");
1767 G.PS2 = get_local_var_value("PS2");
1775 static const char* setup_prompt_string(int promptmode)
1777 const char *prompt_str;
1778 debug_printf("setup_prompt_string %d ", promptmode);
1779 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1780 /* Set up the prompt */
1781 if (promptmode == 0) { /* PS1 */
1783 /* bash uses $PWD value, even if it is set by user.
1784 * It uses current dir only if PWD is unset.
1785 * We always use current dir. */
1786 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1791 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1792 debug_printf("result '%s'\n", prompt_str);
1796 static void get_user_input(struct in_str *i)
1799 const char *prompt_str;
1801 prompt_str = setup_prompt_string(i->promptmode);
1802 # if ENABLE_FEATURE_EDITING
1803 /* Enable command line editing only while a command line
1804 * is actually being read */
1807 /* buglet: SIGINT will not make new prompt to appear _at once_,
1808 * only after <Enter>. (^C will work) */
1809 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1810 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1811 check_and_run_traps(0);
1812 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1813 i->eof_flag = (r < 0);
1814 if (i->eof_flag) { /* EOF/error detected */
1815 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1816 G.user_input_buf[1] = '\0';
1821 fputs(prompt_str, stdout);
1823 G.user_input_buf[0] = r = fgetc(i->file);
1824 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1825 //do we need check_and_run_traps(0)? (maybe only if stdin)
1826 } while (G.flag_SIGINT);
1827 i->eof_flag = (r == EOF);
1829 i->p = G.user_input_buf;
1832 #endif /* INTERACTIVE */
1834 /* This is the magic location that prints prompts
1835 * and gets data back from the user */
1836 static int FAST_FUNC file_get(struct in_str *i)
1840 /* If there is data waiting, eat it up */
1841 if (i->p && *i->p) {
1842 #if ENABLE_HUSH_INTERACTIVE
1846 if (i->eof_flag && !*i->p)
1848 /* note: ch is never NUL */
1850 /* need to double check i->file because we might be doing something
1851 * more complicated by now, like sourcing or substituting. */
1852 #if ENABLE_HUSH_INTERACTIVE
1853 if (G_interactive_fd && i->promptme && i->file == stdin) {
1856 } while (!*i->p); /* need non-empty line */
1857 i->promptmode = 1; /* PS2 */
1862 do ch = fgetc(i->file); while (ch == '\0');
1864 debug_printf("file_get: got '%c' %d\n", ch, ch);
1865 #if ENABLE_HUSH_INTERACTIVE
1872 /* All callers guarantee this routine will never
1873 * be used right after a newline, so prompting is not needed.
1875 static int FAST_FUNC file_peek(struct in_str *i)
1878 if (i->p && *i->p) {
1879 if (i->eof_flag && !i->p[1])
1882 /* note: ch is never NUL */
1884 do ch = fgetc(i->file); while (ch == '\0');
1885 i->eof_flag = (ch == EOF);
1886 i->peek_buf[0] = ch;
1887 i->peek_buf[1] = '\0';
1889 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1893 static void setup_file_in_str(struct in_str *i, FILE *f)
1895 i->peek = file_peek;
1897 #if ENABLE_HUSH_INTERACTIVE
1899 i->promptmode = 0; /* PS1 */
1905 static void setup_string_in_str(struct in_str *i, const char *s)
1907 i->peek = static_peek;
1908 i->get = static_get;
1909 #if ENABLE_HUSH_INTERACTIVE
1911 i->promptmode = 0; /* PS1 */
1921 #define B_CHUNK (32 * sizeof(char*))
1923 static void o_reset_to_empty_unquoted(o_string *o)
1931 static void o_free(o_string *o)
1934 memset(o, 0, sizeof(*o));
1937 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1942 static void o_grow_by(o_string *o, int len)
1944 if (o->length + len > o->maxlen) {
1945 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1946 o->data = xrealloc(o->data, 1 + o->maxlen);
1950 static void o_addchr(o_string *o, int ch)
1952 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1954 o->data[o->length] = ch;
1956 o->data[o->length] = '\0';
1959 static void o_addblock(o_string *o, const char *str, int len)
1962 memcpy(&o->data[o->length], str, len);
1964 o->data[o->length] = '\0';
1967 static void o_addstr(o_string *o, const char *str)
1969 o_addblock(o, str, strlen(str));
1973 static void nommu_addchr(o_string *o, int ch)
1979 # define nommu_addchr(o, str) ((void)0)
1982 static void o_addstr_with_NUL(o_string *o, const char *str)
1984 o_addblock(o, str, strlen(str) + 1);
1987 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1992 && (*str != '*' && *str != '?' && *str != '[')
2000 #undef HUSH_BRACE_EXP
2002 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2003 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2004 * Apparently, on unquoted $v bash still does globbing
2005 * ("v='*.txt'; echo $v" prints all .txt files),
2006 * but NOT brace expansion! Thus, there should be TWO independent
2007 * quoting mechanisms on $v expansion side: one protects
2008 * $v from brace expansion, and other additionally protects "$v" against globbing.
2009 * We have only second one.
2012 #ifdef HUSH_BRACE_EXP
2013 # define MAYBE_BRACES "{}"
2015 # define MAYBE_BRACES ""
2018 /* My analysis of quoting semantics tells me that state information
2019 * is associated with a destination, not a source.
2021 static void o_addqchr(o_string *o, int ch)
2024 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2029 o->data[o->length] = '\\';
2032 o->data[o->length] = ch;
2034 o->data[o->length] = '\0';
2037 static void o_addQchr(o_string *o, int ch)
2040 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2042 o->data[o->length] = '\\';
2046 o->data[o->length] = ch;
2048 o->data[o->length] = '\0';
2051 static void o_addQstr(o_string *o, const char *str, int len)
2054 o_addblock(o, str, len);
2060 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2061 if (ordinary_cnt > len) /* paranoia */
2063 o_addblock(o, str, ordinary_cnt);
2064 if (ordinary_cnt == len)
2066 str += ordinary_cnt;
2067 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2071 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2073 o->data[o->length] = '\\';
2077 o->data[o->length] = ch;
2079 o->data[o->length] = '\0';
2083 /* A special kind of o_string for $VAR and `cmd` expansion.
2084 * It contains char* list[] at the beginning, which is grown in 16 element
2085 * increments. Actual string data starts at the next multiple of 16 * (char*).
2086 * list[i] contains an INDEX (int!) into this string data.
2087 * It means that if list[] needs to grow, data needs to be moved higher up
2088 * but list[i]'s need not be modified.
2089 * NB: remembering how many list[i]'s you have there is crucial.
2090 * o_finalize_list() operation post-processes this structure - calculates
2091 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2093 #if DEBUG_EXPAND || DEBUG_GLOB
2094 static void debug_print_list(const char *prefix, o_string *o, int n)
2096 char **list = (char**)o->data;
2097 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2101 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2102 prefix, list, n, string_start, o->length, o->maxlen);
2105 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2106 o->data + (int)list[i] + string_start,
2107 o->data + (int)list[i] + string_start);
2111 const char *p = o->data + (int)list[n - 1] + string_start;
2113 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2117 # define debug_print_list(prefix, o, n) ((void)0)
2120 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2121 * in list[n] so that it points past last stored byte so far.
2122 * It returns n+1. */
2123 static int o_save_ptr_helper(o_string *o, int n)
2125 char **list = (char**)o->data;
2129 if (!o->has_empty_slot) {
2130 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2131 string_len = o->length - string_start;
2132 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2133 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2134 /* list[n] points to string_start, make space for 16 more pointers */
2135 o->maxlen += 0x10 * sizeof(list[0]);
2136 o->data = xrealloc(o->data, o->maxlen + 1);
2137 list = (char**)o->data;
2138 memmove(list + n + 0x10, list + n, string_len);
2139 o->length += 0x10 * sizeof(list[0]);
2141 debug_printf_list("list[%d]=%d string_start=%d\n",
2142 n, string_len, string_start);
2145 /* We have empty slot at list[n], reuse without growth */
2146 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2147 string_len = o->length - string_start;
2148 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2149 n, string_len, string_start);
2150 o->has_empty_slot = 0;
2152 list[n] = (char*)(ptrdiff_t)string_len;
2156 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2157 static int o_get_last_ptr(o_string *o, int n)
2159 char **list = (char**)o->data;
2160 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2162 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2165 #ifdef HUSH_BRACE_EXP
2166 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2167 * first, it processes even {a} (no commas), second,
2168 * I didn't manage to make it return strings when they don't match
2169 * existing files. Need to re-implement it.
2173 static int glob_needed(const char *s)
2182 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2188 /* Return pointer to next closing brace or to comma */
2189 static const char *next_brace_sub(const char *cp)
2193 while (*cp != '\0') {
2200 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2202 if (*cp++ == '{') /*}*/
2206 return *cp != '\0' ? cp : NULL;
2208 /* Recursive brace globber. Note: may garble pattern[]. */
2209 static int glob_brace(char *pattern, o_string *o, int n)
2211 char *new_pattern_buf;
2218 debug_printf_glob("glob_brace('%s')\n", pattern);
2224 if (*begin == '{') /*}*/ {
2225 /* Find the first sub-pattern and at the same time
2226 * find the rest after the closing brace */
2227 next = next_brace_sub(begin);
2229 /* An illegal expression */
2232 /*{*/ if (*next == '}') {
2233 /* "{abc}" with no commas - illegal
2234 * brace expr, disregard and skip it */
2240 if (*begin == '\\' && begin[1] != '\0')
2244 debug_printf_glob("begin:%s\n", begin);
2245 debug_printf_glob("next:%s\n", next);
2247 /* Now find the end of the whole brace expression */
2249 /*{*/ while (*rest != '}') {
2250 rest = next_brace_sub(rest);
2252 /* An illegal expression */
2255 debug_printf_glob("rest:%s\n", rest);
2257 rest_len = strlen(++rest) + 1;
2259 /* We are sure the brace expression is well-formed */
2261 /* Allocate working buffer large enough for our work */
2262 new_pattern_buf = xmalloc(strlen(pattern));
2264 /* We have a brace expression. BEGIN points to the opening {,
2265 * NEXT points past the terminator of the first element, and REST
2266 * points past the final }. We will accumulate result names from
2267 * recursive runs for each brace alternative in the buffer using
2272 /* Construct the new glob expression */
2275 mempcpy(new_pattern_buf,
2276 /* We know the prefix for all sub-patterns */
2277 pattern, begin - pattern),
2281 /* Note: glob_brace() may garble new_pattern_buf[].
2282 * That's why we re-copy prefix every time (1st memcpy above).
2284 n = glob_brace(new_pattern_buf, o, n);
2285 /*{*/ if (*next == '}') {
2286 /* We saw the last entry */
2290 next = next_brace_sub(next);
2292 free(new_pattern_buf);
2300 memset(&globdata, 0, sizeof(globdata));
2301 gr = glob(pattern, 0, NULL, &globdata);
2302 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2304 if (gr == GLOB_NOMATCH) {
2305 globfree(&globdata);
2306 /* NB: garbles parameter */
2307 unbackslash(pattern);
2308 o_addstr_with_NUL(o, pattern);
2309 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2310 return o_save_ptr_helper(o, n);
2312 if (gr == GLOB_NOSPACE)
2313 bb_error_msg_and_die(bb_msg_memory_exhausted);
2314 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2315 * but we didn't specify it. Paranoia again. */
2316 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2318 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2319 char **argv = globdata.gl_pathv;
2321 o_addstr_with_NUL(o, *argv);
2322 n = o_save_ptr_helper(o, n);
2328 globfree(&globdata);
2332 /* Performs globbing on last list[],
2333 * saving each result as a new list[].
2335 static int o_glob(o_string *o, int n)
2337 char *pattern, *copy;
2339 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2341 return o_save_ptr_helper(o, n);
2342 pattern = o->data + o_get_last_ptr(o, n);
2343 debug_printf_glob("glob pattern '%s'\n", pattern);
2344 if (!glob_needed(pattern)) {
2345 /* unbackslash last string in o in place, fix length */
2346 o->length = unbackslash(pattern) - o->data;
2347 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2348 return o_save_ptr_helper(o, n);
2351 copy = xstrdup(pattern);
2352 /* "forget" pattern in o */
2353 o->length = pattern - o->data;
2354 n = glob_brace(copy, o, n);
2357 debug_print_list("o_glob returning", o, n);
2361 #else /* !HUSH_BRACE_EXP */
2364 static int glob_needed(const char *s)
2373 if (*s == '*' || *s == '[' || *s == '?')
2379 /* Performs globbing on last list[],
2380 * saving each result as a new list[].
2382 static int o_glob(o_string *o, int n)
2388 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2390 return o_save_ptr_helper(o, n);
2391 pattern = o->data + o_get_last_ptr(o, n);
2392 debug_printf_glob("glob pattern '%s'\n", pattern);
2393 if (!glob_needed(pattern)) {
2395 /* unbackslash last string in o in place, fix length */
2396 o->length = unbackslash(pattern) - o->data;
2397 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2398 return o_save_ptr_helper(o, n);
2401 memset(&globdata, 0, sizeof(globdata));
2402 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2403 * If we glob "*.\*" and don't find anything, we need
2404 * to fall back to using literal "*.*", but GLOB_NOCHECK
2405 * will return "*.\*"!
2407 gr = glob(pattern, 0, NULL, &globdata);
2408 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2410 if (gr == GLOB_NOMATCH) {
2411 globfree(&globdata);
2414 if (gr == GLOB_NOSPACE)
2415 bb_error_msg_and_die(bb_msg_memory_exhausted);
2416 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2417 * but we didn't specify it. Paranoia again. */
2418 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2420 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2421 char **argv = globdata.gl_pathv;
2422 /* "forget" pattern in o */
2423 o->length = pattern - o->data;
2425 o_addstr_with_NUL(o, *argv);
2426 n = o_save_ptr_helper(o, n);
2432 globfree(&globdata);
2434 debug_print_list("o_glob returning", o, n);
2438 #endif /* !HUSH_BRACE_EXP */
2440 /* If o->o_glob == 1, glob the string so far remembered.
2441 * Otherwise, just finish current list[] and start new */
2442 static int o_save_ptr(o_string *o, int n)
2444 if (o->o_glob) { /* if globbing is requested */
2445 /* If o->has_empty_slot, list[n] was already globbed
2446 * (if it was requested back then when it was filled)
2447 * so don't do that again! */
2448 if (!o->has_empty_slot)
2449 return o_glob(o, n); /* o_save_ptr_helper is inside */
2451 return o_save_ptr_helper(o, n);
2454 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2455 static char **o_finalize_list(o_string *o, int n)
2460 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2462 debug_print_list("finalized", o, n);
2463 debug_printf_expand("finalized n:%d\n", n);
2464 list = (char**)o->data;
2465 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2469 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2475 /* Expansion can recurse */
2476 #if ENABLE_HUSH_TICK
2477 static int process_command_subs(o_string *dest, const char *s);
2479 static char *expand_string_to_string(const char *str);
2481 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2482 parse_stream_dquoted(dest, input, dquote_end)
2484 static int parse_stream_dquoted(o_string *as_string,
2486 struct in_str *input,
2489 /* expand_strvec_to_strvec() takes a list of strings, expands
2490 * all variable references within and returns a pointer to
2491 * a list of expanded strings, possibly with larger number
2492 * of strings. (Think VAR="a b"; echo $VAR).
2493 * This new list is allocated as a single malloc block.
2494 * NULL-terminated list of char* pointers is at the beginning of it,
2495 * followed by strings themself.
2496 * Caller can deallocate entire list by single free(list). */
2498 /* Store given string, finalizing the word and starting new one whenever
2499 * we encounter IFS char(s). This is used for expanding variable values.
2500 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2501 static int expand_on_ifs(o_string *output, int n, const char *str)
2504 int word_len = strcspn(str, G.ifs);
2506 if (output->o_escape || !output->o_glob)
2507 o_addQstr(output, str, word_len);
2508 else /* protect backslashes against globbing up :) */
2509 o_addblock_duplicate_backslash(output, str, word_len);
2512 if (!*str) /* EOL - do not finalize word */
2514 o_addchr(output, '\0');
2515 debug_print_list("expand_on_ifs", output, n);
2516 n = o_save_ptr(output, n);
2517 str += strspn(str, G.ifs); /* skip ifs chars */
2519 debug_print_list("expand_on_ifs[1]", output, n);
2523 /* Helper to expand $((...)) and heredoc body. These act as if
2524 * they are in double quotes, with the exception that they are not :).
2525 * Just the rules are similar: "expand only $var and `cmd`"
2527 * Returns malloced string.
2528 * As an optimization, we return NULL if expansion is not needed.
2530 static char *expand_pseudo_dquoted(const char *str)
2533 struct in_str input;
2534 o_string dest = NULL_O_STRING;
2536 if (strchr(str, '$') == NULL
2537 #if ENABLE_HUSH_TICK
2538 && strchr(str, '`') == NULL
2544 /* We need to expand. Example:
2545 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2547 setup_string_in_str(&input, str);
2548 parse_stream_dquoted(NULL, &dest, &input, EOF);
2549 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2550 exp_str = expand_string_to_string(dest.data);
2551 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2552 o_free_unsafe(&dest);
2556 #if ENABLE_SH_MATH_SUPPORT
2557 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2559 arith_eval_hooks_t hooks;
2563 hooks.lookupvar = get_local_var_value;
2564 hooks.setvar = set_local_var_from_halves;
2565 hooks.endofname = endofname;
2566 exp_str = expand_pseudo_dquoted(arg);
2567 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2573 /* Expand all variable references in given string, adding words to list[]
2574 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2575 * to be filled). This routine is extremely tricky: has to deal with
2576 * variables/parameters with whitespace, $* and $@, and constructs like
2577 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2578 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2580 /* or_mask is either 0 (normal case) or 0x80 -
2581 * expansion of right-hand side of assignment == 1-element expand.
2582 * It will also do no globbing, and thus we must not backslash-quote!
2589 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2590 debug_print_list("expand_vars_to_list", output, n);
2591 n = o_save_ptr(output, n);
2592 debug_print_list("expand_vars_to_list[0]", output, n);
2594 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2597 char *to_be_freed = NULL;
2598 const char *val = NULL;
2599 #if ENABLE_HUSH_TICK
2600 o_string subst_result = NULL_O_STRING;
2602 #if ENABLE_SH_MATH_SUPPORT
2603 char arith_buf[sizeof(arith_t)*3 + 2];
2605 o_addblock(output, arg, p - arg);
2606 debug_print_list("expand_vars_to_list[1]", output, n);
2608 p = strchr(p, SPECIAL_VAR_SYMBOL);
2610 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2611 /* "$@" is special. Even if quoted, it can still
2612 * expand to nothing (not even an empty string) */
2613 if ((first_ch & 0x7f) != '@')
2614 ored_ch |= first_ch;
2616 switch (first_ch & 0x7f) {
2617 /* Highest bit in first_ch indicates that var is double-quoted */
2621 if (!G.global_argv[i])
2623 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2624 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2625 smallint sv = output->o_escape;
2626 /* unquoted var's contents should be globbed, so don't escape */
2627 output->o_escape = 0;
2628 while (G.global_argv[i]) {
2629 n = expand_on_ifs(output, n, G.global_argv[i]);
2630 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2631 if (G.global_argv[i++][0] && G.global_argv[i]) {
2632 /* this argv[] is not empty and not last:
2633 * put terminating NUL, start new word */
2634 o_addchr(output, '\0');
2635 debug_print_list("expand_vars_to_list[2]", output, n);
2636 n = o_save_ptr(output, n);
2637 debug_print_list("expand_vars_to_list[3]", output, n);
2640 output->o_escape = sv;
2642 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2643 * and in this case should treat it like '$*' - see 'else...' below */
2644 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2646 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2647 if (++i >= G.global_argc)
2649 o_addchr(output, '\0');
2650 debug_print_list("expand_vars_to_list[4]", output, n);
2651 n = o_save_ptr(output, n);
2653 } else { /* quoted $*: add as one word */
2655 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2656 if (!G.global_argv[++i])
2659 o_addchr(output, G.ifs[0]);
2663 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2664 /* "Empty variable", used to make "" etc to not disappear */
2668 #if ENABLE_HUSH_TICK
2669 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2672 /* Can't just stuff it into output o_string,
2673 * expanded result may need to be globbed
2674 * and $IFS-splitted */
2675 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2676 G.last_exitcode = process_command_subs(&subst_result, arg);
2677 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
2678 val = subst_result.data;
2681 #if ENABLE_SH_MATH_SUPPORT
2682 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2686 arg++; /* skip '+' */
2687 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2688 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2689 res = expand_and_evaluate_arith(arg, &errcode);
2692 const char *msg = "error in arithmetic";
2695 msg = "exponent less than 0";
2698 msg = "divide by 0";
2701 msg = "expression recursion loop detected";
2706 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2707 sprintf(arith_buf, arith_t_fmt, res);
2712 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2716 char exp_save = exp_save; /* for compiler */
2717 char *exp_saveptr; /* points to expansion operator */
2718 char *exp_word = exp_word; /* for compiler */
2722 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2723 first_char = arg[0] = first_ch & 0x7f;
2726 if (first_char == '#' && arg[1] && !exp_saveptr) {
2727 /* handle length expansion ${#var} */
2731 /* maybe handle parameter expansion */
2732 if (exp_saveptr /* if 2nd char is one of expansion operators */
2733 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2735 /* ${?:0}, ${#[:]%0} etc */
2736 exp_saveptr = var + 1;
2738 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2739 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2741 exp_op = exp_save = *exp_saveptr;
2743 exp_word = exp_saveptr + 1;
2744 if (exp_op == ':') {
2745 exp_op = *exp_word++;
2746 if (ENABLE_HUSH_BASH_COMPAT
2747 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2749 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2754 *exp_saveptr = '\0';
2755 } /* else: it's not an expansion op, but bare ${var} */
2758 /* lookup the variable in question */
2759 if (isdigit(var[0])) {
2760 /* parse_dollar() should have vetted var for us */
2762 if (i < G.global_argc)
2763 val = G.global_argv[i];
2764 /* else val remains NULL: $N with too big N */
2768 val = utoa(G.root_pid);
2770 case '!': /* bg pid */
2771 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2773 case '?': /* exitcode */
2774 val = utoa(G.last_exitcode);
2776 case '#': /* argc */
2777 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2780 val = get_local_var_value(var);
2784 /* handle any expansions */
2785 if (exp_op == 'L') {
2786 debug_printf_expand("expand: length(%s)=", val);
2787 val = utoa(val ? strlen(val) : 0);
2788 debug_printf_expand("%s\n", val);
2789 } else if (exp_op) {
2790 if (exp_op == '%' || exp_op == '#') {
2791 /* Standard-mandated substring removal ops:
2792 * ${parameter%word} - remove smallest suffix pattern
2793 * ${parameter%%word} - remove largest suffix pattern
2794 * ${parameter#word} - remove smallest prefix pattern
2795 * ${parameter##word} - remove largest prefix pattern
2797 * Word is expanded to produce a glob pattern.
2798 * Then var's value is matched to it and matching part removed.
2803 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2804 if (exp_op == *exp_word) /* ## or %% */
2806 val = to_be_freed = xstrdup(val);
2808 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2810 exp_word = exp_exp_word;
2811 loc = scan(to_be_freed, exp_word, match_at_left);
2812 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2813 // exp_op, to_be_freed, exp_word, loc);
2816 if (loc) { /* match was found */
2817 if (match_at_left) /* # or ## */
2823 } else if (exp_op == ':') {
2824 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2825 /* It's ${var:N[:M]} bashism.
2826 * Note that in encoded form it has TWO parts:
2827 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2832 beg = expand_and_evaluate_arith(exp_word, &errcode);
2833 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2834 *p++ = SPECIAL_VAR_SYMBOL;
2836 p = strchr(p, SPECIAL_VAR_SYMBOL);
2838 len = expand_and_evaluate_arith(exp_word, &errcode);
2839 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2841 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2842 if (beg < 0) /* bash compat */
2844 debug_printf_varexp("from val:'%s'\n", val);
2845 if (len == 0 || !val || beg >= strlen(val))
2848 /* Paranoia. What if user entered 9999999999999
2849 * which fits in arith_t but not int? */
2852 val = to_be_freed = xstrndup(val + beg, len);
2854 debug_printf_varexp("val:'%s'\n", val);
2858 die_if_script("malformed ${%s:...}", var);
2861 } else { /* one of "-=+?" */
2862 /* Standard-mandated substitution ops:
2863 * ${var?word} - indicate error if unset
2864 * If var is unset, word (or a message indicating it is unset
2865 * if word is null) is written to standard error
2866 * and the shell exits with a non-zero exit status.
2867 * Otherwise, the value of var is substituted.
2868 * ${var-word} - use default value
2869 * If var is unset, word is substituted.
2870 * ${var=word} - assign and use default value
2871 * If var is unset, word is assigned to var.
2872 * In all cases, final value of var is substituted.
2873 * ${var+word} - use alternative value
2874 * If var is unset, null is substituted.
2875 * Otherwise, word is substituted.
2877 * Word is subjected to tilde expansion, parameter expansion,
2878 * command substitution, and arithmetic expansion.
2879 * If word is not needed, it is not expanded.
2881 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2882 * but also treat null var as if it is unset.
2884 int use_word = (!val || ((exp_save == ':') && !val[0]));
2886 use_word = !use_word;
2887 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2888 (exp_save == ':') ? "true" : "false", use_word);
2890 to_be_freed = expand_pseudo_dquoted(exp_word);
2892 exp_word = to_be_freed;
2893 if (exp_op == '?') {
2894 /* mimic bash message */
2895 die_if_script("%s: %s",
2897 exp_word[0] ? exp_word : "parameter null or not set"
2899 //TODO: how interactive bash aborts expansion mid-command?
2904 if (exp_op == '=') {
2905 /* ${var=[word]} or ${var:=[word]} */
2906 if (isdigit(var[0]) || var[0] == '#') {
2907 /* mimic bash message */
2908 die_if_script("$%s: cannot assign in this way", var);
2911 char *new_var = xasprintf("%s=%s", var, val);
2912 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2916 } /* one of "-=+?" */
2918 *exp_saveptr = exp_save;
2922 #if ENABLE_HUSH_TICK
2925 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2926 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2928 /* unquoted var's contents should be globbed, so don't escape */
2929 smallint sv = output->o_escape;
2930 output->o_escape = 0;
2931 n = expand_on_ifs(output, n, val);
2933 output->o_escape = sv;
2935 } else { /* quoted $VAR, val will be appended below */
2936 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2939 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2942 o_addQstr(output, val, strlen(val));
2945 /* Do the check to avoid writing to a const string */
2946 if (*p != SPECIAL_VAR_SYMBOL)
2947 *p = SPECIAL_VAR_SYMBOL;
2949 #if ENABLE_HUSH_TICK
2950 o_free(&subst_result);
2953 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2956 debug_print_list("expand_vars_to_list[a]", output, n);
2957 /* this part is literal, and it was already pre-quoted
2958 * if needed (much earlier), do not use o_addQstr here! */
2959 o_addstr_with_NUL(output, arg);
2960 debug_print_list("expand_vars_to_list[b]", output, n);
2961 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2962 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2965 /* allow to reuse list[n] later without re-growth */
2966 output->has_empty_slot = 1;
2968 o_addchr(output, '\0');
2973 static char **expand_variables(char **argv, int or_mask)
2978 o_string output = NULL_O_STRING;
2980 if (or_mask & 0x100) {
2981 output.o_escape = 1; /* protect against globbing for "$var" */
2982 /* (unquoted $var will temporarily switch it off) */
2989 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
2992 debug_print_list("expand_variables", &output, n);
2994 /* output.data (malloced in one block) gets returned in "list" */
2995 list = o_finalize_list(&output, n);
2996 debug_print_strings("expand_variables[1]", list);
3000 static char **expand_strvec_to_strvec(char **argv)
3002 return expand_variables(argv, 0x100);
3005 #if ENABLE_HUSH_BASH_COMPAT
3006 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3008 return expand_variables(argv, 0x80);
3012 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3013 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3018 o_string output = NULL_O_STRING;
3023 int is_var = is_well_formed_var_name(*v, '=');
3024 /* is_var * 0x80: singleword expansion for vars */
3025 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3027 /* Subtle! expand_vars_to_list did not glob last word yet.
3028 * It does this only when fed with further data.
3029 * Therefore we set globbing flags AFTER it, not before:
3032 /* if it is not recognizably abc=...; then: */
3033 output.o_escape = !is_var; /* protect against globbing for "$var" */
3034 /* (unquoted $var will temporarily switch it off) */
3035 output.o_glob = !is_var; /* and indeed do globbing */
3038 debug_print_list("expand_cond", &output, n);
3040 /* output.data (malloced in one block) gets returned in "list" */
3041 list = o_finalize_list(&output, n);
3042 debug_print_strings("expand_cond[1]", list);
3047 /* Used for expansion of right hand of assignments */
3048 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3050 static char *expand_string_to_string(const char *str)
3052 char *argv[2], **list;
3054 argv[0] = (char*)str;
3056 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
3058 if (!list[0] || list[1])
3059 bb_error_msg_and_die("BUG in varexp2");
3060 /* actually, just move string 2*sizeof(char*) bytes back */
3061 overlapping_strcpy((char*)list, list[0]);
3062 unbackslash((char*)list);
3063 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3067 /* Used for "eval" builtin */
3068 static char* expand_strvec_to_string(char **argv)
3072 list = expand_variables(argv, 0x80);
3073 /* Convert all NULs to spaces */
3078 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3079 bb_error_msg_and_die("BUG in varexp3");
3080 /* bash uses ' ' regardless of $IFS contents */
3085 overlapping_strcpy((char*)list, list[0]);
3086 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3090 static char **expand_assignments(char **argv, int count)
3094 /* Expand assignments into one string each */
3095 for (i = 0; i < count; i++) {
3096 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3104 void re_execute_shell(char ***to_free, const char *s,
3105 char *g_argv0, char **g_argv,
3106 char **builtin_argv) NORETURN;
3108 static void reset_traps_to_defaults(void)
3110 /* This function is always called in a child shell
3111 * after fork (not vfork, NOMMU doesn't use this function).
3116 /* Child shells are not interactive.
3117 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3118 * Testcase: (while :; do :; done) + ^Z should background.
3119 * Same goes for SIGTERM, SIGHUP, SIGINT.
3121 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3122 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3124 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3125 * Stupid. It can be done with *single* &= op, but we can't use
3126 * the fact that G.blocked_set is implemented as a bitmask
3128 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3132 /* Careful. Only if no trap or trap is not "" */
3133 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3134 sigdelset(&G.blocked_set, sig);
3141 /* Our homegrown sig mask is saner to work with :) */
3142 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3144 /* Resetting all traps to default except empty ones */
3145 mask = G.non_DFL_mask;
3146 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3147 if (!G.traps[sig] || !G.traps[sig][0])
3150 G.traps[sig] = NULL;
3151 /* There is no signal for 0 (EXIT) */
3154 /* There was a trap handler, we just removed it.
3155 * But if sig still has non-DFL handling,
3156 * we should not unblock the sig. */
3159 sigdelset(&G.blocked_set, sig);
3161 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3166 static void re_execute_shell(char ***to_free, const char *s,
3167 char *g_argv0, char **g_argv,
3168 char **builtin_argv) NORETURN;
3169 static void re_execute_shell(char ***to_free, const char *s,
3170 char *g_argv0, char **g_argv,
3171 char **builtin_argv)
3173 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3174 /* delims + 2 * (number of bytes in printed hex numbers) */
3175 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3176 char *heredoc_argv[4];
3177 struct variable *cur;
3178 # if ENABLE_HUSH_FUNCTIONS
3179 struct function *funcp;
3183 unsigned long long empty_trap_mask;
3185 if (!g_argv0) { /* heredoc */
3186 argv = heredoc_argv;
3187 argv[0] = (char *) G.argv0_for_re_execing;
3188 argv[1] = (char *) "-<";
3189 argv[2] = (char *) s;
3191 pp = &argv[3]; /* used as pointer to empty environment */
3197 if (pp) while (*pp++)
3200 empty_trap_mask = 0;
3203 for (sig = 1; sig < NSIG; sig++) {
3204 if (G.traps[sig] && !G.traps[sig][0])
3205 empty_trap_mask |= 1LL << sig;
3209 sprintf(param_buf, NOMMU_HACK_FMT
3210 , (unsigned) G.root_pid
3211 , (unsigned) G.root_ppid
3212 , (unsigned) G.last_bg_pid
3213 , (unsigned) G.last_exitcode
3216 IF_HUSH_LOOPS(, G.depth_of_loop)
3218 # undef NOMMU_HACK_FMT
3219 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3220 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3223 for (cur = G.top_var; cur; cur = cur->next) {
3224 if (!cur->flg_export || cur->flg_read_only)
3227 # if ENABLE_HUSH_FUNCTIONS
3228 for (funcp = G.top_func; funcp; funcp = funcp->next)
3234 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3235 *pp++ = (char *) G.argv0_for_re_execing;
3237 for (cur = G.top_var; cur; cur = cur->next) {
3238 if (cur->varstr == hush_version_str)
3240 if (cur->flg_read_only) {
3241 *pp++ = (char *) "-R";
3242 *pp++ = cur->varstr;
3243 } else if (!cur->flg_export) {
3244 *pp++ = (char *) "-V";
3245 *pp++ = cur->varstr;
3248 # if ENABLE_HUSH_FUNCTIONS
3249 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3250 *pp++ = (char *) "-F";
3251 *pp++ = funcp->name;
3252 *pp++ = funcp->body_as_string;
3255 /* We can pass activated traps here. Say, -Tnn:trap_string
3257 * However, POSIX says that subshells reset signals with traps
3259 * I tested bash-3.2 and it not only does that with true subshells
3260 * of the form ( list ), but with any forked children shells.
3261 * I set trap "echo W" WINCH; and then tried:
3263 * { echo 1; sleep 20; echo 2; } &
3264 * while true; do echo 1; sleep 20; echo 2; break; done &
3265 * true | { echo 1; sleep 20; echo 2; } | cat
3267 * In all these cases sending SIGWINCH to the child shell
3268 * did not run the trap. If I add trap "echo V" WINCH;
3269 * _inside_ group (just before echo 1), it works.
3271 * I conclude it means we don't need to pass active traps here.
3272 * Even if we would use signal handlers instead of signal masking
3273 * in order to implement trap handling,
3274 * exec syscall below resets signals to SIG_DFL for us.
3276 *pp++ = (char *) "-c";
3279 while (*++builtin_argv)
3280 *pp++ = *builtin_argv;
3281 *pp++ = (char *) "";
3286 /* *pp = NULL; - is already there */
3290 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3291 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3292 execve(bb_busybox_exec_path, argv, pp);
3293 /* Fallback. Useful for init=/bin/hush usage etc */
3294 if (argv[0][0] == '/')
3295 execve(argv[0], argv, pp);
3296 xfunc_error_retval = 127;
3297 bb_error_msg_and_die("can't re-execute the shell");
3299 #endif /* !BB_MMU */
3302 static void setup_heredoc(struct redir_struct *redir)
3304 struct fd_pair pair;
3307 /* the _body_ of heredoc (misleading field name) */
3308 const char *heredoc = redir->rd_filename;
3315 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3316 expanded = expand_pseudo_dquoted(heredoc);
3320 len = strlen(heredoc);
3322 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3324 xmove_fd(pair.rd, redir->rd_fd);
3326 /* Try writing without forking. Newer kernels have
3327 * dynamically growing pipes. Must use non-blocking write! */
3330 written = write(pair.wr, heredoc, len);
3341 ndelay_off(pair.wr);
3343 /* Okay, pipe buffer was not big enough */
3344 /* Note: we must not create a stray child (bastard? :)
3345 * for the unsuspecting parent process. Child creates a grandchild
3346 * and exits before parent execs the process which consumes heredoc
3347 * (that exec happens after we return from this function) */
3354 disable_restore_tty_pgrp_on_exit();
3355 pid = BB_MMU ? xfork() : xvfork();
3359 close(redir->rd_fd); /* read side of the pipe */
3361 full_write(pair.wr, heredoc, len); /* may loop or block */
3364 /* Delegate blocking writes to another process */
3365 xmove_fd(pair.wr, STDOUT_FILENO);
3366 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3370 #if ENABLE_HUSH_FAST
3372 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3374 enable_restore_tty_pgrp_on_exit();
3380 wait(NULL); /* wait till child has died */
3383 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3384 * and stderr if they are redirected. */
3385 static int setup_redirects(struct command *prog, int squirrel[])
3388 struct redir_struct *redir;
3390 for (redir = prog->redirects; redir; redir = redir->next) {
3391 if (redir->rd_type == REDIRECT_HEREDOC2) {
3392 /* rd_fd<<HERE case */
3393 if (squirrel && redir->rd_fd < 3
3394 && squirrel[redir->rd_fd] < 0
3396 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3398 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3400 debug_printf_parse("set heredoc '%s'\n",
3401 redir->rd_filename);
3402 setup_heredoc(redir);
3406 if (redir->rd_dup == REDIRFD_TO_FILE) {
3407 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3409 if (redir->rd_filename == NULL) {
3410 /* Something went wrong in the parse.
3411 * Pretend it didn't happen */
3412 bb_error_msg("bug in redirect parse");
3415 mode = redir_table[redir->rd_type].mode;
3416 p = expand_string_to_string(redir->rd_filename);
3417 openfd = open_or_warn(p, mode);
3420 /* this could get lost if stderr has been redirected, but
3421 * bash and ash both lose it as well (though zsh doesn't!) */
3422 //what the above comment tries to say?
3426 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3427 openfd = redir->rd_dup;
3430 if (openfd != redir->rd_fd) {
3431 if (squirrel && redir->rd_fd < 3
3432 && squirrel[redir->rd_fd] < 0
3434 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3436 if (openfd == REDIRFD_CLOSE) {
3437 /* "n>-" means "close me" */
3438 close(redir->rd_fd);
3440 xdup2(openfd, redir->rd_fd);
3441 if (redir->rd_dup == REDIRFD_TO_FILE)
3449 static void restore_redirects(int squirrel[])
3452 for (i = 0; i < 3; i++) {
3455 /* We simply die on error */
3462 static void free_pipe_list(struct pipe *head);
3464 /* Return code is the exit status of the pipe */
3465 static void free_pipe(struct pipe *pi)
3468 struct command *command;
3469 struct redir_struct *r, *rnext;
3472 if (pi->stopped_cmds > 0) /* why? */
3474 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3475 for (i = 0; i < pi->num_cmds; i++) {
3476 command = &pi->cmds[i];
3477 debug_printf_clean(" command %d:\n", i);
3478 if (command->argv) {
3479 for (a = 0, p = command->argv; *p; a++, p++) {
3480 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3482 free_strings(command->argv);
3483 command->argv = NULL;
3485 /* not "else if": on syntax error, we may have both! */
3486 if (command->group) {
3487 debug_printf_clean(" begin group (cmd_type:%d)\n",
3489 free_pipe_list(command->group);
3490 debug_printf_clean(" end group\n");
3491 command->group = NULL;
3493 /* else is crucial here.
3494 * If group != NULL, child_func is meaningless */
3495 #if ENABLE_HUSH_FUNCTIONS
3496 else if (command->child_func) {
3497 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3498 command->child_func->parent_cmd = NULL;
3502 free(command->group_as_string);
3503 command->group_as_string = NULL;
3505 for (r = command->redirects; r; r = rnext) {
3506 debug_printf_clean(" redirect %d%s",
3507 r->rd_fd, redir_table[r->rd_type].descrip);
3508 /* guard against the case >$FOO, where foo is unset or blank */
3509 if (r->rd_filename) {
3510 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3511 free(r->rd_filename);
3512 r->rd_filename = NULL;
3514 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3518 command->redirects = NULL;
3520 free(pi->cmds); /* children are an array, they get freed all at once */
3528 static void free_pipe_list(struct pipe *head)
3530 struct pipe *pi, *next;
3532 for (pi = head; pi; pi = next) {
3534 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3537 debug_printf_clean("pipe followup code %d\n", pi->followup);
3539 /*pi->next = NULL;*/
3545 static int run_list(struct pipe *pi);
3547 #define parse_stream(pstring, input, end_trigger) \
3548 parse_stream(input, end_trigger)
3550 static struct pipe *parse_stream(char **pstring,
3551 struct in_str *input,
3553 static void parse_and_run_string(const char *s);
3556 static char *find_in_path(const char *arg)
3559 const char *PATH = get_local_var_value("PATH");
3565 const char *end = strchrnul(PATH, ':');
3566 int sz = end - PATH; /* must be int! */
3570 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3572 /* We have xxx::yyyy in $PATH,
3573 * it means "use current dir" */
3576 if (access(ret, F_OK) == 0)
3589 static const struct built_in_command* find_builtin_helper(const char *name,
3590 const struct built_in_command *x,
3591 const struct built_in_command *end)
3594 if (strcmp(name, x->b_cmd) != 0) {
3598 debug_printf_exec("found builtin '%s'\n", name);
3603 static const struct built_in_command* find_builtin1(const char *name)
3605 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3607 static const struct built_in_command* find_builtin(const char *name)
3609 const struct built_in_command *x = find_builtin1(name);
3612 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3615 #if ENABLE_HUSH_FUNCTIONS
3616 static struct function **find_function_slot(const char *name)
3618 struct function **funcpp = &G.top_func;
3620 if (strcmp(name, (*funcpp)->name) == 0) {
3623 funcpp = &(*funcpp)->next;
3628 static const struct function *find_function(const char *name)
3630 const struct function *funcp = *find_function_slot(name);
3632 debug_printf_exec("found function '%s'\n", name);
3636 /* Note: takes ownership on name ptr */
3637 static struct function *new_function(char *name)
3639 struct function **funcpp = find_function_slot(name);
3640 struct function *funcp = *funcpp;
3642 if (funcp != NULL) {
3643 struct command *cmd = funcp->parent_cmd;
3644 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3646 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3648 /* Note: if !funcp->body, do not free body_as_string!
3649 * This is a special case of "-F name body" function:
3650 * body_as_string was not malloced! */
3652 free_pipe_list(funcp->body);
3654 free(funcp->body_as_string);
3658 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3659 cmd->argv[0] = funcp->name;
3660 cmd->group = funcp->body;
3662 cmd->group_as_string = funcp->body_as_string;
3666 debug_printf_exec("remembering new function '%s'\n", name);
3667 funcp = *funcpp = xzalloc(sizeof(*funcp));
3668 /*funcp->next = NULL;*/
3675 static void unset_func(const char *name)
3677 struct function **funcpp = find_function_slot(name);
3678 struct function *funcp = *funcpp;
3680 if (funcp != NULL) {
3681 debug_printf_exec("freeing function '%s'\n", funcp->name);
3682 *funcpp = funcp->next;
3683 /* funcp is unlinked now, deleting it.
3684 * Note: if !funcp->body, the function was created by
3685 * "-F name body", do not free ->body_as_string
3686 * and ->name as they were not malloced. */
3688 free_pipe_list(funcp->body);
3691 free(funcp->body_as_string);
3699 #define exec_function(to_free, funcp, argv) \
3700 exec_function(funcp, argv)
3702 static void exec_function(char ***to_free,
3703 const struct function *funcp,
3704 char **argv) NORETURN;
3705 static void exec_function(char ***to_free,
3706 const struct function *funcp,
3712 argv[0] = G.global_argv[0];
3713 G.global_argv = argv;
3717 /* On MMU, funcp->body is always non-NULL */
3718 n = run_list(funcp->body);
3722 re_execute_shell(to_free,
3723 funcp->body_as_string,
3730 static int run_function(const struct function *funcp, char **argv)
3736 save_and_replace_G_args(&sv, argv);
3738 /* "we are in function, ok to use return" */
3739 sv_flg = G.flag_return_in_progress;
3740 G.flag_return_in_progress = -1;
3741 # if ENABLE_HUSH_LOCAL
3742 G.func_nest_level++;
3745 /* On MMU, funcp->body is always non-NULL */
3748 /* Function defined by -F */
3749 parse_and_run_string(funcp->body_as_string);
3750 rc = G.last_exitcode;
3754 rc = run_list(funcp->body);
3757 # if ENABLE_HUSH_LOCAL
3759 struct variable *var;
3760 struct variable **var_pp;
3762 var_pp = &G.top_var;
3763 while ((var = *var_pp) != NULL) {
3764 if (var->func_nest_level < G.func_nest_level) {
3765 var_pp = &var->next;
3769 if (var->flg_export)
3770 bb_unsetenv(var->varstr);
3771 /* Remove from global list */
3772 *var_pp = var->next;
3778 G.func_nest_level--;
3781 G.flag_return_in_progress = sv_flg;
3783 restore_G_args(&sv, argv);
3787 #endif /* ENABLE_HUSH_FUNCTIONS */
3791 #define exec_builtin(to_free, x, argv) \
3792 exec_builtin(x, argv)
3794 #define exec_builtin(to_free, x, argv) \
3795 exec_builtin(to_free, argv)
3797 static void exec_builtin(char ***to_free,
3798 const struct built_in_command *x,
3799 char **argv) NORETURN;
3800 static void exec_builtin(char ***to_free,
3801 const struct built_in_command *x,
3805 int rcode = x->b_function(argv);
3809 /* On NOMMU, we must never block!
3810 * Example: { sleep 99 | read line; } & echo Ok
3812 re_execute_shell(to_free,
3821 static void execvp_or_die(char **argv) NORETURN;
3822 static void execvp_or_die(char **argv)
3824 debug_printf_exec("execing '%s'\n", argv[0]);
3825 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3826 execvp(argv[0], argv);
3827 bb_perror_msg("can't execute '%s'", argv[0]);
3828 _exit(127); /* bash compat */
3831 #if ENABLE_HUSH_MODE_X
3832 static void dump_cmd_in_x_mode(char **argv)
3834 if (G_x_mode && argv) {
3835 /* We want to output the line in one write op */
3843 len += strlen(argv[n++]) + 1;
3849 p += sprintf(p, " %s", argv[n++]);
3857 # define dump_cmd_in_x_mode(argv) ((void)0)
3861 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3862 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3863 #define pseudo_exec(nommu_save, command, argv_expanded) \
3864 pseudo_exec(command, argv_expanded)
3867 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3869 * Don't exit() here. If you don't exec, use _exit instead.
3870 * The at_exit handlers apparently confuse the calling process,
3871 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3872 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3873 char **argv, int assignment_cnt,
3874 char **argv_expanded) NORETURN;
3875 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3876 char **argv, int assignment_cnt,
3877 char **argv_expanded)
3881 new_env = expand_assignments(argv, assignment_cnt);
3882 dump_cmd_in_x_mode(new_env);
3884 if (!argv[assignment_cnt]) {
3885 /* Case when we are here: ... | var=val | ...
3886 * (note that we do not exit early, i.e., do not optimize out
3887 * expand_assignments(): think about ... | var=`sleep 1` | ...
3889 free_strings(new_env);
3890 _exit(EXIT_SUCCESS);
3894 set_vars_and_save_old(new_env);
3895 free(new_env); /* optional */
3896 /* we can also destroy set_vars_and_save_old's return value,
3899 nommu_save->new_env = new_env;
3900 nommu_save->old_vars = set_vars_and_save_old(new_env);
3903 if (argv_expanded) {
3904 argv = argv_expanded;
3906 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3908 nommu_save->argv = argv;
3911 dump_cmd_in_x_mode(argv);
3913 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3914 if (strchr(argv[0], '/') != NULL)
3918 /* Check if the command matches any of the builtins.
3919 * Depending on context, this might be redundant. But it's
3920 * easier to waste a few CPU cycles than it is to figure out
3921 * if this is one of those cases.
3924 /* On NOMMU, it is more expensive to re-execute shell
3925 * just in order to run echo or test builtin.
3926 * It's better to skip it here and run corresponding
3927 * non-builtin later. */
3928 const struct built_in_command *x;
3929 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3931 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3934 #if ENABLE_HUSH_FUNCTIONS
3935 /* Check if the command matches any functions */
3937 const struct function *funcp = find_function(argv[0]);
3939 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3944 #if ENABLE_FEATURE_SH_STANDALONE
3945 /* Check if the command matches any busybox applets */
3947 int a = find_applet_by_name(argv[0]);
3949 # if BB_MMU /* see above why on NOMMU it is not allowed */
3950 if (APPLET_IS_NOEXEC(a)) {
3951 debug_printf_exec("running applet '%s'\n", argv[0]);
3952 run_applet_no_and_exit(a, argv);
3955 /* Re-exec ourselves */
3956 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3957 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3958 execv(bb_busybox_exec_path, argv);
3959 /* If they called chroot or otherwise made the binary no longer
3960 * executable, fall through */
3965 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3968 execvp_or_die(argv);
3971 /* Called after [v]fork() in run_pipe
3973 static void pseudo_exec(nommu_save_t *nommu_save,
3974 struct command *command,
3975 char **argv_expanded) NORETURN;
3976 static void pseudo_exec(nommu_save_t *nommu_save,
3977 struct command *command,
3978 char **argv_expanded)
3980 if (command->argv) {
3981 pseudo_exec_argv(nommu_save, command->argv,
3982 command->assignment_cnt, argv_expanded);
3985 if (command->group) {
3986 /* Cases when we are here:
3989 * ... | ( list ) | ...
3990 * ... | { list } | ...
3994 debug_printf_exec("pseudo_exec: run_list\n");
3995 reset_traps_to_defaults();
3996 rcode = run_list(command->group);
3997 /* OK to leak memory by not calling free_pipe_list,
3998 * since this process is about to exit */
4001 re_execute_shell(&nommu_save->argv_from_re_execing,
4002 command->group_as_string,
4009 /* Case when we are here: ... | >file */
4010 debug_printf_exec("pseudo_exec'ed null command\n");
4011 _exit(EXIT_SUCCESS);
4015 static const char *get_cmdtext(struct pipe *pi)
4021 /* This is subtle. ->cmdtext is created only on first backgrounding.
4022 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4023 * On subsequent bg argv is trashed, but we won't use it */
4026 argv = pi->cmds[0].argv;
4027 if (!argv || !argv[0]) {
4028 pi->cmdtext = xzalloc(1);
4034 len += strlen(*argv) + 1;
4038 argv = pi->cmds[0].argv;
4040 len = strlen(*argv);
4041 memcpy(p, *argv, len);
4049 static void insert_bg_job(struct pipe *pi)
4051 struct pipe *job, **jobp;
4054 /* Linear search for the ID of the job to use */
4056 for (job = G.job_list; job; job = job->next)
4057 if (job->jobid >= pi->jobid)
4058 pi->jobid = job->jobid + 1;
4060 /* Add job to the list of running jobs */
4062 while ((job = *jobp) != NULL)
4064 job = *jobp = xmalloc(sizeof(*job));
4066 *job = *pi; /* physical copy */
4068 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4069 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4070 for (i = 0; i < pi->num_cmds; i++) {
4071 job->cmds[i].pid = pi->cmds[i].pid;
4072 /* all other fields are not used and stay zero */
4074 job->cmdtext = xstrdup(get_cmdtext(pi));
4076 if (G_interactive_fd)
4077 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4078 /* Last command's pid goes to $! */
4079 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
4080 G.last_jobid = job->jobid;
4083 static void remove_bg_job(struct pipe *pi)
4085 struct pipe *prev_pipe;
4087 if (pi == G.job_list) {
4088 G.job_list = pi->next;
4090 prev_pipe = G.job_list;
4091 while (prev_pipe->next != pi)
4092 prev_pipe = prev_pipe->next;
4093 prev_pipe->next = pi->next;
4096 G.last_jobid = G.job_list->jobid;
4101 /* Remove a backgrounded job */
4102 static void delete_finished_bg_job(struct pipe *pi)
4105 pi->stopped_cmds = 0;
4111 /* Check to see if any processes have exited -- if they
4112 * have, figure out why and see if a job has completed */
4113 static int checkjobs(struct pipe* fg_pipe)
4123 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4125 attributes = WUNTRACED;
4126 if (fg_pipe == NULL)
4127 attributes |= WNOHANG;
4130 #if ENABLE_HUSH_FAST
4131 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4132 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4133 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4134 /* There was neither fork nor SIGCHLD since last waitpid */
4135 /* Avoid doing waitpid syscall if possible */
4136 if (!G.we_have_children) {
4140 if (fg_pipe == NULL) { /* is WNOHANG set? */
4141 /* We have children, but they did not exit
4142 * or stop yet (we saw no SIGCHLD) */
4145 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4149 /* Do we do this right?
4150 * bash-3.00# sleep 20 | false
4152 * [3]+ Stopped sleep 20 | false
4153 * bash-3.00# echo $?
4154 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4155 * [hush 1.14.0: yes we do it right]
4162 #if ENABLE_HUSH_FAST
4163 i = G.count_SIGCHLD;
4165 childpid = waitpid(-1, &status, attributes);
4166 if (childpid <= 0) {
4167 if (childpid && errno != ECHILD)
4168 bb_perror_msg("waitpid");
4169 #if ENABLE_HUSH_FAST
4170 else { /* Until next SIGCHLD, waitpid's are useless */
4171 G.we_have_children = (childpid == 0);
4172 G.handled_SIGCHLD = i;
4173 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4178 dead = WIFEXITED(status) || WIFSIGNALED(status);
4181 if (WIFSTOPPED(status))
4182 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4183 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4184 if (WIFSIGNALED(status))
4185 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4186 childpid, WTERMSIG(status), WEXITSTATUS(status));
4187 if (WIFEXITED(status))
4188 debug_printf_jobs("pid %d exited, exitcode %d\n",
4189 childpid, WEXITSTATUS(status));
4191 /* Were we asked to wait for fg pipe? */
4193 for (i = 0; i < fg_pipe->num_cmds; i++) {
4194 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4195 if (fg_pipe->cmds[i].pid != childpid)
4198 fg_pipe->cmds[i].pid = 0;
4199 fg_pipe->alive_cmds--;
4200 if (i == fg_pipe->num_cmds - 1) {
4201 /* last process gives overall exitstatus */
4202 rcode = WEXITSTATUS(status);
4203 /* bash prints killer signal's name for *last*
4204 * process in pipe (prints just newline for SIGINT).
4205 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4207 if (WIFSIGNALED(status)) {
4208 int sig = WTERMSIG(status);
4209 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4210 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4211 * Maybe we need to use sig | 128? */
4214 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4217 fg_pipe->cmds[i].is_stopped = 1;
4218 fg_pipe->stopped_cmds++;
4220 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4221 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4222 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4223 /* All processes in fg pipe have exited or stopped */
4224 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4225 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4226 * and "killall -STOP cat" */
4227 if (G_interactive_fd) {
4229 if (fg_pipe->alive_cmds)
4230 insert_bg_job(fg_pipe);
4234 if (!fg_pipe->alive_cmds)
4237 /* There are still running processes in the fg pipe */
4238 goto wait_more; /* do waitpid again */
4240 /* it wasnt fg_pipe, look for process in bg pipes */
4244 /* We asked to wait for bg or orphaned children */
4245 /* No need to remember exitcode in this case */
4246 for (pi = G.job_list; pi; pi = pi->next) {
4247 for (i = 0; i < pi->num_cmds; i++) {
4248 if (pi->cmds[i].pid == childpid)
4249 goto found_pi_and_prognum;
4252 /* Happens when shell is used as init process (init=/bin/sh) */
4253 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4254 continue; /* do waitpid again */
4256 found_pi_and_prognum:
4259 pi->cmds[i].pid = 0;
4261 if (!pi->alive_cmds) {
4262 if (G_interactive_fd)
4263 printf(JOB_STATUS_FORMAT, pi->jobid,
4264 "Done", pi->cmdtext);
4265 delete_finished_bg_job(pi);
4269 pi->cmds[i].is_stopped = 1;
4273 } /* while (waitpid succeeds)... */
4279 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4282 int rcode = checkjobs(fg_pipe);
4283 if (G_saved_tty_pgrp) {
4284 /* Job finished, move the shell to the foreground */
4285 p = getpgrp(); /* our process group id */
4286 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4287 tcsetpgrp(G_interactive_fd, p);
4293 /* Start all the jobs, but don't wait for anything to finish.
4296 * Return code is normally -1, when the caller has to wait for children
4297 * to finish to determine the exit status of the pipe. If the pipe
4298 * is a simple builtin command, however, the action is done by the
4299 * time run_pipe returns, and the exit code is provided as the
4302 * Returns -1 only if started some children. IOW: we have to
4303 * mask out retvals of builtins etc with 0xff!
4305 * The only case when we do not need to [v]fork is when the pipe
4306 * is single, non-backgrounded, non-subshell command. Examples:
4307 * cmd ; ... { list } ; ...
4308 * cmd && ... { list } && ...
4309 * cmd || ... { list } || ...
4310 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4311 * or (if SH_STANDALONE) an applet, and we can run the { list }
4312 * with run_list. If it isn't one of these, we fork and exec cmd.
4314 * Cases when we must fork:
4315 * non-single: cmd | cmd
4316 * backgrounded: cmd & { list } &
4317 * subshell: ( list ) [&]
4319 static NOINLINE int run_pipe(struct pipe *pi)
4321 static const char *const null_ptr = NULL;
4325 struct command *command;
4326 char **argv_expanded;
4329 /* it is not always needed, but we aim to smaller code */
4330 int squirrel[] = { -1, -1, -1 };
4333 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4336 IF_HUSH_JOB(pi->pgrp = -1;)
4337 pi->stopped_cmds = 0;
4338 command = &pi->cmds[0];
4339 argv_expanded = NULL;
4341 if (pi->num_cmds != 1
4342 || pi->followup == PIPE_BG
4343 || command->cmd_type == CMD_SUBSHELL
4350 debug_printf_exec(": group:%p argv:'%s'\n",
4351 command->group, command->argv ? command->argv[0] : "NONE");
4353 if (command->group) {
4354 #if ENABLE_HUSH_FUNCTIONS
4355 if (command->cmd_type == CMD_FUNCDEF) {
4356 /* "executing" func () { list } */
4357 struct function *funcp;
4359 funcp = new_function(command->argv[0]);
4360 /* funcp->name is already set to argv[0] */
4361 funcp->body = command->group;
4363 funcp->body_as_string = command->group_as_string;
4364 command->group_as_string = NULL;
4366 command->group = NULL;
4367 command->argv[0] = NULL;
4368 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4369 funcp->parent_cmd = command;
4370 command->child_func = funcp;
4372 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4374 return EXIT_SUCCESS;
4378 debug_printf("non-subshell group\n");
4379 rcode = 1; /* exitcode if redir failed */
4380 if (setup_redirects(command, squirrel) == 0) {
4381 debug_printf_exec(": run_list\n");
4382 rcode = run_list(command->group) & 0xff;
4384 restore_redirects(squirrel);
4385 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4387 debug_printf_exec("run_pipe: return %d\n", rcode);
4391 argv = command->argv ? command->argv : (char **) &null_ptr;
4393 const struct built_in_command *x;
4394 #if ENABLE_HUSH_FUNCTIONS
4395 const struct function *funcp;
4399 char **new_env = NULL;
4400 struct variable *old_vars = NULL;
4402 if (argv[command->assignment_cnt] == NULL) {
4403 /* Assignments, but no command */
4404 /* Ensure redirects take effect (that is, create files).
4405 * Try "a=t >file": */
4406 rcode = setup_redirects(command, squirrel);
4407 restore_redirects(squirrel);
4408 /* Set shell variables */
4410 bb_putchar_stderr('+');
4412 p = expand_string_to_string(*argv);
4414 fprintf(stderr, " %s", p);
4415 debug_printf_exec("set shell var:'%s'->'%s'\n",
4417 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4421 bb_putchar_stderr('\n');
4422 /* Redirect error sets $? to 1. Otherwise,
4423 * if evaluating assignment value set $?, retain it.
4424 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4426 rcode = G.last_exitcode;
4427 /* Do we need to flag set_local_var() errors?
4428 * "assignment to readonly var" and "putenv error"
4430 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4432 debug_printf_exec("run_pipe: return %d\n", rcode);
4436 /* Expand the rest into (possibly) many strings each */
4438 #if ENABLE_HUSH_BASH_COMPAT
4439 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4440 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4443 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4444 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4445 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4450 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4453 /* if someone gives us an empty string: `cmd with empty output` */
4454 if (!argv_expanded[0]) {
4455 free(argv_expanded);
4457 return G.last_exitcode;
4460 x = find_builtin(argv_expanded[0]);
4461 #if ENABLE_HUSH_FUNCTIONS
4464 funcp = find_function(argv_expanded[0]);
4468 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4469 debug_printf("exec with redirects only\n");
4470 rcode = setup_redirects(command, NULL);
4471 goto clean_up_and_ret1;
4474 /* setup_redirects acts on file descriptors, not FILEs.
4475 * This is perfect for work that comes after exec().
4476 * Is it really safe for inline use? Experimentally,
4477 * things seem to work. */
4478 rcode = setup_redirects(command, squirrel);
4480 new_env = expand_assignments(argv, command->assignment_cnt);
4481 dump_cmd_in_x_mode(new_env);
4482 dump_cmd_in_x_mode(argv_expanded);
4483 old_vars = set_vars_and_save_old(new_env);
4485 debug_printf_exec(": builtin '%s' '%s'...\n",
4486 x->b_cmd, argv_expanded[1]);
4487 rcode = x->b_function(argv_expanded) & 0xff;
4490 #if ENABLE_HUSH_FUNCTIONS
4492 # if ENABLE_HUSH_LOCAL
4493 struct variable **sv;
4494 sv = G.shadowed_vars_pp;
4495 G.shadowed_vars_pp = &old_vars;
4497 debug_printf_exec(": function '%s' '%s'...\n",
4498 funcp->name, argv_expanded[1]);
4499 rcode = run_function(funcp, argv_expanded) & 0xff;
4500 # if ENABLE_HUSH_LOCAL
4501 G.shadowed_vars_pp = sv;
4507 restore_redirects(squirrel);
4508 unset_vars(new_env);
4511 free(argv_expanded);
4512 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4514 debug_printf_exec("run_pipe return %d\n", rcode);
4518 if (ENABLE_FEATURE_SH_STANDALONE) {
4519 int n = find_applet_by_name(argv_expanded[0]);
4520 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4521 rcode = setup_redirects(command, squirrel);
4523 new_env = expand_assignments(argv, command->assignment_cnt);
4524 dump_cmd_in_x_mode(new_env);
4525 dump_cmd_in_x_mode(argv_expanded);
4526 old_vars = set_vars_and_save_old(new_env);
4527 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4528 argv_expanded[0], argv_expanded[1]);
4529 rcode = run_nofork_applet(n, argv_expanded);
4531 goto clean_up_and_ret;
4534 /* It is neither builtin nor applet. We must fork. */
4538 /* NB: argv_expanded may already be created, and that
4539 * might include `cmd` runs! Do not rerun it! We *must*
4540 * use argv_expanded if it's non-NULL */
4542 /* Going to fork a child per each pipe member */
4547 while (cmd_no < pi->num_cmds) {
4548 struct fd_pair pipefds;
4550 volatile nommu_save_t nommu_save;
4551 nommu_save.new_env = NULL;
4552 nommu_save.old_vars = NULL;
4553 nommu_save.argv = NULL;
4554 nommu_save.argv_from_re_execing = NULL;
4556 command = &pi->cmds[cmd_no];
4558 if (command->argv) {
4559 debug_printf_exec(": pipe member '%s' '%s'...\n",
4560 command->argv[0], command->argv[1]);
4562 debug_printf_exec(": pipe member with no argv\n");
4565 /* pipes are inserted between pairs of commands */
4568 if (cmd_no < pi->num_cmds)
4569 xpiped_pair(pipefds);
4571 command->pid = BB_MMU ? fork() : vfork();
4572 if (!command->pid) { /* child */
4574 disable_restore_tty_pgrp_on_exit();
4575 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4577 /* Every child adds itself to new process group
4578 * with pgid == pid_of_first_child_in_pipe */
4579 if (G.run_list_level == 1 && G_interactive_fd) {
4582 if (pgrp < 0) /* true for 1st process only */
4584 if (setpgid(0, pgrp) == 0
4585 && pi->followup != PIPE_BG
4586 && G_saved_tty_pgrp /* we have ctty */
4588 /* We do it in *every* child, not just first,
4590 tcsetpgrp(G_interactive_fd, pgrp);
4594 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4595 /* 1st cmd in backgrounded pipe
4596 * should have its stdin /dev/null'ed */
4598 if (open(bb_dev_null, O_RDONLY))
4599 xopen("/", O_RDONLY);
4601 xmove_fd(next_infd, 0);
4603 xmove_fd(pipefds.wr, 1);
4606 /* Like bash, explicit redirects override pipes,
4607 * and the pipe fd is available for dup'ing. */
4608 if (setup_redirects(command, NULL))
4611 /* Restore default handlers just prior to exec */
4612 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4614 /* Stores to nommu_save list of env vars putenv'ed
4615 * (NOMMU, on MMU we don't need that) */
4616 /* cast away volatility... */
4617 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4618 /* pseudo_exec() does not return */
4621 /* parent or error */
4622 #if ENABLE_HUSH_FAST
4624 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4626 enable_restore_tty_pgrp_on_exit();
4628 /* Clean up after vforked child */
4629 free(nommu_save.argv);
4630 free(nommu_save.argv_from_re_execing);
4631 unset_vars(nommu_save.new_env);
4632 add_vars(nommu_save.old_vars);
4634 free(argv_expanded);
4635 argv_expanded = NULL;
4636 if (command->pid < 0) { /* [v]fork failed */
4637 /* Clearly indicate, was it fork or vfork */
4638 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4642 /* Second and next children need to know pid of first one */
4644 pi->pgrp = command->pid;
4650 if (cmd_no < pi->num_cmds)
4652 /* Pass read (output) pipe end to next iteration */
4653 next_infd = pipefds.rd;
4656 if (!pi->alive_cmds) {
4658 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4663 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4667 #ifndef debug_print_tree
4668 static void debug_print_tree(struct pipe *pi, int lvl)
4670 static const char *const PIPE[] = {
4676 static const char *RES[] = {
4677 [RES_NONE ] = "NONE" ,
4680 [RES_THEN ] = "THEN" ,
4681 [RES_ELIF ] = "ELIF" ,
4682 [RES_ELSE ] = "ELSE" ,
4685 # if ENABLE_HUSH_LOOPS
4686 [RES_FOR ] = "FOR" ,
4687 [RES_WHILE] = "WHILE",
4688 [RES_UNTIL] = "UNTIL",
4690 [RES_DONE ] = "DONE" ,
4692 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4695 # if ENABLE_HUSH_CASE
4696 [RES_CASE ] = "CASE" ,
4697 [RES_CASE_IN ] = "CASE_IN" ,
4698 [RES_MATCH] = "MATCH",
4699 [RES_CASE_BODY] = "CASE_BODY",
4700 [RES_ESAC ] = "ESAC" ,
4702 [RES_XXXX ] = "XXXX" ,
4703 [RES_SNTX ] = "SNTX" ,
4705 static const char *const CMDTYPE[] = {
4709 # if ENABLE_HUSH_FUNCTIONS
4718 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4719 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4721 while (prn < pi->num_cmds) {
4722 struct command *command = &pi->cmds[prn];
4723 char **argv = command->argv;
4725 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4727 command->assignment_cnt);
4728 if (command->group) {
4729 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4730 CMDTYPE[command->cmd_type],
4733 , " group_as_string:", command->group_as_string
4738 debug_print_tree(command->group, lvl+1);
4742 if (argv) while (*argv) {
4743 fprintf(stderr, " '%s'", *argv);
4746 fprintf(stderr, "\n");
4753 #endif /* debug_print_tree */
4755 /* NB: called by pseudo_exec, and therefore must not modify any
4756 * global data until exec/_exit (we can be a child after vfork!) */
4757 static int run_list(struct pipe *pi)
4759 #if ENABLE_HUSH_CASE
4760 char *case_word = NULL;
4762 #if ENABLE_HUSH_LOOPS
4763 struct pipe *loop_top = NULL;
4764 char **for_lcur = NULL;
4765 char **for_list = NULL;
4767 smallint last_followup;
4769 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4770 smalluint cond_code = 0;
4772 enum { cond_code = 0 };
4775 smallint rword; /* enum reserved_style */
4776 smallint last_rword; /* ditto */
4779 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4782 #if ENABLE_HUSH_LOOPS
4783 /* Check syntax for "for" */
4784 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4785 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4787 /* current word is FOR or IN (BOLD in comments below) */
4788 if (cpipe->next == NULL) {
4789 syntax_error("malformed for");
4791 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4794 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4795 if (cpipe->next->res_word == RES_DO)
4797 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4798 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4799 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4801 syntax_error("malformed for");
4803 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4809 /* Past this point, all code paths should jump to ret: label
4810 * in order to return, no direct "return" statements please.
4811 * This helps to ensure that no memory is leaked. */
4819 last_rword = RES_XXXX;
4821 last_followup = PIPE_SEQ;
4822 rcode = G.last_exitcode;
4824 /* Go through list of pipes, (maybe) executing them. */
4825 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4829 IF_HAS_KEYWORDS(rword = pi->res_word;)
4830 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4831 rword, cond_code, last_rword);
4832 #if ENABLE_HUSH_LOOPS
4833 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4834 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4836 /* start of a loop: remember where loop starts */
4841 /* Still in the same "if...", "then..." or "do..." branch? */
4842 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4843 if ((rcode == 0 && last_followup == PIPE_OR)
4844 || (rcode != 0 && last_followup == PIPE_AND)
4846 /* It is "<true> || CMD" or "<false> && CMD"
4847 * and we should not execute CMD */
4848 debug_printf_exec("skipped cmd because of || or &&\n");
4849 last_followup = pi->followup;
4853 last_followup = pi->followup;
4854 IF_HAS_KEYWORDS(last_rword = rword;)
4857 if (rword == RES_THEN) {
4858 /* if false; then ... fi has exitcode 0! */
4859 G.last_exitcode = rcode = EXIT_SUCCESS;
4860 /* "if <false> THEN cmd": skip cmd */
4864 if (rword == RES_ELSE || rword == RES_ELIF) {
4865 /* "if <true> then ... ELSE/ELIF cmd":
4866 * skip cmd and all following ones */
4871 #if ENABLE_HUSH_LOOPS
4872 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4874 /* first loop through for */
4876 static const char encoded_dollar_at[] ALIGN1 = {
4877 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4878 }; /* encoded representation of "$@" */
4879 static const char *const encoded_dollar_at_argv[] = {
4880 encoded_dollar_at, NULL
4881 }; /* argv list with one element: "$@" */
4884 vals = (char**)encoded_dollar_at_argv;
4885 if (pi->next->res_word == RES_IN) {
4886 /* if no variable values after "in" we skip "for" */
4887 if (!pi->next->cmds[0].argv) {
4888 G.last_exitcode = rcode = EXIT_SUCCESS;
4889 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4892 vals = pi->next->cmds[0].argv;
4893 } /* else: "for var; do..." -> assume "$@" list */
4894 /* create list of variable values */
4895 debug_print_strings("for_list made from", vals);
4896 for_list = expand_strvec_to_strvec(vals);
4897 for_lcur = for_list;
4898 debug_print_strings("for_list", for_list);
4901 /* "for" loop is over, clean up */
4907 /* Insert next value from for_lcur */
4908 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4909 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4912 if (rword == RES_IN) {
4913 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4915 if (rword == RES_DONE) {
4916 continue; /* "done" has no cmds too */
4919 #if ENABLE_HUSH_CASE
4920 if (rword == RES_CASE) {
4921 case_word = expand_strvec_to_string(pi->cmds->argv);
4924 if (rword == RES_MATCH) {
4927 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4929 /* all prev words didn't match, does this one match? */
4930 argv = pi->cmds->argv;
4932 char *pattern = expand_string_to_string(*argv);
4933 /* TODO: which FNM_xxx flags to use? */
4934 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4936 if (cond_code == 0) { /* match! we will execute this branch */
4937 free(case_word); /* make future "word)" stop */
4945 if (rword == RES_CASE_BODY) { /* inside of a case branch */
4947 continue; /* not matched yet, skip this pipe */
4950 /* Just pressing <enter> in shell should check for jobs.
4951 * OTOH, in non-interactive shell this is useless
4952 * and only leads to extra job checks */
4953 if (pi->num_cmds == 0) {
4954 if (G_interactive_fd)
4955 goto check_jobs_and_continue;
4959 /* After analyzing all keywords and conditions, we decided
4960 * to execute this pipe. NB: have to do checkjobs(NULL)
4961 * after run_pipe to collect any background children,
4962 * even if list execution is to be stopped. */
4963 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
4966 #if ENABLE_HUSH_LOOPS
4967 G.flag_break_continue = 0;
4969 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4971 /* We ran a builtin, function, or group.
4972 * rcode is already known
4973 * and we don't need to wait for anything. */
4974 G.last_exitcode = rcode;
4975 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
4976 check_and_run_traps(0);
4977 #if ENABLE_HUSH_LOOPS
4978 /* Was it "break" or "continue"? */
4979 if (G.flag_break_continue) {
4980 smallint fbc = G.flag_break_continue;
4981 /* We might fall into outer *loop*,
4982 * don't want to break it too */
4984 G.depth_break_continue--;
4985 if (G.depth_break_continue == 0)
4986 G.flag_break_continue = 0;
4987 /* else: e.g. "continue 2" should *break* once, *then* continue */
4988 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
4989 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
4990 goto check_jobs_and_break;
4991 /* "continue": simulate end of loop */
4996 #if ENABLE_HUSH_FUNCTIONS
4997 if (G.flag_return_in_progress == 1) {
4998 /* same as "goto check_jobs_and_break" */
5003 } else if (pi->followup == PIPE_BG) {
5004 /* What does bash do with attempts to background builtins? */
5005 /* even bash 3.2 doesn't do that well with nested bg:
5006 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5007 * I'm NOT treating inner &'s as jobs */
5008 check_and_run_traps(0);
5010 if (G.run_list_level == 1)
5013 G.last_exitcode = rcode = EXIT_SUCCESS;
5014 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5017 if (G.run_list_level == 1 && G_interactive_fd) {
5018 /* Waits for completion, then fg's main shell */
5019 rcode = checkjobs_and_fg_shell(pi);
5020 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5021 check_and_run_traps(0);
5024 { /* This one just waits for completion */
5025 rcode = checkjobs(pi);
5026 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5027 check_and_run_traps(0);
5029 G.last_exitcode = rcode;
5033 /* Analyze how result affects subsequent commands */
5035 if (rword == RES_IF || rword == RES_ELIF)
5038 #if ENABLE_HUSH_LOOPS
5039 /* Beware of "while false; true; do ..."! */
5040 if (pi->next && pi->next->res_word == RES_DO) {
5041 if (rword == RES_WHILE) {
5043 /* "while false; do...done" - exitcode 0 */
5044 G.last_exitcode = rcode = EXIT_SUCCESS;
5045 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5046 goto check_jobs_and_break;
5049 if (rword == RES_UNTIL) {
5051 debug_printf_exec(": until expr is true: breaking\n");
5052 check_jobs_and_break:
5060 check_jobs_and_continue:
5067 #if ENABLE_HUSH_LOOPS
5072 #if ENABLE_HUSH_CASE
5076 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5080 /* Select which version we will use */
5081 static int run_and_free_list(struct pipe *pi)
5084 debug_printf_exec("run_and_free_list entered\n");
5086 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5087 rcode = run_list(pi);
5089 /* free_pipe_list has the side effect of clearing memory.
5090 * In the long run that function can be merged with run_list,
5091 * but doing that now would hobble the debugging effort. */
5093 debug_printf_exec("run_and_free_list return %d\n", rcode);
5098 static struct pipe *new_pipe(void)
5101 pi = xzalloc(sizeof(struct pipe));
5102 /*pi->followup = 0; - deliberately invalid value */
5103 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5107 /* Command (member of a pipe) is complete, or we start a new pipe
5108 * if ctx->command is NULL.
5109 * No errors possible here.
5111 static int done_command(struct parse_context *ctx)
5113 /* The command is really already in the pipe structure, so
5114 * advance the pipe counter and make a new, null command. */
5115 struct pipe *pi = ctx->pipe;
5116 struct command *command = ctx->command;
5119 if (IS_NULL_CMD(command)) {
5120 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5124 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5125 //debug_print_tree(ctx->list_head, 20);
5127 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5130 /* Only real trickiness here is that the uncommitted
5131 * command structure is not counted in pi->num_cmds. */
5132 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5133 ctx->command = command = &pi->cmds[pi->num_cmds];
5135 memset(command, 0, sizeof(*command));
5136 return pi->num_cmds; /* used only for 0/nonzero check */
5139 static void done_pipe(struct parse_context *ctx, pipe_style type)
5143 debug_printf_parse("done_pipe entered, followup %d\n", type);
5144 /* Close previous command */
5145 not_null = done_command(ctx);
5146 ctx->pipe->followup = type;
5148 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5149 ctx->ctx_inverted = 0;
5150 ctx->pipe->res_word = ctx->ctx_res_w;
5153 /* Without this check, even just <enter> on command line generates
5154 * tree of three NOPs (!). Which is harmless but annoying.
5155 * IOW: it is safe to do it unconditionally. */
5158 || ctx->ctx_res_w == RES_FI
5160 #if ENABLE_HUSH_LOOPS
5161 || ctx->ctx_res_w == RES_DONE
5162 || ctx->ctx_res_w == RES_FOR
5163 || ctx->ctx_res_w == RES_IN
5165 #if ENABLE_HUSH_CASE
5166 || ctx->ctx_res_w == RES_ESAC
5170 debug_printf_parse("done_pipe: adding new pipe: "
5171 "not_null:%d ctx->ctx_res_w:%d\n",
5172 not_null, ctx->ctx_res_w);
5174 ctx->pipe->next = new_p;
5176 /* RES_THEN, RES_DO etc are "sticky" -
5177 * they remain set for pipes inside if/while.
5178 * This is used to control execution.
5179 * RES_FOR and RES_IN are NOT sticky (needed to support
5180 * cases where variable or value happens to match a keyword):
5182 #if ENABLE_HUSH_LOOPS
5183 if (ctx->ctx_res_w == RES_FOR
5184 || ctx->ctx_res_w == RES_IN)
5185 ctx->ctx_res_w = RES_NONE;
5187 #if ENABLE_HUSH_CASE
5188 if (ctx->ctx_res_w == RES_MATCH)
5189 ctx->ctx_res_w = RES_CASE_BODY;
5190 if (ctx->ctx_res_w == RES_CASE)
5191 ctx->ctx_res_w = RES_CASE_IN;
5193 ctx->command = NULL; /* trick done_command below */
5194 /* Create the memory for command, roughly:
5195 * ctx->pipe->cmds = new struct command;
5196 * ctx->command = &ctx->pipe->cmds[0];
5199 //debug_print_tree(ctx->list_head, 10);
5201 debug_printf_parse("done_pipe return\n");
5204 static void initialize_context(struct parse_context *ctx)
5206 memset(ctx, 0, sizeof(*ctx));
5207 ctx->pipe = ctx->list_head = new_pipe();
5208 /* Create the memory for command, roughly:
5209 * ctx->pipe->cmds = new struct command;
5210 * ctx->command = &ctx->pipe->cmds[0];
5215 /* If a reserved word is found and processed, parse context is modified
5216 * and 1 is returned.
5219 struct reserved_combo {
5222 unsigned char assignment_flag;
5226 FLAG_END = (1 << RES_NONE ),
5228 FLAG_IF = (1 << RES_IF ),
5229 FLAG_THEN = (1 << RES_THEN ),
5230 FLAG_ELIF = (1 << RES_ELIF ),
5231 FLAG_ELSE = (1 << RES_ELSE ),
5232 FLAG_FI = (1 << RES_FI ),
5234 # if ENABLE_HUSH_LOOPS
5235 FLAG_FOR = (1 << RES_FOR ),
5236 FLAG_WHILE = (1 << RES_WHILE),
5237 FLAG_UNTIL = (1 << RES_UNTIL),
5238 FLAG_DO = (1 << RES_DO ),
5239 FLAG_DONE = (1 << RES_DONE ),
5240 FLAG_IN = (1 << RES_IN ),
5242 # if ENABLE_HUSH_CASE
5243 FLAG_MATCH = (1 << RES_MATCH),
5244 FLAG_ESAC = (1 << RES_ESAC ),
5246 FLAG_START = (1 << RES_XXXX ),
5249 static const struct reserved_combo* match_reserved_word(o_string *word)
5251 /* Mostly a list of accepted follow-up reserved words.
5252 * FLAG_END means we are done with the sequence, and are ready
5253 * to turn the compound list into a command.
5254 * FLAG_START means the word must start a new compound list.
5256 static const struct reserved_combo reserved_list[] = {
5258 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5259 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5260 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5261 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5262 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5263 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5265 # if ENABLE_HUSH_LOOPS
5266 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5267 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5268 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5269 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5270 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5271 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5273 # if ENABLE_HUSH_CASE
5274 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5275 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5278 const struct reserved_combo *r;
5280 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5281 if (strcmp(word->data, r->literal) == 0)
5286 /* Return 0: not a keyword, 1: keyword
5288 static int reserved_word(o_string *word, struct parse_context *ctx)
5290 # if ENABLE_HUSH_CASE
5291 static const struct reserved_combo reserved_match = {
5292 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5295 const struct reserved_combo *r;
5299 r = match_reserved_word(word);
5303 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5304 # if ENABLE_HUSH_CASE
5305 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5306 /* "case word IN ..." - IN part starts first MATCH part */
5307 r = &reserved_match;
5310 if (r->flag == 0) { /* '!' */
5311 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5312 syntax_error("! ! command");
5313 ctx->ctx_res_w = RES_SNTX;
5315 ctx->ctx_inverted = 1;
5318 if (r->flag & FLAG_START) {
5319 struct parse_context *old;
5321 old = xmalloc(sizeof(*old));
5322 debug_printf_parse("push stack %p\n", old);
5323 *old = *ctx; /* physical copy */
5324 initialize_context(ctx);
5326 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5327 syntax_error_at(word->data);
5328 ctx->ctx_res_w = RES_SNTX;
5331 /* "{...} fi" is ok. "{...} if" is not
5333 * if { echo foo; } then { echo bar; } fi */
5334 if (ctx->command->group)
5335 done_pipe(ctx, PIPE_SEQ);
5338 ctx->ctx_res_w = r->res;
5339 ctx->old_flag = r->flag;
5340 word->o_assignment = r->assignment_flag;
5342 if (ctx->old_flag & FLAG_END) {
5343 struct parse_context *old;
5345 done_pipe(ctx, PIPE_SEQ);
5346 debug_printf_parse("pop stack %p\n", ctx->stack);
5348 old->command->group = ctx->list_head;
5349 old->command->cmd_type = CMD_NORMAL;
5351 o_addstr(&old->as_string, ctx->as_string.data);
5352 o_free_unsafe(&ctx->as_string);
5353 old->command->group_as_string = xstrdup(old->as_string.data);
5354 debug_printf_parse("pop, remembering as:'%s'\n",
5355 old->command->group_as_string);
5357 *ctx = *old; /* physical copy */
5362 #endif /* HAS_KEYWORDS */
5364 /* Word is complete, look at it and update parsing context.
5365 * Normal return is 0. Syntax errors return 1.
5366 * Note: on return, word is reset, but not o_free'd!
5368 static int done_word(o_string *word, struct parse_context *ctx)
5370 struct command *command = ctx->command;
5372 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5373 if (word->length == 0 && word->o_quoted == 0) {
5374 debug_printf_parse("done_word return 0: true null, ignored\n");
5378 if (ctx->pending_redirect) {
5379 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5380 * only if run as "bash", not "sh" */
5381 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5383 * ...the word that follows the redirection operator
5384 * shall be subjected to tilde expansion, parameter expansion,
5385 * command substitution, arithmetic expansion, and quote
5386 * removal. Pathname expansion shall not be performed
5387 * on the word by a non-interactive shell; an interactive
5388 * shell may perform it, but shall do so only when
5389 * the expansion would result in one word."
5391 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5392 /* Cater for >\file case:
5393 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5394 * Same with heredocs:
5395 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5397 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5398 unbackslash(ctx->pending_redirect->rd_filename);
5399 /* Is it <<"HEREDOC"? */
5400 if (word->o_quoted) {
5401 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5404 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5405 ctx->pending_redirect = NULL;
5407 /* If this word wasn't an assignment, next ones definitely
5408 * can't be assignments. Even if they look like ones. */
5409 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5410 && word->o_assignment != WORD_IS_KEYWORD
5412 word->o_assignment = NOT_ASSIGNMENT;
5414 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5415 command->assignment_cnt++;
5416 word->o_assignment = MAYBE_ASSIGNMENT;
5420 # if ENABLE_HUSH_CASE
5421 if (ctx->ctx_dsemicolon
5422 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5424 /* already done when ctx_dsemicolon was set to 1: */
5425 /* ctx->ctx_res_w = RES_MATCH; */
5426 ctx->ctx_dsemicolon = 0;
5429 if (!command->argv /* if it's the first word... */
5430 # if ENABLE_HUSH_LOOPS
5431 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5432 && ctx->ctx_res_w != RES_IN
5434 # if ENABLE_HUSH_CASE
5435 && ctx->ctx_res_w != RES_CASE
5438 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5439 if (reserved_word(word, ctx)) {
5440 o_reset_to_empty_unquoted(word);
5441 debug_printf_parse("done_word return %d\n",
5442 (ctx->ctx_res_w == RES_SNTX));
5443 return (ctx->ctx_res_w == RES_SNTX);
5445 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5446 if (strcmp(word->data, "export") == 0
5447 # if ENABLE_HUSH_LOCAL
5448 || strcmp(word->data, "local") == 0
5451 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5454 # if ENABLE_HUSH_BASH_COMPAT
5455 if (strcmp(word->data, "[[") == 0) {
5456 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5462 if (command->group) {
5463 /* "{ echo foo; } echo bar" - bad */
5464 syntax_error_at(word->data);
5465 debug_printf_parse("done_word return 1: syntax error, "
5466 "groups and arglists don't mix\n");
5469 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5470 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5471 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5472 /* (otherwise it's known to be not empty and is already safe) */
5474 /* exclude "$@" - it can expand to no word despite "" */
5475 char *p = word->data;
5476 while (p[0] == SPECIAL_VAR_SYMBOL
5477 && (p[1] & 0x7f) == '@'
5478 && p[2] == SPECIAL_VAR_SYMBOL
5482 if (p == word->data || p[0] != '\0') {
5483 /* saw no "$@", or not only "$@" but some
5484 * real text is there too */
5485 /* insert "empty variable" reference, this makes
5486 * e.g. "", $empty"" etc to not disappear */
5487 o_addchr(word, SPECIAL_VAR_SYMBOL);
5488 o_addchr(word, SPECIAL_VAR_SYMBOL);
5491 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5492 debug_print_strings("word appended to argv", command->argv);
5495 #if ENABLE_HUSH_LOOPS
5496 if (ctx->ctx_res_w == RES_FOR) {
5498 || !is_well_formed_var_name(command->argv[0], '\0')
5500 /* bash says just "not a valid identifier" */
5501 syntax_error("not a valid identifier in for");
5504 /* Force FOR to have just one word (variable name) */
5505 /* NB: basically, this makes hush see "for v in ..."
5506 * syntax as if it is "for v; in ...". FOR and IN become
5507 * two pipe structs in parse tree. */
5508 done_pipe(ctx, PIPE_SEQ);
5511 #if ENABLE_HUSH_CASE
5512 /* Force CASE to have just one word */
5513 if (ctx->ctx_res_w == RES_CASE) {
5514 done_pipe(ctx, PIPE_SEQ);
5518 o_reset_to_empty_unquoted(word);
5520 debug_printf_parse("done_word return 0\n");
5525 /* Peek ahead in the input to find out if we have a "&n" construct,
5526 * as in "2>&1", that represents duplicating a file descriptor.
5528 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5529 * REDIRFD_SYNTAX_ERR if syntax error,
5530 * REDIRFD_TO_FILE if no & was seen,
5531 * or the number found.
5534 #define parse_redir_right_fd(as_string, input) \
5535 parse_redir_right_fd(input)
5537 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5543 return REDIRFD_TO_FILE;
5545 ch = i_getch(input); /* get the & */
5546 nommu_addchr(as_string, ch);
5549 ch = i_getch(input);
5550 nommu_addchr(as_string, ch);
5551 return REDIRFD_CLOSE;
5555 while (ch != EOF && isdigit(ch)) {
5556 d = d*10 + (ch-'0');
5558 ch = i_getch(input);
5559 nommu_addchr(as_string, ch);
5564 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5566 bb_error_msg("ambiguous redirect");
5567 return REDIRFD_SYNTAX_ERR;
5570 /* Return code is 0 normal, 1 if a syntax error is detected
5572 static int parse_redirect(struct parse_context *ctx,
5575 struct in_str *input)
5577 struct command *command = ctx->command;
5578 struct redir_struct *redir;
5579 struct redir_struct **redirp;
5582 dup_num = REDIRFD_TO_FILE;
5583 if (style != REDIRECT_HEREDOC) {
5584 /* Check for a '>&1' type redirect */
5585 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5586 if (dup_num == REDIRFD_SYNTAX_ERR)
5589 int ch = i_peek(input);
5590 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5591 if (dup_num) { /* <<-... */
5592 ch = i_getch(input);
5593 nommu_addchr(&ctx->as_string, ch);
5598 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5599 int ch = i_peek(input);
5601 /* >|FILE redirect ("clobbering" >).
5602 * Since we do not support "set -o noclobber" yet,
5603 * >| and > are the same for now. Just eat |.
5605 ch = i_getch(input);
5606 nommu_addchr(&ctx->as_string, ch);
5610 /* Create a new redir_struct and append it to the linked list */
5611 redirp = &command->redirects;
5612 while ((redir = *redirp) != NULL) {
5613 redirp = &(redir->next);
5615 *redirp = redir = xzalloc(sizeof(*redir));
5616 /* redir->next = NULL; */
5617 /* redir->rd_filename = NULL; */
5618 redir->rd_type = style;
5619 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5621 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5622 redir_table[style].descrip);
5624 redir->rd_dup = dup_num;
5625 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5626 /* Erik had a check here that the file descriptor in question
5627 * is legit; I postpone that to "run time"
5628 * A "-" representation of "close me" shows up as a -3 here */
5629 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5630 redir->rd_fd, redir->rd_dup);
5632 /* Set ctx->pending_redirect, so we know what to do at the
5633 * end of the next parsed word. */
5634 ctx->pending_redirect = redir;
5639 /* If a redirect is immediately preceded by a number, that number is
5640 * supposed to tell which file descriptor to redirect. This routine
5641 * looks for such preceding numbers. In an ideal world this routine
5642 * needs to handle all the following classes of redirects...
5643 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5644 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5645 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5646 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5648 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5650 * ... If n is quoted, the number shall not be recognized as part of
5651 * the redirection expression. For example:
5653 * writes the character 2 into file a"
5654 * We are getting it right by setting ->o_quoted on any \<char>
5656 * A -1 return means no valid number was found,
5657 * the caller should use the appropriate default for this redirection.
5659 static int redirect_opt_num(o_string *o)
5663 if (o->data == NULL)
5665 num = bb_strtou(o->data, NULL, 10);
5666 if (errno || num < 0)
5668 o_reset_to_empty_unquoted(o);
5673 #define fetch_till_str(as_string, input, word, skip_tabs) \
5674 fetch_till_str(input, word, skip_tabs)
5676 static char *fetch_till_str(o_string *as_string,
5677 struct in_str *input,
5681 o_string heredoc = NULL_O_STRING;
5687 ch = i_getch(input);
5688 nommu_addchr(as_string, ch);
5690 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5691 heredoc.data[past_EOL] = '\0';
5692 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5693 return heredoc.data;
5696 o_addchr(&heredoc, ch);
5697 past_EOL = heredoc.length;
5700 ch = i_getch(input);
5701 nommu_addchr(as_string, ch);
5702 } while (skip_tabs && ch == '\t');
5703 } while (ch == '\n');
5706 o_free_unsafe(&heredoc);
5709 o_addchr(&heredoc, ch);
5710 nommu_addchr(as_string, ch);
5714 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5715 * and load them all. There should be exactly heredoc_cnt of them.
5717 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5719 struct pipe *pi = ctx->list_head;
5721 while (pi && heredoc_cnt) {
5723 struct command *cmd = pi->cmds;
5725 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5727 cmd->argv ? cmd->argv[0] : "NONE");
5728 for (i = 0; i < pi->num_cmds; i++) {
5729 struct redir_struct *redir = cmd->redirects;
5731 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5732 i, cmd->argv ? cmd->argv[0] : "NONE");
5734 if (redir->rd_type == REDIRECT_HEREDOC) {
5737 redir->rd_type = REDIRECT_HEREDOC2;
5738 /* redir->rd_dup is (ab)used to indicate <<- */
5739 p = fetch_till_str(&ctx->as_string, input,
5740 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5742 syntax_error("unexpected EOF in here document");
5745 free(redir->rd_filename);
5746 redir->rd_filename = p;
5749 redir = redir->next;
5756 /* Should be 0. If it isn't, it's a parse error */
5758 bb_error_msg_and_die("heredoc BUG 2");
5764 #if ENABLE_HUSH_TICK
5765 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5770 char **to_free = NULL;
5774 pid = BB_MMU ? xfork() : xvfork();
5775 if (pid == 0) { /* child */
5776 disable_restore_tty_pgrp_on_exit();
5777 /* Process substitution is not considered to be usual
5778 * 'command execution'.
5779 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5786 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5787 close(channel[0]); /* NB: close _first_, then move fd! */
5788 xmove_fd(channel[1], 1);
5789 /* Prevent it from trying to handle ctrl-z etc */
5790 IF_HUSH_JOB(G.run_list_level = 1;)
5791 /* Awful hack for `trap` or $(trap).
5793 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5794 * contains an example where "trap" is executed in a subshell:
5796 * save_traps=$(trap)
5798 * eval "$save_traps"
5800 * Standard does not say that "trap" in subshell shall print
5801 * parent shell's traps. It only says that its output
5802 * must have suitable form, but then, in the above example
5803 * (which is not supposed to be normative), it implies that.
5805 * bash (and probably other shell) does implement it
5806 * (traps are reset to defaults, but "trap" still shows them),
5807 * but as a result, "trap" logic is hopelessly messed up:
5810 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5811 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5812 * # true | trap <--- trap is in subshell - no output (ditto)
5813 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5814 * trap -- 'echo Ho' SIGWINCH
5815 * # echo `(trap)` <--- in subshell in subshell - output
5816 * trap -- 'echo Ho' SIGWINCH
5817 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5818 * trap -- 'echo Ho' SIGWINCH
5820 * The rules when to forget and when to not forget traps
5821 * get really complex and nonsensical.
5823 * Our solution: ONLY bare $(trap) or `trap` is special.
5825 s = skip_whitespace(s);
5826 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5828 static const char *const argv[] = { NULL, NULL };
5829 builtin_trap((char**)argv);
5830 exit(0); /* not _exit() - we need to fflush */
5833 reset_traps_to_defaults();
5834 parse_and_run_string(s);
5835 _exit(G.last_exitcode);
5837 /* We re-execute after vfork on NOMMU. This makes this script safe:
5838 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5839 * huge=`cat BIG` # was blocking here forever
5842 re_execute_shell(&to_free,
5852 # if ENABLE_HUSH_FAST
5854 //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);
5856 enable_restore_tty_pgrp_on_exit();
5861 close_on_exec_on(channel[0]);
5862 return xfdopen_for_read(channel[0]);
5865 /* Return code is exit status of the process that is run. */
5866 static int process_command_subs(o_string *dest, const char *s)
5869 struct in_str pipe_str;
5871 int status, ch, eol_cnt;
5873 fp = generate_stream_from_string(s, &pid);
5875 /* Now send results of command back into original context */
5876 setup_file_in_str(&pipe_str, fp);
5878 while ((ch = i_getch(&pipe_str)) != EOF) {
5884 o_addchr(dest, '\n');
5887 o_addQchr(dest, ch);
5890 debug_printf("done reading from `cmd` pipe, closing it\n");
5892 /* We need to extract exitcode. Test case
5893 * "true; echo `sleep 1; false` $?"
5895 safe_waitpid(pid, &status, 0);
5896 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5897 return WEXITSTATUS(status);
5899 #endif /* ENABLE_HUSH_TICK */
5901 #if !ENABLE_HUSH_FUNCTIONS
5902 #define parse_group(dest, ctx, input, ch) \
5903 parse_group(ctx, input, ch)
5905 static int parse_group(o_string *dest, struct parse_context *ctx,
5906 struct in_str *input, int ch)
5908 /* dest contains characters seen prior to ( or {.
5909 * Typically it's empty, but for function defs,
5910 * it contains function name (without '()'). */
5911 struct pipe *pipe_list;
5913 struct command *command = ctx->command;
5915 debug_printf_parse("parse_group entered\n");
5916 #if ENABLE_HUSH_FUNCTIONS
5917 if (ch == '(' && !dest->o_quoted) {
5919 if (done_word(dest, ctx))
5922 goto skip; /* (... */
5923 if (command->argv[1]) { /* word word ... (... */
5924 syntax_error_unexpected_ch('(');
5927 /* it is "word(..." or "word (..." */
5929 ch = i_getch(input);
5930 while (ch == ' ' || ch == '\t');
5932 syntax_error_unexpected_ch(ch);
5935 nommu_addchr(&ctx->as_string, ch);
5937 ch = i_getch(input);
5938 while (ch == ' ' || ch == '\t' || ch == '\n');
5940 syntax_error_unexpected_ch(ch);
5943 nommu_addchr(&ctx->as_string, ch);
5944 command->cmd_type = CMD_FUNCDEF;
5949 #if 0 /* Prevented by caller */
5950 if (command->argv /* word [word]{... */
5951 || dest->length /* word{... */
5952 || dest->o_quoted /* ""{... */
5955 debug_printf_parse("parse_group return 1: "
5956 "syntax error, groups and arglists don't mix\n");
5961 #if ENABLE_HUSH_FUNCTIONS
5967 command->cmd_type = CMD_SUBSHELL;
5969 /* bash does not allow "{echo...", requires whitespace */
5970 ch = i_getch(input);
5971 if (ch != ' ' && ch != '\t' && ch != '\n') {
5972 syntax_error_unexpected_ch(ch);
5975 nommu_addchr(&ctx->as_string, ch);
5980 # define as_string NULL
5982 char *as_string = NULL;
5984 pipe_list = parse_stream(&as_string, input, endch);
5987 o_addstr(&ctx->as_string, as_string);
5989 /* empty ()/{} or parse error? */
5990 if (!pipe_list || pipe_list == ERR_PTR) {
5991 /* parse_stream already emitted error msg */
5994 debug_printf_parse("parse_group return 1: "
5995 "parse_stream returned %p\n", pipe_list);
5998 command->group = pipe_list;
6000 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6001 command->group_as_string = as_string;
6002 debug_printf_parse("end of group, remembering as:'%s'\n",
6003 command->group_as_string);
6007 debug_printf_parse("parse_group return 0\n");
6009 /* command remains "open", available for possible redirects */
6012 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6013 /* Subroutines for copying $(...) and `...` things */
6014 static void add_till_backquote(o_string *dest, struct in_str *input);
6016 static void add_till_single_quote(o_string *dest, struct in_str *input)
6019 int ch = i_getch(input);
6021 syntax_error_unterm_ch('\'');
6022 /*xfunc_die(); - redundant */
6029 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6030 static void add_till_double_quote(o_string *dest, struct in_str *input)
6033 int ch = i_getch(input);
6035 syntax_error_unterm_ch('"');
6036 /*xfunc_die(); - redundant */
6040 if (ch == '\\') { /* \x. Copy both chars. */
6042 ch = i_getch(input);
6046 add_till_backquote(dest, input);
6050 //if (ch == '$') ...
6053 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6055 * "Within the backquoted style of command substitution, backslash
6056 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6057 * The search for the matching backquote shall be satisfied by the first
6058 * backquote found without a preceding backslash; during this search,
6059 * if a non-escaped backquote is encountered within a shell comment,
6060 * a here-document, an embedded command substitution of the $(command)
6061 * form, or a quoted string, undefined results occur. A single-quoted
6062 * or double-quoted string that begins, but does not end, within the
6063 * "`...`" sequence produces undefined results."
6065 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6067 static void add_till_backquote(o_string *dest, struct in_str *input)
6070 int ch = i_getch(input);
6072 syntax_error_unterm_ch('`');
6073 /*xfunc_die(); - redundant */
6078 /* \x. Copy both chars unless it is \` */
6079 int ch2 = i_getch(input);
6081 syntax_error_unterm_ch('`');
6082 /*xfunc_die(); - redundant */
6084 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6091 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6092 * quoting and nested ()s.
6093 * "With the $(command) style of command substitution, all characters
6094 * following the open parenthesis to the matching closing parenthesis
6095 * constitute the command. Any valid shell script can be used for command,
6096 * except a script consisting solely of redirections which produces
6097 * unspecified results."
6099 * echo $(echo '(TEST)' BEST) (TEST) BEST
6100 * echo $(echo 'TEST)' BEST) TEST) BEST
6101 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6103 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6104 * can contain arbitrary constructs, just like $(cmd).
6105 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6106 * for ${var:N[:M]} parsing.
6108 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6109 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6112 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6113 # if ENABLE_HUSH_BASH_COMPAT
6114 char end_char2 = end_ch >> 8;
6116 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6119 ch = i_getch(input);
6121 syntax_error_unterm_ch(end_ch);
6122 /*xfunc_die(); - redundant */
6124 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6127 /* we look for closing )) of $((EXPR)) */
6128 if (i_peek(input) == end_ch) {
6129 i_getch(input); /* eat second ')' */
6134 if (ch == '(' || ch == '{') {
6135 ch = (ch == '(' ? ')' : '}');
6136 add_till_closing_bracket(dest, input, ch);
6141 add_till_single_quote(dest, input);
6146 add_till_double_quote(dest, input);
6151 add_till_backquote(dest, input);
6156 /* \x. Copy verbatim. Important for \(, \) */
6157 ch = i_getch(input);
6159 syntax_error_unterm_ch(')');
6160 /*xfunc_die(); - redundant */
6168 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6170 /* Return code: 0 for OK, 1 for syntax error */
6172 #define parse_dollar(as_string, dest, input) \
6173 parse_dollar(dest, input)
6174 #define as_string NULL
6176 static int parse_dollar(o_string *as_string,
6178 struct in_str *input)
6180 int ch = i_peek(input); /* first character after the $ */
6181 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6183 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6185 ch = i_getch(input);
6186 nommu_addchr(as_string, ch);
6188 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6190 debug_printf_parse(": '%c'\n", ch);
6191 o_addchr(dest, ch | quote_mask);
6194 if (!isalnum(ch) && ch != '_')
6196 ch = i_getch(input);
6197 nommu_addchr(as_string, ch);
6199 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6200 } else if (isdigit(ch)) {
6202 ch = i_getch(input);
6203 nommu_addchr(as_string, ch);
6204 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6205 debug_printf_parse(": '%c'\n", ch);
6206 o_addchr(dest, ch | quote_mask);
6207 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6208 } else switch (ch) {
6210 case '!': /* last bg pid */
6211 case '?': /* last exit code */
6212 case '#': /* number of args */
6213 case '*': /* args */
6214 case '@': /* args */
6215 goto make_one_char_var;
6217 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6219 ch = i_getch(input); /* eat '{' */
6220 nommu_addchr(as_string, ch);
6222 ch = i_getch(input); /* first char after '{' */
6223 nommu_addchr(as_string, ch);
6224 /* It should be ${?}, or ${#var},
6225 * or even ${?+subst} - operator acting on a special variable,
6226 * or the beginning of variable name.
6228 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6230 syntax_error_unterm_str("${name}");
6231 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6236 /* It's possible to just call add_till_closing_bracket() at this point.
6237 * However, this regresses some of our testsuite cases
6238 * which check invalid constructs like ${%}.
6239 * Oh well... let's check that the var name part is fine... */
6245 debug_printf_parse(": '%c'\n", ch);
6247 ch = i_getch(input);
6248 nommu_addchr(as_string, ch);
6252 if (!isalnum(ch) && ch != '_') {
6254 unsigned char last_ch;
6255 /* handle parameter expansions
6256 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6258 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6259 goto bad_dollar_syntax;
6262 /* Eat everything until closing '}' (or ':') */
6264 if (ENABLE_HUSH_BASH_COMPAT
6266 && !strchr("%#:-=+?"+3, i_peek(input))
6268 /* It's ${var:N[:M]} thing */
6269 end_ch = '}' * 0x100 + ':';
6274 #if ENABLE_HUSH_DOLLAR_OPS
6275 last_ch = add_till_closing_bracket(dest, input, end_ch);
6277 #error Simple code to only allow ${var} is not implemented
6280 o_addstr(as_string, dest->data + pos);
6281 o_addchr(as_string, last_ch);
6284 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6285 /* close the first block: */
6286 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6287 /* while parsing N from ${var:N[:M]}... */
6288 if ((end_ch & 0xff) == last_ch) {
6289 /* ...got ':' - parse the rest */
6293 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6294 o_addstr(dest, "999999999");
6299 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6302 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6306 ch = i_getch(input);
6307 nommu_addchr(as_string, ch);
6308 # if ENABLE_SH_MATH_SUPPORT
6309 if (i_peek(input) == '(') {
6310 ch = i_getch(input);
6311 nommu_addchr(as_string, ch);
6312 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6313 o_addchr(dest, /*quote_mask |*/ '+');
6316 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6318 o_addstr(as_string, dest->data + pos);
6319 o_addchr(as_string, ')');
6320 o_addchr(as_string, ')');
6322 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6326 # if ENABLE_HUSH_TICK
6327 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6328 o_addchr(dest, quote_mask | '`');
6331 add_till_closing_bracket(dest, input, ')');
6333 o_addstr(as_string, dest->data + pos);
6334 o_addchr(as_string, ')');
6336 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6342 ch = i_getch(input);
6343 nommu_addchr(as_string, ch);
6345 if (isalnum(ch)) { /* it's $_name or $_123 */
6350 /* TODO: $_ and $-: */
6351 /* $_ Shell or shell script name; or last argument of last command
6352 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6353 * but in command's env, set to full pathname used to invoke it */
6354 /* $- Option flags set by set builtin or shell options (-i etc) */
6356 o_addQchr(dest, '$');
6358 debug_printf_parse("parse_dollar return 0\n");
6364 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6365 parse_stream_dquoted(dest, input, dquote_end)
6366 #define as_string NULL
6368 static int parse_stream_dquoted(o_string *as_string,
6370 struct in_str *input,
6377 ch = i_getch(input);
6379 nommu_addchr(as_string, ch);
6380 if (ch == dquote_end) { /* may be only '"' or EOF */
6381 if (dest->o_assignment == NOT_ASSIGNMENT)
6382 dest->o_escape ^= 1;
6383 debug_printf_parse("parse_stream_dquoted return 0\n");
6386 /* note: can't move it above ch == dquote_end check! */
6388 syntax_error_unterm_ch('"');
6389 /*xfunc_die(); - redundant */
6393 next = i_peek(input);
6395 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6396 ch, ch, dest->o_escape);
6399 syntax_error("\\<eof>");
6403 * "The backslash retains its special meaning [in "..."]
6404 * only when followed by one of the following characters:
6405 * $, `, ", \, or <newline>. A double quote may be quoted
6406 * within double quotes by preceding it with a backslash."
6408 if (strchr("$`\"\\\n", next) != NULL) {
6409 ch = i_getch(input);
6411 o_addqchr(dest, ch);
6412 nommu_addchr(as_string, ch);
6415 o_addqchr(dest, '\\');
6416 nommu_addchr(as_string, '\\');
6421 if (parse_dollar(as_string, dest, input) != 0) {
6422 debug_printf_parse("parse_stream_dquoted return 1: "
6423 "parse_dollar returned non-0\n");
6428 #if ENABLE_HUSH_TICK
6430 //unsigned pos = dest->length;
6431 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6432 o_addchr(dest, 0x80 | '`');
6433 add_till_backquote(dest, input);
6434 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6435 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6439 o_addQchr(dest, ch);
6441 && (dest->o_assignment == MAYBE_ASSIGNMENT
6442 || dest->o_assignment == WORD_IS_KEYWORD)
6443 && is_well_formed_var_name(dest->data, '=')
6445 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6452 * Scan input until EOF or end_trigger char.
6453 * Return a list of pipes to execute, or NULL on EOF
6454 * or if end_trigger character is met.
6455 * On syntax error, exit is shell is not interactive,
6456 * reset parsing machinery and start parsing anew,
6457 * or return ERR_PTR.
6459 static struct pipe *parse_stream(char **pstring,
6460 struct in_str *input,
6463 struct parse_context ctx;
6464 o_string dest = NULL_O_STRING;
6468 /* Double-quote state is handled in the state variable is_in_dquote.
6469 * A single-quote triggers a bypass of the main loop until its mate is
6470 * found. When recursing, quote state is passed in via dest->o_escape.
6472 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6473 end_trigger ? end_trigger : 'X');
6476 /* If very first arg is "" or '', dest.data may end up NULL.
6477 * Preventing this: */
6478 o_addchr(&dest, '\0');
6481 G.ifs = get_local_var_value("IFS");
6486 #if ENABLE_HUSH_INTERACTIVE
6487 input->promptmode = 0; /* PS1 */
6489 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6490 initialize_context(&ctx);
6495 const char *is_special;
6499 redir_type redir_style;
6502 /* dest.o_quoted = 1; - already is (see below) */
6503 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6506 /* We reached closing '"' */
6509 ch = i_getch(input);
6510 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6511 ch, ch, dest.o_escape);
6516 syntax_error_unterm_str("here document");
6519 /* end_trigger == '}' case errors out earlier,
6520 * checking only ')' */
6521 if (end_trigger == ')') {
6522 syntax_error_unterm_ch('('); /* exits */
6523 /* goto parse_error; */
6526 if (done_word(&dest, &ctx)) {
6530 done_pipe(&ctx, PIPE_SEQ);
6532 /* If we got nothing... */
6533 /* (this makes bare "&" cmd a no-op.
6534 * bash says: "syntax error near unexpected token '&'") */
6535 if (pi->num_cmds == 0
6536 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6542 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6544 *pstring = ctx.as_string.data;
6546 o_free_unsafe(&ctx.as_string);
6549 debug_printf_parse("parse_stream return %p\n", pi);
6552 nommu_addchr(&ctx.as_string, ch);
6556 next = i_peek(input);
6558 is_special = "{}<>;&|()#'" /* special outside of "str" */
6559 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6560 /* Are { and } special here? */
6561 if (ctx.command->argv /* word [word]{... - non-special */
6562 || dest.length /* word{... - non-special */
6563 || dest.o_quoted /* ""{... - non-special */
6564 || (next != ';' /* }; - special */
6565 && next != ')' /* }) - special */
6566 && next != '&' /* }& and }&& ... - special */
6567 && next != '|' /* }|| ... - special */
6568 && !strchr(G.ifs, next) /* {word - non-special */
6571 /* They are not special, skip "{}" */
6574 is_special = strchr(is_special, ch);
6575 is_ifs = strchr(G.ifs, ch);
6577 if (!is_special && !is_ifs) { /* ordinary char */
6579 o_addQchr(&dest, ch);
6580 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6581 || dest.o_assignment == WORD_IS_KEYWORD)
6583 && is_well_formed_var_name(dest.data, '=')
6585 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6591 if (done_word(&dest, &ctx)) {
6595 #if ENABLE_HUSH_CASE
6596 /* "case ... in <newline> word) ..." -
6597 * newlines are ignored (but ';' wouldn't be) */
6598 if (ctx.command->argv == NULL
6599 && ctx.ctx_res_w == RES_MATCH
6604 /* Treat newline as a command separator. */
6605 done_pipe(&ctx, PIPE_SEQ);
6606 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6608 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6613 dest.o_assignment = MAYBE_ASSIGNMENT;
6615 /* note: if (is_ifs) continue;
6616 * will still trigger for us */
6620 /* "cmd}" or "cmd }..." without semicolon or &:
6621 * } is an ordinary char in this case, even inside { cmd; }
6622 * Pathological example: { ""}; } should exec "}" cmd
6625 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6626 || dest.length != 0 /* word} */
6627 || dest.o_quoted /* ""} */
6631 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6632 goto skip_end_trigger;
6633 /* else: } does terminate a group */
6636 if (end_trigger && end_trigger == ch
6637 && (ch != ';' || heredoc_cnt == 0)
6638 #if ENABLE_HUSH_CASE
6640 || ctx.ctx_res_w != RES_MATCH
6641 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6646 /* This is technically valid:
6647 * { cat <<HERE; }; echo Ok
6651 * but we don't support this.
6652 * We require heredoc to be in enclosing {}/(),
6655 syntax_error_unterm_str("here document");
6658 if (done_word(&dest, &ctx)) {
6661 done_pipe(&ctx, PIPE_SEQ);
6662 dest.o_assignment = MAYBE_ASSIGNMENT;
6663 /* Do we sit outside of any if's, loops or case's? */
6665 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6669 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6671 *pstring = ctx.as_string.data;
6673 o_free_unsafe(&ctx.as_string);
6676 debug_printf_parse("parse_stream return %p: "
6677 "end_trigger char found\n",
6679 return ctx.list_head;
6686 /* Catch <, > before deciding whether this word is
6687 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6690 redir_fd = redirect_opt_num(&dest);
6691 if (done_word(&dest, &ctx)) {
6694 redir_style = REDIRECT_OVERWRITE;
6696 redir_style = REDIRECT_APPEND;
6697 ch = i_getch(input);
6698 nommu_addchr(&ctx.as_string, ch);
6701 else if (next == '(') {
6702 syntax_error(">(process) not supported");
6706 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6708 continue; /* back to top of while (1) */
6710 redir_fd = redirect_opt_num(&dest);
6711 if (done_word(&dest, &ctx)) {
6714 redir_style = REDIRECT_INPUT;
6716 redir_style = REDIRECT_HEREDOC;
6718 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6719 ch = i_getch(input);
6720 nommu_addchr(&ctx.as_string, ch);
6721 } else if (next == '>') {
6722 redir_style = REDIRECT_IO;
6723 ch = i_getch(input);
6724 nommu_addchr(&ctx.as_string, ch);
6727 else if (next == '(') {
6728 syntax_error("<(process) not supported");
6732 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6734 continue; /* back to top of while (1) */
6737 if (dest.o_assignment == MAYBE_ASSIGNMENT
6738 /* check that we are not in word in "a=1 2>word b=1": */
6739 && !ctx.pending_redirect
6741 /* ch is a special char and thus this word
6742 * cannot be an assignment */
6743 dest.o_assignment = NOT_ASSIGNMENT;
6746 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6750 if (dest.length == 0) {
6753 if (ch == EOF || ch == '\n')
6756 /* note: we do not add it to &ctx.as_string */
6758 nommu_addchr(&ctx.as_string, '\n');
6760 o_addQchr(&dest, ch);
6765 syntax_error("\\<eof>");
6768 ch = i_getch(input);
6770 o_addchr(&dest, '\\');
6771 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6772 o_addchr(&dest, ch);
6773 nommu_addchr(&ctx.as_string, ch);
6774 /* Example: echo Hello \2>file
6775 * we need to know that word 2 is quoted */
6780 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6781 ctx.as_string.data[--ctx.as_string.length] = '\0';
6786 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6787 debug_printf_parse("parse_stream parse error: "
6788 "parse_dollar returned non-0\n");
6795 ch = i_getch(input);
6797 syntax_error_unterm_ch('\'');
6798 /*xfunc_die(); - redundant */
6800 nommu_addchr(&ctx.as_string, ch);
6803 o_addqchr(&dest, ch);
6808 is_in_dquote ^= 1; /* invert */
6809 if (dest.o_assignment == NOT_ASSIGNMENT)
6812 #if ENABLE_HUSH_TICK
6816 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6817 o_addchr(&dest, '`');
6819 add_till_backquote(&dest, input);
6821 o_addstr(&ctx.as_string, dest.data + pos);
6822 o_addchr(&ctx.as_string, '`');
6824 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6825 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6830 #if ENABLE_HUSH_CASE
6833 if (done_word(&dest, &ctx)) {
6836 done_pipe(&ctx, PIPE_SEQ);
6837 #if ENABLE_HUSH_CASE
6838 /* Eat multiple semicolons, detect
6839 * whether it means something special */
6844 ch = i_getch(input);
6845 nommu_addchr(&ctx.as_string, ch);
6846 if (ctx.ctx_res_w == RES_CASE_BODY) {
6847 ctx.ctx_dsemicolon = 1;
6848 ctx.ctx_res_w = RES_MATCH;
6854 /* We just finished a cmd. New one may start
6855 * with an assignment */
6856 dest.o_assignment = MAYBE_ASSIGNMENT;
6859 if (done_word(&dest, &ctx)) {
6863 ch = i_getch(input);
6864 nommu_addchr(&ctx.as_string, ch);
6865 done_pipe(&ctx, PIPE_AND);
6867 done_pipe(&ctx, PIPE_BG);
6871 if (done_word(&dest, &ctx)) {
6874 #if ENABLE_HUSH_CASE
6875 if (ctx.ctx_res_w == RES_MATCH)
6876 break; /* we are in case's "word | word)" */
6878 if (next == '|') { /* || */
6879 ch = i_getch(input);
6880 nommu_addchr(&ctx.as_string, ch);
6881 done_pipe(&ctx, PIPE_OR);
6883 /* we could pick up a file descriptor choice here
6884 * with redirect_opt_num(), but bash doesn't do it.
6885 * "echo foo 2| cat" yields "foo 2". */
6888 o_reset_to_empty_unquoted(&ctx.as_string);
6893 #if ENABLE_HUSH_CASE
6894 /* "case... in [(]word)..." - skip '(' */
6895 if (ctx.ctx_res_w == RES_MATCH
6896 && ctx.command->argv == NULL /* not (word|(... */
6897 && dest.length == 0 /* not word(... */
6898 && dest.o_quoted == 0 /* not ""(... */
6904 if (parse_group(&dest, &ctx, input, ch) != 0) {
6909 #if ENABLE_HUSH_CASE
6910 if (ctx.ctx_res_w == RES_MATCH)
6914 /* proper use of this character is caught by end_trigger:
6915 * if we see {, we call parse_group(..., end_trigger='}')
6916 * and it will match } earlier (not here). */
6917 syntax_error_unexpected_ch(ch);
6921 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6927 struct parse_context *pctx;
6928 IF_HAS_KEYWORDS(struct parse_context *p2;)
6930 /* Clean up allocated tree.
6931 * Sample for finding leaks on syntax error recovery path.
6932 * Run it from interactive shell, watch pmap `pidof hush`.
6933 * while if false; then false; fi; do break; fi
6934 * Samples to catch leaks at execution:
6935 * while if (true | {true;}); then echo ok; fi; do break; done
6936 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
6940 /* Update pipe/command counts,
6941 * otherwise freeing may miss some */
6942 done_pipe(pctx, PIPE_SEQ);
6943 debug_printf_clean("freeing list %p from ctx %p\n",
6944 pctx->list_head, pctx);
6945 debug_print_tree(pctx->list_head, 0);
6946 free_pipe_list(pctx->list_head);
6947 debug_printf_clean("freed list %p\n", pctx->list_head);
6949 o_free_unsafe(&pctx->as_string);
6951 IF_HAS_KEYWORDS(p2 = pctx->stack;)
6955 IF_HAS_KEYWORDS(pctx = p2;)
6956 } while (HAS_KEYWORDS && pctx);
6957 /* Free text, clear all dest fields */
6959 /* If we are not in top-level parse, we return,
6960 * our caller will propagate error.
6962 if (end_trigger != ';') {
6970 /* Discard cached input, force prompt */
6972 IF_HUSH_INTERACTIVE(input->promptme = 1;)
6977 /* Executing from string: eval, sh -c '...'
6978 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6979 * end_trigger controls how often we stop parsing
6980 * NUL: parse all, execute, return
6981 * ';': parse till ';' or newline, execute, repeat till EOF
6983 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
6985 /* Why we need empty flag?
6986 * An obscure corner case "false; ``; echo $?":
6987 * empty command in `` should still set $? to 0.
6988 * But we can't just set $? to 0 at the start,
6989 * this breaks "false; echo `echo $?`" case.
6993 struct pipe *pipe_list;
6995 pipe_list = parse_stream(NULL, inp, end_trigger);
6996 if (!pipe_list) { /* EOF */
6998 G.last_exitcode = 0;
7001 debug_print_tree(pipe_list, 0);
7002 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7003 run_and_free_list(pipe_list);
7008 static void parse_and_run_string(const char *s)
7010 struct in_str input;
7011 setup_string_in_str(&input, s);
7012 parse_and_run_stream(&input, '\0');
7015 static void parse_and_run_file(FILE *f)
7017 struct in_str input;
7018 setup_file_in_str(&input, f);
7019 parse_and_run_stream(&input, ';');
7022 /* Called a few times only (or even once if "sh -c") */
7023 static void init_sigmasks(void)
7027 sigset_t old_blocked_set;
7029 if (!G.inherited_set_is_saved) {
7030 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7031 G.inherited_set = G.blocked_set;
7033 old_blocked_set = G.blocked_set;
7035 mask = (1 << SIGQUIT);
7036 if (G_interactive_fd) {
7037 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7038 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7039 mask |= SPECIAL_JOB_SIGS;
7041 G.non_DFL_mask = mask;
7046 sigaddset(&G.blocked_set, sig);
7050 sigdelset(&G.blocked_set, SIGCHLD);
7052 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7053 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7055 /* POSIX allows shell to re-enable SIGCHLD
7056 * even if it was SIG_IGN on entry */
7057 #if ENABLE_HUSH_FAST
7058 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7059 if (!G.inherited_set_is_saved)
7060 signal(SIGCHLD, SIGCHLD_handler);
7062 if (!G.inherited_set_is_saved)
7063 signal(SIGCHLD, SIG_DFL);
7066 G.inherited_set_is_saved = 1;
7071 static void maybe_set_to_sigexit(int sig)
7073 void (*handler)(int);
7074 /* non_DFL_mask'ed signals are, well, masked,
7075 * no need to set handler for them.
7077 if (!((G.non_DFL_mask >> sig) & 1)) {
7078 handler = signal(sig, sigexit);
7079 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7080 signal(sig, handler);
7083 /* Set handlers to restore tty pgrp and exit */
7084 static void set_fatal_handlers(void)
7086 /* We _must_ restore tty pgrp on fatal signals */
7088 maybe_set_to_sigexit(SIGILL );
7089 maybe_set_to_sigexit(SIGFPE );
7090 maybe_set_to_sigexit(SIGBUS );
7091 maybe_set_to_sigexit(SIGSEGV);
7092 maybe_set_to_sigexit(SIGTRAP);
7093 } /* else: hush is perfect. what SEGV? */
7094 maybe_set_to_sigexit(SIGABRT);
7095 /* bash 3.2 seems to handle these just like 'fatal' ones */
7096 maybe_set_to_sigexit(SIGPIPE);
7097 maybe_set_to_sigexit(SIGALRM);
7098 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7099 * if we aren't interactive... but in this case
7100 * we never want to restore pgrp on exit, and this fn is not called */
7101 /*maybe_set_to_sigexit(SIGHUP );*/
7102 /*maybe_set_to_sigexit(SIGTERM);*/
7103 /*maybe_set_to_sigexit(SIGINT );*/
7107 static int set_mode(const char cstate, const char mode)
7109 int state = (cstate == '-' ? 1 : 0);
7111 case 'n': G.n_mode = state; break;
7112 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7113 default: return EXIT_FAILURE;
7115 return EXIT_SUCCESS;
7118 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7119 int hush_main(int argc, char **argv)
7121 static const struct variable const_shell_ver = {
7123 .varstr = (char*)hush_version_str,
7124 .max_len = 1, /* 0 can provoke free(name) */
7129 unsigned builtin_argc;
7131 struct variable *cur_var;
7134 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7135 G.last_exitcode = EXIT_SUCCESS;
7137 G.argv0_for_re_execing = argv[0];
7139 /* Deal with HUSH_VERSION */
7140 G.shell_ver = const_shell_ver; /* copying struct here */
7141 G.top_var = &G.shell_ver;
7142 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7143 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7144 /* Initialize our shell local variables with the values
7145 * currently living in the environment */
7146 cur_var = G.top_var;
7149 char *value = strchr(*e, '=');
7150 if (value) { /* paranoia */
7151 cur_var->next = xzalloc(sizeof(*cur_var));
7152 cur_var = cur_var->next;
7153 cur_var->varstr = *e;
7154 cur_var->max_len = strlen(*e);
7155 cur_var->flg_export = 1;
7159 /* reinstate HUSH_VERSION */
7160 debug_printf_env("putenv '%s'\n", hush_version_str);
7161 putenv((char *)hush_version_str);
7164 set_pwd_var(/*exp:*/ 1);
7165 /* bash also exports SHLVL and _,
7166 * and sets (but doesn't export) the following variables:
7168 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7169 * BASH_VERSION='3.2.0(1)-release'
7171 * MACHTYPE=i386-pc-linux-gnu
7173 * HOSTNAME=<xxxxxxxxxx>
7174 * PPID=<NNNNN> - we also do it elsewhere
7185 * PIPESTATUS=([0]="0")
7186 * HISTFILE=/<xxx>/.bash_history
7190 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7192 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7202 #if ENABLE_FEATURE_EDITING
7203 G.line_input_state = new_line_input_t(FOR_SHELL);
7205 G.global_argc = argc;
7206 G.global_argv = argv;
7207 /* Initialize some more globals to non-zero values */
7208 cmdedit_update_prompt();
7210 if (setjmp(die_jmp)) {
7211 /* xfunc has failed! die die die */
7212 /* no EXIT traps, this is an escape hatch! */
7214 hush_exit(xfunc_error_retval);
7217 /* Shell is non-interactive at first. We need to call
7218 * init_sigmasks() if we are going to execute "sh <script>",
7219 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7220 * If we later decide that we are interactive, we run init_sigmasks()
7221 * in order to intercept (more) signals.
7225 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7228 opt = getopt(argc, argv, "+c:xins"
7231 # if ENABLE_HUSH_FUNCTIONS
7241 * sh ... -c 'script'
7242 * sh ... -c 'script' ARG0 [ARG1...]
7243 * On NOMMU, if builtin_argc != 0,
7244 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7245 * "" needs to be replaced with NULL
7246 * and BARGV vector fed to builtin function.
7247 * Note: the form without ARG0 never happens:
7248 * sh ... -c 'builtin' BARGV... ""
7251 G.root_pid = getpid();
7252 G.root_ppid = getppid();
7254 G.global_argv = argv + optind;
7255 G.global_argc = argc - optind;
7257 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7258 const struct built_in_command *x;
7261 x = find_builtin(optarg);
7262 if (x) { /* paranoia */
7263 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7264 G.global_argv += builtin_argc;
7265 G.global_argv[-1] = NULL; /* replace "" */
7266 G.last_exitcode = x->b_function(argv + optind - 1);
7270 if (!G.global_argv[0]) {
7271 /* -c 'script' (no params): prevent empty $0 */
7272 G.global_argv--; /* points to argv[i] of 'script' */
7273 G.global_argv[0] = argv[0];
7275 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7277 parse_and_run_string(optarg);
7280 /* Well, we cannot just declare interactiveness,
7281 * we have to have some stuff (ctty, etc) */
7282 /* G_interactive_fd++; */
7285 /* "-s" means "read from stdin", but this is how we always
7286 * operate, so simply do nothing here. */
7289 case '<': /* "big heredoc" support */
7290 full_write1_str(optarg);
7293 unsigned long long empty_trap_mask;
7295 G.root_pid = bb_strtou(optarg, &optarg, 16);
7297 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7299 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7301 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7303 builtin_argc = bb_strtou(optarg, &optarg, 16);
7305 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7306 if (empty_trap_mask != 0) {
7309 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7310 for (sig = 1; sig < NSIG; sig++) {
7311 if (empty_trap_mask & (1LL << sig)) {
7312 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7313 sigaddset(&G.blocked_set, sig);
7316 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7318 # if ENABLE_HUSH_LOOPS
7320 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7326 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7328 # if ENABLE_HUSH_FUNCTIONS
7330 struct function *funcp = new_function(optarg);
7331 /* funcp->name is already set to optarg */
7332 /* funcp->body is set to NULL. It's a special case. */
7333 funcp->body_as_string = argv[optind];
7341 if (set_mode('-', opt) == 0) /* no error */
7345 fprintf(stderr, "Usage: sh [FILE]...\n"
7346 " or: sh -c command [args]...\n\n");
7352 } /* option parsing loop */
7355 G.root_pid = getpid();
7356 G.root_ppid = getppid();
7359 /* If we are login shell... */
7360 if (argv[0] && argv[0][0] == '-') {
7362 debug_printf("sourcing /etc/profile\n");
7363 input = fopen_for_read("/etc/profile");
7364 if (input != NULL) {
7365 close_on_exec_on(fileno(input));
7367 parse_and_run_file(input);
7370 /* bash: after sourcing /etc/profile,
7371 * tries to source (in the given order):
7372 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7373 * stopping on first found. --noprofile turns this off.
7374 * bash also sources ~/.bash_logout on exit.
7375 * If called as sh, skips .bash_XXX files.
7382 * "bash <script>" (which is never interactive (unless -i?))
7383 * sources $BASH_ENV here (without scanning $PATH).
7384 * If called as sh, does the same but with $ENV.
7386 debug_printf("running script '%s'\n", argv[optind]);
7387 G.global_argv = argv + optind;
7388 G.global_argc = argc - optind;
7389 input = xfopen_for_read(argv[optind]);
7390 close_on_exec_on(fileno(input));
7392 parse_and_run_file(input);
7393 #if ENABLE_FEATURE_CLEAN_UP
7399 /* Up to here, shell was non-interactive. Now it may become one.
7400 * NB: don't forget to (re)run init_sigmasks() as needed.
7403 /* A shell is interactive if the '-i' flag was given,
7404 * or if all of the following conditions are met:
7406 * no arguments remaining or the -s flag given
7407 * standard input is a terminal
7408 * standard output is a terminal
7409 * Refer to Posix.2, the description of the 'sh' utility.
7412 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7413 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7414 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7415 if (G_saved_tty_pgrp < 0)
7416 G_saved_tty_pgrp = 0;
7418 /* try to dup stdin to high fd#, >= 255 */
7419 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7420 if (G_interactive_fd < 0) {
7421 /* try to dup to any fd */
7422 G_interactive_fd = dup(STDIN_FILENO);
7423 if (G_interactive_fd < 0) {
7425 G_interactive_fd = 0;
7426 G_saved_tty_pgrp = 0;
7429 // TODO: track & disallow any attempts of user
7430 // to (inadvertently) close/redirect G_interactive_fd
7432 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7433 if (G_interactive_fd) {
7434 close_on_exec_on(G_interactive_fd);
7436 if (G_saved_tty_pgrp) {
7437 /* If we were run as 'hush &', sleep until we are
7438 * in the foreground (tty pgrp == our pgrp).
7439 * If we get started under a job aware app (like bash),
7440 * make sure we are now in charge so we don't fight over
7441 * who gets the foreground */
7443 pid_t shell_pgrp = getpgrp();
7444 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7445 if (G_saved_tty_pgrp == shell_pgrp)
7447 /* send TTIN to ourself (should stop us) */
7448 kill(- shell_pgrp, SIGTTIN);
7452 /* Block some signals */
7455 if (G_saved_tty_pgrp) {
7456 /* Set other signals to restore saved_tty_pgrp */
7457 set_fatal_handlers();
7458 /* Put ourselves in our own process group
7459 * (bash, too, does this only if ctty is available) */
7460 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7461 /* Grab control of the terminal */
7462 tcsetpgrp(G_interactive_fd, getpid());
7464 /* -1 is special - makes xfuncs longjmp, not exit
7465 * (we reset die_sleep = 0 whereever we [v]fork) */
7466 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7470 #elif ENABLE_HUSH_INTERACTIVE
7471 /* No job control compiled in, only prompt/line editing */
7472 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7473 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7474 if (G_interactive_fd < 0) {
7475 /* try to dup to any fd */
7476 G_interactive_fd = dup(STDIN_FILENO);
7477 if (G_interactive_fd < 0)
7479 G_interactive_fd = 0;
7482 if (G_interactive_fd) {
7483 close_on_exec_on(G_interactive_fd);
7487 /* We have interactiveness code disabled */
7491 * if interactive but not a login shell, sources ~/.bashrc
7492 * (--norc turns this off, --rcfile <file> overrides)
7495 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7496 /* note: ash and hush share this string */
7497 printf("\n\n%s %s\n"
7498 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7501 "hush - the humble shell"
7505 parse_and_run_file(stdin);
7508 #if ENABLE_FEATURE_CLEAN_UP
7509 if (G.cwd != bb_msg_unknown)
7511 cur_var = G.top_var->next;
7513 struct variable *tmp = cur_var;
7514 if (!cur_var->max_len)
7515 free(cur_var->varstr);
7516 cur_var = cur_var->next;
7520 hush_exit(G.last_exitcode);
7525 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7526 int lash_main(int argc, char **argv)
7528 bb_error_msg("lash is deprecated, please use hush instead");
7529 return hush_main(argc, argv);
7534 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7535 int msh_main(int argc, char **argv)
7537 //bb_error_msg("msh is deprecated, please use hush instead");
7538 return hush_main(argc, argv);
7546 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7551 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7558 return applet_main_func(argc, argv - argc);
7561 static int FAST_FUNC builtin_test(char **argv)
7563 return run_applet_main(argv, test_main);
7566 static int FAST_FUNC builtin_echo(char **argv)
7568 return run_applet_main(argv, echo_main);
7572 static int FAST_FUNC builtin_printf(char **argv)
7574 return run_applet_main(argv, printf_main);
7578 static char **skip_dash_dash(char **argv)
7581 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7586 static int FAST_FUNC builtin_eval(char **argv)
7588 int rcode = EXIT_SUCCESS;
7590 argv = skip_dash_dash(argv);
7592 char *str = expand_strvec_to_string(argv);
7594 * eval "echo Hi; done" ("done" is syntax error):
7595 * "echo Hi" will not execute too.
7597 parse_and_run_string(str);
7599 rcode = G.last_exitcode;
7604 static int FAST_FUNC builtin_cd(char **argv)
7608 argv = skip_dash_dash(argv);
7610 if (newdir == NULL) {
7611 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7612 * bash says "bash: cd: HOME not set" and does nothing
7615 const char *home = get_local_var_value("HOME");
7616 newdir = home ? home : "/";
7618 if (chdir(newdir)) {
7619 /* Mimic bash message exactly */
7620 bb_perror_msg("cd: %s", newdir);
7621 return EXIT_FAILURE;
7623 /* Read current dir (get_cwd(1) is inside) and set PWD.
7624 * Note: do not enforce exporting. If PWD was unset or unexported,
7625 * set it again, but do not export. bash does the same.
7627 set_pwd_var(/*exp:*/ 0);
7628 return EXIT_SUCCESS;
7631 static int FAST_FUNC builtin_exec(char **argv)
7633 argv = skip_dash_dash(argv);
7634 if (argv[0] == NULL)
7635 return EXIT_SUCCESS; /* bash does this */
7637 /* Careful: we can end up here after [v]fork. Do not restore
7638 * tty pgrp then, only top-level shell process does that */
7639 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7640 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7642 /* TODO: if exec fails, bash does NOT exit! We do.
7643 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7644 * and tcsetpgrp, and this is inherently racy.
7646 execvp_or_die(argv);
7649 static int FAST_FUNC builtin_exit(char **argv)
7651 debug_printf_exec("%s()\n", __func__);
7653 /* interactive bash:
7654 * # trap "echo EEE" EXIT
7657 * There are stopped jobs.
7658 * (if there are _stopped_ jobs, running ones don't count)
7661 # EEE (then bash exits)
7663 * we can use G.exiting = -1 as indicator "last cmd was exit"
7666 /* note: EXIT trap is run by hush_exit */
7667 argv = skip_dash_dash(argv);
7668 if (argv[0] == NULL)
7669 hush_exit(G.last_exitcode);
7670 /* mimic bash: exit 123abc == exit 255 + error msg */
7671 xfunc_error_retval = 255;
7672 /* bash: exit -2 == exit 254, no error msg */
7673 hush_exit(xatoi(argv[0]) & 0xff);
7676 static void print_escaped(const char *s)
7681 const char *p = strchrnul(s, '\'');
7682 /* print 'xxxx', possibly just '' */
7683 printf("'%.*s'", (int)(p - s), s);
7688 /* s points to '; print "'''...'''" */
7690 do putchar('\''); while (*++s == '\'');
7695 #if !ENABLE_HUSH_LOCAL
7696 #define helper_export_local(argv, exp, lvl) \
7697 helper_export_local(argv, exp)
7699 static void helper_export_local(char **argv, int exp, int lvl)
7704 /* So far we do not check that name is valid (TODO?) */
7706 if (strchr(name, '=') == NULL) {
7707 struct variable *var;
7709 var = get_local_var(name);
7710 if (exp == -1) { /* unexporting? */
7711 /* export -n NAME (without =VALUE) */
7713 var->flg_export = 0;
7714 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7716 } /* else: export -n NOT_EXISTING_VAR: no-op */
7719 if (exp == 1) { /* exporting? */
7720 /* export NAME (without =VALUE) */
7722 var->flg_export = 1;
7723 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7724 putenv(var->varstr);
7728 /* Exporting non-existing variable.
7729 * bash does not put it in environment,
7730 * but remembers that it is exported,
7731 * and does put it in env when it is set later.
7732 * We just set it to "" and export. */
7733 /* Or, it's "local NAME" (without =VALUE).
7734 * bash sets the value to "". */
7735 name = xasprintf("%s=", name);
7737 /* (Un)exporting/making local NAME=VALUE */
7738 name = xstrdup(name);
7740 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7744 static int FAST_FUNC builtin_export(char **argv)
7746 unsigned opt_unexport;
7748 #if ENABLE_HUSH_EXPORT_N
7749 /* "!": do not abort on errors */
7750 opt_unexport = getopt32(argv, "!n");
7751 if (opt_unexport == (uint32_t)-1)
7752 return EXIT_FAILURE;
7759 if (argv[0] == NULL) {
7766 /* ash emits: export VAR='VAL'
7767 * bash: declare -x VAR="VAL"
7768 * we follow ash example */
7769 const char *s = *e++;
7770 const char *p = strchr(s, '=');
7772 if (!p) /* wtf? take next variable */
7775 printf("export %.*s", (int)(p - s) + 1, s);
7776 print_escaped(p + 1);
7780 /*fflush_all(); - done after each builtin anyway */
7782 return EXIT_SUCCESS;
7785 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7787 return EXIT_SUCCESS;
7790 #if ENABLE_HUSH_LOCAL
7791 static int FAST_FUNC builtin_local(char **argv)
7793 if (G.func_nest_level == 0) {
7794 bb_error_msg("%s: not in a function", argv[0]);
7795 return EXIT_FAILURE; /* bash compat */
7797 helper_export_local(argv, 0, G.func_nest_level);
7798 return EXIT_SUCCESS;
7802 static int FAST_FUNC builtin_trap(char **argv)
7808 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7813 /* No args: print all trapped */
7814 for (i = 0; i < NSIG; ++i) {
7817 print_escaped(G.traps[i]);
7818 /* note: bash adds "SIG", but only if invoked
7819 * as "bash". If called as "sh", or if set -o posix,
7820 * then it prints short signal names.
7821 * We are printing short names: */
7822 printf(" %s\n", get_signame(i));
7825 /*fflush_all(); - done after each builtin anyway */
7826 return EXIT_SUCCESS;
7830 /* If first arg is a number: reset all specified signals */
7831 sig = bb_strtou(*argv, NULL, 10);
7837 sig = get_signum(*argv++);
7838 if (sig < 0 || sig >= NSIG) {
7840 /* Mimic bash message exactly */
7841 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7846 G.traps[sig] = xstrdup(new_cmd);
7848 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7849 get_signame(sig), sig, G.traps[sig]);
7851 /* There is no signal for 0 (EXIT) */
7856 sigaddset(&G.blocked_set, sig);
7858 /* There was a trap handler, we are removing it
7859 * (if sig has non-DFL handling,
7860 * we don't need to do anything) */
7861 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7863 sigdelset(&G.blocked_set, sig);
7866 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7870 if (!argv[1]) { /* no second arg */
7871 bb_error_msg("trap: invalid arguments");
7872 return EXIT_FAILURE;
7875 /* First arg is "-": reset all specified to default */
7876 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7877 /* Everything else: set arg as signal handler
7878 * (includes "" case, which ignores signal) */
7879 if (argv[0][0] == '-') {
7880 if (argv[0][1] == '\0') { /* "-" */
7881 /* new_cmd remains NULL: "reset these sigs" */
7884 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7887 /* else: "-something", no special meaning */
7892 goto process_sig_list;
7895 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7896 static int FAST_FUNC builtin_type(char **argv)
7898 int ret = EXIT_SUCCESS;
7904 if (0) {} /* make conditional compile easier below */
7905 /*else if (find_alias(*argv))
7906 type = "an alias";*/
7907 #if ENABLE_HUSH_FUNCTIONS
7908 else if (find_function(*argv))
7909 type = "a function";
7911 else if (find_builtin(*argv))
7912 type = "a shell builtin";
7913 else if ((path = find_in_path(*argv)) != NULL)
7916 bb_error_msg("type: %s: not found", *argv);
7921 printf("%s is %s\n", *argv, type);
7929 /* built-in 'fg' and 'bg' handler */
7930 static int FAST_FUNC builtin_fg_bg(char **argv)
7935 if (!G_interactive_fd)
7936 return EXIT_FAILURE;
7938 /* If they gave us no args, assume they want the last backgrounded task */
7940 for (pi = G.job_list; pi; pi = pi->next) {
7941 if (pi->jobid == G.last_jobid) {
7945 bb_error_msg("%s: no current job", argv[0]);
7946 return EXIT_FAILURE;
7948 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7949 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7950 return EXIT_FAILURE;
7952 for (pi = G.job_list; pi; pi = pi->next) {
7953 if (pi->jobid == jobnum) {
7957 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7958 return EXIT_FAILURE;
7960 /* TODO: bash prints a string representation
7961 * of job being foregrounded (like "sleep 1 | cat") */
7962 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
7963 /* Put the job into the foreground. */
7964 tcsetpgrp(G_interactive_fd, pi->pgrp);
7967 /* Restart the processes in the job */
7968 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7969 for (i = 0; i < pi->num_cmds; i++) {
7970 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7971 pi->cmds[i].is_stopped = 0;
7973 pi->stopped_cmds = 0;
7975 i = kill(- pi->pgrp, SIGCONT);
7977 if (errno == ESRCH) {
7978 delete_finished_bg_job(pi);
7979 return EXIT_SUCCESS;
7981 bb_perror_msg("kill (SIGCONT)");
7984 if (argv[0][0] == 'f') {
7986 return checkjobs_and_fg_shell(pi);
7988 return EXIT_SUCCESS;
7992 #if ENABLE_HUSH_HELP
7993 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
7995 const struct built_in_command *x;
7998 "Built-in commands:\n"
7999 "------------------\n");
8000 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8002 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8005 return EXIT_SUCCESS;
8010 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8013 const char *status_string;
8015 for (job = G.job_list; job; job = job->next) {
8016 if (job->alive_cmds == job->stopped_cmds)
8017 status_string = "Stopped";
8019 status_string = "Running";
8021 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8023 return EXIT_SUCCESS;
8028 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8033 # ifdef M_TRIM_THRESHOLD
8034 /* Optional. Reduces probability of false positives */
8037 /* Crude attempt to find where "free memory" starts,
8038 * sans fragmentation. */
8040 l = (unsigned long)p;
8043 if (l < (unsigned long)p) l = (unsigned long)p;
8046 if (!G.memleak_value)
8047 G.memleak_value = l;
8049 l -= G.memleak_value;
8056 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8061 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8064 return EXIT_SUCCESS;
8067 static int FAST_FUNC builtin_read(char **argv)
8076 /* "!": do not abort on errors.
8077 * Option string must start with "sr" to match BUILTIN_READ_xxx
8079 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8080 if (read_flags == (uint32_t)-1)
8081 return EXIT_FAILURE;
8084 r = shell_builtin_read(set_local_var_from_halves,
8086 get_local_var_value("IFS"), /* can be NULL */
8094 if ((uintptr_t)r > 1) {
8095 bb_error_msg("%s", r);
8096 r = (char*)(uintptr_t)1;
8099 return (uintptr_t)r;
8102 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8103 * built-in 'set' handler
8105 * set [-abCefhmnuvx] [-o option] [argument...]
8106 * set [+abCefhmnuvx] [+o option] [argument...]
8107 * set -- [argument...]
8110 * Implementations shall support the options in both their hyphen and
8111 * plus-sign forms. These options can also be specified as options to sh.
8113 * Write out all variables and their values: set
8114 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8115 * Turn on the -x and -v options: set -xv
8116 * Unset all positional parameters: set --
8117 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8118 * Set the positional parameters to the expansion of x, even if x expands
8119 * with a leading '-' or '+': set -- $x
8121 * So far, we only support "set -- [argument...]" and some of the short names.
8123 static int FAST_FUNC builtin_set(char **argv)
8126 char **pp, **g_argv;
8127 char *arg = *++argv;
8131 for (e = G.top_var; e; e = e->next)
8133 return EXIT_SUCCESS;
8137 if (!strcmp(arg, "--")) {
8141 if (arg[0] != '+' && arg[0] != '-')
8143 for (n = 1; arg[n]; ++n)
8144 if (set_mode(arg[0], arg[n]))
8146 } while ((arg = *++argv) != NULL);
8147 /* Now argv[0] is 1st argument */
8150 return EXIT_SUCCESS;
8153 /* NB: G.global_argv[0] ($0) is never freed/changed */
8154 g_argv = G.global_argv;
8155 if (G.global_args_malloced) {
8161 G.global_args_malloced = 1;
8162 pp = xzalloc(sizeof(pp[0]) * 2);
8163 pp[0] = g_argv[0]; /* retain $0 */
8166 /* This realloc's G.global_argv */
8167 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8174 return EXIT_SUCCESS;
8176 /* Nothing known, so abort */
8178 bb_error_msg("set: %s: invalid option", arg);
8179 return EXIT_FAILURE;
8182 static int FAST_FUNC builtin_shift(char **argv)
8185 argv = skip_dash_dash(argv);
8189 if (n >= 0 && n < G.global_argc) {
8190 if (G.global_args_malloced) {
8193 free(G.global_argv[m++]);
8196 memmove(&G.global_argv[1], &G.global_argv[n+1],
8197 G.global_argc * sizeof(G.global_argv[0]));
8198 return EXIT_SUCCESS;
8200 return EXIT_FAILURE;
8203 static int FAST_FUNC builtin_source(char **argv)
8205 char *arg_path, *filename;
8208 #if ENABLE_HUSH_FUNCTIONS
8212 argv = skip_dash_dash(argv);
8215 /* bash says: "bash: .: filename argument required" */
8216 return 2; /* bash compat */
8219 if (!strchr(filename, '/')) {
8220 arg_path = find_in_path(filename);
8222 filename = arg_path;
8224 input = fopen_or_warn(filename, "r");
8227 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8228 return EXIT_FAILURE;
8230 close_on_exec_on(fileno(input));
8232 #if ENABLE_HUSH_FUNCTIONS
8233 sv_flg = G.flag_return_in_progress;
8234 /* "we are inside sourced file, ok to use return" */
8235 G.flag_return_in_progress = -1;
8237 save_and_replace_G_args(&sv, argv);
8239 parse_and_run_file(input);
8242 restore_G_args(&sv, argv);
8243 #if ENABLE_HUSH_FUNCTIONS
8244 G.flag_return_in_progress = sv_flg;
8247 return G.last_exitcode;
8250 static int FAST_FUNC builtin_umask(char **argv)
8256 argv = skip_dash_dash(argv);
8258 mode_t old_mask = mask;
8261 rc = bb_parse_mode(argv[0], &mask);
8266 * bash: umask: 'q': invalid symbolic mode operator
8267 * bash: umask: 999: octal number out of range
8269 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8274 printf("%04o\n", (unsigned) mask);
8275 /* fall through and restore mask which we set to 0 */
8279 return !rc; /* rc != 0 - success */
8282 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8283 static int FAST_FUNC builtin_unset(char **argv)
8288 /* "!": do not abort on errors */
8289 /* "+": stop at 1st non-option */
8290 opts = getopt32(argv, "!+vf");
8291 if (opts == (unsigned)-1)
8292 return EXIT_FAILURE;
8294 bb_error_msg("unset: -v and -f are exclusive");
8295 return EXIT_FAILURE;
8301 if (!(opts & 2)) { /* not -f */
8302 if (unset_local_var(*argv)) {
8303 /* unset <nonexistent_var> doesn't fail.
8304 * Error is when one tries to unset RO var.
8305 * Message was printed by unset_local_var. */
8309 #if ENABLE_HUSH_FUNCTIONS
8319 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8320 static int FAST_FUNC builtin_wait(char **argv)
8322 int ret = EXIT_SUCCESS;
8325 argv = skip_dash_dash(argv);
8326 if (argv[0] == NULL) {
8327 /* Don't care about wait results */
8328 /* Note 1: must wait until there are no more children */
8329 /* Note 2: must be interruptible */
8331 * $ sleep 3 & sleep 6 & wait
8336 * $ sleep 3 & sleep 6 & wait
8340 * ^C <-- after ~4 sec from keyboard
8343 sigaddset(&G.blocked_set, SIGCHLD);
8344 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8347 if (errno == ECHILD)
8349 /* Wait for SIGCHLD or any other signal of interest */
8350 /* sigtimedwait with infinite timeout: */
8351 sig = sigwaitinfo(&G.blocked_set, NULL);
8353 sig = check_and_run_traps(sig);
8354 if (sig && sig != SIGCHLD) { /* see note 2 */
8360 sigdelset(&G.blocked_set, SIGCHLD);
8361 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8365 /* This is probably buggy wrt interruptible-ness */
8367 pid_t pid = bb_strtou(*argv, NULL, 10);
8369 /* mimic bash message */
8370 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8371 return EXIT_FAILURE;
8373 if (waitpid(pid, &status, 0) == pid) {
8374 if (WIFSIGNALED(status))
8375 ret = 128 + WTERMSIG(status);
8376 else if (WIFEXITED(status))
8377 ret = WEXITSTATUS(status);
8381 bb_perror_msg("wait %s", *argv);
8390 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8391 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8394 def = bb_strtou(argv[1], NULL, 10);
8395 if (errno || def < def_min || argv[2]) {
8396 bb_error_msg("%s: bad arguments", argv[0]);
8404 #if ENABLE_HUSH_LOOPS
8405 static int FAST_FUNC builtin_break(char **argv)
8408 if (G.depth_of_loop == 0) {
8409 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8410 return EXIT_SUCCESS; /* bash compat */
8412 G.flag_break_continue++; /* BC_BREAK = 1 */
8414 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8415 if (depth == UINT_MAX)
8416 G.flag_break_continue = BC_BREAK;
8417 if (G.depth_of_loop < depth)
8418 G.depth_break_continue = G.depth_of_loop;
8420 return EXIT_SUCCESS;
8423 static int FAST_FUNC builtin_continue(char **argv)
8425 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8426 return builtin_break(argv);
8430 #if ENABLE_HUSH_FUNCTIONS
8431 static int FAST_FUNC builtin_return(char **argv)
8435 if (G.flag_return_in_progress != -1) {
8436 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8437 return EXIT_FAILURE; /* bash compat */
8440 G.flag_return_in_progress = 1;
8443 * out of range: wraps around at 256, does not error out
8444 * non-numeric param:
8445 * f() { false; return qwe; }; f; echo $?
8446 * bash: return: qwe: numeric argument required <== we do this
8447 * 255 <== we also do this
8449 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);