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 GPLv2 or later, see file LICENSE in this source tree.
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. */
393 //TODO: rename to no_empty_expansion?
395 smallint has_empty_slot;
396 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
399 MAYBE_ASSIGNMENT = 0,
400 DEFINITELY_ASSIGNMENT = 1,
402 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
404 /* Used for initialization: o_string foo = NULL_O_STRING; */
405 #define NULL_O_STRING { NULL }
407 /* I can almost use ordinary FILE*. Is open_memstream() universally
408 * available? Where is it documented? */
409 typedef struct in_str {
411 /* eof_flag=1: last char in ->p is really an EOF */
412 char eof_flag; /* meaningless if ->p == NULL */
414 #if ENABLE_HUSH_INTERACTIVE
416 smallint promptmode; /* 0: PS1, 1: PS2 */
419 int (*get) (struct in_str *) FAST_FUNC;
420 int (*peek) (struct in_str *) FAST_FUNC;
422 #define i_getch(input) ((input)->get(input))
423 #define i_peek(input) ((input)->peek(input))
425 /* The descrip member of this structure is only used to make
426 * debugging output pretty */
427 static const struct {
429 signed char default_fd;
432 { O_RDONLY, 0, "<" },
433 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
434 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
435 { O_CREAT|O_RDWR, 1, "<>" },
436 { O_RDONLY, 0, "<<" },
437 /* Should not be needed. Bogus default_fd helps in debugging */
438 /* { O_RDONLY, 77, "<<" }, */
441 struct redir_struct {
442 struct redir_struct *next;
443 char *rd_filename; /* filename */
444 int rd_fd; /* fd to redirect */
445 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
447 smallint rd_type; /* (enum redir_type) */
448 /* note: for heredocs, rd_filename contains heredoc delimiter,
449 * and subsequently heredoc itself; and rd_dup is a bitmask:
450 * bit 0: do we need to trim leading tabs?
451 * bit 1: is heredoc quoted (<<'delim' syntax) ?
454 typedef enum redir_type {
456 REDIRECT_OVERWRITE = 1,
459 REDIRECT_HEREDOC = 4,
460 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
463 REDIRFD_SYNTAX_ERR = -2,
464 REDIRFD_TO_FILE = -1,
465 /* otherwise, rd_fd is redirected to rd_dup */
467 HEREDOC_SKIPTABS = 1,
473 pid_t pid; /* 0 if exited */
474 int assignment_cnt; /* how many argv[i] are assignments? */
475 smallint is_stopped; /* is the command currently running? */
476 smallint cmd_type; /* CMD_xxx */
478 #define CMD_SUBSHELL 1
480 /* used for "[[ EXPR ]]" */
481 #if ENABLE_HUSH_BASH_COMPAT
482 # define CMD_SINGLEWORD_NOGLOB 2
485 /* used for "export noglob=* glob* a=`echo a b`" */
486 //#define CMD_SINGLEWORD_NOGLOB_COND 3
487 // It is hard to implement correctly, it adds significant amounts of tricky code,
488 // and all this is only useful for really obscure export statements
489 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
490 // guards the code which implements it, but I have doubts it works
491 // in all cases (especially with mixed globbed/non-globbed arguments)
493 #if ENABLE_HUSH_FUNCTIONS
494 # define CMD_FUNCDEF 3
497 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
500 char *group_as_string;
502 #if ENABLE_HUSH_FUNCTIONS
503 struct function *child_func;
504 /* This field is used to prevent a bug here:
505 * while...do f1() {a;}; f1; f1() {b;}; f1; done
506 * When we execute "f1() {a;}" cmd, we create new function and clear
507 * cmd->group, cmd->group_as_string, cmd->argv[0].
508 * When we execute "f1() {b;}", we notice that f1 exists,
509 * and that its "parent cmd" struct is still "alive",
510 * we put those fields back into cmd->xxx
511 * (struct function has ->parent_cmd ptr to facilitate that).
512 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
513 * Without this trick, loop would execute a;b;b;b;...
514 * instead of correct sequence a;b;a;b;...
515 * When command is freed, it severs the link
516 * (sets ->child_func->parent_cmd to NULL).
519 char **argv; /* command name and arguments */
520 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
521 * and on execution these are substituted with their values.
522 * Substitution can make _several_ words out of one argv[n]!
523 * Example: argv[0]=='.^C*^C.' here: echo .$*.
524 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
526 struct redir_struct *redirects; /* I/O redirections */
528 /* Is there anything in this command at all? */
529 #define IS_NULL_CMD(cmd) \
530 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
535 int num_cmds; /* total number of commands in pipe */
536 int alive_cmds; /* number of commands running (not exited) */
537 int stopped_cmds; /* number of commands alive, but stopped */
539 int jobid; /* job number */
540 pid_t pgrp; /* process group ID for the job */
541 char *cmdtext; /* name of job */
543 struct command *cmds; /* array of commands in pipe */
544 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
545 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
546 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
548 typedef enum pipe_style {
554 /* Is there anything in this pipe at all? */
555 #define IS_NULL_PIPE(pi) \
556 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
558 /* This holds pointers to the various results of parsing */
559 struct parse_context {
560 /* linked list of pipes */
561 struct pipe *list_head;
562 /* last pipe (being constructed right now) */
564 /* last command in pipe (being constructed right now) */
565 struct command *command;
566 /* last redirect in command->redirects list */
567 struct redir_struct *pending_redirect;
573 smallint ctx_inverted; /* "! cmd | cmd" */
575 smallint ctx_dsemicolon; /* ";;" seen */
577 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
579 /* group we are enclosed in:
580 * example: "if pipe1; pipe2; then pipe3; fi"
581 * when we see "if" or "then", we malloc and copy current context,
582 * and make ->stack point to it. then we parse pipeN.
583 * when closing "then" / fi" / whatever is found,
584 * we move list_head into ->stack->command->group,
585 * copy ->stack into current context, and delete ->stack.
586 * (parsing of { list } and ( list ) doesn't use this method)
588 struct parse_context *stack;
592 /* On program start, environ points to initial environment.
593 * putenv adds new pointers into it, unsetenv removes them.
594 * Neither of these (de)allocates the strings.
595 * setenv allocates new strings in malloc space and does putenv,
596 * and thus setenv is unusable (leaky) for shell's purposes */
597 #define setenv(...) setenv_is_leaky_dont_use()
599 struct variable *next;
600 char *varstr; /* points to "name=" portion */
601 #if ENABLE_HUSH_LOCAL
602 unsigned func_nest_level;
604 int max_len; /* if > 0, name is part of initial env; else name is malloced */
605 smallint flg_export; /* putenv should be done on this var */
606 smallint flg_read_only;
614 #if ENABLE_HUSH_FUNCTIONS
616 struct function *next;
618 struct command *parent_cmd;
621 char *body_as_string;
627 /* "Globals" within this file */
628 /* Sorted roughly by size (smaller offsets == smaller code) */
630 /* interactive_fd != 0 means we are an interactive shell.
631 * If we are, then saved_tty_pgrp can also be != 0, meaning
632 * that controlling tty is available. With saved_tty_pgrp == 0,
633 * job control still works, but terminal signals
634 * (^C, ^Z, ^Y, ^\) won't work at all, and background
635 * process groups can only be created with "cmd &".
636 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
637 * to give tty to the foreground process group,
638 * and will take it back when the group is stopped (^Z)
641 #if ENABLE_HUSH_INTERACTIVE
642 /* 'interactive_fd' is a fd# open to ctty, if we have one
643 * _AND_ if we decided to act interactively */
647 # define G_interactive_fd (G.interactive_fd)
649 # define G_interactive_fd 0
651 #if ENABLE_FEATURE_EDITING
652 line_input_t *line_input_state;
657 #if ENABLE_HUSH_RANDOM_SUPPORT
663 pid_t saved_tty_pgrp;
664 struct pipe *job_list;
665 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
667 # define G_saved_tty_pgrp 0
669 smallint flag_SIGINT;
670 #if ENABLE_HUSH_LOOPS
671 smallint flag_break_continue;
673 #if ENABLE_HUSH_FUNCTIONS
674 /* 0: outside of a function (or sourced file)
675 * -1: inside of a function, ok to use return builtin
676 * 1: return is invoked, skip all till end of func
678 smallint flag_return_in_progress;
681 #if ENABLE_HUSH_MODE_X
683 # define G_x_mode (G.x_mode)
687 smallint exiting; /* used to prevent EXIT trap recursion */
688 /* These four support $?, $#, and $1 */
689 smalluint last_exitcode;
690 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
691 smalluint global_args_malloced;
692 smalluint inherited_set_is_saved;
693 /* how many non-NULL argv's we have. NB: $# + 1 */
697 char *argv0_for_re_execing;
699 #if ENABLE_HUSH_LOOPS
700 unsigned depth_break_continue;
701 unsigned depth_of_loop;
705 struct variable *top_var; /* = &G.shell_ver (set in main()) */
706 struct variable shell_ver;
707 char **expanded_assignments;
708 #if ENABLE_HUSH_FUNCTIONS
709 struct function *top_func;
710 # if ENABLE_HUSH_LOCAL
711 struct variable **shadowed_vars_pp;
712 unsigned func_nest_level;
715 /* Signal and trap handling */
717 unsigned count_SIGCHLD;
718 unsigned handled_SIGCHLD;
719 smallint we_have_children;
721 /* which signals have non-DFL handler (even with no traps set)? */
722 unsigned non_DFL_mask;
723 char **traps; /* char *traps[NSIG] */
724 sigset_t blocked_set;
725 sigset_t inherited_set;
727 unsigned long memleak_value;
730 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
732 #define G (*ptr_to_globals)
733 /* Not #defining name to G.name - this quickly gets unwieldy
734 * (too many defines). Also, I actually prefer to see when a variable
735 * is global, thus "G." prefix is a useful hint */
736 #define INIT_G() do { \
737 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
741 /* Function prototypes for builtins */
742 static int builtin_cd(char **argv) FAST_FUNC;
743 static int builtin_echo(char **argv) FAST_FUNC;
744 static int builtin_eval(char **argv) FAST_FUNC;
745 static int builtin_exec(char **argv) FAST_FUNC;
746 static int builtin_exit(char **argv) FAST_FUNC;
747 static int builtin_export(char **argv) FAST_FUNC;
749 static int builtin_fg_bg(char **argv) FAST_FUNC;
750 static int builtin_jobs(char **argv) FAST_FUNC;
753 static int builtin_help(char **argv) FAST_FUNC;
755 #if ENABLE_HUSH_LOCAL
756 static int builtin_local(char **argv) FAST_FUNC;
759 static int builtin_memleak(char **argv) FAST_FUNC;
762 static int builtin_printf(char **argv) FAST_FUNC;
764 static int builtin_pwd(char **argv) FAST_FUNC;
765 static int builtin_read(char **argv) FAST_FUNC;
766 static int builtin_set(char **argv) FAST_FUNC;
767 static int builtin_shift(char **argv) FAST_FUNC;
768 static int builtin_source(char **argv) FAST_FUNC;
769 static int builtin_test(char **argv) FAST_FUNC;
770 static int builtin_trap(char **argv) FAST_FUNC;
771 static int builtin_type(char **argv) FAST_FUNC;
772 static int builtin_true(char **argv) FAST_FUNC;
773 static int builtin_umask(char **argv) FAST_FUNC;
774 static int builtin_unset(char **argv) FAST_FUNC;
775 static int builtin_wait(char **argv) FAST_FUNC;
776 #if ENABLE_HUSH_LOOPS
777 static int builtin_break(char **argv) FAST_FUNC;
778 static int builtin_continue(char **argv) FAST_FUNC;
780 #if ENABLE_HUSH_FUNCTIONS
781 static int builtin_return(char **argv) FAST_FUNC;
784 /* Table of built-in functions. They can be forked or not, depending on
785 * context: within pipes, they fork. As simple commands, they do not.
786 * When used in non-forking context, they can change global variables
787 * in the parent shell process. If forked, of course they cannot.
788 * For example, 'unset foo | whatever' will parse and run, but foo will
789 * still be set at the end. */
790 struct built_in_command {
792 int (*b_function)(char **argv) FAST_FUNC;
795 # define BLTIN(cmd, func, help) { cmd, func, help }
797 # define BLTIN(cmd, func, help) { cmd, func }
801 static const struct built_in_command bltins1[] = {
802 BLTIN("." , builtin_source , "Run commands in a file"),
803 BLTIN(":" , builtin_true , NULL),
805 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
807 #if ENABLE_HUSH_LOOPS
808 BLTIN("break" , builtin_break , "Exit from a loop"),
810 BLTIN("cd" , builtin_cd , "Change directory"),
811 #if ENABLE_HUSH_LOOPS
812 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
814 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
815 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
816 BLTIN("exit" , builtin_exit , "Exit"),
817 BLTIN("export" , builtin_export , "Set environment variables"),
819 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
822 BLTIN("help" , builtin_help , NULL),
825 BLTIN("jobs" , builtin_jobs , "List jobs"),
827 #if ENABLE_HUSH_LOCAL
828 BLTIN("local" , builtin_local , "Set local variables"),
831 BLTIN("memleak" , builtin_memleak , NULL),
833 BLTIN("read" , builtin_read , "Input into variable"),
834 #if ENABLE_HUSH_FUNCTIONS
835 BLTIN("return" , builtin_return , "Return from a function"),
837 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
838 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
839 #if ENABLE_HUSH_BASH_COMPAT
840 BLTIN("source" , builtin_source , "Run commands in a file"),
842 BLTIN("trap" , builtin_trap , "Trap signals"),
843 BLTIN("type" , builtin_type , "Show command type"),
844 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
845 BLTIN("umask" , builtin_umask , "Set file creation mask"),
846 BLTIN("unset" , builtin_unset , "Unset variables"),
847 BLTIN("wait" , builtin_wait , "Wait for process"),
849 /* For now, echo and test are unconditionally enabled.
850 * Maybe make it configurable? */
851 static const struct built_in_command bltins2[] = {
852 BLTIN("[" , builtin_test , NULL),
853 BLTIN("echo" , builtin_echo , NULL),
855 BLTIN("printf" , builtin_printf , NULL),
857 BLTIN("pwd" , builtin_pwd , NULL),
858 BLTIN("test" , builtin_test , NULL),
865 /* prevent disasters with G.debug_indent < 0 */
866 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
867 # define debug_enter() (G.debug_indent++)
868 # define debug_leave() (G.debug_indent--)
870 # define indent() ((void)0)
871 # define debug_enter() ((void)0)
872 # define debug_leave() ((void)0)
876 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
879 #ifndef debug_printf_parse
880 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
883 #ifndef debug_printf_exec
884 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
887 #ifndef debug_printf_env
888 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
891 #ifndef debug_printf_jobs
892 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
893 # define DEBUG_JOBS 1
895 # define DEBUG_JOBS 0
898 #ifndef debug_printf_expand
899 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
900 # define DEBUG_EXPAND 1
902 # define DEBUG_EXPAND 0
905 #ifndef debug_printf_varexp
906 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 #ifndef debug_printf_glob
910 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
911 # define DEBUG_GLOB 1
913 # define DEBUG_GLOB 0
916 #ifndef debug_printf_list
917 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 #ifndef debug_printf_subst
921 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
924 #ifndef debug_printf_clean
925 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
926 # define DEBUG_CLEAN 1
928 # define DEBUG_CLEAN 0
932 static void debug_print_strings(const char *prefix, char **vv)
935 fprintf(stderr, "%s:\n", prefix);
937 fprintf(stderr, " '%s'\n", *vv++);
940 # define debug_print_strings(prefix, vv) ((void)0)
944 /* Leak hunting. Use hush_leaktool.sh for post-processing.
947 static void *xxmalloc(int lineno, size_t size)
949 void *ptr = xmalloc((size + 0xff) & ~0xff);
950 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
953 static void *xxrealloc(int lineno, void *ptr, size_t size)
955 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
956 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
959 static char *xxstrdup(int lineno, const char *str)
961 char *ptr = xstrdup(str);
962 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
965 static void xxfree(void *ptr)
967 fdprintf(2, "free %p\n", ptr);
970 # define xmalloc(s) xxmalloc(__LINE__, s)
971 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
972 # define xstrdup(s) xxstrdup(__LINE__, s)
973 # define free(p) xxfree(p)
977 /* Syntax and runtime errors. They always abort scripts.
978 * In interactive use they usually discard unparsed and/or unexecuted commands
979 * and return to the prompt.
980 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
983 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
984 # define syntax_error(lineno, msg) syntax_error(msg)
985 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
986 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
987 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
988 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
991 static void die_if_script(unsigned lineno, const char *fmt, ...)
996 bb_error_msg("hush.c:%u", lineno);
999 bb_verror_msg(fmt, p, NULL);
1001 if (!G_interactive_fd)
1005 static void syntax_error(unsigned lineno, const char *msg)
1008 die_if_script(lineno, "syntax error: %s", msg);
1010 die_if_script(lineno, "syntax error", NULL);
1013 static void syntax_error_at(unsigned lineno, const char *msg)
1015 die_if_script(lineno, "syntax error at '%s'", msg);
1018 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1020 die_if_script(lineno, "syntax error: unterminated %s", s);
1023 /* It so happens that all such cases are totally fatal
1024 * even if shell is interactive: EOF while looking for closing
1025 * delimiter. There is nowhere to read stuff from after that,
1026 * it's EOF! The only choice is to terminate.
1028 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1029 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1031 char msg[2] = { ch, '\0' };
1032 syntax_error_unterm_str(lineno, msg);
1036 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1041 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1045 # undef die_if_script
1046 # undef syntax_error
1047 # undef syntax_error_at
1048 # undef syntax_error_unterm_ch
1049 # undef syntax_error_unterm_str
1050 # undef syntax_error_unexpected_ch
1052 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1053 # define syntax_error(msg) syntax_error(__LINE__, msg)
1054 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1055 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1056 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1057 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1061 #if ENABLE_HUSH_INTERACTIVE
1062 static void cmdedit_update_prompt(void);
1064 # define cmdedit_update_prompt() ((void)0)
1068 /* Utility functions
1070 /* Replace each \x with x in place, return ptr past NUL. */
1071 static char *unbackslash(char *src)
1073 char *dst = src = strchrnul(src, '\\');
1077 if ((*dst++ = *src++) == '\0')
1083 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1104 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1105 v[count1 + count2] = NULL;
1108 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1112 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1114 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1115 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1118 #define add_strings_to_strings(strings, add, need_to_dup) \
1119 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1122 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1123 static char **add_string_to_strings(char **strings, char *add)
1128 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1131 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1133 char **ptr = add_string_to_strings(strings, add);
1134 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1137 #define add_string_to_strings(strings, add) \
1138 xx_add_string_to_strings(__LINE__, strings, add)
1141 static void free_strings(char **strings)
1156 /* Helpers for setting new $n and restoring them back
1158 typedef struct save_arg_t {
1162 smallint sv_g_malloced;
1165 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1169 sv->sv_argv0 = argv[0];
1170 sv->sv_g_argv = G.global_argv;
1171 sv->sv_g_argc = G.global_argc;
1172 sv->sv_g_malloced = G.global_args_malloced;
1174 argv[0] = G.global_argv[0]; /* retain $0 */
1175 G.global_argv = argv;
1176 G.global_args_malloced = 0;
1184 static void restore_G_args(save_arg_t *sv, char **argv)
1188 if (G.global_args_malloced) {
1189 /* someone ran "set -- arg1 arg2 ...", undo */
1191 while (*++pp) /* note: does not free $0 */
1193 free(G.global_argv);
1195 argv[0] = sv->sv_argv0;
1196 G.global_argv = sv->sv_g_argv;
1197 G.global_argc = sv->sv_g_argc;
1198 G.global_args_malloced = sv->sv_g_malloced;
1202 /* Basic theory of signal handling in shell
1203 * ========================================
1204 * This does not describe what hush does, rather, it is current understanding
1205 * what it _should_ do. If it doesn't, it's a bug.
1206 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1208 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1209 * is finished or backgrounded. It is the same in interactive and
1210 * non-interactive shells, and is the same regardless of whether
1211 * a user trap handler is installed or a shell special one is in effect.
1212 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1213 * backgrounds (i.e. stops) or kills all members of currently running
1216 * Wait builtin in interruptible by signals for which user trap is set
1217 * or by SIGINT in interactive shell.
1219 * Trap handlers will execute even within trap handlers. (right?)
1221 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1222 * except for handlers set to '' (empty string).
1224 * If job control is off, backgrounded commands ("cmd &")
1225 * have SIGINT, SIGQUIT set to SIG_IGN.
1227 * Commands which are run in command substitution ("`cmd`")
1228 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1230 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1231 * by the shell from its parent.
1233 * Signals which differ from SIG_DFL action
1234 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1237 * SIGTERM (interactive): ignore
1238 * SIGHUP (interactive):
1239 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1240 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1241 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1242 * that all pipe members are stopped. Try this in bash:
1243 * while :; do :; done - ^Z does not background it
1244 * (while :; do :; done) - ^Z backgrounds it
1245 * SIGINT (interactive): wait for last pipe, ignore the rest
1246 * of the command line, show prompt. NB: ^C does not send SIGINT
1247 * to interactive shell while shell is waiting for a pipe,
1248 * since shell is bg'ed (is not in foreground process group).
1249 * Example 1: this waits 5 sec, but does not execute ls:
1250 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1251 * Example 2: this does not wait and does not execute ls:
1252 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1253 * Example 3: this does not wait 5 sec, but executes ls:
1254 * "sleep 5; ls -l" + press ^C
1256 * (What happens to signals which are IGN on shell start?)
1257 * (What happens with signal mask on shell start?)
1259 * Implementation in hush
1260 * ======================
1261 * We use in-kernel pending signal mask to determine which signals were sent.
1262 * We block all signals which we don't want to take action immediately,
1263 * i.e. we block all signals which need to have special handling as described
1264 * above, and all signals which have traps set.
1265 * After each pipe execution, we extract any pending signals via sigtimedwait()
1268 * unsigned non_DFL_mask: a mask of such "special" signals
1269 * sigset_t blocked_set: current blocked signal set
1272 * clear bit in blocked_set unless it is also in non_DFL_mask
1273 * "trap 'cmd' SIGxxx":
1274 * set bit in blocked_set (even if 'cmd' is '')
1275 * after [v]fork, if we plan to be a shell:
1276 * unblock signals with special interactive handling
1277 * (child shell is not interactive),
1278 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1279 * after [v]fork, if we plan to exec:
1280 * POSIX says fork clears pending signal mask in child - no need to clear it.
1281 * Restore blocked signal set to one inherited by shell just prior to exec.
1283 * Note: as a result, we do not use signal handlers much. The only uses
1284 * are to count SIGCHLDs
1285 * and to restore tty pgrp on signal-induced exit.
1288 * Standard says "When a subshell is entered, traps that are not being ignored
1289 * are set to the default actions". bash interprets it so that traps which
1290 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1293 SPECIAL_INTERACTIVE_SIGS = 0
1298 SPECIAL_JOB_SIGS = 0
1306 #if ENABLE_HUSH_FAST
1307 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1310 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1316 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1317 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1318 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1319 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1321 /* Restores tty foreground process group, and exits.
1322 * May be called as signal handler for fatal signal
1323 * (will resend signal to itself, producing correct exit state)
1324 * or called directly with -EXITCODE.
1325 * We also call it if xfunc is exiting. */
1326 static void sigexit(int sig) NORETURN;
1327 static void sigexit(int sig)
1329 /* Disable all signals: job control, SIGPIPE, etc. */
1330 sigprocmask_allsigs(SIG_BLOCK);
1332 /* Careful: we can end up here after [v]fork. Do not restore
1333 * tty pgrp then, only top-level shell process does that */
1334 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1335 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1337 /* Not a signal, just exit */
1341 kill_myself_with_sig(sig); /* does not return */
1345 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1346 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1350 /* Restores tty foreground process group, and exits. */
1351 static void hush_exit(int exitcode) NORETURN;
1352 static void hush_exit(int exitcode)
1354 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1355 /* Prevent recursion:
1356 * trap "echo Hi; exit" EXIT; exit
1358 char *argv[] = { NULL, G.traps[0], NULL };
1367 sigexit(- (exitcode & 0xff));
1373 static int check_and_run_traps(int sig)
1375 static const struct timespec zero_timespec;
1376 smalluint save_rcode;
1382 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1387 if (G.traps && G.traps[sig]) {
1388 if (G.traps[sig][0]) {
1389 /* We have user-defined handler */
1390 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1391 save_rcode = G.last_exitcode;
1394 G.last_exitcode = save_rcode;
1395 } /* else: "" trap, ignoring signal */
1398 /* not a trap: special action */
1400 #if ENABLE_HUSH_FAST
1403 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1407 /* Builtin was ^C'ed, make it look prettier: */
1414 /* bash is observed to signal whole process groups,
1415 * not individual processes */
1416 for (job = G.job_list; job; job = job->next) {
1419 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1420 if (kill(- job->pgrp, SIGHUP) == 0)
1421 kill(- job->pgrp, SIGCONT);
1426 default: /* ignored: */
1427 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1435 static const char *get_cwd(int force)
1437 if (force || G.cwd == NULL) {
1438 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1439 * we must not try to free(bb_msg_unknown) */
1440 if (G.cwd == bb_msg_unknown)
1442 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1444 G.cwd = bb_msg_unknown;
1451 * Shell and environment variable support
1453 static struct variable **get_ptr_to_local_var(const char *name)
1455 struct variable **pp;
1456 struct variable *cur;
1461 while ((cur = *pp) != NULL) {
1462 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1469 static struct variable *get_local_var(const char *name)
1471 struct variable **pp = get_ptr_to_local_var(name);
1477 static const char* FAST_FUNC get_local_var_value(const char *name)
1479 struct variable **vpp;
1481 if (G.expanded_assignments) {
1482 char **cpp = G.expanded_assignments;
1483 int len = strlen(name);
1486 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1487 return cp + len + 1;
1492 vpp = get_ptr_to_local_var(name);
1494 return strchr((*vpp)->varstr, '=') + 1;
1496 if (strcmp(name, "PPID") == 0)
1497 return utoa(G.root_ppid);
1498 // bash compat: UID? EUID?
1499 #if ENABLE_HUSH_RANDOM_SUPPORT
1500 if (strcmp(name, "RANDOM") == 0) {
1501 return utoa(next_random(&G.random_gen));
1507 /* str holds "NAME=VAL" and is expected to be malloced.
1508 * We take ownership of it.
1510 * 0: do not change export flag
1511 * (if creating new variable, flag will be 0)
1512 * 1: set export flag and putenv the variable
1513 * -1: clear export flag and unsetenv the variable
1514 * flg_read_only is set only when we handle -R var=val
1516 #if !BB_MMU && ENABLE_HUSH_LOCAL
1517 /* all params are used */
1518 #elif BB_MMU && ENABLE_HUSH_LOCAL
1519 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1520 set_local_var(str, flg_export, local_lvl)
1521 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1522 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1523 set_local_var(str, flg_export)
1524 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1525 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1526 set_local_var(str, flg_export, flg_read_only)
1528 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1530 struct variable **var_pp;
1531 struct variable *cur;
1535 eq_sign = strchr(str, '=');
1536 if (!eq_sign) { /* not expected to ever happen? */
1541 name_len = eq_sign - str + 1; /* including '=' */
1542 var_pp = &G.top_var;
1543 while ((cur = *var_pp) != NULL) {
1544 if (strncmp(cur->varstr, str, name_len) != 0) {
1545 var_pp = &cur->next;
1548 /* We found an existing var with this name */
1549 if (cur->flg_read_only) {
1553 bb_error_msg("%s: readonly variable", str);
1557 if (flg_export == -1) { // "&& cur->flg_export" ?
1558 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1563 #if ENABLE_HUSH_LOCAL
1564 if (cur->func_nest_level < local_lvl) {
1565 /* New variable is declared as local,
1566 * and existing one is global, or local
1567 * from enclosing function.
1568 * Remove and save old one: */
1569 *var_pp = cur->next;
1570 cur->next = *G.shadowed_vars_pp;
1571 *G.shadowed_vars_pp = cur;
1572 /* bash 3.2.33(1) and exported vars:
1574 * # f() { local z=a; env | grep ^z; }
1580 if (cur->flg_export)
1585 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1590 if (cur->max_len != 0) {
1591 if (cur->max_len >= strlen(str)) {
1592 /* This one is from startup env, reuse space */
1593 strcpy(cur->varstr, str);
1597 /* max_len == 0 signifies "malloced" var, which we can
1598 * (and has to) free */
1602 goto set_str_and_exp;
1605 /* Not found - create new variable struct */
1606 cur = xzalloc(sizeof(*cur));
1607 #if ENABLE_HUSH_LOCAL
1608 cur->func_nest_level = local_lvl;
1610 cur->next = *var_pp;
1616 cur->flg_read_only = flg_read_only;
1619 if (flg_export == 1)
1620 cur->flg_export = 1;
1621 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1622 cmdedit_update_prompt();
1623 if (cur->flg_export) {
1624 if (flg_export == -1) {
1625 cur->flg_export = 0;
1626 /* unsetenv was already done */
1628 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1629 return putenv(cur->varstr);
1635 /* Used at startup and after each cd */
1636 static void set_pwd_var(int exp)
1638 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1639 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1642 static int unset_local_var_len(const char *name, int name_len)
1644 struct variable *cur;
1645 struct variable **var_pp;
1648 return EXIT_SUCCESS;
1649 var_pp = &G.top_var;
1650 while ((cur = *var_pp) != NULL) {
1651 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1652 if (cur->flg_read_only) {
1653 bb_error_msg("%s: readonly variable", name);
1654 return EXIT_FAILURE;
1656 *var_pp = cur->next;
1657 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1658 bb_unsetenv(cur->varstr);
1659 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1660 cmdedit_update_prompt();
1664 return EXIT_SUCCESS;
1666 var_pp = &cur->next;
1668 return EXIT_SUCCESS;
1671 static int unset_local_var(const char *name)
1673 return unset_local_var_len(name, strlen(name));
1676 static void unset_vars(char **strings)
1684 const char *eq = strchrnul(*v, '=');
1685 unset_local_var_len(*v, (int)(eq - *v));
1691 #if ENABLE_SH_MATH_SUPPORT
1692 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1693 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1694 static char* FAST_FUNC endofname(const char *name)
1702 if (!is_in_name(*p))
1709 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1711 char *var = xasprintf("%s=%s", name, val);
1712 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1717 * Helpers for "var1=val1 var2=val2 cmd" feature
1719 static void add_vars(struct variable *var)
1721 struct variable *next;
1725 var->next = G.top_var;
1727 if (var->flg_export) {
1728 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1729 putenv(var->varstr);
1731 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1737 static struct variable *set_vars_and_save_old(char **strings)
1740 struct variable *old = NULL;
1746 struct variable *var_p;
1747 struct variable **var_pp;
1750 eq = strchr(*s, '=');
1753 var_pp = get_ptr_to_local_var(*s);
1756 /* Remove variable from global linked list */
1758 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1759 *var_pp = var_p->next;
1760 /* Add it to returned list */
1764 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1775 static int FAST_FUNC static_get(struct in_str *i)
1785 static int FAST_FUNC static_peek(struct in_str *i)
1790 #if ENABLE_HUSH_INTERACTIVE
1792 static void cmdedit_update_prompt(void)
1794 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1795 G.PS1 = get_local_var_value("PS1");
1798 G.PS2 = get_local_var_value("PS2");
1806 static const char* setup_prompt_string(int promptmode)
1808 const char *prompt_str;
1809 debug_printf("setup_prompt_string %d ", promptmode);
1810 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1811 /* Set up the prompt */
1812 if (promptmode == 0) { /* PS1 */
1814 /* bash uses $PWD value, even if it is set by user.
1815 * It uses current dir only if PWD is unset.
1816 * We always use current dir. */
1817 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1822 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1823 debug_printf("result '%s'\n", prompt_str);
1827 static void get_user_input(struct in_str *i)
1830 const char *prompt_str;
1832 prompt_str = setup_prompt_string(i->promptmode);
1833 # if ENABLE_FEATURE_EDITING
1834 /* Enable command line editing only while a command line
1835 * is actually being read */
1838 /* buglet: SIGINT will not make new prompt to appear _at once_,
1839 * only after <Enter>. (^C will work) */
1840 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1841 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1842 check_and_run_traps(0);
1843 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1844 i->eof_flag = (r < 0);
1845 if (i->eof_flag) { /* EOF/error detected */
1846 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1847 G.user_input_buf[1] = '\0';
1852 fputs(prompt_str, stdout);
1854 G.user_input_buf[0] = r = fgetc(i->file);
1855 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1856 //do we need check_and_run_traps(0)? (maybe only if stdin)
1857 } while (G.flag_SIGINT);
1858 i->eof_flag = (r == EOF);
1860 i->p = G.user_input_buf;
1863 #endif /* INTERACTIVE */
1865 /* This is the magic location that prints prompts
1866 * and gets data back from the user */
1867 static int FAST_FUNC file_get(struct in_str *i)
1871 /* If there is data waiting, eat it up */
1872 if (i->p && *i->p) {
1873 #if ENABLE_HUSH_INTERACTIVE
1877 if (i->eof_flag && !*i->p)
1879 /* note: ch is never NUL */
1881 /* need to double check i->file because we might be doing something
1882 * more complicated by now, like sourcing or substituting. */
1883 #if ENABLE_HUSH_INTERACTIVE
1884 if (G_interactive_fd && i->promptme && i->file == stdin) {
1887 } while (!*i->p); /* need non-empty line */
1888 i->promptmode = 1; /* PS2 */
1893 do ch = fgetc(i->file); while (ch == '\0');
1895 debug_printf("file_get: got '%c' %d\n", ch, ch);
1896 #if ENABLE_HUSH_INTERACTIVE
1903 /* All callers guarantee this routine will never
1904 * be used right after a newline, so prompting is not needed.
1906 static int FAST_FUNC file_peek(struct in_str *i)
1909 if (i->p && *i->p) {
1910 if (i->eof_flag && !i->p[1])
1913 /* note: ch is never NUL */
1915 do ch = fgetc(i->file); while (ch == '\0');
1916 i->eof_flag = (ch == EOF);
1917 i->peek_buf[0] = ch;
1918 i->peek_buf[1] = '\0';
1920 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1924 static void setup_file_in_str(struct in_str *i, FILE *f)
1926 i->peek = file_peek;
1928 #if ENABLE_HUSH_INTERACTIVE
1930 i->promptmode = 0; /* PS1 */
1936 static void setup_string_in_str(struct in_str *i, const char *s)
1938 i->peek = static_peek;
1939 i->get = static_get;
1940 #if ENABLE_HUSH_INTERACTIVE
1942 i->promptmode = 0; /* PS1 */
1952 #define B_CHUNK (32 * sizeof(char*))
1954 static void o_reset_to_empty_unquoted(o_string *o)
1962 static void o_free(o_string *o)
1965 memset(o, 0, sizeof(*o));
1968 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1973 static void o_grow_by(o_string *o, int len)
1975 if (o->length + len > o->maxlen) {
1976 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1977 o->data = xrealloc(o->data, 1 + o->maxlen);
1981 static void o_addchr(o_string *o, int ch)
1983 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1985 o->data[o->length] = ch;
1987 o->data[o->length] = '\0';
1990 static void o_addblock(o_string *o, const char *str, int len)
1993 memcpy(&o->data[o->length], str, len);
1995 o->data[o->length] = '\0';
1998 static void o_addstr(o_string *o, const char *str)
2000 o_addblock(o, str, strlen(str));
2004 static void nommu_addchr(o_string *o, int ch)
2010 # define nommu_addchr(o, str) ((void)0)
2013 static void o_addstr_with_NUL(o_string *o, const char *str)
2015 o_addblock(o, str, strlen(str) + 1);
2018 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
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 glob:%d quoted:%d escape:%d\n",
2132 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->o_quoted, o->o_escape);
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, '$')
2567 #if ENABLE_HUSH_TICK
2568 && !strchr(str, '`')
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> */
2743 //TODO: move to a subroutine?
2747 char exp_save = exp_save; /* for compiler */
2748 char *exp_saveptr; /* points to expansion operator */
2749 char *exp_word = exp_word; /* for compiler */
2753 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2754 first_char = arg[0] = first_ch & 0x7f;
2757 if (first_char == '#' && arg[1] && !exp_saveptr) {
2758 /* handle length expansion ${#var} */
2762 /* maybe handle parameter expansion */
2763 if (exp_saveptr /* if 2nd char is one of expansion operators */
2764 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2766 /* ${?:0}, ${#[:]%0} etc */
2767 exp_saveptr = var + 1;
2769 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2770 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2772 exp_op = exp_save = *exp_saveptr;
2774 exp_word = exp_saveptr + 1;
2775 if (exp_op == ':') {
2776 exp_op = *exp_word++;
2777 if (ENABLE_HUSH_BASH_COMPAT
2778 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2780 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2785 *exp_saveptr = '\0';
2786 } /* else: it's not an expansion op, but bare ${var} */
2789 /* lookup the variable in question */
2790 if (isdigit(var[0])) {
2791 /* parse_dollar() should have vetted var for us */
2792 i = xatoi_positive(var);
2793 if (i < G.global_argc)
2794 val = G.global_argv[i];
2795 /* else val remains NULL: $N with too big N */
2799 val = utoa(G.root_pid);
2801 case '!': /* bg pid */
2802 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2804 case '?': /* exitcode */
2805 val = utoa(G.last_exitcode);
2807 case '#': /* argc */
2808 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2811 val = get_local_var_value(var);
2815 /* handle any expansions */
2816 if (exp_op == 'L') {
2817 debug_printf_expand("expand: length(%s)=", val);
2818 val = utoa(val ? strlen(val) : 0);
2819 debug_printf_expand("%s\n", val);
2820 } else if (exp_op) {
2821 if (exp_op == '%' || exp_op == '#') {
2822 /* Standard-mandated substring removal ops:
2823 * ${parameter%word} - remove smallest suffix pattern
2824 * ${parameter%%word} - remove largest suffix pattern
2825 * ${parameter#word} - remove smallest prefix pattern
2826 * ${parameter##word} - remove largest prefix pattern
2828 * Word is expanded to produce a glob pattern.
2829 * Then var's value is matched to it and matching part removed.
2834 unsigned scan_flags = pick_scan(exp_op, *exp_word);
2835 if (exp_op == *exp_word) /* ## or %% */
2837 val = to_be_freed = xstrdup(val);
2838 exp_exp_word = expand_pseudo_dquoted(exp_word);
2840 exp_word = exp_exp_word;
2841 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
2842 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2843 // exp_op, to_be_freed, exp_word, loc);
2845 if (loc) { /* match was found */
2846 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* # or ## */
2852 } else if (exp_op == ':') {
2853 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2854 /* It's ${var:N[:M]} bashism.
2855 * Note that in encoded form it has TWO parts:
2856 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2861 beg = expand_and_evaluate_arith(exp_word, &errcode);
2862 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2863 *p++ = SPECIAL_VAR_SYMBOL;
2865 p = strchr(p, SPECIAL_VAR_SYMBOL);
2867 len = expand_and_evaluate_arith(exp_word, &errcode);
2868 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2870 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2871 if (beg < 0) /* bash compat */
2873 debug_printf_varexp("from val:'%s'\n", val);
2874 if (len == 0 || !val || beg >= strlen(val))
2877 /* Paranoia. What if user entered 9999999999999
2878 * which fits in arith_t but not int? */
2881 val = to_be_freed = xstrndup(val + beg, len);
2883 debug_printf_varexp("val:'%s'\n", val);
2887 die_if_script("malformed ${%s:...}", var);
2890 } else { /* one of "-=+?" */
2891 /* Standard-mandated substitution ops:
2892 * ${var?word} - indicate error if unset
2893 * If var is unset, word (or a message indicating it is unset
2894 * if word is null) is written to standard error
2895 * and the shell exits with a non-zero exit status.
2896 * Otherwise, the value of var is substituted.
2897 * ${var-word} - use default value
2898 * If var is unset, word is substituted.
2899 * ${var=word} - assign and use default value
2900 * If var is unset, word is assigned to var.
2901 * In all cases, final value of var is substituted.
2902 * ${var+word} - use alternative value
2903 * If var is unset, null is substituted.
2904 * Otherwise, word is substituted.
2906 * Word is subjected to tilde expansion, parameter expansion,
2907 * command substitution, and arithmetic expansion.
2908 * If word is not needed, it is not expanded.
2910 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2911 * but also treat null var as if it is unset.
2913 int use_word = (!val || ((exp_save == ':') && !val[0]));
2915 use_word = !use_word;
2916 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2917 (exp_save == ':') ? "true" : "false", use_word);
2919 to_be_freed = expand_pseudo_dquoted(exp_word);
2921 exp_word = to_be_freed;
2922 if (exp_op == '?') {
2923 /* mimic bash message */
2924 die_if_script("%s: %s",
2926 exp_word[0] ? exp_word : "parameter null or not set"
2928 //TODO: how interactive bash aborts expansion mid-command?
2933 if (exp_op == '=') {
2934 /* ${var=[word]} or ${var:=[word]} */
2935 if (isdigit(var[0]) || var[0] == '#') {
2936 /* mimic bash message */
2937 die_if_script("$%s: cannot assign in this way", var);
2940 char *new_var = xasprintf("%s=%s", var, val);
2941 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2945 } /* one of "-=+?" */
2947 *exp_saveptr = exp_save;
2951 #if ENABLE_HUSH_TICK
2954 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2955 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2957 /* unquoted var's contents should be globbed, so don't escape */
2958 smallint sv = output->o_escape;
2959 output->o_escape = 0;
2960 n = expand_on_ifs(output, n, val);
2962 output->o_escape = sv;
2964 } else { /* quoted $VAR, val will be appended below */
2965 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2968 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2971 o_addQstr(output, val, strlen(val));
2974 /* Do the check to avoid writing to a const string */
2975 if (*p != SPECIAL_VAR_SYMBOL)
2976 *p = SPECIAL_VAR_SYMBOL;
2978 #if ENABLE_HUSH_TICK
2979 o_free(&subst_result);
2982 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2985 debug_print_list("expand_vars_to_list[a]", output, n);
2986 /* this part is literal, and it was already pre-quoted
2987 * if needed (much earlier), do not use o_addQstr here! */
2988 o_addstr_with_NUL(output, arg);
2989 debug_print_list("expand_vars_to_list[b]", output, n);
2990 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2991 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2994 /* allow to reuse list[n] later without re-growth */
2995 output->has_empty_slot = 1;
2997 o_addchr(output, '\0');
3003 EXPVAR_FLAG_GLOB = 0x200,
3004 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
3005 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
3007 static char **expand_variables(char **argv, unsigned or_mask)
3012 o_string output = NULL_O_STRING;
3014 /* protect against globbing for "$var"? */
3015 /* (unquoted $var will temporarily switch it off) */
3016 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
3017 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
3022 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
3025 debug_print_list("expand_variables", &output, n);
3027 /* output.data (malloced in one block) gets returned in "list" */
3028 list = o_finalize_list(&output, n);
3029 debug_print_strings("expand_variables[1]", list);
3033 static char **expand_strvec_to_strvec(char **argv)
3035 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
3038 #if ENABLE_HUSH_BASH_COMPAT
3039 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3041 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3045 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3046 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3051 o_string output = NULL_O_STRING;
3056 int is_var = is_well_formed_var_name(*v, '=');
3057 /* is_var * 0x80: singleword expansion for vars */
3058 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3060 /* Subtle! expand_vars_to_list did not glob last word yet.
3061 * It does this only when fed with further data.
3062 * Therefore we set globbing flags AFTER it, not before:
3065 /* if it is not recognizably abc=...; then: */
3066 output.o_escape = !is_var; /* protect against globbing for "$var" */
3067 /* (unquoted $var will temporarily switch it off) */
3068 output.o_glob = !is_var; /* and indeed do globbing */
3071 debug_print_list("expand_cond", &output, n);
3073 /* output.data (malloced in one block) gets returned in "list" */
3074 list = o_finalize_list(&output, n);
3075 debug_print_strings("expand_cond[1]", list);
3080 /* Used for expansion of right hand of assignments */
3081 /* NB: should NOT do globbing!
3082 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
3083 static char *expand_string_to_string(const char *str)
3085 char *argv[2], **list;
3087 argv[0] = (char*)str;
3089 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
3091 if (!list[0] || list[1])
3092 bb_error_msg_and_die("BUG in varexp2");
3093 /* actually, just move string 2*sizeof(char*) bytes back */
3094 overlapping_strcpy((char*)list, list[0]);
3095 unbackslash((char*)list);
3096 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3100 /* Used for "eval" builtin */
3101 static char* expand_strvec_to_string(char **argv)
3105 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3106 /* Convert all NULs to spaces */
3111 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3112 bb_error_msg_and_die("BUG in varexp3");
3113 /* bash uses ' ' regardless of $IFS contents */
3118 overlapping_strcpy((char*)list, list[0]);
3119 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3123 static char **expand_assignments(char **argv, int count)
3128 G.expanded_assignments = p = NULL;
3129 /* Expand assignments into one string each */
3130 for (i = 0; i < count; i++) {
3131 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3133 G.expanded_assignments = NULL;
3140 void re_execute_shell(char ***to_free, const char *s,
3141 char *g_argv0, char **g_argv,
3142 char **builtin_argv) NORETURN;
3144 static void reset_traps_to_defaults(void)
3146 /* This function is always called in a child shell
3147 * after fork (not vfork, NOMMU doesn't use this function).
3152 /* Child shells are not interactive.
3153 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3154 * Testcase: (while :; do :; done) + ^Z should background.
3155 * Same goes for SIGTERM, SIGHUP, SIGINT.
3157 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3158 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3160 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3161 * Stupid. It can be done with *single* &= op, but we can't use
3162 * the fact that G.blocked_set is implemented as a bitmask
3164 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3168 /* Careful. Only if no trap or trap is not "" */
3169 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3170 sigdelset(&G.blocked_set, sig);
3177 /* Our homegrown sig mask is saner to work with :) */
3178 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3180 /* Resetting all traps to default except empty ones */
3181 mask = G.non_DFL_mask;
3182 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3183 if (!G.traps[sig] || !G.traps[sig][0])
3186 G.traps[sig] = NULL;
3187 /* There is no signal for 0 (EXIT) */
3190 /* There was a trap handler, we just removed it.
3191 * But if sig still has non-DFL handling,
3192 * we should not unblock the sig. */
3195 sigdelset(&G.blocked_set, sig);
3197 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3202 static void re_execute_shell(char ***to_free, const char *s,
3203 char *g_argv0, char **g_argv,
3204 char **builtin_argv) NORETURN;
3205 static void re_execute_shell(char ***to_free, const char *s,
3206 char *g_argv0, char **g_argv,
3207 char **builtin_argv)
3209 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3210 /* delims + 2 * (number of bytes in printed hex numbers) */
3211 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3212 char *heredoc_argv[4];
3213 struct variable *cur;
3214 # if ENABLE_HUSH_FUNCTIONS
3215 struct function *funcp;
3219 unsigned long long empty_trap_mask;
3221 if (!g_argv0) { /* heredoc */
3222 argv = heredoc_argv;
3223 argv[0] = (char *) G.argv0_for_re_execing;
3224 argv[1] = (char *) "-<";
3225 argv[2] = (char *) s;
3227 pp = &argv[3]; /* used as pointer to empty environment */
3233 if (pp) while (*pp++)
3236 empty_trap_mask = 0;
3239 for (sig = 1; sig < NSIG; sig++) {
3240 if (G.traps[sig] && !G.traps[sig][0])
3241 empty_trap_mask |= 1LL << sig;
3245 sprintf(param_buf, NOMMU_HACK_FMT
3246 , (unsigned) G.root_pid
3247 , (unsigned) G.root_ppid
3248 , (unsigned) G.last_bg_pid
3249 , (unsigned) G.last_exitcode
3252 IF_HUSH_LOOPS(, G.depth_of_loop)
3254 # undef NOMMU_HACK_FMT
3255 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3256 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3259 for (cur = G.top_var; cur; cur = cur->next) {
3260 if (!cur->flg_export || cur->flg_read_only)
3263 # if ENABLE_HUSH_FUNCTIONS
3264 for (funcp = G.top_func; funcp; funcp = funcp->next)
3270 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3271 *pp++ = (char *) G.argv0_for_re_execing;
3273 for (cur = G.top_var; cur; cur = cur->next) {
3274 if (cur->varstr == hush_version_str)
3276 if (cur->flg_read_only) {
3277 *pp++ = (char *) "-R";
3278 *pp++ = cur->varstr;
3279 } else if (!cur->flg_export) {
3280 *pp++ = (char *) "-V";
3281 *pp++ = cur->varstr;
3284 # if ENABLE_HUSH_FUNCTIONS
3285 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3286 *pp++ = (char *) "-F";
3287 *pp++ = funcp->name;
3288 *pp++ = funcp->body_as_string;
3291 /* We can pass activated traps here. Say, -Tnn:trap_string
3293 * However, POSIX says that subshells reset signals with traps
3295 * I tested bash-3.2 and it not only does that with true subshells
3296 * of the form ( list ), but with any forked children shells.
3297 * I set trap "echo W" WINCH; and then tried:
3299 * { echo 1; sleep 20; echo 2; } &
3300 * while true; do echo 1; sleep 20; echo 2; break; done &
3301 * true | { echo 1; sleep 20; echo 2; } | cat
3303 * In all these cases sending SIGWINCH to the child shell
3304 * did not run the trap. If I add trap "echo V" WINCH;
3305 * _inside_ group (just before echo 1), it works.
3307 * I conclude it means we don't need to pass active traps here.
3308 * Even if we would use signal handlers instead of signal masking
3309 * in order to implement trap handling,
3310 * exec syscall below resets signals to SIG_DFL for us.
3312 *pp++ = (char *) "-c";
3315 while (*++builtin_argv)
3316 *pp++ = *builtin_argv;
3317 *pp++ = (char *) "";
3322 /* *pp = NULL; - is already there */
3326 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3327 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3328 execve(bb_busybox_exec_path, argv, pp);
3329 /* Fallback. Useful for init=/bin/hush usage etc */
3330 if (argv[0][0] == '/')
3331 execve(argv[0], argv, pp);
3332 xfunc_error_retval = 127;
3333 bb_error_msg_and_die("can't re-execute the shell");
3335 #endif /* !BB_MMU */
3338 static void setup_heredoc(struct redir_struct *redir)
3340 struct fd_pair pair;
3343 /* the _body_ of heredoc (misleading field name) */
3344 const char *heredoc = redir->rd_filename;
3351 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3352 expanded = expand_pseudo_dquoted(heredoc);
3356 len = strlen(heredoc);
3358 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3360 xmove_fd(pair.rd, redir->rd_fd);
3362 /* Try writing without forking. Newer kernels have
3363 * dynamically growing pipes. Must use non-blocking write! */
3366 written = write(pair.wr, heredoc, len);
3377 ndelay_off(pair.wr);
3379 /* Okay, pipe buffer was not big enough */
3380 /* Note: we must not create a stray child (bastard? :)
3381 * for the unsuspecting parent process. Child creates a grandchild
3382 * and exits before parent execs the process which consumes heredoc
3383 * (that exec happens after we return from this function) */
3390 disable_restore_tty_pgrp_on_exit();
3391 pid = BB_MMU ? xfork() : xvfork();
3395 close(redir->rd_fd); /* read side of the pipe */
3397 full_write(pair.wr, heredoc, len); /* may loop or block */
3400 /* Delegate blocking writes to another process */
3401 xmove_fd(pair.wr, STDOUT_FILENO);
3402 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3406 #if ENABLE_HUSH_FAST
3408 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3410 enable_restore_tty_pgrp_on_exit();
3416 wait(NULL); /* wait till child has died */
3419 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3420 * and stderr if they are redirected. */
3421 static int setup_redirects(struct command *prog, int squirrel[])
3424 struct redir_struct *redir;
3426 for (redir = prog->redirects; redir; redir = redir->next) {
3427 if (redir->rd_type == REDIRECT_HEREDOC2) {
3428 /* rd_fd<<HERE case */
3429 if (squirrel && redir->rd_fd < 3
3430 && squirrel[redir->rd_fd] < 0
3432 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3434 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3436 debug_printf_parse("set heredoc '%s'\n",
3437 redir->rd_filename);
3438 setup_heredoc(redir);
3442 if (redir->rd_dup == REDIRFD_TO_FILE) {
3443 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3445 if (redir->rd_filename == NULL) {
3446 /* Something went wrong in the parse.
3447 * Pretend it didn't happen */
3448 bb_error_msg("bug in redirect parse");
3451 mode = redir_table[redir->rd_type].mode;
3452 p = expand_string_to_string(redir->rd_filename);
3453 openfd = open_or_warn(p, mode);
3456 /* this could get lost if stderr has been redirected, but
3457 * bash and ash both lose it as well (though zsh doesn't!) */
3458 //what the above comment tries to say?
3462 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3463 openfd = redir->rd_dup;
3466 if (openfd != redir->rd_fd) {
3467 if (squirrel && redir->rd_fd < 3
3468 && squirrel[redir->rd_fd] < 0
3470 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3472 if (openfd == REDIRFD_CLOSE) {
3473 /* "n>-" means "close me" */
3474 close(redir->rd_fd);
3476 xdup2(openfd, redir->rd_fd);
3477 if (redir->rd_dup == REDIRFD_TO_FILE)
3485 static void restore_redirects(int squirrel[])
3488 for (i = 0; i < 3; i++) {
3491 /* We simply die on error */
3498 static void free_pipe_list(struct pipe *head);
3500 /* Return code is the exit status of the pipe */
3501 static void free_pipe(struct pipe *pi)
3504 struct command *command;
3505 struct redir_struct *r, *rnext;
3508 if (pi->stopped_cmds > 0) /* why? */
3510 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3511 for (i = 0; i < pi->num_cmds; i++) {
3512 command = &pi->cmds[i];
3513 debug_printf_clean(" command %d:\n", i);
3514 if (command->argv) {
3515 for (a = 0, p = command->argv; *p; a++, p++) {
3516 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3518 free_strings(command->argv);
3519 command->argv = NULL;
3521 /* not "else if": on syntax error, we may have both! */
3522 if (command->group) {
3523 debug_printf_clean(" begin group (cmd_type:%d)\n",
3525 free_pipe_list(command->group);
3526 debug_printf_clean(" end group\n");
3527 command->group = NULL;
3529 /* else is crucial here.
3530 * If group != NULL, child_func is meaningless */
3531 #if ENABLE_HUSH_FUNCTIONS
3532 else if (command->child_func) {
3533 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3534 command->child_func->parent_cmd = NULL;
3538 free(command->group_as_string);
3539 command->group_as_string = NULL;
3541 for (r = command->redirects; r; r = rnext) {
3542 debug_printf_clean(" redirect %d%s",
3543 r->rd_fd, redir_table[r->rd_type].descrip);
3544 /* guard against the case >$FOO, where foo is unset or blank */
3545 if (r->rd_filename) {
3546 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3547 free(r->rd_filename);
3548 r->rd_filename = NULL;
3550 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3554 command->redirects = NULL;
3556 free(pi->cmds); /* children are an array, they get freed all at once */
3564 static void free_pipe_list(struct pipe *head)
3566 struct pipe *pi, *next;
3568 for (pi = head; pi; pi = next) {
3570 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3573 debug_printf_clean("pipe followup code %d\n", pi->followup);
3575 /*pi->next = NULL;*/
3581 static int run_list(struct pipe *pi);
3583 #define parse_stream(pstring, input, end_trigger) \
3584 parse_stream(input, end_trigger)
3586 static struct pipe *parse_stream(char **pstring,
3587 struct in_str *input,
3589 static void parse_and_run_string(const char *s);
3592 static char *find_in_path(const char *arg)
3595 const char *PATH = get_local_var_value("PATH");
3601 const char *end = strchrnul(PATH, ':');
3602 int sz = end - PATH; /* must be int! */
3606 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3608 /* We have xxx::yyyy in $PATH,
3609 * it means "use current dir" */
3612 if (access(ret, F_OK) == 0)
3625 static const struct built_in_command* find_builtin_helper(const char *name,
3626 const struct built_in_command *x,
3627 const struct built_in_command *end)
3630 if (strcmp(name, x->b_cmd) != 0) {
3634 debug_printf_exec("found builtin '%s'\n", name);
3639 static const struct built_in_command* find_builtin1(const char *name)
3641 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3643 static const struct built_in_command* find_builtin(const char *name)
3645 const struct built_in_command *x = find_builtin1(name);
3648 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3651 #if ENABLE_HUSH_FUNCTIONS
3652 static struct function **find_function_slot(const char *name)
3654 struct function **funcpp = &G.top_func;
3656 if (strcmp(name, (*funcpp)->name) == 0) {
3659 funcpp = &(*funcpp)->next;
3664 static const struct function *find_function(const char *name)
3666 const struct function *funcp = *find_function_slot(name);
3668 debug_printf_exec("found function '%s'\n", name);
3672 /* Note: takes ownership on name ptr */
3673 static struct function *new_function(char *name)
3675 struct function **funcpp = find_function_slot(name);
3676 struct function *funcp = *funcpp;
3678 if (funcp != NULL) {
3679 struct command *cmd = funcp->parent_cmd;
3680 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3682 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3684 /* Note: if !funcp->body, do not free body_as_string!
3685 * This is a special case of "-F name body" function:
3686 * body_as_string was not malloced! */
3688 free_pipe_list(funcp->body);
3690 free(funcp->body_as_string);
3694 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3695 cmd->argv[0] = funcp->name;
3696 cmd->group = funcp->body;
3698 cmd->group_as_string = funcp->body_as_string;
3702 debug_printf_exec("remembering new function '%s'\n", name);
3703 funcp = *funcpp = xzalloc(sizeof(*funcp));
3704 /*funcp->next = NULL;*/
3711 static void unset_func(const char *name)
3713 struct function **funcpp = find_function_slot(name);
3714 struct function *funcp = *funcpp;
3716 if (funcp != NULL) {
3717 debug_printf_exec("freeing function '%s'\n", funcp->name);
3718 *funcpp = funcp->next;
3719 /* funcp is unlinked now, deleting it.
3720 * Note: if !funcp->body, the function was created by
3721 * "-F name body", do not free ->body_as_string
3722 * and ->name as they were not malloced. */
3724 free_pipe_list(funcp->body);
3727 free(funcp->body_as_string);
3735 #define exec_function(to_free, funcp, argv) \
3736 exec_function(funcp, argv)
3738 static void exec_function(char ***to_free,
3739 const struct function *funcp,
3740 char **argv) NORETURN;
3741 static void exec_function(char ***to_free,
3742 const struct function *funcp,
3748 argv[0] = G.global_argv[0];
3749 G.global_argv = argv;
3753 /* On MMU, funcp->body is always non-NULL */
3754 n = run_list(funcp->body);
3758 re_execute_shell(to_free,
3759 funcp->body_as_string,
3766 static int run_function(const struct function *funcp, char **argv)
3772 save_and_replace_G_args(&sv, argv);
3774 /* "we are in function, ok to use return" */
3775 sv_flg = G.flag_return_in_progress;
3776 G.flag_return_in_progress = -1;
3777 # if ENABLE_HUSH_LOCAL
3778 G.func_nest_level++;
3781 /* On MMU, funcp->body is always non-NULL */
3784 /* Function defined by -F */
3785 parse_and_run_string(funcp->body_as_string);
3786 rc = G.last_exitcode;
3790 rc = run_list(funcp->body);
3793 # if ENABLE_HUSH_LOCAL
3795 struct variable *var;
3796 struct variable **var_pp;
3798 var_pp = &G.top_var;
3799 while ((var = *var_pp) != NULL) {
3800 if (var->func_nest_level < G.func_nest_level) {
3801 var_pp = &var->next;
3805 if (var->flg_export)
3806 bb_unsetenv(var->varstr);
3807 /* Remove from global list */
3808 *var_pp = var->next;
3814 G.func_nest_level--;
3817 G.flag_return_in_progress = sv_flg;
3819 restore_G_args(&sv, argv);
3823 #endif /* ENABLE_HUSH_FUNCTIONS */
3827 #define exec_builtin(to_free, x, argv) \
3828 exec_builtin(x, argv)
3830 #define exec_builtin(to_free, x, argv) \
3831 exec_builtin(to_free, argv)
3833 static void exec_builtin(char ***to_free,
3834 const struct built_in_command *x,
3835 char **argv) NORETURN;
3836 static void exec_builtin(char ***to_free,
3837 const struct built_in_command *x,
3841 int rcode = x->b_function(argv);
3845 /* On NOMMU, we must never block!
3846 * Example: { sleep 99 | read line; } & echo Ok
3848 re_execute_shell(to_free,
3857 static void execvp_or_die(char **argv) NORETURN;
3858 static void execvp_or_die(char **argv)
3860 debug_printf_exec("execing '%s'\n", argv[0]);
3861 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3862 execvp(argv[0], argv);
3863 bb_perror_msg("can't execute '%s'", argv[0]);
3864 _exit(127); /* bash compat */
3867 #if ENABLE_HUSH_MODE_X
3868 static void dump_cmd_in_x_mode(char **argv)
3870 if (G_x_mode && argv) {
3871 /* We want to output the line in one write op */
3879 len += strlen(argv[n++]) + 1;
3885 p += sprintf(p, " %s", argv[n++]);
3893 # define dump_cmd_in_x_mode(argv) ((void)0)
3897 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3898 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3899 #define pseudo_exec(nommu_save, command, argv_expanded) \
3900 pseudo_exec(command, argv_expanded)
3903 /* Called after [v]fork() in run_pipe, or from builtin_exec.
3905 * Don't exit() here. If you don't exec, use _exit instead.
3906 * The at_exit handlers apparently confuse the calling process,
3907 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
3908 static void pseudo_exec_argv(nommu_save_t *nommu_save,
3909 char **argv, int assignment_cnt,
3910 char **argv_expanded) NORETURN;
3911 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
3912 char **argv, int assignment_cnt,
3913 char **argv_expanded)
3917 new_env = expand_assignments(argv, assignment_cnt);
3918 dump_cmd_in_x_mode(new_env);
3920 if (!argv[assignment_cnt]) {
3921 /* Case when we are here: ... | var=val | ...
3922 * (note that we do not exit early, i.e., do not optimize out
3923 * expand_assignments(): think about ... | var=`sleep 1` | ...
3925 free_strings(new_env);
3926 _exit(EXIT_SUCCESS);
3930 set_vars_and_save_old(new_env);
3931 free(new_env); /* optional */
3932 /* we can also destroy set_vars_and_save_old's return value,
3935 nommu_save->new_env = new_env;
3936 nommu_save->old_vars = set_vars_and_save_old(new_env);
3939 if (argv_expanded) {
3940 argv = argv_expanded;
3942 argv = expand_strvec_to_strvec(argv + assignment_cnt);
3944 nommu_save->argv = argv;
3947 dump_cmd_in_x_mode(argv);
3949 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3950 if (strchr(argv[0], '/') != NULL)
3954 /* Check if the command matches any of the builtins.
3955 * Depending on context, this might be redundant. But it's
3956 * easier to waste a few CPU cycles than it is to figure out
3957 * if this is one of those cases.
3960 /* On NOMMU, it is more expensive to re-execute shell
3961 * just in order to run echo or test builtin.
3962 * It's better to skip it here and run corresponding
3963 * non-builtin later. */
3964 const struct built_in_command *x;
3965 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
3967 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
3970 #if ENABLE_HUSH_FUNCTIONS
3971 /* Check if the command matches any functions */
3973 const struct function *funcp = find_function(argv[0]);
3975 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
3980 #if ENABLE_FEATURE_SH_STANDALONE
3981 /* Check if the command matches any busybox applets */
3983 int a = find_applet_by_name(argv[0]);
3985 # if BB_MMU /* see above why on NOMMU it is not allowed */
3986 if (APPLET_IS_NOEXEC(a)) {
3987 debug_printf_exec("running applet '%s'\n", argv[0]);
3988 run_applet_no_and_exit(a, argv);
3991 /* Re-exec ourselves */
3992 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
3993 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3994 execv(bb_busybox_exec_path, argv);
3995 /* If they called chroot or otherwise made the binary no longer
3996 * executable, fall through */
4001 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4004 execvp_or_die(argv);
4007 /* Called after [v]fork() in run_pipe
4009 static void pseudo_exec(nommu_save_t *nommu_save,
4010 struct command *command,
4011 char **argv_expanded) NORETURN;
4012 static void pseudo_exec(nommu_save_t *nommu_save,
4013 struct command *command,
4014 char **argv_expanded)
4016 if (command->argv) {
4017 pseudo_exec_argv(nommu_save, command->argv,
4018 command->assignment_cnt, argv_expanded);
4021 if (command->group) {
4022 /* Cases when we are here:
4025 * ... | ( list ) | ...
4026 * ... | { list } | ...
4030 debug_printf_exec("pseudo_exec: run_list\n");
4031 reset_traps_to_defaults();
4032 rcode = run_list(command->group);
4033 /* OK to leak memory by not calling free_pipe_list,
4034 * since this process is about to exit */
4037 re_execute_shell(&nommu_save->argv_from_re_execing,
4038 command->group_as_string,
4045 /* Case when we are here: ... | >file */
4046 debug_printf_exec("pseudo_exec'ed null command\n");
4047 _exit(EXIT_SUCCESS);
4051 static const char *get_cmdtext(struct pipe *pi)
4057 /* This is subtle. ->cmdtext is created only on first backgrounding.
4058 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4059 * On subsequent bg argv is trashed, but we won't use it */
4062 argv = pi->cmds[0].argv;
4063 if (!argv || !argv[0]) {
4064 pi->cmdtext = xzalloc(1);
4070 len += strlen(*argv) + 1;
4074 argv = pi->cmds[0].argv;
4076 len = strlen(*argv);
4077 memcpy(p, *argv, len);
4085 static void insert_bg_job(struct pipe *pi)
4087 struct pipe *job, **jobp;
4090 /* Linear search for the ID of the job to use */
4092 for (job = G.job_list; job; job = job->next)
4093 if (job->jobid >= pi->jobid)
4094 pi->jobid = job->jobid + 1;
4096 /* Add job to the list of running jobs */
4098 while ((job = *jobp) != NULL)
4100 job = *jobp = xmalloc(sizeof(*job));
4102 *job = *pi; /* physical copy */
4104 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4105 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4106 for (i = 0; i < pi->num_cmds; i++) {
4107 job->cmds[i].pid = pi->cmds[i].pid;
4108 /* all other fields are not used and stay zero */
4110 job->cmdtext = xstrdup(get_cmdtext(pi));
4112 if (G_interactive_fd)
4113 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4114 G.last_jobid = job->jobid;
4117 static void remove_bg_job(struct pipe *pi)
4119 struct pipe *prev_pipe;
4121 if (pi == G.job_list) {
4122 G.job_list = pi->next;
4124 prev_pipe = G.job_list;
4125 while (prev_pipe->next != pi)
4126 prev_pipe = prev_pipe->next;
4127 prev_pipe->next = pi->next;
4130 G.last_jobid = G.job_list->jobid;
4135 /* Remove a backgrounded job */
4136 static void delete_finished_bg_job(struct pipe *pi)
4139 pi->stopped_cmds = 0;
4145 /* Check to see if any processes have exited -- if they
4146 * have, figure out why and see if a job has completed */
4147 static int checkjobs(struct pipe* fg_pipe)
4157 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4159 attributes = WUNTRACED;
4160 if (fg_pipe == NULL)
4161 attributes |= WNOHANG;
4164 #if ENABLE_HUSH_FAST
4165 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4166 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4167 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4168 /* There was neither fork nor SIGCHLD since last waitpid */
4169 /* Avoid doing waitpid syscall if possible */
4170 if (!G.we_have_children) {
4174 if (fg_pipe == NULL) { /* is WNOHANG set? */
4175 /* We have children, but they did not exit
4176 * or stop yet (we saw no SIGCHLD) */
4179 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4183 /* Do we do this right?
4184 * bash-3.00# sleep 20 | false
4186 * [3]+ Stopped sleep 20 | false
4187 * bash-3.00# echo $?
4188 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4189 * [hush 1.14.0: yes we do it right]
4196 #if ENABLE_HUSH_FAST
4197 i = G.count_SIGCHLD;
4199 childpid = waitpid(-1, &status, attributes);
4200 if (childpid <= 0) {
4201 if (childpid && errno != ECHILD)
4202 bb_perror_msg("waitpid");
4203 #if ENABLE_HUSH_FAST
4204 else { /* Until next SIGCHLD, waitpid's are useless */
4205 G.we_have_children = (childpid == 0);
4206 G.handled_SIGCHLD = i;
4207 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4212 dead = WIFEXITED(status) || WIFSIGNALED(status);
4215 if (WIFSTOPPED(status))
4216 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4217 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4218 if (WIFSIGNALED(status))
4219 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4220 childpid, WTERMSIG(status), WEXITSTATUS(status));
4221 if (WIFEXITED(status))
4222 debug_printf_jobs("pid %d exited, exitcode %d\n",
4223 childpid, WEXITSTATUS(status));
4225 /* Were we asked to wait for fg pipe? */
4227 for (i = 0; i < fg_pipe->num_cmds; i++) {
4228 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4229 if (fg_pipe->cmds[i].pid != childpid)
4232 fg_pipe->cmds[i].pid = 0;
4233 fg_pipe->alive_cmds--;
4234 if (i == fg_pipe->num_cmds - 1) {
4235 /* last process gives overall exitstatus */
4236 rcode = WEXITSTATUS(status);
4237 /* bash prints killer signal's name for *last*
4238 * process in pipe (prints just newline for SIGINT).
4239 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4241 if (WIFSIGNALED(status)) {
4242 int sig = WTERMSIG(status);
4243 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4244 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4245 * Maybe we need to use sig | 128? */
4248 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4251 fg_pipe->cmds[i].is_stopped = 1;
4252 fg_pipe->stopped_cmds++;
4254 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4255 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4256 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4257 /* All processes in fg pipe have exited or stopped */
4258 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4259 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4260 * and "killall -STOP cat" */
4261 if (G_interactive_fd) {
4263 if (fg_pipe->alive_cmds)
4264 insert_bg_job(fg_pipe);
4268 if (!fg_pipe->alive_cmds)
4271 /* There are still running processes in the fg pipe */
4272 goto wait_more; /* do waitpid again */
4274 /* it wasnt fg_pipe, look for process in bg pipes */
4278 /* We asked to wait for bg or orphaned children */
4279 /* No need to remember exitcode in this case */
4280 for (pi = G.job_list; pi; pi = pi->next) {
4281 for (i = 0; i < pi->num_cmds; i++) {
4282 if (pi->cmds[i].pid == childpid)
4283 goto found_pi_and_prognum;
4286 /* Happens when shell is used as init process (init=/bin/sh) */
4287 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4288 continue; /* do waitpid again */
4290 found_pi_and_prognum:
4293 pi->cmds[i].pid = 0;
4295 if (!pi->alive_cmds) {
4296 if (G_interactive_fd)
4297 printf(JOB_STATUS_FORMAT, pi->jobid,
4298 "Done", pi->cmdtext);
4299 delete_finished_bg_job(pi);
4303 pi->cmds[i].is_stopped = 1;
4307 } /* while (waitpid succeeds)... */
4313 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4316 int rcode = checkjobs(fg_pipe);
4317 if (G_saved_tty_pgrp) {
4318 /* Job finished, move the shell to the foreground */
4319 p = getpgrp(); /* our process group id */
4320 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4321 tcsetpgrp(G_interactive_fd, p);
4327 /* Start all the jobs, but don't wait for anything to finish.
4330 * Return code is normally -1, when the caller has to wait for children
4331 * to finish to determine the exit status of the pipe. If the pipe
4332 * is a simple builtin command, however, the action is done by the
4333 * time run_pipe returns, and the exit code is provided as the
4336 * Returns -1 only if started some children. IOW: we have to
4337 * mask out retvals of builtins etc with 0xff!
4339 * The only case when we do not need to [v]fork is when the pipe
4340 * is single, non-backgrounded, non-subshell command. Examples:
4341 * cmd ; ... { list } ; ...
4342 * cmd && ... { list } && ...
4343 * cmd || ... { list } || ...
4344 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4345 * or (if SH_STANDALONE) an applet, and we can run the { list }
4346 * with run_list. If it isn't one of these, we fork and exec cmd.
4348 * Cases when we must fork:
4349 * non-single: cmd | cmd
4350 * backgrounded: cmd & { list } &
4351 * subshell: ( list ) [&]
4353 #if !ENABLE_HUSH_MODE_X
4354 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4355 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4357 static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4359 /* setup_redirects acts on file descriptors, not FILEs.
4360 * This is perfect for work that comes after exec().
4361 * Is it really safe for inline use? Experimentally,
4362 * things seem to work. */
4363 int rcode = setup_redirects(command, squirrel);
4365 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4366 *new_env_p = new_env;
4367 dump_cmd_in_x_mode(new_env);
4368 dump_cmd_in_x_mode(argv_expanded);
4370 *old_vars_p = set_vars_and_save_old(new_env);
4374 static NOINLINE int run_pipe(struct pipe *pi)
4376 static const char *const null_ptr = NULL;
4380 struct command *command;
4381 char **argv_expanded;
4383 /* it is not always needed, but we aim to smaller code */
4384 int squirrel[] = { -1, -1, -1 };
4387 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4390 IF_HUSH_JOB(pi->pgrp = -1;)
4391 pi->stopped_cmds = 0;
4392 command = &pi->cmds[0];
4393 argv_expanded = NULL;
4395 if (pi->num_cmds != 1
4396 || pi->followup == PIPE_BG
4397 || command->cmd_type == CMD_SUBSHELL
4404 debug_printf_exec(": group:%p argv:'%s'\n",
4405 command->group, command->argv ? command->argv[0] : "NONE");
4407 if (command->group) {
4408 #if ENABLE_HUSH_FUNCTIONS
4409 if (command->cmd_type == CMD_FUNCDEF) {
4410 /* "executing" func () { list } */
4411 struct function *funcp;
4413 funcp = new_function(command->argv[0]);
4414 /* funcp->name is already set to argv[0] */
4415 funcp->body = command->group;
4417 funcp->body_as_string = command->group_as_string;
4418 command->group_as_string = NULL;
4420 command->group = NULL;
4421 command->argv[0] = NULL;
4422 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4423 funcp->parent_cmd = command;
4424 command->child_func = funcp;
4426 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4428 return EXIT_SUCCESS;
4432 debug_printf("non-subshell group\n");
4433 rcode = 1; /* exitcode if redir failed */
4434 if (setup_redirects(command, squirrel) == 0) {
4435 debug_printf_exec(": run_list\n");
4436 rcode = run_list(command->group) & 0xff;
4438 restore_redirects(squirrel);
4439 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4441 debug_printf_exec("run_pipe: return %d\n", rcode);
4445 argv = command->argv ? command->argv : (char **) &null_ptr;
4447 const struct built_in_command *x;
4448 #if ENABLE_HUSH_FUNCTIONS
4449 const struct function *funcp;
4453 char **new_env = NULL;
4454 struct variable *old_vars = NULL;
4456 if (argv[command->assignment_cnt] == NULL) {
4457 /* Assignments, but no command */
4458 /* Ensure redirects take effect (that is, create files).
4459 * Try "a=t >file" */
4460 #if 0 /* A few cases in testsuite fail with this code. FIXME */
4461 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4462 /* Set shell variables */
4466 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4467 /* Do we need to flag set_local_var() errors?
4468 * "assignment to readonly var" and "putenv error"
4473 /* Redirect error sets $? to 1. Otherwise,
4474 * if evaluating assignment value set $?, retain it.
4475 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4477 rcode = G.last_exitcode;
4478 /* Exit, _skipping_ variable restoring code: */
4479 goto clean_up_and_ret0;
4481 #else /* Older, bigger, but more correct code */
4483 rcode = setup_redirects(command, squirrel);
4484 restore_redirects(squirrel);
4485 /* Set shell variables */
4487 bb_putchar_stderr('+');
4489 char *p = expand_string_to_string(*argv);
4491 fprintf(stderr, " %s", p);
4492 debug_printf_exec("set shell var:'%s'->'%s'\n",
4494 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4495 /* Do we need to flag set_local_var() errors?
4496 * "assignment to readonly var" and "putenv error"
4501 bb_putchar_stderr('\n');
4502 /* Redirect error sets $? to 1. Otherwise,
4503 * if evaluating assignment value set $?, retain it.
4504 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4506 rcode = G.last_exitcode;
4507 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4509 debug_printf_exec("run_pipe: return %d\n", rcode);
4514 /* Expand the rest into (possibly) many strings each */
4516 #if ENABLE_HUSH_BASH_COMPAT
4517 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4518 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4521 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4522 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4523 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4527 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4530 /* if someone gives us an empty string: `cmd with empty output` */
4531 if (!argv_expanded[0]) {
4532 free(argv_expanded);
4534 return G.last_exitcode;
4537 x = find_builtin(argv_expanded[0]);
4538 #if ENABLE_HUSH_FUNCTIONS
4541 funcp = find_function(argv_expanded[0]);
4545 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4546 debug_printf("exec with redirects only\n");
4547 rcode = setup_redirects(command, NULL);
4548 goto clean_up_and_ret1;
4551 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4554 debug_printf_exec(": builtin '%s' '%s'...\n",
4555 x->b_cmd, argv_expanded[1]);
4556 rcode = x->b_function(argv_expanded) & 0xff;
4559 #if ENABLE_HUSH_FUNCTIONS
4561 # if ENABLE_HUSH_LOCAL
4562 struct variable **sv;
4563 sv = G.shadowed_vars_pp;
4564 G.shadowed_vars_pp = &old_vars;
4566 debug_printf_exec(": function '%s' '%s'...\n",
4567 funcp->name, argv_expanded[1]);
4568 rcode = run_function(funcp, argv_expanded) & 0xff;
4569 # if ENABLE_HUSH_LOCAL
4570 G.shadowed_vars_pp = sv;
4576 unset_vars(new_env);
4578 /* clean_up_and_ret0: */
4579 restore_redirects(squirrel);
4581 free(argv_expanded);
4582 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4584 debug_printf_exec("run_pipe return %d\n", rcode);
4588 if (ENABLE_FEATURE_SH_STANDALONE) {
4589 int n = find_applet_by_name(argv_expanded[0]);
4590 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4591 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4593 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4594 argv_expanded[0], argv_expanded[1]);
4595 rcode = run_nofork_applet(n, argv_expanded);
4597 goto clean_up_and_ret;
4600 /* It is neither builtin nor applet. We must fork. */
4604 /* NB: argv_expanded may already be created, and that
4605 * might include `cmd` runs! Do not rerun it! We *must*
4606 * use argv_expanded if it's non-NULL */
4608 /* Going to fork a child per each pipe member */
4613 while (cmd_no < pi->num_cmds) {
4614 struct fd_pair pipefds;
4616 volatile nommu_save_t nommu_save;
4617 nommu_save.new_env = NULL;
4618 nommu_save.old_vars = NULL;
4619 nommu_save.argv = NULL;
4620 nommu_save.argv_from_re_execing = NULL;
4622 command = &pi->cmds[cmd_no];
4624 if (command->argv) {
4625 debug_printf_exec(": pipe member '%s' '%s'...\n",
4626 command->argv[0], command->argv[1]);
4628 debug_printf_exec(": pipe member with no argv\n");
4631 /* pipes are inserted between pairs of commands */
4634 if (cmd_no < pi->num_cmds)
4635 xpiped_pair(pipefds);
4637 command->pid = BB_MMU ? fork() : vfork();
4638 if (!command->pid) { /* child */
4640 disable_restore_tty_pgrp_on_exit();
4641 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4643 /* Every child adds itself to new process group
4644 * with pgid == pid_of_first_child_in_pipe */
4645 if (G.run_list_level == 1 && G_interactive_fd) {
4648 if (pgrp < 0) /* true for 1st process only */
4650 if (setpgid(0, pgrp) == 0
4651 && pi->followup != PIPE_BG
4652 && G_saved_tty_pgrp /* we have ctty */
4654 /* We do it in *every* child, not just first,
4656 tcsetpgrp(G_interactive_fd, pgrp);
4660 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4661 /* 1st cmd in backgrounded pipe
4662 * should have its stdin /dev/null'ed */
4664 if (open(bb_dev_null, O_RDONLY))
4665 xopen("/", O_RDONLY);
4667 xmove_fd(next_infd, 0);
4669 xmove_fd(pipefds.wr, 1);
4672 /* Like bash, explicit redirects override pipes,
4673 * and the pipe fd is available for dup'ing. */
4674 if (setup_redirects(command, NULL))
4677 /* Restore default handlers just prior to exec */
4678 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4680 /* Stores to nommu_save list of env vars putenv'ed
4681 * (NOMMU, on MMU we don't need that) */
4682 /* cast away volatility... */
4683 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4684 /* pseudo_exec() does not return */
4687 /* parent or error */
4688 #if ENABLE_HUSH_FAST
4690 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4692 enable_restore_tty_pgrp_on_exit();
4694 /* Clean up after vforked child */
4695 free(nommu_save.argv);
4696 free(nommu_save.argv_from_re_execing);
4697 unset_vars(nommu_save.new_env);
4698 add_vars(nommu_save.old_vars);
4700 free(argv_expanded);
4701 argv_expanded = NULL;
4702 if (command->pid < 0) { /* [v]fork failed */
4703 /* Clearly indicate, was it fork or vfork */
4704 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4708 /* Second and next children need to know pid of first one */
4710 pi->pgrp = command->pid;
4716 if (cmd_no < pi->num_cmds)
4718 /* Pass read (output) pipe end to next iteration */
4719 next_infd = pipefds.rd;
4722 if (!pi->alive_cmds) {
4724 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4729 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4733 #ifndef debug_print_tree
4734 static void debug_print_tree(struct pipe *pi, int lvl)
4736 static const char *const PIPE[] = {
4742 static const char *RES[] = {
4743 [RES_NONE ] = "NONE" ,
4746 [RES_THEN ] = "THEN" ,
4747 [RES_ELIF ] = "ELIF" ,
4748 [RES_ELSE ] = "ELSE" ,
4751 # if ENABLE_HUSH_LOOPS
4752 [RES_FOR ] = "FOR" ,
4753 [RES_WHILE] = "WHILE",
4754 [RES_UNTIL] = "UNTIL",
4756 [RES_DONE ] = "DONE" ,
4758 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4761 # if ENABLE_HUSH_CASE
4762 [RES_CASE ] = "CASE" ,
4763 [RES_CASE_IN ] = "CASE_IN" ,
4764 [RES_MATCH] = "MATCH",
4765 [RES_CASE_BODY] = "CASE_BODY",
4766 [RES_ESAC ] = "ESAC" ,
4768 [RES_XXXX ] = "XXXX" ,
4769 [RES_SNTX ] = "SNTX" ,
4771 static const char *const CMDTYPE[] = {
4775 # if ENABLE_HUSH_FUNCTIONS
4784 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4785 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4787 while (prn < pi->num_cmds) {
4788 struct command *command = &pi->cmds[prn];
4789 char **argv = command->argv;
4791 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4793 command->assignment_cnt);
4794 if (command->group) {
4795 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4796 CMDTYPE[command->cmd_type],
4799 , " group_as_string:", command->group_as_string
4804 debug_print_tree(command->group, lvl+1);
4808 if (argv) while (*argv) {
4809 fprintf(stderr, " '%s'", *argv);
4812 fprintf(stderr, "\n");
4819 #endif /* debug_print_tree */
4821 /* NB: called by pseudo_exec, and therefore must not modify any
4822 * global data until exec/_exit (we can be a child after vfork!) */
4823 static int run_list(struct pipe *pi)
4825 #if ENABLE_HUSH_CASE
4826 char *case_word = NULL;
4828 #if ENABLE_HUSH_LOOPS
4829 struct pipe *loop_top = NULL;
4830 char **for_lcur = NULL;
4831 char **for_list = NULL;
4833 smallint last_followup;
4835 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4836 smalluint cond_code = 0;
4838 enum { cond_code = 0 };
4841 smallint rword; /* enum reserved_style */
4842 smallint last_rword; /* ditto */
4845 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4848 #if ENABLE_HUSH_LOOPS
4849 /* Check syntax for "for" */
4850 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4851 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4853 /* current word is FOR or IN (BOLD in comments below) */
4854 if (cpipe->next == NULL) {
4855 syntax_error("malformed for");
4857 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4860 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4861 if (cpipe->next->res_word == RES_DO)
4863 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4864 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4865 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4867 syntax_error("malformed for");
4869 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4875 /* Past this point, all code paths should jump to ret: label
4876 * in order to return, no direct "return" statements please.
4877 * This helps to ensure that no memory is leaked. */
4885 last_rword = RES_XXXX;
4887 last_followup = PIPE_SEQ;
4888 rcode = G.last_exitcode;
4890 /* Go through list of pipes, (maybe) executing them. */
4891 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
4895 IF_HAS_KEYWORDS(rword = pi->res_word;)
4896 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4897 rword, cond_code, last_rword);
4898 #if ENABLE_HUSH_LOOPS
4899 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
4900 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
4902 /* start of a loop: remember where loop starts */
4907 /* Still in the same "if...", "then..." or "do..." branch? */
4908 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
4909 if ((rcode == 0 && last_followup == PIPE_OR)
4910 || (rcode != 0 && last_followup == PIPE_AND)
4912 /* It is "<true> || CMD" or "<false> && CMD"
4913 * and we should not execute CMD */
4914 debug_printf_exec("skipped cmd because of || or &&\n");
4915 last_followup = pi->followup;
4919 last_followup = pi->followup;
4920 IF_HAS_KEYWORDS(last_rword = rword;)
4923 if (rword == RES_THEN) {
4924 /* if false; then ... fi has exitcode 0! */
4925 G.last_exitcode = rcode = EXIT_SUCCESS;
4926 /* "if <false> THEN cmd": skip cmd */
4930 if (rword == RES_ELSE || rword == RES_ELIF) {
4931 /* "if <true> then ... ELSE/ELIF cmd":
4932 * skip cmd and all following ones */
4937 #if ENABLE_HUSH_LOOPS
4938 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
4940 /* first loop through for */
4942 static const char encoded_dollar_at[] ALIGN1 = {
4943 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4944 }; /* encoded representation of "$@" */
4945 static const char *const encoded_dollar_at_argv[] = {
4946 encoded_dollar_at, NULL
4947 }; /* argv list with one element: "$@" */
4950 vals = (char**)encoded_dollar_at_argv;
4951 if (pi->next->res_word == RES_IN) {
4952 /* if no variable values after "in" we skip "for" */
4953 if (!pi->next->cmds[0].argv) {
4954 G.last_exitcode = rcode = EXIT_SUCCESS;
4955 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
4958 vals = pi->next->cmds[0].argv;
4959 } /* else: "for var; do..." -> assume "$@" list */
4960 /* create list of variable values */
4961 debug_print_strings("for_list made from", vals);
4962 for_list = expand_strvec_to_strvec(vals);
4963 for_lcur = for_list;
4964 debug_print_strings("for_list", for_list);
4967 /* "for" loop is over, clean up */
4973 /* Insert next value from for_lcur */
4974 /* note: *for_lcur already has quotes removed, $var expanded, etc */
4975 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4978 if (rword == RES_IN) {
4979 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4981 if (rword == RES_DONE) {
4982 continue; /* "done" has no cmds too */
4985 #if ENABLE_HUSH_CASE
4986 if (rword == RES_CASE) {
4987 case_word = expand_strvec_to_string(pi->cmds->argv);
4990 if (rword == RES_MATCH) {
4993 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4995 /* all prev words didn't match, does this one match? */
4996 argv = pi->cmds->argv;
4998 char *pattern = expand_string_to_string(*argv);
4999 /* TODO: which FNM_xxx flags to use? */
5000 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
5002 if (cond_code == 0) { /* match! we will execute this branch */
5003 free(case_word); /* make future "word)" stop */
5011 if (rword == RES_CASE_BODY) { /* inside of a case branch */
5013 continue; /* not matched yet, skip this pipe */
5016 /* Just pressing <enter> in shell should check for jobs.
5017 * OTOH, in non-interactive shell this is useless
5018 * and only leads to extra job checks */
5019 if (pi->num_cmds == 0) {
5020 if (G_interactive_fd)
5021 goto check_jobs_and_continue;
5025 /* After analyzing all keywords and conditions, we decided
5026 * to execute this pipe. NB: have to do checkjobs(NULL)
5027 * after run_pipe to collect any background children,
5028 * even if list execution is to be stopped. */
5029 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
5032 #if ENABLE_HUSH_LOOPS
5033 G.flag_break_continue = 0;
5035 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5037 /* We ran a builtin, function, or group.
5038 * rcode is already known
5039 * and we don't need to wait for anything. */
5040 G.last_exitcode = rcode;
5041 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
5042 check_and_run_traps(0);
5043 #if ENABLE_HUSH_LOOPS
5044 /* Was it "break" or "continue"? */
5045 if (G.flag_break_continue) {
5046 smallint fbc = G.flag_break_continue;
5047 /* We might fall into outer *loop*,
5048 * don't want to break it too */
5050 G.depth_break_continue--;
5051 if (G.depth_break_continue == 0)
5052 G.flag_break_continue = 0;
5053 /* else: e.g. "continue 2" should *break* once, *then* continue */
5054 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
5055 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
5056 goto check_jobs_and_break;
5057 /* "continue": simulate end of loop */
5062 #if ENABLE_HUSH_FUNCTIONS
5063 if (G.flag_return_in_progress == 1) {
5064 /* same as "goto check_jobs_and_break" */
5069 } else if (pi->followup == PIPE_BG) {
5070 /* What does bash do with attempts to background builtins? */
5071 /* even bash 3.2 doesn't do that well with nested bg:
5072 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5073 * I'm NOT treating inner &'s as jobs */
5074 check_and_run_traps(0);
5076 if (G.run_list_level == 1)
5079 /* Last command's pid goes to $! */
5080 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
5081 G.last_exitcode = rcode = EXIT_SUCCESS;
5082 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5085 if (G.run_list_level == 1 && G_interactive_fd) {
5086 /* Waits for completion, then fg's main shell */
5087 rcode = checkjobs_and_fg_shell(pi);
5088 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5089 check_and_run_traps(0);
5092 { /* This one just waits for completion */
5093 rcode = checkjobs(pi);
5094 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5095 check_and_run_traps(0);
5097 G.last_exitcode = rcode;
5101 /* Analyze how result affects subsequent commands */
5103 if (rword == RES_IF || rword == RES_ELIF)
5106 #if ENABLE_HUSH_LOOPS
5107 /* Beware of "while false; true; do ..."! */
5108 if (pi->next && pi->next->res_word == RES_DO) {
5109 if (rword == RES_WHILE) {
5111 /* "while false; do...done" - exitcode 0 */
5112 G.last_exitcode = rcode = EXIT_SUCCESS;
5113 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5114 goto check_jobs_and_break;
5117 if (rword == RES_UNTIL) {
5119 debug_printf_exec(": until expr is true: breaking\n");
5120 check_jobs_and_break:
5128 check_jobs_and_continue:
5135 #if ENABLE_HUSH_LOOPS
5140 #if ENABLE_HUSH_CASE
5144 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5148 /* Select which version we will use */
5149 static int run_and_free_list(struct pipe *pi)
5152 debug_printf_exec("run_and_free_list entered\n");
5154 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5155 rcode = run_list(pi);
5157 /* free_pipe_list has the side effect of clearing memory.
5158 * In the long run that function can be merged with run_list,
5159 * but doing that now would hobble the debugging effort. */
5161 debug_printf_exec("run_and_free_list return %d\n", rcode);
5166 static struct pipe *new_pipe(void)
5169 pi = xzalloc(sizeof(struct pipe));
5170 /*pi->followup = 0; - deliberately invalid value */
5171 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5175 /* Command (member of a pipe) is complete, or we start a new pipe
5176 * if ctx->command is NULL.
5177 * No errors possible here.
5179 static int done_command(struct parse_context *ctx)
5181 /* The command is really already in the pipe structure, so
5182 * advance the pipe counter and make a new, null command. */
5183 struct pipe *pi = ctx->pipe;
5184 struct command *command = ctx->command;
5187 if (IS_NULL_CMD(command)) {
5188 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5192 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5193 //debug_print_tree(ctx->list_head, 20);
5195 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5198 /* Only real trickiness here is that the uncommitted
5199 * command structure is not counted in pi->num_cmds. */
5200 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5201 ctx->command = command = &pi->cmds[pi->num_cmds];
5203 memset(command, 0, sizeof(*command));
5204 return pi->num_cmds; /* used only for 0/nonzero check */
5207 static void done_pipe(struct parse_context *ctx, pipe_style type)
5211 debug_printf_parse("done_pipe entered, followup %d\n", type);
5212 /* Close previous command */
5213 not_null = done_command(ctx);
5214 ctx->pipe->followup = type;
5216 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5217 ctx->ctx_inverted = 0;
5218 ctx->pipe->res_word = ctx->ctx_res_w;
5221 /* Without this check, even just <enter> on command line generates
5222 * tree of three NOPs (!). Which is harmless but annoying.
5223 * IOW: it is safe to do it unconditionally. */
5226 || ctx->ctx_res_w == RES_FI
5228 #if ENABLE_HUSH_LOOPS
5229 || ctx->ctx_res_w == RES_DONE
5230 || ctx->ctx_res_w == RES_FOR
5231 || ctx->ctx_res_w == RES_IN
5233 #if ENABLE_HUSH_CASE
5234 || ctx->ctx_res_w == RES_ESAC
5238 debug_printf_parse("done_pipe: adding new pipe: "
5239 "not_null:%d ctx->ctx_res_w:%d\n",
5240 not_null, ctx->ctx_res_w);
5242 ctx->pipe->next = new_p;
5244 /* RES_THEN, RES_DO etc are "sticky" -
5245 * they remain set for pipes inside if/while.
5246 * This is used to control execution.
5247 * RES_FOR and RES_IN are NOT sticky (needed to support
5248 * cases where variable or value happens to match a keyword):
5250 #if ENABLE_HUSH_LOOPS
5251 if (ctx->ctx_res_w == RES_FOR
5252 || ctx->ctx_res_w == RES_IN)
5253 ctx->ctx_res_w = RES_NONE;
5255 #if ENABLE_HUSH_CASE
5256 if (ctx->ctx_res_w == RES_MATCH)
5257 ctx->ctx_res_w = RES_CASE_BODY;
5258 if (ctx->ctx_res_w == RES_CASE)
5259 ctx->ctx_res_w = RES_CASE_IN;
5261 ctx->command = NULL; /* trick done_command below */
5262 /* Create the memory for command, roughly:
5263 * ctx->pipe->cmds = new struct command;
5264 * ctx->command = &ctx->pipe->cmds[0];
5267 //debug_print_tree(ctx->list_head, 10);
5269 debug_printf_parse("done_pipe return\n");
5272 static void initialize_context(struct parse_context *ctx)
5274 memset(ctx, 0, sizeof(*ctx));
5275 ctx->pipe = ctx->list_head = new_pipe();
5276 /* Create the memory for command, roughly:
5277 * ctx->pipe->cmds = new struct command;
5278 * ctx->command = &ctx->pipe->cmds[0];
5283 /* If a reserved word is found and processed, parse context is modified
5284 * and 1 is returned.
5287 struct reserved_combo {
5290 unsigned char assignment_flag;
5294 FLAG_END = (1 << RES_NONE ),
5296 FLAG_IF = (1 << RES_IF ),
5297 FLAG_THEN = (1 << RES_THEN ),
5298 FLAG_ELIF = (1 << RES_ELIF ),
5299 FLAG_ELSE = (1 << RES_ELSE ),
5300 FLAG_FI = (1 << RES_FI ),
5302 # if ENABLE_HUSH_LOOPS
5303 FLAG_FOR = (1 << RES_FOR ),
5304 FLAG_WHILE = (1 << RES_WHILE),
5305 FLAG_UNTIL = (1 << RES_UNTIL),
5306 FLAG_DO = (1 << RES_DO ),
5307 FLAG_DONE = (1 << RES_DONE ),
5308 FLAG_IN = (1 << RES_IN ),
5310 # if ENABLE_HUSH_CASE
5311 FLAG_MATCH = (1 << RES_MATCH),
5312 FLAG_ESAC = (1 << RES_ESAC ),
5314 FLAG_START = (1 << RES_XXXX ),
5317 static const struct reserved_combo* match_reserved_word(o_string *word)
5319 /* Mostly a list of accepted follow-up reserved words.
5320 * FLAG_END means we are done with the sequence, and are ready
5321 * to turn the compound list into a command.
5322 * FLAG_START means the word must start a new compound list.
5324 static const struct reserved_combo reserved_list[] = {
5326 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5327 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5328 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5329 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5330 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5331 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5333 # if ENABLE_HUSH_LOOPS
5334 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5335 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5336 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5337 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5338 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5339 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5341 # if ENABLE_HUSH_CASE
5342 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5343 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5346 const struct reserved_combo *r;
5348 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5349 if (strcmp(word->data, r->literal) == 0)
5354 /* Return 0: not a keyword, 1: keyword
5356 static int reserved_word(o_string *word, struct parse_context *ctx)
5358 # if ENABLE_HUSH_CASE
5359 static const struct reserved_combo reserved_match = {
5360 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5363 const struct reserved_combo *r;
5367 r = match_reserved_word(word);
5371 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5372 # if ENABLE_HUSH_CASE
5373 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5374 /* "case word IN ..." - IN part starts first MATCH part */
5375 r = &reserved_match;
5378 if (r->flag == 0) { /* '!' */
5379 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5380 syntax_error("! ! command");
5381 ctx->ctx_res_w = RES_SNTX;
5383 ctx->ctx_inverted = 1;
5386 if (r->flag & FLAG_START) {
5387 struct parse_context *old;
5389 old = xmalloc(sizeof(*old));
5390 debug_printf_parse("push stack %p\n", old);
5391 *old = *ctx; /* physical copy */
5392 initialize_context(ctx);
5394 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5395 syntax_error_at(word->data);
5396 ctx->ctx_res_w = RES_SNTX;
5399 /* "{...} fi" is ok. "{...} if" is not
5401 * if { echo foo; } then { echo bar; } fi */
5402 if (ctx->command->group)
5403 done_pipe(ctx, PIPE_SEQ);
5406 ctx->ctx_res_w = r->res;
5407 ctx->old_flag = r->flag;
5408 word->o_assignment = r->assignment_flag;
5410 if (ctx->old_flag & FLAG_END) {
5411 struct parse_context *old;
5413 done_pipe(ctx, PIPE_SEQ);
5414 debug_printf_parse("pop stack %p\n", ctx->stack);
5416 old->command->group = ctx->list_head;
5417 old->command->cmd_type = CMD_NORMAL;
5419 o_addstr(&old->as_string, ctx->as_string.data);
5420 o_free_unsafe(&ctx->as_string);
5421 old->command->group_as_string = xstrdup(old->as_string.data);
5422 debug_printf_parse("pop, remembering as:'%s'\n",
5423 old->command->group_as_string);
5425 *ctx = *old; /* physical copy */
5430 #endif /* HAS_KEYWORDS */
5432 /* Word is complete, look at it and update parsing context.
5433 * Normal return is 0. Syntax errors return 1.
5434 * Note: on return, word is reset, but not o_free'd!
5436 static int done_word(o_string *word, struct parse_context *ctx)
5438 struct command *command = ctx->command;
5440 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5441 if (word->length == 0 && word->o_quoted == 0) {
5442 debug_printf_parse("done_word return 0: true null, ignored\n");
5446 if (ctx->pending_redirect) {
5447 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5448 * only if run as "bash", not "sh" */
5449 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5451 * ...the word that follows the redirection operator
5452 * shall be subjected to tilde expansion, parameter expansion,
5453 * command substitution, arithmetic expansion, and quote
5454 * removal. Pathname expansion shall not be performed
5455 * on the word by a non-interactive shell; an interactive
5456 * shell may perform it, but shall do so only when
5457 * the expansion would result in one word."
5459 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5460 /* Cater for >\file case:
5461 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5462 * Same with heredocs:
5463 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5465 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5466 unbackslash(ctx->pending_redirect->rd_filename);
5467 /* Is it <<"HEREDOC"? */
5468 if (word->o_quoted) {
5469 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5472 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5473 ctx->pending_redirect = NULL;
5475 /* If this word wasn't an assignment, next ones definitely
5476 * can't be assignments. Even if they look like ones. */
5477 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5478 && word->o_assignment != WORD_IS_KEYWORD
5480 word->o_assignment = NOT_ASSIGNMENT;
5482 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5483 command->assignment_cnt++;
5484 word->o_assignment = MAYBE_ASSIGNMENT;
5488 # if ENABLE_HUSH_CASE
5489 if (ctx->ctx_dsemicolon
5490 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5492 /* already done when ctx_dsemicolon was set to 1: */
5493 /* ctx->ctx_res_w = RES_MATCH; */
5494 ctx->ctx_dsemicolon = 0;
5497 if (!command->argv /* if it's the first word... */
5498 # if ENABLE_HUSH_LOOPS
5499 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5500 && ctx->ctx_res_w != RES_IN
5502 # if ENABLE_HUSH_CASE
5503 && ctx->ctx_res_w != RES_CASE
5506 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5507 if (reserved_word(word, ctx)) {
5508 o_reset_to_empty_unquoted(word);
5509 debug_printf_parse("done_word return %d\n",
5510 (ctx->ctx_res_w == RES_SNTX));
5511 return (ctx->ctx_res_w == RES_SNTX);
5513 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5514 if (strcmp(word->data, "export") == 0
5515 # if ENABLE_HUSH_LOCAL
5516 || strcmp(word->data, "local") == 0
5519 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5522 # if ENABLE_HUSH_BASH_COMPAT
5523 if (strcmp(word->data, "[[") == 0) {
5524 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5530 if (command->group) {
5531 /* "{ echo foo; } echo bar" - bad */
5532 syntax_error_at(word->data);
5533 debug_printf_parse("done_word return 1: syntax error, "
5534 "groups and arglists don't mix\n");
5537 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5538 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5539 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5540 /* (otherwise it's known to be not empty and is already safe) */
5542 /* exclude "$@" - it can expand to no word despite "" */
5543 char *p = word->data;
5544 while (p[0] == SPECIAL_VAR_SYMBOL
5545 && (p[1] & 0x7f) == '@'
5546 && p[2] == SPECIAL_VAR_SYMBOL
5550 if (p == word->data || p[0] != '\0') {
5551 /* saw no "$@", or not only "$@" but some
5552 * real text is there too */
5553 /* insert "empty variable" reference, this makes
5554 * e.g. "", $empty"" etc to not disappear */
5555 o_addchr(word, SPECIAL_VAR_SYMBOL);
5556 o_addchr(word, SPECIAL_VAR_SYMBOL);
5559 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5560 debug_print_strings("word appended to argv", command->argv);
5563 #if ENABLE_HUSH_LOOPS
5564 if (ctx->ctx_res_w == RES_FOR) {
5566 || !is_well_formed_var_name(command->argv[0], '\0')
5568 /* bash says just "not a valid identifier" */
5569 syntax_error("not a valid identifier in for");
5572 /* Force FOR to have just one word (variable name) */
5573 /* NB: basically, this makes hush see "for v in ..."
5574 * syntax as if it is "for v; in ...". FOR and IN become
5575 * two pipe structs in parse tree. */
5576 done_pipe(ctx, PIPE_SEQ);
5579 #if ENABLE_HUSH_CASE
5580 /* Force CASE to have just one word */
5581 if (ctx->ctx_res_w == RES_CASE) {
5582 done_pipe(ctx, PIPE_SEQ);
5586 o_reset_to_empty_unquoted(word);
5588 debug_printf_parse("done_word return 0\n");
5593 /* Peek ahead in the input to find out if we have a "&n" construct,
5594 * as in "2>&1", that represents duplicating a file descriptor.
5596 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5597 * REDIRFD_SYNTAX_ERR if syntax error,
5598 * REDIRFD_TO_FILE if no & was seen,
5599 * or the number found.
5602 #define parse_redir_right_fd(as_string, input) \
5603 parse_redir_right_fd(input)
5605 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5611 return REDIRFD_TO_FILE;
5613 ch = i_getch(input); /* get the & */
5614 nommu_addchr(as_string, ch);
5617 ch = i_getch(input);
5618 nommu_addchr(as_string, ch);
5619 return REDIRFD_CLOSE;
5623 while (ch != EOF && isdigit(ch)) {
5624 d = d*10 + (ch-'0');
5626 ch = i_getch(input);
5627 nommu_addchr(as_string, ch);
5632 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5634 bb_error_msg("ambiguous redirect");
5635 return REDIRFD_SYNTAX_ERR;
5638 /* Return code is 0 normal, 1 if a syntax error is detected
5640 static int parse_redirect(struct parse_context *ctx,
5643 struct in_str *input)
5645 struct command *command = ctx->command;
5646 struct redir_struct *redir;
5647 struct redir_struct **redirp;
5650 dup_num = REDIRFD_TO_FILE;
5651 if (style != REDIRECT_HEREDOC) {
5652 /* Check for a '>&1' type redirect */
5653 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5654 if (dup_num == REDIRFD_SYNTAX_ERR)
5657 int ch = i_peek(input);
5658 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5659 if (dup_num) { /* <<-... */
5660 ch = i_getch(input);
5661 nommu_addchr(&ctx->as_string, ch);
5666 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5667 int ch = i_peek(input);
5669 /* >|FILE redirect ("clobbering" >).
5670 * Since we do not support "set -o noclobber" yet,
5671 * >| and > are the same for now. Just eat |.
5673 ch = i_getch(input);
5674 nommu_addchr(&ctx->as_string, ch);
5678 /* Create a new redir_struct and append it to the linked list */
5679 redirp = &command->redirects;
5680 while ((redir = *redirp) != NULL) {
5681 redirp = &(redir->next);
5683 *redirp = redir = xzalloc(sizeof(*redir));
5684 /* redir->next = NULL; */
5685 /* redir->rd_filename = NULL; */
5686 redir->rd_type = style;
5687 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5689 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5690 redir_table[style].descrip);
5692 redir->rd_dup = dup_num;
5693 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5694 /* Erik had a check here that the file descriptor in question
5695 * is legit; I postpone that to "run time"
5696 * A "-" representation of "close me" shows up as a -3 here */
5697 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5698 redir->rd_fd, redir->rd_dup);
5700 /* Set ctx->pending_redirect, so we know what to do at the
5701 * end of the next parsed word. */
5702 ctx->pending_redirect = redir;
5707 /* If a redirect is immediately preceded by a number, that number is
5708 * supposed to tell which file descriptor to redirect. This routine
5709 * looks for such preceding numbers. In an ideal world this routine
5710 * needs to handle all the following classes of redirects...
5711 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5712 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5713 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5714 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5716 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5718 * ... If n is quoted, the number shall not be recognized as part of
5719 * the redirection expression. For example:
5721 * writes the character 2 into file a"
5722 * We are getting it right by setting ->o_quoted on any \<char>
5724 * A -1 return means no valid number was found,
5725 * the caller should use the appropriate default for this redirection.
5727 static int redirect_opt_num(o_string *o)
5731 if (o->data == NULL)
5733 num = bb_strtou(o->data, NULL, 10);
5734 if (errno || num < 0)
5736 o_reset_to_empty_unquoted(o);
5741 #define fetch_till_str(as_string, input, word, skip_tabs) \
5742 fetch_till_str(input, word, skip_tabs)
5744 static char *fetch_till_str(o_string *as_string,
5745 struct in_str *input,
5749 o_string heredoc = NULL_O_STRING;
5755 ch = i_getch(input);
5756 nommu_addchr(as_string, ch);
5758 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5759 heredoc.data[past_EOL] = '\0';
5760 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5761 return heredoc.data;
5764 o_addchr(&heredoc, ch);
5765 past_EOL = heredoc.length;
5768 ch = i_getch(input);
5769 nommu_addchr(as_string, ch);
5770 } while (skip_tabs && ch == '\t');
5771 } while (ch == '\n');
5774 o_free_unsafe(&heredoc);
5777 o_addchr(&heredoc, ch);
5778 nommu_addchr(as_string, ch);
5782 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5783 * and load them all. There should be exactly heredoc_cnt of them.
5785 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5787 struct pipe *pi = ctx->list_head;
5789 while (pi && heredoc_cnt) {
5791 struct command *cmd = pi->cmds;
5793 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5795 cmd->argv ? cmd->argv[0] : "NONE");
5796 for (i = 0; i < pi->num_cmds; i++) {
5797 struct redir_struct *redir = cmd->redirects;
5799 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5800 i, cmd->argv ? cmd->argv[0] : "NONE");
5802 if (redir->rd_type == REDIRECT_HEREDOC) {
5805 redir->rd_type = REDIRECT_HEREDOC2;
5806 /* redir->rd_dup is (ab)used to indicate <<- */
5807 p = fetch_till_str(&ctx->as_string, input,
5808 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5810 syntax_error("unexpected EOF in here document");
5813 free(redir->rd_filename);
5814 redir->rd_filename = p;
5817 redir = redir->next;
5824 /* Should be 0. If it isn't, it's a parse error */
5826 bb_error_msg_and_die("heredoc BUG 2");
5832 #if ENABLE_HUSH_TICK
5833 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5838 char **to_free = NULL;
5842 pid = BB_MMU ? xfork() : xvfork();
5843 if (pid == 0) { /* child */
5844 disable_restore_tty_pgrp_on_exit();
5845 /* Process substitution is not considered to be usual
5846 * 'command execution'.
5847 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5854 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5855 close(channel[0]); /* NB: close _first_, then move fd! */
5856 xmove_fd(channel[1], 1);
5857 /* Prevent it from trying to handle ctrl-z etc */
5858 IF_HUSH_JOB(G.run_list_level = 1;)
5859 /* Awful hack for `trap` or $(trap).
5861 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5862 * contains an example where "trap" is executed in a subshell:
5864 * save_traps=$(trap)
5866 * eval "$save_traps"
5868 * Standard does not say that "trap" in subshell shall print
5869 * parent shell's traps. It only says that its output
5870 * must have suitable form, but then, in the above example
5871 * (which is not supposed to be normative), it implies that.
5873 * bash (and probably other shell) does implement it
5874 * (traps are reset to defaults, but "trap" still shows them),
5875 * but as a result, "trap" logic is hopelessly messed up:
5878 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5879 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5880 * # true | trap <--- trap is in subshell - no output (ditto)
5881 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5882 * trap -- 'echo Ho' SIGWINCH
5883 * # echo `(trap)` <--- in subshell in subshell - output
5884 * trap -- 'echo Ho' SIGWINCH
5885 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5886 * trap -- 'echo Ho' SIGWINCH
5888 * The rules when to forget and when to not forget traps
5889 * get really complex and nonsensical.
5891 * Our solution: ONLY bare $(trap) or `trap` is special.
5893 s = skip_whitespace(s);
5894 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5896 static const char *const argv[] = { NULL, NULL };
5897 builtin_trap((char**)argv);
5898 exit(0); /* not _exit() - we need to fflush */
5901 reset_traps_to_defaults();
5902 parse_and_run_string(s);
5903 _exit(G.last_exitcode);
5905 /* We re-execute after vfork on NOMMU. This makes this script safe:
5906 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5907 * huge=`cat BIG` # was blocking here forever
5910 re_execute_shell(&to_free,
5920 # if ENABLE_HUSH_FAST
5922 //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);
5924 enable_restore_tty_pgrp_on_exit();
5929 close_on_exec_on(channel[0]);
5930 return xfdopen_for_read(channel[0]);
5933 /* Return code is exit status of the process that is run. */
5934 static int process_command_subs(o_string *dest, const char *s)
5937 struct in_str pipe_str;
5939 int status, ch, eol_cnt;
5941 fp = generate_stream_from_string(s, &pid);
5943 /* Now send results of command back into original context */
5944 setup_file_in_str(&pipe_str, fp);
5946 while ((ch = i_getch(&pipe_str)) != EOF) {
5952 o_addchr(dest, '\n');
5955 o_addQchr(dest, ch);
5958 debug_printf("done reading from `cmd` pipe, closing it\n");
5960 /* We need to extract exitcode. Test case
5961 * "true; echo `sleep 1; false` $?"
5963 safe_waitpid(pid, &status, 0);
5964 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5965 return WEXITSTATUS(status);
5967 #endif /* ENABLE_HUSH_TICK */
5969 #if !ENABLE_HUSH_FUNCTIONS
5970 #define parse_group(dest, ctx, input, ch) \
5971 parse_group(ctx, input, ch)
5973 static int parse_group(o_string *dest, struct parse_context *ctx,
5974 struct in_str *input, int ch)
5976 /* dest contains characters seen prior to ( or {.
5977 * Typically it's empty, but for function defs,
5978 * it contains function name (without '()'). */
5979 struct pipe *pipe_list;
5981 struct command *command = ctx->command;
5983 debug_printf_parse("parse_group entered\n");
5984 #if ENABLE_HUSH_FUNCTIONS
5985 if (ch == '(' && !dest->o_quoted) {
5987 if (done_word(dest, ctx))
5990 goto skip; /* (... */
5991 if (command->argv[1]) { /* word word ... (... */
5992 syntax_error_unexpected_ch('(');
5995 /* it is "word(..." or "word (..." */
5997 ch = i_getch(input);
5998 while (ch == ' ' || ch == '\t');
6000 syntax_error_unexpected_ch(ch);
6003 nommu_addchr(&ctx->as_string, ch);
6005 ch = i_getch(input);
6006 while (ch == ' ' || ch == '\t' || ch == '\n');
6008 syntax_error_unexpected_ch(ch);
6011 nommu_addchr(&ctx->as_string, ch);
6012 command->cmd_type = CMD_FUNCDEF;
6017 #if 0 /* Prevented by caller */
6018 if (command->argv /* word [word]{... */
6019 || dest->length /* word{... */
6020 || dest->o_quoted /* ""{... */
6023 debug_printf_parse("parse_group return 1: "
6024 "syntax error, groups and arglists don't mix\n");
6029 #if ENABLE_HUSH_FUNCTIONS
6035 command->cmd_type = CMD_SUBSHELL;
6037 /* bash does not allow "{echo...", requires whitespace */
6038 ch = i_getch(input);
6039 if (ch != ' ' && ch != '\t' && ch != '\n') {
6040 syntax_error_unexpected_ch(ch);
6043 nommu_addchr(&ctx->as_string, ch);
6048 # define as_string NULL
6050 char *as_string = NULL;
6052 pipe_list = parse_stream(&as_string, input, endch);
6055 o_addstr(&ctx->as_string, as_string);
6057 /* empty ()/{} or parse error? */
6058 if (!pipe_list || pipe_list == ERR_PTR) {
6059 /* parse_stream already emitted error msg */
6062 debug_printf_parse("parse_group return 1: "
6063 "parse_stream returned %p\n", pipe_list);
6066 command->group = pipe_list;
6068 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6069 command->group_as_string = as_string;
6070 debug_printf_parse("end of group, remembering as:'%s'\n",
6071 command->group_as_string);
6075 debug_printf_parse("parse_group return 0\n");
6077 /* command remains "open", available for possible redirects */
6080 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6081 /* Subroutines for copying $(...) and `...` things */
6082 static void add_till_backquote(o_string *dest, struct in_str *input);
6084 static void add_till_single_quote(o_string *dest, struct in_str *input)
6087 int ch = i_getch(input);
6089 syntax_error_unterm_ch('\'');
6090 /*xfunc_die(); - redundant */
6097 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6098 static void add_till_double_quote(o_string *dest, struct in_str *input)
6101 int ch = i_getch(input);
6103 syntax_error_unterm_ch('"');
6104 /*xfunc_die(); - redundant */
6108 if (ch == '\\') { /* \x. Copy both chars. */
6110 ch = i_getch(input);
6114 add_till_backquote(dest, input);
6118 //if (ch == '$') ...
6121 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6123 * "Within the backquoted style of command substitution, backslash
6124 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6125 * The search for the matching backquote shall be satisfied by the first
6126 * backquote found without a preceding backslash; during this search,
6127 * if a non-escaped backquote is encountered within a shell comment,
6128 * a here-document, an embedded command substitution of the $(command)
6129 * form, or a quoted string, undefined results occur. A single-quoted
6130 * or double-quoted string that begins, but does not end, within the
6131 * "`...`" sequence produces undefined results."
6133 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6135 static void add_till_backquote(o_string *dest, struct in_str *input)
6138 int ch = i_getch(input);
6140 syntax_error_unterm_ch('`');
6141 /*xfunc_die(); - redundant */
6146 /* \x. Copy both chars unless it is \` */
6147 int ch2 = i_getch(input);
6149 syntax_error_unterm_ch('`');
6150 /*xfunc_die(); - redundant */
6152 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6159 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6160 * quoting and nested ()s.
6161 * "With the $(command) style of command substitution, all characters
6162 * following the open parenthesis to the matching closing parenthesis
6163 * constitute the command. Any valid shell script can be used for command,
6164 * except a script consisting solely of redirections which produces
6165 * unspecified results."
6167 * echo $(echo '(TEST)' BEST) (TEST) BEST
6168 * echo $(echo 'TEST)' BEST) TEST) BEST
6169 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6171 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6172 * can contain arbitrary constructs, just like $(cmd).
6173 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6174 * for ${var:N[:M]} parsing.
6176 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6177 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6180 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6181 # if ENABLE_HUSH_BASH_COMPAT
6182 char end_char2 = end_ch >> 8;
6184 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6187 ch = i_getch(input);
6189 syntax_error_unterm_ch(end_ch);
6190 /*xfunc_die(); - redundant */
6192 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6195 /* we look for closing )) of $((EXPR)) */
6196 if (i_peek(input) == end_ch) {
6197 i_getch(input); /* eat second ')' */
6202 if (ch == '(' || ch == '{') {
6203 ch = (ch == '(' ? ')' : '}');
6204 add_till_closing_bracket(dest, input, ch);
6209 add_till_single_quote(dest, input);
6214 add_till_double_quote(dest, input);
6219 add_till_backquote(dest, input);
6224 /* \x. Copy verbatim. Important for \(, \) */
6225 ch = i_getch(input);
6227 syntax_error_unterm_ch(')');
6228 /*xfunc_die(); - redundant */
6236 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6238 /* Return code: 0 for OK, 1 for syntax error */
6240 #define parse_dollar(as_string, dest, input) \
6241 parse_dollar(dest, input)
6242 #define as_string NULL
6244 static int parse_dollar(o_string *as_string,
6246 struct in_str *input)
6248 int ch = i_peek(input); /* first character after the $ */
6249 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6251 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6253 ch = i_getch(input);
6254 nommu_addchr(as_string, ch);
6256 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6258 debug_printf_parse(": '%c'\n", ch);
6259 o_addchr(dest, ch | quote_mask);
6262 if (!isalnum(ch) && ch != '_')
6264 ch = i_getch(input);
6265 nommu_addchr(as_string, ch);
6267 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6268 } else if (isdigit(ch)) {
6270 ch = i_getch(input);
6271 nommu_addchr(as_string, ch);
6272 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6273 debug_printf_parse(": '%c'\n", ch);
6274 o_addchr(dest, ch | quote_mask);
6275 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6276 } else switch (ch) {
6278 case '!': /* last bg pid */
6279 case '?': /* last exit code */
6280 case '#': /* number of args */
6281 case '*': /* args */
6282 case '@': /* args */
6283 goto make_one_char_var;
6285 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6287 ch = i_getch(input); /* eat '{' */
6288 nommu_addchr(as_string, ch);
6290 ch = i_getch(input); /* first char after '{' */
6291 nommu_addchr(as_string, ch);
6292 /* It should be ${?}, or ${#var},
6293 * or even ${?+subst} - operator acting on a special variable,
6294 * or the beginning of variable name.
6296 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6298 syntax_error_unterm_str("${name}");
6299 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6304 /* It's possible to just call add_till_closing_bracket() at this point.
6305 * However, this regresses some of our testsuite cases
6306 * which check invalid constructs like ${%}.
6307 * Oh well... let's check that the var name part is fine... */
6313 debug_printf_parse(": '%c'\n", ch);
6315 ch = i_getch(input);
6316 nommu_addchr(as_string, ch);
6320 if (!isalnum(ch) && ch != '_') {
6322 unsigned char last_ch;
6323 /* handle parameter expansions
6324 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6326 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6327 goto bad_dollar_syntax;
6330 /* Eat everything until closing '}' (or ':') */
6332 if (ENABLE_HUSH_BASH_COMPAT
6334 && !strchr("%#:-=+?"+3, i_peek(input))
6336 /* It's ${var:N[:M]} thing */
6337 end_ch = '}' * 0x100 + ':';
6342 #if ENABLE_HUSH_DOLLAR_OPS
6343 last_ch = add_till_closing_bracket(dest, input, end_ch);
6345 #error Simple code to only allow ${var} is not implemented
6348 o_addstr(as_string, dest->data + pos);
6349 o_addchr(as_string, last_ch);
6352 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6353 /* close the first block: */
6354 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6355 /* while parsing N from ${var:N[:M]}... */
6356 if ((end_ch & 0xff) == last_ch) {
6357 /* ...got ':' - parse the rest */
6361 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6362 o_addstr(dest, "999999999");
6367 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6370 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6374 ch = i_getch(input);
6375 nommu_addchr(as_string, ch);
6376 # if ENABLE_SH_MATH_SUPPORT
6377 if (i_peek(input) == '(') {
6378 ch = i_getch(input);
6379 nommu_addchr(as_string, ch);
6380 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6381 o_addchr(dest, /*quote_mask |*/ '+');
6384 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6386 o_addstr(as_string, dest->data + pos);
6387 o_addchr(as_string, ')');
6388 o_addchr(as_string, ')');
6390 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6394 # if ENABLE_HUSH_TICK
6395 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6396 o_addchr(dest, quote_mask | '`');
6399 add_till_closing_bracket(dest, input, ')');
6401 o_addstr(as_string, dest->data + pos);
6402 o_addchr(as_string, ')');
6404 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6410 ch = i_getch(input);
6411 nommu_addchr(as_string, ch);
6413 if (isalnum(ch)) { /* it's $_name or $_123 */
6418 /* TODO: $_ and $-: */
6419 /* $_ Shell or shell script name; or last argument of last command
6420 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6421 * but in command's env, set to full pathname used to invoke it */
6422 /* $- Option flags set by set builtin or shell options (-i etc) */
6424 o_addQchr(dest, '$');
6426 debug_printf_parse("parse_dollar return 0\n");
6432 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6433 parse_stream_dquoted(dest, input, dquote_end)
6434 #define as_string NULL
6436 static int parse_stream_dquoted(o_string *as_string,
6438 struct in_str *input,
6445 ch = i_getch(input);
6447 nommu_addchr(as_string, ch);
6448 if (ch == dquote_end) { /* may be only '"' or EOF */
6449 if (dest->o_assignment == NOT_ASSIGNMENT)
6450 dest->o_escape ^= 1;
6451 debug_printf_parse("parse_stream_dquoted return 0\n");
6454 /* note: can't move it above ch == dquote_end check! */
6456 syntax_error_unterm_ch('"');
6457 /*xfunc_die(); - redundant */
6461 next = i_peek(input);
6463 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6464 ch, ch, dest->o_escape);
6467 syntax_error("\\<eof>");
6471 * "The backslash retains its special meaning [in "..."]
6472 * only when followed by one of the following characters:
6473 * $, `, ", \, or <newline>. A double quote may be quoted
6474 * within double quotes by preceding it with a backslash."
6476 if (strchr("$`\"\\\n", next) != NULL) {
6477 ch = i_getch(input);
6479 o_addqchr(dest, ch);
6480 nommu_addchr(as_string, ch);
6483 o_addqchr(dest, '\\');
6484 nommu_addchr(as_string, '\\');
6489 if (parse_dollar(as_string, dest, input) != 0) {
6490 debug_printf_parse("parse_stream_dquoted return 1: "
6491 "parse_dollar returned non-0\n");
6496 #if ENABLE_HUSH_TICK
6498 //unsigned pos = dest->length;
6499 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6500 o_addchr(dest, 0x80 | '`');
6501 add_till_backquote(dest, input);
6502 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6503 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6507 o_addQchr(dest, ch);
6509 && (dest->o_assignment == MAYBE_ASSIGNMENT
6510 || dest->o_assignment == WORD_IS_KEYWORD)
6511 && is_well_formed_var_name(dest->data, '=')
6513 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6520 * Scan input until EOF or end_trigger char.
6521 * Return a list of pipes to execute, or NULL on EOF
6522 * or if end_trigger character is met.
6523 * On syntax error, exit is shell is not interactive,
6524 * reset parsing machinery and start parsing anew,
6525 * or return ERR_PTR.
6527 static struct pipe *parse_stream(char **pstring,
6528 struct in_str *input,
6531 struct parse_context ctx;
6532 o_string dest = NULL_O_STRING;
6536 /* Double-quote state is handled in the state variable is_in_dquote.
6537 * A single-quote triggers a bypass of the main loop until its mate is
6538 * found. When recursing, quote state is passed in via dest->o_escape.
6540 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6541 end_trigger ? end_trigger : 'X');
6544 /* If very first arg is "" or '', dest.data may end up NULL.
6545 * Preventing this: */
6546 o_addchr(&dest, '\0');
6549 G.ifs = get_local_var_value("IFS");
6554 #if ENABLE_HUSH_INTERACTIVE
6555 input->promptmode = 0; /* PS1 */
6557 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6558 initialize_context(&ctx);
6563 const char *is_special;
6567 redir_type redir_style;
6570 /* dest.o_quoted = 1; - already is (see below) */
6571 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6574 /* We reached closing '"' */
6577 ch = i_getch(input);
6578 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6579 ch, ch, dest.o_escape);
6584 syntax_error_unterm_str("here document");
6587 /* end_trigger == '}' case errors out earlier,
6588 * checking only ')' */
6589 if (end_trigger == ')') {
6590 syntax_error_unterm_ch('('); /* exits */
6591 /* goto parse_error; */
6594 if (done_word(&dest, &ctx)) {
6598 done_pipe(&ctx, PIPE_SEQ);
6600 /* If we got nothing... */
6601 /* (this makes bare "&" cmd a no-op.
6602 * bash says: "syntax error near unexpected token '&'") */
6603 if (pi->num_cmds == 0
6604 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6610 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6612 *pstring = ctx.as_string.data;
6614 o_free_unsafe(&ctx.as_string);
6617 debug_printf_parse("parse_stream return %p\n", pi);
6620 nommu_addchr(&ctx.as_string, ch);
6624 next = i_peek(input);
6626 is_special = "{}<>;&|()#'" /* special outside of "str" */
6627 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6628 /* Are { and } special here? */
6629 if (ctx.command->argv /* word [word]{... - non-special */
6630 || dest.length /* word{... - non-special */
6631 || dest.o_quoted /* ""{... - non-special */
6632 || (next != ';' /* }; - special */
6633 && next != ')' /* }) - special */
6634 && next != '&' /* }& and }&& ... - special */
6635 && next != '|' /* }|| ... - special */
6636 && !strchr(G.ifs, next) /* {word - non-special */
6639 /* They are not special, skip "{}" */
6642 is_special = strchr(is_special, ch);
6643 is_ifs = strchr(G.ifs, ch);
6645 if (!is_special && !is_ifs) { /* ordinary char */
6647 o_addQchr(&dest, ch);
6648 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6649 || dest.o_assignment == WORD_IS_KEYWORD)
6651 && is_well_formed_var_name(dest.data, '=')
6653 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6659 if (done_word(&dest, &ctx)) {
6663 #if ENABLE_HUSH_CASE
6664 /* "case ... in <newline> word) ..." -
6665 * newlines are ignored (but ';' wouldn't be) */
6666 if (ctx.command->argv == NULL
6667 && ctx.ctx_res_w == RES_MATCH
6672 /* Treat newline as a command separator. */
6673 done_pipe(&ctx, PIPE_SEQ);
6674 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6676 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6681 dest.o_assignment = MAYBE_ASSIGNMENT;
6683 /* note: if (is_ifs) continue;
6684 * will still trigger for us */
6688 /* "cmd}" or "cmd }..." without semicolon or &:
6689 * } is an ordinary char in this case, even inside { cmd; }
6690 * Pathological example: { ""}; } should exec "}" cmd
6693 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6694 || dest.length != 0 /* word} */
6695 || dest.o_quoted /* ""} */
6699 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6700 goto skip_end_trigger;
6701 /* else: } does terminate a group */
6704 if (end_trigger && end_trigger == ch
6705 && (ch != ';' || heredoc_cnt == 0)
6706 #if ENABLE_HUSH_CASE
6708 || ctx.ctx_res_w != RES_MATCH
6709 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6714 /* This is technically valid:
6715 * { cat <<HERE; }; echo Ok
6719 * but we don't support this.
6720 * We require heredoc to be in enclosing {}/(),
6723 syntax_error_unterm_str("here document");
6726 if (done_word(&dest, &ctx)) {
6729 done_pipe(&ctx, PIPE_SEQ);
6730 dest.o_assignment = MAYBE_ASSIGNMENT;
6731 /* Do we sit outside of any if's, loops or case's? */
6733 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6737 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6739 *pstring = ctx.as_string.data;
6741 o_free_unsafe(&ctx.as_string);
6744 debug_printf_parse("parse_stream return %p: "
6745 "end_trigger char found\n",
6747 return ctx.list_head;
6754 /* Catch <, > before deciding whether this word is
6755 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6758 redir_fd = redirect_opt_num(&dest);
6759 if (done_word(&dest, &ctx)) {
6762 redir_style = REDIRECT_OVERWRITE;
6764 redir_style = REDIRECT_APPEND;
6765 ch = i_getch(input);
6766 nommu_addchr(&ctx.as_string, ch);
6769 else if (next == '(') {
6770 syntax_error(">(process) not supported");
6774 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6776 continue; /* back to top of while (1) */
6778 redir_fd = redirect_opt_num(&dest);
6779 if (done_word(&dest, &ctx)) {
6782 redir_style = REDIRECT_INPUT;
6784 redir_style = REDIRECT_HEREDOC;
6786 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6787 ch = i_getch(input);
6788 nommu_addchr(&ctx.as_string, ch);
6789 } else if (next == '>') {
6790 redir_style = REDIRECT_IO;
6791 ch = i_getch(input);
6792 nommu_addchr(&ctx.as_string, ch);
6795 else if (next == '(') {
6796 syntax_error("<(process) not supported");
6800 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6802 continue; /* back to top of while (1) */
6805 if (dest.o_assignment == MAYBE_ASSIGNMENT
6806 /* check that we are not in word in "a=1 2>word b=1": */
6807 && !ctx.pending_redirect
6809 /* ch is a special char and thus this word
6810 * cannot be an assignment */
6811 dest.o_assignment = NOT_ASSIGNMENT;
6814 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6818 if (dest.length == 0) {
6821 if (ch == EOF || ch == '\n')
6824 /* note: we do not add it to &ctx.as_string */
6826 nommu_addchr(&ctx.as_string, '\n');
6828 o_addQchr(&dest, ch);
6833 syntax_error("\\<eof>");
6836 ch = i_getch(input);
6838 o_addchr(&dest, '\\');
6839 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6840 o_addchr(&dest, ch);
6841 nommu_addchr(&ctx.as_string, ch);
6842 /* Example: echo Hello \2>file
6843 * we need to know that word 2 is quoted */
6848 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6849 ctx.as_string.data[--ctx.as_string.length] = '\0';
6854 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6855 debug_printf_parse("parse_stream parse error: "
6856 "parse_dollar returned non-0\n");
6863 ch = i_getch(input);
6865 syntax_error_unterm_ch('\'');
6866 /*xfunc_die(); - redundant */
6868 nommu_addchr(&ctx.as_string, ch);
6871 o_addqchr(&dest, ch);
6876 is_in_dquote ^= 1; /* invert */
6877 if (dest.o_assignment == NOT_ASSIGNMENT)
6880 #if ENABLE_HUSH_TICK
6884 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6885 o_addchr(&dest, '`');
6887 add_till_backquote(&dest, input);
6889 o_addstr(&ctx.as_string, dest.data + pos);
6890 o_addchr(&ctx.as_string, '`');
6892 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6893 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
6898 #if ENABLE_HUSH_CASE
6901 if (done_word(&dest, &ctx)) {
6904 done_pipe(&ctx, PIPE_SEQ);
6905 #if ENABLE_HUSH_CASE
6906 /* Eat multiple semicolons, detect
6907 * whether it means something special */
6912 ch = i_getch(input);
6913 nommu_addchr(&ctx.as_string, ch);
6914 if (ctx.ctx_res_w == RES_CASE_BODY) {
6915 ctx.ctx_dsemicolon = 1;
6916 ctx.ctx_res_w = RES_MATCH;
6922 /* We just finished a cmd. New one may start
6923 * with an assignment */
6924 dest.o_assignment = MAYBE_ASSIGNMENT;
6927 if (done_word(&dest, &ctx)) {
6931 ch = i_getch(input);
6932 nommu_addchr(&ctx.as_string, ch);
6933 done_pipe(&ctx, PIPE_AND);
6935 done_pipe(&ctx, PIPE_BG);
6939 if (done_word(&dest, &ctx)) {
6942 #if ENABLE_HUSH_CASE
6943 if (ctx.ctx_res_w == RES_MATCH)
6944 break; /* we are in case's "word | word)" */
6946 if (next == '|') { /* || */
6947 ch = i_getch(input);
6948 nommu_addchr(&ctx.as_string, ch);
6949 done_pipe(&ctx, PIPE_OR);
6951 /* we could pick up a file descriptor choice here
6952 * with redirect_opt_num(), but bash doesn't do it.
6953 * "echo foo 2| cat" yields "foo 2". */
6956 o_reset_to_empty_unquoted(&ctx.as_string);
6961 #if ENABLE_HUSH_CASE
6962 /* "case... in [(]word)..." - skip '(' */
6963 if (ctx.ctx_res_w == RES_MATCH
6964 && ctx.command->argv == NULL /* not (word|(... */
6965 && dest.length == 0 /* not word(... */
6966 && dest.o_quoted == 0 /* not ""(... */
6972 if (parse_group(&dest, &ctx, input, ch) != 0) {
6977 #if ENABLE_HUSH_CASE
6978 if (ctx.ctx_res_w == RES_MATCH)
6982 /* proper use of this character is caught by end_trigger:
6983 * if we see {, we call parse_group(..., end_trigger='}')
6984 * and it will match } earlier (not here). */
6985 syntax_error_unexpected_ch(ch);
6989 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
6995 struct parse_context *pctx;
6996 IF_HAS_KEYWORDS(struct parse_context *p2;)
6998 /* Clean up allocated tree.
6999 * Sample for finding leaks on syntax error recovery path.
7000 * Run it from interactive shell, watch pmap `pidof hush`.
7001 * while if false; then false; fi; do break; fi
7002 * Samples to catch leaks at execution:
7003 * while if (true | {true;}); then echo ok; fi; do break; done
7004 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
7008 /* Update pipe/command counts,
7009 * otherwise freeing may miss some */
7010 done_pipe(pctx, PIPE_SEQ);
7011 debug_printf_clean("freeing list %p from ctx %p\n",
7012 pctx->list_head, pctx);
7013 debug_print_tree(pctx->list_head, 0);
7014 free_pipe_list(pctx->list_head);
7015 debug_printf_clean("freed list %p\n", pctx->list_head);
7017 o_free_unsafe(&pctx->as_string);
7019 IF_HAS_KEYWORDS(p2 = pctx->stack;)
7023 IF_HAS_KEYWORDS(pctx = p2;)
7024 } while (HAS_KEYWORDS && pctx);
7025 /* Free text, clear all dest fields */
7027 /* If we are not in top-level parse, we return,
7028 * our caller will propagate error.
7030 if (end_trigger != ';') {
7038 /* Discard cached input, force prompt */
7040 IF_HUSH_INTERACTIVE(input->promptme = 1;)
7045 /* Executing from string: eval, sh -c '...'
7046 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7047 * end_trigger controls how often we stop parsing
7048 * NUL: parse all, execute, return
7049 * ';': parse till ';' or newline, execute, repeat till EOF
7051 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7053 /* Why we need empty flag?
7054 * An obscure corner case "false; ``; echo $?":
7055 * empty command in `` should still set $? to 0.
7056 * But we can't just set $? to 0 at the start,
7057 * this breaks "false; echo `echo $?`" case.
7061 struct pipe *pipe_list;
7063 pipe_list = parse_stream(NULL, inp, end_trigger);
7064 if (!pipe_list) { /* EOF */
7066 G.last_exitcode = 0;
7069 debug_print_tree(pipe_list, 0);
7070 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7071 run_and_free_list(pipe_list);
7076 static void parse_and_run_string(const char *s)
7078 struct in_str input;
7079 setup_string_in_str(&input, s);
7080 parse_and_run_stream(&input, '\0');
7083 static void parse_and_run_file(FILE *f)
7085 struct in_str input;
7086 setup_file_in_str(&input, f);
7087 parse_and_run_stream(&input, ';');
7090 /* Called a few times only (or even once if "sh -c") */
7091 static void init_sigmasks(void)
7095 sigset_t old_blocked_set;
7097 if (!G.inherited_set_is_saved) {
7098 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7099 G.inherited_set = G.blocked_set;
7101 old_blocked_set = G.blocked_set;
7103 mask = (1 << SIGQUIT);
7104 if (G_interactive_fd) {
7105 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7106 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7107 mask |= SPECIAL_JOB_SIGS;
7109 G.non_DFL_mask = mask;
7114 sigaddset(&G.blocked_set, sig);
7118 sigdelset(&G.blocked_set, SIGCHLD);
7120 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7121 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7123 /* POSIX allows shell to re-enable SIGCHLD
7124 * even if it was SIG_IGN on entry */
7125 #if ENABLE_HUSH_FAST
7126 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7127 if (!G.inherited_set_is_saved)
7128 signal(SIGCHLD, SIGCHLD_handler);
7130 if (!G.inherited_set_is_saved)
7131 signal(SIGCHLD, SIG_DFL);
7134 G.inherited_set_is_saved = 1;
7139 static void maybe_set_to_sigexit(int sig)
7141 void (*handler)(int);
7142 /* non_DFL_mask'ed signals are, well, masked,
7143 * no need to set handler for them.
7145 if (!((G.non_DFL_mask >> sig) & 1)) {
7146 handler = signal(sig, sigexit);
7147 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7148 signal(sig, handler);
7151 /* Set handlers to restore tty pgrp and exit */
7152 static void set_fatal_handlers(void)
7154 /* We _must_ restore tty pgrp on fatal signals */
7156 maybe_set_to_sigexit(SIGILL );
7157 maybe_set_to_sigexit(SIGFPE );
7158 maybe_set_to_sigexit(SIGBUS );
7159 maybe_set_to_sigexit(SIGSEGV);
7160 maybe_set_to_sigexit(SIGTRAP);
7161 } /* else: hush is perfect. what SEGV? */
7162 maybe_set_to_sigexit(SIGABRT);
7163 /* bash 3.2 seems to handle these just like 'fatal' ones */
7164 maybe_set_to_sigexit(SIGPIPE);
7165 maybe_set_to_sigexit(SIGALRM);
7166 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7167 * if we aren't interactive... but in this case
7168 * we never want to restore pgrp on exit, and this fn is not called */
7169 /*maybe_set_to_sigexit(SIGHUP );*/
7170 /*maybe_set_to_sigexit(SIGTERM);*/
7171 /*maybe_set_to_sigexit(SIGINT );*/
7175 static int set_mode(const char cstate, const char mode)
7177 int state = (cstate == '-' ? 1 : 0);
7179 case 'n': G.n_mode = state; break;
7180 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7181 default: return EXIT_FAILURE;
7183 return EXIT_SUCCESS;
7186 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7187 int hush_main(int argc, char **argv)
7189 static const struct variable const_shell_ver = {
7191 .varstr = (char*)hush_version_str,
7192 .max_len = 1, /* 0 can provoke free(name) */
7197 unsigned builtin_argc;
7199 struct variable *cur_var;
7202 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7203 G.last_exitcode = EXIT_SUCCESS;
7205 G.argv0_for_re_execing = argv[0];
7207 /* Deal with HUSH_VERSION */
7208 G.shell_ver = const_shell_ver; /* copying struct here */
7209 G.top_var = &G.shell_ver;
7210 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7211 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7212 /* Initialize our shell local variables with the values
7213 * currently living in the environment */
7214 cur_var = G.top_var;
7217 char *value = strchr(*e, '=');
7218 if (value) { /* paranoia */
7219 cur_var->next = xzalloc(sizeof(*cur_var));
7220 cur_var = cur_var->next;
7221 cur_var->varstr = *e;
7222 cur_var->max_len = strlen(*e);
7223 cur_var->flg_export = 1;
7227 /* reinstate HUSH_VERSION */
7228 debug_printf_env("putenv '%s'\n", hush_version_str);
7229 putenv((char *)hush_version_str);
7232 set_pwd_var(/*exp:*/ 1);
7233 /* bash also exports SHLVL and _,
7234 * and sets (but doesn't export) the following variables:
7236 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7237 * BASH_VERSION='3.2.0(1)-release'
7239 * MACHTYPE=i386-pc-linux-gnu
7241 * HOSTNAME=<xxxxxxxxxx>
7242 * PPID=<NNNNN> - we also do it elsewhere
7253 * PIPESTATUS=([0]="0")
7254 * HISTFILE=/<xxx>/.bash_history
7258 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7260 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7270 #if ENABLE_FEATURE_EDITING
7271 G.line_input_state = new_line_input_t(FOR_SHELL);
7273 G.global_argc = argc;
7274 G.global_argv = argv;
7275 /* Initialize some more globals to non-zero values */
7276 cmdedit_update_prompt();
7278 if (setjmp(die_jmp)) {
7279 /* xfunc has failed! die die die */
7280 /* no EXIT traps, this is an escape hatch! */
7282 hush_exit(xfunc_error_retval);
7285 /* Shell is non-interactive at first. We need to call
7286 * init_sigmasks() if we are going to execute "sh <script>",
7287 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7288 * If we later decide that we are interactive, we run init_sigmasks()
7289 * in order to intercept (more) signals.
7293 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7296 opt = getopt(argc, argv, "+c:xins"
7299 # if ENABLE_HUSH_FUNCTIONS
7309 * sh ... -c 'script'
7310 * sh ... -c 'script' ARG0 [ARG1...]
7311 * On NOMMU, if builtin_argc != 0,
7312 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7313 * "" needs to be replaced with NULL
7314 * and BARGV vector fed to builtin function.
7315 * Note: the form without ARG0 never happens:
7316 * sh ... -c 'builtin' BARGV... ""
7319 G.root_pid = getpid();
7320 G.root_ppid = getppid();
7322 G.global_argv = argv + optind;
7323 G.global_argc = argc - optind;
7325 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7326 const struct built_in_command *x;
7329 x = find_builtin(optarg);
7330 if (x) { /* paranoia */
7331 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7332 G.global_argv += builtin_argc;
7333 G.global_argv[-1] = NULL; /* replace "" */
7334 G.last_exitcode = x->b_function(argv + optind - 1);
7338 if (!G.global_argv[0]) {
7339 /* -c 'script' (no params): prevent empty $0 */
7340 G.global_argv--; /* points to argv[i] of 'script' */
7341 G.global_argv[0] = argv[0];
7343 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7345 parse_and_run_string(optarg);
7348 /* Well, we cannot just declare interactiveness,
7349 * we have to have some stuff (ctty, etc) */
7350 /* G_interactive_fd++; */
7353 /* "-s" means "read from stdin", but this is how we always
7354 * operate, so simply do nothing here. */
7357 case '<': /* "big heredoc" support */
7358 full_write1_str(optarg);
7361 unsigned long long empty_trap_mask;
7363 G.root_pid = bb_strtou(optarg, &optarg, 16);
7365 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7367 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7369 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7371 builtin_argc = bb_strtou(optarg, &optarg, 16);
7373 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7374 if (empty_trap_mask != 0) {
7377 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7378 for (sig = 1; sig < NSIG; sig++) {
7379 if (empty_trap_mask & (1LL << sig)) {
7380 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7381 sigaddset(&G.blocked_set, sig);
7384 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7386 # if ENABLE_HUSH_LOOPS
7388 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7394 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7396 # if ENABLE_HUSH_FUNCTIONS
7398 struct function *funcp = new_function(optarg);
7399 /* funcp->name is already set to optarg */
7400 /* funcp->body is set to NULL. It's a special case. */
7401 funcp->body_as_string = argv[optind];
7409 if (set_mode('-', opt) == 0) /* no error */
7413 fprintf(stderr, "Usage: sh [FILE]...\n"
7414 " or: sh -c command [args]...\n\n");
7420 } /* option parsing loop */
7423 G.root_pid = getpid();
7424 G.root_ppid = getppid();
7427 /* If we are login shell... */
7428 if (argv[0] && argv[0][0] == '-') {
7430 debug_printf("sourcing /etc/profile\n");
7431 input = fopen_for_read("/etc/profile");
7432 if (input != NULL) {
7433 close_on_exec_on(fileno(input));
7435 parse_and_run_file(input);
7438 /* bash: after sourcing /etc/profile,
7439 * tries to source (in the given order):
7440 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7441 * stopping on first found. --noprofile turns this off.
7442 * bash also sources ~/.bash_logout on exit.
7443 * If called as sh, skips .bash_XXX files.
7450 * "bash <script>" (which is never interactive (unless -i?))
7451 * sources $BASH_ENV here (without scanning $PATH).
7452 * If called as sh, does the same but with $ENV.
7454 debug_printf("running script '%s'\n", argv[optind]);
7455 G.global_argv = argv + optind;
7456 G.global_argc = argc - optind;
7457 input = xfopen_for_read(argv[optind]);
7458 close_on_exec_on(fileno(input));
7460 parse_and_run_file(input);
7461 #if ENABLE_FEATURE_CLEAN_UP
7467 /* Up to here, shell was non-interactive. Now it may become one.
7468 * NB: don't forget to (re)run init_sigmasks() as needed.
7471 /* A shell is interactive if the '-i' flag was given,
7472 * or if all of the following conditions are met:
7474 * no arguments remaining or the -s flag given
7475 * standard input is a terminal
7476 * standard output is a terminal
7477 * Refer to Posix.2, the description of the 'sh' utility.
7480 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7481 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7482 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7483 if (G_saved_tty_pgrp < 0)
7484 G_saved_tty_pgrp = 0;
7486 /* try to dup stdin to high fd#, >= 255 */
7487 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7488 if (G_interactive_fd < 0) {
7489 /* try to dup to any fd */
7490 G_interactive_fd = dup(STDIN_FILENO);
7491 if (G_interactive_fd < 0) {
7493 G_interactive_fd = 0;
7494 G_saved_tty_pgrp = 0;
7497 // TODO: track & disallow any attempts of user
7498 // to (inadvertently) close/redirect G_interactive_fd
7500 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7501 if (G_interactive_fd) {
7502 close_on_exec_on(G_interactive_fd);
7504 if (G_saved_tty_pgrp) {
7505 /* If we were run as 'hush &', sleep until we are
7506 * in the foreground (tty pgrp == our pgrp).
7507 * If we get started under a job aware app (like bash),
7508 * make sure we are now in charge so we don't fight over
7509 * who gets the foreground */
7511 pid_t shell_pgrp = getpgrp();
7512 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7513 if (G_saved_tty_pgrp == shell_pgrp)
7515 /* send TTIN to ourself (should stop us) */
7516 kill(- shell_pgrp, SIGTTIN);
7520 /* Block some signals */
7523 if (G_saved_tty_pgrp) {
7524 /* Set other signals to restore saved_tty_pgrp */
7525 set_fatal_handlers();
7526 /* Put ourselves in our own process group
7527 * (bash, too, does this only if ctty is available) */
7528 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7529 /* Grab control of the terminal */
7530 tcsetpgrp(G_interactive_fd, getpid());
7532 /* -1 is special - makes xfuncs longjmp, not exit
7533 * (we reset die_sleep = 0 whereever we [v]fork) */
7534 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7538 #elif ENABLE_HUSH_INTERACTIVE
7539 /* No job control compiled in, only prompt/line editing */
7540 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7541 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7542 if (G_interactive_fd < 0) {
7543 /* try to dup to any fd */
7544 G_interactive_fd = dup(STDIN_FILENO);
7545 if (G_interactive_fd < 0)
7547 G_interactive_fd = 0;
7550 if (G_interactive_fd) {
7551 close_on_exec_on(G_interactive_fd);
7555 /* We have interactiveness code disabled */
7559 * if interactive but not a login shell, sources ~/.bashrc
7560 * (--norc turns this off, --rcfile <file> overrides)
7563 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7564 /* note: ash and hush share this string */
7565 printf("\n\n%s %s\n"
7566 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7569 "hush - the humble shell"
7573 parse_and_run_file(stdin);
7576 #if ENABLE_FEATURE_CLEAN_UP
7577 if (G.cwd != bb_msg_unknown)
7579 cur_var = G.top_var->next;
7581 struct variable *tmp = cur_var;
7582 if (!cur_var->max_len)
7583 free(cur_var->varstr);
7584 cur_var = cur_var->next;
7588 hush_exit(G.last_exitcode);
7593 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7594 int lash_main(int argc, char **argv)
7596 bb_error_msg("lash is deprecated, please use hush instead");
7597 return hush_main(argc, argv);
7602 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7603 int msh_main(int argc, char **argv)
7605 //bb_error_msg("msh is deprecated, please use hush instead");
7606 return hush_main(argc, argv);
7614 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7619 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7626 return applet_main_func(argc, argv - argc);
7629 static int FAST_FUNC builtin_test(char **argv)
7631 return run_applet_main(argv, test_main);
7634 static int FAST_FUNC builtin_echo(char **argv)
7636 return run_applet_main(argv, echo_main);
7640 static int FAST_FUNC builtin_printf(char **argv)
7642 return run_applet_main(argv, printf_main);
7646 static char **skip_dash_dash(char **argv)
7649 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7654 static int FAST_FUNC builtin_eval(char **argv)
7656 int rcode = EXIT_SUCCESS;
7658 argv = skip_dash_dash(argv);
7660 char *str = expand_strvec_to_string(argv);
7662 * eval "echo Hi; done" ("done" is syntax error):
7663 * "echo Hi" will not execute too.
7665 parse_and_run_string(str);
7667 rcode = G.last_exitcode;
7672 static int FAST_FUNC builtin_cd(char **argv)
7676 argv = skip_dash_dash(argv);
7678 if (newdir == NULL) {
7679 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7680 * bash says "bash: cd: HOME not set" and does nothing
7683 const char *home = get_local_var_value("HOME");
7684 newdir = home ? home : "/";
7686 if (chdir(newdir)) {
7687 /* Mimic bash message exactly */
7688 bb_perror_msg("cd: %s", newdir);
7689 return EXIT_FAILURE;
7691 /* Read current dir (get_cwd(1) is inside) and set PWD.
7692 * Note: do not enforce exporting. If PWD was unset or unexported,
7693 * set it again, but do not export. bash does the same.
7695 set_pwd_var(/*exp:*/ 0);
7696 return EXIT_SUCCESS;
7699 static int FAST_FUNC builtin_exec(char **argv)
7701 argv = skip_dash_dash(argv);
7702 if (argv[0] == NULL)
7703 return EXIT_SUCCESS; /* bash does this */
7705 /* Careful: we can end up here after [v]fork. Do not restore
7706 * tty pgrp then, only top-level shell process does that */
7707 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7708 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7710 /* TODO: if exec fails, bash does NOT exit! We do.
7711 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7712 * and tcsetpgrp, and this is inherently racy.
7714 execvp_or_die(argv);
7717 static int FAST_FUNC builtin_exit(char **argv)
7719 debug_printf_exec("%s()\n", __func__);
7721 /* interactive bash:
7722 * # trap "echo EEE" EXIT
7725 * There are stopped jobs.
7726 * (if there are _stopped_ jobs, running ones don't count)
7729 # EEE (then bash exits)
7731 * we can use G.exiting = -1 as indicator "last cmd was exit"
7734 /* note: EXIT trap is run by hush_exit */
7735 argv = skip_dash_dash(argv);
7736 if (argv[0] == NULL)
7737 hush_exit(G.last_exitcode);
7738 /* mimic bash: exit 123abc == exit 255 + error msg */
7739 xfunc_error_retval = 255;
7740 /* bash: exit -2 == exit 254, no error msg */
7741 hush_exit(xatoi(argv[0]) & 0xff);
7744 static void print_escaped(const char *s)
7749 const char *p = strchrnul(s, '\'');
7750 /* print 'xxxx', possibly just '' */
7751 printf("'%.*s'", (int)(p - s), s);
7756 /* s points to '; print "'''...'''" */
7758 do putchar('\''); while (*++s == '\'');
7763 #if !ENABLE_HUSH_LOCAL
7764 #define helper_export_local(argv, exp, lvl) \
7765 helper_export_local(argv, exp)
7767 static void helper_export_local(char **argv, int exp, int lvl)
7772 /* So far we do not check that name is valid (TODO?) */
7774 if (strchr(name, '=') == NULL) {
7775 struct variable *var;
7777 var = get_local_var(name);
7778 if (exp == -1) { /* unexporting? */
7779 /* export -n NAME (without =VALUE) */
7781 var->flg_export = 0;
7782 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7784 } /* else: export -n NOT_EXISTING_VAR: no-op */
7787 if (exp == 1) { /* exporting? */
7788 /* export NAME (without =VALUE) */
7790 var->flg_export = 1;
7791 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7792 putenv(var->varstr);
7796 /* Exporting non-existing variable.
7797 * bash does not put it in environment,
7798 * but remembers that it is exported,
7799 * and does put it in env when it is set later.
7800 * We just set it to "" and export. */
7801 /* Or, it's "local NAME" (without =VALUE).
7802 * bash sets the value to "". */
7803 name = xasprintf("%s=", name);
7805 /* (Un)exporting/making local NAME=VALUE */
7806 name = xstrdup(name);
7808 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7812 static int FAST_FUNC builtin_export(char **argv)
7814 unsigned opt_unexport;
7816 #if ENABLE_HUSH_EXPORT_N
7817 /* "!": do not abort on errors */
7818 opt_unexport = getopt32(argv, "!n");
7819 if (opt_unexport == (uint32_t)-1)
7820 return EXIT_FAILURE;
7827 if (argv[0] == NULL) {
7834 /* ash emits: export VAR='VAL'
7835 * bash: declare -x VAR="VAL"
7836 * we follow ash example */
7837 const char *s = *e++;
7838 const char *p = strchr(s, '=');
7840 if (!p) /* wtf? take next variable */
7843 printf("export %.*s", (int)(p - s) + 1, s);
7844 print_escaped(p + 1);
7848 /*fflush_all(); - done after each builtin anyway */
7850 return EXIT_SUCCESS;
7853 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7855 return EXIT_SUCCESS;
7858 #if ENABLE_HUSH_LOCAL
7859 static int FAST_FUNC builtin_local(char **argv)
7861 if (G.func_nest_level == 0) {
7862 bb_error_msg("%s: not in a function", argv[0]);
7863 return EXIT_FAILURE; /* bash compat */
7865 helper_export_local(argv, 0, G.func_nest_level);
7866 return EXIT_SUCCESS;
7870 static int FAST_FUNC builtin_trap(char **argv)
7876 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7881 /* No args: print all trapped */
7882 for (i = 0; i < NSIG; ++i) {
7885 print_escaped(G.traps[i]);
7886 /* note: bash adds "SIG", but only if invoked
7887 * as "bash". If called as "sh", or if set -o posix,
7888 * then it prints short signal names.
7889 * We are printing short names: */
7890 printf(" %s\n", get_signame(i));
7893 /*fflush_all(); - done after each builtin anyway */
7894 return EXIT_SUCCESS;
7898 /* If first arg is a number: reset all specified signals */
7899 sig = bb_strtou(*argv, NULL, 10);
7905 sig = get_signum(*argv++);
7906 if (sig < 0 || sig >= NSIG) {
7908 /* Mimic bash message exactly */
7909 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
7914 G.traps[sig] = xstrdup(new_cmd);
7916 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
7917 get_signame(sig), sig, G.traps[sig]);
7919 /* There is no signal for 0 (EXIT) */
7924 sigaddset(&G.blocked_set, sig);
7926 /* There was a trap handler, we are removing it
7927 * (if sig has non-DFL handling,
7928 * we don't need to do anything) */
7929 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7931 sigdelset(&G.blocked_set, sig);
7934 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7938 if (!argv[1]) { /* no second arg */
7939 bb_error_msg("trap: invalid arguments");
7940 return EXIT_FAILURE;
7943 /* First arg is "-": reset all specified to default */
7944 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7945 /* Everything else: set arg as signal handler
7946 * (includes "" case, which ignores signal) */
7947 if (argv[0][0] == '-') {
7948 if (argv[0][1] == '\0') { /* "-" */
7949 /* new_cmd remains NULL: "reset these sigs" */
7952 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7955 /* else: "-something", no special meaning */
7960 goto process_sig_list;
7963 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
7964 static int FAST_FUNC builtin_type(char **argv)
7966 int ret = EXIT_SUCCESS;
7972 if (0) {} /* make conditional compile easier below */
7973 /*else if (find_alias(*argv))
7974 type = "an alias";*/
7975 #if ENABLE_HUSH_FUNCTIONS
7976 else if (find_function(*argv))
7977 type = "a function";
7979 else if (find_builtin(*argv))
7980 type = "a shell builtin";
7981 else if ((path = find_in_path(*argv)) != NULL)
7984 bb_error_msg("type: %s: not found", *argv);
7989 printf("%s is %s\n", *argv, type);
7997 /* built-in 'fg' and 'bg' handler */
7998 static int FAST_FUNC builtin_fg_bg(char **argv)
8003 if (!G_interactive_fd)
8004 return EXIT_FAILURE;
8006 /* If they gave us no args, assume they want the last backgrounded task */
8008 for (pi = G.job_list; pi; pi = pi->next) {
8009 if (pi->jobid == G.last_jobid) {
8013 bb_error_msg("%s: no current job", argv[0]);
8014 return EXIT_FAILURE;
8016 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8017 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8018 return EXIT_FAILURE;
8020 for (pi = G.job_list; pi; pi = pi->next) {
8021 if (pi->jobid == jobnum) {
8025 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8026 return EXIT_FAILURE;
8028 /* TODO: bash prints a string representation
8029 * of job being foregrounded (like "sleep 1 | cat") */
8030 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8031 /* Put the job into the foreground. */
8032 tcsetpgrp(G_interactive_fd, pi->pgrp);
8035 /* Restart the processes in the job */
8036 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8037 for (i = 0; i < pi->num_cmds; i++) {
8038 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8039 pi->cmds[i].is_stopped = 0;
8041 pi->stopped_cmds = 0;
8043 i = kill(- pi->pgrp, SIGCONT);
8045 if (errno == ESRCH) {
8046 delete_finished_bg_job(pi);
8047 return EXIT_SUCCESS;
8049 bb_perror_msg("kill (SIGCONT)");
8052 if (argv[0][0] == 'f') {
8054 return checkjobs_and_fg_shell(pi);
8056 return EXIT_SUCCESS;
8060 #if ENABLE_HUSH_HELP
8061 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8063 const struct built_in_command *x;
8066 "Built-in commands:\n"
8067 "------------------\n");
8068 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8070 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8073 return EXIT_SUCCESS;
8078 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8081 const char *status_string;
8083 for (job = G.job_list; job; job = job->next) {
8084 if (job->alive_cmds == job->stopped_cmds)
8085 status_string = "Stopped";
8087 status_string = "Running";
8089 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8091 return EXIT_SUCCESS;
8096 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8101 # ifdef M_TRIM_THRESHOLD
8102 /* Optional. Reduces probability of false positives */
8105 /* Crude attempt to find where "free memory" starts,
8106 * sans fragmentation. */
8108 l = (unsigned long)p;
8111 if (l < (unsigned long)p) l = (unsigned long)p;
8114 if (!G.memleak_value)
8115 G.memleak_value = l;
8117 l -= G.memleak_value;
8124 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8129 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8132 return EXIT_SUCCESS;
8135 static int FAST_FUNC builtin_read(char **argv)
8144 /* "!": do not abort on errors.
8145 * Option string must start with "sr" to match BUILTIN_READ_xxx
8147 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8148 if (read_flags == (uint32_t)-1)
8149 return EXIT_FAILURE;
8152 r = shell_builtin_read(set_local_var_from_halves,
8154 get_local_var_value("IFS"), /* can be NULL */
8162 if ((uintptr_t)r > 1) {
8163 bb_error_msg("%s", r);
8164 r = (char*)(uintptr_t)1;
8167 return (uintptr_t)r;
8170 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8171 * built-in 'set' handler
8173 * set [-abCefhmnuvx] [-o option] [argument...]
8174 * set [+abCefhmnuvx] [+o option] [argument...]
8175 * set -- [argument...]
8178 * Implementations shall support the options in both their hyphen and
8179 * plus-sign forms. These options can also be specified as options to sh.
8181 * Write out all variables and their values: set
8182 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8183 * Turn on the -x and -v options: set -xv
8184 * Unset all positional parameters: set --
8185 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8186 * Set the positional parameters to the expansion of x, even if x expands
8187 * with a leading '-' or '+': set -- $x
8189 * So far, we only support "set -- [argument...]" and some of the short names.
8191 static int FAST_FUNC builtin_set(char **argv)
8194 char **pp, **g_argv;
8195 char *arg = *++argv;
8199 for (e = G.top_var; e; e = e->next)
8201 return EXIT_SUCCESS;
8205 if (!strcmp(arg, "--")) {
8209 if (arg[0] != '+' && arg[0] != '-')
8211 for (n = 1; arg[n]; ++n)
8212 if (set_mode(arg[0], arg[n]))
8214 } while ((arg = *++argv) != NULL);
8215 /* Now argv[0] is 1st argument */
8218 return EXIT_SUCCESS;
8221 /* NB: G.global_argv[0] ($0) is never freed/changed */
8222 g_argv = G.global_argv;
8223 if (G.global_args_malloced) {
8229 G.global_args_malloced = 1;
8230 pp = xzalloc(sizeof(pp[0]) * 2);
8231 pp[0] = g_argv[0]; /* retain $0 */
8234 /* This realloc's G.global_argv */
8235 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8242 return EXIT_SUCCESS;
8244 /* Nothing known, so abort */
8246 bb_error_msg("set: %s: invalid option", arg);
8247 return EXIT_FAILURE;
8250 static int FAST_FUNC builtin_shift(char **argv)
8253 argv = skip_dash_dash(argv);
8257 if (n >= 0 && n < G.global_argc) {
8258 if (G.global_args_malloced) {
8261 free(G.global_argv[m++]);
8264 memmove(&G.global_argv[1], &G.global_argv[n+1],
8265 G.global_argc * sizeof(G.global_argv[0]));
8266 return EXIT_SUCCESS;
8268 return EXIT_FAILURE;
8271 static int FAST_FUNC builtin_source(char **argv)
8273 char *arg_path, *filename;
8276 #if ENABLE_HUSH_FUNCTIONS
8280 argv = skip_dash_dash(argv);
8283 /* bash says: "bash: .: filename argument required" */
8284 return 2; /* bash compat */
8287 if (!strchr(filename, '/')) {
8288 arg_path = find_in_path(filename);
8290 filename = arg_path;
8292 input = fopen_or_warn(filename, "r");
8295 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8296 return EXIT_FAILURE;
8298 close_on_exec_on(fileno(input));
8300 #if ENABLE_HUSH_FUNCTIONS
8301 sv_flg = G.flag_return_in_progress;
8302 /* "we are inside sourced file, ok to use return" */
8303 G.flag_return_in_progress = -1;
8305 save_and_replace_G_args(&sv, argv);
8307 parse_and_run_file(input);
8310 restore_G_args(&sv, argv);
8311 #if ENABLE_HUSH_FUNCTIONS
8312 G.flag_return_in_progress = sv_flg;
8315 return G.last_exitcode;
8318 static int FAST_FUNC builtin_umask(char **argv)
8324 argv = skip_dash_dash(argv);
8326 mode_t old_mask = mask;
8329 rc = bb_parse_mode(argv[0], &mask);
8334 * bash: umask: 'q': invalid symbolic mode operator
8335 * bash: umask: 999: octal number out of range
8337 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8342 printf("%04o\n", (unsigned) mask);
8343 /* fall through and restore mask which we set to 0 */
8347 return !rc; /* rc != 0 - success */
8350 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8351 static int FAST_FUNC builtin_unset(char **argv)
8356 /* "!": do not abort on errors */
8357 /* "+": stop at 1st non-option */
8358 opts = getopt32(argv, "!+vf");
8359 if (opts == (unsigned)-1)
8360 return EXIT_FAILURE;
8362 bb_error_msg("unset: -v and -f are exclusive");
8363 return EXIT_FAILURE;
8369 if (!(opts & 2)) { /* not -f */
8370 if (unset_local_var(*argv)) {
8371 /* unset <nonexistent_var> doesn't fail.
8372 * Error is when one tries to unset RO var.
8373 * Message was printed by unset_local_var. */
8377 #if ENABLE_HUSH_FUNCTIONS
8387 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8388 static int FAST_FUNC builtin_wait(char **argv)
8390 int ret = EXIT_SUCCESS;
8393 argv = skip_dash_dash(argv);
8394 if (argv[0] == NULL) {
8395 /* Don't care about wait results */
8396 /* Note 1: must wait until there are no more children */
8397 /* Note 2: must be interruptible */
8399 * $ sleep 3 & sleep 6 & wait
8404 * $ sleep 3 & sleep 6 & wait
8408 * ^C <-- after ~4 sec from keyboard
8411 sigaddset(&G.blocked_set, SIGCHLD);
8412 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8415 if (errno == ECHILD)
8417 /* Wait for SIGCHLD or any other signal of interest */
8418 /* sigtimedwait with infinite timeout: */
8419 sig = sigwaitinfo(&G.blocked_set, NULL);
8421 sig = check_and_run_traps(sig);
8422 if (sig && sig != SIGCHLD) { /* see note 2 */
8428 sigdelset(&G.blocked_set, SIGCHLD);
8429 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8433 /* This is probably buggy wrt interruptible-ness */
8435 pid_t pid = bb_strtou(*argv, NULL, 10);
8437 /* mimic bash message */
8438 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8439 return EXIT_FAILURE;
8441 if (waitpid(pid, &status, 0) == pid) {
8442 if (WIFSIGNALED(status))
8443 ret = 128 + WTERMSIG(status);
8444 else if (WIFEXITED(status))
8445 ret = WEXITSTATUS(status);
8449 bb_perror_msg("wait %s", *argv);
8458 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8459 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8462 def = bb_strtou(argv[1], NULL, 10);
8463 if (errno || def < def_min || argv[2]) {
8464 bb_error_msg("%s: bad arguments", argv[0]);
8472 #if ENABLE_HUSH_LOOPS
8473 static int FAST_FUNC builtin_break(char **argv)
8476 if (G.depth_of_loop == 0) {
8477 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8478 return EXIT_SUCCESS; /* bash compat */
8480 G.flag_break_continue++; /* BC_BREAK = 1 */
8482 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8483 if (depth == UINT_MAX)
8484 G.flag_break_continue = BC_BREAK;
8485 if (G.depth_of_loop < depth)
8486 G.depth_break_continue = G.depth_of_loop;
8488 return EXIT_SUCCESS;
8491 static int FAST_FUNC builtin_continue(char **argv)
8493 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8494 return builtin_break(argv);
8498 #if ENABLE_HUSH_FUNCTIONS
8499 static int FAST_FUNC builtin_return(char **argv)
8503 if (G.flag_return_in_progress != -1) {
8504 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8505 return EXIT_FAILURE; /* bash compat */
8508 G.flag_return_in_progress = 1;
8511 * out of range: wraps around at 256, does not error out
8512 * non-numeric param:
8513 * f() { false; return qwe; }; f; echo $?
8514 * bash: return: qwe: numeric argument required <== we do this
8515 * 255 <== we also do this
8517 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);