1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * subst operator: ${var/[/]expr/expr}
54 * brace expansion: one/{two,three,four}
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
67 * export builtin should be special, its arguments are assignments
68 * and therefore expansion of them should be "one-word" expansion:
69 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
71 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
72 * ls: cannot access i=a: No such file or directory
73 * ls: cannot access b: No such file or directory
74 * Note1: same applies to local builtin.
75 * Note2: bash 3.2.33(1) does this only if export word itself
77 * $ export i=`echo 'aaa bbb'`; echo "$i"
79 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #include <malloc.h> /* for malloc_trim */
87 /* #include <dmalloc.h> */
92 #include "shell_common.h"
95 #if ENABLE_HUSH_RANDOM_SUPPORT
98 # define CLEAR_RANDOM_T(rnd) ((void)0)
101 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
104 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_LASH(APPLET(lash, _BB_DIR_BIN, _BB_SUID_DROP))
107 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
108 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
110 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
111 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, brace expansion,
125 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_HELP
135 //config: bool "help builtin"
137 //config: depends on HUSH
139 //config: Enable help builtin in hush. Code size + ~1 kbyte.
141 //config:config HUSH_INTERACTIVE
142 //config: bool "Interactive mode"
144 //config: depends on HUSH
146 //config: Enable interactive mode (prompt and command editing).
147 //config: Without this, hush simply reads and executes commands
148 //config: from stdin just like a shell script from a file.
149 //config: No prompt, no PS1/PS2 magic shell variables.
151 //config:config HUSH_JOB
152 //config: bool "Job control"
154 //config: depends on HUSH_INTERACTIVE
156 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
157 //config: command (not entire shell), fg/bg builtins work. Without this option,
158 //config: "cmd &" still works by simply spawning a process and immediately
159 //config: prompting for next command (or executing next command in a script),
160 //config: but no separate process group is formed.
162 //config:config HUSH_TICK
163 //config: bool "Process substitution"
165 //config: depends on HUSH
167 //config: Enable process substitution `command` and $(command) in hush.
169 //config:config HUSH_IF
170 //config: bool "Support if/then/elif/else/fi"
172 //config: depends on HUSH
174 //config: Enable if/then/elif/else/fi in hush.
176 //config:config HUSH_LOOPS
177 //config: bool "Support for, while and until loops"
179 //config: depends on HUSH
181 //config: Enable for, while and until loops in hush.
183 //config:config HUSH_CASE
184 //config: bool "Support case ... esac statement"
186 //config: depends on HUSH
188 //config: Enable case ... esac statement in hush. +400 bytes.
190 //config:config HUSH_FUNCTIONS
191 //config: bool "Support funcname() { commands; } syntax"
193 //config: depends on HUSH
195 //config: Enable support for shell functions in hush. +800 bytes.
197 //config:config HUSH_LOCAL
198 //config: bool "Support local builtin"
200 //config: depends on HUSH_FUNCTIONS
202 //config: Enable support for local variables in functions.
204 //config:config HUSH_RANDOM_SUPPORT
205 //config: bool "Pseudorandom generator and $RANDOM variable"
207 //config: depends on HUSH
209 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
210 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
212 //config:config HUSH_EXPORT_N
213 //config: bool "Support 'export -n' option"
215 //config: depends on HUSH
217 //config: export -n unexports variables. It is a bash extension.
219 //config:config HUSH_MODE_X
220 //config: bool "Support 'hush -x' option and 'set -x' command"
222 //config: depends on HUSH
224 //config: This instructs hush to print commands before execution.
225 //config: Adds ~300 bytes.
228 //config: bool "lash (deprecated: aliased to hush)"
230 //config: select HUSH
232 //config: lash is deprecated and will be removed, please migrate to hush.
235 //config: bool "msh (deprecated: aliased to hush)"
237 //config: select HUSH
239 //config: msh is deprecated and will be removed, please migrate to hush.
242 //usage:#define hush_trivial_usage NOUSAGE_STR
243 //usage:#define hush_full_usage ""
244 //usage:#define lash_trivial_usage NOUSAGE_STR
245 //usage:#define lash_full_usage ""
246 //usage:#define msh_trivial_usage NOUSAGE_STR
247 //usage:#define msh_full_usage ""
251 #define LEAK_HUNTING 0
252 #define BUILD_AS_NOMMU 0
253 /* Enable/disable sanity checks. Ok to enable in production,
254 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
255 * Keeping 1 for now even in released versions.
258 /* Slightly bigger (+200 bytes), but faster hush.
259 * So far it only enables a trick with counting SIGCHLDs and forks,
260 * which allows us to do fewer waitpid's.
261 * (we can detect a case where neither forks were done nor SIGCHLDs happened
262 * and therefore waitpid will return the same result as last time)
264 #define ENABLE_HUSH_FAST 0
265 /* TODO: implement simplified code for users which do not need ${var%...} ops
266 * So far ${var%...} ops are always enabled:
268 #define ENABLE_HUSH_DOLLAR_OPS 1
273 # undef USE_FOR_NOMMU
276 # define USE_FOR_NOMMU(...) __VA_ARGS__
277 # define USE_FOR_MMU(...)
280 #include "NUM_APPLETS.h"
282 /* STANDALONE does not make sense, and won't compile */
283 # undef CONFIG_FEATURE_SH_STANDALONE
284 # undef ENABLE_FEATURE_SH_STANDALONE
285 # undef IF_FEATURE_SH_STANDALONE
286 # undef IF_NOT_FEATURE_SH_STANDALONE
287 # define ENABLE_FEATURE_SH_STANDALONE 0
288 # define IF_FEATURE_SH_STANDALONE(...)
289 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
292 #if !ENABLE_HUSH_INTERACTIVE
293 # undef ENABLE_FEATURE_EDITING
294 # define ENABLE_FEATURE_EDITING 0
295 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
296 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
299 /* Do we support ANY keywords? */
300 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
301 # define HAS_KEYWORDS 1
302 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
303 # define IF_HAS_NO_KEYWORDS(...)
305 # define HAS_KEYWORDS 0
306 # define IF_HAS_KEYWORDS(...)
307 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
310 /* If you comment out one of these below, it will be #defined later
311 * to perform debug printfs to stderr: */
312 #define debug_printf(...) do {} while (0)
313 /* Finer-grained debug switches */
314 #define debug_printf_parse(...) do {} while (0)
315 #define debug_print_tree(a, b) do {} while (0)
316 #define debug_printf_exec(...) do {} while (0)
317 #define debug_printf_env(...) do {} while (0)
318 #define debug_printf_jobs(...) do {} while (0)
319 #define debug_printf_expand(...) do {} while (0)
320 #define debug_printf_varexp(...) do {} while (0)
321 #define debug_printf_glob(...) do {} while (0)
322 #define debug_printf_list(...) do {} while (0)
323 #define debug_printf_subst(...) do {} while (0)
324 #define debug_printf_clean(...) do {} while (0)
326 #define ERR_PTR ((void*)(long)1)
328 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
330 #define _SPECIAL_VARS_STR "_*@$!?#"
331 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
332 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
334 #define SPECIAL_VAR_SYMBOL 3
338 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
340 /* This supports saving pointers malloced in vfork child,
341 * to be freed in the parent.
344 typedef struct nommu_save_t {
346 struct variable *old_vars;
348 char **argv_from_re_execing;
352 typedef enum reserved_style {
361 #if ENABLE_HUSH_LOOPS
368 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
373 /* three pseudo-keywords support contrived "case" syntax: */
374 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
375 RES_MATCH , /* "word)" */
376 RES_CASE_BODY, /* "this command is inside CASE" */
383 typedef struct o_string {
385 int length; /* position where data is appended */
387 /* Protect newly added chars against globbing
388 * (by prepending \ to *, ?, [, \) */
391 /* At least some part of the string was inside '' or "",
392 * possibly empty one: word"", wo''rd etc. */
394 smallint has_empty_slot;
395 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
398 MAYBE_ASSIGNMENT = 0,
399 DEFINITELY_ASSIGNMENT = 1,
401 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
403 /* Used for initialization: o_string foo = NULL_O_STRING; */
404 #define NULL_O_STRING { NULL }
406 /* I can almost use ordinary FILE*. Is open_memstream() universally
407 * available? Where is it documented? */
408 typedef struct in_str {
410 /* eof_flag=1: last char in ->p is really an EOF */
411 char eof_flag; /* meaningless if ->p == NULL */
413 #if ENABLE_HUSH_INTERACTIVE
415 smallint promptmode; /* 0: PS1, 1: PS2 */
418 int (*get) (struct in_str *) FAST_FUNC;
419 int (*peek) (struct in_str *) FAST_FUNC;
421 #define i_getch(input) ((input)->get(input))
422 #define i_peek(input) ((input)->peek(input))
424 /* The descrip member of this structure is only used to make
425 * debugging output pretty */
426 static const struct {
428 signed char default_fd;
431 { O_RDONLY, 0, "<" },
432 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
433 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
434 { O_CREAT|O_RDWR, 1, "<>" },
435 { O_RDONLY, 0, "<<" },
436 /* Should not be needed. Bogus default_fd helps in debugging */
437 /* { O_RDONLY, 77, "<<" }, */
440 struct redir_struct {
441 struct redir_struct *next;
442 char *rd_filename; /* filename */
443 int rd_fd; /* fd to redirect */
444 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
446 smallint rd_type; /* (enum redir_type) */
447 /* note: for heredocs, rd_filename contains heredoc delimiter,
448 * and subsequently heredoc itself; and rd_dup is a bitmask:
449 * bit 0: do we need to trim leading tabs?
450 * bit 1: is heredoc quoted (<<'delim' syntax) ?
453 typedef enum redir_type {
455 REDIRECT_OVERWRITE = 1,
458 REDIRECT_HEREDOC = 4,
459 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
462 REDIRFD_SYNTAX_ERR = -2,
463 REDIRFD_TO_FILE = -1,
464 /* otherwise, rd_fd is redirected to rd_dup */
466 HEREDOC_SKIPTABS = 1,
472 pid_t pid; /* 0 if exited */
473 int assignment_cnt; /* how many argv[i] are assignments? */
474 smallint is_stopped; /* is the command currently running? */
475 smallint cmd_type; /* CMD_xxx */
477 #define CMD_SUBSHELL 1
479 /* used for "[[ EXPR ]]" */
480 #if ENABLE_HUSH_BASH_COMPAT
481 # define CMD_SINGLEWORD_NOGLOB 2
484 /* used for "export noglob=* glob* a=`echo a b`" */
485 //#define CMD_SINGLEWORD_NOGLOB_COND 3
486 // It is hard to implement correctly, it adds significant amounts of tricky code,
487 // and all this is only useful for really obscure export statements
488 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
489 // guards the code which implements it, but I have doubts it works
490 // in all cases (especially with mixed globbed/non-globbed arguments)
492 #if ENABLE_HUSH_FUNCTIONS
493 # define CMD_FUNCDEF 3
496 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
499 char *group_as_string;
501 #if ENABLE_HUSH_FUNCTIONS
502 struct function *child_func;
503 /* This field is used to prevent a bug here:
504 * while...do f1() {a;}; f1; f1() {b;}; f1; done
505 * When we execute "f1() {a;}" cmd, we create new function and clear
506 * cmd->group, cmd->group_as_string, cmd->argv[0].
507 * When we execute "f1() {b;}", we notice that f1 exists,
508 * and that its "parent cmd" struct is still "alive",
509 * we put those fields back into cmd->xxx
510 * (struct function has ->parent_cmd ptr to facilitate that).
511 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
512 * Without this trick, loop would execute a;b;b;b;...
513 * instead of correct sequence a;b;a;b;...
514 * When command is freed, it severs the link
515 * (sets ->child_func->parent_cmd to NULL).
518 char **argv; /* command name and arguments */
519 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
520 * and on execution these are substituted with their values.
521 * Substitution can make _several_ words out of one argv[n]!
522 * Example: argv[0]=='.^C*^C.' here: echo .$*.
523 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
525 struct redir_struct *redirects; /* I/O redirections */
527 /* Is there anything in this command at all? */
528 #define IS_NULL_CMD(cmd) \
529 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
534 int num_cmds; /* total number of commands in pipe */
535 int alive_cmds; /* number of commands running (not exited) */
536 int stopped_cmds; /* number of commands alive, but stopped */
538 int jobid; /* job number */
539 pid_t pgrp; /* process group ID for the job */
540 char *cmdtext; /* name of job */
542 struct command *cmds; /* array of commands in pipe */
543 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
544 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
545 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
547 typedef enum pipe_style {
553 /* Is there anything in this pipe at all? */
554 #define IS_NULL_PIPE(pi) \
555 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
557 /* This holds pointers to the various results of parsing */
558 struct parse_context {
559 /* linked list of pipes */
560 struct pipe *list_head;
561 /* last pipe (being constructed right now) */
563 /* last command in pipe (being constructed right now) */
564 struct command *command;
565 /* last redirect in command->redirects list */
566 struct redir_struct *pending_redirect;
572 smallint ctx_inverted; /* "! cmd | cmd" */
574 smallint ctx_dsemicolon; /* ";;" seen */
576 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
578 /* group we are enclosed in:
579 * example: "if pipe1; pipe2; then pipe3; fi"
580 * when we see "if" or "then", we malloc and copy current context,
581 * and make ->stack point to it. then we parse pipeN.
582 * when closing "then" / fi" / whatever is found,
583 * we move list_head into ->stack->command->group,
584 * copy ->stack into current context, and delete ->stack.
585 * (parsing of { list } and ( list ) doesn't use this method)
587 struct parse_context *stack;
591 /* On program start, environ points to initial environment.
592 * putenv adds new pointers into it, unsetenv removes them.
593 * Neither of these (de)allocates the strings.
594 * setenv allocates new strings in malloc space and does putenv,
595 * and thus setenv is unusable (leaky) for shell's purposes */
596 #define setenv(...) setenv_is_leaky_dont_use()
598 struct variable *next;
599 char *varstr; /* points to "name=" portion */
600 #if ENABLE_HUSH_LOCAL
601 unsigned func_nest_level;
603 int max_len; /* if > 0, name is part of initial env; else name is malloced */
604 smallint flg_export; /* putenv should be done on this var */
605 smallint flg_read_only;
613 #if ENABLE_HUSH_FUNCTIONS
615 struct function *next;
617 struct command *parent_cmd;
620 char *body_as_string;
626 /* "Globals" within this file */
627 /* Sorted roughly by size (smaller offsets == smaller code) */
629 /* interactive_fd != 0 means we are an interactive shell.
630 * If we are, then saved_tty_pgrp can also be != 0, meaning
631 * that controlling tty is available. With saved_tty_pgrp == 0,
632 * job control still works, but terminal signals
633 * (^C, ^Z, ^Y, ^\) won't work at all, and background
634 * process groups can only be created with "cmd &".
635 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
636 * to give tty to the foreground process group,
637 * and will take it back when the group is stopped (^Z)
640 #if ENABLE_HUSH_INTERACTIVE
641 /* 'interactive_fd' is a fd# open to ctty, if we have one
642 * _AND_ if we decided to act interactively */
646 # define G_interactive_fd (G.interactive_fd)
648 # define G_interactive_fd 0
650 #if ENABLE_FEATURE_EDITING
651 line_input_t *line_input_state;
656 #if ENABLE_HUSH_RANDOM_SUPPORT
662 pid_t saved_tty_pgrp;
663 struct pipe *job_list;
664 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
666 # define G_saved_tty_pgrp 0
668 smallint flag_SIGINT;
669 #if ENABLE_HUSH_LOOPS
670 smallint flag_break_continue;
672 #if ENABLE_HUSH_FUNCTIONS
673 /* 0: outside of a function (or sourced file)
674 * -1: inside of a function, ok to use return builtin
675 * 1: return is invoked, skip all till end of func
677 smallint flag_return_in_progress;
680 #if ENABLE_HUSH_MODE_X
682 # define G_x_mode (G.x_mode)
686 smallint exiting; /* used to prevent EXIT trap recursion */
687 /* These four support $?, $#, and $1 */
688 smalluint last_exitcode;
689 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
690 smalluint global_args_malloced;
691 smalluint inherited_set_is_saved;
692 /* how many non-NULL argv's we have. NB: $# + 1 */
696 char *argv0_for_re_execing;
698 #if ENABLE_HUSH_LOOPS
699 unsigned depth_break_continue;
700 unsigned depth_of_loop;
704 struct variable *top_var; /* = &G.shell_ver (set in main()) */
705 struct variable shell_ver;
706 char **expanded_assignments;
707 #if ENABLE_HUSH_FUNCTIONS
708 struct function *top_func;
709 # if ENABLE_HUSH_LOCAL
710 struct variable **shadowed_vars_pp;
711 unsigned func_nest_level;
714 /* Signal and trap handling */
716 unsigned count_SIGCHLD;
717 unsigned handled_SIGCHLD;
718 smallint we_have_children;
720 /* which signals have non-DFL handler (even with no traps set)? */
721 unsigned non_DFL_mask;
722 char **traps; /* char *traps[NSIG] */
723 sigset_t blocked_set;
724 sigset_t inherited_set;
726 unsigned long memleak_value;
729 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
731 #define G (*ptr_to_globals)
732 /* Not #defining name to G.name - this quickly gets unwieldy
733 * (too many defines). Also, I actually prefer to see when a variable
734 * is global, thus "G." prefix is a useful hint */
735 #define INIT_G() do { \
736 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
740 /* Function prototypes for builtins */
741 static int builtin_cd(char **argv) FAST_FUNC;
742 static int builtin_echo(char **argv) FAST_FUNC;
743 static int builtin_eval(char **argv) FAST_FUNC;
744 static int builtin_exec(char **argv) FAST_FUNC;
745 static int builtin_exit(char **argv) FAST_FUNC;
746 static int builtin_export(char **argv) FAST_FUNC;
748 static int builtin_fg_bg(char **argv) FAST_FUNC;
749 static int builtin_jobs(char **argv) FAST_FUNC;
752 static int builtin_help(char **argv) FAST_FUNC;
754 #if ENABLE_HUSH_LOCAL
755 static int builtin_local(char **argv) FAST_FUNC;
758 static int builtin_memleak(char **argv) FAST_FUNC;
761 static int builtin_printf(char **argv) FAST_FUNC;
763 static int builtin_pwd(char **argv) FAST_FUNC;
764 static int builtin_read(char **argv) FAST_FUNC;
765 static int builtin_set(char **argv) FAST_FUNC;
766 static int builtin_shift(char **argv) FAST_FUNC;
767 static int builtin_source(char **argv) FAST_FUNC;
768 static int builtin_test(char **argv) FAST_FUNC;
769 static int builtin_trap(char **argv) FAST_FUNC;
770 static int builtin_type(char **argv) FAST_FUNC;
771 static int builtin_true(char **argv) FAST_FUNC;
772 static int builtin_umask(char **argv) FAST_FUNC;
773 static int builtin_unset(char **argv) FAST_FUNC;
774 static int builtin_wait(char **argv) FAST_FUNC;
775 #if ENABLE_HUSH_LOOPS
776 static int builtin_break(char **argv) FAST_FUNC;
777 static int builtin_continue(char **argv) FAST_FUNC;
779 #if ENABLE_HUSH_FUNCTIONS
780 static int builtin_return(char **argv) FAST_FUNC;
783 /* Table of built-in functions. They can be forked or not, depending on
784 * context: within pipes, they fork. As simple commands, they do not.
785 * When used in non-forking context, they can change global variables
786 * in the parent shell process. If forked, of course they cannot.
787 * For example, 'unset foo | whatever' will parse and run, but foo will
788 * still be set at the end. */
789 struct built_in_command {
791 int (*b_function)(char **argv) FAST_FUNC;
794 # define BLTIN(cmd, func, help) { cmd, func, help }
796 # define BLTIN(cmd, func, help) { cmd, func }
800 static const struct built_in_command bltins1[] = {
801 BLTIN("." , builtin_source , "Run commands in a file"),
802 BLTIN(":" , builtin_true , NULL),
804 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
806 #if ENABLE_HUSH_LOOPS
807 BLTIN("break" , builtin_break , "Exit from a loop"),
809 BLTIN("cd" , builtin_cd , "Change directory"),
810 #if ENABLE_HUSH_LOOPS
811 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
813 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
814 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
815 BLTIN("exit" , builtin_exit , "Exit"),
816 BLTIN("export" , builtin_export , "Set environment variables"),
818 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
821 BLTIN("help" , builtin_help , NULL),
824 BLTIN("jobs" , builtin_jobs , "List jobs"),
826 #if ENABLE_HUSH_LOCAL
827 BLTIN("local" , builtin_local , "Set local variables"),
830 BLTIN("memleak" , builtin_memleak , NULL),
832 BLTIN("read" , builtin_read , "Input into variable"),
833 #if ENABLE_HUSH_FUNCTIONS
834 BLTIN("return" , builtin_return , "Return from a function"),
836 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
837 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
838 #if ENABLE_HUSH_BASH_COMPAT
839 BLTIN("source" , builtin_source , "Run commands in a file"),
841 BLTIN("trap" , builtin_trap , "Trap signals"),
842 BLTIN("type" , builtin_type , "Show command type"),
843 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
844 BLTIN("umask" , builtin_umask , "Set file creation mask"),
845 BLTIN("unset" , builtin_unset , "Unset variables"),
846 BLTIN("wait" , builtin_wait , "Wait for process"),
848 /* For now, echo and test are unconditionally enabled.
849 * Maybe make it configurable? */
850 static const struct built_in_command bltins2[] = {
851 BLTIN("[" , builtin_test , NULL),
852 BLTIN("echo" , builtin_echo , NULL),
854 BLTIN("printf" , builtin_printf , NULL),
856 BLTIN("pwd" , builtin_pwd , NULL),
857 BLTIN("test" , builtin_test , NULL),
864 /* prevent disasters with G.debug_indent < 0 */
865 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
866 # define debug_enter() (G.debug_indent++)
867 # define debug_leave() (G.debug_indent--)
869 # define indent() ((void)0)
870 # define debug_enter() ((void)0)
871 # define debug_leave() ((void)0)
875 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
878 #ifndef debug_printf_parse
879 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
882 #ifndef debug_printf_exec
883 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
886 #ifndef debug_printf_env
887 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
890 #ifndef debug_printf_jobs
891 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 # define DEBUG_JOBS 1
894 # define DEBUG_JOBS 0
897 #ifndef debug_printf_expand
898 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
899 # define DEBUG_EXPAND 1
901 # define DEBUG_EXPAND 0
904 #ifndef debug_printf_varexp
905 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
908 #ifndef debug_printf_glob
909 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
910 # define DEBUG_GLOB 1
912 # define DEBUG_GLOB 0
915 #ifndef debug_printf_list
916 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
919 #ifndef debug_printf_subst
920 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
923 #ifndef debug_printf_clean
924 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
925 # define DEBUG_CLEAN 1
927 # define DEBUG_CLEAN 0
931 static void debug_print_strings(const char *prefix, char **vv)
934 fprintf(stderr, "%s:\n", prefix);
936 fprintf(stderr, " '%s'\n", *vv++);
939 # define debug_print_strings(prefix, vv) ((void)0)
943 /* Leak hunting. Use hush_leaktool.sh for post-processing.
946 static void *xxmalloc(int lineno, size_t size)
948 void *ptr = xmalloc((size + 0xff) & ~0xff);
949 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
952 static void *xxrealloc(int lineno, void *ptr, size_t size)
954 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
955 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
958 static char *xxstrdup(int lineno, const char *str)
960 char *ptr = xstrdup(str);
961 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
964 static void xxfree(void *ptr)
966 fdprintf(2, "free %p\n", ptr);
969 # define xmalloc(s) xxmalloc(__LINE__, s)
970 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
971 # define xstrdup(s) xxstrdup(__LINE__, s)
972 # define free(p) xxfree(p)
976 /* Syntax and runtime errors. They always abort scripts.
977 * In interactive use they usually discard unparsed and/or unexecuted commands
978 * and return to the prompt.
979 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
982 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
983 # define syntax_error(lineno, msg) syntax_error(msg)
984 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
985 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
986 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
987 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
990 static void die_if_script(unsigned lineno, const char *fmt, ...)
995 bb_error_msg("hush.c:%u", lineno);
998 bb_verror_msg(fmt, p, NULL);
1000 if (!G_interactive_fd)
1004 static void syntax_error(unsigned lineno, const char *msg)
1007 die_if_script(lineno, "syntax error: %s", msg);
1009 die_if_script(lineno, "syntax error", NULL);
1012 static void syntax_error_at(unsigned lineno, const char *msg)
1014 die_if_script(lineno, "syntax error at '%s'", msg);
1017 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1019 die_if_script(lineno, "syntax error: unterminated %s", s);
1022 /* It so happens that all such cases are totally fatal
1023 * even if shell is interactive: EOF while looking for closing
1024 * delimiter. There is nowhere to read stuff from after that,
1025 * it's EOF! The only choice is to terminate.
1027 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1028 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1030 char msg[2] = { ch, '\0' };
1031 syntax_error_unterm_str(lineno, msg);
1035 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1040 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1044 # undef die_if_script
1045 # undef syntax_error
1046 # undef syntax_error_at
1047 # undef syntax_error_unterm_ch
1048 # undef syntax_error_unterm_str
1049 # undef syntax_error_unexpected_ch
1051 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1052 # define syntax_error(msg) syntax_error(__LINE__, msg)
1053 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1054 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1055 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1056 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1060 #if ENABLE_HUSH_INTERACTIVE
1061 static void cmdedit_update_prompt(void);
1063 # define cmdedit_update_prompt() ((void)0)
1067 /* Utility functions
1069 /* Replace each \x with x in place, return ptr past NUL. */
1070 static char *unbackslash(char *src)
1072 char *dst = src = strchrnul(src, '\\');
1076 if ((*dst++ = *src++) == '\0')
1082 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1103 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1104 v[count1 + count2] = NULL;
1107 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1111 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1113 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1114 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1117 #define add_strings_to_strings(strings, add, need_to_dup) \
1118 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1121 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1122 static char **add_string_to_strings(char **strings, char *add)
1127 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1130 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1132 char **ptr = add_string_to_strings(strings, add);
1133 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1136 #define add_string_to_strings(strings, add) \
1137 xx_add_string_to_strings(__LINE__, strings, add)
1140 static void free_strings(char **strings)
1155 /* Helpers for setting new $n and restoring them back
1157 typedef struct save_arg_t {
1161 smallint sv_g_malloced;
1164 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1168 sv->sv_argv0 = argv[0];
1169 sv->sv_g_argv = G.global_argv;
1170 sv->sv_g_argc = G.global_argc;
1171 sv->sv_g_malloced = G.global_args_malloced;
1173 argv[0] = G.global_argv[0]; /* retain $0 */
1174 G.global_argv = argv;
1175 G.global_args_malloced = 0;
1183 static void restore_G_args(save_arg_t *sv, char **argv)
1187 if (G.global_args_malloced) {
1188 /* someone ran "set -- arg1 arg2 ...", undo */
1190 while (*++pp) /* note: does not free $0 */
1192 free(G.global_argv);
1194 argv[0] = sv->sv_argv0;
1195 G.global_argv = sv->sv_g_argv;
1196 G.global_argc = sv->sv_g_argc;
1197 G.global_args_malloced = sv->sv_g_malloced;
1201 /* Basic theory of signal handling in shell
1202 * ========================================
1203 * This does not describe what hush does, rather, it is current understanding
1204 * what it _should_ do. If it doesn't, it's a bug.
1205 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1207 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1208 * is finished or backgrounded. It is the same in interactive and
1209 * non-interactive shells, and is the same regardless of whether
1210 * a user trap handler is installed or a shell special one is in effect.
1211 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1212 * backgrounds (i.e. stops) or kills all members of currently running
1215 * Wait builtin in interruptible by signals for which user trap is set
1216 * or by SIGINT in interactive shell.
1218 * Trap handlers will execute even within trap handlers. (right?)
1220 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1221 * except for handlers set to '' (empty string).
1223 * If job control is off, backgrounded commands ("cmd &")
1224 * have SIGINT, SIGQUIT set to SIG_IGN.
1226 * Commands which are run in command substitution ("`cmd`")
1227 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1229 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1230 * by the shell from its parent.
1232 * Signals which differ from SIG_DFL action
1233 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1236 * SIGTERM (interactive): ignore
1237 * SIGHUP (interactive):
1238 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1239 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1240 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1241 * that all pipe members are stopped. Try this in bash:
1242 * while :; do :; done - ^Z does not background it
1243 * (while :; do :; done) - ^Z backgrounds it
1244 * SIGINT (interactive): wait for last pipe, ignore the rest
1245 * of the command line, show prompt. NB: ^C does not send SIGINT
1246 * to interactive shell while shell is waiting for a pipe,
1247 * since shell is bg'ed (is not in foreground process group).
1248 * Example 1: this waits 5 sec, but does not execute ls:
1249 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1250 * Example 2: this does not wait and does not execute ls:
1251 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1252 * Example 3: this does not wait 5 sec, but executes ls:
1253 * "sleep 5; ls -l" + press ^C
1255 * (What happens to signals which are IGN on shell start?)
1256 * (What happens with signal mask on shell start?)
1258 * Implementation in hush
1259 * ======================
1260 * We use in-kernel pending signal mask to determine which signals were sent.
1261 * We block all signals which we don't want to take action immediately,
1262 * i.e. we block all signals which need to have special handling as described
1263 * above, and all signals which have traps set.
1264 * After each pipe execution, we extract any pending signals via sigtimedwait()
1267 * unsigned non_DFL_mask: a mask of such "special" signals
1268 * sigset_t blocked_set: current blocked signal set
1271 * clear bit in blocked_set unless it is also in non_DFL_mask
1272 * "trap 'cmd' SIGxxx":
1273 * set bit in blocked_set (even if 'cmd' is '')
1274 * after [v]fork, if we plan to be a shell:
1275 * unblock signals with special interactive handling
1276 * (child shell is not interactive),
1277 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1278 * after [v]fork, if we plan to exec:
1279 * POSIX says fork clears pending signal mask in child - no need to clear it.
1280 * Restore blocked signal set to one inherited by shell just prior to exec.
1282 * Note: as a result, we do not use signal handlers much. The only uses
1283 * are to count SIGCHLDs
1284 * and to restore tty pgrp on signal-induced exit.
1287 * Standard says "When a subshell is entered, traps that are not being ignored
1288 * are set to the default actions". bash interprets it so that traps which
1289 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1292 SPECIAL_INTERACTIVE_SIGS = 0
1297 SPECIAL_JOB_SIGS = 0
1305 #if ENABLE_HUSH_FAST
1306 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1309 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1315 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1316 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1317 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1318 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1320 /* Restores tty foreground process group, and exits.
1321 * May be called as signal handler for fatal signal
1322 * (will resend signal to itself, producing correct exit state)
1323 * or called directly with -EXITCODE.
1324 * We also call it if xfunc is exiting. */
1325 static void sigexit(int sig) NORETURN;
1326 static void sigexit(int sig)
1328 /* Disable all signals: job control, SIGPIPE, etc. */
1329 sigprocmask_allsigs(SIG_BLOCK);
1331 /* Careful: we can end up here after [v]fork. Do not restore
1332 * tty pgrp then, only top-level shell process does that */
1333 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1334 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1336 /* Not a signal, just exit */
1340 kill_myself_with_sig(sig); /* does not return */
1344 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1345 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1349 /* Restores tty foreground process group, and exits. */
1350 static void hush_exit(int exitcode) NORETURN;
1351 static void hush_exit(int exitcode)
1353 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1354 /* Prevent recursion:
1355 * trap "echo Hi; exit" EXIT; exit
1357 char *argv[] = { NULL, G.traps[0], NULL };
1366 sigexit(- (exitcode & 0xff));
1372 static int check_and_run_traps(int sig)
1374 static const struct timespec zero_timespec;
1375 smalluint save_rcode;
1381 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1386 if (G.traps && G.traps[sig]) {
1387 if (G.traps[sig][0]) {
1388 /* We have user-defined handler */
1389 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1390 save_rcode = G.last_exitcode;
1393 G.last_exitcode = save_rcode;
1394 } /* else: "" trap, ignoring signal */
1397 /* not a trap: special action */
1399 #if ENABLE_HUSH_FAST
1402 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1406 /* Builtin was ^C'ed, make it look prettier: */
1413 /* bash is observed to signal whole process groups,
1414 * not individual processes */
1415 for (job = G.job_list; job; job = job->next) {
1418 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1419 if (kill(- job->pgrp, SIGHUP) == 0)
1420 kill(- job->pgrp, SIGCONT);
1425 default: /* ignored: */
1426 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1434 static const char *get_cwd(int force)
1436 if (force || G.cwd == NULL) {
1437 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1438 * we must not try to free(bb_msg_unknown) */
1439 if (G.cwd == bb_msg_unknown)
1441 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1443 G.cwd = bb_msg_unknown;
1450 * Shell and environment variable support
1452 static struct variable **get_ptr_to_local_var(const char *name)
1454 struct variable **pp;
1455 struct variable *cur;
1460 while ((cur = *pp) != NULL) {
1461 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1468 static struct variable *get_local_var(const char *name)
1470 struct variable **pp = get_ptr_to_local_var(name);
1476 static const char* FAST_FUNC get_local_var_value(const char *name)
1478 struct variable **vpp;
1480 if (G.expanded_assignments) {
1481 char **cpp = G.expanded_assignments;
1482 int len = strlen(name);
1485 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1486 return cp + len + 1;
1491 vpp = get_ptr_to_local_var(name);
1493 return strchr((*vpp)->varstr, '=') + 1;
1495 if (strcmp(name, "PPID") == 0)
1496 return utoa(G.root_ppid);
1497 // bash compat: UID? EUID?
1498 #if ENABLE_HUSH_RANDOM_SUPPORT
1499 if (strcmp(name, "RANDOM") == 0) {
1500 return utoa(next_random(&G.random_gen));
1506 /* str holds "NAME=VAL" and is expected to be malloced.
1507 * We take ownership of it.
1509 * 0: do not change export flag
1510 * (if creating new variable, flag will be 0)
1511 * 1: set export flag and putenv the variable
1512 * -1: clear export flag and unsetenv the variable
1513 * flg_read_only is set only when we handle -R var=val
1515 #if !BB_MMU && ENABLE_HUSH_LOCAL
1516 /* all params are used */
1517 #elif BB_MMU && ENABLE_HUSH_LOCAL
1518 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1519 set_local_var(str, flg_export, local_lvl)
1520 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1521 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1522 set_local_var(str, flg_export)
1523 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1524 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1525 set_local_var(str, flg_export, flg_read_only)
1527 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1529 struct variable **var_pp;
1530 struct variable *cur;
1534 eq_sign = strchr(str, '=');
1535 if (!eq_sign) { /* not expected to ever happen? */
1540 name_len = eq_sign - str + 1; /* including '=' */
1541 var_pp = &G.top_var;
1542 while ((cur = *var_pp) != NULL) {
1543 if (strncmp(cur->varstr, str, name_len) != 0) {
1544 var_pp = &cur->next;
1547 /* We found an existing var with this name */
1548 if (cur->flg_read_only) {
1552 bb_error_msg("%s: readonly variable", str);
1556 if (flg_export == -1) { // "&& cur->flg_export" ?
1557 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1562 #if ENABLE_HUSH_LOCAL
1563 if (cur->func_nest_level < local_lvl) {
1564 /* New variable is declared as local,
1565 * and existing one is global, or local
1566 * from enclosing function.
1567 * Remove and save old one: */
1568 *var_pp = cur->next;
1569 cur->next = *G.shadowed_vars_pp;
1570 *G.shadowed_vars_pp = cur;
1571 /* bash 3.2.33(1) and exported vars:
1573 * # f() { local z=a; env | grep ^z; }
1579 if (cur->flg_export)
1584 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1589 if (cur->max_len != 0) {
1590 if (cur->max_len >= strlen(str)) {
1591 /* This one is from startup env, reuse space */
1592 strcpy(cur->varstr, str);
1596 /* max_len == 0 signifies "malloced" var, which we can
1597 * (and has to) free */
1601 goto set_str_and_exp;
1604 /* Not found - create new variable struct */
1605 cur = xzalloc(sizeof(*cur));
1606 #if ENABLE_HUSH_LOCAL
1607 cur->func_nest_level = local_lvl;
1609 cur->next = *var_pp;
1615 cur->flg_read_only = flg_read_only;
1618 if (flg_export == 1)
1619 cur->flg_export = 1;
1620 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1621 cmdedit_update_prompt();
1622 if (cur->flg_export) {
1623 if (flg_export == -1) {
1624 cur->flg_export = 0;
1625 /* unsetenv was already done */
1627 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1628 return putenv(cur->varstr);
1634 /* Used at startup and after each cd */
1635 static void set_pwd_var(int exp)
1637 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1638 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1641 static int unset_local_var_len(const char *name, int name_len)
1643 struct variable *cur;
1644 struct variable **var_pp;
1647 return EXIT_SUCCESS;
1648 var_pp = &G.top_var;
1649 while ((cur = *var_pp) != NULL) {
1650 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1651 if (cur->flg_read_only) {
1652 bb_error_msg("%s: readonly variable", name);
1653 return EXIT_FAILURE;
1655 *var_pp = cur->next;
1656 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1657 bb_unsetenv(cur->varstr);
1658 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1659 cmdedit_update_prompt();
1663 return EXIT_SUCCESS;
1665 var_pp = &cur->next;
1667 return EXIT_SUCCESS;
1670 static int unset_local_var(const char *name)
1672 return unset_local_var_len(name, strlen(name));
1675 static void unset_vars(char **strings)
1683 const char *eq = strchrnul(*v, '=');
1684 unset_local_var_len(*v, (int)(eq - *v));
1690 #if ENABLE_SH_MATH_SUPPORT
1691 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1692 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1693 static char* FAST_FUNC endofname(const char *name)
1701 if (!is_in_name(*p))
1708 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1710 char *var = xasprintf("%s=%s", name, val);
1711 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1716 * Helpers for "var1=val1 var2=val2 cmd" feature
1718 static void add_vars(struct variable *var)
1720 struct variable *next;
1724 var->next = G.top_var;
1726 if (var->flg_export) {
1727 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1728 putenv(var->varstr);
1730 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1736 static struct variable *set_vars_and_save_old(char **strings)
1739 struct variable *old = NULL;
1745 struct variable *var_p;
1746 struct variable **var_pp;
1749 eq = strchr(*s, '=');
1752 var_pp = get_ptr_to_local_var(*s);
1755 /* Remove variable from global linked list */
1757 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1758 *var_pp = var_p->next;
1759 /* Add it to returned list */
1763 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1774 static int FAST_FUNC static_get(struct in_str *i)
1784 static int FAST_FUNC static_peek(struct in_str *i)
1789 #if ENABLE_HUSH_INTERACTIVE
1791 static void cmdedit_update_prompt(void)
1793 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1794 G.PS1 = get_local_var_value("PS1");
1797 G.PS2 = get_local_var_value("PS2");
1805 static const char* setup_prompt_string(int promptmode)
1807 const char *prompt_str;
1808 debug_printf("setup_prompt_string %d ", promptmode);
1809 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1810 /* Set up the prompt */
1811 if (promptmode == 0) { /* PS1 */
1813 /* bash uses $PWD value, even if it is set by user.
1814 * It uses current dir only if PWD is unset.
1815 * We always use current dir. */
1816 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1821 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1822 debug_printf("result '%s'\n", prompt_str);
1826 static void get_user_input(struct in_str *i)
1829 const char *prompt_str;
1831 prompt_str = setup_prompt_string(i->promptmode);
1832 # if ENABLE_FEATURE_EDITING
1833 /* Enable command line editing only while a command line
1834 * is actually being read */
1837 /* buglet: SIGINT will not make new prompt to appear _at once_,
1838 * only after <Enter>. (^C will work) */
1839 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1840 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1841 check_and_run_traps(0);
1842 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1843 i->eof_flag = (r < 0);
1844 if (i->eof_flag) { /* EOF/error detected */
1845 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1846 G.user_input_buf[1] = '\0';
1851 fputs(prompt_str, stdout);
1853 G.user_input_buf[0] = r = fgetc(i->file);
1854 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1855 //do we need check_and_run_traps(0)? (maybe only if stdin)
1856 } while (G.flag_SIGINT);
1857 i->eof_flag = (r == EOF);
1859 i->p = G.user_input_buf;
1862 #endif /* INTERACTIVE */
1864 /* This is the magic location that prints prompts
1865 * and gets data back from the user */
1866 static int FAST_FUNC file_get(struct in_str *i)
1870 /* If there is data waiting, eat it up */
1871 if (i->p && *i->p) {
1872 #if ENABLE_HUSH_INTERACTIVE
1876 if (i->eof_flag && !*i->p)
1878 /* note: ch is never NUL */
1880 /* need to double check i->file because we might be doing something
1881 * more complicated by now, like sourcing or substituting. */
1882 #if ENABLE_HUSH_INTERACTIVE
1883 if (G_interactive_fd && i->promptme && i->file == stdin) {
1886 } while (!*i->p); /* need non-empty line */
1887 i->promptmode = 1; /* PS2 */
1892 do ch = fgetc(i->file); while (ch == '\0');
1894 debug_printf("file_get: got '%c' %d\n", ch, ch);
1895 #if ENABLE_HUSH_INTERACTIVE
1902 /* All callers guarantee this routine will never
1903 * be used right after a newline, so prompting is not needed.
1905 static int FAST_FUNC file_peek(struct in_str *i)
1908 if (i->p && *i->p) {
1909 if (i->eof_flag && !i->p[1])
1912 /* note: ch is never NUL */
1914 do ch = fgetc(i->file); while (ch == '\0');
1915 i->eof_flag = (ch == EOF);
1916 i->peek_buf[0] = ch;
1917 i->peek_buf[1] = '\0';
1919 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1923 static void setup_file_in_str(struct in_str *i, FILE *f)
1925 i->peek = file_peek;
1927 #if ENABLE_HUSH_INTERACTIVE
1929 i->promptmode = 0; /* PS1 */
1935 static void setup_string_in_str(struct in_str *i, const char *s)
1937 i->peek = static_peek;
1938 i->get = static_get;
1939 #if ENABLE_HUSH_INTERACTIVE
1941 i->promptmode = 0; /* PS1 */
1951 #define B_CHUNK (32 * sizeof(char*))
1953 static void o_reset_to_empty_unquoted(o_string *o)
1961 static void o_free(o_string *o)
1964 memset(o, 0, sizeof(*o));
1967 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1972 static void o_grow_by(o_string *o, int len)
1974 if (o->length + len > o->maxlen) {
1975 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1976 o->data = xrealloc(o->data, 1 + o->maxlen);
1980 static void o_addchr(o_string *o, int ch)
1982 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1984 o->data[o->length] = ch;
1986 o->data[o->length] = '\0';
1989 static void o_addblock(o_string *o, const char *str, int len)
1992 memcpy(&o->data[o->length], str, len);
1994 o->data[o->length] = '\0';
1997 static void o_addstr(o_string *o, const char *str)
1999 o_addblock(o, str, strlen(str));
2003 static void nommu_addchr(o_string *o, int ch)
2009 # define nommu_addchr(o, str) ((void)0)
2012 static void o_addstr_with_NUL(o_string *o, const char *str)
2014 o_addblock(o, str, strlen(str) + 1);
2017 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2022 && (*str != '*' && *str != '?' && *str != '[')
2030 #undef HUSH_BRACE_EXP
2032 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2033 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2034 * Apparently, on unquoted $v bash still does globbing
2035 * ("v='*.txt'; echo $v" prints all .txt files),
2036 * but NOT brace expansion! Thus, there should be TWO independent
2037 * quoting mechanisms on $v expansion side: one protects
2038 * $v from brace expansion, and other additionally protects "$v" against globbing.
2039 * We have only second one.
2042 #ifdef HUSH_BRACE_EXP
2043 # define MAYBE_BRACES "{}"
2045 # define MAYBE_BRACES ""
2048 /* My analysis of quoting semantics tells me that state information
2049 * is associated with a destination, not a source.
2051 static void o_addqchr(o_string *o, int ch)
2054 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2059 o->data[o->length] = '\\';
2062 o->data[o->length] = ch;
2064 o->data[o->length] = '\0';
2067 static void o_addQchr(o_string *o, int ch)
2070 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2072 o->data[o->length] = '\\';
2076 o->data[o->length] = ch;
2078 o->data[o->length] = '\0';
2081 static void o_addQstr(o_string *o, const char *str, int len)
2084 o_addblock(o, str, len);
2090 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2091 if (ordinary_cnt > len) /* paranoia */
2093 o_addblock(o, str, ordinary_cnt);
2094 if (ordinary_cnt == len)
2096 str += ordinary_cnt;
2097 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2101 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2103 o->data[o->length] = '\\';
2107 o->data[o->length] = ch;
2109 o->data[o->length] = '\0';
2113 /* A special kind of o_string for $VAR and `cmd` expansion.
2114 * It contains char* list[] at the beginning, which is grown in 16 element
2115 * increments. Actual string data starts at the next multiple of 16 * (char*).
2116 * list[i] contains an INDEX (int!) into this string data.
2117 * It means that if list[] needs to grow, data needs to be moved higher up
2118 * but list[i]'s need not be modified.
2119 * NB: remembering how many list[i]'s you have there is crucial.
2120 * o_finalize_list() operation post-processes this structure - calculates
2121 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2123 #if DEBUG_EXPAND || DEBUG_GLOB
2124 static void debug_print_list(const char *prefix, o_string *o, int n)
2126 char **list = (char**)o->data;
2127 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2131 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2132 prefix, list, n, string_start, o->length, o->maxlen);
2135 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2136 o->data + (int)list[i] + string_start,
2137 o->data + (int)list[i] + string_start);
2141 const char *p = o->data + (int)list[n - 1] + string_start;
2143 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2147 # define debug_print_list(prefix, o, n) ((void)0)
2150 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2151 * in list[n] so that it points past last stored byte so far.
2152 * It returns n+1. */
2153 static int o_save_ptr_helper(o_string *o, int n)
2155 char **list = (char**)o->data;
2159 if (!o->has_empty_slot) {
2160 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2161 string_len = o->length - string_start;
2162 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2163 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2164 /* list[n] points to string_start, make space for 16 more pointers */
2165 o->maxlen += 0x10 * sizeof(list[0]);
2166 o->data = xrealloc(o->data, o->maxlen + 1);
2167 list = (char**)o->data;
2168 memmove(list + n + 0x10, list + n, string_len);
2169 o->length += 0x10 * sizeof(list[0]);
2171 debug_printf_list("list[%d]=%d string_start=%d\n",
2172 n, string_len, string_start);
2175 /* We have empty slot at list[n], reuse without growth */
2176 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2177 string_len = o->length - string_start;
2178 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2179 n, string_len, string_start);
2180 o->has_empty_slot = 0;
2182 list[n] = (char*)(ptrdiff_t)string_len;
2186 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2187 static int o_get_last_ptr(o_string *o, int n)
2189 char **list = (char**)o->data;
2190 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2192 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2195 #ifdef HUSH_BRACE_EXP
2196 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2197 * first, it processes even {a} (no commas), second,
2198 * I didn't manage to make it return strings when they don't match
2199 * existing files. Need to re-implement it.
2203 static int glob_needed(const char *s)
2212 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2218 /* Return pointer to next closing brace or to comma */
2219 static const char *next_brace_sub(const char *cp)
2223 while (*cp != '\0') {
2230 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2232 if (*cp++ == '{') /*}*/
2236 return *cp != '\0' ? cp : NULL;
2238 /* Recursive brace globber. Note: may garble pattern[]. */
2239 static int glob_brace(char *pattern, o_string *o, int n)
2241 char *new_pattern_buf;
2248 debug_printf_glob("glob_brace('%s')\n", pattern);
2254 if (*begin == '{') /*}*/ {
2255 /* Find the first sub-pattern and at the same time
2256 * find the rest after the closing brace */
2257 next = next_brace_sub(begin);
2259 /* An illegal expression */
2262 /*{*/ if (*next == '}') {
2263 /* "{abc}" with no commas - illegal
2264 * brace expr, disregard and skip it */
2270 if (*begin == '\\' && begin[1] != '\0')
2274 debug_printf_glob("begin:%s\n", begin);
2275 debug_printf_glob("next:%s\n", next);
2277 /* Now find the end of the whole brace expression */
2279 /*{*/ while (*rest != '}') {
2280 rest = next_brace_sub(rest);
2282 /* An illegal expression */
2285 debug_printf_glob("rest:%s\n", rest);
2287 rest_len = strlen(++rest) + 1;
2289 /* We are sure the brace expression is well-formed */
2291 /* Allocate working buffer large enough for our work */
2292 new_pattern_buf = xmalloc(strlen(pattern));
2294 /* We have a brace expression. BEGIN points to the opening {,
2295 * NEXT points past the terminator of the first element, and REST
2296 * points past the final }. We will accumulate result names from
2297 * recursive runs for each brace alternative in the buffer using
2302 /* Construct the new glob expression */
2305 mempcpy(new_pattern_buf,
2306 /* We know the prefix for all sub-patterns */
2307 pattern, begin - pattern),
2311 /* Note: glob_brace() may garble new_pattern_buf[].
2312 * That's why we re-copy prefix every time (1st memcpy above).
2314 n = glob_brace(new_pattern_buf, o, n);
2315 /*{*/ if (*next == '}') {
2316 /* We saw the last entry */
2320 next = next_brace_sub(next);
2322 free(new_pattern_buf);
2330 memset(&globdata, 0, sizeof(globdata));
2331 gr = glob(pattern, 0, NULL, &globdata);
2332 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2334 if (gr == GLOB_NOMATCH) {
2335 globfree(&globdata);
2336 /* NB: garbles parameter */
2337 unbackslash(pattern);
2338 o_addstr_with_NUL(o, pattern);
2339 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2340 return o_save_ptr_helper(o, n);
2342 if (gr == GLOB_NOSPACE)
2343 bb_error_msg_and_die(bb_msg_memory_exhausted);
2344 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2345 * but we didn't specify it. Paranoia again. */
2346 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2348 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2349 char **argv = globdata.gl_pathv;
2351 o_addstr_with_NUL(o, *argv);
2352 n = o_save_ptr_helper(o, n);
2358 globfree(&globdata);
2362 /* Performs globbing on last list[],
2363 * saving each result as a new list[].
2365 static int o_glob(o_string *o, int n)
2367 char *pattern, *copy;
2369 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2371 return o_save_ptr_helper(o, n);
2372 pattern = o->data + o_get_last_ptr(o, n);
2373 debug_printf_glob("glob pattern '%s'\n", pattern);
2374 if (!glob_needed(pattern)) {
2375 /* unbackslash last string in o in place, fix length */
2376 o->length = unbackslash(pattern) - o->data;
2377 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2378 return o_save_ptr_helper(o, n);
2381 copy = xstrdup(pattern);
2382 /* "forget" pattern in o */
2383 o->length = pattern - o->data;
2384 n = glob_brace(copy, o, n);
2387 debug_print_list("o_glob returning", o, n);
2391 #else /* !HUSH_BRACE_EXP */
2394 static int glob_needed(const char *s)
2403 if (*s == '*' || *s == '[' || *s == '?')
2409 /* Performs globbing on last list[],
2410 * saving each result as a new list[].
2412 static int o_glob(o_string *o, int n)
2418 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2420 return o_save_ptr_helper(o, n);
2421 pattern = o->data + o_get_last_ptr(o, n);
2422 debug_printf_glob("glob pattern '%s'\n", pattern);
2423 if (!glob_needed(pattern)) {
2425 /* unbackslash last string in o in place, fix length */
2426 o->length = unbackslash(pattern) - o->data;
2427 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2428 return o_save_ptr_helper(o, n);
2431 memset(&globdata, 0, sizeof(globdata));
2432 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2433 * If we glob "*.\*" and don't find anything, we need
2434 * to fall back to using literal "*.*", but GLOB_NOCHECK
2435 * will return "*.\*"!
2437 gr = glob(pattern, 0, NULL, &globdata);
2438 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2440 if (gr == GLOB_NOMATCH) {
2441 globfree(&globdata);
2444 if (gr == GLOB_NOSPACE)
2445 bb_error_msg_and_die(bb_msg_memory_exhausted);
2446 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2447 * but we didn't specify it. Paranoia again. */
2448 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2450 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2451 char **argv = globdata.gl_pathv;
2452 /* "forget" pattern in o */
2453 o->length = pattern - o->data;
2455 o_addstr_with_NUL(o, *argv);
2456 n = o_save_ptr_helper(o, n);
2462 globfree(&globdata);
2464 debug_print_list("o_glob returning", o, n);
2468 #endif /* !HUSH_BRACE_EXP */
2470 /* If o->o_glob == 1, glob the string so far remembered.
2471 * Otherwise, just finish current list[] and start new */
2472 static int o_save_ptr(o_string *o, int n)
2474 if (o->o_glob) { /* if globbing is requested */
2475 /* If o->has_empty_slot, list[n] was already globbed
2476 * (if it was requested back then when it was filled)
2477 * so don't do that again! */
2478 if (!o->has_empty_slot)
2479 return o_glob(o, n); /* o_save_ptr_helper is inside */
2481 return o_save_ptr_helper(o, n);
2484 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2485 static char **o_finalize_list(o_string *o, int n)
2490 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2492 debug_print_list("finalized", o, n);
2493 debug_printf_expand("finalized n:%d\n", n);
2494 list = (char**)o->data;
2495 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2499 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2505 /* Expansion can recurse */
2506 #if ENABLE_HUSH_TICK
2507 static int process_command_subs(o_string *dest, const char *s);
2509 static char *expand_string_to_string(const char *str);
2511 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2512 parse_stream_dquoted(dest, input, dquote_end)
2514 static int parse_stream_dquoted(o_string *as_string,
2516 struct in_str *input,
2519 /* expand_strvec_to_strvec() takes a list of strings, expands
2520 * all variable references within and returns a pointer to
2521 * a list of expanded strings, possibly with larger number
2522 * of strings. (Think VAR="a b"; echo $VAR).
2523 * This new list is allocated as a single malloc block.
2524 * NULL-terminated list of char* pointers is at the beginning of it,
2525 * followed by strings themself.
2526 * Caller can deallocate entire list by single free(list). */
2528 /* Store given string, finalizing the word and starting new one whenever
2529 * we encounter IFS char(s). This is used for expanding variable values.
2530 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2531 static int expand_on_ifs(o_string *output, int n, const char *str)
2534 int word_len = strcspn(str, G.ifs);
2536 if (output->o_escape || !output->o_glob)
2537 o_addQstr(output, str, word_len);
2538 else /* protect backslashes against globbing up :) */
2539 o_addblock_duplicate_backslash(output, str, word_len);
2542 if (!*str) /* EOL - do not finalize word */
2544 o_addchr(output, '\0');
2545 debug_print_list("expand_on_ifs", output, n);
2546 n = o_save_ptr(output, n);
2547 str += strspn(str, G.ifs); /* skip ifs chars */
2549 debug_print_list("expand_on_ifs[1]", output, n);
2553 /* Helper to expand $((...)) and heredoc body. These act as if
2554 * they are in double quotes, with the exception that they are not :).
2555 * Just the rules are similar: "expand only $var and `cmd`"
2557 * Returns malloced string.
2558 * As an optimization, we return NULL if expansion is not needed.
2560 static char *expand_pseudo_dquoted(const char *str)
2563 struct in_str input;
2564 o_string dest = NULL_O_STRING;
2566 if (strchr(str, '$') == NULL
2567 #if ENABLE_HUSH_TICK
2568 && strchr(str, '`') == NULL
2574 /* We need to expand. Example:
2575 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2577 setup_string_in_str(&input, str);
2578 parse_stream_dquoted(NULL, &dest, &input, EOF);
2579 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2580 exp_str = expand_string_to_string(dest.data);
2581 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2582 o_free_unsafe(&dest);
2586 #if ENABLE_SH_MATH_SUPPORT
2587 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2589 arith_eval_hooks_t hooks;
2593 hooks.lookupvar = get_local_var_value;
2594 hooks.setvar = set_local_var_from_halves;
2595 hooks.endofname = endofname;
2596 exp_str = expand_pseudo_dquoted(arg);
2597 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2603 /* Expand all variable references in given string, adding words to list[]
2604 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2605 * to be filled). This routine is extremely tricky: has to deal with
2606 * variables/parameters with whitespace, $* and $@, and constructs like
2607 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2608 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2610 /* or_mask is either 0 (normal case) or 0x80 -
2611 * expansion of right-hand side of assignment == 1-element expand.
2612 * It will also do no globbing, and thus we must not backslash-quote!
2619 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2620 debug_print_list("expand_vars_to_list", output, n);
2621 n = o_save_ptr(output, n);
2622 debug_print_list("expand_vars_to_list[0]", output, n);
2624 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2627 char *to_be_freed = NULL;
2628 const char *val = NULL;
2629 #if ENABLE_HUSH_TICK
2630 o_string subst_result = NULL_O_STRING;
2632 #if ENABLE_SH_MATH_SUPPORT
2633 char arith_buf[sizeof(arith_t)*3 + 2];
2635 o_addblock(output, arg, p - arg);
2636 debug_print_list("expand_vars_to_list[1]", output, n);
2638 p = strchr(p, SPECIAL_VAR_SYMBOL);
2640 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2641 /* "$@" is special. Even if quoted, it can still
2642 * expand to nothing (not even an empty string) */
2643 if ((first_ch & 0x7f) != '@')
2644 ored_ch |= first_ch;
2646 switch (first_ch & 0x7f) {
2647 /* Highest bit in first_ch indicates that var is double-quoted */
2651 if (!G.global_argv[i])
2653 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2654 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2655 smallint sv = output->o_escape;
2656 /* unquoted var's contents should be globbed, so don't escape */
2657 output->o_escape = 0;
2658 while (G.global_argv[i]) {
2659 n = expand_on_ifs(output, n, G.global_argv[i]);
2660 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2661 if (G.global_argv[i++][0] && G.global_argv[i]) {
2662 /* this argv[] is not empty and not last:
2663 * put terminating NUL, start new word */
2664 o_addchr(output, '\0');
2665 debug_print_list("expand_vars_to_list[2]", output, n);
2666 n = o_save_ptr(output, n);
2667 debug_print_list("expand_vars_to_list[3]", output, n);
2670 output->o_escape = sv;
2672 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2673 * and in this case should treat it like '$*' - see 'else...' below */
2674 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2676 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2677 if (++i >= G.global_argc)
2679 o_addchr(output, '\0');
2680 debug_print_list("expand_vars_to_list[4]", output, n);
2681 n = o_save_ptr(output, n);
2683 } else { /* quoted $*: add as one word */
2685 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2686 if (!G.global_argv[++i])
2689 o_addchr(output, G.ifs[0]);
2693 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2694 /* "Empty variable", used to make "" etc to not disappear */
2698 #if ENABLE_HUSH_TICK
2699 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2702 /* Can't just stuff it into output o_string,
2703 * expanded result may need to be globbed
2704 * and $IFS-splitted */
2705 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2706 G.last_exitcode = process_command_subs(&subst_result, arg);
2707 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
2708 val = subst_result.data;
2711 #if ENABLE_SH_MATH_SUPPORT
2712 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
2716 arg++; /* skip '+' */
2717 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
2718 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
2719 res = expand_and_evaluate_arith(arg, &errcode);
2722 const char *msg = "error in arithmetic";
2725 msg = "exponent less than 0";
2728 msg = "divide by 0";
2731 msg = "expression recursion loop detected";
2736 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2737 sprintf(arith_buf, arith_t_fmt, res);
2742 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2746 char exp_save = exp_save; /* for compiler */
2747 char *exp_saveptr; /* points to expansion operator */
2748 char *exp_word = exp_word; /* for compiler */
2752 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2753 first_char = arg[0] = first_ch & 0x7f;
2756 if (first_char == '#' && arg[1] && !exp_saveptr) {
2757 /* handle length expansion ${#var} */
2761 /* maybe handle parameter expansion */
2762 if (exp_saveptr /* if 2nd char is one of expansion operators */
2763 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2765 /* ${?:0}, ${#[:]%0} etc */
2766 exp_saveptr = var + 1;
2768 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2769 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2771 exp_op = exp_save = *exp_saveptr;
2773 exp_word = exp_saveptr + 1;
2774 if (exp_op == ':') {
2775 exp_op = *exp_word++;
2776 if (ENABLE_HUSH_BASH_COMPAT
2777 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2779 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2784 *exp_saveptr = '\0';
2785 } /* else: it's not an expansion op, but bare ${var} */
2788 /* lookup the variable in question */
2789 if (isdigit(var[0])) {
2790 /* parse_dollar() should have vetted var for us */
2791 i = xatoi_positive(var);
2792 if (i < G.global_argc)
2793 val = G.global_argv[i];
2794 /* else val remains NULL: $N with too big N */
2798 val = utoa(G.root_pid);
2800 case '!': /* bg pid */
2801 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2803 case '?': /* exitcode */
2804 val = utoa(G.last_exitcode);
2806 case '#': /* argc */
2807 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2810 val = get_local_var_value(var);
2814 /* handle any expansions */
2815 if (exp_op == 'L') {
2816 debug_printf_expand("expand: length(%s)=", val);
2817 val = utoa(val ? strlen(val) : 0);
2818 debug_printf_expand("%s\n", val);
2819 } else if (exp_op) {
2820 if (exp_op == '%' || exp_op == '#') {
2821 /* Standard-mandated substring removal ops:
2822 * ${parameter%word} - remove smallest suffix pattern
2823 * ${parameter%%word} - remove largest suffix pattern
2824 * ${parameter#word} - remove smallest prefix pattern
2825 * ${parameter##word} - remove largest prefix pattern
2827 * Word is expanded to produce a glob pattern.
2828 * Then var's value is matched to it and matching part removed.
2833 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
2834 if (exp_op == *exp_word) /* ## or %% */
2836 val = to_be_freed = xstrdup(val);
2838 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2840 exp_word = exp_exp_word;
2841 loc = scan(to_be_freed, exp_word, match_at_left);
2842 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2843 // exp_op, to_be_freed, exp_word, loc);
2846 if (loc) { /* match was found */
2847 if (match_at_left) /* # or ## */
2853 } else if (exp_op == ':') {
2854 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2855 /* It's ${var:N[:M]} bashism.
2856 * Note that in encoded form it has TWO parts:
2857 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2862 beg = expand_and_evaluate_arith(exp_word, &errcode);
2863 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2864 *p++ = SPECIAL_VAR_SYMBOL;
2866 p = strchr(p, SPECIAL_VAR_SYMBOL);
2868 len = expand_and_evaluate_arith(exp_word, &errcode);
2869 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2871 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2872 if (beg < 0) /* bash compat */
2874 debug_printf_varexp("from val:'%s'\n", val);
2875 if (len == 0 || !val || beg >= strlen(val))
2878 /* Paranoia. What if user entered 9999999999999
2879 * which fits in arith_t but not int? */
2882 val = to_be_freed = xstrndup(val + beg, len);
2884 debug_printf_varexp("val:'%s'\n", val);
2888 die_if_script("malformed ${%s:...}", var);
2891 } else { /* one of "-=+?" */
2892 /* Standard-mandated substitution ops:
2893 * ${var?word} - indicate error if unset
2894 * If var is unset, word (or a message indicating it is unset
2895 * if word is null) is written to standard error
2896 * and the shell exits with a non-zero exit status.
2897 * Otherwise, the value of var is substituted.
2898 * ${var-word} - use default value
2899 * If var is unset, word is substituted.
2900 * ${var=word} - assign and use default value
2901 * If var is unset, word is assigned to var.
2902 * In all cases, final value of var is substituted.
2903 * ${var+word} - use alternative value
2904 * If var is unset, null is substituted.
2905 * Otherwise, word is substituted.
2907 * Word is subjected to tilde expansion, parameter expansion,
2908 * command substitution, and arithmetic expansion.
2909 * If word is not needed, it is not expanded.
2911 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2912 * but also treat null var as if it is unset.
2914 int use_word = (!val || ((exp_save == ':') && !val[0]));
2916 use_word = !use_word;
2917 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2918 (exp_save == ':') ? "true" : "false", use_word);
2920 to_be_freed = expand_pseudo_dquoted(exp_word);
2922 exp_word = to_be_freed;
2923 if (exp_op == '?') {
2924 /* mimic bash message */
2925 die_if_script("%s: %s",
2927 exp_word[0] ? exp_word : "parameter null or not set"
2929 //TODO: how interactive bash aborts expansion mid-command?
2934 if (exp_op == '=') {
2935 /* ${var=[word]} or ${var:=[word]} */
2936 if (isdigit(var[0]) || var[0] == '#') {
2937 /* mimic bash message */
2938 die_if_script("$%s: cannot assign in this way", var);
2941 char *new_var = xasprintf("%s=%s", var, val);
2942 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2946 } /* one of "-=+?" */
2948 *exp_saveptr = exp_save;
2952 #if ENABLE_HUSH_TICK
2955 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2956 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2958 /* unquoted var's contents should be globbed, so don't escape */
2959 smallint sv = output->o_escape;
2960 output->o_escape = 0;
2961 n = expand_on_ifs(output, n, val);
2963 output->o_escape = sv;
2965 } else { /* quoted $VAR, val will be appended below */
2966 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2969 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2972 o_addQstr(output, val, strlen(val));
2975 /* Do the check to avoid writing to a const string */
2976 if (*p != SPECIAL_VAR_SYMBOL)
2977 *p = SPECIAL_VAR_SYMBOL;
2979 #if ENABLE_HUSH_TICK
2980 o_free(&subst_result);
2983 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2986 debug_print_list("expand_vars_to_list[a]", output, n);
2987 /* this part is literal, and it was already pre-quoted
2988 * if needed (much earlier), do not use o_addQstr here! */
2989 o_addstr_with_NUL(output, arg);
2990 debug_print_list("expand_vars_to_list[b]", output, n);
2991 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2992 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2995 /* allow to reuse list[n] later without re-growth */
2996 output->has_empty_slot = 1;
2998 o_addchr(output, '\0');
3003 static char **expand_variables(char **argv, int or_mask)
3008 o_string output = NULL_O_STRING;
3010 if (or_mask & 0x100) {
3011 output.o_escape = 1; /* protect against globbing for "$var" */
3012 /* (unquoted $var will temporarily switch it off) */
3019 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
3022 debug_print_list("expand_variables", &output, n);
3024 /* output.data (malloced in one block) gets returned in "list" */
3025 list = o_finalize_list(&output, n);
3026 debug_print_strings("expand_variables[1]", list);
3030 static char **expand_strvec_to_strvec(char **argv)
3032 return expand_variables(argv, 0x100);
3035 #if ENABLE_HUSH_BASH_COMPAT
3036 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3038 return expand_variables(argv, 0x80);
3042 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3043 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3048 o_string output = NULL_O_STRING;
3053 int is_var = is_well_formed_var_name(*v, '=');
3054 /* is_var * 0x80: singleword expansion for vars */
3055 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3057 /* Subtle! expand_vars_to_list did not glob last word yet.
3058 * It does this only when fed with further data.
3059 * Therefore we set globbing flags AFTER it, not before:
3062 /* if it is not recognizably abc=...; then: */
3063 output.o_escape = !is_var; /* protect against globbing for "$var" */
3064 /* (unquoted $var will temporarily switch it off) */
3065 output.o_glob = !is_var; /* and indeed do globbing */
3068 debug_print_list("expand_cond", &output, n);
3070 /* output.data (malloced in one block) gets returned in "list" */
3071 list = o_finalize_list(&output, n);
3072 debug_print_strings("expand_cond[1]", list);
3077 /* Used for expansion of right hand of assignments */
3078 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3080 static char *expand_string_to_string(const char *str)
3082 char *argv[2], **list;
3084 argv[0] = (char*)str;
3086 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
3088 if (!list[0] || list[1])
3089 bb_error_msg_and_die("BUG in varexp2");
3090 /* actually, just move string 2*sizeof(char*) bytes back */
3091 overlapping_strcpy((char*)list, list[0]);
3092 unbackslash((char*)list);
3093 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3097 /* Used for "eval" builtin */
3098 static char* expand_strvec_to_string(char **argv)
3102 list = expand_variables(argv, 0x80);
3103 /* Convert all NULs to spaces */
3108 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3109 bb_error_msg_and_die("BUG in varexp3");
3110 /* bash uses ' ' regardless of $IFS contents */
3115 overlapping_strcpy((char*)list, list[0]);
3116 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3120 static char **expand_assignments(char **argv, int count)
3125 G.expanded_assignments = p = NULL;
3126 /* Expand assignments into one string each */
3127 for (i = 0; i < count; i++) {
3128 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3130 G.expanded_assignments = NULL;
3137 void re_execute_shell(char ***to_free, const char *s,
3138 char *g_argv0, char **g_argv,
3139 char **builtin_argv) NORETURN;
3141 static void reset_traps_to_defaults(void)
3143 /* This function is always called in a child shell
3144 * after fork (not vfork, NOMMU doesn't use this function).
3149 /* Child shells are not interactive.
3150 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3151 * Testcase: (while :; do :; done) + ^Z should background.
3152 * Same goes for SIGTERM, SIGHUP, SIGINT.
3154 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3155 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3157 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3158 * Stupid. It can be done with *single* &= op, but we can't use
3159 * the fact that G.blocked_set is implemented as a bitmask
3161 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3165 /* Careful. Only if no trap or trap is not "" */
3166 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3167 sigdelset(&G.blocked_set, sig);
3174 /* Our homegrown sig mask is saner to work with :) */
3175 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3177 /* Resetting all traps to default except empty ones */
3178 mask = G.non_DFL_mask;
3179 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3180 if (!G.traps[sig] || !G.traps[sig][0])
3183 G.traps[sig] = NULL;
3184 /* There is no signal for 0 (EXIT) */
3187 /* There was a trap handler, we just removed it.
3188 * But if sig still has non-DFL handling,
3189 * we should not unblock the sig. */
3192 sigdelset(&G.blocked_set, sig);
3194 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3199 static void re_execute_shell(char ***to_free, const char *s,
3200 char *g_argv0, char **g_argv,
3201 char **builtin_argv) NORETURN;
3202 static void re_execute_shell(char ***to_free, const char *s,
3203 char *g_argv0, char **g_argv,
3204 char **builtin_argv)
3206 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3207 /* delims + 2 * (number of bytes in printed hex numbers) */
3208 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3209 char *heredoc_argv[4];
3210 struct variable *cur;
3211 # if ENABLE_HUSH_FUNCTIONS
3212 struct function *funcp;
3216 unsigned long long empty_trap_mask;
3218 if (!g_argv0) { /* heredoc */
3219 argv = heredoc_argv;
3220 argv[0] = (char *) G.argv0_for_re_execing;
3221 argv[1] = (char *) "-<";
3222 argv[2] = (char *) s;
3224 pp = &argv[3]; /* used as pointer to empty environment */
3230 if (pp) while (*pp++)
3233 empty_trap_mask = 0;
3236 for (sig = 1; sig < NSIG; sig++) {
3237 if (G.traps[sig] && !G.traps[sig][0])
3238 empty_trap_mask |= 1LL << sig;
3242 sprintf(param_buf, NOMMU_HACK_FMT
3243 , (unsigned) G.root_pid
3244 , (unsigned) G.root_ppid
3245 , (unsigned) G.last_bg_pid
3246 , (unsigned) G.last_exitcode
3249 IF_HUSH_LOOPS(, G.depth_of_loop)
3251 # undef NOMMU_HACK_FMT
3252 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3253 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3256 for (cur = G.top_var; cur; cur = cur->next) {
3257 if (!cur->flg_export || cur->flg_read_only)
3260 # if ENABLE_HUSH_FUNCTIONS
3261 for (funcp = G.top_func; funcp; funcp = funcp->next)
3267 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3268 *pp++ = (char *) G.argv0_for_re_execing;
3270 for (cur = G.top_var; cur; cur = cur->next) {
3271 if (cur->varstr == hush_version_str)
3273 if (cur->flg_read_only) {
3274 *pp++ = (char *) "-R";
3275 *pp++ = cur->varstr;
3276 } else if (!cur->flg_export) {
3277 *pp++ = (char *) "-V";
3278 *pp++ = cur->varstr;
3281 # if ENABLE_HUSH_FUNCTIONS
3282 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3283 *pp++ = (char *) "-F";
3284 *pp++ = funcp->name;
3285 *pp++ = funcp->body_as_string;
3288 /* We can pass activated traps here. Say, -Tnn:trap_string
3290 * However, POSIX says that subshells reset signals with traps
3292 * I tested bash-3.2 and it not only does that with true subshells
3293 * of the form ( list ), but with any forked children shells.
3294 * I set trap "echo W" WINCH; and then tried:
3296 * { echo 1; sleep 20; echo 2; } &
3297 * while true; do echo 1; sleep 20; echo 2; break; done &
3298 * true | { echo 1; sleep 20; echo 2; } | cat
3300 * In all these cases sending SIGWINCH to the child shell
3301 * did not run the trap. If I add trap "echo V" WINCH;
3302 * _inside_ group (just before echo 1), it works.
3304 * I conclude it means we don't need to pass active traps here.
3305 * Even if we would use signal handlers instead of signal masking
3306 * in order to implement trap handling,
3307 * exec syscall below resets signals to SIG_DFL for us.
3309 *pp++ = (char *) "-c";
3312 while (*++builtin_argv)
3313 *pp++ = *builtin_argv;
3314 *pp++ = (char *) "";
3319 /* *pp = NULL; - is already there */
3323 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3324 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3325 execve(bb_busybox_exec_path, argv, pp);
3326 /* Fallback. Useful for init=/bin/hush usage etc */
3327 if (argv[0][0] == '/')
3328 execve(argv[0], argv, pp);
3329 xfunc_error_retval = 127;
3330 bb_error_msg_and_die("can't re-execute the shell");
3332 #endif /* !BB_MMU */
3335 static void setup_heredoc(struct redir_struct *redir)
3337 struct fd_pair pair;
3340 /* the _body_ of heredoc (misleading field name) */
3341 const char *heredoc = redir->rd_filename;
3348 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3349 expanded = expand_pseudo_dquoted(heredoc);
3353 len = strlen(heredoc);
3355 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3357 xmove_fd(pair.rd, redir->rd_fd);
3359 /* Try writing without forking. Newer kernels have
3360 * dynamically growing pipes. Must use non-blocking write! */
3363 written = write(pair.wr, heredoc, len);
3374 ndelay_off(pair.wr);
3376 /* Okay, pipe buffer was not big enough */
3377 /* Note: we must not create a stray child (bastard? :)
3378 * for the unsuspecting parent process. Child creates a grandchild
3379 * and exits before parent execs the process which consumes heredoc
3380 * (that exec happens after we return from this function) */
3387 disable_restore_tty_pgrp_on_exit();
3388 pid = BB_MMU ? xfork() : xvfork();
3392 close(redir->rd_fd); /* read side of the pipe */
3394 full_write(pair.wr, heredoc, len); /* may loop or block */
3397 /* Delegate blocking writes to another process */
3398 xmove_fd(pair.wr, STDOUT_FILENO);
3399 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3403 #if ENABLE_HUSH_FAST
3405 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3407 enable_restore_tty_pgrp_on_exit();
3413 wait(NULL); /* wait till child has died */
3416 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3417 * and stderr if they are redirected. */
3418 static int setup_redirects(struct command *prog, int squirrel[])
3421 struct redir_struct *redir;
3423 for (redir = prog->redirects; redir; redir = redir->next) {
3424 if (redir->rd_type == REDIRECT_HEREDOC2) {
3425 /* rd_fd<<HERE case */
3426 if (squirrel && redir->rd_fd < 3
3427 && squirrel[redir->rd_fd] < 0
3429 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3431 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3433 debug_printf_parse("set heredoc '%s'\n",
3434 redir->rd_filename);
3435 setup_heredoc(redir);
3439 if (redir->rd_dup == REDIRFD_TO_FILE) {
3440 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3442 if (redir->rd_filename == NULL) {
3443 /* Something went wrong in the parse.
3444 * Pretend it didn't happen */
3445 bb_error_msg("bug in redirect parse");
3448 mode = redir_table[redir->rd_type].mode;
3449 p = expand_string_to_string(redir->rd_filename);
3450 openfd = open_or_warn(p, mode);
3453 /* this could get lost if stderr has been redirected, but
3454 * bash and ash both lose it as well (though zsh doesn't!) */
3455 //what the above comment tries to say?
3459 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3460 openfd = redir->rd_dup;
3463 if (openfd != redir->rd_fd) {
3464 if (squirrel && redir->rd_fd < 3
3465 && squirrel[redir->rd_fd] < 0
3467 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3469 if (openfd == REDIRFD_CLOSE) {
3470 /* "n>-" means "close me" */
3471 close(redir->rd_fd);
3473 xdup2(openfd, redir->rd_fd);
3474 if (redir->rd_dup == REDIRFD_TO_FILE)
3482 static void restore_redirects(int squirrel[])
3485 for (i = 0; i < 3; i++) {
3488 /* We simply die on error */
3495 static void free_pipe_list(struct pipe *head);
3497 /* Return code is the exit status of the pipe */
3498 static void free_pipe(struct pipe *pi)
3501 struct command *command;
3502 struct redir_struct *r, *rnext;
3505 if (pi->stopped_cmds > 0) /* why? */
3507 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3508 for (i = 0; i < pi->num_cmds; i++) {
3509 command = &pi->cmds[i];
3510 debug_printf_clean(" command %d:\n", i);
3511 if (command->argv) {
3512 for (a = 0, p = command->argv; *p; a++, p++) {
3513 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3515 free_strings(command->argv);
3516 command->argv = NULL;
3518 /* not "else if": on syntax error, we may have both! */
3519 if (command->group) {
3520 debug_printf_clean(" begin group (cmd_type:%d)\n",
3522 free_pipe_list(command->group);
3523 debug_printf_clean(" end group\n");
3524 command->group = NULL;
3526 /* else is crucial here.
3527 * If group != NULL, child_func is meaningless */
3528 #if ENABLE_HUSH_FUNCTIONS
3529 else if (command->child_func) {
3530 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3531 command->child_func->parent_cmd = NULL;
3535 free(command->group_as_string);
3536 command->group_as_string = NULL;
3538 for (r = command->redirects; r; r = rnext) {
3539 debug_printf_clean(" redirect %d%s",
3540 r->rd_fd, redir_table[r->rd_type].descrip);
3541 /* guard against the case >$FOO, where foo is unset or blank */
3542 if (r->rd_filename) {
3543 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3544 free(r->rd_filename);
3545 r->rd_filename = NULL;
3547 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3551 command->redirects = NULL;
3553 free(pi->cmds); /* children are an array, they get freed all at once */
3561 static void free_pipe_list(struct pipe *head)
3563 struct pipe *pi, *next;
3565 for (pi = head; pi; pi = next) {
3567 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3570 debug_printf_clean("pipe followup code %d\n", pi->followup);
3572 /*pi->next = NULL;*/
3578 static int run_list(struct pipe *pi);
3580 #define parse_stream(pstring, input, end_trigger) \
3581 parse_stream(input, end_trigger)
3583 static struct pipe *parse_stream(char **pstring,
3584 struct in_str *input,
3586 static void parse_and_run_string(const char *s);
3589 static char *find_in_path(const char *arg)
3592 const char *PATH = get_local_var_value("PATH");
3598 const char *end = strchrnul(PATH, ':');
3599 int sz = end - PATH; /* must be int! */
3603 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3605 /* We have xxx::yyyy in $PATH,
3606 * it means "use current dir" */
3609 if (access(ret, F_OK) == 0)
3622 static const struct built_in_command* find_builtin_helper(const char *name,
3623 const struct built_in_command *x,
3624 const struct built_in_command *end)
3627 if (strcmp(name, x->b_cmd) != 0) {
3631 debug_printf_exec("found builtin '%s'\n", name);
3636 static const struct built_in_command* find_builtin1(const char *name)
3638 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3640 static const struct built_in_command* find_builtin(const char *name)
3642 const struct built_in_command *x = find_builtin1(name);
3645 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3648 #if ENABLE_HUSH_FUNCTIONS
3649 static struct function **find_function_slot(const char *name)
3651 struct function **funcpp = &G.top_func;
3653 if (strcmp(name, (*funcpp)->name) == 0) {
3656 funcpp = &(*funcpp)->next;
3661 static const struct function *find_function(const char *name)
3663 const struct function *funcp = *find_function_slot(name);
3665 debug_printf_exec("found function '%s'\n", name);
3669 /* Note: takes ownership on name ptr */
3670 static struct function *new_function(char *name)
3672 struct function **funcpp = find_function_slot(name);
3673 struct function *funcp = *funcpp;
3675 if (funcp != NULL) {
3676 struct command *cmd = funcp->parent_cmd;
3677 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3679 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3681 /* Note: if !funcp->body, do not free body_as_string!
3682 * This is a special case of "-F name body" function:
3683 * body_as_string was not malloced! */
3685 free_pipe_list(funcp->body);
3687 free(funcp->body_as_string);
3691 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3692 cmd->argv[0] = funcp->name;
3693 cmd->group = funcp->body;
3695 cmd->group_as_string = funcp->body_as_string;
3699 debug_printf_exec("remembering new function '%s'\n", name);
3700 funcp = *funcpp = xzalloc(sizeof(*funcp));
3701 /*funcp->next = NULL;*/
3708 static void unset_func(const char *name)
3710 struct function **funcpp = find_function_slot(name);
3711 struct function *funcp = *funcpp;
3713 if (funcp != NULL) {
3714 debug_printf_exec("freeing function '%s'\n", funcp->name);
3715 *funcpp = funcp->next;
3716 /* funcp is unlinked now, deleting it.
3717 * Note: if !funcp->body, the function was created by
3718 * "-F name body", do not free ->body_as_string
3719 * and ->name as they were not malloced. */
3721 free_pipe_list(funcp->body);
3724 free(funcp->body_as_string);
3732 #define exec_function(to_free, funcp, argv) \
3733 exec_function(funcp, argv)
3735 static void exec_function(char ***to_free,
3736 const struct function *funcp,
3737 char **argv) NORETURN;
3738 static void exec_function(char ***to_free,
3739 const struct function *funcp,
3745 argv[0] = G.global_argv[0];
3746 G.global_argv = argv;
3750 /* On MMU, funcp->body is always non-NULL */
3751 n = run_list(funcp->body);
3755 re_execute_shell(to_free,
3756 funcp->body_as_string,
3763 static int run_function(const struct function *funcp, char **argv)
3769 save_and_replace_G_args(&sv, argv);
3771 /* "we are in function, ok to use return" */
3772 sv_flg = G.flag_return_in_progress;
3773 G.flag_return_in_progress = -1;
3774 # if ENABLE_HUSH_LOCAL
3775 G.func_nest_level++;
3778 /* On MMU, funcp->body is always non-NULL */
3781 /* Function defined by -F */
3782 parse_and_run_string(funcp->body_as_string);
3783 rc = G.last_exitcode;
3787 rc = run_list(funcp->body);
3790 # if ENABLE_HUSH_LOCAL
3792 struct variable *var;
3793 struct variable **var_pp;
3795 var_pp = &G.top_var;
3796 while ((var = *var_pp) != NULL) {
3797 if (var->func_nest_level < G.func_nest_level) {
3798 var_pp = &var->next;
3802 if (var->flg_export)
3803 bb_unsetenv(var->varstr);
3804 /* Remove from global list */
3805 *var_pp = var->next;
3811 G.func_nest_level--;
3814 G.flag_return_in_progress = sv_flg;
3816 restore_G_args(&sv, argv);
3820 #endif /* ENABLE_HUSH_FUNCTIONS */
3824 #define exec_builtin(to_free, x, argv) \
3825 exec_builtin(x, argv)
3827 #define exec_builtin(to_free, x, argv) \
3828 exec_builtin(to_free, argv)
3830 static void exec_builtin(char ***to_free,
3831 const struct built_in_command *x,
3832 char **argv) NORETURN;
3833 static void exec_builtin(char ***to_free,
3834 const struct built_in_command *x,
3838 int rcode = x->b_function(argv);
3842 /* On NOMMU, we must never block!
3843 * Example: { sleep 99 | read line; } & echo Ok
3845 re_execute_shell(to_free,
3854 static void execvp_or_die(char **argv) NORETURN;
3855 static void execvp_or_die(char **argv)
3857 debug_printf_exec("execing '%s'\n", argv[0]);
3858 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3859 execvp(argv[0], argv);
3860 bb_perror_msg("can't execute '%s'", argv[0]);
3861 _exit(127); /* bash compat */
3864 #if ENABLE_HUSH_MODE_X
3865 static void dump_cmd_in_x_mode(char **argv)
3867 if (G_x_mode && argv) {
3868 /* We want to output the line in one write op */
3876 len += strlen(argv[n++]) + 1;
3882 p += sprintf(p, " %s", argv[n++]);
3890 # define dump_cmd_in_x_mode(argv) ((void)0)
3894 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3895 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3896 #define pseudo_exec(nommu_save, command, argv_expanded) \
3897 pseudo_exec(command, argv_expanded)
3900 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3902 * Don't exit() here. If you don't exec, use _exit instead.
3903 * The at_exit handlers apparently confuse the calling process,
3904 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3905 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3906 char **argv, int assignment_cnt,
3907 char **argv_expanded) NORETURN;
3908 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3909 char **argv, int assignment_cnt,
3910 char **argv_expanded)
3914 new_env = expand_assignments(argv, assignment_cnt);
3915 dump_cmd_in_x_mode(new_env);
3917 if (!argv[assignment_cnt]) {
3918 /* Case when we are here: ... | var=val | ...
3919 * (note that we do not exit early, i.e., do not optimize out
3920 * expand_assignments(): think about ... | var=`sleep 1` | ...
3922 free_strings(new_env);
3923 _exit(EXIT_SUCCESS);
3927 set_vars_and_save_old(new_env);
3928 free(new_env); /* optional */
3929 /* we can also destroy set_vars_and_save_old's return value,
3932 nommu_save->new_env = new_env;
3933 nommu_save->old_vars = set_vars_and_save_old(new_env);
3936 if (argv_expanded) {
3937 argv = argv_expanded;
3939 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3941 nommu_save->argv = argv;
3944 dump_cmd_in_x_mode(argv);
3946 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3947 if (strchr(argv[0], '/') != NULL)
3951 /* Check if the command matches any of the builtins.
3952 * Depending on context, this might be redundant. But it's
3953 * easier to waste a few CPU cycles than it is to figure out
3954 * if this is one of those cases.
3957 /* On NOMMU, it is more expensive to re-execute shell
3958 * just in order to run echo or test builtin.
3959 * It's better to skip it here and run corresponding
3960 * non-builtin later. */
3961 const struct built_in_command *x;
3962 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3964 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3967 #if ENABLE_HUSH_FUNCTIONS
3968 /* Check if the command matches any functions */
3970 const struct function *funcp = find_function(argv[0]);
3972 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3977 #if ENABLE_FEATURE_SH_STANDALONE
3978 /* Check if the command matches any busybox applets */
3980 int a = find_applet_by_name(argv[0]);
3982 # if BB_MMU /* see above why on NOMMU it is not allowed */
3983 if (APPLET_IS_NOEXEC(a)) {
3984 debug_printf_exec("running applet '%s'\n", argv[0]);
3985 run_applet_no_and_exit(a, argv);
3988 /* Re-exec ourselves */
3989 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3990 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3991 execv(bb_busybox_exec_path, argv);
3992 /* If they called chroot or otherwise made the binary no longer
3993 * executable, fall through */
3998 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4001 execvp_or_die(argv);
4004 /* Called after [v]fork() in run_pipe
4006 static void pseudo_exec(nommu_save_t *nommu_save,
4007 struct command *command,
4008 char **argv_expanded) NORETURN;
4009 static void pseudo_exec(nommu_save_t *nommu_save,
4010 struct command *command,
4011 char **argv_expanded)
4013 if (command->argv) {
4014 pseudo_exec_argv(nommu_save, command->argv,
4015 command->assignment_cnt, argv_expanded);
4018 if (command->group) {
4019 /* Cases when we are here:
4022 * ... | ( list ) | ...
4023 * ... | { list } | ...
4027 debug_printf_exec("pseudo_exec: run_list\n");
4028 reset_traps_to_defaults();
4029 rcode = run_list(command->group);
4030 /* OK to leak memory by not calling free_pipe_list,
4031 * since this process is about to exit */
4034 re_execute_shell(&nommu_save->argv_from_re_execing,
4035 command->group_as_string,
4042 /* Case when we are here: ... | >file */
4043 debug_printf_exec("pseudo_exec'ed null command\n");
4044 _exit(EXIT_SUCCESS);
4048 static const char *get_cmdtext(struct pipe *pi)
4054 /* This is subtle. ->cmdtext is created only on first backgrounding.
4055 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4056 * On subsequent bg argv is trashed, but we won't use it */
4059 argv = pi->cmds[0].argv;
4060 if (!argv || !argv[0]) {
4061 pi->cmdtext = xzalloc(1);
4067 len += strlen(*argv) + 1;
4071 argv = pi->cmds[0].argv;
4073 len = strlen(*argv);
4074 memcpy(p, *argv, len);
4082 static void insert_bg_job(struct pipe *pi)
4084 struct pipe *job, **jobp;
4087 /* Linear search for the ID of the job to use */
4089 for (job = G.job_list; job; job = job->next)
4090 if (job->jobid >= pi->jobid)
4091 pi->jobid = job->jobid + 1;
4093 /* Add job to the list of running jobs */
4095 while ((job = *jobp) != NULL)
4097 job = *jobp = xmalloc(sizeof(*job));
4099 *job = *pi; /* physical copy */
4101 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4102 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4103 for (i = 0; i < pi->num_cmds; i++) {
4104 job->cmds[i].pid = pi->cmds[i].pid;
4105 /* all other fields are not used and stay zero */
4107 job->cmdtext = xstrdup(get_cmdtext(pi));
4109 if (G_interactive_fd)
4110 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4111 G.last_jobid = job->jobid;
4114 static void remove_bg_job(struct pipe *pi)
4116 struct pipe *prev_pipe;
4118 if (pi == G.job_list) {
4119 G.job_list = pi->next;
4121 prev_pipe = G.job_list;
4122 while (prev_pipe->next != pi)
4123 prev_pipe = prev_pipe->next;
4124 prev_pipe->next = pi->next;
4127 G.last_jobid = G.job_list->jobid;
4132 /* Remove a backgrounded job */
4133 static void delete_finished_bg_job(struct pipe *pi)
4136 pi->stopped_cmds = 0;
4142 /* Check to see if any processes have exited -- if they
4143 * have, figure out why and see if a job has completed */
4144 static int checkjobs(struct pipe* fg_pipe)
4154 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4156 attributes = WUNTRACED;
4157 if (fg_pipe == NULL)
4158 attributes |= WNOHANG;
4161 #if ENABLE_HUSH_FAST
4162 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4163 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4164 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4165 /* There was neither fork nor SIGCHLD since last waitpid */
4166 /* Avoid doing waitpid syscall if possible */
4167 if (!G.we_have_children) {
4171 if (fg_pipe == NULL) { /* is WNOHANG set? */
4172 /* We have children, but they did not exit
4173 * or stop yet (we saw no SIGCHLD) */
4176 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4180 /* Do we do this right?
4181 * bash-3.00# sleep 20 | false
4183 * [3]+ Stopped sleep 20 | false
4184 * bash-3.00# echo $?
4185 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4186 * [hush 1.14.0: yes we do it right]
4193 #if ENABLE_HUSH_FAST
4194 i = G.count_SIGCHLD;
4196 childpid = waitpid(-1, &status, attributes);
4197 if (childpid <= 0) {
4198 if (childpid && errno != ECHILD)
4199 bb_perror_msg("waitpid");
4200 #if ENABLE_HUSH_FAST
4201 else { /* Until next SIGCHLD, waitpid's are useless */
4202 G.we_have_children = (childpid == 0);
4203 G.handled_SIGCHLD = i;
4204 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4209 dead = WIFEXITED(status) || WIFSIGNALED(status);
4212 if (WIFSTOPPED(status))
4213 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4214 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4215 if (WIFSIGNALED(status))
4216 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4217 childpid, WTERMSIG(status), WEXITSTATUS(status));
4218 if (WIFEXITED(status))
4219 debug_printf_jobs("pid %d exited, exitcode %d\n",
4220 childpid, WEXITSTATUS(status));
4222 /* Were we asked to wait for fg pipe? */
4224 for (i = 0; i < fg_pipe->num_cmds; i++) {
4225 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4226 if (fg_pipe->cmds[i].pid != childpid)
4229 fg_pipe->cmds[i].pid = 0;
4230 fg_pipe->alive_cmds--;
4231 if (i == fg_pipe->num_cmds - 1) {
4232 /* last process gives overall exitstatus */
4233 rcode = WEXITSTATUS(status);
4234 /* bash prints killer signal's name for *last*
4235 * process in pipe (prints just newline for SIGINT).
4236 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4238 if (WIFSIGNALED(status)) {
4239 int sig = WTERMSIG(status);
4240 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4241 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4242 * Maybe we need to use sig | 128? */
4245 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4248 fg_pipe->cmds[i].is_stopped = 1;
4249 fg_pipe->stopped_cmds++;
4251 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4252 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4253 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4254 /* All processes in fg pipe have exited or stopped */
4255 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4256 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4257 * and "killall -STOP cat" */
4258 if (G_interactive_fd) {
4260 if (fg_pipe->alive_cmds)
4261 insert_bg_job(fg_pipe);
4265 if (!fg_pipe->alive_cmds)
4268 /* There are still running processes in the fg pipe */
4269 goto wait_more; /* do waitpid again */
4271 /* it wasnt fg_pipe, look for process in bg pipes */
4275 /* We asked to wait for bg or orphaned children */
4276 /* No need to remember exitcode in this case */
4277 for (pi = G.job_list; pi; pi = pi->next) {
4278 for (i = 0; i < pi->num_cmds; i++) {
4279 if (pi->cmds[i].pid == childpid)
4280 goto found_pi_and_prognum;
4283 /* Happens when shell is used as init process (init=/bin/sh) */
4284 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4285 continue; /* do waitpid again */
4287 found_pi_and_prognum:
4290 pi->cmds[i].pid = 0;
4292 if (!pi->alive_cmds) {
4293 if (G_interactive_fd)
4294 printf(JOB_STATUS_FORMAT, pi->jobid,
4295 "Done", pi->cmdtext);
4296 delete_finished_bg_job(pi);
4300 pi->cmds[i].is_stopped = 1;
4304 } /* while (waitpid succeeds)... */
4310 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4313 int rcode = checkjobs(fg_pipe);
4314 if (G_saved_tty_pgrp) {
4315 /* Job finished, move the shell to the foreground */
4316 p = getpgrp(); /* our process group id */
4317 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4318 tcsetpgrp(G_interactive_fd, p);
4324 /* Start all the jobs, but don't wait for anything to finish.
4327 * Return code is normally -1, when the caller has to wait for children
4328 * to finish to determine the exit status of the pipe. If the pipe
4329 * is a simple builtin command, however, the action is done by the
4330 * time run_pipe returns, and the exit code is provided as the
4333 * Returns -1 only if started some children. IOW: we have to
4334 * mask out retvals of builtins etc with 0xff!
4336 * The only case when we do not need to [v]fork is when the pipe
4337 * is single, non-backgrounded, non-subshell command. Examples:
4338 * cmd ; ... { list } ; ...
4339 * cmd && ... { list } && ...
4340 * cmd || ... { list } || ...
4341 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4342 * or (if SH_STANDALONE) an applet, and we can run the { list }
4343 * with run_list. If it isn't one of these, we fork and exec cmd.
4345 * Cases when we must fork:
4346 * non-single: cmd | cmd
4347 * backgrounded: cmd & { list } &
4348 * subshell: ( list ) [&]
4350 #if !ENABLE_HUSH_MODE_X
4351 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4352 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4354 static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4356 /* setup_redirects acts on file descriptors, not FILEs.
4357 * This is perfect for work that comes after exec().
4358 * Is it really safe for inline use? Experimentally,
4359 * things seem to work. */
4360 int rcode = setup_redirects(command, squirrel);
4362 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4363 *new_env_p = new_env;
4364 dump_cmd_in_x_mode(new_env);
4365 dump_cmd_in_x_mode(argv_expanded);
4367 *old_vars_p = set_vars_and_save_old(new_env);
4371 static NOINLINE int run_pipe(struct pipe *pi)
4373 static const char *const null_ptr = NULL;
4377 struct command *command;
4378 char **argv_expanded;
4380 /* it is not always needed, but we aim to smaller code */
4381 int squirrel[] = { -1, -1, -1 };
4384 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4387 IF_HUSH_JOB(pi->pgrp = -1;)
4388 pi->stopped_cmds = 0;
4389 command = &pi->cmds[0];
4390 argv_expanded = NULL;
4392 if (pi->num_cmds != 1
4393 || pi->followup == PIPE_BG
4394 || command->cmd_type == CMD_SUBSHELL
4401 debug_printf_exec(": group:%p argv:'%s'\n",
4402 command->group, command->argv ? command->argv[0] : "NONE");
4404 if (command->group) {
4405 #if ENABLE_HUSH_FUNCTIONS
4406 if (command->cmd_type == CMD_FUNCDEF) {
4407 /* "executing" func () { list } */
4408 struct function *funcp;
4410 funcp = new_function(command->argv[0]);
4411 /* funcp->name is already set to argv[0] */
4412 funcp->body = command->group;
4414 funcp->body_as_string = command->group_as_string;
4415 command->group_as_string = NULL;
4417 command->group = NULL;
4418 command->argv[0] = NULL;
4419 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4420 funcp->parent_cmd = command;
4421 command->child_func = funcp;
4423 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4425 return EXIT_SUCCESS;
4429 debug_printf("non-subshell group\n");
4430 rcode = 1; /* exitcode if redir failed */
4431 if (setup_redirects(command, squirrel) == 0) {
4432 debug_printf_exec(": run_list\n");
4433 rcode = run_list(command->group) & 0xff;
4435 restore_redirects(squirrel);
4436 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4438 debug_printf_exec("run_pipe: return %d\n", rcode);
4442 argv = command->argv ? command->argv : (char **) &null_ptr;
4444 const struct built_in_command *x;
4445 #if ENABLE_HUSH_FUNCTIONS
4446 const struct function *funcp;
4450 char **new_env = NULL;
4451 struct variable *old_vars = NULL;
4453 if (argv[command->assignment_cnt] == NULL) {
4454 /* Assignments, but no command */
4455 /* Ensure redirects take effect (that is, create files).
4456 * Try "a=t >file" */
4457 #if 0 /* A few cases in testsuite fail with this code. FIXME */
4458 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4459 /* Set shell variables */
4463 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4464 /* Do we need to flag set_local_var() errors?
4465 * "assignment to readonly var" and "putenv error"
4470 /* Redirect error sets $? to 1. Otherwise,
4471 * if evaluating assignment value set $?, retain it.
4472 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4474 rcode = G.last_exitcode;
4475 /* Exit, _skipping_ variable restoring code: */
4476 goto clean_up_and_ret0;
4478 #else /* Older, bigger, but more correct code */
4480 rcode = setup_redirects(command, squirrel);
4481 restore_redirects(squirrel);
4482 /* Set shell variables */
4484 bb_putchar_stderr('+');
4486 char *p = expand_string_to_string(*argv);
4488 fprintf(stderr, " %s", p);
4489 debug_printf_exec("set shell var:'%s'->'%s'\n",
4491 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4492 /* Do we need to flag set_local_var() errors?
4493 * "assignment to readonly var" and "putenv error"
4498 bb_putchar_stderr('\n');
4499 /* Redirect error sets $? to 1. Otherwise,
4500 * if evaluating assignment value set $?, retain it.
4501 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4503 rcode = G.last_exitcode;
4504 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4506 debug_printf_exec("run_pipe: return %d\n", rcode);
4511 /* Expand the rest into (possibly) many strings each */
4513 #if ENABLE_HUSH_BASH_COMPAT
4514 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4515 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4518 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4519 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4520 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4524 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4527 /* if someone gives us an empty string: `cmd with empty output` */
4528 if (!argv_expanded[0]) {
4529 free(argv_expanded);
4531 return G.last_exitcode;
4534 x = find_builtin(argv_expanded[0]);
4535 #if ENABLE_HUSH_FUNCTIONS
4538 funcp = find_function(argv_expanded[0]);
4542 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4543 debug_printf("exec with redirects only\n");
4544 rcode = setup_redirects(command, NULL);
4545 goto clean_up_and_ret1;
4548 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4551 debug_printf_exec(": builtin '%s' '%s'...\n",
4552 x->b_cmd, argv_expanded[1]);
4553 rcode = x->b_function(argv_expanded) & 0xff;
4556 #if ENABLE_HUSH_FUNCTIONS
4558 # if ENABLE_HUSH_LOCAL
4559 struct variable **sv;
4560 sv = G.shadowed_vars_pp;
4561 G.shadowed_vars_pp = &old_vars;
4563 debug_printf_exec(": function '%s' '%s'...\n",
4564 funcp->name, argv_expanded[1]);
4565 rcode = run_function(funcp, argv_expanded) & 0xff;
4566 # if ENABLE_HUSH_LOCAL
4567 G.shadowed_vars_pp = sv;
4573 unset_vars(new_env);
4575 /* clean_up_and_ret0: */
4576 restore_redirects(squirrel);
4578 free(argv_expanded);
4579 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4581 debug_printf_exec("run_pipe return %d\n", rcode);
4585 if (ENABLE_FEATURE_SH_STANDALONE) {
4586 int n = find_applet_by_name(argv_expanded[0]);
4587 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4588 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4590 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4591 argv_expanded[0], argv_expanded[1]);
4592 rcode = run_nofork_applet(n, argv_expanded);
4594 goto clean_up_and_ret;
4597 /* It is neither builtin nor applet. We must fork. */
4601 /* NB: argv_expanded may already be created, and that
4602 * might include `cmd` runs! Do not rerun it! We *must*
4603 * use argv_expanded if it's non-NULL */
4605 /* Going to fork a child per each pipe member */
4610 while (cmd_no < pi->num_cmds) {
4611 struct fd_pair pipefds;
4613 volatile nommu_save_t nommu_save;
4614 nommu_save.new_env = NULL;
4615 nommu_save.old_vars = NULL;
4616 nommu_save.argv = NULL;
4617 nommu_save.argv_from_re_execing = NULL;
4619 command = &pi->cmds[cmd_no];
4621 if (command->argv) {
4622 debug_printf_exec(": pipe member '%s' '%s'...\n",
4623 command->argv[0], command->argv[1]);
4625 debug_printf_exec(": pipe member with no argv\n");
4628 /* pipes are inserted between pairs of commands */
4631 if (cmd_no < pi->num_cmds)
4632 xpiped_pair(pipefds);
4634 command->pid = BB_MMU ? fork() : vfork();
4635 if (!command->pid) { /* child */
4637 disable_restore_tty_pgrp_on_exit();
4638 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4640 /* Every child adds itself to new process group
4641 * with pgid == pid_of_first_child_in_pipe */
4642 if (G.run_list_level == 1 && G_interactive_fd) {
4645 if (pgrp < 0) /* true for 1st process only */
4647 if (setpgid(0, pgrp) == 0
4648 && pi->followup != PIPE_BG
4649 && G_saved_tty_pgrp /* we have ctty */
4651 /* We do it in *every* child, not just first,
4653 tcsetpgrp(G_interactive_fd, pgrp);
4657 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4658 /* 1st cmd in backgrounded pipe
4659 * should have its stdin /dev/null'ed */
4661 if (open(bb_dev_null, O_RDONLY))
4662 xopen("/", O_RDONLY);
4664 xmove_fd(next_infd, 0);
4666 xmove_fd(pipefds.wr, 1);
4669 /* Like bash, explicit redirects override pipes,
4670 * and the pipe fd is available for dup'ing. */
4671 if (setup_redirects(command, NULL))
4674 /* Restore default handlers just prior to exec */
4675 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4677 /* Stores to nommu_save list of env vars putenv'ed
4678 * (NOMMU, on MMU we don't need that) */
4679 /* cast away volatility... */
4680 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4681 /* pseudo_exec() does not return */
4684 /* parent or error */
4685 #if ENABLE_HUSH_FAST
4687 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4689 enable_restore_tty_pgrp_on_exit();
4691 /* Clean up after vforked child */
4692 free(nommu_save.argv);
4693 free(nommu_save.argv_from_re_execing);
4694 unset_vars(nommu_save.new_env);
4695 add_vars(nommu_save.old_vars);
4697 free(argv_expanded);
4698 argv_expanded = NULL;
4699 if (command->pid < 0) { /* [v]fork failed */
4700 /* Clearly indicate, was it fork or vfork */
4701 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4705 /* Second and next children need to know pid of first one */
4707 pi->pgrp = command->pid;
4713 if (cmd_no < pi->num_cmds)
4715 /* Pass read (output) pipe end to next iteration */
4716 next_infd = pipefds.rd;
4719 if (!pi->alive_cmds) {
4721 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4726 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4730 #ifndef debug_print_tree
4731 static void debug_print_tree(struct pipe *pi, int lvl)
4733 static const char *const PIPE[] = {
4739 static const char *RES[] = {
4740 [RES_NONE ] = "NONE" ,
4743 [RES_THEN ] = "THEN" ,
4744 [RES_ELIF ] = "ELIF" ,
4745 [RES_ELSE ] = "ELSE" ,
4748 # if ENABLE_HUSH_LOOPS
4749 [RES_FOR ] = "FOR" ,
4750 [RES_WHILE] = "WHILE",
4751 [RES_UNTIL] = "UNTIL",
4753 [RES_DONE ] = "DONE" ,
4755 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4758 # if ENABLE_HUSH_CASE
4759 [RES_CASE ] = "CASE" ,
4760 [RES_CASE_IN ] = "CASE_IN" ,
4761 [RES_MATCH] = "MATCH",
4762 [RES_CASE_BODY] = "CASE_BODY",
4763 [RES_ESAC ] = "ESAC" ,
4765 [RES_XXXX ] = "XXXX" ,
4766 [RES_SNTX ] = "SNTX" ,
4768 static const char *const CMDTYPE[] = {
4772 # if ENABLE_HUSH_FUNCTIONS
4781 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4782 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4784 while (prn < pi->num_cmds) {
4785 struct command *command = &pi->cmds[prn];
4786 char **argv = command->argv;
4788 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4790 command->assignment_cnt);
4791 if (command->group) {
4792 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4793 CMDTYPE[command->cmd_type],
4796 , " group_as_string:", command->group_as_string
4801 debug_print_tree(command->group, lvl+1);
4805 if (argv) while (*argv) {
4806 fprintf(stderr, " '%s'", *argv);
4809 fprintf(stderr, "\n");
4816 #endif /* debug_print_tree */
4818 /* NB: called by pseudo_exec, and therefore must not modify any
4819 * global data until exec/_exit (we can be a child after vfork!) */
4820 static int run_list(struct pipe *pi)
4822 #if ENABLE_HUSH_CASE
4823 char *case_word = NULL;
4825 #if ENABLE_HUSH_LOOPS
4826 struct pipe *loop_top = NULL;
4827 char **for_lcur = NULL;
4828 char **for_list = NULL;
4830 smallint last_followup;
4832 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4833 smalluint cond_code = 0;
4835 enum { cond_code = 0 };
4838 smallint rword; /* enum reserved_style */
4839 smallint last_rword; /* ditto */
4842 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4845 #if ENABLE_HUSH_LOOPS
4846 /* Check syntax for "for" */
4847 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4848 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4850 /* current word is FOR or IN (BOLD in comments below) */
4851 if (cpipe->next == NULL) {
4852 syntax_error("malformed for");
4854 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4857 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4858 if (cpipe->next->res_word == RES_DO)
4860 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4861 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4862 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4864 syntax_error("malformed for");
4866 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4872 /* Past this point, all code paths should jump to ret: label
4873 * in order to return, no direct "return" statements please.
4874 * This helps to ensure that no memory is leaked. */
4882 last_rword = RES_XXXX;
4884 last_followup = PIPE_SEQ;
4885 rcode = G.last_exitcode;
4887 /* Go through list of pipes, (maybe) executing them. */
4888 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4892 IF_HAS_KEYWORDS(rword = pi->res_word;)
4893 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4894 rword, cond_code, last_rword);
4895 #if ENABLE_HUSH_LOOPS
4896 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4897 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4899 /* start of a loop: remember where loop starts */
4904 /* Still in the same "if...", "then..." or "do..." branch? */
4905 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4906 if ((rcode == 0 && last_followup == PIPE_OR)
4907 || (rcode != 0 && last_followup == PIPE_AND)
4909 /* It is "<true> || CMD" or "<false> && CMD"
4910 * and we should not execute CMD */
4911 debug_printf_exec("skipped cmd because of || or &&\n");
4912 last_followup = pi->followup;
4916 last_followup = pi->followup;
4917 IF_HAS_KEYWORDS(last_rword = rword;)
4920 if (rword == RES_THEN) {
4921 /* if false; then ... fi has exitcode 0! */
4922 G.last_exitcode = rcode = EXIT_SUCCESS;
4923 /* "if <false> THEN cmd": skip cmd */
4927 if (rword == RES_ELSE || rword == RES_ELIF) {
4928 /* "if <true> then ... ELSE/ELIF cmd":
4929 * skip cmd and all following ones */
4934 #if ENABLE_HUSH_LOOPS
4935 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4937 /* first loop through for */
4939 static const char encoded_dollar_at[] ALIGN1 = {
4940 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4941 }; /* encoded representation of "$@" */
4942 static const char *const encoded_dollar_at_argv[] = {
4943 encoded_dollar_at, NULL
4944 }; /* argv list with one element: "$@" */
4947 vals = (char**)encoded_dollar_at_argv;
4948 if (pi->next->res_word == RES_IN) {
4949 /* if no variable values after "in" we skip "for" */
4950 if (!pi->next->cmds[0].argv) {
4951 G.last_exitcode = rcode = EXIT_SUCCESS;
4952 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4955 vals = pi->next->cmds[0].argv;
4956 } /* else: "for var; do..." -> assume "$@" list */
4957 /* create list of variable values */
4958 debug_print_strings("for_list made from", vals);
4959 for_list = expand_strvec_to_strvec(vals);
4960 for_lcur = for_list;
4961 debug_print_strings("for_list", for_list);
4964 /* "for" loop is over, clean up */
4970 /* Insert next value from for_lcur */
4971 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4972 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4975 if (rword == RES_IN) {
4976 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4978 if (rword == RES_DONE) {
4979 continue; /* "done" has no cmds too */
4982 #if ENABLE_HUSH_CASE
4983 if (rword == RES_CASE) {
4984 case_word = expand_strvec_to_string(pi->cmds->argv);
4987 if (rword == RES_MATCH) {
4990 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4992 /* all prev words didn't match, does this one match? */
4993 argv = pi->cmds->argv;
4995 char *pattern = expand_string_to_string(*argv);
4996 /* TODO: which FNM_xxx flags to use? */
4997 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4999 if (cond_code == 0) { /* match! we will execute this branch */
5000 free(case_word); /* make future "word)" stop */
5008 if (rword == RES_CASE_BODY) { /* inside of a case branch */
5010 continue; /* not matched yet, skip this pipe */
5013 /* Just pressing <enter> in shell should check for jobs.
5014 * OTOH, in non-interactive shell this is useless
5015 * and only leads to extra job checks */
5016 if (pi->num_cmds == 0) {
5017 if (G_interactive_fd)
5018 goto check_jobs_and_continue;
5022 /* After analyzing all keywords and conditions, we decided
5023 * to execute this pipe. NB: have to do checkjobs(NULL)
5024 * after run_pipe to collect any background children,
5025 * even if list execution is to be stopped. */
5026 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
5029 #if ENABLE_HUSH_LOOPS
5030 G.flag_break_continue = 0;
5032 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5034 /* We ran a builtin, function, or group.
5035 * rcode is already known
5036 * and we don't need to wait for anything. */
5037 G.last_exitcode = rcode;
5038 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
5039 check_and_run_traps(0);
5040 #if ENABLE_HUSH_LOOPS
5041 /* Was it "break" or "continue"? */
5042 if (G.flag_break_continue) {
5043 smallint fbc = G.flag_break_continue;
5044 /* We might fall into outer *loop*,
5045 * don't want to break it too */
5047 G.depth_break_continue--;
5048 if (G.depth_break_continue == 0)
5049 G.flag_break_continue = 0;
5050 /* else: e.g. "continue 2" should *break* once, *then* continue */
5051 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
5052 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
5053 goto check_jobs_and_break;
5054 /* "continue": simulate end of loop */
5059 #if ENABLE_HUSH_FUNCTIONS
5060 if (G.flag_return_in_progress == 1) {
5061 /* same as "goto check_jobs_and_break" */
5066 } else if (pi->followup == PIPE_BG) {
5067 /* What does bash do with attempts to background builtins? */
5068 /* even bash 3.2 doesn't do that well with nested bg:
5069 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5070 * I'm NOT treating inner &'s as jobs */
5071 check_and_run_traps(0);
5073 if (G.run_list_level == 1)
5076 /* Last command's pid goes to $! */
5077 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
5078 G.last_exitcode = rcode = EXIT_SUCCESS;
5079 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5082 if (G.run_list_level == 1 && G_interactive_fd) {
5083 /* Waits for completion, then fg's main shell */
5084 rcode = checkjobs_and_fg_shell(pi);
5085 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5086 check_and_run_traps(0);
5089 { /* This one just waits for completion */
5090 rcode = checkjobs(pi);
5091 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5092 check_and_run_traps(0);
5094 G.last_exitcode = rcode;
5098 /* Analyze how result affects subsequent commands */
5100 if (rword == RES_IF || rword == RES_ELIF)
5103 #if ENABLE_HUSH_LOOPS
5104 /* Beware of "while false; true; do ..."! */
5105 if (pi->next && pi->next->res_word == RES_DO) {
5106 if (rword == RES_WHILE) {
5108 /* "while false; do...done" - exitcode 0 */
5109 G.last_exitcode = rcode = EXIT_SUCCESS;
5110 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5111 goto check_jobs_and_break;
5114 if (rword == RES_UNTIL) {
5116 debug_printf_exec(": until expr is true: breaking\n");
5117 check_jobs_and_break:
5125 check_jobs_and_continue:
5132 #if ENABLE_HUSH_LOOPS
5137 #if ENABLE_HUSH_CASE
5141 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5145 /* Select which version we will use */
5146 static int run_and_free_list(struct pipe *pi)
5149 debug_printf_exec("run_and_free_list entered\n");
5151 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5152 rcode = run_list(pi);
5154 /* free_pipe_list has the side effect of clearing memory.
5155 * In the long run that function can be merged with run_list,
5156 * but doing that now would hobble the debugging effort. */
5158 debug_printf_exec("run_and_free_list return %d\n", rcode);
5163 static struct pipe *new_pipe(void)
5166 pi = xzalloc(sizeof(struct pipe));
5167 /*pi->followup = 0; - deliberately invalid value */
5168 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5172 /* Command (member of a pipe) is complete, or we start a new pipe
5173 * if ctx->command is NULL.
5174 * No errors possible here.
5176 static int done_command(struct parse_context *ctx)
5178 /* The command is really already in the pipe structure, so
5179 * advance the pipe counter and make a new, null command. */
5180 struct pipe *pi = ctx->pipe;
5181 struct command *command = ctx->command;
5184 if (IS_NULL_CMD(command)) {
5185 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5189 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5190 //debug_print_tree(ctx->list_head, 20);
5192 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5195 /* Only real trickiness here is that the uncommitted
5196 * command structure is not counted in pi->num_cmds. */
5197 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5198 ctx->command = command = &pi->cmds[pi->num_cmds];
5200 memset(command, 0, sizeof(*command));
5201 return pi->num_cmds; /* used only for 0/nonzero check */
5204 static void done_pipe(struct parse_context *ctx, pipe_style type)
5208 debug_printf_parse("done_pipe entered, followup %d\n", type);
5209 /* Close previous command */
5210 not_null = done_command(ctx);
5211 ctx->pipe->followup = type;
5213 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5214 ctx->ctx_inverted = 0;
5215 ctx->pipe->res_word = ctx->ctx_res_w;
5218 /* Without this check, even just <enter> on command line generates
5219 * tree of three NOPs (!). Which is harmless but annoying.
5220 * IOW: it is safe to do it unconditionally. */
5223 || ctx->ctx_res_w == RES_FI
5225 #if ENABLE_HUSH_LOOPS
5226 || ctx->ctx_res_w == RES_DONE
5227 || ctx->ctx_res_w == RES_FOR
5228 || ctx->ctx_res_w == RES_IN
5230 #if ENABLE_HUSH_CASE
5231 || ctx->ctx_res_w == RES_ESAC
5235 debug_printf_parse("done_pipe: adding new pipe: "
5236 "not_null:%d ctx->ctx_res_w:%d\n",
5237 not_null, ctx->ctx_res_w);
5239 ctx->pipe->next = new_p;
5241 /* RES_THEN, RES_DO etc are "sticky" -
5242 * they remain set for pipes inside if/while.
5243 * This is used to control execution.
5244 * RES_FOR and RES_IN are NOT sticky (needed to support
5245 * cases where variable or value happens to match a keyword):
5247 #if ENABLE_HUSH_LOOPS
5248 if (ctx->ctx_res_w == RES_FOR
5249 || ctx->ctx_res_w == RES_IN)
5250 ctx->ctx_res_w = RES_NONE;
5252 #if ENABLE_HUSH_CASE
5253 if (ctx->ctx_res_w == RES_MATCH)
5254 ctx->ctx_res_w = RES_CASE_BODY;
5255 if (ctx->ctx_res_w == RES_CASE)
5256 ctx->ctx_res_w = RES_CASE_IN;
5258 ctx->command = NULL; /* trick done_command below */
5259 /* Create the memory for command, roughly:
5260 * ctx->pipe->cmds = new struct command;
5261 * ctx->command = &ctx->pipe->cmds[0];
5264 //debug_print_tree(ctx->list_head, 10);
5266 debug_printf_parse("done_pipe return\n");
5269 static void initialize_context(struct parse_context *ctx)
5271 memset(ctx, 0, sizeof(*ctx));
5272 ctx->pipe = ctx->list_head = new_pipe();
5273 /* Create the memory for command, roughly:
5274 * ctx->pipe->cmds = new struct command;
5275 * ctx->command = &ctx->pipe->cmds[0];
5280 /* If a reserved word is found and processed, parse context is modified
5281 * and 1 is returned.
5284 struct reserved_combo {
5287 unsigned char assignment_flag;
5291 FLAG_END = (1 << RES_NONE ),
5293 FLAG_IF = (1 << RES_IF ),
5294 FLAG_THEN = (1 << RES_THEN ),
5295 FLAG_ELIF = (1 << RES_ELIF ),
5296 FLAG_ELSE = (1 << RES_ELSE ),
5297 FLAG_FI = (1 << RES_FI ),
5299 # if ENABLE_HUSH_LOOPS
5300 FLAG_FOR = (1 << RES_FOR ),
5301 FLAG_WHILE = (1 << RES_WHILE),
5302 FLAG_UNTIL = (1 << RES_UNTIL),
5303 FLAG_DO = (1 << RES_DO ),
5304 FLAG_DONE = (1 << RES_DONE ),
5305 FLAG_IN = (1 << RES_IN ),
5307 # if ENABLE_HUSH_CASE
5308 FLAG_MATCH = (1 << RES_MATCH),
5309 FLAG_ESAC = (1 << RES_ESAC ),
5311 FLAG_START = (1 << RES_XXXX ),
5314 static const struct reserved_combo* match_reserved_word(o_string *word)
5316 /* Mostly a list of accepted follow-up reserved words.
5317 * FLAG_END means we are done with the sequence, and are ready
5318 * to turn the compound list into a command.
5319 * FLAG_START means the word must start a new compound list.
5321 static const struct reserved_combo reserved_list[] = {
5323 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5324 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5325 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5326 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5327 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5328 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5330 # if ENABLE_HUSH_LOOPS
5331 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5332 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5333 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5334 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5335 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5336 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5338 # if ENABLE_HUSH_CASE
5339 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5340 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5343 const struct reserved_combo *r;
5345 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5346 if (strcmp(word->data, r->literal) == 0)
5351 /* Return 0: not a keyword, 1: keyword
5353 static int reserved_word(o_string *word, struct parse_context *ctx)
5355 # if ENABLE_HUSH_CASE
5356 static const struct reserved_combo reserved_match = {
5357 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5360 const struct reserved_combo *r;
5364 r = match_reserved_word(word);
5368 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5369 # if ENABLE_HUSH_CASE
5370 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5371 /* "case word IN ..." - IN part starts first MATCH part */
5372 r = &reserved_match;
5375 if (r->flag == 0) { /* '!' */
5376 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5377 syntax_error("! ! command");
5378 ctx->ctx_res_w = RES_SNTX;
5380 ctx->ctx_inverted = 1;
5383 if (r->flag & FLAG_START) {
5384 struct parse_context *old;
5386 old = xmalloc(sizeof(*old));
5387 debug_printf_parse("push stack %p\n", old);
5388 *old = *ctx; /* physical copy */
5389 initialize_context(ctx);
5391 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5392 syntax_error_at(word->data);
5393 ctx->ctx_res_w = RES_SNTX;
5396 /* "{...} fi" is ok. "{...} if" is not
5398 * if { echo foo; } then { echo bar; } fi */
5399 if (ctx->command->group)
5400 done_pipe(ctx, PIPE_SEQ);
5403 ctx->ctx_res_w = r->res;
5404 ctx->old_flag = r->flag;
5405 word->o_assignment = r->assignment_flag;
5407 if (ctx->old_flag & FLAG_END) {
5408 struct parse_context *old;
5410 done_pipe(ctx, PIPE_SEQ);
5411 debug_printf_parse("pop stack %p\n", ctx->stack);
5413 old->command->group = ctx->list_head;
5414 old->command->cmd_type = CMD_NORMAL;
5416 o_addstr(&old->as_string, ctx->as_string.data);
5417 o_free_unsafe(&ctx->as_string);
5418 old->command->group_as_string = xstrdup(old->as_string.data);
5419 debug_printf_parse("pop, remembering as:'%s'\n",
5420 old->command->group_as_string);
5422 *ctx = *old; /* physical copy */
5427 #endif /* HAS_KEYWORDS */
5429 /* Word is complete, look at it and update parsing context.
5430 * Normal return is 0. Syntax errors return 1.
5431 * Note: on return, word is reset, but not o_free'd!
5433 static int done_word(o_string *word, struct parse_context *ctx)
5435 struct command *command = ctx->command;
5437 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5438 if (word->length == 0 && word->o_quoted == 0) {
5439 debug_printf_parse("done_word return 0: true null, ignored\n");
5443 if (ctx->pending_redirect) {
5444 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5445 * only if run as "bash", not "sh" */
5446 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5448 * ...the word that follows the redirection operator
5449 * shall be subjected to tilde expansion, parameter expansion,
5450 * command substitution, arithmetic expansion, and quote
5451 * removal. Pathname expansion shall not be performed
5452 * on the word by a non-interactive shell; an interactive
5453 * shell may perform it, but shall do so only when
5454 * the expansion would result in one word."
5456 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5457 /* Cater for >\file case:
5458 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5459 * Same with heredocs:
5460 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5462 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5463 unbackslash(ctx->pending_redirect->rd_filename);
5464 /* Is it <<"HEREDOC"? */
5465 if (word->o_quoted) {
5466 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5469 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5470 ctx->pending_redirect = NULL;
5472 /* If this word wasn't an assignment, next ones definitely
5473 * can't be assignments. Even if they look like ones. */
5474 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5475 && word->o_assignment != WORD_IS_KEYWORD
5477 word->o_assignment = NOT_ASSIGNMENT;
5479 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5480 command->assignment_cnt++;
5481 word->o_assignment = MAYBE_ASSIGNMENT;
5485 # if ENABLE_HUSH_CASE
5486 if (ctx->ctx_dsemicolon
5487 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5489 /* already done when ctx_dsemicolon was set to 1: */
5490 /* ctx->ctx_res_w = RES_MATCH; */
5491 ctx->ctx_dsemicolon = 0;
5494 if (!command->argv /* if it's the first word... */
5495 # if ENABLE_HUSH_LOOPS
5496 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5497 && ctx->ctx_res_w != RES_IN
5499 # if ENABLE_HUSH_CASE
5500 && ctx->ctx_res_w != RES_CASE
5503 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5504 if (reserved_word(word, ctx)) {
5505 o_reset_to_empty_unquoted(word);
5506 debug_printf_parse("done_word return %d\n",
5507 (ctx->ctx_res_w == RES_SNTX));
5508 return (ctx->ctx_res_w == RES_SNTX);
5510 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5511 if (strcmp(word->data, "export") == 0
5512 # if ENABLE_HUSH_LOCAL
5513 || strcmp(word->data, "local") == 0
5516 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5519 # if ENABLE_HUSH_BASH_COMPAT
5520 if (strcmp(word->data, "[[") == 0) {
5521 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5527 if (command->group) {
5528 /* "{ echo foo; } echo bar" - bad */
5529 syntax_error_at(word->data);
5530 debug_printf_parse("done_word return 1: syntax error, "
5531 "groups and arglists don't mix\n");
5534 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5535 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5536 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5537 /* (otherwise it's known to be not empty and is already safe) */
5539 /* exclude "$@" - it can expand to no word despite "" */
5540 char *p = word->data;
5541 while (p[0] == SPECIAL_VAR_SYMBOL
5542 && (p[1] & 0x7f) == '@'
5543 && p[2] == SPECIAL_VAR_SYMBOL
5547 if (p == word->data || p[0] != '\0') {
5548 /* saw no "$@", or not only "$@" but some
5549 * real text is there too */
5550 /* insert "empty variable" reference, this makes
5551 * e.g. "", $empty"" etc to not disappear */
5552 o_addchr(word, SPECIAL_VAR_SYMBOL);
5553 o_addchr(word, SPECIAL_VAR_SYMBOL);
5556 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5557 debug_print_strings("word appended to argv", command->argv);
5560 #if ENABLE_HUSH_LOOPS
5561 if (ctx->ctx_res_w == RES_FOR) {
5563 || !is_well_formed_var_name(command->argv[0], '\0')
5565 /* bash says just "not a valid identifier" */
5566 syntax_error("not a valid identifier in for");
5569 /* Force FOR to have just one word (variable name) */
5570 /* NB: basically, this makes hush see "for v in ..."
5571 * syntax as if it is "for v; in ...". FOR and IN become
5572 * two pipe structs in parse tree. */
5573 done_pipe(ctx, PIPE_SEQ);
5576 #if ENABLE_HUSH_CASE
5577 /* Force CASE to have just one word */
5578 if (ctx->ctx_res_w == RES_CASE) {
5579 done_pipe(ctx, PIPE_SEQ);
5583 o_reset_to_empty_unquoted(word);
5585 debug_printf_parse("done_word return 0\n");
5590 /* Peek ahead in the input to find out if we have a "&n" construct,
5591 * as in "2>&1", that represents duplicating a file descriptor.
5593 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5594 * REDIRFD_SYNTAX_ERR if syntax error,
5595 * REDIRFD_TO_FILE if no & was seen,
5596 * or the number found.
5599 #define parse_redir_right_fd(as_string, input) \
5600 parse_redir_right_fd(input)
5602 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5608 return REDIRFD_TO_FILE;
5610 ch = i_getch(input); /* get the & */
5611 nommu_addchr(as_string, ch);
5614 ch = i_getch(input);
5615 nommu_addchr(as_string, ch);
5616 return REDIRFD_CLOSE;
5620 while (ch != EOF && isdigit(ch)) {
5621 d = d*10 + (ch-'0');
5623 ch = i_getch(input);
5624 nommu_addchr(as_string, ch);
5629 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5631 bb_error_msg("ambiguous redirect");
5632 return REDIRFD_SYNTAX_ERR;
5635 /* Return code is 0 normal, 1 if a syntax error is detected
5637 static int parse_redirect(struct parse_context *ctx,
5640 struct in_str *input)
5642 struct command *command = ctx->command;
5643 struct redir_struct *redir;
5644 struct redir_struct **redirp;
5647 dup_num = REDIRFD_TO_FILE;
5648 if (style != REDIRECT_HEREDOC) {
5649 /* Check for a '>&1' type redirect */
5650 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5651 if (dup_num == REDIRFD_SYNTAX_ERR)
5654 int ch = i_peek(input);
5655 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5656 if (dup_num) { /* <<-... */
5657 ch = i_getch(input);
5658 nommu_addchr(&ctx->as_string, ch);
5663 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5664 int ch = i_peek(input);
5666 /* >|FILE redirect ("clobbering" >).
5667 * Since we do not support "set -o noclobber" yet,
5668 * >| and > are the same for now. Just eat |.
5670 ch = i_getch(input);
5671 nommu_addchr(&ctx->as_string, ch);
5675 /* Create a new redir_struct and append it to the linked list */
5676 redirp = &command->redirects;
5677 while ((redir = *redirp) != NULL) {
5678 redirp = &(redir->next);
5680 *redirp = redir = xzalloc(sizeof(*redir));
5681 /* redir->next = NULL; */
5682 /* redir->rd_filename = NULL; */
5683 redir->rd_type = style;
5684 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5686 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5687 redir_table[style].descrip);
5689 redir->rd_dup = dup_num;
5690 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5691 /* Erik had a check here that the file descriptor in question
5692 * is legit; I postpone that to "run time"
5693 * A "-" representation of "close me" shows up as a -3 here */
5694 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5695 redir->rd_fd, redir->rd_dup);
5697 /* Set ctx->pending_redirect, so we know what to do at the
5698 * end of the next parsed word. */
5699 ctx->pending_redirect = redir;
5704 /* If a redirect is immediately preceded by a number, that number is
5705 * supposed to tell which file descriptor to redirect. This routine
5706 * looks for such preceding numbers. In an ideal world this routine
5707 * needs to handle all the following classes of redirects...
5708 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5709 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5710 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5711 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5713 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5715 * ... If n is quoted, the number shall not be recognized as part of
5716 * the redirection expression. For example:
5718 * writes the character 2 into file a"
5719 * We are getting it right by setting ->o_quoted on any \<char>
5721 * A -1 return means no valid number was found,
5722 * the caller should use the appropriate default for this redirection.
5724 static int redirect_opt_num(o_string *o)
5728 if (o->data == NULL)
5730 num = bb_strtou(o->data, NULL, 10);
5731 if (errno || num < 0)
5733 o_reset_to_empty_unquoted(o);
5738 #define fetch_till_str(as_string, input, word, skip_tabs) \
5739 fetch_till_str(input, word, skip_tabs)
5741 static char *fetch_till_str(o_string *as_string,
5742 struct in_str *input,
5746 o_string heredoc = NULL_O_STRING;
5752 ch = i_getch(input);
5753 nommu_addchr(as_string, ch);
5755 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5756 heredoc.data[past_EOL] = '\0';
5757 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5758 return heredoc.data;
5761 o_addchr(&heredoc, ch);
5762 past_EOL = heredoc.length;
5765 ch = i_getch(input);
5766 nommu_addchr(as_string, ch);
5767 } while (skip_tabs && ch == '\t');
5768 } while (ch == '\n');
5771 o_free_unsafe(&heredoc);
5774 o_addchr(&heredoc, ch);
5775 nommu_addchr(as_string, ch);
5779 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5780 * and load them all. There should be exactly heredoc_cnt of them.
5782 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5784 struct pipe *pi = ctx->list_head;
5786 while (pi && heredoc_cnt) {
5788 struct command *cmd = pi->cmds;
5790 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5792 cmd->argv ? cmd->argv[0] : "NONE");
5793 for (i = 0; i < pi->num_cmds; i++) {
5794 struct redir_struct *redir = cmd->redirects;
5796 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5797 i, cmd->argv ? cmd->argv[0] : "NONE");
5799 if (redir->rd_type == REDIRECT_HEREDOC) {
5802 redir->rd_type = REDIRECT_HEREDOC2;
5803 /* redir->rd_dup is (ab)used to indicate <<- */
5804 p = fetch_till_str(&ctx->as_string, input,
5805 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5807 syntax_error("unexpected EOF in here document");
5810 free(redir->rd_filename);
5811 redir->rd_filename = p;
5814 redir = redir->next;
5821 /* Should be 0. If it isn't, it's a parse error */
5823 bb_error_msg_and_die("heredoc BUG 2");
5829 #if ENABLE_HUSH_TICK
5830 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5835 char **to_free = NULL;
5839 pid = BB_MMU ? xfork() : xvfork();
5840 if (pid == 0) { /* child */
5841 disable_restore_tty_pgrp_on_exit();
5842 /* Process substitution is not considered to be usual
5843 * 'command execution'.
5844 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5851 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5852 close(channel[0]); /* NB: close _first_, then move fd! */
5853 xmove_fd(channel[1], 1);
5854 /* Prevent it from trying to handle ctrl-z etc */
5855 IF_HUSH_JOB(G.run_list_level = 1;)
5856 /* Awful hack for `trap` or $(trap).
5858 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5859 * contains an example where "trap" is executed in a subshell:
5861 * save_traps=$(trap)
5863 * eval "$save_traps"
5865 * Standard does not say that "trap" in subshell shall print
5866 * parent shell's traps. It only says that its output
5867 * must have suitable form, but then, in the above example
5868 * (which is not supposed to be normative), it implies that.
5870 * bash (and probably other shell) does implement it
5871 * (traps are reset to defaults, but "trap" still shows them),
5872 * but as a result, "trap" logic is hopelessly messed up:
5875 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5876 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5877 * # true | trap <--- trap is in subshell - no output (ditto)
5878 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5879 * trap -- 'echo Ho' SIGWINCH
5880 * # echo `(trap)` <--- in subshell in subshell - output
5881 * trap -- 'echo Ho' SIGWINCH
5882 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5883 * trap -- 'echo Ho' SIGWINCH
5885 * The rules when to forget and when to not forget traps
5886 * get really complex and nonsensical.
5888 * Our solution: ONLY bare $(trap) or `trap` is special.
5890 s = skip_whitespace(s);
5891 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5893 static const char *const argv[] = { NULL, NULL };
5894 builtin_trap((char**)argv);
5895 exit(0); /* not _exit() - we need to fflush */
5898 reset_traps_to_defaults();
5899 parse_and_run_string(s);
5900 _exit(G.last_exitcode);
5902 /* We re-execute after vfork on NOMMU. This makes this script safe:
5903 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5904 * huge=`cat BIG` # was blocking here forever
5907 re_execute_shell(&to_free,
5917 # if ENABLE_HUSH_FAST
5919 //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);
5921 enable_restore_tty_pgrp_on_exit();
5926 close_on_exec_on(channel[0]);
5927 return xfdopen_for_read(channel[0]);
5930 /* Return code is exit status of the process that is run. */
5931 static int process_command_subs(o_string *dest, const char *s)
5934 struct in_str pipe_str;
5936 int status, ch, eol_cnt;
5938 fp = generate_stream_from_string(s, &pid);
5940 /* Now send results of command back into original context */
5941 setup_file_in_str(&pipe_str, fp);
5943 while ((ch = i_getch(&pipe_str)) != EOF) {
5949 o_addchr(dest, '\n');
5952 o_addQchr(dest, ch);
5955 debug_printf("done reading from `cmd` pipe, closing it\n");
5957 /* We need to extract exitcode. Test case
5958 * "true; echo `sleep 1; false` $?"
5960 safe_waitpid(pid, &status, 0);
5961 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5962 return WEXITSTATUS(status);
5964 #endif /* ENABLE_HUSH_TICK */
5966 #if !ENABLE_HUSH_FUNCTIONS
5967 #define parse_group(dest, ctx, input, ch) \
5968 parse_group(ctx, input, ch)
5970 static int parse_group(o_string *dest, struct parse_context *ctx,
5971 struct in_str *input, int ch)
5973 /* dest contains characters seen prior to ( or {.
5974 * Typically it's empty, but for function defs,
5975 * it contains function name (without '()'). */
5976 struct pipe *pipe_list;
5978 struct command *command = ctx->command;
5980 debug_printf_parse("parse_group entered\n");
5981 #if ENABLE_HUSH_FUNCTIONS
5982 if (ch == '(' && !dest->o_quoted) {
5984 if (done_word(dest, ctx))
5987 goto skip; /* (... */
5988 if (command->argv[1]) { /* word word ... (... */
5989 syntax_error_unexpected_ch('(');
5992 /* it is "word(..." or "word (..." */
5994 ch = i_getch(input);
5995 while (ch == ' ' || ch == '\t');
5997 syntax_error_unexpected_ch(ch);
6000 nommu_addchr(&ctx->as_string, ch);
6002 ch = i_getch(input);
6003 while (ch == ' ' || ch == '\t' || ch == '\n');
6005 syntax_error_unexpected_ch(ch);
6008 nommu_addchr(&ctx->as_string, ch);
6009 command->cmd_type = CMD_FUNCDEF;
6014 #if 0 /* Prevented by caller */
6015 if (command->argv /* word [word]{... */
6016 || dest->length /* word{... */
6017 || dest->o_quoted /* ""{... */
6020 debug_printf_parse("parse_group return 1: "
6021 "syntax error, groups and arglists don't mix\n");
6026 #if ENABLE_HUSH_FUNCTIONS
6032 command->cmd_type = CMD_SUBSHELL;
6034 /* bash does not allow "{echo...", requires whitespace */
6035 ch = i_getch(input);
6036 if (ch != ' ' && ch != '\t' && ch != '\n') {
6037 syntax_error_unexpected_ch(ch);
6040 nommu_addchr(&ctx->as_string, ch);
6045 # define as_string NULL
6047 char *as_string = NULL;
6049 pipe_list = parse_stream(&as_string, input, endch);
6052 o_addstr(&ctx->as_string, as_string);
6054 /* empty ()/{} or parse error? */
6055 if (!pipe_list || pipe_list == ERR_PTR) {
6056 /* parse_stream already emitted error msg */
6059 debug_printf_parse("parse_group return 1: "
6060 "parse_stream returned %p\n", pipe_list);
6063 command->group = pipe_list;
6065 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6066 command->group_as_string = as_string;
6067 debug_printf_parse("end of group, remembering as:'%s'\n",
6068 command->group_as_string);
6072 debug_printf_parse("parse_group return 0\n");
6074 /* command remains "open", available for possible redirects */
6077 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6078 /* Subroutines for copying $(...) and `...` things */
6079 static void add_till_backquote(o_string *dest, struct in_str *input);
6081 static void add_till_single_quote(o_string *dest, struct in_str *input)
6084 int ch = i_getch(input);
6086 syntax_error_unterm_ch('\'');
6087 /*xfunc_die(); - redundant */
6094 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6095 static void add_till_double_quote(o_string *dest, struct in_str *input)
6098 int ch = i_getch(input);
6100 syntax_error_unterm_ch('"');
6101 /*xfunc_die(); - redundant */
6105 if (ch == '\\') { /* \x. Copy both chars. */
6107 ch = i_getch(input);
6111 add_till_backquote(dest, input);
6115 //if (ch == '$') ...
6118 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6120 * "Within the backquoted style of command substitution, backslash
6121 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6122 * The search for the matching backquote shall be satisfied by the first
6123 * backquote found without a preceding backslash; during this search,
6124 * if a non-escaped backquote is encountered within a shell comment,
6125 * a here-document, an embedded command substitution of the $(command)
6126 * form, or a quoted string, undefined results occur. A single-quoted
6127 * or double-quoted string that begins, but does not end, within the
6128 * "`...`" sequence produces undefined results."
6130 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6132 static void add_till_backquote(o_string *dest, struct in_str *input)
6135 int ch = i_getch(input);
6137 syntax_error_unterm_ch('`');
6138 /*xfunc_die(); - redundant */
6143 /* \x. Copy both chars unless it is \` */
6144 int ch2 = i_getch(input);
6146 syntax_error_unterm_ch('`');
6147 /*xfunc_die(); - redundant */
6149 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6156 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6157 * quoting and nested ()s.
6158 * "With the $(command) style of command substitution, all characters
6159 * following the open parenthesis to the matching closing parenthesis
6160 * constitute the command. Any valid shell script can be used for command,
6161 * except a script consisting solely of redirections which produces
6162 * unspecified results."
6164 * echo $(echo '(TEST)' BEST) (TEST) BEST
6165 * echo $(echo 'TEST)' BEST) TEST) BEST
6166 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6168 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6169 * can contain arbitrary constructs, just like $(cmd).
6170 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6171 * for ${var:N[:M]} parsing.
6173 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6174 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6177 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6178 # if ENABLE_HUSH_BASH_COMPAT
6179 char end_char2 = end_ch >> 8;
6181 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6184 ch = i_getch(input);
6186 syntax_error_unterm_ch(end_ch);
6187 /*xfunc_die(); - redundant */
6189 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6192 /* we look for closing )) of $((EXPR)) */
6193 if (i_peek(input) == end_ch) {
6194 i_getch(input); /* eat second ')' */
6199 if (ch == '(' || ch == '{') {
6200 ch = (ch == '(' ? ')' : '}');
6201 add_till_closing_bracket(dest, input, ch);
6206 add_till_single_quote(dest, input);
6211 add_till_double_quote(dest, input);
6216 add_till_backquote(dest, input);
6221 /* \x. Copy verbatim. Important for \(, \) */
6222 ch = i_getch(input);
6224 syntax_error_unterm_ch(')');
6225 /*xfunc_die(); - redundant */
6233 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6235 /* Return code: 0 for OK, 1 for syntax error */
6237 #define parse_dollar(as_string, dest, input) \
6238 parse_dollar(dest, input)
6239 #define as_string NULL
6241 static int parse_dollar(o_string *as_string,
6243 struct in_str *input)
6245 int ch = i_peek(input); /* first character after the $ */
6246 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6248 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6250 ch = i_getch(input);
6251 nommu_addchr(as_string, ch);
6253 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6255 debug_printf_parse(": '%c'\n", ch);
6256 o_addchr(dest, ch | quote_mask);
6259 if (!isalnum(ch) && ch != '_')
6261 ch = i_getch(input);
6262 nommu_addchr(as_string, ch);
6264 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6265 } else if (isdigit(ch)) {
6267 ch = i_getch(input);
6268 nommu_addchr(as_string, ch);
6269 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6270 debug_printf_parse(": '%c'\n", ch);
6271 o_addchr(dest, ch | quote_mask);
6272 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6273 } else switch (ch) {
6275 case '!': /* last bg pid */
6276 case '?': /* last exit code */
6277 case '#': /* number of args */
6278 case '*': /* args */
6279 case '@': /* args */
6280 goto make_one_char_var;
6282 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6284 ch = i_getch(input); /* eat '{' */
6285 nommu_addchr(as_string, ch);
6287 ch = i_getch(input); /* first char after '{' */
6288 nommu_addchr(as_string, ch);
6289 /* It should be ${?}, or ${#var},
6290 * or even ${?+subst} - operator acting on a special variable,
6291 * or the beginning of variable name.
6293 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6295 syntax_error_unterm_str("${name}");
6296 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6301 /* It's possible to just call add_till_closing_bracket() at this point.
6302 * However, this regresses some of our testsuite cases
6303 * which check invalid constructs like ${%}.
6304 * Oh well... let's check that the var name part is fine... */
6310 debug_printf_parse(": '%c'\n", ch);
6312 ch = i_getch(input);
6313 nommu_addchr(as_string, ch);
6317 if (!isalnum(ch) && ch != '_') {
6319 unsigned char last_ch;
6320 /* handle parameter expansions
6321 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6323 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6324 goto bad_dollar_syntax;
6327 /* Eat everything until closing '}' (or ':') */
6329 if (ENABLE_HUSH_BASH_COMPAT
6331 && !strchr("%#:-=+?"+3, i_peek(input))
6333 /* It's ${var:N[:M]} thing */
6334 end_ch = '}' * 0x100 + ':';
6339 #if ENABLE_HUSH_DOLLAR_OPS
6340 last_ch = add_till_closing_bracket(dest, input, end_ch);
6342 #error Simple code to only allow ${var} is not implemented
6345 o_addstr(as_string, dest->data + pos);
6346 o_addchr(as_string, last_ch);
6349 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6350 /* close the first block: */
6351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6352 /* while parsing N from ${var:N[:M]}... */
6353 if ((end_ch & 0xff) == last_ch) {
6354 /* ...got ':' - parse the rest */
6358 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6359 o_addstr(dest, "999999999");
6364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6367 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6371 ch = i_getch(input);
6372 nommu_addchr(as_string, ch);
6373 # if ENABLE_SH_MATH_SUPPORT
6374 if (i_peek(input) == '(') {
6375 ch = i_getch(input);
6376 nommu_addchr(as_string, ch);
6377 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6378 o_addchr(dest, /*quote_mask |*/ '+');
6381 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6383 o_addstr(as_string, dest->data + pos);
6384 o_addchr(as_string, ')');
6385 o_addchr(as_string, ')');
6387 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6391 # if ENABLE_HUSH_TICK
6392 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6393 o_addchr(dest, quote_mask | '`');
6396 add_till_closing_bracket(dest, input, ')');
6398 o_addstr(as_string, dest->data + pos);
6399 o_addchr(as_string, ')');
6401 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6407 ch = i_getch(input);
6408 nommu_addchr(as_string, ch);
6410 if (isalnum(ch)) { /* it's $_name or $_123 */
6415 /* TODO: $_ and $-: */
6416 /* $_ Shell or shell script name; or last argument of last command
6417 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6418 * but in command's env, set to full pathname used to invoke it */
6419 /* $- Option flags set by set builtin or shell options (-i etc) */
6421 o_addQchr(dest, '$');
6423 debug_printf_parse("parse_dollar return 0\n");
6429 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6430 parse_stream_dquoted(dest, input, dquote_end)
6431 #define as_string NULL
6433 static int parse_stream_dquoted(o_string *as_string,
6435 struct in_str *input,
6442 ch = i_getch(input);
6444 nommu_addchr(as_string, ch);
6445 if (ch == dquote_end) { /* may be only '"' or EOF */
6446 if (dest->o_assignment == NOT_ASSIGNMENT)
6447 dest->o_escape ^= 1;
6448 debug_printf_parse("parse_stream_dquoted return 0\n");
6451 /* note: can't move it above ch == dquote_end check! */
6453 syntax_error_unterm_ch('"');
6454 /*xfunc_die(); - redundant */
6458 next = i_peek(input);
6460 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6461 ch, ch, dest->o_escape);
6464 syntax_error("\\<eof>");
6468 * "The backslash retains its special meaning [in "..."]
6469 * only when followed by one of the following characters:
6470 * $, `, ", \, or <newline>. A double quote may be quoted
6471 * within double quotes by preceding it with a backslash."
6473 if (strchr("$`\"\\\n", next) != NULL) {
6474 ch = i_getch(input);
6476 o_addqchr(dest, ch);
6477 nommu_addchr(as_string, ch);
6480 o_addqchr(dest, '\\');
6481 nommu_addchr(as_string, '\\');
6486 if (parse_dollar(as_string, dest, input) != 0) {
6487 debug_printf_parse("parse_stream_dquoted return 1: "
6488 "parse_dollar returned non-0\n");
6493 #if ENABLE_HUSH_TICK
6495 //unsigned pos = dest->length;
6496 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6497 o_addchr(dest, 0x80 | '`');
6498 add_till_backquote(dest, input);
6499 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6500 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6504 o_addQchr(dest, ch);
6506 && (dest->o_assignment == MAYBE_ASSIGNMENT
6507 || dest->o_assignment == WORD_IS_KEYWORD)
6508 && is_well_formed_var_name(dest->data, '=')
6510 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6517 * Scan input until EOF or end_trigger char.
6518 * Return a list of pipes to execute, or NULL on EOF
6519 * or if end_trigger character is met.
6520 * On syntax error, exit is shell is not interactive,
6521 * reset parsing machinery and start parsing anew,
6522 * or return ERR_PTR.
6524 static struct pipe *parse_stream(char **pstring,
6525 struct in_str *input,
6528 struct parse_context ctx;
6529 o_string dest = NULL_O_STRING;
6533 /* Double-quote state is handled in the state variable is_in_dquote.
6534 * A single-quote triggers a bypass of the main loop until its mate is
6535 * found. When recursing, quote state is passed in via dest->o_escape.
6537 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6538 end_trigger ? end_trigger : 'X');
6541 /* If very first arg is "" or '', dest.data may end up NULL.
6542 * Preventing this: */
6543 o_addchr(&dest, '\0');
6546 G.ifs = get_local_var_value("IFS");
6551 #if ENABLE_HUSH_INTERACTIVE
6552 input->promptmode = 0; /* PS1 */
6554 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6555 initialize_context(&ctx);
6560 const char *is_special;
6564 redir_type redir_style;
6567 /* dest.o_quoted = 1; - already is (see below) */
6568 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6571 /* We reached closing '"' */
6574 ch = i_getch(input);
6575 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6576 ch, ch, dest.o_escape);
6581 syntax_error_unterm_str("here document");
6584 /* end_trigger == '}' case errors out earlier,
6585 * checking only ')' */
6586 if (end_trigger == ')') {
6587 syntax_error_unterm_ch('('); /* exits */
6588 /* goto parse_error; */
6591 if (done_word(&dest, &ctx)) {
6595 done_pipe(&ctx, PIPE_SEQ);
6597 /* If we got nothing... */
6598 /* (this makes bare "&" cmd a no-op.
6599 * bash says: "syntax error near unexpected token '&'") */
6600 if (pi->num_cmds == 0
6601 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6607 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6609 *pstring = ctx.as_string.data;
6611 o_free_unsafe(&ctx.as_string);
6614 debug_printf_parse("parse_stream return %p\n", pi);
6617 nommu_addchr(&ctx.as_string, ch);
6621 next = i_peek(input);
6623 is_special = "{}<>;&|()#'" /* special outside of "str" */
6624 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6625 /* Are { and } special here? */
6626 if (ctx.command->argv /* word [word]{... - non-special */
6627 || dest.length /* word{... - non-special */
6628 || dest.o_quoted /* ""{... - non-special */
6629 || (next != ';' /* }; - special */
6630 && next != ')' /* }) - special */
6631 && next != '&' /* }& and }&& ... - special */
6632 && next != '|' /* }|| ... - special */
6633 && !strchr(G.ifs, next) /* {word - non-special */
6636 /* They are not special, skip "{}" */
6639 is_special = strchr(is_special, ch);
6640 is_ifs = strchr(G.ifs, ch);
6642 if (!is_special && !is_ifs) { /* ordinary char */
6644 o_addQchr(&dest, ch);
6645 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6646 || dest.o_assignment == WORD_IS_KEYWORD)
6648 && is_well_formed_var_name(dest.data, '=')
6650 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6656 if (done_word(&dest, &ctx)) {
6660 #if ENABLE_HUSH_CASE
6661 /* "case ... in <newline> word) ..." -
6662 * newlines are ignored (but ';' wouldn't be) */
6663 if (ctx.command->argv == NULL
6664 && ctx.ctx_res_w == RES_MATCH
6669 /* Treat newline as a command separator. */
6670 done_pipe(&ctx, PIPE_SEQ);
6671 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6673 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6678 dest.o_assignment = MAYBE_ASSIGNMENT;
6680 /* note: if (is_ifs) continue;
6681 * will still trigger for us */
6685 /* "cmd}" or "cmd }..." without semicolon or &:
6686 * } is an ordinary char in this case, even inside { cmd; }
6687 * Pathological example: { ""}; } should exec "}" cmd
6690 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6691 || dest.length != 0 /* word} */
6692 || dest.o_quoted /* ""} */
6696 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6697 goto skip_end_trigger;
6698 /* else: } does terminate a group */
6701 if (end_trigger && end_trigger == ch
6702 && (ch != ';' || heredoc_cnt == 0)
6703 #if ENABLE_HUSH_CASE
6705 || ctx.ctx_res_w != RES_MATCH
6706 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6711 /* This is technically valid:
6712 * { cat <<HERE; }; echo Ok
6716 * but we don't support this.
6717 * We require heredoc to be in enclosing {}/(),
6720 syntax_error_unterm_str("here document");
6723 if (done_word(&dest, &ctx)) {
6726 done_pipe(&ctx, PIPE_SEQ);
6727 dest.o_assignment = MAYBE_ASSIGNMENT;
6728 /* Do we sit outside of any if's, loops or case's? */
6730 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6734 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6736 *pstring = ctx.as_string.data;
6738 o_free_unsafe(&ctx.as_string);
6741 debug_printf_parse("parse_stream return %p: "
6742 "end_trigger char found\n",
6744 return ctx.list_head;
6751 /* Catch <, > before deciding whether this word is
6752 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6755 redir_fd = redirect_opt_num(&dest);
6756 if (done_word(&dest, &ctx)) {
6759 redir_style = REDIRECT_OVERWRITE;
6761 redir_style = REDIRECT_APPEND;
6762 ch = i_getch(input);
6763 nommu_addchr(&ctx.as_string, ch);
6766 else if (next == '(') {
6767 syntax_error(">(process) not supported");
6771 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6773 continue; /* back to top of while (1) */
6775 redir_fd = redirect_opt_num(&dest);
6776 if (done_word(&dest, &ctx)) {
6779 redir_style = REDIRECT_INPUT;
6781 redir_style = REDIRECT_HEREDOC;
6783 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6784 ch = i_getch(input);
6785 nommu_addchr(&ctx.as_string, ch);
6786 } else if (next == '>') {
6787 redir_style = REDIRECT_IO;
6788 ch = i_getch(input);
6789 nommu_addchr(&ctx.as_string, ch);
6792 else if (next == '(') {
6793 syntax_error("<(process) not supported");
6797 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6799 continue; /* back to top of while (1) */
6802 if (dest.o_assignment == MAYBE_ASSIGNMENT
6803 /* check that we are not in word in "a=1 2>word b=1": */
6804 && !ctx.pending_redirect
6806 /* ch is a special char and thus this word
6807 * cannot be an assignment */
6808 dest.o_assignment = NOT_ASSIGNMENT;
6811 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6815 if (dest.length == 0) {
6818 if (ch == EOF || ch == '\n')
6821 /* note: we do not add it to &ctx.as_string */
6823 nommu_addchr(&ctx.as_string, '\n');
6825 o_addQchr(&dest, ch);
6830 syntax_error("\\<eof>");
6833 ch = i_getch(input);
6835 o_addchr(&dest, '\\');
6836 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6837 o_addchr(&dest, ch);
6838 nommu_addchr(&ctx.as_string, ch);
6839 /* Example: echo Hello \2>file
6840 * we need to know that word 2 is quoted */
6845 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6846 ctx.as_string.data[--ctx.as_string.length] = '\0';
6851 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6852 debug_printf_parse("parse_stream parse error: "
6853 "parse_dollar returned non-0\n");
6860 ch = i_getch(input);
6862 syntax_error_unterm_ch('\'');
6863 /*xfunc_die(); - redundant */
6865 nommu_addchr(&ctx.as_string, ch);
6868 o_addqchr(&dest, ch);
6873 is_in_dquote ^= 1; /* invert */
6874 if (dest.o_assignment == NOT_ASSIGNMENT)
6877 #if ENABLE_HUSH_TICK
6881 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6882 o_addchr(&dest, '`');
6884 add_till_backquote(&dest, input);
6886 o_addstr(&ctx.as_string, dest.data + pos);
6887 o_addchr(&ctx.as_string, '`');
6889 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6890 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6895 #if ENABLE_HUSH_CASE
6898 if (done_word(&dest, &ctx)) {
6901 done_pipe(&ctx, PIPE_SEQ);
6902 #if ENABLE_HUSH_CASE
6903 /* Eat multiple semicolons, detect
6904 * whether it means something special */
6909 ch = i_getch(input);
6910 nommu_addchr(&ctx.as_string, ch);
6911 if (ctx.ctx_res_w == RES_CASE_BODY) {
6912 ctx.ctx_dsemicolon = 1;
6913 ctx.ctx_res_w = RES_MATCH;
6919 /* We just finished a cmd. New one may start
6920 * with an assignment */
6921 dest.o_assignment = MAYBE_ASSIGNMENT;
6924 if (done_word(&dest, &ctx)) {
6928 ch = i_getch(input);
6929 nommu_addchr(&ctx.as_string, ch);
6930 done_pipe(&ctx, PIPE_AND);
6932 done_pipe(&ctx, PIPE_BG);
6936 if (done_word(&dest, &ctx)) {
6939 #if ENABLE_HUSH_CASE
6940 if (ctx.ctx_res_w == RES_MATCH)
6941 break; /* we are in case's "word | word)" */
6943 if (next == '|') { /* || */
6944 ch = i_getch(input);
6945 nommu_addchr(&ctx.as_string, ch);
6946 done_pipe(&ctx, PIPE_OR);
6948 /* we could pick up a file descriptor choice here
6949 * with redirect_opt_num(), but bash doesn't do it.
6950 * "echo foo 2| cat" yields "foo 2". */
6953 o_reset_to_empty_unquoted(&ctx.as_string);
6958 #if ENABLE_HUSH_CASE
6959 /* "case... in [(]word)..." - skip '(' */
6960 if (ctx.ctx_res_w == RES_MATCH
6961 && ctx.command->argv == NULL /* not (word|(... */
6962 && dest.length == 0 /* not word(... */
6963 && dest.o_quoted == 0 /* not ""(... */
6969 if (parse_group(&dest, &ctx, input, ch) != 0) {
6974 #if ENABLE_HUSH_CASE
6975 if (ctx.ctx_res_w == RES_MATCH)
6979 /* proper use of this character is caught by end_trigger:
6980 * if we see {, we call parse_group(..., end_trigger='}')
6981 * and it will match } earlier (not here). */
6982 syntax_error_unexpected_ch(ch);
6986 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6992 struct parse_context *pctx;
6993 IF_HAS_KEYWORDS(struct parse_context *p2;)
6995 /* Clean up allocated tree.
6996 * Sample for finding leaks on syntax error recovery path.
6997 * Run it from interactive shell, watch pmap `pidof hush`.
6998 * while if false; then false; fi; do break; fi
6999 * Samples to catch leaks at execution:
7000 * while if (true | {true;}); then echo ok; fi; do break; done
7001 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
7005 /* Update pipe/command counts,
7006 * otherwise freeing may miss some */
7007 done_pipe(pctx, PIPE_SEQ);
7008 debug_printf_clean("freeing list %p from ctx %p\n",
7009 pctx->list_head, pctx);
7010 debug_print_tree(pctx->list_head, 0);
7011 free_pipe_list(pctx->list_head);
7012 debug_printf_clean("freed list %p\n", pctx->list_head);
7014 o_free_unsafe(&pctx->as_string);
7016 IF_HAS_KEYWORDS(p2 = pctx->stack;)
7020 IF_HAS_KEYWORDS(pctx = p2;)
7021 } while (HAS_KEYWORDS && pctx);
7022 /* Free text, clear all dest fields */
7024 /* If we are not in top-level parse, we return,
7025 * our caller will propagate error.
7027 if (end_trigger != ';') {
7035 /* Discard cached input, force prompt */
7037 IF_HUSH_INTERACTIVE(input->promptme = 1;)
7042 /* Executing from string: eval, sh -c '...'
7043 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7044 * end_trigger controls how often we stop parsing
7045 * NUL: parse all, execute, return
7046 * ';': parse till ';' or newline, execute, repeat till EOF
7048 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7050 /* Why we need empty flag?
7051 * An obscure corner case "false; ``; echo $?":
7052 * empty command in `` should still set $? to 0.
7053 * But we can't just set $? to 0 at the start,
7054 * this breaks "false; echo `echo $?`" case.
7058 struct pipe *pipe_list;
7060 pipe_list = parse_stream(NULL, inp, end_trigger);
7061 if (!pipe_list) { /* EOF */
7063 G.last_exitcode = 0;
7066 debug_print_tree(pipe_list, 0);
7067 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7068 run_and_free_list(pipe_list);
7073 static void parse_and_run_string(const char *s)
7075 struct in_str input;
7076 setup_string_in_str(&input, s);
7077 parse_and_run_stream(&input, '\0');
7080 static void parse_and_run_file(FILE *f)
7082 struct in_str input;
7083 setup_file_in_str(&input, f);
7084 parse_and_run_stream(&input, ';');
7087 /* Called a few times only (or even once if "sh -c") */
7088 static void init_sigmasks(void)
7092 sigset_t old_blocked_set;
7094 if (!G.inherited_set_is_saved) {
7095 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7096 G.inherited_set = G.blocked_set;
7098 old_blocked_set = G.blocked_set;
7100 mask = (1 << SIGQUIT);
7101 if (G_interactive_fd) {
7102 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7103 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7104 mask |= SPECIAL_JOB_SIGS;
7106 G.non_DFL_mask = mask;
7111 sigaddset(&G.blocked_set, sig);
7115 sigdelset(&G.blocked_set, SIGCHLD);
7117 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7118 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7120 /* POSIX allows shell to re-enable SIGCHLD
7121 * even if it was SIG_IGN on entry */
7122 #if ENABLE_HUSH_FAST
7123 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7124 if (!G.inherited_set_is_saved)
7125 signal(SIGCHLD, SIGCHLD_handler);
7127 if (!G.inherited_set_is_saved)
7128 signal(SIGCHLD, SIG_DFL);
7131 G.inherited_set_is_saved = 1;
7136 static void maybe_set_to_sigexit(int sig)
7138 void (*handler)(int);
7139 /* non_DFL_mask'ed signals are, well, masked,
7140 * no need to set handler for them.
7142 if (!((G.non_DFL_mask >> sig) & 1)) {
7143 handler = signal(sig, sigexit);
7144 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7145 signal(sig, handler);
7148 /* Set handlers to restore tty pgrp and exit */
7149 static void set_fatal_handlers(void)
7151 /* We _must_ restore tty pgrp on fatal signals */
7153 maybe_set_to_sigexit(SIGILL );
7154 maybe_set_to_sigexit(SIGFPE );
7155 maybe_set_to_sigexit(SIGBUS );
7156 maybe_set_to_sigexit(SIGSEGV);
7157 maybe_set_to_sigexit(SIGTRAP);
7158 } /* else: hush is perfect. what SEGV? */
7159 maybe_set_to_sigexit(SIGABRT);
7160 /* bash 3.2 seems to handle these just like 'fatal' ones */
7161 maybe_set_to_sigexit(SIGPIPE);
7162 maybe_set_to_sigexit(SIGALRM);
7163 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7164 * if we aren't interactive... but in this case
7165 * we never want to restore pgrp on exit, and this fn is not called */
7166 /*maybe_set_to_sigexit(SIGHUP );*/
7167 /*maybe_set_to_sigexit(SIGTERM);*/
7168 /*maybe_set_to_sigexit(SIGINT );*/
7172 static int set_mode(const char cstate, const char mode)
7174 int state = (cstate == '-' ? 1 : 0);
7176 case 'n': G.n_mode = state; break;
7177 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7178 default: return EXIT_FAILURE;
7180 return EXIT_SUCCESS;
7183 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7184 int hush_main(int argc, char **argv)
7186 static const struct variable const_shell_ver = {
7188 .varstr = (char*)hush_version_str,
7189 .max_len = 1, /* 0 can provoke free(name) */
7194 unsigned builtin_argc;
7196 struct variable *cur_var;
7199 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7200 G.last_exitcode = EXIT_SUCCESS;
7202 G.argv0_for_re_execing = argv[0];
7204 /* Deal with HUSH_VERSION */
7205 G.shell_ver = const_shell_ver; /* copying struct here */
7206 G.top_var = &G.shell_ver;
7207 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7208 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7209 /* Initialize our shell local variables with the values
7210 * currently living in the environment */
7211 cur_var = G.top_var;
7214 char *value = strchr(*e, '=');
7215 if (value) { /* paranoia */
7216 cur_var->next = xzalloc(sizeof(*cur_var));
7217 cur_var = cur_var->next;
7218 cur_var->varstr = *e;
7219 cur_var->max_len = strlen(*e);
7220 cur_var->flg_export = 1;
7224 /* reinstate HUSH_VERSION */
7225 debug_printf_env("putenv '%s'\n", hush_version_str);
7226 putenv((char *)hush_version_str);
7229 set_pwd_var(/*exp:*/ 1);
7230 /* bash also exports SHLVL and _,
7231 * and sets (but doesn't export) the following variables:
7233 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7234 * BASH_VERSION='3.2.0(1)-release'
7236 * MACHTYPE=i386-pc-linux-gnu
7238 * HOSTNAME=<xxxxxxxxxx>
7239 * PPID=<NNNNN> - we also do it elsewhere
7250 * PIPESTATUS=([0]="0")
7251 * HISTFILE=/<xxx>/.bash_history
7255 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7257 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7267 #if ENABLE_FEATURE_EDITING
7268 G.line_input_state = new_line_input_t(FOR_SHELL);
7270 G.global_argc = argc;
7271 G.global_argv = argv;
7272 /* Initialize some more globals to non-zero values */
7273 cmdedit_update_prompt();
7275 if (setjmp(die_jmp)) {
7276 /* xfunc has failed! die die die */
7277 /* no EXIT traps, this is an escape hatch! */
7279 hush_exit(xfunc_error_retval);
7282 /* Shell is non-interactive at first. We need to call
7283 * init_sigmasks() if we are going to execute "sh <script>",
7284 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7285 * If we later decide that we are interactive, we run init_sigmasks()
7286 * in order to intercept (more) signals.
7290 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7293 opt = getopt(argc, argv, "+c:xins"
7296 # if ENABLE_HUSH_FUNCTIONS
7306 * sh ... -c 'script'
7307 * sh ... -c 'script' ARG0 [ARG1...]
7308 * On NOMMU, if builtin_argc != 0,
7309 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7310 * "" needs to be replaced with NULL
7311 * and BARGV vector fed to builtin function.
7312 * Note: the form without ARG0 never happens:
7313 * sh ... -c 'builtin' BARGV... ""
7316 G.root_pid = getpid();
7317 G.root_ppid = getppid();
7319 G.global_argv = argv + optind;
7320 G.global_argc = argc - optind;
7322 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7323 const struct built_in_command *x;
7326 x = find_builtin(optarg);
7327 if (x) { /* paranoia */
7328 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7329 G.global_argv += builtin_argc;
7330 G.global_argv[-1] = NULL; /* replace "" */
7331 G.last_exitcode = x->b_function(argv + optind - 1);
7335 if (!G.global_argv[0]) {
7336 /* -c 'script' (no params): prevent empty $0 */
7337 G.global_argv--; /* points to argv[i] of 'script' */
7338 G.global_argv[0] = argv[0];
7340 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7342 parse_and_run_string(optarg);
7345 /* Well, we cannot just declare interactiveness,
7346 * we have to have some stuff (ctty, etc) */
7347 /* G_interactive_fd++; */
7350 /* "-s" means "read from stdin", but this is how we always
7351 * operate, so simply do nothing here. */
7354 case '<': /* "big heredoc" support */
7355 full_write1_str(optarg);
7358 unsigned long long empty_trap_mask;
7360 G.root_pid = bb_strtou(optarg, &optarg, 16);
7362 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7364 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7366 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7368 builtin_argc = bb_strtou(optarg, &optarg, 16);
7370 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7371 if (empty_trap_mask != 0) {
7374 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7375 for (sig = 1; sig < NSIG; sig++) {
7376 if (empty_trap_mask & (1LL << sig)) {
7377 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7378 sigaddset(&G.blocked_set, sig);
7381 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7383 # if ENABLE_HUSH_LOOPS
7385 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7391 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7393 # if ENABLE_HUSH_FUNCTIONS
7395 struct function *funcp = new_function(optarg);
7396 /* funcp->name is already set to optarg */
7397 /* funcp->body is set to NULL. It's a special case. */
7398 funcp->body_as_string = argv[optind];
7406 if (set_mode('-', opt) == 0) /* no error */
7410 fprintf(stderr, "Usage: sh [FILE]...\n"
7411 " or: sh -c command [args]...\n\n");
7417 } /* option parsing loop */
7420 G.root_pid = getpid();
7421 G.root_ppid = getppid();
7424 /* If we are login shell... */
7425 if (argv[0] && argv[0][0] == '-') {
7427 debug_printf("sourcing /etc/profile\n");
7428 input = fopen_for_read("/etc/profile");
7429 if (input != NULL) {
7430 close_on_exec_on(fileno(input));
7432 parse_and_run_file(input);
7435 /* bash: after sourcing /etc/profile,
7436 * tries to source (in the given order):
7437 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7438 * stopping on first found. --noprofile turns this off.
7439 * bash also sources ~/.bash_logout on exit.
7440 * If called as sh, skips .bash_XXX files.
7447 * "bash <script>" (which is never interactive (unless -i?))
7448 * sources $BASH_ENV here (without scanning $PATH).
7449 * If called as sh, does the same but with $ENV.
7451 debug_printf("running script '%s'\n", argv[optind]);
7452 G.global_argv = argv + optind;
7453 G.global_argc = argc - optind;
7454 input = xfopen_for_read(argv[optind]);
7455 close_on_exec_on(fileno(input));
7457 parse_and_run_file(input);
7458 #if ENABLE_FEATURE_CLEAN_UP
7464 /* Up to here, shell was non-interactive. Now it may become one.
7465 * NB: don't forget to (re)run init_sigmasks() as needed.
7468 /* A shell is interactive if the '-i' flag was given,
7469 * or if all of the following conditions are met:
7471 * no arguments remaining or the -s flag given
7472 * standard input is a terminal
7473 * standard output is a terminal
7474 * Refer to Posix.2, the description of the 'sh' utility.
7477 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7478 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7479 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7480 if (G_saved_tty_pgrp < 0)
7481 G_saved_tty_pgrp = 0;
7483 /* try to dup stdin to high fd#, >= 255 */
7484 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7485 if (G_interactive_fd < 0) {
7486 /* try to dup to any fd */
7487 G_interactive_fd = dup(STDIN_FILENO);
7488 if (G_interactive_fd < 0) {
7490 G_interactive_fd = 0;
7491 G_saved_tty_pgrp = 0;
7494 // TODO: track & disallow any attempts of user
7495 // to (inadvertently) close/redirect G_interactive_fd
7497 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7498 if (G_interactive_fd) {
7499 close_on_exec_on(G_interactive_fd);
7501 if (G_saved_tty_pgrp) {
7502 /* If we were run as 'hush &', sleep until we are
7503 * in the foreground (tty pgrp == our pgrp).
7504 * If we get started under a job aware app (like bash),
7505 * make sure we are now in charge so we don't fight over
7506 * who gets the foreground */
7508 pid_t shell_pgrp = getpgrp();
7509 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7510 if (G_saved_tty_pgrp == shell_pgrp)
7512 /* send TTIN to ourself (should stop us) */
7513 kill(- shell_pgrp, SIGTTIN);
7517 /* Block some signals */
7520 if (G_saved_tty_pgrp) {
7521 /* Set other signals to restore saved_tty_pgrp */
7522 set_fatal_handlers();
7523 /* Put ourselves in our own process group
7524 * (bash, too, does this only if ctty is available) */
7525 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7526 /* Grab control of the terminal */
7527 tcsetpgrp(G_interactive_fd, getpid());
7529 /* -1 is special - makes xfuncs longjmp, not exit
7530 * (we reset die_sleep = 0 whereever we [v]fork) */
7531 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7535 #elif ENABLE_HUSH_INTERACTIVE
7536 /* No job control compiled in, only prompt/line editing */
7537 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7538 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7539 if (G_interactive_fd < 0) {
7540 /* try to dup to any fd */
7541 G_interactive_fd = dup(STDIN_FILENO);
7542 if (G_interactive_fd < 0)
7544 G_interactive_fd = 0;
7547 if (G_interactive_fd) {
7548 close_on_exec_on(G_interactive_fd);
7552 /* We have interactiveness code disabled */
7556 * if interactive but not a login shell, sources ~/.bashrc
7557 * (--norc turns this off, --rcfile <file> overrides)
7560 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7561 /* note: ash and hush share this string */
7562 printf("\n\n%s %s\n"
7563 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7566 "hush - the humble shell"
7570 parse_and_run_file(stdin);
7573 #if ENABLE_FEATURE_CLEAN_UP
7574 if (G.cwd != bb_msg_unknown)
7576 cur_var = G.top_var->next;
7578 struct variable *tmp = cur_var;
7579 if (!cur_var->max_len)
7580 free(cur_var->varstr);
7581 cur_var = cur_var->next;
7585 hush_exit(G.last_exitcode);
7590 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7591 int lash_main(int argc, char **argv)
7593 bb_error_msg("lash is deprecated, please use hush instead");
7594 return hush_main(argc, argv);
7599 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7600 int msh_main(int argc, char **argv)
7602 //bb_error_msg("msh is deprecated, please use hush instead");
7603 return hush_main(argc, argv);
7611 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7616 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7623 return applet_main_func(argc, argv - argc);
7626 static int FAST_FUNC builtin_test(char **argv)
7628 return run_applet_main(argv, test_main);
7631 static int FAST_FUNC builtin_echo(char **argv)
7633 return run_applet_main(argv, echo_main);
7637 static int FAST_FUNC builtin_printf(char **argv)
7639 return run_applet_main(argv, printf_main);
7643 static char **skip_dash_dash(char **argv)
7646 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7651 static int FAST_FUNC builtin_eval(char **argv)
7653 int rcode = EXIT_SUCCESS;
7655 argv = skip_dash_dash(argv);
7657 char *str = expand_strvec_to_string(argv);
7659 * eval "echo Hi; done" ("done" is syntax error):
7660 * "echo Hi" will not execute too.
7662 parse_and_run_string(str);
7664 rcode = G.last_exitcode;
7669 static int FAST_FUNC builtin_cd(char **argv)
7673 argv = skip_dash_dash(argv);
7675 if (newdir == NULL) {
7676 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7677 * bash says "bash: cd: HOME not set" and does nothing
7680 const char *home = get_local_var_value("HOME");
7681 newdir = home ? home : "/";
7683 if (chdir(newdir)) {
7684 /* Mimic bash message exactly */
7685 bb_perror_msg("cd: %s", newdir);
7686 return EXIT_FAILURE;
7688 /* Read current dir (get_cwd(1) is inside) and set PWD.
7689 * Note: do not enforce exporting. If PWD was unset or unexported,
7690 * set it again, but do not export. bash does the same.
7692 set_pwd_var(/*exp:*/ 0);
7693 return EXIT_SUCCESS;
7696 static int FAST_FUNC builtin_exec(char **argv)
7698 argv = skip_dash_dash(argv);
7699 if (argv[0] == NULL)
7700 return EXIT_SUCCESS; /* bash does this */
7702 /* Careful: we can end up here after [v]fork. Do not restore
7703 * tty pgrp then, only top-level shell process does that */
7704 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7705 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7707 /* TODO: if exec fails, bash does NOT exit! We do.
7708 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7709 * and tcsetpgrp, and this is inherently racy.
7711 execvp_or_die(argv);
7714 static int FAST_FUNC builtin_exit(char **argv)
7716 debug_printf_exec("%s()\n", __func__);
7718 /* interactive bash:
7719 * # trap "echo EEE" EXIT
7722 * There are stopped jobs.
7723 * (if there are _stopped_ jobs, running ones don't count)
7726 # EEE (then bash exits)
7728 * we can use G.exiting = -1 as indicator "last cmd was exit"
7731 /* note: EXIT trap is run by hush_exit */
7732 argv = skip_dash_dash(argv);
7733 if (argv[0] == NULL)
7734 hush_exit(G.last_exitcode);
7735 /* mimic bash: exit 123abc == exit 255 + error msg */
7736 xfunc_error_retval = 255;
7737 /* bash: exit -2 == exit 254, no error msg */
7738 hush_exit(xatoi(argv[0]) & 0xff);
7741 static void print_escaped(const char *s)
7746 const char *p = strchrnul(s, '\'');
7747 /* print 'xxxx', possibly just '' */
7748 printf("'%.*s'", (int)(p - s), s);
7753 /* s points to '; print "'''...'''" */
7755 do putchar('\''); while (*++s == '\'');
7760 #if !ENABLE_HUSH_LOCAL
7761 #define helper_export_local(argv, exp, lvl) \
7762 helper_export_local(argv, exp)
7764 static void helper_export_local(char **argv, int exp, int lvl)
7769 /* So far we do not check that name is valid (TODO?) */
7771 if (strchr(name, '=') == NULL) {
7772 struct variable *var;
7774 var = get_local_var(name);
7775 if (exp == -1) { /* unexporting? */
7776 /* export -n NAME (without =VALUE) */
7778 var->flg_export = 0;
7779 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7781 } /* else: export -n NOT_EXISTING_VAR: no-op */
7784 if (exp == 1) { /* exporting? */
7785 /* export NAME (without =VALUE) */
7787 var->flg_export = 1;
7788 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7789 putenv(var->varstr);
7793 /* Exporting non-existing variable.
7794 * bash does not put it in environment,
7795 * but remembers that it is exported,
7796 * and does put it in env when it is set later.
7797 * We just set it to "" and export. */
7798 /* Or, it's "local NAME" (without =VALUE).
7799 * bash sets the value to "". */
7800 name = xasprintf("%s=", name);
7802 /* (Un)exporting/making local NAME=VALUE */
7803 name = xstrdup(name);
7805 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7809 static int FAST_FUNC builtin_export(char **argv)
7811 unsigned opt_unexport;
7813 #if ENABLE_HUSH_EXPORT_N
7814 /* "!": do not abort on errors */
7815 opt_unexport = getopt32(argv, "!n");
7816 if (opt_unexport == (uint32_t)-1)
7817 return EXIT_FAILURE;
7824 if (argv[0] == NULL) {
7831 /* ash emits: export VAR='VAL'
7832 * bash: declare -x VAR="VAL"
7833 * we follow ash example */
7834 const char *s = *e++;
7835 const char *p = strchr(s, '=');
7837 if (!p) /* wtf? take next variable */
7840 printf("export %.*s", (int)(p - s) + 1, s);
7841 print_escaped(p + 1);
7845 /*fflush_all(); - done after each builtin anyway */
7847 return EXIT_SUCCESS;
7850 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7852 return EXIT_SUCCESS;
7855 #if ENABLE_HUSH_LOCAL
7856 static int FAST_FUNC builtin_local(char **argv)
7858 if (G.func_nest_level == 0) {
7859 bb_error_msg("%s: not in a function", argv[0]);
7860 return EXIT_FAILURE; /* bash compat */
7862 helper_export_local(argv, 0, G.func_nest_level);
7863 return EXIT_SUCCESS;
7867 static int FAST_FUNC builtin_trap(char **argv)
7873 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7878 /* No args: print all trapped */
7879 for (i = 0; i < NSIG; ++i) {
7882 print_escaped(G.traps[i]);
7883 /* note: bash adds "SIG", but only if invoked
7884 * as "bash". If called as "sh", or if set -o posix,
7885 * then it prints short signal names.
7886 * We are printing short names: */
7887 printf(" %s\n", get_signame(i));
7890 /*fflush_all(); - done after each builtin anyway */
7891 return EXIT_SUCCESS;
7895 /* If first arg is a number: reset all specified signals */
7896 sig = bb_strtou(*argv, NULL, 10);
7902 sig = get_signum(*argv++);
7903 if (sig < 0 || sig >= NSIG) {
7905 /* Mimic bash message exactly */
7906 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7911 G.traps[sig] = xstrdup(new_cmd);
7913 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7914 get_signame(sig), sig, G.traps[sig]);
7916 /* There is no signal for 0 (EXIT) */
7921 sigaddset(&G.blocked_set, sig);
7923 /* There was a trap handler, we are removing it
7924 * (if sig has non-DFL handling,
7925 * we don't need to do anything) */
7926 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7928 sigdelset(&G.blocked_set, sig);
7931 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7935 if (!argv[1]) { /* no second arg */
7936 bb_error_msg("trap: invalid arguments");
7937 return EXIT_FAILURE;
7940 /* First arg is "-": reset all specified to default */
7941 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7942 /* Everything else: set arg as signal handler
7943 * (includes "" case, which ignores signal) */
7944 if (argv[0][0] == '-') {
7945 if (argv[0][1] == '\0') { /* "-" */
7946 /* new_cmd remains NULL: "reset these sigs" */
7949 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7952 /* else: "-something", no special meaning */
7957 goto process_sig_list;
7960 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7961 static int FAST_FUNC builtin_type(char **argv)
7963 int ret = EXIT_SUCCESS;
7969 if (0) {} /* make conditional compile easier below */
7970 /*else if (find_alias(*argv))
7971 type = "an alias";*/
7972 #if ENABLE_HUSH_FUNCTIONS
7973 else if (find_function(*argv))
7974 type = "a function";
7976 else if (find_builtin(*argv))
7977 type = "a shell builtin";
7978 else if ((path = find_in_path(*argv)) != NULL)
7981 bb_error_msg("type: %s: not found", *argv);
7986 printf("%s is %s\n", *argv, type);
7994 /* built-in 'fg' and 'bg' handler */
7995 static int FAST_FUNC builtin_fg_bg(char **argv)
8000 if (!G_interactive_fd)
8001 return EXIT_FAILURE;
8003 /* If they gave us no args, assume they want the last backgrounded task */
8005 for (pi = G.job_list; pi; pi = pi->next) {
8006 if (pi->jobid == G.last_jobid) {
8010 bb_error_msg("%s: no current job", argv[0]);
8011 return EXIT_FAILURE;
8013 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8014 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8015 return EXIT_FAILURE;
8017 for (pi = G.job_list; pi; pi = pi->next) {
8018 if (pi->jobid == jobnum) {
8022 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8023 return EXIT_FAILURE;
8025 /* TODO: bash prints a string representation
8026 * of job being foregrounded (like "sleep 1 | cat") */
8027 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8028 /* Put the job into the foreground. */
8029 tcsetpgrp(G_interactive_fd, pi->pgrp);
8032 /* Restart the processes in the job */
8033 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8034 for (i = 0; i < pi->num_cmds; i++) {
8035 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8036 pi->cmds[i].is_stopped = 0;
8038 pi->stopped_cmds = 0;
8040 i = kill(- pi->pgrp, SIGCONT);
8042 if (errno == ESRCH) {
8043 delete_finished_bg_job(pi);
8044 return EXIT_SUCCESS;
8046 bb_perror_msg("kill (SIGCONT)");
8049 if (argv[0][0] == 'f') {
8051 return checkjobs_and_fg_shell(pi);
8053 return EXIT_SUCCESS;
8057 #if ENABLE_HUSH_HELP
8058 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8060 const struct built_in_command *x;
8063 "Built-in commands:\n"
8064 "------------------\n");
8065 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8067 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8070 return EXIT_SUCCESS;
8075 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8078 const char *status_string;
8080 for (job = G.job_list; job; job = job->next) {
8081 if (job->alive_cmds == job->stopped_cmds)
8082 status_string = "Stopped";
8084 status_string = "Running";
8086 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8088 return EXIT_SUCCESS;
8093 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8098 # ifdef M_TRIM_THRESHOLD
8099 /* Optional. Reduces probability of false positives */
8102 /* Crude attempt to find where "free memory" starts,
8103 * sans fragmentation. */
8105 l = (unsigned long)p;
8108 if (l < (unsigned long)p) l = (unsigned long)p;
8111 if (!G.memleak_value)
8112 G.memleak_value = l;
8114 l -= G.memleak_value;
8121 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8126 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8129 return EXIT_SUCCESS;
8132 static int FAST_FUNC builtin_read(char **argv)
8141 /* "!": do not abort on errors.
8142 * Option string must start with "sr" to match BUILTIN_READ_xxx
8144 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8145 if (read_flags == (uint32_t)-1)
8146 return EXIT_FAILURE;
8149 r = shell_builtin_read(set_local_var_from_halves,
8151 get_local_var_value("IFS"), /* can be NULL */
8159 if ((uintptr_t)r > 1) {
8160 bb_error_msg("%s", r);
8161 r = (char*)(uintptr_t)1;
8164 return (uintptr_t)r;
8167 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8168 * built-in 'set' handler
8170 * set [-abCefhmnuvx] [-o option] [argument...]
8171 * set [+abCefhmnuvx] [+o option] [argument...]
8172 * set -- [argument...]
8175 * Implementations shall support the options in both their hyphen and
8176 * plus-sign forms. These options can also be specified as options to sh.
8178 * Write out all variables and their values: set
8179 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8180 * Turn on the -x and -v options: set -xv
8181 * Unset all positional parameters: set --
8182 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8183 * Set the positional parameters to the expansion of x, even if x expands
8184 * with a leading '-' or '+': set -- $x
8186 * So far, we only support "set -- [argument...]" and some of the short names.
8188 static int FAST_FUNC builtin_set(char **argv)
8191 char **pp, **g_argv;
8192 char *arg = *++argv;
8196 for (e = G.top_var; e; e = e->next)
8198 return EXIT_SUCCESS;
8202 if (!strcmp(arg, "--")) {
8206 if (arg[0] != '+' && arg[0] != '-')
8208 for (n = 1; arg[n]; ++n)
8209 if (set_mode(arg[0], arg[n]))
8211 } while ((arg = *++argv) != NULL);
8212 /* Now argv[0] is 1st argument */
8215 return EXIT_SUCCESS;
8218 /* NB: G.global_argv[0] ($0) is never freed/changed */
8219 g_argv = G.global_argv;
8220 if (G.global_args_malloced) {
8226 G.global_args_malloced = 1;
8227 pp = xzalloc(sizeof(pp[0]) * 2);
8228 pp[0] = g_argv[0]; /* retain $0 */
8231 /* This realloc's G.global_argv */
8232 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8239 return EXIT_SUCCESS;
8241 /* Nothing known, so abort */
8243 bb_error_msg("set: %s: invalid option", arg);
8244 return EXIT_FAILURE;
8247 static int FAST_FUNC builtin_shift(char **argv)
8250 argv = skip_dash_dash(argv);
8254 if (n >= 0 && n < G.global_argc) {
8255 if (G.global_args_malloced) {
8258 free(G.global_argv[m++]);
8261 memmove(&G.global_argv[1], &G.global_argv[n+1],
8262 G.global_argc * sizeof(G.global_argv[0]));
8263 return EXIT_SUCCESS;
8265 return EXIT_FAILURE;
8268 static int FAST_FUNC builtin_source(char **argv)
8270 char *arg_path, *filename;
8273 #if ENABLE_HUSH_FUNCTIONS
8277 argv = skip_dash_dash(argv);
8280 /* bash says: "bash: .: filename argument required" */
8281 return 2; /* bash compat */
8284 if (!strchr(filename, '/')) {
8285 arg_path = find_in_path(filename);
8287 filename = arg_path;
8289 input = fopen_or_warn(filename, "r");
8292 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8293 return EXIT_FAILURE;
8295 close_on_exec_on(fileno(input));
8297 #if ENABLE_HUSH_FUNCTIONS
8298 sv_flg = G.flag_return_in_progress;
8299 /* "we are inside sourced file, ok to use return" */
8300 G.flag_return_in_progress = -1;
8302 save_and_replace_G_args(&sv, argv);
8304 parse_and_run_file(input);
8307 restore_G_args(&sv, argv);
8308 #if ENABLE_HUSH_FUNCTIONS
8309 G.flag_return_in_progress = sv_flg;
8312 return G.last_exitcode;
8315 static int FAST_FUNC builtin_umask(char **argv)
8321 argv = skip_dash_dash(argv);
8323 mode_t old_mask = mask;
8326 rc = bb_parse_mode(argv[0], &mask);
8331 * bash: umask: 'q': invalid symbolic mode operator
8332 * bash: umask: 999: octal number out of range
8334 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8339 printf("%04o\n", (unsigned) mask);
8340 /* fall through and restore mask which we set to 0 */
8344 return !rc; /* rc != 0 - success */
8347 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8348 static int FAST_FUNC builtin_unset(char **argv)
8353 /* "!": do not abort on errors */
8354 /* "+": stop at 1st non-option */
8355 opts = getopt32(argv, "!+vf");
8356 if (opts == (unsigned)-1)
8357 return EXIT_FAILURE;
8359 bb_error_msg("unset: -v and -f are exclusive");
8360 return EXIT_FAILURE;
8366 if (!(opts & 2)) { /* not -f */
8367 if (unset_local_var(*argv)) {
8368 /* unset <nonexistent_var> doesn't fail.
8369 * Error is when one tries to unset RO var.
8370 * Message was printed by unset_local_var. */
8374 #if ENABLE_HUSH_FUNCTIONS
8384 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8385 static int FAST_FUNC builtin_wait(char **argv)
8387 int ret = EXIT_SUCCESS;
8390 argv = skip_dash_dash(argv);
8391 if (argv[0] == NULL) {
8392 /* Don't care about wait results */
8393 /* Note 1: must wait until there are no more children */
8394 /* Note 2: must be interruptible */
8396 * $ sleep 3 & sleep 6 & wait
8401 * $ sleep 3 & sleep 6 & wait
8405 * ^C <-- after ~4 sec from keyboard
8408 sigaddset(&G.blocked_set, SIGCHLD);
8409 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8412 if (errno == ECHILD)
8414 /* Wait for SIGCHLD or any other signal of interest */
8415 /* sigtimedwait with infinite timeout: */
8416 sig = sigwaitinfo(&G.blocked_set, NULL);
8418 sig = check_and_run_traps(sig);
8419 if (sig && sig != SIGCHLD) { /* see note 2 */
8425 sigdelset(&G.blocked_set, SIGCHLD);
8426 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8430 /* This is probably buggy wrt interruptible-ness */
8432 pid_t pid = bb_strtou(*argv, NULL, 10);
8434 /* mimic bash message */
8435 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8436 return EXIT_FAILURE;
8438 if (waitpid(pid, &status, 0) == pid) {
8439 if (WIFSIGNALED(status))
8440 ret = 128 + WTERMSIG(status);
8441 else if (WIFEXITED(status))
8442 ret = WEXITSTATUS(status);
8446 bb_perror_msg("wait %s", *argv);
8455 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8456 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8459 def = bb_strtou(argv[1], NULL, 10);
8460 if (errno || def < def_min || argv[2]) {
8461 bb_error_msg("%s: bad arguments", argv[0]);
8469 #if ENABLE_HUSH_LOOPS
8470 static int FAST_FUNC builtin_break(char **argv)
8473 if (G.depth_of_loop == 0) {
8474 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8475 return EXIT_SUCCESS; /* bash compat */
8477 G.flag_break_continue++; /* BC_BREAK = 1 */
8479 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8480 if (depth == UINT_MAX)
8481 G.flag_break_continue = BC_BREAK;
8482 if (G.depth_of_loop < depth)
8483 G.depth_break_continue = G.depth_of_loop;
8485 return EXIT_SUCCESS;
8488 static int FAST_FUNC builtin_continue(char **argv)
8490 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8491 return builtin_break(argv);
8495 #if ENABLE_HUSH_FUNCTIONS
8496 static int FAST_FUNC builtin_return(char **argv)
8500 if (G.flag_return_in_progress != -1) {
8501 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8502 return EXIT_FAILURE; /* bash compat */
8505 G.flag_return_in_progress = 1;
8508 * out of range: wraps around at 256, does not error out
8509 * non-numeric param:
8510 * f() { false; return qwe; }; f; echo $?
8511 * bash: return: qwe: numeric argument required <== we do this
8512 * 255 <== we also do this
8514 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);