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>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
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))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
90 /* #include <dmalloc.h> */
94 #include <sys/utsname.h> /* for setting $HOSTNAME */
96 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
98 #include "shell_common.h"
101 #if ENABLE_HUSH_RANDOM_SUPPORT
104 # define CLEAR_RANDOM_T(rnd) ((void)0)
107 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
111 //config: bool "hush"
114 //config: hush is a small shell (25k). It handles the normal flow control
115 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
116 //config: case/esac. Redirections, here documents, $((arithmetic))
117 //config: and functions are supported.
119 //config: It will compile and work on no-mmu systems.
121 //config: It does not handle select, aliases, tilde expansion,
122 //config: &>file and >&file redirection of stdout+stderr.
124 //config:config HUSH_BASH_COMPAT
125 //config: bool "bash-compatible extensions"
127 //config: depends on HUSH
129 //config: Enable bash-compatible extensions.
131 //config:config HUSH_BRACE_EXPANSION
132 //config: bool "Brace expansion"
134 //config: depends on HUSH_BASH_COMPAT
136 //config: Enable {abc,def} extension.
138 //config:config HUSH_HELP
139 //config: bool "help builtin"
141 //config: depends on HUSH
143 //config: Enable help builtin in hush. Code size + ~1 kbyte.
145 //config:config HUSH_INTERACTIVE
146 //config: bool "Interactive mode"
148 //config: depends on HUSH
150 //config: Enable interactive mode (prompt and command editing).
151 //config: Without this, hush simply reads and executes commands
152 //config: from stdin just like a shell script from a file.
153 //config: No prompt, no PS1/PS2 magic shell variables.
155 //config:config HUSH_SAVEHISTORY
156 //config: bool "Save command history to .hush_history"
158 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
160 //config: Enable history saving in hush.
162 //config:config HUSH_JOB
163 //config: bool "Job control"
165 //config: depends on HUSH_INTERACTIVE
167 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
168 //config: command (not entire shell), fg/bg builtins work. Without this option,
169 //config: "cmd &" still works by simply spawning a process and immediately
170 //config: prompting for next command (or executing next command in a script),
171 //config: but no separate process group is formed.
173 //config:config HUSH_TICK
174 //config: bool "Process substitution"
176 //config: depends on HUSH
178 //config: Enable process substitution `command` and $(command) in hush.
180 //config:config HUSH_IF
181 //config: bool "Support if/then/elif/else/fi"
183 //config: depends on HUSH
185 //config: Enable if/then/elif/else/fi in hush.
187 //config:config HUSH_LOOPS
188 //config: bool "Support for, while and until loops"
190 //config: depends on HUSH
192 //config: Enable for, while and until loops in hush.
194 //config:config HUSH_CASE
195 //config: bool "Support case ... esac statement"
197 //config: depends on HUSH
199 //config: Enable case ... esac statement in hush. +400 bytes.
201 //config:config HUSH_FUNCTIONS
202 //config: bool "Support funcname() { commands; } syntax"
204 //config: depends on HUSH
206 //config: Enable support for shell functions in hush. +800 bytes.
208 //config:config HUSH_LOCAL
209 //config: bool "Support local builtin"
211 //config: depends on HUSH_FUNCTIONS
213 //config: Enable support for local variables in functions.
215 //config:config HUSH_RANDOM_SUPPORT
216 //config: bool "Pseudorandom generator and $RANDOM variable"
218 //config: depends on HUSH
220 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
221 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
223 //config:config HUSH_EXPORT_N
224 //config: bool "Support 'export -n' option"
226 //config: depends on HUSH
228 //config: export -n unexports variables. It is a bash extension.
230 //config:config HUSH_MODE_X
231 //config: bool "Support 'hush -x' option and 'set -x' command"
233 //config: depends on HUSH
235 //config: This instructs hush to print commands before execution.
236 //config: Adds ~300 bytes.
239 //config: bool "msh (deprecated: aliased to hush)"
241 //config: select HUSH
243 //config: msh is deprecated and will be removed, please migrate to hush.
246 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
247 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
248 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
249 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
251 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
252 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
254 /* -i (interactive) and -s (read stdin) are also accepted,
255 * but currently do nothing, therefore aren't shown in help.
256 * NOMMU-specific options are not meant to be used by users,
257 * therefore we don't show them either.
259 //usage:#define hush_trivial_usage
260 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
261 //usage:#define hush_full_usage "\n\n"
262 //usage: "Unix shell interpreter"
264 //usage:#define msh_trivial_usage hush_trivial_usage
265 //usage:#define msh_full_usage hush_full_usage
267 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
268 //usage:# define sh_trivial_usage hush_trivial_usage
269 //usage:# define sh_full_usage hush_full_usage
271 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
272 //usage:# define bash_trivial_usage hush_trivial_usage
273 //usage:# define bash_full_usage hush_full_usage
278 #define LEAK_HUNTING 0
279 #define BUILD_AS_NOMMU 0
280 /* Enable/disable sanity checks. Ok to enable in production,
281 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
282 * Keeping 1 for now even in released versions.
285 /* Slightly bigger (+200 bytes), but faster hush.
286 * So far it only enables a trick with counting SIGCHLDs and forks,
287 * which allows us to do fewer waitpid's.
288 * (we can detect a case where neither forks were done nor SIGCHLDs happened
289 * and therefore waitpid will return the same result as last time)
291 #define ENABLE_HUSH_FAST 0
292 /* TODO: implement simplified code for users which do not need ${var%...} ops
293 * So far ${var%...} ops are always enabled:
295 #define ENABLE_HUSH_DOLLAR_OPS 1
300 # undef USE_FOR_NOMMU
303 # define USE_FOR_NOMMU(...) __VA_ARGS__
304 # define USE_FOR_MMU(...)
307 #include "NUM_APPLETS.h"
309 /* STANDALONE does not make sense, and won't compile */
310 # undef CONFIG_FEATURE_SH_STANDALONE
311 # undef ENABLE_FEATURE_SH_STANDALONE
312 # undef IF_FEATURE_SH_STANDALONE
313 # undef IF_NOT_FEATURE_SH_STANDALONE
314 # define ENABLE_FEATURE_SH_STANDALONE 0
315 # define IF_FEATURE_SH_STANDALONE(...)
316 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
319 #if !ENABLE_HUSH_INTERACTIVE
320 # undef ENABLE_FEATURE_EDITING
321 # define ENABLE_FEATURE_EDITING 0
322 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
323 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
324 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
325 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
328 /* Do we support ANY keywords? */
329 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
330 # define HAS_KEYWORDS 1
331 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
332 # define IF_HAS_NO_KEYWORDS(...)
334 # define HAS_KEYWORDS 0
335 # define IF_HAS_KEYWORDS(...)
336 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
339 /* If you comment out one of these below, it will be #defined later
340 * to perform debug printfs to stderr: */
341 #define debug_printf(...) do {} while (0)
342 /* Finer-grained debug switches */
343 #define debug_printf_parse(...) do {} while (0)
344 #define debug_print_tree(a, b) do {} while (0)
345 #define debug_printf_exec(...) do {} while (0)
346 #define debug_printf_env(...) do {} while (0)
347 #define debug_printf_jobs(...) do {} while (0)
348 #define debug_printf_expand(...) do {} while (0)
349 #define debug_printf_varexp(...) do {} while (0)
350 #define debug_printf_glob(...) do {} while (0)
351 #define debug_printf_list(...) do {} while (0)
352 #define debug_printf_subst(...) do {} while (0)
353 #define debug_printf_clean(...) do {} while (0)
355 #define ERR_PTR ((void*)(long)1)
357 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
359 #define _SPECIAL_VARS_STR "_*@$!?#"
360 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
361 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
362 #if ENABLE_HUSH_BASH_COMPAT
363 /* Support / and // replace ops */
364 /* Note that // is stored as \ in "encoded" string representation */
365 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
366 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
367 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
369 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
370 # define VAR_SUBST_OPS "%#:-=+?"
371 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
374 #define SPECIAL_VAR_SYMBOL 3
378 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
380 /* This supports saving pointers malloced in vfork child,
381 * to be freed in the parent.
384 typedef struct nommu_save_t {
386 struct variable *old_vars;
388 char **argv_from_re_execing;
401 #if ENABLE_HUSH_LOOPS
408 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
413 /* three pseudo-keywords support contrived "case" syntax: */
414 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
415 RES_MATCH , /* "word)" */
416 RES_CASE_BODY, /* "this command is inside CASE" */
423 typedef struct o_string {
425 int length; /* position where data is appended */
428 /* At least some part of the string was inside '' or "",
429 * possibly empty one: word"", wo''rd etc. */
430 smallint has_quoted_part;
431 smallint has_empty_slot;
432 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
435 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
437 /* Protect newly added chars against globbing
438 * by prepending \ to *, ?, [, \ */
439 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
442 MAYBE_ASSIGNMENT = 0,
443 DEFINITELY_ASSIGNMENT = 1,
445 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
448 /* Used for initialization: o_string foo = NULL_O_STRING; */
449 #define NULL_O_STRING { NULL }
451 #ifndef debug_printf_parse
452 static const char *const assignment_flag[] = {
454 "DEFINITELY_ASSIGNMENT",
460 typedef struct in_str {
462 /* eof_flag=1: last char in ->p is really an EOF */
463 char eof_flag; /* meaningless if ->p == NULL */
465 #if ENABLE_HUSH_INTERACTIVE
466 smallint promptmode; /* 0: PS1, 1: PS2 */
470 int (*get) (struct in_str *) FAST_FUNC;
471 int (*peek) (struct in_str *) FAST_FUNC;
473 #define i_getch(input) ((input)->get(input))
474 #define i_peek(input) ((input)->peek(input))
476 /* The descrip member of this structure is only used to make
477 * debugging output pretty */
478 static const struct {
480 signed char default_fd;
483 { O_RDONLY, 0, "<" },
484 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
485 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
486 { O_CREAT|O_RDWR, 1, "<>" },
487 { O_RDONLY, 0, "<<" },
488 /* Should not be needed. Bogus default_fd helps in debugging */
489 /* { O_RDONLY, 77, "<<" }, */
492 struct redir_struct {
493 struct redir_struct *next;
494 char *rd_filename; /* filename */
495 int rd_fd; /* fd to redirect */
496 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
498 smallint rd_type; /* (enum redir_type) */
499 /* note: for heredocs, rd_filename contains heredoc delimiter,
500 * and subsequently heredoc itself; and rd_dup is a bitmask:
501 * bit 0: do we need to trim leading tabs?
502 * bit 1: is heredoc quoted (<<'delim' syntax) ?
505 typedef enum redir_type {
507 REDIRECT_OVERWRITE = 1,
510 REDIRECT_HEREDOC = 4,
511 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
514 REDIRFD_SYNTAX_ERR = -2,
515 REDIRFD_TO_FILE = -1,
516 /* otherwise, rd_fd is redirected to rd_dup */
518 HEREDOC_SKIPTABS = 1,
524 pid_t pid; /* 0 if exited */
525 int assignment_cnt; /* how many argv[i] are assignments? */
526 smallint cmd_type; /* CMD_xxx */
528 #define CMD_SUBSHELL 1
529 #if ENABLE_HUSH_BASH_COMPAT
530 /* used for "[[ EXPR ]]" */
531 # define CMD_SINGLEWORD_NOGLOB 2
533 #if ENABLE_HUSH_FUNCTIONS
534 # define CMD_FUNCDEF 3
537 smalluint cmd_exitcode;
538 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
541 char *group_as_string;
543 #if ENABLE_HUSH_FUNCTIONS
544 struct function *child_func;
545 /* This field is used to prevent a bug here:
546 * while...do f1() {a;}; f1; f1() {b;}; f1; done
547 * When we execute "f1() {a;}" cmd, we create new function and clear
548 * cmd->group, cmd->group_as_string, cmd->argv[0].
549 * When we execute "f1() {b;}", we notice that f1 exists,
550 * and that its "parent cmd" struct is still "alive",
551 * we put those fields back into cmd->xxx
552 * (struct function has ->parent_cmd ptr to facilitate that).
553 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
554 * Without this trick, loop would execute a;b;b;b;...
555 * instead of correct sequence a;b;a;b;...
556 * When command is freed, it severs the link
557 * (sets ->child_func->parent_cmd to NULL).
560 char **argv; /* command name and arguments */
561 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
562 * and on execution these are substituted with their values.
563 * Substitution can make _several_ words out of one argv[n]!
564 * Example: argv[0]=='.^C*^C.' here: echo .$*.
565 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
567 struct redir_struct *redirects; /* I/O redirections */
569 /* Is there anything in this command at all? */
570 #define IS_NULL_CMD(cmd) \
571 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
575 int num_cmds; /* total number of commands in pipe */
576 int alive_cmds; /* number of commands running (not exited) */
577 int stopped_cmds; /* number of commands alive, but stopped */
579 int jobid; /* job number */
580 pid_t pgrp; /* process group ID for the job */
581 char *cmdtext; /* name of job */
583 struct command *cmds; /* array of commands in pipe */
584 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
585 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
586 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
588 typedef enum pipe_style {
594 /* Is there anything in this pipe at all? */
595 #define IS_NULL_PIPE(pi) \
596 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
598 /* This holds pointers to the various results of parsing */
599 struct parse_context {
600 /* linked list of pipes */
601 struct pipe *list_head;
602 /* last pipe (being constructed right now) */
604 /* last command in pipe (being constructed right now) */
605 struct command *command;
606 /* last redirect in command->redirects list */
607 struct redir_struct *pending_redirect;
613 smallint ctx_inverted; /* "! cmd | cmd" */
615 smallint ctx_dsemicolon; /* ";;" seen */
617 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
619 /* group we are enclosed in:
620 * example: "if pipe1; pipe2; then pipe3; fi"
621 * when we see "if" or "then", we malloc and copy current context,
622 * and make ->stack point to it. then we parse pipeN.
623 * when closing "then" / fi" / whatever is found,
624 * we move list_head into ->stack->command->group,
625 * copy ->stack into current context, and delete ->stack.
626 * (parsing of { list } and ( list ) doesn't use this method)
628 struct parse_context *stack;
632 /* On program start, environ points to initial environment.
633 * putenv adds new pointers into it, unsetenv removes them.
634 * Neither of these (de)allocates the strings.
635 * setenv allocates new strings in malloc space and does putenv,
636 * and thus setenv is unusable (leaky) for shell's purposes */
637 #define setenv(...) setenv_is_leaky_dont_use()
639 struct variable *next;
640 char *varstr; /* points to "name=" portion */
641 #if ENABLE_HUSH_LOCAL
642 unsigned func_nest_level;
644 int max_len; /* if > 0, name is part of initial env; else name is malloced */
645 smallint flg_export; /* putenv should be done on this var */
646 smallint flg_read_only;
654 #if ENABLE_HUSH_FUNCTIONS
656 struct function *next;
658 struct command *parent_cmd;
661 char *body_as_string;
667 /* set -/+o OPT support. (TODO: make it optional)
668 * bash supports the following opts:
679 * interactive-comments on
697 static const char o_opt_strings[] ALIGN1 =
700 #if ENABLE_HUSH_MODE_X
707 #if ENABLE_HUSH_MODE_X
714 /* "Globals" within this file */
715 /* Sorted roughly by size (smaller offsets == smaller code) */
717 /* interactive_fd != 0 means we are an interactive shell.
718 * If we are, then saved_tty_pgrp can also be != 0, meaning
719 * that controlling tty is available. With saved_tty_pgrp == 0,
720 * job control still works, but terminal signals
721 * (^C, ^Z, ^Y, ^\) won't work at all, and background
722 * process groups can only be created with "cmd &".
723 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
724 * to give tty to the foreground process group,
725 * and will take it back when the group is stopped (^Z)
728 #if ENABLE_HUSH_INTERACTIVE
729 /* 'interactive_fd' is a fd# open to ctty, if we have one
730 * _AND_ if we decided to act interactively */
734 # define G_interactive_fd (G.interactive_fd)
736 # define G_interactive_fd 0
738 #if ENABLE_FEATURE_EDITING
739 line_input_t *line_input_state;
744 #if ENABLE_HUSH_RANDOM_SUPPORT
750 pid_t saved_tty_pgrp;
751 struct pipe *job_list;
752 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
754 # define G_saved_tty_pgrp 0
756 char o_opt[NUM_OPT_O];
757 #if ENABLE_HUSH_MODE_X
758 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
762 smallint flag_SIGINT;
763 #if ENABLE_HUSH_LOOPS
764 smallint flag_break_continue;
766 #if ENABLE_HUSH_FUNCTIONS
767 /* 0: outside of a function (or sourced file)
768 * -1: inside of a function, ok to use return builtin
769 * 1: return is invoked, skip all till end of func
771 smallint flag_return_in_progress;
773 smallint exiting; /* used to prevent EXIT trap recursion */
774 /* These four support $?, $#, and $1 */
775 smalluint last_exitcode;
776 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
777 smalluint global_args_malloced;
778 /* how many non-NULL argv's we have. NB: $# + 1 */
782 char *argv0_for_re_execing;
784 #if ENABLE_HUSH_LOOPS
785 unsigned depth_break_continue;
786 unsigned depth_of_loop;
790 struct variable *top_var;
791 char **expanded_assignments;
792 #if ENABLE_HUSH_FUNCTIONS
793 struct function *top_func;
794 # if ENABLE_HUSH_LOCAL
795 struct variable **shadowed_vars_pp;
796 unsigned func_nest_level;
799 /* Signal and trap handling */
801 unsigned count_SIGCHLD;
802 unsigned handled_SIGCHLD;
803 smallint we_have_children;
805 /* Which signals have non-DFL handler (even with no traps set)?
806 * Set at the start to:
807 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
808 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
809 * The rest is cleared right before execv syscalls.
810 * Other than these two times, never modified.
812 unsigned special_sig_mask;
814 unsigned fatal_sig_mask;
815 # define G_fatal_sig_mask G.fatal_sig_mask
817 # define G_fatal_sig_mask 0
819 char **traps; /* char *traps[NSIG] */
820 sigset_t pending_set;
822 unsigned long memleak_value;
826 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
828 #define G (*ptr_to_globals)
829 /* Not #defining name to G.name - this quickly gets unwieldy
830 * (too many defines). Also, I actually prefer to see when a variable
831 * is global, thus "G." prefix is a useful hint */
832 #define INIT_G() do { \
833 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
834 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
835 sigfillset(&G.sa.sa_mask); \
836 G.sa.sa_flags = SA_RESTART; \
840 /* Function prototypes for builtins */
841 static int builtin_cd(char **argv) FAST_FUNC;
842 static int builtin_echo(char **argv) FAST_FUNC;
843 static int builtin_eval(char **argv) FAST_FUNC;
844 static int builtin_exec(char **argv) FAST_FUNC;
845 static int builtin_exit(char **argv) FAST_FUNC;
846 static int builtin_export(char **argv) FAST_FUNC;
848 static int builtin_fg_bg(char **argv) FAST_FUNC;
849 static int builtin_jobs(char **argv) FAST_FUNC;
852 static int builtin_help(char **argv) FAST_FUNC;
854 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
855 static int builtin_history(char **argv) FAST_FUNC;
857 #if ENABLE_HUSH_LOCAL
858 static int builtin_local(char **argv) FAST_FUNC;
861 static int builtin_memleak(char **argv) FAST_FUNC;
864 static int builtin_printf(char **argv) FAST_FUNC;
866 static int builtin_pwd(char **argv) FAST_FUNC;
867 static int builtin_read(char **argv) FAST_FUNC;
868 static int builtin_set(char **argv) FAST_FUNC;
869 static int builtin_shift(char **argv) FAST_FUNC;
870 static int builtin_source(char **argv) FAST_FUNC;
871 static int builtin_test(char **argv) FAST_FUNC;
872 static int builtin_trap(char **argv) FAST_FUNC;
873 static int builtin_type(char **argv) FAST_FUNC;
874 static int builtin_true(char **argv) FAST_FUNC;
875 static int builtin_umask(char **argv) FAST_FUNC;
876 static int builtin_unset(char **argv) FAST_FUNC;
877 static int builtin_wait(char **argv) FAST_FUNC;
878 #if ENABLE_HUSH_LOOPS
879 static int builtin_break(char **argv) FAST_FUNC;
880 static int builtin_continue(char **argv) FAST_FUNC;
882 #if ENABLE_HUSH_FUNCTIONS
883 static int builtin_return(char **argv) FAST_FUNC;
886 /* Table of built-in functions. They can be forked or not, depending on
887 * context: within pipes, they fork. As simple commands, they do not.
888 * When used in non-forking context, they can change global variables
889 * in the parent shell process. If forked, of course they cannot.
890 * For example, 'unset foo | whatever' will parse and run, but foo will
891 * still be set at the end. */
892 struct built_in_command {
894 int (*b_function)(char **argv) FAST_FUNC;
897 # define BLTIN(cmd, func, help) { cmd, func, help }
899 # define BLTIN(cmd, func, help) { cmd, func }
903 static const struct built_in_command bltins1[] = {
904 BLTIN("." , builtin_source , "Run commands in a file"),
905 BLTIN(":" , builtin_true , NULL),
907 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
909 #if ENABLE_HUSH_LOOPS
910 BLTIN("break" , builtin_break , "Exit from a loop"),
912 BLTIN("cd" , builtin_cd , "Change directory"),
913 #if ENABLE_HUSH_LOOPS
914 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
916 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
917 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
918 BLTIN("exit" , builtin_exit , "Exit"),
919 BLTIN("export" , builtin_export , "Set environment variables"),
921 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
924 BLTIN("help" , builtin_help , NULL),
926 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
927 BLTIN("history" , builtin_history , "Show command history"),
930 BLTIN("jobs" , builtin_jobs , "List jobs"),
932 #if ENABLE_HUSH_LOCAL
933 BLTIN("local" , builtin_local , "Set local variables"),
936 BLTIN("memleak" , builtin_memleak , NULL),
938 BLTIN("read" , builtin_read , "Input into variable"),
939 #if ENABLE_HUSH_FUNCTIONS
940 BLTIN("return" , builtin_return , "Return from a function"),
942 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
943 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
944 #if ENABLE_HUSH_BASH_COMPAT
945 BLTIN("source" , builtin_source , "Run commands in a file"),
947 BLTIN("trap" , builtin_trap , "Trap signals"),
948 BLTIN("true" , builtin_true , NULL),
949 BLTIN("type" , builtin_type , "Show command type"),
950 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
951 BLTIN("umask" , builtin_umask , "Set file creation mask"),
952 BLTIN("unset" , builtin_unset , "Unset variables"),
953 BLTIN("wait" , builtin_wait , "Wait for process"),
955 /* For now, echo and test are unconditionally enabled.
956 * Maybe make it configurable? */
957 static const struct built_in_command bltins2[] = {
958 BLTIN("[" , builtin_test , NULL),
959 BLTIN("echo" , builtin_echo , NULL),
961 BLTIN("printf" , builtin_printf , NULL),
963 BLTIN("pwd" , builtin_pwd , NULL),
964 BLTIN("test" , builtin_test , NULL),
971 /* prevent disasters with G.debug_indent < 0 */
972 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
973 # define debug_enter() (G.debug_indent++)
974 # define debug_leave() (G.debug_indent--)
976 # define indent() ((void)0)
977 # define debug_enter() ((void)0)
978 # define debug_leave() ((void)0)
982 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
985 #ifndef debug_printf_parse
986 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
989 #ifndef debug_printf_exec
990 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
993 #ifndef debug_printf_env
994 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
997 #ifndef debug_printf_jobs
998 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
999 # define DEBUG_JOBS 1
1001 # define DEBUG_JOBS 0
1004 #ifndef debug_printf_expand
1005 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1006 # define DEBUG_EXPAND 1
1008 # define DEBUG_EXPAND 0
1011 #ifndef debug_printf_varexp
1012 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1015 #ifndef debug_printf_glob
1016 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1017 # define DEBUG_GLOB 1
1019 # define DEBUG_GLOB 0
1022 #ifndef debug_printf_list
1023 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1026 #ifndef debug_printf_subst
1027 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1030 #ifndef debug_printf_clean
1031 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1032 # define DEBUG_CLEAN 1
1034 # define DEBUG_CLEAN 0
1038 static void debug_print_strings(const char *prefix, char **vv)
1041 fdprintf(2, "%s:\n", prefix);
1043 fdprintf(2, " '%s'\n", *vv++);
1046 # define debug_print_strings(prefix, vv) ((void)0)
1050 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1053 static void *xxmalloc(int lineno, size_t size)
1055 void *ptr = xmalloc((size + 0xff) & ~0xff);
1056 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1059 static void *xxrealloc(int lineno, void *ptr, size_t size)
1061 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1062 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1065 static char *xxstrdup(int lineno, const char *str)
1067 char *ptr = xstrdup(str);
1068 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1071 static void xxfree(void *ptr)
1073 fdprintf(2, "free %p\n", ptr);
1076 # define xmalloc(s) xxmalloc(__LINE__, s)
1077 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1078 # define xstrdup(s) xxstrdup(__LINE__, s)
1079 # define free(p) xxfree(p)
1083 /* Syntax and runtime errors. They always abort scripts.
1084 * In interactive use they usually discard unparsed and/or unexecuted commands
1085 * and return to the prompt.
1086 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1089 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1090 # define syntax_error(lineno, msg) syntax_error(msg)
1091 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1092 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1093 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1094 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1097 static void die_if_script(unsigned lineno, const char *fmt, ...)
1102 bb_error_msg("hush.c:%u", lineno);
1105 bb_verror_msg(fmt, p, NULL);
1107 if (!G_interactive_fd)
1111 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1114 bb_error_msg("syntax error: %s", msg);
1116 bb_error_msg("syntax error");
1119 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1121 bb_error_msg("syntax error at '%s'", msg);
1124 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1126 bb_error_msg("syntax error: unterminated %s", s);
1129 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1131 char msg[2] = { ch, '\0' };
1132 syntax_error_unterm_str(lineno, msg);
1135 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1140 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1144 # undef die_if_script
1145 # undef syntax_error
1146 # undef syntax_error_at
1147 # undef syntax_error_unterm_ch
1148 # undef syntax_error_unterm_str
1149 # undef syntax_error_unexpected_ch
1151 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1152 # define syntax_error(msg) syntax_error(__LINE__, msg)
1153 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1154 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1155 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1156 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1160 #if ENABLE_HUSH_INTERACTIVE
1161 static void cmdedit_update_prompt(void);
1163 # define cmdedit_update_prompt() ((void)0)
1167 /* Utility functions
1169 /* Replace each \x with x in place, return ptr past NUL. */
1170 static char *unbackslash(char *src)
1172 char *dst = src = strchrnul(src, '\\');
1176 if ((*dst++ = *src++) == '\0')
1182 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1203 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1204 v[count1 + count2] = NULL;
1207 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1211 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1213 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1214 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1217 #define add_strings_to_strings(strings, add, need_to_dup) \
1218 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1221 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1222 static char **add_string_to_strings(char **strings, char *add)
1227 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1230 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1232 char **ptr = add_string_to_strings(strings, add);
1233 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1236 #define add_string_to_strings(strings, add) \
1237 xx_add_string_to_strings(__LINE__, strings, add)
1240 static void free_strings(char **strings)
1255 /* Helpers for setting new $n and restoring them back
1257 typedef struct save_arg_t {
1261 smallint sv_g_malloced;
1264 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1268 sv->sv_argv0 = argv[0];
1269 sv->sv_g_argv = G.global_argv;
1270 sv->sv_g_argc = G.global_argc;
1271 sv->sv_g_malloced = G.global_args_malloced;
1273 argv[0] = G.global_argv[0]; /* retain $0 */
1274 G.global_argv = argv;
1275 G.global_args_malloced = 0;
1283 static void restore_G_args(save_arg_t *sv, char **argv)
1287 if (G.global_args_malloced) {
1288 /* someone ran "set -- arg1 arg2 ...", undo */
1290 while (*++pp) /* note: does not free $0 */
1292 free(G.global_argv);
1294 argv[0] = sv->sv_argv0;
1295 G.global_argv = sv->sv_g_argv;
1296 G.global_argc = sv->sv_g_argc;
1297 G.global_args_malloced = sv->sv_g_malloced;
1301 /* Basic theory of signal handling in shell
1302 * ========================================
1303 * This does not describe what hush does, rather, it is current understanding
1304 * what it _should_ do. If it doesn't, it's a bug.
1305 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1307 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1308 * is finished or backgrounded. It is the same in interactive and
1309 * non-interactive shells, and is the same regardless of whether
1310 * a user trap handler is installed or a shell special one is in effect.
1311 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1312 * backgrounds (i.e. stops) or kills all members of currently running
1315 * Wait builtin is interruptible by signals for which user trap is set
1316 * or by SIGINT in interactive shell.
1318 * Trap handlers will execute even within trap handlers. (right?)
1320 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1321 * except for handlers set to '' (empty string).
1323 * If job control is off, backgrounded commands ("cmd &")
1324 * have SIGINT, SIGQUIT set to SIG_IGN.
1326 * Commands which are run in command substitution ("`cmd`")
1327 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1329 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1330 * by the shell from its parent.
1332 * Signals which differ from SIG_DFL action
1333 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1336 * SIGTERM (interactive): ignore
1337 * SIGHUP (interactive):
1338 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1339 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1340 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1341 * that all pipe members are stopped. Try this in bash:
1342 * while :; do :; done - ^Z does not background it
1343 * (while :; do :; done) - ^Z backgrounds it
1344 * SIGINT (interactive): wait for last pipe, ignore the rest
1345 * of the command line, show prompt. NB: ^C does not send SIGINT
1346 * to interactive shell while shell is waiting for a pipe,
1347 * since shell is bg'ed (is not in foreground process group).
1348 * Example 1: this waits 5 sec, but does not execute ls:
1349 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1350 * Example 2: this does not wait and does not execute ls:
1351 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1352 * Example 3: this does not wait 5 sec, but executes ls:
1353 * "sleep 5; ls -l" + press ^C
1354 * Example 4: this does not wait and does not execute ls:
1355 * "sleep 5 & wait; ls -l" + press ^C
1357 * (What happens to signals which are IGN on shell start?)
1358 * (What happens with signal mask on shell start?)
1360 * Old implementation
1361 * ==================
1362 * We use in-kernel pending signal mask to determine which signals were sent.
1363 * We block all signals which we don't want to take action immediately,
1364 * i.e. we block all signals which need to have special handling as described
1365 * above, and all signals which have traps set.
1366 * After each pipe execution, we extract any pending signals via sigtimedwait()
1369 * unsigned special_sig_mask: a mask of such "special" signals
1370 * sigset_t blocked_set: current blocked signal set
1373 * clear bit in blocked_set unless it is also in special_sig_mask
1374 * "trap 'cmd' SIGxxx":
1375 * set bit in blocked_set (even if 'cmd' is '')
1376 * after [v]fork, if we plan to be a shell:
1377 * unblock signals with special interactive handling
1378 * (child shell is not interactive),
1379 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1380 * after [v]fork, if we plan to exec:
1381 * POSIX says fork clears pending signal mask in child - no need to clear it.
1382 * Restore blocked signal set to one inherited by shell just prior to exec.
1384 * Note: as a result, we do not use signal handlers much. The only uses
1385 * are to count SIGCHLDs
1386 * and to restore tty pgrp on signal-induced exit.
1389 * Standard says "When a subshell is entered, traps that are not being ignored
1390 * are set to the default actions". bash interprets it so that traps which
1391 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1393 * Problem: the above approach makes it unwieldy to catch signals while
1394 * we are in read builtin, or while we read commands from stdin:
1395 * masked signals are not visible!
1397 * New implementation
1398 * ==================
1399 * We record each signal we are interested in by installing signal handler
1400 * for them - a bit like emulating kernel pending signal mask in userspace.
1401 * We are interested in: signals which need to have special handling
1402 * as described above, and all signals which have traps set.
1403 * Signals are recorded in pending_set.
1404 * After each pipe execution, we extract any pending signals
1407 * unsigned special_sig_mask: a mask of shell-special signals.
1408 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1409 * char *traps[sig] if trap for sig is set (even if it's '').
1410 * sigset_t pending_set: set of sigs we received.
1413 * if sig is in special_sig_mask, set handler back to:
1414 * record_pending_signo, or to IGN if it's a tty stop signal
1415 * if sig is in fatal_sig_mask, set handler back to sigexit.
1416 * else: set handler back to SIG_DFL
1417 * "trap 'cmd' SIGxxx":
1418 * set handler to record_pending_signo.
1420 * set handler to SIG_IGN.
1421 * after [v]fork, if we plan to be a shell:
1422 * set signals with special interactive handling to SIG_DFL
1423 * (because child shell is not interactive),
1424 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1425 * after [v]fork, if we plan to exec:
1426 * POSIX says fork clears pending signal mask in child - no need to clear it.
1428 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1429 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1432 * Standard says "When a subshell is entered, traps that are not being ignored
1433 * are set to the default actions". bash interprets it so that traps which
1434 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1437 SPECIAL_INTERACTIVE_SIGS = 0
1442 SPECIAL_JOBSTOP_SIGS = 0
1451 static void record_pending_signo(int sig)
1453 sigaddset(&G.pending_set, sig);
1454 #if ENABLE_HUSH_FAST
1455 if (sig == SIGCHLD) {
1457 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1462 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1464 struct sigaction old_sa;
1466 /* We could use signal() to install handlers... almost:
1467 * except that we need to mask ALL signals while handlers run.
1468 * I saw signal nesting in strace, race window isn't small.
1469 * SA_RESTART is also needed, but in Linux, signal()
1470 * sets SA_RESTART too.
1472 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1473 /* sigfillset(&G.sa.sa_mask); - already done */
1474 /* G.sa.sa_flags = SA_RESTART; - already done */
1475 G.sa.sa_handler = handler;
1476 sigaction(sig, &G.sa, &old_sa);
1477 return old_sa.sa_handler;
1482 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1483 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1484 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1485 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1487 /* Restores tty foreground process group, and exits.
1488 * May be called as signal handler for fatal signal
1489 * (will resend signal to itself, producing correct exit state)
1490 * or called directly with -EXITCODE.
1491 * We also call it if xfunc is exiting. */
1492 static void sigexit(int sig) NORETURN;
1493 static void sigexit(int sig)
1495 /* Careful: we can end up here after [v]fork. Do not restore
1496 * tty pgrp then, only top-level shell process does that */
1497 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1498 /* Disable all signals: job control, SIGPIPE, etc.
1499 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1501 sigprocmask_allsigs(SIG_BLOCK);
1502 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1505 /* Not a signal, just exit */
1509 kill_myself_with_sig(sig); /* does not return */
1513 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1514 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1518 static sighandler_t pick_sighandler(unsigned sig)
1520 sighandler_t handler = SIG_DFL;
1521 if (sig < sizeof(unsigned)*8) {
1522 unsigned sigmask = (1 << sig);
1526 if (G_fatal_sig_mask & sigmask)
1530 /* sig has special handling? */
1531 if (G.special_sig_mask & sigmask) {
1532 handler = record_pending_signo;
1533 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1534 * in order to ignore them: they will be raised
1535 * in an endless loop when we try to do some
1536 * terminal ioctls! We do have to _ignore_ these.
1538 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1545 /* Restores tty foreground process group, and exits. */
1546 static void hush_exit(int exitcode) NORETURN;
1547 static void hush_exit(int exitcode)
1549 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1550 save_history(G.line_input_state);
1554 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1556 /* argv[0] is unused */
1557 argv[1] = G.traps[0];
1559 G.exiting = 1; /* prevent EXIT trap recursion */
1560 /* Note: G.traps[0] is not cleared!
1561 * "trap" will still show it, if executed
1566 #if ENABLE_FEATURE_CLEAN_UP
1568 struct variable *cur_var;
1569 if (G.cwd != bb_msg_unknown)
1571 cur_var = G.top_var;
1573 struct variable *tmp = cur_var;
1574 if (!cur_var->max_len)
1575 free(cur_var->varstr);
1576 cur_var = cur_var->next;
1584 sigexit(- (exitcode & 0xff));
1591 //TODO: return a mask of ALL handled sigs?
1592 static int check_and_run_traps(void)
1599 if (sigisemptyset(&G.pending_set))
1604 if (sigismember(&G.pending_set, sig)) {
1605 sigdelset(&G.pending_set, sig);
1608 } while (sig < NSIG);
1611 if (G.traps && G.traps[sig]) {
1612 if (G.traps[sig][0]) {
1613 /* We have user-defined handler */
1614 smalluint save_rcode;
1616 /* argv[0] is unused */
1617 argv[1] = G.traps[sig];
1619 save_rcode = G.last_exitcode;
1621 G.last_exitcode = save_rcode;
1623 } /* else: "" trap, ignoring signal */
1626 /* not a trap: special action */
1629 /* Builtin was ^C'ed, make it look prettier: */
1637 /* bash is observed to signal whole process groups,
1638 * not individual processes */
1639 for (job = G.job_list; job; job = job->next) {
1642 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1643 if (kill(- job->pgrp, SIGHUP) == 0)
1644 kill(- job->pgrp, SIGCONT);
1649 #if ENABLE_HUSH_FAST
1652 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1654 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1655 * This simplifies wait builtin a bit.
1659 default: /* ignored: */
1660 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1662 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1663 * Example: wait is not interrupted by TERM
1664 * in interactive shell, because TERM is ignored.
1673 static const char *get_cwd(int force)
1675 if (force || G.cwd == NULL) {
1676 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1677 * we must not try to free(bb_msg_unknown) */
1678 if (G.cwd == bb_msg_unknown)
1680 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1682 G.cwd = bb_msg_unknown;
1689 * Shell and environment variable support
1691 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1693 struct variable **pp;
1694 struct variable *cur;
1697 while ((cur = *pp) != NULL) {
1698 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1705 static const char* FAST_FUNC get_local_var_value(const char *name)
1707 struct variable **vpp;
1708 unsigned len = strlen(name);
1710 if (G.expanded_assignments) {
1711 char **cpp = G.expanded_assignments;
1714 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1715 return cp + len + 1;
1720 vpp = get_ptr_to_local_var(name, len);
1722 return (*vpp)->varstr + len + 1;
1724 if (strcmp(name, "PPID") == 0)
1725 return utoa(G.root_ppid);
1726 // bash compat: UID? EUID?
1727 #if ENABLE_HUSH_RANDOM_SUPPORT
1728 if (strcmp(name, "RANDOM") == 0)
1729 return utoa(next_random(&G.random_gen));
1734 /* str holds "NAME=VAL" and is expected to be malloced.
1735 * We take ownership of it.
1737 * 0: do not change export flag
1738 * (if creating new variable, flag will be 0)
1739 * 1: set export flag and putenv the variable
1740 * -1: clear export flag and unsetenv the variable
1741 * flg_read_only is set only when we handle -R var=val
1743 #if !BB_MMU && ENABLE_HUSH_LOCAL
1744 /* all params are used */
1745 #elif BB_MMU && ENABLE_HUSH_LOCAL
1746 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1747 set_local_var(str, flg_export, local_lvl)
1748 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1749 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1750 set_local_var(str, flg_export)
1751 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1752 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1753 set_local_var(str, flg_export, flg_read_only)
1755 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1757 struct variable **var_pp;
1758 struct variable *cur;
1762 eq_sign = strchr(str, '=');
1763 if (!eq_sign) { /* not expected to ever happen? */
1768 name_len = eq_sign - str + 1; /* including '=' */
1769 var_pp = &G.top_var;
1770 while ((cur = *var_pp) != NULL) {
1771 if (strncmp(cur->varstr, str, name_len) != 0) {
1772 var_pp = &cur->next;
1775 /* We found an existing var with this name */
1776 if (cur->flg_read_only) {
1780 bb_error_msg("%s: readonly variable", str);
1784 if (flg_export == -1) { // "&& cur->flg_export" ?
1785 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1790 #if ENABLE_HUSH_LOCAL
1791 if (cur->func_nest_level < local_lvl) {
1792 /* New variable is declared as local,
1793 * and existing one is global, or local
1794 * from enclosing function.
1795 * Remove and save old one: */
1796 *var_pp = cur->next;
1797 cur->next = *G.shadowed_vars_pp;
1798 *G.shadowed_vars_pp = cur;
1799 /* bash 3.2.33(1) and exported vars:
1801 * # f() { local z=a; env | grep ^z; }
1807 if (cur->flg_export)
1812 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1817 if (cur->max_len != 0) {
1818 if (cur->max_len >= strlen(str)) {
1819 /* This one is from startup env, reuse space */
1820 strcpy(cur->varstr, str);
1824 /* max_len == 0 signifies "malloced" var, which we can
1825 * (and has to) free */
1829 goto set_str_and_exp;
1832 /* Not found - create new variable struct */
1833 cur = xzalloc(sizeof(*cur));
1834 #if ENABLE_HUSH_LOCAL
1835 cur->func_nest_level = local_lvl;
1837 cur->next = *var_pp;
1843 cur->flg_read_only = flg_read_only;
1846 if (flg_export == 1)
1847 cur->flg_export = 1;
1848 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1849 cmdedit_update_prompt();
1850 if (cur->flg_export) {
1851 if (flg_export == -1) {
1852 cur->flg_export = 0;
1853 /* unsetenv was already done */
1855 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1856 return putenv(cur->varstr);
1862 /* Used at startup and after each cd */
1863 static void set_pwd_var(int exp)
1865 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1866 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1869 static int unset_local_var_len(const char *name, int name_len)
1871 struct variable *cur;
1872 struct variable **var_pp;
1875 return EXIT_SUCCESS;
1876 var_pp = &G.top_var;
1877 while ((cur = *var_pp) != NULL) {
1878 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1879 if (cur->flg_read_only) {
1880 bb_error_msg("%s: readonly variable", name);
1881 return EXIT_FAILURE;
1883 *var_pp = cur->next;
1884 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1885 bb_unsetenv(cur->varstr);
1886 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1887 cmdedit_update_prompt();
1891 return EXIT_SUCCESS;
1893 var_pp = &cur->next;
1895 return EXIT_SUCCESS;
1898 static int unset_local_var(const char *name)
1900 return unset_local_var_len(name, strlen(name));
1903 static void unset_vars(char **strings)
1911 const char *eq = strchrnul(*v, '=');
1912 unset_local_var_len(*v, (int)(eq - *v));
1918 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1920 char *var = xasprintf("%s=%s", name, val);
1921 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1926 * Helpers for "var1=val1 var2=val2 cmd" feature
1928 static void add_vars(struct variable *var)
1930 struct variable *next;
1934 var->next = G.top_var;
1936 if (var->flg_export) {
1937 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1938 putenv(var->varstr);
1940 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1946 static struct variable *set_vars_and_save_old(char **strings)
1949 struct variable *old = NULL;
1955 struct variable *var_p;
1956 struct variable **var_pp;
1959 eq = strchr(*s, '=');
1961 var_pp = get_ptr_to_local_var(*s, eq - *s);
1963 /* Remove variable from global linked list */
1965 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1966 *var_pp = var_p->next;
1967 /* Add it to returned list */
1971 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1982 static void reinit_unicode_for_hush(void)
1984 /* Unicode support should be activated even if LANG is set
1985 * _during_ shell execution, not only if it was set when
1986 * shell was started. Therefore, re-check LANG every time:
1988 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
1989 || ENABLE_UNICODE_USING_LOCALE
1991 const char *s = get_local_var_value("LC_ALL");
1992 if (!s) s = get_local_var_value("LC_CTYPE");
1993 if (!s) s = get_local_var_value("LANG");
2002 static int FAST_FUNC static_get(struct in_str *i)
2013 static int FAST_FUNC static_peek(struct in_str *i)
2018 #if ENABLE_HUSH_INTERACTIVE
2020 static void cmdedit_update_prompt(void)
2022 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2023 G.PS1 = get_local_var_value("PS1");
2026 G.PS2 = get_local_var_value("PS2");
2034 static const char *setup_prompt_string(int promptmode)
2036 const char *prompt_str;
2037 debug_printf("setup_prompt_string %d ", promptmode);
2038 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2039 /* Set up the prompt */
2040 if (promptmode == 0) { /* PS1 */
2042 /* bash uses $PWD value, even if it is set by user.
2043 * It uses current dir only if PWD is unset.
2044 * We always use current dir. */
2045 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2050 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2051 debug_printf("result '%s'\n", prompt_str);
2055 static void get_user_input(struct in_str *i)
2058 const char *prompt_str;
2060 prompt_str = setup_prompt_string(i->promptmode);
2061 # if ENABLE_FEATURE_EDITING
2062 /* Enable command line editing only while a command line
2063 * is actually being read */
2065 reinit_unicode_for_hush();
2067 /* buglet: SIGINT will not make new prompt to appear _at once_,
2068 * only after <Enter>. (^C will work) */
2069 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2070 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2071 check_and_run_traps();
2072 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2073 i->eof_flag = (r < 0);
2074 if (i->eof_flag) { /* EOF/error detected */
2075 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2076 G.user_input_buf[1] = '\0';
2081 if (i->last_char == '\0' || i->last_char == '\n') {
2082 /* Why check_and_run_traps here? Try this interactively:
2083 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2084 * $ <[enter], repeatedly...>
2085 * Without check_and_run_traps, handler never runs.
2087 check_and_run_traps();
2088 fputs(prompt_str, stdout);
2091 G.user_input_buf[0] = r = fgetc(i->file);
2092 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2093 } while (G.flag_SIGINT);
2094 i->eof_flag = (r == EOF);
2096 i->p = G.user_input_buf;
2099 #endif /* INTERACTIVE */
2101 /* This is the magic location that prints prompts
2102 * and gets data back from the user */
2103 static int FAST_FUNC file_get(struct in_str *i)
2107 /* If there is data waiting, eat it up */
2108 if (i->p && *i->p) {
2109 #if ENABLE_HUSH_INTERACTIVE
2113 if (i->eof_flag && !*i->p)
2115 /* note: ch is never NUL */
2117 /* need to double check i->file because we might be doing something
2118 * more complicated by now, like sourcing or substituting. */
2119 #if ENABLE_HUSH_INTERACTIVE
2120 if (G_interactive_fd && i->file == stdin) {
2123 } while (!*i->p); /* need non-empty line */
2124 i->promptmode = 1; /* PS2 */
2128 do ch = fgetc(i->file); while (ch == '\0');
2130 debug_printf("file_get: got '%c' %d\n", ch, ch);
2135 /* All callers guarantee this routine will never
2136 * be used right after a newline, so prompting is not needed.
2138 static int FAST_FUNC file_peek(struct in_str *i)
2141 if (i->p && *i->p) {
2142 if (i->eof_flag && !i->p[1])
2145 /* note: ch is never NUL */
2147 do ch = fgetc(i->file); while (ch == '\0');
2148 i->eof_flag = (ch == EOF);
2149 i->peek_buf[0] = ch;
2150 i->peek_buf[1] = '\0';
2152 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2156 static void setup_file_in_str(struct in_str *i, FILE *f)
2158 memset(i, 0, sizeof(*i));
2159 i->peek = file_peek;
2161 /* i->promptmode = 0; - PS1 (memset did it) */
2166 static void setup_string_in_str(struct in_str *i, const char *s)
2168 memset(i, 0, sizeof(*i));
2169 i->peek = static_peek;
2170 i->get = static_get;
2171 /* i->promptmode = 0; - PS1 (memset did it) */
2173 /* i->eof_flag = 0; */
2180 #define B_CHUNK (32 * sizeof(char*))
2182 static void o_reset_to_empty_unquoted(o_string *o)
2185 o->has_quoted_part = 0;
2190 static void o_free(o_string *o)
2193 memset(o, 0, sizeof(*o));
2196 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2201 static void o_grow_by(o_string *o, int len)
2203 if (o->length + len > o->maxlen) {
2204 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2205 o->data = xrealloc(o->data, 1 + o->maxlen);
2209 static void o_addchr(o_string *o, int ch)
2211 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2213 o->data[o->length] = ch;
2215 o->data[o->length] = '\0';
2218 static void o_addblock(o_string *o, const char *str, int len)
2221 memcpy(&o->data[o->length], str, len);
2223 o->data[o->length] = '\0';
2226 static void o_addstr(o_string *o, const char *str)
2228 o_addblock(o, str, strlen(str));
2232 static void nommu_addchr(o_string *o, int ch)
2238 # define nommu_addchr(o, str) ((void)0)
2241 static void o_addstr_with_NUL(o_string *o, const char *str)
2243 o_addblock(o, str, strlen(str) + 1);
2247 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2248 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2249 * Apparently, on unquoted $v bash still does globbing
2250 * ("v='*.txt'; echo $v" prints all .txt files),
2251 * but NOT brace expansion! Thus, there should be TWO independent
2252 * quoting mechanisms on $v expansion side: one protects
2253 * $v from brace expansion, and other additionally protects "$v" against globbing.
2254 * We have only second one.
2257 #if ENABLE_HUSH_BRACE_EXPANSION
2258 # define MAYBE_BRACES "{}"
2260 # define MAYBE_BRACES ""
2263 /* My analysis of quoting semantics tells me that state information
2264 * is associated with a destination, not a source.
2266 static void o_addqchr(o_string *o, int ch)
2269 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2274 o->data[o->length] = '\\';
2277 o->data[o->length] = ch;
2279 o->data[o->length] = '\0';
2282 static void o_addQchr(o_string *o, int ch)
2285 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2286 && strchr("*?[\\" MAYBE_BRACES, ch)
2289 o->data[o->length] = '\\';
2293 o->data[o->length] = ch;
2295 o->data[o->length] = '\0';
2298 static void o_addqblock(o_string *o, const char *str, int len)
2303 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2304 if (ordinary_cnt > len) /* paranoia */
2306 o_addblock(o, str, ordinary_cnt);
2307 if (ordinary_cnt == len)
2308 return; /* NUL is already added by o_addblock */
2309 str += ordinary_cnt;
2310 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2314 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2316 o->data[o->length] = '\\';
2320 o->data[o->length] = ch;
2323 o->data[o->length] = '\0';
2326 static void o_addQblock(o_string *o, const char *str, int len)
2328 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2329 o_addblock(o, str, len);
2332 o_addqblock(o, str, len);
2335 static void o_addQstr(o_string *o, const char *str)
2337 o_addQblock(o, str, strlen(str));
2340 /* A special kind of o_string for $VAR and `cmd` expansion.
2341 * It contains char* list[] at the beginning, which is grown in 16 element
2342 * increments. Actual string data starts at the next multiple of 16 * (char*).
2343 * list[i] contains an INDEX (int!) into this string data.
2344 * It means that if list[] needs to grow, data needs to be moved higher up
2345 * but list[i]'s need not be modified.
2346 * NB: remembering how many list[i]'s you have there is crucial.
2347 * o_finalize_list() operation post-processes this structure - calculates
2348 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2350 #if DEBUG_EXPAND || DEBUG_GLOB
2351 static void debug_print_list(const char *prefix, o_string *o, int n)
2353 char **list = (char**)o->data;
2354 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2358 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2359 prefix, list, n, string_start, o->length, o->maxlen,
2360 !!(o->o_expflags & EXP_FLAG_GLOB),
2362 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2365 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2366 o->data + (int)(uintptr_t)list[i] + string_start,
2367 o->data + (int)(uintptr_t)list[i] + string_start);
2371 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2373 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2377 # define debug_print_list(prefix, o, n) ((void)0)
2380 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2381 * in list[n] so that it points past last stored byte so far.
2382 * It returns n+1. */
2383 static int o_save_ptr_helper(o_string *o, int n)
2385 char **list = (char**)o->data;
2389 if (!o->has_empty_slot) {
2390 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2391 string_len = o->length - string_start;
2392 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2393 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2394 /* list[n] points to string_start, make space for 16 more pointers */
2395 o->maxlen += 0x10 * sizeof(list[0]);
2396 o->data = xrealloc(o->data, o->maxlen + 1);
2397 list = (char**)o->data;
2398 memmove(list + n + 0x10, list + n, string_len);
2399 o->length += 0x10 * sizeof(list[0]);
2401 debug_printf_list("list[%d]=%d string_start=%d\n",
2402 n, string_len, string_start);
2405 /* We have empty slot at list[n], reuse without growth */
2406 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2407 string_len = o->length - string_start;
2408 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2409 n, string_len, string_start);
2410 o->has_empty_slot = 0;
2412 o->has_quoted_part = 0;
2413 list[n] = (char*)(uintptr_t)string_len;
2417 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2418 static int o_get_last_ptr(o_string *o, int n)
2420 char **list = (char**)o->data;
2421 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2423 return ((int)(uintptr_t)list[n-1]) + string_start;
2426 #if ENABLE_HUSH_BRACE_EXPANSION
2427 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2428 * first, it processes even {a} (no commas), second,
2429 * I didn't manage to make it return strings when they don't match
2430 * existing files. Need to re-implement it.
2434 static int glob_needed(const char *s)
2443 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2449 /* Return pointer to next closing brace or to comma */
2450 static const char *next_brace_sub(const char *cp)
2454 while (*cp != '\0') {
2461 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2467 return *cp != '\0' ? cp : NULL;
2469 /* Recursive brace globber. Note: may garble pattern[]. */
2470 static int glob_brace(char *pattern, o_string *o, int n)
2472 char *new_pattern_buf;
2479 debug_printf_glob("glob_brace('%s')\n", pattern);
2485 if (*begin == '{') {
2486 /* Find the first sub-pattern and at the same time
2487 * find the rest after the closing brace */
2488 next = next_brace_sub(begin);
2490 /* An illegal expression */
2494 /* "{abc}" with no commas - illegal
2495 * brace expr, disregard and skip it */
2501 if (*begin == '\\' && begin[1] != '\0')
2505 debug_printf_glob("begin:%s\n", begin);
2506 debug_printf_glob("next:%s\n", next);
2508 /* Now find the end of the whole brace expression */
2510 while (*rest != '}') {
2511 rest = next_brace_sub(rest);
2513 /* An illegal expression */
2516 debug_printf_glob("rest:%s\n", rest);
2518 rest_len = strlen(++rest) + 1;
2520 /* We are sure the brace expression is well-formed */
2522 /* Allocate working buffer large enough for our work */
2523 new_pattern_buf = xmalloc(strlen(pattern));
2525 /* We have a brace expression. BEGIN points to the opening {,
2526 * NEXT points past the terminator of the first element, and REST
2527 * points past the final }. We will accumulate result names from
2528 * recursive runs for each brace alternative in the buffer using
2533 /* Construct the new glob expression */
2536 mempcpy(new_pattern_buf,
2537 /* We know the prefix for all sub-patterns */
2538 pattern, begin - pattern),
2542 /* Note: glob_brace() may garble new_pattern_buf[].
2543 * That's why we re-copy prefix every time (1st memcpy above).
2545 n = glob_brace(new_pattern_buf, o, n);
2547 /* We saw the last entry */
2551 next = next_brace_sub(next);
2553 free(new_pattern_buf);
2561 memset(&globdata, 0, sizeof(globdata));
2562 gr = glob(pattern, 0, NULL, &globdata);
2563 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2565 if (gr == GLOB_NOMATCH) {
2566 globfree(&globdata);
2567 /* NB: garbles parameter */
2568 unbackslash(pattern);
2569 o_addstr_with_NUL(o, pattern);
2570 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2571 return o_save_ptr_helper(o, n);
2573 if (gr == GLOB_NOSPACE)
2574 bb_error_msg_and_die(bb_msg_memory_exhausted);
2575 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2576 * but we didn't specify it. Paranoia again. */
2577 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2579 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2580 char **argv = globdata.gl_pathv;
2582 o_addstr_with_NUL(o, *argv);
2583 n = o_save_ptr_helper(o, n);
2589 globfree(&globdata);
2593 /* Performs globbing on last list[],
2594 * saving each result as a new list[].
2596 static int perform_glob(o_string *o, int n)
2598 char *pattern, *copy;
2600 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2602 return o_save_ptr_helper(o, n);
2603 pattern = o->data + o_get_last_ptr(o, n);
2604 debug_printf_glob("glob pattern '%s'\n", pattern);
2605 if (!glob_needed(pattern)) {
2606 /* unbackslash last string in o in place, fix length */
2607 o->length = unbackslash(pattern) - o->data;
2608 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2609 return o_save_ptr_helper(o, n);
2612 copy = xstrdup(pattern);
2613 /* "forget" pattern in o */
2614 o->length = pattern - o->data;
2615 n = glob_brace(copy, o, n);
2618 debug_print_list("perform_glob returning", o, n);
2622 #else /* !HUSH_BRACE_EXPANSION */
2625 static int glob_needed(const char *s)
2634 if (*s == '*' || *s == '[' || *s == '?')
2640 /* Performs globbing on last list[],
2641 * saving each result as a new list[].
2643 static int perform_glob(o_string *o, int n)
2649 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2651 return o_save_ptr_helper(o, n);
2652 pattern = o->data + o_get_last_ptr(o, n);
2653 debug_printf_glob("glob pattern '%s'\n", pattern);
2654 if (!glob_needed(pattern)) {
2656 /* unbackslash last string in o in place, fix length */
2657 o->length = unbackslash(pattern) - o->data;
2658 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2659 return o_save_ptr_helper(o, n);
2662 memset(&globdata, 0, sizeof(globdata));
2663 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2664 * If we glob "*.\*" and don't find anything, we need
2665 * to fall back to using literal "*.*", but GLOB_NOCHECK
2666 * will return "*.\*"!
2668 gr = glob(pattern, 0, NULL, &globdata);
2669 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2671 if (gr == GLOB_NOMATCH) {
2672 globfree(&globdata);
2675 if (gr == GLOB_NOSPACE)
2676 bb_error_msg_and_die(bb_msg_memory_exhausted);
2677 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2678 * but we didn't specify it. Paranoia again. */
2679 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2681 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2682 char **argv = globdata.gl_pathv;
2683 /* "forget" pattern in o */
2684 o->length = pattern - o->data;
2686 o_addstr_with_NUL(o, *argv);
2687 n = o_save_ptr_helper(o, n);
2693 globfree(&globdata);
2695 debug_print_list("perform_glob returning", o, n);
2699 #endif /* !HUSH_BRACE_EXPANSION */
2701 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2702 * Otherwise, just finish current list[] and start new */
2703 static int o_save_ptr(o_string *o, int n)
2705 if (o->o_expflags & EXP_FLAG_GLOB) {
2706 /* If o->has_empty_slot, list[n] was already globbed
2707 * (if it was requested back then when it was filled)
2708 * so don't do that again! */
2709 if (!o->has_empty_slot)
2710 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2712 return o_save_ptr_helper(o, n);
2715 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2716 static char **o_finalize_list(o_string *o, int n)
2721 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2723 debug_print_list("finalized", o, n);
2724 debug_printf_expand("finalized n:%d\n", n);
2725 list = (char**)o->data;
2726 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2730 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2735 static void free_pipe_list(struct pipe *pi);
2737 /* Returns pi->next - next pipe in the list */
2738 static struct pipe *free_pipe(struct pipe *pi)
2743 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2744 for (i = 0; i < pi->num_cmds; i++) {
2745 struct command *command;
2746 struct redir_struct *r, *rnext;
2748 command = &pi->cmds[i];
2749 debug_printf_clean(" command %d:\n", i);
2750 if (command->argv) {
2754 for (a = 0, p = command->argv; *p; a++, p++) {
2755 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2758 free_strings(command->argv);
2759 //command->argv = NULL;
2761 /* not "else if": on syntax error, we may have both! */
2762 if (command->group) {
2763 debug_printf_clean(" begin group (cmd_type:%d)\n",
2765 free_pipe_list(command->group);
2766 debug_printf_clean(" end group\n");
2767 //command->group = NULL;
2769 /* else is crucial here.
2770 * If group != NULL, child_func is meaningless */
2771 #if ENABLE_HUSH_FUNCTIONS
2772 else if (command->child_func) {
2773 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2774 command->child_func->parent_cmd = NULL;
2778 free(command->group_as_string);
2779 //command->group_as_string = NULL;
2781 for (r = command->redirects; r; r = rnext) {
2782 debug_printf_clean(" redirect %d%s",
2783 r->rd_fd, redir_table[r->rd_type].descrip);
2784 /* guard against the case >$FOO, where foo is unset or blank */
2785 if (r->rd_filename) {
2786 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2787 free(r->rd_filename);
2788 //r->rd_filename = NULL;
2790 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2794 //command->redirects = NULL;
2796 free(pi->cmds); /* children are an array, they get freed all at once */
2800 //pi->cmdtext = NULL;
2808 static void free_pipe_list(struct pipe *pi)
2812 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2814 debug_printf_clean("pipe followup code %d\n", pi->followup);
2820 /*** Parsing routines ***/
2822 #ifndef debug_print_tree
2823 static void debug_print_tree(struct pipe *pi, int lvl)
2825 static const char *const PIPE[] = {
2831 static const char *RES[] = {
2832 [RES_NONE ] = "NONE" ,
2835 [RES_THEN ] = "THEN" ,
2836 [RES_ELIF ] = "ELIF" ,
2837 [RES_ELSE ] = "ELSE" ,
2840 # if ENABLE_HUSH_LOOPS
2841 [RES_FOR ] = "FOR" ,
2842 [RES_WHILE] = "WHILE",
2843 [RES_UNTIL] = "UNTIL",
2845 [RES_DONE ] = "DONE" ,
2847 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2850 # if ENABLE_HUSH_CASE
2851 [RES_CASE ] = "CASE" ,
2852 [RES_CASE_IN ] = "CASE_IN" ,
2853 [RES_MATCH] = "MATCH",
2854 [RES_CASE_BODY] = "CASE_BODY",
2855 [RES_ESAC ] = "ESAC" ,
2857 [RES_XXXX ] = "XXXX" ,
2858 [RES_SNTX ] = "SNTX" ,
2860 static const char *const CMDTYPE[] = {
2864 # if ENABLE_HUSH_FUNCTIONS
2873 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2874 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2876 while (prn < pi->num_cmds) {
2877 struct command *command = &pi->cmds[prn];
2878 char **argv = command->argv;
2880 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2882 command->assignment_cnt);
2883 if (command->group) {
2884 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2885 CMDTYPE[command->cmd_type],
2888 , " group_as_string:", command->group_as_string
2893 debug_print_tree(command->group, lvl+1);
2897 if (argv) while (*argv) {
2898 fdprintf(2, " '%s'", *argv);
2908 #endif /* debug_print_tree */
2910 static struct pipe *new_pipe(void)
2913 pi = xzalloc(sizeof(struct pipe));
2914 /*pi->followup = 0; - deliberately invalid value */
2915 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2919 /* Command (member of a pipe) is complete, or we start a new pipe
2920 * if ctx->command is NULL.
2921 * No errors possible here.
2923 static int done_command(struct parse_context *ctx)
2925 /* The command is really already in the pipe structure, so
2926 * advance the pipe counter and make a new, null command. */
2927 struct pipe *pi = ctx->pipe;
2928 struct command *command = ctx->command;
2931 if (IS_NULL_CMD(command)) {
2932 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2936 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2937 //debug_print_tree(ctx->list_head, 20);
2939 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2942 /* Only real trickiness here is that the uncommitted
2943 * command structure is not counted in pi->num_cmds. */
2944 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2945 ctx->command = command = &pi->cmds[pi->num_cmds];
2947 memset(command, 0, sizeof(*command));
2948 return pi->num_cmds; /* used only for 0/nonzero check */
2951 static void done_pipe(struct parse_context *ctx, pipe_style type)
2955 debug_printf_parse("done_pipe entered, followup %d\n", type);
2956 /* Close previous command */
2957 not_null = done_command(ctx);
2958 ctx->pipe->followup = type;
2960 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2961 ctx->ctx_inverted = 0;
2962 ctx->pipe->res_word = ctx->ctx_res_w;
2965 /* Without this check, even just <enter> on command line generates
2966 * tree of three NOPs (!). Which is harmless but annoying.
2967 * IOW: it is safe to do it unconditionally. */
2970 || ctx->ctx_res_w == RES_FI
2972 #if ENABLE_HUSH_LOOPS
2973 || ctx->ctx_res_w == RES_DONE
2974 || ctx->ctx_res_w == RES_FOR
2975 || ctx->ctx_res_w == RES_IN
2977 #if ENABLE_HUSH_CASE
2978 || ctx->ctx_res_w == RES_ESAC
2982 debug_printf_parse("done_pipe: adding new pipe: "
2983 "not_null:%d ctx->ctx_res_w:%d\n",
2984 not_null, ctx->ctx_res_w);
2986 ctx->pipe->next = new_p;
2988 /* RES_THEN, RES_DO etc are "sticky" -
2989 * they remain set for pipes inside if/while.
2990 * This is used to control execution.
2991 * RES_FOR and RES_IN are NOT sticky (needed to support
2992 * cases where variable or value happens to match a keyword):
2994 #if ENABLE_HUSH_LOOPS
2995 if (ctx->ctx_res_w == RES_FOR
2996 || ctx->ctx_res_w == RES_IN)
2997 ctx->ctx_res_w = RES_NONE;
2999 #if ENABLE_HUSH_CASE
3000 if (ctx->ctx_res_w == RES_MATCH)
3001 ctx->ctx_res_w = RES_CASE_BODY;
3002 if (ctx->ctx_res_w == RES_CASE)
3003 ctx->ctx_res_w = RES_CASE_IN;
3005 ctx->command = NULL; /* trick done_command below */
3006 /* Create the memory for command, roughly:
3007 * ctx->pipe->cmds = new struct command;
3008 * ctx->command = &ctx->pipe->cmds[0];
3011 //debug_print_tree(ctx->list_head, 10);
3013 debug_printf_parse("done_pipe return\n");
3016 static void initialize_context(struct parse_context *ctx)
3018 memset(ctx, 0, sizeof(*ctx));
3019 ctx->pipe = ctx->list_head = new_pipe();
3020 /* Create the memory for command, roughly:
3021 * ctx->pipe->cmds = new struct command;
3022 * ctx->command = &ctx->pipe->cmds[0];
3027 /* If a reserved word is found and processed, parse context is modified
3028 * and 1 is returned.
3031 struct reserved_combo {
3034 unsigned char assignment_flag;
3038 FLAG_END = (1 << RES_NONE ),
3040 FLAG_IF = (1 << RES_IF ),
3041 FLAG_THEN = (1 << RES_THEN ),
3042 FLAG_ELIF = (1 << RES_ELIF ),
3043 FLAG_ELSE = (1 << RES_ELSE ),
3044 FLAG_FI = (1 << RES_FI ),
3046 # if ENABLE_HUSH_LOOPS
3047 FLAG_FOR = (1 << RES_FOR ),
3048 FLAG_WHILE = (1 << RES_WHILE),
3049 FLAG_UNTIL = (1 << RES_UNTIL),
3050 FLAG_DO = (1 << RES_DO ),
3051 FLAG_DONE = (1 << RES_DONE ),
3052 FLAG_IN = (1 << RES_IN ),
3054 # if ENABLE_HUSH_CASE
3055 FLAG_MATCH = (1 << RES_MATCH),
3056 FLAG_ESAC = (1 << RES_ESAC ),
3058 FLAG_START = (1 << RES_XXXX ),
3061 static const struct reserved_combo* match_reserved_word(o_string *word)
3063 /* Mostly a list of accepted follow-up reserved words.
3064 * FLAG_END means we are done with the sequence, and are ready
3065 * to turn the compound list into a command.
3066 * FLAG_START means the word must start a new compound list.
3068 static const struct reserved_combo reserved_list[] = {
3070 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3071 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3072 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3073 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3074 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3075 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3077 # if ENABLE_HUSH_LOOPS
3078 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3079 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3080 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3081 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3082 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3083 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3085 # if ENABLE_HUSH_CASE
3086 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3087 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3090 const struct reserved_combo *r;
3092 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3093 if (strcmp(word->data, r->literal) == 0)
3098 /* Return 0: not a keyword, 1: keyword
3100 static int reserved_word(o_string *word, struct parse_context *ctx)
3102 # if ENABLE_HUSH_CASE
3103 static const struct reserved_combo reserved_match = {
3104 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3107 const struct reserved_combo *r;
3109 if (word->has_quoted_part)
3111 r = match_reserved_word(word);
3115 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3116 # if ENABLE_HUSH_CASE
3117 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3118 /* "case word IN ..." - IN part starts first MATCH part */
3119 r = &reserved_match;
3122 if (r->flag == 0) { /* '!' */
3123 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3124 syntax_error("! ! command");
3125 ctx->ctx_res_w = RES_SNTX;
3127 ctx->ctx_inverted = 1;
3130 if (r->flag & FLAG_START) {
3131 struct parse_context *old;
3133 old = xmalloc(sizeof(*old));
3134 debug_printf_parse("push stack %p\n", old);
3135 *old = *ctx; /* physical copy */
3136 initialize_context(ctx);
3138 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3139 syntax_error_at(word->data);
3140 ctx->ctx_res_w = RES_SNTX;
3143 /* "{...} fi" is ok. "{...} if" is not
3145 * if { echo foo; } then { echo bar; } fi */
3146 if (ctx->command->group)
3147 done_pipe(ctx, PIPE_SEQ);
3150 ctx->ctx_res_w = r->res;
3151 ctx->old_flag = r->flag;
3152 word->o_assignment = r->assignment_flag;
3153 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3155 if (ctx->old_flag & FLAG_END) {
3156 struct parse_context *old;
3158 done_pipe(ctx, PIPE_SEQ);
3159 debug_printf_parse("pop stack %p\n", ctx->stack);
3161 old->command->group = ctx->list_head;
3162 old->command->cmd_type = CMD_NORMAL;
3164 o_addstr(&old->as_string, ctx->as_string.data);
3165 o_free_unsafe(&ctx->as_string);
3166 old->command->group_as_string = xstrdup(old->as_string.data);
3167 debug_printf_parse("pop, remembering as:'%s'\n",
3168 old->command->group_as_string);
3170 *ctx = *old; /* physical copy */
3175 #endif /* HAS_KEYWORDS */
3177 /* Word is complete, look at it and update parsing context.
3178 * Normal return is 0. Syntax errors return 1.
3179 * Note: on return, word is reset, but not o_free'd!
3181 static int done_word(o_string *word, struct parse_context *ctx)
3183 struct command *command = ctx->command;
3185 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3186 if (word->length == 0 && !word->has_quoted_part) {
3187 debug_printf_parse("done_word return 0: true null, ignored\n");
3191 if (ctx->pending_redirect) {
3192 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3193 * only if run as "bash", not "sh" */
3194 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3196 * ...the word that follows the redirection operator
3197 * shall be subjected to tilde expansion, parameter expansion,
3198 * command substitution, arithmetic expansion, and quote
3199 * removal. Pathname expansion shall not be performed
3200 * on the word by a non-interactive shell; an interactive
3201 * shell may perform it, but shall do so only when
3202 * the expansion would result in one word."
3204 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3205 /* Cater for >\file case:
3206 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3207 * Same with heredocs:
3208 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3210 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3211 unbackslash(ctx->pending_redirect->rd_filename);
3212 /* Is it <<"HEREDOC"? */
3213 if (word->has_quoted_part) {
3214 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3217 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3218 ctx->pending_redirect = NULL;
3221 # if ENABLE_HUSH_CASE
3222 if (ctx->ctx_dsemicolon
3223 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3225 /* already done when ctx_dsemicolon was set to 1: */
3226 /* ctx->ctx_res_w = RES_MATCH; */
3227 ctx->ctx_dsemicolon = 0;
3230 if (!command->argv /* if it's the first word... */
3231 # if ENABLE_HUSH_LOOPS
3232 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3233 && ctx->ctx_res_w != RES_IN
3235 # if ENABLE_HUSH_CASE
3236 && ctx->ctx_res_w != RES_CASE
3239 int reserved = reserved_word(word, ctx);
3240 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3242 o_reset_to_empty_unquoted(word);
3243 debug_printf_parse("done_word return %d\n",
3244 (ctx->ctx_res_w == RES_SNTX));
3245 return (ctx->ctx_res_w == RES_SNTX);
3247 # if ENABLE_HUSH_BASH_COMPAT
3248 if (strcmp(word->data, "[[") == 0) {
3249 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3255 if (command->group) {
3256 /* "{ echo foo; } echo bar" - bad */
3257 syntax_error_at(word->data);
3258 debug_printf_parse("done_word return 1: syntax error, "
3259 "groups and arglists don't mix\n");
3263 /* If this word wasn't an assignment, next ones definitely
3264 * can't be assignments. Even if they look like ones. */
3265 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3266 && word->o_assignment != WORD_IS_KEYWORD
3268 word->o_assignment = NOT_ASSIGNMENT;
3270 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3271 command->assignment_cnt++;
3272 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3274 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3275 word->o_assignment = MAYBE_ASSIGNMENT;
3277 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3279 if (word->has_quoted_part
3280 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3281 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3282 /* (otherwise it's known to be not empty and is already safe) */
3284 /* exclude "$@" - it can expand to no word despite "" */
3285 char *p = word->data;
3286 while (p[0] == SPECIAL_VAR_SYMBOL
3287 && (p[1] & 0x7f) == '@'
3288 && p[2] == SPECIAL_VAR_SYMBOL
3293 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3294 debug_print_strings("word appended to argv", command->argv);
3297 #if ENABLE_HUSH_LOOPS
3298 if (ctx->ctx_res_w == RES_FOR) {
3299 if (word->has_quoted_part
3300 || !is_well_formed_var_name(command->argv[0], '\0')
3302 /* bash says just "not a valid identifier" */
3303 syntax_error("not a valid identifier in for");
3306 /* Force FOR to have just one word (variable name) */
3307 /* NB: basically, this makes hush see "for v in ..."
3308 * syntax as if it is "for v; in ...". FOR and IN become
3309 * two pipe structs in parse tree. */
3310 done_pipe(ctx, PIPE_SEQ);
3313 #if ENABLE_HUSH_CASE
3314 /* Force CASE to have just one word */
3315 if (ctx->ctx_res_w == RES_CASE) {
3316 done_pipe(ctx, PIPE_SEQ);
3320 o_reset_to_empty_unquoted(word);
3322 debug_printf_parse("done_word return 0\n");
3327 /* Peek ahead in the input to find out if we have a "&n" construct,
3328 * as in "2>&1", that represents duplicating a file descriptor.
3330 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3331 * REDIRFD_SYNTAX_ERR if syntax error,
3332 * REDIRFD_TO_FILE if no & was seen,
3333 * or the number found.
3336 #define parse_redir_right_fd(as_string, input) \
3337 parse_redir_right_fd(input)
3339 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3345 return REDIRFD_TO_FILE;
3347 ch = i_getch(input); /* get the & */
3348 nommu_addchr(as_string, ch);
3351 ch = i_getch(input);
3352 nommu_addchr(as_string, ch);
3353 return REDIRFD_CLOSE;
3357 while (ch != EOF && isdigit(ch)) {
3358 d = d*10 + (ch-'0');
3360 ch = i_getch(input);
3361 nommu_addchr(as_string, ch);
3366 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3368 bb_error_msg("ambiguous redirect");
3369 return REDIRFD_SYNTAX_ERR;
3372 /* Return code is 0 normal, 1 if a syntax error is detected
3374 static int parse_redirect(struct parse_context *ctx,
3377 struct in_str *input)
3379 struct command *command = ctx->command;
3380 struct redir_struct *redir;
3381 struct redir_struct **redirp;
3384 dup_num = REDIRFD_TO_FILE;
3385 if (style != REDIRECT_HEREDOC) {
3386 /* Check for a '>&1' type redirect */
3387 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3388 if (dup_num == REDIRFD_SYNTAX_ERR)
3391 int ch = i_peek(input);
3392 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3393 if (dup_num) { /* <<-... */
3394 ch = i_getch(input);
3395 nommu_addchr(&ctx->as_string, ch);
3400 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3401 int ch = i_peek(input);
3403 /* >|FILE redirect ("clobbering" >).
3404 * Since we do not support "set -o noclobber" yet,
3405 * >| and > are the same for now. Just eat |.
3407 ch = i_getch(input);
3408 nommu_addchr(&ctx->as_string, ch);
3412 /* Create a new redir_struct and append it to the linked list */
3413 redirp = &command->redirects;
3414 while ((redir = *redirp) != NULL) {
3415 redirp = &(redir->next);
3417 *redirp = redir = xzalloc(sizeof(*redir));
3418 /* redir->next = NULL; */
3419 /* redir->rd_filename = NULL; */
3420 redir->rd_type = style;
3421 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3423 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3424 redir_table[style].descrip);
3426 redir->rd_dup = dup_num;
3427 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3428 /* Erik had a check here that the file descriptor in question
3429 * is legit; I postpone that to "run time"
3430 * A "-" representation of "close me" shows up as a -3 here */
3431 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3432 redir->rd_fd, redir->rd_dup);
3434 /* Set ctx->pending_redirect, so we know what to do at the
3435 * end of the next parsed word. */
3436 ctx->pending_redirect = redir;
3441 /* If a redirect is immediately preceded by a number, that number is
3442 * supposed to tell which file descriptor to redirect. This routine
3443 * looks for such preceding numbers. In an ideal world this routine
3444 * needs to handle all the following classes of redirects...
3445 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3446 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3447 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3448 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3450 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3452 * ... If n is quoted, the number shall not be recognized as part of
3453 * the redirection expression. For example:
3455 * writes the character 2 into file a"
3456 * We are getting it right by setting ->has_quoted_part on any \<char>
3458 * A -1 return means no valid number was found,
3459 * the caller should use the appropriate default for this redirection.
3461 static int redirect_opt_num(o_string *o)
3465 if (o->data == NULL)
3467 num = bb_strtou(o->data, NULL, 10);
3468 if (errno || num < 0)
3470 o_reset_to_empty_unquoted(o);
3475 #define fetch_till_str(as_string, input, word, skip_tabs) \
3476 fetch_till_str(input, word, skip_tabs)
3478 static char *fetch_till_str(o_string *as_string,
3479 struct in_str *input,
3483 o_string heredoc = NULL_O_STRING;
3485 int prev = 0; /* not \ */
3491 ch = i_getch(input);
3493 nommu_addchr(as_string, ch);
3494 if ((ch == '\n' || ch == EOF)
3495 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3497 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3498 heredoc.data[past_EOL] = '\0';
3499 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3500 return heredoc.data;
3502 while (ch == '\n') {
3503 o_addchr(&heredoc, ch);
3506 past_EOL = heredoc.length;
3508 ch = i_getch(input);
3510 nommu_addchr(as_string, ch);
3511 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3515 o_free_unsafe(&heredoc);
3518 o_addchr(&heredoc, ch);
3519 nommu_addchr(as_string, ch);
3520 if (prev == '\\' && ch == '\\')
3521 /* Correctly handle foo\\<eol> (not a line cont.) */
3522 prev = 0; /* not \ */
3528 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3529 * and load them all. There should be exactly heredoc_cnt of them.
3531 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3533 struct pipe *pi = ctx->list_head;
3535 while (pi && heredoc_cnt) {
3537 struct command *cmd = pi->cmds;
3539 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3541 cmd->argv ? cmd->argv[0] : "NONE");
3542 for (i = 0; i < pi->num_cmds; i++) {
3543 struct redir_struct *redir = cmd->redirects;
3545 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3546 i, cmd->argv ? cmd->argv[0] : "NONE");
3548 if (redir->rd_type == REDIRECT_HEREDOC) {
3551 redir->rd_type = REDIRECT_HEREDOC2;
3552 /* redir->rd_dup is (ab)used to indicate <<- */
3553 p = fetch_till_str(&ctx->as_string, input,
3554 redir->rd_filename, redir->rd_dup);
3556 syntax_error("unexpected EOF in here document");
3559 free(redir->rd_filename);
3560 redir->rd_filename = p;
3563 redir = redir->next;
3570 /* Should be 0. If it isn't, it's a parse error */
3572 bb_error_msg_and_die("heredoc BUG 2");
3578 static int run_list(struct pipe *pi);
3580 #define parse_stream(pstring, input, end_trigger) \
3581 parse_stream(input, end_trigger)
3583 static struct pipe *parse_stream(char **pstring,
3584 struct in_str *input,
3588 #if !ENABLE_HUSH_FUNCTIONS
3589 #define parse_group(dest, ctx, input, ch) \
3590 parse_group(ctx, input, ch)
3592 static int parse_group(o_string *dest, struct parse_context *ctx,
3593 struct in_str *input, int ch)
3595 /* dest contains characters seen prior to ( or {.
3596 * Typically it's empty, but for function defs,
3597 * it contains function name (without '()'). */
3598 struct pipe *pipe_list;
3600 struct command *command = ctx->command;
3602 debug_printf_parse("parse_group entered\n");
3603 #if ENABLE_HUSH_FUNCTIONS
3604 if (ch == '(' && !dest->has_quoted_part) {
3606 if (done_word(dest, ctx))
3609 goto skip; /* (... */
3610 if (command->argv[1]) { /* word word ... (... */
3611 syntax_error_unexpected_ch('(');
3614 /* it is "word(..." or "word (..." */
3616 ch = i_getch(input);
3617 while (ch == ' ' || ch == '\t');
3619 syntax_error_unexpected_ch(ch);
3622 nommu_addchr(&ctx->as_string, ch);
3624 ch = i_getch(input);
3625 while (ch == ' ' || ch == '\t' || ch == '\n');
3627 syntax_error_unexpected_ch(ch);
3630 nommu_addchr(&ctx->as_string, ch);
3631 command->cmd_type = CMD_FUNCDEF;
3636 #if 0 /* Prevented by caller */
3637 if (command->argv /* word [word]{... */
3638 || dest->length /* word{... */
3639 || dest->has_quoted_part /* ""{... */
3642 debug_printf_parse("parse_group return 1: "
3643 "syntax error, groups and arglists don't mix\n");
3648 #if ENABLE_HUSH_FUNCTIONS
3654 command->cmd_type = CMD_SUBSHELL;
3656 /* bash does not allow "{echo...", requires whitespace */
3657 ch = i_getch(input);
3658 if (ch != ' ' && ch != '\t' && ch != '\n') {
3659 syntax_error_unexpected_ch(ch);
3662 nommu_addchr(&ctx->as_string, ch);
3667 # define as_string NULL
3669 char *as_string = NULL;
3671 pipe_list = parse_stream(&as_string, input, endch);
3674 o_addstr(&ctx->as_string, as_string);
3676 /* empty ()/{} or parse error? */
3677 if (!pipe_list || pipe_list == ERR_PTR) {
3678 /* parse_stream already emitted error msg */
3681 debug_printf_parse("parse_group return 1: "
3682 "parse_stream returned %p\n", pipe_list);
3685 command->group = pipe_list;
3687 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3688 command->group_as_string = as_string;
3689 debug_printf_parse("end of group, remembering as:'%s'\n",
3690 command->group_as_string);
3694 debug_printf_parse("parse_group return 0\n");
3696 /* command remains "open", available for possible redirects */
3699 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3700 /* Subroutines for copying $(...) and `...` things */
3701 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3703 static int add_till_single_quote(o_string *dest, struct in_str *input)
3706 int ch = i_getch(input);
3708 syntax_error_unterm_ch('\'');
3716 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3717 static int add_till_double_quote(o_string *dest, struct in_str *input)
3720 int ch = i_getch(input);
3722 syntax_error_unterm_ch('"');
3727 if (ch == '\\') { /* \x. Copy both chars. */
3729 ch = i_getch(input);
3733 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3738 //if (ch == '$') ...
3741 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3743 * "Within the backquoted style of command substitution, backslash
3744 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3745 * The search for the matching backquote shall be satisfied by the first
3746 * backquote found without a preceding backslash; during this search,
3747 * if a non-escaped backquote is encountered within a shell comment,
3748 * a here-document, an embedded command substitution of the $(command)
3749 * form, or a quoted string, undefined results occur. A single-quoted
3750 * or double-quoted string that begins, but does not end, within the
3751 * "`...`" sequence produces undefined results."
3753 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3755 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3758 int ch = i_getch(input);
3762 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3763 ch = i_getch(input);
3767 && (!in_dquote || ch != '"')
3769 o_addchr(dest, '\\');
3773 syntax_error_unterm_ch('`');
3779 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3780 * quoting and nested ()s.
3781 * "With the $(command) style of command substitution, all characters
3782 * following the open parenthesis to the matching closing parenthesis
3783 * constitute the command. Any valid shell script can be used for command,
3784 * except a script consisting solely of redirections which produces
3785 * unspecified results."
3787 * echo $(echo '(TEST)' BEST) (TEST) BEST
3788 * echo $(echo 'TEST)' BEST) TEST) BEST
3789 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3791 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3792 * can contain arbitrary constructs, just like $(cmd).
3793 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3794 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3796 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3797 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3800 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3801 # if ENABLE_HUSH_BASH_COMPAT
3802 char end_char2 = end_ch >> 8;
3804 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3807 ch = i_getch(input);
3809 syntax_error_unterm_ch(end_ch);
3812 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3815 /* we look for closing )) of $((EXPR)) */
3816 if (i_peek(input) == end_ch) {
3817 i_getch(input); /* eat second ')' */
3822 if (ch == '(' || ch == '{') {
3823 ch = (ch == '(' ? ')' : '}');
3824 if (!add_till_closing_bracket(dest, input, ch))
3830 if (!add_till_single_quote(dest, input))
3836 if (!add_till_double_quote(dest, input))
3842 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3848 /* \x. Copy verbatim. Important for \(, \) */
3849 ch = i_getch(input);
3851 syntax_error_unterm_ch(')');
3860 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3862 /* Return code: 0 for OK, 1 for syntax error */
3864 #define parse_dollar(as_string, dest, input, quote_mask) \
3865 parse_dollar(dest, input, quote_mask)
3866 #define as_string NULL
3868 static int parse_dollar(o_string *as_string,
3870 struct in_str *input, unsigned char quote_mask)
3872 int ch = i_peek(input); /* first character after the $ */
3874 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3876 ch = i_getch(input);
3877 nommu_addchr(as_string, ch);
3879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3881 debug_printf_parse(": '%c'\n", ch);
3882 o_addchr(dest, ch | quote_mask);
3885 if (!isalnum(ch) && ch != '_')
3887 ch = i_getch(input);
3888 nommu_addchr(as_string, ch);
3890 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3891 } else if (isdigit(ch)) {
3893 ch = i_getch(input);
3894 nommu_addchr(as_string, ch);
3895 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3896 debug_printf_parse(": '%c'\n", ch);
3897 o_addchr(dest, ch | quote_mask);
3898 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3899 } else switch (ch) {
3901 case '!': /* last bg pid */
3902 case '?': /* last exit code */
3903 case '#': /* number of args */
3904 case '*': /* args */
3905 case '@': /* args */
3906 goto make_one_char_var;
3908 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3910 ch = i_getch(input); /* eat '{' */
3911 nommu_addchr(as_string, ch);
3913 ch = i_getch(input); /* first char after '{' */
3914 /* It should be ${?}, or ${#var},
3915 * or even ${?+subst} - operator acting on a special variable,
3916 * or the beginning of variable name.
3919 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3922 syntax_error_unterm_str("${name}");
3923 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3926 nommu_addchr(as_string, ch);
3929 /* It's possible to just call add_till_closing_bracket() at this point.
3930 * However, this regresses some of our testsuite cases
3931 * which check invalid constructs like ${%}.
3932 * Oh well... let's check that the var name part is fine... */
3938 debug_printf_parse(": '%c'\n", ch);
3940 ch = i_getch(input);
3941 nommu_addchr(as_string, ch);
3945 if (!isalnum(ch) && ch != '_') {
3947 unsigned char last_ch;
3948 /* handle parameter expansions
3949 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3951 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3952 goto bad_dollar_syntax;
3954 /* Eat everything until closing '}' (or ':') */
3956 if (ENABLE_HUSH_BASH_COMPAT
3958 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3960 /* It's ${var:N[:M]} thing */
3961 end_ch = '}' * 0x100 + ':';
3963 if (ENABLE_HUSH_BASH_COMPAT
3966 /* It's ${var/[/]pattern[/repl]} thing */
3967 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3969 nommu_addchr(as_string, '/');
3972 end_ch = '}' * 0x100 + '/';
3978 #if ENABLE_HUSH_DOLLAR_OPS
3979 last_ch = add_till_closing_bracket(dest, input, end_ch);
3980 if (last_ch == 0) /* error? */
3983 #error Simple code to only allow ${var} is not implemented
3986 o_addstr(as_string, dest->data + pos);
3987 o_addchr(as_string, last_ch);
3990 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3991 /* close the first block: */
3992 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3993 /* while parsing N from ${var:N[:M]}
3994 * or pattern from ${var/[/]pattern[/repl]} */
3995 if ((end_ch & 0xff) == last_ch) {
3996 /* got ':' or '/'- parse the rest */
4001 if (end_ch == '}' * 0x100 + ':') {
4002 /* it's ${var:N} - emulate :999999999 */
4003 o_addstr(dest, "999999999");
4004 } /* else: it's ${var/[/]pattern} */
4009 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4012 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
4016 ch = i_getch(input);
4017 nommu_addchr(as_string, ch);
4018 # if ENABLE_SH_MATH_SUPPORT
4019 if (i_peek(input) == '(') {
4020 ch = i_getch(input);
4021 nommu_addchr(as_string, ch);
4022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4023 o_addchr(dest, /*quote_mask |*/ '+');
4026 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4027 return 0; /* error */
4029 o_addstr(as_string, dest->data + pos);
4030 o_addchr(as_string, ')');
4031 o_addchr(as_string, ')');
4033 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4037 # if ENABLE_HUSH_TICK
4038 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4039 o_addchr(dest, quote_mask | '`');
4042 if (!add_till_closing_bracket(dest, input, ')'))
4043 return 0; /* error */
4045 o_addstr(as_string, dest->data + pos);
4046 o_addchr(as_string, ')');
4048 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4054 ch = i_getch(input);
4055 nommu_addchr(as_string, ch);
4057 if (isalnum(ch)) { /* it's $_name or $_123 */
4062 /* TODO: $_ and $-: */
4063 /* $_ Shell or shell script name; or last argument of last command
4064 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4065 * but in command's env, set to full pathname used to invoke it */
4066 /* $- Option flags set by set builtin or shell options (-i etc) */
4068 o_addQchr(dest, '$');
4070 debug_printf_parse("parse_dollar return 1 (ok)\n");
4076 # if ENABLE_HUSH_BASH_COMPAT
4077 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4078 encode_string(dest, input, dquote_end, process_bkslash)
4080 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4081 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4082 encode_string(dest, input, dquote_end)
4084 #define as_string NULL
4088 # if ENABLE_HUSH_BASH_COMPAT
4089 /* all parameters are needed, no macro tricks */
4091 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4092 encode_string(as_string, dest, input, dquote_end)
4095 static int encode_string(o_string *as_string,
4097 struct in_str *input,
4099 int process_bkslash)
4101 #if !ENABLE_HUSH_BASH_COMPAT
4102 const int process_bkslash = 1;
4108 ch = i_getch(input);
4110 nommu_addchr(as_string, ch);
4111 if (ch == dquote_end) { /* may be only '"' or EOF */
4112 debug_printf_parse("encode_string return 1 (ok)\n");
4115 /* note: can't move it above ch == dquote_end check! */
4117 syntax_error_unterm_ch('"');
4118 return 0; /* error */
4122 next = i_peek(input);
4124 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4125 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4126 if (process_bkslash && ch == '\\') {
4128 syntax_error("\\<eof>");
4132 * "The backslash retains its special meaning [in "..."]
4133 * only when followed by one of the following characters:
4134 * $, `, ", \, or <newline>. A double quote may be quoted
4135 * within double quotes by preceding it with a backslash."
4136 * NB: in (unquoted) heredoc, above does not apply to ",
4137 * therefore we check for it by "next == dquote_end" cond.
4139 if (next == dquote_end || strchr("$`\\\n", next)) {
4140 ch = i_getch(input); /* eat next */
4142 goto again; /* skip \<newline> */
4143 } /* else: ch remains == '\\', and we double it below: */
4144 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4145 nommu_addchr(as_string, ch);
4149 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4150 debug_printf_parse("encode_string return 0: "
4151 "parse_dollar returned 0 (error)\n");
4156 #if ENABLE_HUSH_TICK
4158 //unsigned pos = dest->length;
4159 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4160 o_addchr(dest, 0x80 | '`');
4161 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4162 return 0; /* error */
4163 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4164 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4168 o_addQchr(dest, ch);
4174 * Scan input until EOF or end_trigger char.
4175 * Return a list of pipes to execute, or NULL on EOF
4176 * or if end_trigger character is met.
4177 * On syntax error, exit if shell is not interactive,
4178 * reset parsing machinery and start parsing anew,
4179 * or return ERR_PTR.
4181 static struct pipe *parse_stream(char **pstring,
4182 struct in_str *input,
4185 struct parse_context ctx;
4186 o_string dest = NULL_O_STRING;
4189 /* Single-quote triggers a bypass of the main loop until its mate is
4190 * found. When recursing, quote state is passed in via dest->o_expflags.
4192 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4193 end_trigger ? end_trigger : 'X');
4196 /* If very first arg is "" or '', dest.data may end up NULL.
4197 * Preventing this: */
4198 o_addchr(&dest, '\0');
4201 /* We used to separate words on $IFS here. This was wrong.
4202 * $IFS is used only for word splitting when $var is expanded,
4203 * here we should use blank chars as separators, not $IFS
4206 if (MAYBE_ASSIGNMENT != 0)
4207 dest.o_assignment = MAYBE_ASSIGNMENT;
4208 initialize_context(&ctx);
4211 const char *is_blank;
4212 const char *is_special;
4216 redir_type redir_style;
4218 ch = i_getch(input);
4219 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4220 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4225 syntax_error_unterm_str("here document");
4228 /* end_trigger == '}' case errors out earlier,
4229 * checking only ')' */
4230 if (end_trigger == ')') {
4231 syntax_error_unterm_ch('(');
4235 if (done_word(&dest, &ctx)) {
4239 done_pipe(&ctx, PIPE_SEQ);
4241 /* If we got nothing... */
4242 /* (this makes bare "&" cmd a no-op.
4243 * bash says: "syntax error near unexpected token '&'") */
4244 if (pi->num_cmds == 0
4245 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4251 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4253 *pstring = ctx.as_string.data;
4255 o_free_unsafe(&ctx.as_string);
4258 debug_printf_parse("parse_stream return %p\n", pi);
4261 nommu_addchr(&ctx.as_string, ch);
4265 next = i_peek(input);
4267 is_special = "{}<>;&|()#'" /* special outside of "str" */
4268 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4269 /* Are { and } special here? */
4270 if (ctx.command->argv /* word [word]{... - non-special */
4271 || dest.length /* word{... - non-special */
4272 || dest.has_quoted_part /* ""{... - non-special */
4273 || (next != ';' /* }; - special */
4274 && next != ')' /* }) - special */
4275 && next != '&' /* }& and }&& ... - special */
4276 && next != '|' /* }|| ... - special */
4277 && !strchr(defifs, next) /* {word - non-special */
4280 /* They are not special, skip "{}" */
4283 is_special = strchr(is_special, ch);
4284 is_blank = strchr(defifs, ch);
4286 if (!is_special && !is_blank) { /* ordinary char */
4288 o_addQchr(&dest, ch);
4289 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4290 || dest.o_assignment == WORD_IS_KEYWORD)
4292 && is_well_formed_var_name(dest.data, '=')
4294 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4295 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4301 if (done_word(&dest, &ctx)) {
4305 /* Is this a case when newline is simply ignored?
4307 * "cmd | <newline> cmd ..."
4308 * "case ... in <newline> word) ..."
4310 if (IS_NULL_CMD(ctx.command)
4311 && dest.length == 0 && !dest.has_quoted_part
4313 /* This newline can be ignored. But...
4314 * Without check #1, interactive shell
4315 * ignores even bare <newline>,
4316 * and shows the continuation prompt:
4317 * ps1_prompt$ <enter>
4318 * ps2> _ <=== wrong, should be ps1
4319 * Without check #2, "cmd & <newline>"
4320 * is similarly mistreated.
4321 * (BTW, this makes "cmd & cmd"
4322 * and "cmd && cmd" non-orthogonal.
4323 * Really, ask yourself, why
4324 * "cmd && <newline>" doesn't start
4325 * cmd but waits for more input?
4328 struct pipe *pi = ctx.list_head;
4329 if (pi->num_cmds != 0 /* check #1 */
4330 && pi->followup != PIPE_BG /* check #2 */
4335 /* Treat newline as a command separator. */
4336 done_pipe(&ctx, PIPE_SEQ);
4337 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4339 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4344 dest.o_assignment = MAYBE_ASSIGNMENT;
4345 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4347 /* note: if (is_blank) continue;
4348 * will still trigger for us */
4352 /* "cmd}" or "cmd }..." without semicolon or &:
4353 * } is an ordinary char in this case, even inside { cmd; }
4354 * Pathological example: { ""}; } should exec "}" cmd
4357 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4358 || dest.length != 0 /* word} */
4359 || dest.has_quoted_part /* ""} */
4363 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4364 goto skip_end_trigger;
4365 /* else: } does terminate a group */
4368 if (end_trigger && end_trigger == ch
4369 && (ch != ';' || heredoc_cnt == 0)
4370 #if ENABLE_HUSH_CASE
4372 || ctx.ctx_res_w != RES_MATCH
4373 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4378 /* This is technically valid:
4379 * { cat <<HERE; }; echo Ok
4383 * but we don't support this.
4384 * We require heredoc to be in enclosing {}/(),
4387 syntax_error_unterm_str("here document");
4390 if (done_word(&dest, &ctx)) {
4393 done_pipe(&ctx, PIPE_SEQ);
4394 dest.o_assignment = MAYBE_ASSIGNMENT;
4395 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4396 /* Do we sit outside of any if's, loops or case's? */
4398 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4402 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4404 *pstring = ctx.as_string.data;
4406 o_free_unsafe(&ctx.as_string);
4409 debug_printf_parse("parse_stream return %p: "
4410 "end_trigger char found\n",
4412 return ctx.list_head;
4419 /* Catch <, > before deciding whether this word is
4420 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4423 redir_fd = redirect_opt_num(&dest);
4424 if (done_word(&dest, &ctx)) {
4427 redir_style = REDIRECT_OVERWRITE;
4429 redir_style = REDIRECT_APPEND;
4430 ch = i_getch(input);
4431 nommu_addchr(&ctx.as_string, ch);
4434 else if (next == '(') {
4435 syntax_error(">(process) not supported");
4439 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4441 continue; /* back to top of while (1) */
4443 redir_fd = redirect_opt_num(&dest);
4444 if (done_word(&dest, &ctx)) {
4447 redir_style = REDIRECT_INPUT;
4449 redir_style = REDIRECT_HEREDOC;
4451 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4452 ch = i_getch(input);
4453 nommu_addchr(&ctx.as_string, ch);
4454 } else if (next == '>') {
4455 redir_style = REDIRECT_IO;
4456 ch = i_getch(input);
4457 nommu_addchr(&ctx.as_string, ch);
4460 else if (next == '(') {
4461 syntax_error("<(process) not supported");
4465 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4467 continue; /* back to top of while (1) */
4469 if (dest.length == 0 && !dest.has_quoted_part) {
4470 /* skip "#comment" */
4473 if (ch == EOF || ch == '\n')
4476 /* note: we do not add it to &ctx.as_string */
4478 nommu_addchr(&ctx.as_string, '\n');
4479 continue; /* back to top of while (1) */
4484 /* It's "\<newline>" */
4486 /* Remove trailing '\' from ctx.as_string */
4487 ctx.as_string.data[--ctx.as_string.length] = '\0';
4489 ch = i_getch(input); /* eat it */
4490 continue; /* back to top of while (1) */
4495 if (dest.o_assignment == MAYBE_ASSIGNMENT
4496 /* check that we are not in word in "a=1 2>word b=1": */
4497 && !ctx.pending_redirect
4499 /* ch is a special char and thus this word
4500 * cannot be an assignment */
4501 dest.o_assignment = NOT_ASSIGNMENT;
4502 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4505 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4508 case '#': /* non-comment #: "echo a#b" etc */
4509 o_addQchr(&dest, ch);
4513 syntax_error("\\<eof>");
4516 ch = i_getch(input);
4517 /* note: ch != '\n' (that case does not reach this place) */
4518 o_addchr(&dest, '\\');
4519 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4520 o_addchr(&dest, ch);
4521 nommu_addchr(&ctx.as_string, ch);
4522 /* Example: echo Hello \2>file
4523 * we need to know that word 2 is quoted */
4524 dest.has_quoted_part = 1;
4527 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4528 debug_printf_parse("parse_stream parse error: "
4529 "parse_dollar returned 0 (error)\n");
4534 dest.has_quoted_part = 1;
4535 if (next == '\'' && !ctx.pending_redirect) {
4536 insert_empty_quoted_str_marker:
4537 nommu_addchr(&ctx.as_string, next);
4538 i_getch(input); /* eat second ' */
4539 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4540 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4543 ch = i_getch(input);
4545 syntax_error_unterm_ch('\'');
4548 nommu_addchr(&ctx.as_string, ch);
4551 o_addqchr(&dest, ch);
4556 dest.has_quoted_part = 1;
4557 if (next == '"' && !ctx.pending_redirect)
4558 goto insert_empty_quoted_str_marker;
4559 if (dest.o_assignment == NOT_ASSIGNMENT)
4560 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4561 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4563 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4565 #if ENABLE_HUSH_TICK
4567 USE_FOR_NOMMU(unsigned pos;)
4569 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4570 o_addchr(&dest, '`');
4571 USE_FOR_NOMMU(pos = dest.length;)
4572 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4575 o_addstr(&ctx.as_string, dest.data + pos);
4576 o_addchr(&ctx.as_string, '`');
4578 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4579 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4584 #if ENABLE_HUSH_CASE
4587 if (done_word(&dest, &ctx)) {
4590 done_pipe(&ctx, PIPE_SEQ);
4591 #if ENABLE_HUSH_CASE
4592 /* Eat multiple semicolons, detect
4593 * whether it means something special */
4598 ch = i_getch(input);
4599 nommu_addchr(&ctx.as_string, ch);
4600 if (ctx.ctx_res_w == RES_CASE_BODY) {
4601 ctx.ctx_dsemicolon = 1;
4602 ctx.ctx_res_w = RES_MATCH;
4608 /* We just finished a cmd. New one may start
4609 * with an assignment */
4610 dest.o_assignment = MAYBE_ASSIGNMENT;
4611 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4614 if (done_word(&dest, &ctx)) {
4618 ch = i_getch(input);
4619 nommu_addchr(&ctx.as_string, ch);
4620 done_pipe(&ctx, PIPE_AND);
4622 done_pipe(&ctx, PIPE_BG);
4626 if (done_word(&dest, &ctx)) {
4629 #if ENABLE_HUSH_CASE
4630 if (ctx.ctx_res_w == RES_MATCH)
4631 break; /* we are in case's "word | word)" */
4633 if (next == '|') { /* || */
4634 ch = i_getch(input);
4635 nommu_addchr(&ctx.as_string, ch);
4636 done_pipe(&ctx, PIPE_OR);
4638 /* we could pick up a file descriptor choice here
4639 * with redirect_opt_num(), but bash doesn't do it.
4640 * "echo foo 2| cat" yields "foo 2". */
4643 o_reset_to_empty_unquoted(&ctx.as_string);
4648 #if ENABLE_HUSH_CASE
4649 /* "case... in [(]word)..." - skip '(' */
4650 if (ctx.ctx_res_w == RES_MATCH
4651 && ctx.command->argv == NULL /* not (word|(... */
4652 && dest.length == 0 /* not word(... */
4653 && dest.has_quoted_part == 0 /* not ""(... */
4659 if (parse_group(&dest, &ctx, input, ch) != 0) {
4664 #if ENABLE_HUSH_CASE
4665 if (ctx.ctx_res_w == RES_MATCH)
4669 /* proper use of this character is caught by end_trigger:
4670 * if we see {, we call parse_group(..., end_trigger='}')
4671 * and it will match } earlier (not here). */
4672 syntax_error_unexpected_ch(ch);
4676 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4682 struct parse_context *pctx;
4683 IF_HAS_KEYWORDS(struct parse_context *p2;)
4685 /* Clean up allocated tree.
4686 * Sample for finding leaks on syntax error recovery path.
4687 * Run it from interactive shell, watch pmap `pidof hush`.
4688 * while if false; then false; fi; do break; fi
4689 * Samples to catch leaks at execution:
4690 * while if (true | {true;}); then echo ok; fi; do break; done
4691 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4695 /* Update pipe/command counts,
4696 * otherwise freeing may miss some */
4697 done_pipe(pctx, PIPE_SEQ);
4698 debug_printf_clean("freeing list %p from ctx %p\n",
4699 pctx->list_head, pctx);
4700 debug_print_tree(pctx->list_head, 0);
4701 free_pipe_list(pctx->list_head);
4702 debug_printf_clean("freed list %p\n", pctx->list_head);
4704 o_free_unsafe(&pctx->as_string);
4706 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4710 IF_HAS_KEYWORDS(pctx = p2;)
4711 } while (HAS_KEYWORDS && pctx);
4714 G.last_exitcode = 1;
4725 /*** Execution routines ***/
4727 /* Expansion can recurse, need forward decls: */
4728 #if !ENABLE_HUSH_BASH_COMPAT
4729 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4730 #define expand_string_to_string(str, do_unbackslash) \
4731 expand_string_to_string(str)
4733 static char *expand_string_to_string(const char *str, int do_unbackslash);
4734 #if ENABLE_HUSH_TICK
4735 static int process_command_subs(o_string *dest, const char *s);
4738 /* expand_strvec_to_strvec() takes a list of strings, expands
4739 * all variable references within and returns a pointer to
4740 * a list of expanded strings, possibly with larger number
4741 * of strings. (Think VAR="a b"; echo $VAR).
4742 * This new list is allocated as a single malloc block.
4743 * NULL-terminated list of char* pointers is at the beginning of it,
4744 * followed by strings themselves.
4745 * Caller can deallocate entire list by single free(list). */
4747 /* A horde of its helpers come first: */
4749 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4751 while (--len >= 0) {
4754 #if ENABLE_HUSH_BRACE_EXPANSION
4755 if (c == '{' || c == '}') {
4756 /* { -> \{, } -> \} */
4758 /* And now we want to add { or } and continue:
4761 * luckily, just falling throught achieves this.
4767 /* \z -> \\\z; \<eol> -> \\<eol> */
4772 o_addchr(o, *str++);
4778 /* Store given string, finalizing the word and starting new one whenever
4779 * we encounter IFS char(s). This is used for expanding variable values.
4780 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4781 * Return in *ended_with_ifs:
4782 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4784 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4786 int last_is_ifs = 0;
4791 if (!*str) /* EOL - do not finalize word */
4793 word_len = strcspn(str, G.ifs);
4795 /* We have WORD_LEN leading non-IFS chars */
4796 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4797 o_addblock(output, str, word_len);
4799 /* Protect backslashes against globbing up :)
4800 * Example: "v='\*'; echo b$v" prints "b\*"
4801 * (and does not try to glob on "*")
4803 o_addblock_duplicate_backslash(output, str, word_len);
4804 /*/ Why can't we do it easier? */
4805 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4806 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4810 if (!*str) /* EOL - do not finalize word */
4814 /* We know str here points to at least one IFS char */
4816 str += strspn(str, G.ifs); /* skip IFS chars */
4817 if (!*str) /* EOL - do not finalize word */
4820 /* Start new word... but not always! */
4821 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4822 if (output->has_quoted_part
4823 /* Case "v=' a'; echo $v":
4824 * here nothing precedes the space in $v expansion,
4825 * therefore we should not finish the word
4826 * (IOW: if there *is* word to finalize, only then do it):
4828 || (n > 0 && output->data[output->length - 1])
4830 o_addchr(output, '\0');
4831 debug_print_list("expand_on_ifs", output, n);
4832 n = o_save_ptr(output, n);
4837 *ended_with_ifs = last_is_ifs;
4838 debug_print_list("expand_on_ifs[1]", output, n);
4842 /* Helper to expand $((...)) and heredoc body. These act as if
4843 * they are in double quotes, with the exception that they are not :).
4844 * Just the rules are similar: "expand only $var and `cmd`"
4846 * Returns malloced string.
4847 * As an optimization, we return NULL if expansion is not needed.
4849 #if !ENABLE_HUSH_BASH_COMPAT
4850 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4851 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4852 encode_then_expand_string(str)
4854 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4857 struct in_str input;
4858 o_string dest = NULL_O_STRING;
4860 if (!strchr(str, '$')
4861 && !strchr(str, '\\')
4862 #if ENABLE_HUSH_TICK
4863 && !strchr(str, '`')
4869 /* We need to expand. Example:
4870 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4872 setup_string_in_str(&input, str);
4873 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4874 //TODO: error check (encode_string returns 0 on error)?
4875 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4876 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4877 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4878 o_free_unsafe(&dest);
4882 #if ENABLE_SH_MATH_SUPPORT
4883 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4885 arith_state_t math_state;
4889 math_state.lookupvar = get_local_var_value;
4890 math_state.setvar = set_local_var_from_halves;
4891 //math_state.endofname = endofname;
4892 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4893 res = arith(&math_state, exp_str ? exp_str : arg);
4896 *errmsg_p = math_state.errmsg;
4897 if (math_state.errmsg)
4898 die_if_script(math_state.errmsg);
4903 #if ENABLE_HUSH_BASH_COMPAT
4904 /* ${var/[/]pattern[/repl]} helpers */
4905 static char *strstr_pattern(char *val, const char *pattern, int *size)
4908 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4909 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4916 /* Optimization: if "*pat" did not match the start of "string",
4917 * we know that "tring", "ring" etc will not match too:
4919 if (pattern[0] == '*')
4924 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4926 char *result = NULL;
4927 unsigned res_len = 0;
4928 unsigned repl_len = strlen(repl);
4932 char *s = strstr_pattern(val, pattern, &size);
4936 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4937 memcpy(result + res_len, val, s - val);
4939 strcpy(result + res_len, repl);
4940 res_len += repl_len;
4941 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4947 if (val[0] && result) {
4948 result = xrealloc(result, res_len + strlen(val) + 1);
4949 strcpy(result + res_len, val);
4950 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4952 debug_printf_varexp("result:'%s'\n", result);
4958 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4960 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4962 const char *val = NULL;
4963 char *to_be_freed = NULL;
4968 char exp_save = exp_save; /* for compiler */
4969 char *exp_saveptr; /* points to expansion operator */
4970 char *exp_word = exp_word; /* for compiler */
4973 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4975 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4977 first_char = arg[0] = arg0 & 0x7f;
4980 if (first_char == '#' /* ${#... */
4981 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4983 /* It must be length operator: ${#var} */
4987 /* Maybe handle parameter expansion */
4988 if (exp_saveptr /* if 2nd char is one of expansion operators */
4989 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4991 /* ${?:0}, ${#[:]%0} etc */
4992 exp_saveptr = var + 1;
4994 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4995 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4997 exp_op = exp_save = *exp_saveptr;
4999 exp_word = exp_saveptr + 1;
5000 if (exp_op == ':') {
5001 exp_op = *exp_word++;
5002 //TODO: try ${var:} and ${var:bogus} in non-bash config
5003 if (ENABLE_HUSH_BASH_COMPAT
5004 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
5006 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5011 *exp_saveptr = '\0';
5012 } /* else: it's not an expansion op, but bare ${var} */
5015 /* Look up the variable in question */
5016 if (isdigit(var[0])) {
5017 /* parse_dollar should have vetted var for us */
5018 int n = xatoi_positive(var);
5019 if (n < G.global_argc)
5020 val = G.global_argv[n];
5021 /* else val remains NULL: $N with too big N */
5025 val = utoa(G.root_pid);
5027 case '!': /* bg pid */
5028 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5030 case '?': /* exitcode */
5031 val = utoa(G.last_exitcode);
5033 case '#': /* argc */
5034 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5037 val = get_local_var_value(var);
5041 /* Handle any expansions */
5042 if (exp_op == 'L') {
5043 reinit_unicode_for_hush();
5044 debug_printf_expand("expand: length(%s)=", val);
5045 val = utoa(val ? unicode_strlen(val) : 0);
5046 debug_printf_expand("%s\n", val);
5047 } else if (exp_op) {
5048 if (exp_op == '%' || exp_op == '#') {
5049 /* Standard-mandated substring removal ops:
5050 * ${parameter%word} - remove smallest suffix pattern
5051 * ${parameter%%word} - remove largest suffix pattern
5052 * ${parameter#word} - remove smallest prefix pattern
5053 * ${parameter##word} - remove largest prefix pattern
5055 * Word is expanded to produce a glob pattern.
5056 * Then var's value is matched to it and matching part removed.
5058 if (val && val[0]) {
5062 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5063 if (exp_op == *exp_word) /* ## or %% */
5065 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5067 exp_word = exp_exp_word;
5068 /* HACK ALERT. We depend here on the fact that
5069 * G.global_argv and results of utoa and get_local_var_value
5070 * are actually in writable memory:
5071 * scan_and_match momentarily stores NULs there. */
5073 loc = scan_and_match(t, exp_word, scan_flags);
5074 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5075 // exp_op, t, exp_word, loc);
5077 if (loc) { /* match was found */
5078 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5079 val = loc; /* take right part */
5081 val = to_be_freed = xstrndup(val, loc - val); /* left */
5085 #if ENABLE_HUSH_BASH_COMPAT
5086 else if (exp_op == '/' || exp_op == '\\') {
5087 /* It's ${var/[/]pattern[/repl]} thing.
5088 * Note that in encoded form it has TWO parts:
5089 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5090 * and if // is used, it is encoded as \:
5091 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5093 /* Empty variable always gives nothing: */
5094 // "v=''; echo ${v/*/w}" prints "", not "w"
5095 if (val && val[0]) {
5096 /* pattern uses non-standard expansion.
5097 * repl should be unbackslashed and globbed
5098 * by the usual expansion rules:
5100 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5101 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5102 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5103 * v='a bz'; echo ${v/a*z/\z} prints "z"
5104 * (note that a*z _pattern_ is never globbed!)
5106 char *pattern, *repl, *t;
5107 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5109 pattern = xstrdup(exp_word);
5110 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5111 *p++ = SPECIAL_VAR_SYMBOL;
5113 p = strchr(p, SPECIAL_VAR_SYMBOL);
5115 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5116 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5117 /* HACK ALERT. We depend here on the fact that
5118 * G.global_argv and results of utoa and get_local_var_value
5119 * are actually in writable memory:
5120 * replace_pattern momentarily stores NULs there. */
5122 to_be_freed = replace_pattern(t,
5124 (repl ? repl : exp_word),
5126 if (to_be_freed) /* at least one replace happened */
5133 else if (exp_op == ':') {
5134 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5135 /* It's ${var:N[:M]} bashism.
5136 * Note that in encoded form it has TWO parts:
5137 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5142 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5145 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5146 *p++ = SPECIAL_VAR_SYMBOL;
5148 p = strchr(p, SPECIAL_VAR_SYMBOL);
5150 len = expand_and_evaluate_arith(exp_word, &errmsg);
5153 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5154 if (len >= 0) { /* bash compat: len < 0 is illegal */
5155 if (beg < 0) /* bash compat */
5157 debug_printf_varexp("from val:'%s'\n", val);
5158 if (len == 0 || !val || beg >= strlen(val)) {
5162 /* Paranoia. What if user entered 9999999999999
5163 * which fits in arith_t but not int? */
5166 val = to_be_freed = xstrndup(val + beg, len);
5168 debug_printf_varexp("val:'%s'\n", val);
5172 die_if_script("malformed ${%s:...}", var);
5175 } else { /* one of "-=+?" */
5176 /* Standard-mandated substitution ops:
5177 * ${var?word} - indicate error if unset
5178 * If var is unset, word (or a message indicating it is unset
5179 * if word is null) is written to standard error
5180 * and the shell exits with a non-zero exit status.
5181 * Otherwise, the value of var is substituted.
5182 * ${var-word} - use default value
5183 * If var is unset, word is substituted.
5184 * ${var=word} - assign and use default value
5185 * If var is unset, word is assigned to var.
5186 * In all cases, final value of var is substituted.
5187 * ${var+word} - use alternative value
5188 * If var is unset, null is substituted.
5189 * Otherwise, word is substituted.
5191 * Word is subjected to tilde expansion, parameter expansion,
5192 * command substitution, and arithmetic expansion.
5193 * If word is not needed, it is not expanded.
5195 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5196 * but also treat null var as if it is unset.
5198 int use_word = (!val || ((exp_save == ':') && !val[0]));
5200 use_word = !use_word;
5201 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5202 (exp_save == ':') ? "true" : "false", use_word);
5204 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5206 exp_word = to_be_freed;
5207 if (exp_op == '?') {
5208 /* mimic bash message */
5209 die_if_script("%s: %s",
5211 exp_word[0] ? exp_word : "parameter null or not set"
5213 //TODO: how interactive bash aborts expansion mid-command?
5218 if (exp_op == '=') {
5219 /* ${var=[word]} or ${var:=[word]} */
5220 if (isdigit(var[0]) || var[0] == '#') {
5221 /* mimic bash message */
5222 die_if_script("$%s: cannot assign in this way", var);
5225 char *new_var = xasprintf("%s=%s", var, val);
5226 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5230 } /* one of "-=+?" */
5232 *exp_saveptr = exp_save;
5238 *to_be_freed_pp = to_be_freed;
5242 /* Expand all variable references in given string, adding words to list[]
5243 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5244 * to be filled). This routine is extremely tricky: has to deal with
5245 * variables/parameters with whitespace, $* and $@, and constructs like
5246 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5247 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5249 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5250 * expansion of right-hand side of assignment == 1-element expand.
5252 char cant_be_null = 0; /* only bit 0x80 matters */
5253 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5256 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5257 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5258 debug_print_list("expand_vars_to_list", output, n);
5259 n = o_save_ptr(output, n);
5260 debug_print_list("expand_vars_to_list[0]", output, n);
5262 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5264 char *to_be_freed = NULL;
5265 const char *val = NULL;
5266 #if ENABLE_HUSH_TICK
5267 o_string subst_result = NULL_O_STRING;
5269 #if ENABLE_SH_MATH_SUPPORT
5270 char arith_buf[sizeof(arith_t)*3 + 2];
5274 o_addchr(output, '\0');
5275 n = o_save_ptr(output, n);
5279 o_addblock(output, arg, p - arg);
5280 debug_print_list("expand_vars_to_list[1]", output, n);
5282 p = strchr(p, SPECIAL_VAR_SYMBOL);
5284 /* Fetch special var name (if it is indeed one of them)
5285 * and quote bit, force the bit on if singleword expansion -
5286 * important for not getting v=$@ expand to many words. */
5287 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5289 /* Is this variable quoted and thus expansion can't be null?
5290 * "$@" is special. Even if quoted, it can still
5291 * expand to nothing (not even an empty string),
5292 * thus it is excluded. */
5293 if ((first_ch & 0x7f) != '@')
5294 cant_be_null |= first_ch;
5296 switch (first_ch & 0x7f) {
5297 /* Highest bit in first_ch indicates that var is double-quoted */
5301 if (!G.global_argv[1])
5304 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5305 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5306 while (G.global_argv[i]) {
5307 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5308 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5309 if (G.global_argv[i++][0] && G.global_argv[i]) {
5310 /* this argv[] is not empty and not last:
5311 * put terminating NUL, start new word */
5312 o_addchr(output, '\0');
5313 debug_print_list("expand_vars_to_list[2]", output, n);
5314 n = o_save_ptr(output, n);
5315 debug_print_list("expand_vars_to_list[3]", output, n);
5319 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5320 * and in this case should treat it like '$*' - see 'else...' below */
5321 if (first_ch == ('@'|0x80) /* quoted $@ */
5322 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5325 o_addQstr(output, G.global_argv[i]);
5326 if (++i >= G.global_argc)
5328 o_addchr(output, '\0');
5329 debug_print_list("expand_vars_to_list[4]", output, n);
5330 n = o_save_ptr(output, n);
5332 } else { /* quoted $* (or v="$@" case): add as one word */
5334 o_addQstr(output, G.global_argv[i]);
5335 if (!G.global_argv[++i])
5338 o_addchr(output, G.ifs[0]);
5340 output->has_quoted_part = 1;
5344 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5345 /* "Empty variable", used to make "" etc to not disappear */
5346 output->has_quoted_part = 1;
5348 cant_be_null = 0x80;
5350 #if ENABLE_HUSH_TICK
5351 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5352 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5354 /* Can't just stuff it into output o_string,
5355 * expanded result may need to be globbed
5356 * and $IFS-splitted */
5357 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5358 G.last_exitcode = process_command_subs(&subst_result, arg);
5359 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5360 val = subst_result.data;
5363 #if ENABLE_SH_MATH_SUPPORT
5364 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5367 arg++; /* skip '+' */
5368 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5369 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5370 res = expand_and_evaluate_arith(arg, NULL);
5371 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5372 sprintf(arith_buf, ARITH_FMT, res);
5378 val = expand_one_var(&to_be_freed, arg, &p);
5379 IF_HUSH_TICK(store_val:)
5380 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5381 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5382 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5383 if (val && val[0]) {
5384 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5387 } else { /* quoted $VAR, val will be appended below */
5388 output->has_quoted_part = 1;
5389 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5390 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5394 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5396 if (val && val[0]) {
5397 o_addQstr(output, val);
5401 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5402 * Do the check to avoid writing to a const string. */
5403 if (*p != SPECIAL_VAR_SYMBOL)
5404 *p = SPECIAL_VAR_SYMBOL;
5406 #if ENABLE_HUSH_TICK
5407 o_free(&subst_result);
5410 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5414 o_addchr(output, '\0');
5415 n = o_save_ptr(output, n);
5417 debug_print_list("expand_vars_to_list[a]", output, n);
5418 /* this part is literal, and it was already pre-quoted
5419 * if needed (much earlier), do not use o_addQstr here! */
5420 o_addstr_with_NUL(output, arg);
5421 debug_print_list("expand_vars_to_list[b]", output, n);
5422 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5423 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5426 /* allow to reuse list[n] later without re-growth */
5427 output->has_empty_slot = 1;
5429 o_addchr(output, '\0');
5435 static char **expand_variables(char **argv, unsigned expflags)
5439 o_string output = NULL_O_STRING;
5441 output.o_expflags = expflags;
5445 n = expand_vars_to_list(&output, n, *argv);
5448 debug_print_list("expand_variables", &output, n);
5450 /* output.data (malloced in one block) gets returned in "list" */
5451 list = o_finalize_list(&output, n);
5452 debug_print_strings("expand_variables[1]", list);
5456 static char **expand_strvec_to_strvec(char **argv)
5458 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5461 #if ENABLE_HUSH_BASH_COMPAT
5462 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5464 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5468 /* Used for expansion of right hand of assignments,
5469 * $((...)), heredocs, variable espansion parts.
5471 * NB: should NOT do globbing!
5472 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5474 static char *expand_string_to_string(const char *str, int do_unbackslash)
5476 #if !ENABLE_HUSH_BASH_COMPAT
5477 const int do_unbackslash = 1;
5479 char *argv[2], **list;
5481 debug_printf_expand("string_to_string<='%s'\n", str);
5482 /* This is generally an optimization, but it also
5483 * handles "", which otherwise trips over !list[0] check below.
5484 * (is this ever happens that we actually get str="" here?)
5486 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5487 //TODO: Can use on strings with \ too, just unbackslash() them?
5488 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5489 return xstrdup(str);
5492 argv[0] = (char*)str;
5494 list = expand_variables(argv, do_unbackslash
5495 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5496 : EXP_FLAG_SINGLEWORD
5499 if (!list[0] || list[1])
5500 bb_error_msg_and_die("BUG in varexp2");
5501 /* actually, just move string 2*sizeof(char*) bytes back */
5502 overlapping_strcpy((char*)list, list[0]);
5504 unbackslash((char*)list);
5505 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5509 /* Used for "eval" builtin */
5510 static char* expand_strvec_to_string(char **argv)
5514 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5515 /* Convert all NULs to spaces */
5520 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5521 bb_error_msg_and_die("BUG in varexp3");
5522 /* bash uses ' ' regardless of $IFS contents */
5527 overlapping_strcpy((char*)list, list[0]);
5528 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5532 static char **expand_assignments(char **argv, int count)
5537 G.expanded_assignments = p = NULL;
5538 /* Expand assignments into one string each */
5539 for (i = 0; i < count; i++) {
5540 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5542 G.expanded_assignments = NULL;
5547 static void switch_off_special_sigs(unsigned mask)
5550 while ((mask >>= 1) != 0) {
5555 if (G.traps[sig] && !G.traps[sig][0])
5556 /* trap is '', has to remain SIG_IGN */
5559 G.traps[sig] = NULL;
5561 /* We are here only if no trap or trap was not '' */
5562 install_sighandler(sig, SIG_DFL);
5568 void re_execute_shell(char ***to_free, const char *s,
5569 char *g_argv0, char **g_argv,
5570 char **builtin_argv) NORETURN;
5572 static void reset_traps_to_defaults(void)
5574 /* This function is always called in a child shell
5575 * after fork (not vfork, NOMMU doesn't use this function).
5580 /* Child shells are not interactive.
5581 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5582 * Testcase: (while :; do :; done) + ^Z should background.
5583 * Same goes for SIGTERM, SIGHUP, SIGINT.
5585 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5586 if (!G.traps && !mask)
5587 return; /* already no traps and no special sigs */
5589 /* Switch off special sigs */
5590 switch_off_special_sigs(mask);
5592 G_fatal_sig_mask = 0;
5594 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5595 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5596 * remain set in G.special_sig_mask */
5601 /* Reset all sigs to default except ones with empty traps */
5602 for (sig = 0; sig < NSIG; sig++) {
5604 continue; /* no trap: nothing to do */
5605 if (!G.traps[sig][0])
5606 continue; /* empty trap: has to remain SIG_IGN */
5607 /* sig has non-empty trap, reset it: */
5609 G.traps[sig] = NULL;
5610 /* There is no signal for trap 0 (EXIT) */
5613 install_sighandler(sig, pick_sighandler(sig));
5619 static void re_execute_shell(char ***to_free, const char *s,
5620 char *g_argv0, char **g_argv,
5621 char **builtin_argv) NORETURN;
5622 static void re_execute_shell(char ***to_free, const char *s,
5623 char *g_argv0, char **g_argv,
5624 char **builtin_argv)
5626 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5627 /* delims + 2 * (number of bytes in printed hex numbers) */
5628 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5629 char *heredoc_argv[4];
5630 struct variable *cur;
5631 # if ENABLE_HUSH_FUNCTIONS
5632 struct function *funcp;
5636 unsigned long long empty_trap_mask;
5638 if (!g_argv0) { /* heredoc */
5639 argv = heredoc_argv;
5640 argv[0] = (char *) G.argv0_for_re_execing;
5641 argv[1] = (char *) "-<";
5642 argv[2] = (char *) s;
5644 pp = &argv[3]; /* used as pointer to empty environment */
5650 if (pp) while (*pp++)
5653 empty_trap_mask = 0;
5656 for (sig = 1; sig < NSIG; sig++) {
5657 if (G.traps[sig] && !G.traps[sig][0])
5658 empty_trap_mask |= 1LL << sig;
5662 sprintf(param_buf, NOMMU_HACK_FMT
5663 , (unsigned) G.root_pid
5664 , (unsigned) G.root_ppid
5665 , (unsigned) G.last_bg_pid
5666 , (unsigned) G.last_exitcode
5669 IF_HUSH_LOOPS(, G.depth_of_loop)
5671 # undef NOMMU_HACK_FMT
5672 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5673 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5676 for (cur = G.top_var; cur; cur = cur->next) {
5677 if (!cur->flg_export || cur->flg_read_only)
5680 # if ENABLE_HUSH_FUNCTIONS
5681 for (funcp = G.top_func; funcp; funcp = funcp->next)
5687 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5688 *pp++ = (char *) G.argv0_for_re_execing;
5690 for (cur = G.top_var; cur; cur = cur->next) {
5691 if (strcmp(cur->varstr, hush_version_str) == 0)
5693 if (cur->flg_read_only) {
5694 *pp++ = (char *) "-R";
5695 *pp++ = cur->varstr;
5696 } else if (!cur->flg_export) {
5697 *pp++ = (char *) "-V";
5698 *pp++ = cur->varstr;
5701 # if ENABLE_HUSH_FUNCTIONS
5702 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5703 *pp++ = (char *) "-F";
5704 *pp++ = funcp->name;
5705 *pp++ = funcp->body_as_string;
5708 /* We can pass activated traps here. Say, -Tnn:trap_string
5710 * However, POSIX says that subshells reset signals with traps
5712 * I tested bash-3.2 and it not only does that with true subshells
5713 * of the form ( list ), but with any forked children shells.
5714 * I set trap "echo W" WINCH; and then tried:
5716 * { echo 1; sleep 20; echo 2; } &
5717 * while true; do echo 1; sleep 20; echo 2; break; done &
5718 * true | { echo 1; sleep 20; echo 2; } | cat
5720 * In all these cases sending SIGWINCH to the child shell
5721 * did not run the trap. If I add trap "echo V" WINCH;
5722 * _inside_ group (just before echo 1), it works.
5724 * I conclude it means we don't need to pass active traps here.
5726 *pp++ = (char *) "-c";
5729 while (*++builtin_argv)
5730 *pp++ = *builtin_argv;
5731 *pp++ = (char *) "";
5736 /* *pp = NULL; - is already there */
5740 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5741 /* Don't propagate SIG_IGN to the child */
5742 if (SPECIAL_JOBSTOP_SIGS != 0)
5743 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5744 execve(bb_busybox_exec_path, argv, pp);
5745 /* Fallback. Useful for init=/bin/hush usage etc */
5746 if (argv[0][0] == '/')
5747 execve(argv[0], argv, pp);
5748 xfunc_error_retval = 127;
5749 bb_error_msg_and_die("can't re-execute the shell");
5751 #endif /* !BB_MMU */
5754 static int run_and_free_list(struct pipe *pi);
5756 /* Executing from string: eval, sh -c '...'
5757 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5758 * end_trigger controls how often we stop parsing
5759 * NUL: parse all, execute, return
5760 * ';': parse till ';' or newline, execute, repeat till EOF
5762 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5764 /* Why we need empty flag?
5765 * An obscure corner case "false; ``; echo $?":
5766 * empty command in `` should still set $? to 0.
5767 * But we can't just set $? to 0 at the start,
5768 * this breaks "false; echo `echo $?`" case.
5772 struct pipe *pipe_list;
5774 #if ENABLE_HUSH_INTERACTIVE
5775 if (end_trigger == ';')
5776 inp->promptmode = 0; /* PS1 */
5778 pipe_list = parse_stream(NULL, inp, end_trigger);
5779 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5780 /* If we are in "big" script
5781 * (not in `cmd` or something similar)...
5783 if (pipe_list == ERR_PTR && end_trigger == ';') {
5784 /* Discard cached input (rest of line) */
5785 int ch = inp->last_char;
5786 while (ch != EOF && ch != '\n') {
5787 //bb_error_msg("Discarded:'%c'", ch);
5792 /* This stream isn't empty */
5796 if (!pipe_list && empty)
5797 G.last_exitcode = 0;
5800 debug_print_tree(pipe_list, 0);
5801 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5802 run_and_free_list(pipe_list);
5804 #if ENABLE_HUSH_FUNCTIONS
5805 if (G.flag_return_in_progress == 1)
5811 static void parse_and_run_string(const char *s)
5813 struct in_str input;
5814 setup_string_in_str(&input, s);
5815 parse_and_run_stream(&input, '\0');
5818 static void parse_and_run_file(FILE *f)
5820 struct in_str input;
5821 setup_file_in_str(&input, f);
5822 parse_and_run_stream(&input, ';');
5825 #if ENABLE_HUSH_TICK
5826 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5831 char **to_free = NULL;
5835 pid = BB_MMU ? xfork() : xvfork();
5836 if (pid == 0) { /* child */
5837 disable_restore_tty_pgrp_on_exit();
5838 /* Process substitution is not considered to be usual
5839 * 'command execution'.
5840 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5847 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5848 close(channel[0]); /* NB: close _first_, then move fd! */
5849 xmove_fd(channel[1], 1);
5850 /* Prevent it from trying to handle ctrl-z etc */
5851 IF_HUSH_JOB(G.run_list_level = 1;)
5852 /* Awful hack for `trap` or $(trap).
5854 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5855 * contains an example where "trap" is executed in a subshell:
5857 * save_traps=$(trap)
5859 * eval "$save_traps"
5861 * Standard does not say that "trap" in subshell shall print
5862 * parent shell's traps. It only says that its output
5863 * must have suitable form, but then, in the above example
5864 * (which is not supposed to be normative), it implies that.
5866 * bash (and probably other shell) does implement it
5867 * (traps are reset to defaults, but "trap" still shows them),
5868 * but as a result, "trap" logic is hopelessly messed up:
5871 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5872 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5873 * # true | trap <--- trap is in subshell - no output (ditto)
5874 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5875 * trap -- 'echo Ho' SIGWINCH
5876 * # echo `(trap)` <--- in subshell in subshell - output
5877 * trap -- 'echo Ho' SIGWINCH
5878 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5879 * trap -- 'echo Ho' SIGWINCH
5881 * The rules when to forget and when to not forget traps
5882 * get really complex and nonsensical.
5884 * Our solution: ONLY bare $(trap) or `trap` is special.
5886 s = skip_whitespace(s);
5887 if (is_prefixed_with(s, "trap")
5888 && skip_whitespace(s + 4)[0] == '\0'
5890 static const char *const argv[] = { NULL, NULL };
5891 builtin_trap((char**)argv);
5892 exit(0); /* not _exit() - we need to fflush */
5895 reset_traps_to_defaults();
5896 parse_and_run_string(s);
5897 _exit(G.last_exitcode);
5899 /* We re-execute after vfork on NOMMU. This makes this script safe:
5900 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5901 * huge=`cat BIG` # was blocking here forever
5904 re_execute_shell(&to_free,
5914 # if ENABLE_HUSH_FAST
5916 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5917 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5918 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5920 enable_restore_tty_pgrp_on_exit();
5925 close_on_exec_on(channel[0]);
5926 return xfdopen_for_read(channel[0]);
5929 /* Return code is exit status of the process that is run. */
5930 static int process_command_subs(o_string *dest, const char *s)
5933 struct in_str pipe_str;
5935 int status, ch, eol_cnt;
5937 fp = generate_stream_from_string(s, &pid);
5939 /* Now send results of command back into original context */
5940 setup_file_in_str(&pipe_str, fp);
5942 while ((ch = i_getch(&pipe_str)) != EOF) {
5948 o_addchr(dest, '\n');
5951 o_addQchr(dest, ch);
5954 debug_printf("done reading from `cmd` pipe, closing it\n");
5956 /* We need to extract exitcode. Test case
5957 * "true; echo `sleep 1; false` $?"
5959 safe_waitpid(pid, &status, 0);
5960 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5961 return WEXITSTATUS(status);
5963 #endif /* ENABLE_HUSH_TICK */
5966 static void setup_heredoc(struct redir_struct *redir)
5968 struct fd_pair pair;
5971 /* the _body_ of heredoc (misleading field name) */
5972 const char *heredoc = redir->rd_filename;
5979 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5980 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5984 len = strlen(heredoc);
5986 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5988 xmove_fd(pair.rd, redir->rd_fd);
5990 /* Try writing without forking. Newer kernels have
5991 * dynamically growing pipes. Must use non-blocking write! */
5994 written = write(pair.wr, heredoc, len);
6005 ndelay_off(pair.wr);
6007 /* Okay, pipe buffer was not big enough */
6008 /* Note: we must not create a stray child (bastard? :)
6009 * for the unsuspecting parent process. Child creates a grandchild
6010 * and exits before parent execs the process which consumes heredoc
6011 * (that exec happens after we return from this function) */
6018 disable_restore_tty_pgrp_on_exit();
6019 pid = BB_MMU ? xfork() : xvfork();
6023 close(redir->rd_fd); /* read side of the pipe */
6025 full_write(pair.wr, heredoc, len); /* may loop or block */
6028 /* Delegate blocking writes to another process */
6029 xmove_fd(pair.wr, STDOUT_FILENO);
6030 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6034 #if ENABLE_HUSH_FAST
6036 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6038 enable_restore_tty_pgrp_on_exit();
6044 wait(NULL); /* wait till child has died */
6047 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6048 * and stderr if they are redirected. */
6049 static int setup_redirects(struct command *prog, int squirrel[])
6052 struct redir_struct *redir;
6054 for (redir = prog->redirects; redir; redir = redir->next) {
6055 if (redir->rd_type == REDIRECT_HEREDOC2) {
6056 /* rd_fd<<HERE case */
6057 if (squirrel && redir->rd_fd < 3
6058 && squirrel[redir->rd_fd] < 0
6060 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6062 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6064 debug_printf_parse("set heredoc '%s'\n",
6065 redir->rd_filename);
6066 setup_heredoc(redir);
6070 if (redir->rd_dup == REDIRFD_TO_FILE) {
6071 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6073 if (redir->rd_filename == NULL) {
6074 /* Something went wrong in the parse.
6075 * Pretend it didn't happen */
6076 bb_error_msg("bug in redirect parse");
6079 mode = redir_table[redir->rd_type].mode;
6080 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6081 openfd = open_or_warn(p, mode);
6084 /* this could get lost if stderr has been redirected, but
6085 * bash and ash both lose it as well (though zsh doesn't!) */
6086 //what the above comment tries to say?
6090 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6091 openfd = redir->rd_dup;
6094 if (openfd != redir->rd_fd) {
6095 if (squirrel && redir->rd_fd < 3
6096 && squirrel[redir->rd_fd] < 0
6098 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6100 if (openfd == REDIRFD_CLOSE) {
6101 /* "n>-" means "close me" */
6102 close(redir->rd_fd);
6104 xdup2(openfd, redir->rd_fd);
6105 if (redir->rd_dup == REDIRFD_TO_FILE)
6113 static void restore_redirects(int squirrel[])
6116 for (i = 0; i < 3; i++) {
6119 /* We simply die on error */
6125 static char *find_in_path(const char *arg)
6128 const char *PATH = get_local_var_value("PATH");
6134 const char *end = strchrnul(PATH, ':');
6135 int sz = end - PATH; /* must be int! */
6139 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6141 /* We have xxx::yyyy in $PATH,
6142 * it means "use current dir" */
6145 if (access(ret, F_OK) == 0)
6158 static const struct built_in_command *find_builtin_helper(const char *name,
6159 const struct built_in_command *x,
6160 const struct built_in_command *end)
6163 if (strcmp(name, x->b_cmd) != 0) {
6167 debug_printf_exec("found builtin '%s'\n", name);
6172 static const struct built_in_command *find_builtin1(const char *name)
6174 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6176 static const struct built_in_command *find_builtin(const char *name)
6178 const struct built_in_command *x = find_builtin1(name);
6181 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6184 #if ENABLE_HUSH_FUNCTIONS
6185 static struct function **find_function_slot(const char *name)
6187 struct function **funcpp = &G.top_func;
6189 if (strcmp(name, (*funcpp)->name) == 0) {
6192 funcpp = &(*funcpp)->next;
6197 static const struct function *find_function(const char *name)
6199 const struct function *funcp = *find_function_slot(name);
6201 debug_printf_exec("found function '%s'\n", name);
6205 /* Note: takes ownership on name ptr */
6206 static struct function *new_function(char *name)
6208 struct function **funcpp = find_function_slot(name);
6209 struct function *funcp = *funcpp;
6211 if (funcp != NULL) {
6212 struct command *cmd = funcp->parent_cmd;
6213 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6215 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6217 /* Note: if !funcp->body, do not free body_as_string!
6218 * This is a special case of "-F name body" function:
6219 * body_as_string was not malloced! */
6221 free_pipe_list(funcp->body);
6223 free(funcp->body_as_string);
6227 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6228 cmd->argv[0] = funcp->name;
6229 cmd->group = funcp->body;
6231 cmd->group_as_string = funcp->body_as_string;
6235 debug_printf_exec("remembering new function '%s'\n", name);
6236 funcp = *funcpp = xzalloc(sizeof(*funcp));
6237 /*funcp->next = NULL;*/
6244 static void unset_func(const char *name)
6246 struct function **funcpp = find_function_slot(name);
6247 struct function *funcp = *funcpp;
6249 if (funcp != NULL) {
6250 debug_printf_exec("freeing function '%s'\n", funcp->name);
6251 *funcpp = funcp->next;
6252 /* funcp is unlinked now, deleting it.
6253 * Note: if !funcp->body, the function was created by
6254 * "-F name body", do not free ->body_as_string
6255 * and ->name as they were not malloced. */
6257 free_pipe_list(funcp->body);
6260 free(funcp->body_as_string);
6268 #define exec_function(to_free, funcp, argv) \
6269 exec_function(funcp, argv)
6271 static void exec_function(char ***to_free,
6272 const struct function *funcp,
6273 char **argv) NORETURN;
6274 static void exec_function(char ***to_free,
6275 const struct function *funcp,
6281 argv[0] = G.global_argv[0];
6282 G.global_argv = argv;
6286 /* On MMU, funcp->body is always non-NULL */
6287 n = run_list(funcp->body);
6291 re_execute_shell(to_free,
6292 funcp->body_as_string,
6299 static int run_function(const struct function *funcp, char **argv)
6305 save_and_replace_G_args(&sv, argv);
6307 /* "we are in function, ok to use return" */
6308 sv_flg = G.flag_return_in_progress;
6309 G.flag_return_in_progress = -1;
6310 # if ENABLE_HUSH_LOCAL
6311 G.func_nest_level++;
6314 /* On MMU, funcp->body is always non-NULL */
6317 /* Function defined by -F */
6318 parse_and_run_string(funcp->body_as_string);
6319 rc = G.last_exitcode;
6323 rc = run_list(funcp->body);
6326 # if ENABLE_HUSH_LOCAL
6328 struct variable *var;
6329 struct variable **var_pp;
6331 var_pp = &G.top_var;
6332 while ((var = *var_pp) != NULL) {
6333 if (var->func_nest_level < G.func_nest_level) {
6334 var_pp = &var->next;
6338 if (var->flg_export)
6339 bb_unsetenv(var->varstr);
6340 /* Remove from global list */
6341 *var_pp = var->next;
6347 G.func_nest_level--;
6350 G.flag_return_in_progress = sv_flg;
6352 restore_G_args(&sv, argv);
6356 #endif /* ENABLE_HUSH_FUNCTIONS */
6360 #define exec_builtin(to_free, x, argv) \
6361 exec_builtin(x, argv)
6363 #define exec_builtin(to_free, x, argv) \
6364 exec_builtin(to_free, argv)
6366 static void exec_builtin(char ***to_free,
6367 const struct built_in_command *x,
6368 char **argv) NORETURN;
6369 static void exec_builtin(char ***to_free,
6370 const struct built_in_command *x,
6376 rcode = x->b_function(argv);
6381 /* On NOMMU, we must never block!
6382 * Example: { sleep 99 | read line; } & echo Ok
6384 re_execute_shell(to_free,
6393 static void execvp_or_die(char **argv) NORETURN;
6394 static void execvp_or_die(char **argv)
6396 debug_printf_exec("execing '%s'\n", argv[0]);
6397 /* Don't propagate SIG_IGN to the child */
6398 if (SPECIAL_JOBSTOP_SIGS != 0)
6399 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6400 execvp(argv[0], argv);
6401 bb_perror_msg("can't execute '%s'", argv[0]);
6402 _exit(127); /* bash compat */
6405 #if ENABLE_HUSH_MODE_X
6406 static void dump_cmd_in_x_mode(char **argv)
6408 if (G_x_mode && argv) {
6409 /* We want to output the line in one write op */
6417 len += strlen(argv[n++]) + 1;
6423 p += sprintf(p, " %s", argv[n++]);
6431 # define dump_cmd_in_x_mode(argv) ((void)0)
6435 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6436 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6437 #define pseudo_exec(nommu_save, command, argv_expanded) \
6438 pseudo_exec(command, argv_expanded)
6441 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6443 * Don't exit() here. If you don't exec, use _exit instead.
6444 * The at_exit handlers apparently confuse the calling process,
6445 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6446 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6447 char **argv, int assignment_cnt,
6448 char **argv_expanded) NORETURN;
6449 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6450 char **argv, int assignment_cnt,
6451 char **argv_expanded)
6455 new_env = expand_assignments(argv, assignment_cnt);
6456 dump_cmd_in_x_mode(new_env);
6458 if (!argv[assignment_cnt]) {
6459 /* Case when we are here: ... | var=val | ...
6460 * (note that we do not exit early, i.e., do not optimize out
6461 * expand_assignments(): think about ... | var=`sleep 1` | ...
6463 free_strings(new_env);
6464 _exit(EXIT_SUCCESS);
6468 set_vars_and_save_old(new_env);
6469 free(new_env); /* optional */
6470 /* we can also destroy set_vars_and_save_old's return value,
6473 nommu_save->new_env = new_env;
6474 nommu_save->old_vars = set_vars_and_save_old(new_env);
6477 if (argv_expanded) {
6478 argv = argv_expanded;
6480 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6482 nommu_save->argv = argv;
6485 dump_cmd_in_x_mode(argv);
6487 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6488 if (strchr(argv[0], '/') != NULL)
6492 /* Check if the command matches any of the builtins.
6493 * Depending on context, this might be redundant. But it's
6494 * easier to waste a few CPU cycles than it is to figure out
6495 * if this is one of those cases.
6498 /* On NOMMU, it is more expensive to re-execute shell
6499 * just in order to run echo or test builtin.
6500 * It's better to skip it here and run corresponding
6501 * non-builtin later. */
6502 const struct built_in_command *x;
6503 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6505 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6508 #if ENABLE_HUSH_FUNCTIONS
6509 /* Check if the command matches any functions */
6511 const struct function *funcp = find_function(argv[0]);
6513 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6518 #if ENABLE_FEATURE_SH_STANDALONE
6519 /* Check if the command matches any busybox applets */
6521 int a = find_applet_by_name(argv[0]);
6523 # if BB_MMU /* see above why on NOMMU it is not allowed */
6524 if (APPLET_IS_NOEXEC(a)) {
6525 debug_printf_exec("running applet '%s'\n", argv[0]);
6526 run_applet_no_and_exit(a, argv);
6529 /* Re-exec ourselves */
6530 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6531 /* Don't propagate SIG_IGN to the child */
6532 if (SPECIAL_JOBSTOP_SIGS != 0)
6533 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6534 execv(bb_busybox_exec_path, argv);
6535 /* If they called chroot or otherwise made the binary no longer
6536 * executable, fall through */
6541 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6544 execvp_or_die(argv);
6547 /* Called after [v]fork() in run_pipe
6549 static void pseudo_exec(nommu_save_t *nommu_save,
6550 struct command *command,
6551 char **argv_expanded) NORETURN;
6552 static void pseudo_exec(nommu_save_t *nommu_save,
6553 struct command *command,
6554 char **argv_expanded)
6556 if (command->argv) {
6557 pseudo_exec_argv(nommu_save, command->argv,
6558 command->assignment_cnt, argv_expanded);
6561 if (command->group) {
6562 /* Cases when we are here:
6565 * ... | ( list ) | ...
6566 * ... | { list } | ...
6570 debug_printf_exec("pseudo_exec: run_list\n");
6571 reset_traps_to_defaults();
6572 rcode = run_list(command->group);
6573 /* OK to leak memory by not calling free_pipe_list,
6574 * since this process is about to exit */
6577 re_execute_shell(&nommu_save->argv_from_re_execing,
6578 command->group_as_string,
6585 /* Case when we are here: ... | >file */
6586 debug_printf_exec("pseudo_exec'ed null command\n");
6587 _exit(EXIT_SUCCESS);
6591 static const char *get_cmdtext(struct pipe *pi)
6597 /* This is subtle. ->cmdtext is created only on first backgrounding.
6598 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6599 * On subsequent bg argv is trashed, but we won't use it */
6602 argv = pi->cmds[0].argv;
6603 if (!argv || !argv[0]) {
6604 pi->cmdtext = xzalloc(1);
6610 len += strlen(*argv) + 1;
6614 argv = pi->cmds[0].argv;
6616 len = strlen(*argv);
6617 memcpy(p, *argv, len);
6625 static void insert_bg_job(struct pipe *pi)
6627 struct pipe *job, **jobp;
6630 /* Linear search for the ID of the job to use */
6632 for (job = G.job_list; job; job = job->next)
6633 if (job->jobid >= pi->jobid)
6634 pi->jobid = job->jobid + 1;
6636 /* Add job to the list of running jobs */
6638 while ((job = *jobp) != NULL)
6640 job = *jobp = xmalloc(sizeof(*job));
6642 *job = *pi; /* physical copy */
6644 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6645 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6646 for (i = 0; i < pi->num_cmds; i++) {
6647 job->cmds[i].pid = pi->cmds[i].pid;
6648 /* all other fields are not used and stay zero */
6650 job->cmdtext = xstrdup(get_cmdtext(pi));
6652 if (G_interactive_fd)
6653 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6654 G.last_jobid = job->jobid;
6657 static void remove_bg_job(struct pipe *pi)
6659 struct pipe *prev_pipe;
6661 if (pi == G.job_list) {
6662 G.job_list = pi->next;
6664 prev_pipe = G.job_list;
6665 while (prev_pipe->next != pi)
6666 prev_pipe = prev_pipe->next;
6667 prev_pipe->next = pi->next;
6670 G.last_jobid = G.job_list->jobid;
6675 /* Remove a backgrounded job */
6676 static void delete_finished_bg_job(struct pipe *pi)
6683 /* Check to see if any processes have exited -- if they
6684 * have, figure out why and see if a job has completed */
6685 static int checkjobs(struct pipe *fg_pipe)
6695 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6697 attributes = WUNTRACED;
6698 if (fg_pipe == NULL)
6699 attributes |= WNOHANG;
6702 #if ENABLE_HUSH_FAST
6703 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6704 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6705 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6706 /* There was neither fork nor SIGCHLD since last waitpid */
6707 /* Avoid doing waitpid syscall if possible */
6708 if (!G.we_have_children) {
6712 if (fg_pipe == NULL) { /* is WNOHANG set? */
6713 /* We have children, but they did not exit
6714 * or stop yet (we saw no SIGCHLD) */
6717 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6721 /* Do we do this right?
6722 * bash-3.00# sleep 20 | false
6724 * [3]+ Stopped sleep 20 | false
6725 * bash-3.00# echo $?
6726 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6727 * [hush 1.14.0: yes we do it right]
6734 #if ENABLE_HUSH_FAST
6735 i = G.count_SIGCHLD;
6737 childpid = waitpid(-1, &status, attributes);
6738 if (childpid <= 0) {
6739 if (childpid && errno != ECHILD)
6740 bb_perror_msg("waitpid");
6741 #if ENABLE_HUSH_FAST
6742 else { /* Until next SIGCHLD, waitpid's are useless */
6743 G.we_have_children = (childpid == 0);
6744 G.handled_SIGCHLD = i;
6745 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6750 dead = WIFEXITED(status) || WIFSIGNALED(status);
6753 if (WIFSTOPPED(status))
6754 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6755 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6756 if (WIFSIGNALED(status))
6757 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6758 childpid, WTERMSIG(status), WEXITSTATUS(status));
6759 if (WIFEXITED(status))
6760 debug_printf_jobs("pid %d exited, exitcode %d\n",
6761 childpid, WEXITSTATUS(status));
6763 /* Were we asked to wait for fg pipe? */
6765 i = fg_pipe->num_cmds;
6767 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6768 if (fg_pipe->cmds[i].pid != childpid)
6772 fg_pipe->cmds[i].pid = 0;
6773 fg_pipe->alive_cmds--;
6774 ex = WEXITSTATUS(status);
6775 /* bash prints killer signal's name for *last*
6776 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6777 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6779 if (WIFSIGNALED(status)) {
6780 int sig = WTERMSIG(status);
6781 if (i == fg_pipe->num_cmds-1)
6782 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6783 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6784 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6785 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6786 * Maybe we need to use sig | 128? */
6789 fg_pipe->cmds[i].cmd_exitcode = ex;
6791 fg_pipe->stopped_cmds++;
6793 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6794 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6795 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6796 /* All processes in fg pipe have exited or stopped */
6797 i = fg_pipe->num_cmds;
6799 rcode = fg_pipe->cmds[i].cmd_exitcode;
6800 /* usually last process gives overall exitstatus,
6801 * but with "set -o pipefail", last *failed* process does */
6802 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6805 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6806 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6807 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6808 * and "killall -STOP cat" */
6809 if (G_interactive_fd) {
6811 if (fg_pipe->alive_cmds != 0)
6812 insert_bg_job(fg_pipe);
6816 if (fg_pipe->alive_cmds == 0)
6819 /* There are still running processes in the fg pipe */
6820 goto wait_more; /* do waitpid again */
6822 /* it wasnt fg_pipe, look for process in bg pipes */
6826 /* We asked to wait for bg or orphaned children */
6827 /* No need to remember exitcode in this case */
6828 for (pi = G.job_list; pi; pi = pi->next) {
6829 for (i = 0; i < pi->num_cmds; i++) {
6830 if (pi->cmds[i].pid == childpid)
6831 goto found_pi_and_prognum;
6834 /* Happens when shell is used as init process (init=/bin/sh) */
6835 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6836 continue; /* do waitpid again */
6838 found_pi_and_prognum:
6841 pi->cmds[i].pid = 0;
6843 if (!pi->alive_cmds) {
6844 if (G_interactive_fd)
6845 printf(JOB_STATUS_FORMAT, pi->jobid,
6846 "Done", pi->cmdtext);
6847 delete_finished_bg_job(pi);
6854 } /* while (waitpid succeeds)... */
6860 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6863 int rcode = checkjobs(fg_pipe);
6864 if (G_saved_tty_pgrp) {
6865 /* Job finished, move the shell to the foreground */
6866 p = getpgrp(); /* our process group id */
6867 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6868 tcsetpgrp(G_interactive_fd, p);
6874 /* Start all the jobs, but don't wait for anything to finish.
6877 * Return code is normally -1, when the caller has to wait for children
6878 * to finish to determine the exit status of the pipe. If the pipe
6879 * is a simple builtin command, however, the action is done by the
6880 * time run_pipe returns, and the exit code is provided as the
6883 * Returns -1 only if started some children. IOW: we have to
6884 * mask out retvals of builtins etc with 0xff!
6886 * The only case when we do not need to [v]fork is when the pipe
6887 * is single, non-backgrounded, non-subshell command. Examples:
6888 * cmd ; ... { list } ; ...
6889 * cmd && ... { list } && ...
6890 * cmd || ... { list } || ...
6891 * If it is, then we can run cmd as a builtin, NOFORK,
6892 * or (if SH_STANDALONE) an applet, and we can run the { list }
6893 * with run_list. If it isn't one of these, we fork and exec cmd.
6895 * Cases when we must fork:
6896 * non-single: cmd | cmd
6897 * backgrounded: cmd & { list } &
6898 * subshell: ( list ) [&]
6900 #if !ENABLE_HUSH_MODE_X
6901 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6902 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6904 static int redirect_and_varexp_helper(char ***new_env_p,
6905 struct variable **old_vars_p,
6906 struct command *command,
6908 char **argv_expanded)
6910 /* setup_redirects acts on file descriptors, not FILEs.
6911 * This is perfect for work that comes after exec().
6912 * Is it really safe for inline use? Experimentally,
6913 * things seem to work. */
6914 int rcode = setup_redirects(command, squirrel);
6916 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6917 *new_env_p = new_env;
6918 dump_cmd_in_x_mode(new_env);
6919 dump_cmd_in_x_mode(argv_expanded);
6921 *old_vars_p = set_vars_and_save_old(new_env);
6925 static NOINLINE int run_pipe(struct pipe *pi)
6927 static const char *const null_ptr = NULL;
6931 struct command *command;
6932 char **argv_expanded;
6934 /* it is not always needed, but we aim to smaller code */
6935 int squirrel[] = { -1, -1, -1 };
6938 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6941 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6942 * Result should be 3 lines: q w e, qwe, q w e
6944 G.ifs = get_local_var_value("IFS");
6948 IF_HUSH_JOB(pi->pgrp = -1;)
6949 pi->stopped_cmds = 0;
6950 command = &pi->cmds[0];
6951 argv_expanded = NULL;
6953 if (pi->num_cmds != 1
6954 || pi->followup == PIPE_BG
6955 || command->cmd_type == CMD_SUBSHELL
6962 debug_printf_exec(": group:%p argv:'%s'\n",
6963 command->group, command->argv ? command->argv[0] : "NONE");
6965 if (command->group) {
6966 #if ENABLE_HUSH_FUNCTIONS
6967 if (command->cmd_type == CMD_FUNCDEF) {
6968 /* "executing" func () { list } */
6969 struct function *funcp;
6971 funcp = new_function(command->argv[0]);
6972 /* funcp->name is already set to argv[0] */
6973 funcp->body = command->group;
6975 funcp->body_as_string = command->group_as_string;
6976 command->group_as_string = NULL;
6978 command->group = NULL;
6979 command->argv[0] = NULL;
6980 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6981 funcp->parent_cmd = command;
6982 command->child_func = funcp;
6984 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6986 return EXIT_SUCCESS;
6990 debug_printf("non-subshell group\n");
6991 rcode = 1; /* exitcode if redir failed */
6992 if (setup_redirects(command, squirrel) == 0) {
6993 debug_printf_exec(": run_list\n");
6994 rcode = run_list(command->group) & 0xff;
6996 restore_redirects(squirrel);
6997 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6999 debug_printf_exec("run_pipe: return %d\n", rcode);
7003 argv = command->argv ? command->argv : (char **) &null_ptr;
7005 const struct built_in_command *x;
7006 #if ENABLE_HUSH_FUNCTIONS
7007 const struct function *funcp;
7011 char **new_env = NULL;
7012 struct variable *old_vars = NULL;
7014 if (argv[command->assignment_cnt] == NULL) {
7015 /* Assignments, but no command */
7016 /* Ensure redirects take effect (that is, create files).
7017 * Try "a=t >file" */
7018 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7019 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7020 /* Set shell variables */
7024 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7025 /* Do we need to flag set_local_var() errors?
7026 * "assignment to readonly var" and "putenv error"
7031 /* Redirect error sets $? to 1. Otherwise,
7032 * if evaluating assignment value set $?, retain it.
7033 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7035 rcode = G.last_exitcode;
7036 /* Exit, _skipping_ variable restoring code: */
7037 goto clean_up_and_ret0;
7039 #else /* Older, bigger, but more correct code */
7041 rcode = setup_redirects(command, squirrel);
7042 restore_redirects(squirrel);
7043 /* Set shell variables */
7045 bb_putchar_stderr('+');
7047 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7049 fprintf(stderr, " %s", p);
7050 debug_printf_exec("set shell var:'%s'->'%s'\n",
7052 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7053 /* Do we need to flag set_local_var() errors?
7054 * "assignment to readonly var" and "putenv error"
7059 bb_putchar_stderr('\n');
7060 /* Redirect error sets $? to 1. Otherwise,
7061 * if evaluating assignment value set $?, retain it.
7062 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7064 rcode = G.last_exitcode;
7065 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7067 debug_printf_exec("run_pipe: return %d\n", rcode);
7072 /* Expand the rest into (possibly) many strings each */
7073 #if ENABLE_HUSH_BASH_COMPAT
7074 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7075 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7079 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7082 /* if someone gives us an empty string: `cmd with empty output` */
7083 if (!argv_expanded[0]) {
7084 free(argv_expanded);
7086 return G.last_exitcode;
7089 x = find_builtin(argv_expanded[0]);
7090 #if ENABLE_HUSH_FUNCTIONS
7093 funcp = find_function(argv_expanded[0]);
7097 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7098 debug_printf("exec with redirects only\n");
7099 rcode = setup_redirects(command, NULL);
7100 goto clean_up_and_ret1;
7103 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7106 debug_printf_exec(": builtin '%s' '%s'...\n",
7107 x->b_cmd, argv_expanded[1]);
7109 rcode = x->b_function(argv_expanded) & 0xff;
7112 #if ENABLE_HUSH_FUNCTIONS
7114 # if ENABLE_HUSH_LOCAL
7115 struct variable **sv;
7116 sv = G.shadowed_vars_pp;
7117 G.shadowed_vars_pp = &old_vars;
7119 debug_printf_exec(": function '%s' '%s'...\n",
7120 funcp->name, argv_expanded[1]);
7121 rcode = run_function(funcp, argv_expanded) & 0xff;
7122 # if ENABLE_HUSH_LOCAL
7123 G.shadowed_vars_pp = sv;
7129 unset_vars(new_env);
7131 /* clean_up_and_ret0: */
7132 restore_redirects(squirrel);
7134 free(argv_expanded);
7135 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7137 debug_printf_exec("run_pipe return %d\n", rcode);
7141 if (ENABLE_FEATURE_SH_NOFORK) {
7142 int n = find_applet_by_name(argv_expanded[0]);
7143 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7144 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7146 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7147 argv_expanded[0], argv_expanded[1]);
7148 rcode = run_nofork_applet(n, argv_expanded);
7150 goto clean_up_and_ret;
7153 /* It is neither builtin nor applet. We must fork. */
7157 /* NB: argv_expanded may already be created, and that
7158 * might include `cmd` runs! Do not rerun it! We *must*
7159 * use argv_expanded if it's non-NULL */
7161 /* Going to fork a child per each pipe member */
7166 while (cmd_no < pi->num_cmds) {
7167 struct fd_pair pipefds;
7169 volatile nommu_save_t nommu_save;
7170 nommu_save.new_env = NULL;
7171 nommu_save.old_vars = NULL;
7172 nommu_save.argv = NULL;
7173 nommu_save.argv_from_re_execing = NULL;
7175 command = &pi->cmds[cmd_no];
7177 if (command->argv) {
7178 debug_printf_exec(": pipe member '%s' '%s'...\n",
7179 command->argv[0], command->argv[1]);
7181 debug_printf_exec(": pipe member with no argv\n");
7184 /* pipes are inserted between pairs of commands */
7187 if (cmd_no < pi->num_cmds)
7188 xpiped_pair(pipefds);
7190 command->pid = BB_MMU ? fork() : vfork();
7191 if (!command->pid) { /* child */
7193 disable_restore_tty_pgrp_on_exit();
7194 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7196 /* Every child adds itself to new process group
7197 * with pgid == pid_of_first_child_in_pipe */
7198 if (G.run_list_level == 1 && G_interactive_fd) {
7201 if (pgrp < 0) /* true for 1st process only */
7203 if (setpgid(0, pgrp) == 0
7204 && pi->followup != PIPE_BG
7205 && G_saved_tty_pgrp /* we have ctty */
7207 /* We do it in *every* child, not just first,
7209 tcsetpgrp(G_interactive_fd, pgrp);
7213 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7214 /* 1st cmd in backgrounded pipe
7215 * should have its stdin /dev/null'ed */
7217 if (open(bb_dev_null, O_RDONLY))
7218 xopen("/", O_RDONLY);
7220 xmove_fd(next_infd, 0);
7222 xmove_fd(pipefds.wr, 1);
7225 /* Like bash, explicit redirects override pipes,
7226 * and the pipe fd is available for dup'ing. */
7227 if (setup_redirects(command, NULL))
7230 /* Stores to nommu_save list of env vars putenv'ed
7231 * (NOMMU, on MMU we don't need that) */
7232 /* cast away volatility... */
7233 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7234 /* pseudo_exec() does not return */
7237 /* parent or error */
7238 #if ENABLE_HUSH_FAST
7240 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7242 enable_restore_tty_pgrp_on_exit();
7244 /* Clean up after vforked child */
7245 free(nommu_save.argv);
7246 free(nommu_save.argv_from_re_execing);
7247 unset_vars(nommu_save.new_env);
7248 add_vars(nommu_save.old_vars);
7250 free(argv_expanded);
7251 argv_expanded = NULL;
7252 if (command->pid < 0) { /* [v]fork failed */
7253 /* Clearly indicate, was it fork or vfork */
7254 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7258 /* Second and next children need to know pid of first one */
7260 pi->pgrp = command->pid;
7266 if (cmd_no < pi->num_cmds)
7268 /* Pass read (output) pipe end to next iteration */
7269 next_infd = pipefds.rd;
7272 if (!pi->alive_cmds) {
7274 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7279 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7283 /* NB: called by pseudo_exec, and therefore must not modify any
7284 * global data until exec/_exit (we can be a child after vfork!) */
7285 static int run_list(struct pipe *pi)
7287 #if ENABLE_HUSH_CASE
7288 char *case_word = NULL;
7290 #if ENABLE_HUSH_LOOPS
7291 struct pipe *loop_top = NULL;
7292 char **for_lcur = NULL;
7293 char **for_list = NULL;
7295 smallint last_followup;
7297 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7298 smalluint cond_code = 0;
7300 enum { cond_code = 0 };
7303 smallint rword; /* RES_foo */
7304 smallint last_rword; /* ditto */
7307 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7310 #if ENABLE_HUSH_LOOPS
7311 /* Check syntax for "for" */
7314 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7315 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7317 /* current word is FOR or IN (BOLD in comments below) */
7318 if (cpipe->next == NULL) {
7319 syntax_error("malformed for");
7321 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7324 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7325 if (cpipe->next->res_word == RES_DO)
7327 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7328 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7329 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7331 syntax_error("malformed for");
7333 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7340 /* Past this point, all code paths should jump to ret: label
7341 * in order to return, no direct "return" statements please.
7342 * This helps to ensure that no memory is leaked. */
7350 last_rword = RES_XXXX;
7352 last_followup = PIPE_SEQ;
7353 rcode = G.last_exitcode;
7355 /* Go through list of pipes, (maybe) executing them. */
7356 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7360 IF_HAS_KEYWORDS(rword = pi->res_word;)
7361 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7362 rword, cond_code, last_rword);
7363 #if ENABLE_HUSH_LOOPS
7364 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7365 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7367 /* start of a loop: remember where loop starts */
7372 /* Still in the same "if...", "then..." or "do..." branch? */
7373 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7374 if ((rcode == 0 && last_followup == PIPE_OR)
7375 || (rcode != 0 && last_followup == PIPE_AND)
7377 /* It is "<true> || CMD" or "<false> && CMD"
7378 * and we should not execute CMD */
7379 debug_printf_exec("skipped cmd because of || or &&\n");
7380 last_followup = pi->followup;
7381 goto dont_check_jobs_but_continue;
7384 last_followup = pi->followup;
7385 IF_HAS_KEYWORDS(last_rword = rword;)
7388 if (rword == RES_THEN) {
7389 /* if false; then ... fi has exitcode 0! */
7390 G.last_exitcode = rcode = EXIT_SUCCESS;
7391 /* "if <false> THEN cmd": skip cmd */
7395 if (rword == RES_ELSE || rword == RES_ELIF) {
7396 /* "if <true> then ... ELSE/ELIF cmd":
7397 * skip cmd and all following ones */
7402 #if ENABLE_HUSH_LOOPS
7403 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7405 /* first loop through for */
7407 static const char encoded_dollar_at[] ALIGN1 = {
7408 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7409 }; /* encoded representation of "$@" */
7410 static const char *const encoded_dollar_at_argv[] = {
7411 encoded_dollar_at, NULL
7412 }; /* argv list with one element: "$@" */
7415 vals = (char**)encoded_dollar_at_argv;
7416 if (pi->next->res_word == RES_IN) {
7417 /* if no variable values after "in" we skip "for" */
7418 if (!pi->next->cmds[0].argv) {
7419 G.last_exitcode = rcode = EXIT_SUCCESS;
7420 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7423 vals = pi->next->cmds[0].argv;
7424 } /* else: "for var; do..." -> assume "$@" list */
7425 /* create list of variable values */
7426 debug_print_strings("for_list made from", vals);
7427 for_list = expand_strvec_to_strvec(vals);
7428 for_lcur = for_list;
7429 debug_print_strings("for_list", for_list);
7432 /* "for" loop is over, clean up */
7438 /* Insert next value from for_lcur */
7439 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7440 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7443 if (rword == RES_IN) {
7444 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7446 if (rword == RES_DONE) {
7447 continue; /* "done" has no cmds too */
7450 #if ENABLE_HUSH_CASE
7451 if (rword == RES_CASE) {
7452 case_word = expand_strvec_to_string(pi->cmds->argv);
7455 if (rword == RES_MATCH) {
7458 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7460 /* all prev words didn't match, does this one match? */
7461 argv = pi->cmds->argv;
7463 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7464 /* TODO: which FNM_xxx flags to use? */
7465 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7467 if (cond_code == 0) { /* match! we will execute this branch */
7468 free(case_word); /* make future "word)" stop */
7476 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7478 continue; /* not matched yet, skip this pipe */
7481 /* Just pressing <enter> in shell should check for jobs.
7482 * OTOH, in non-interactive shell this is useless
7483 * and only leads to extra job checks */
7484 if (pi->num_cmds == 0) {
7485 if (G_interactive_fd)
7486 goto check_jobs_and_continue;
7490 /* After analyzing all keywords and conditions, we decided
7491 * to execute this pipe. NB: have to do checkjobs(NULL)
7492 * after run_pipe to collect any background children,
7493 * even if list execution is to be stopped. */
7494 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7497 #if ENABLE_HUSH_LOOPS
7498 G.flag_break_continue = 0;
7500 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7502 /* We ran a builtin, function, or group.
7503 * rcode is already known
7504 * and we don't need to wait for anything. */
7505 G.last_exitcode = rcode;
7506 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7507 check_and_run_traps();
7508 #if ENABLE_HUSH_LOOPS
7509 /* Was it "break" or "continue"? */
7510 if (G.flag_break_continue) {
7511 smallint fbc = G.flag_break_continue;
7512 /* We might fall into outer *loop*,
7513 * don't want to break it too */
7515 G.depth_break_continue--;
7516 if (G.depth_break_continue == 0)
7517 G.flag_break_continue = 0;
7518 /* else: e.g. "continue 2" should *break* once, *then* continue */
7519 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7520 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7524 /* "continue": simulate end of loop */
7529 #if ENABLE_HUSH_FUNCTIONS
7530 if (G.flag_return_in_progress == 1) {
7535 } else if (pi->followup == PIPE_BG) {
7536 /* What does bash do with attempts to background builtins? */
7537 /* even bash 3.2 doesn't do that well with nested bg:
7538 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7539 * I'm NOT treating inner &'s as jobs */
7540 check_and_run_traps();
7542 if (G.run_list_level == 1)
7545 /* Last command's pid goes to $! */
7546 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7547 G.last_exitcode = rcode = EXIT_SUCCESS;
7548 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7551 if (G.run_list_level == 1 && G_interactive_fd) {
7552 /* Waits for completion, then fg's main shell */
7553 rcode = checkjobs_and_fg_shell(pi);
7554 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7555 check_and_run_traps();
7558 { /* This one just waits for completion */
7559 rcode = checkjobs(pi);
7560 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7561 check_and_run_traps();
7563 G.last_exitcode = rcode;
7567 /* Analyze how result affects subsequent commands */
7569 if (rword == RES_IF || rword == RES_ELIF)
7572 check_jobs_and_continue:
7574 dont_check_jobs_but_continue: ;
7575 #if ENABLE_HUSH_LOOPS
7576 /* Beware of "while false; true; do ..."! */
7578 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7579 /* check for RES_DONE is needed for "while ...; do \n done" case */
7581 if (rword == RES_WHILE) {
7583 /* "while false; do...done" - exitcode 0 */
7584 G.last_exitcode = rcode = EXIT_SUCCESS;
7585 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7589 if (rword == RES_UNTIL) {
7591 debug_printf_exec(": until expr is true: breaking\n");
7602 #if ENABLE_HUSH_LOOPS
7607 #if ENABLE_HUSH_CASE
7611 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7615 /* Select which version we will use */
7616 static int run_and_free_list(struct pipe *pi)
7619 debug_printf_exec("run_and_free_list entered\n");
7620 if (!G.o_opt[OPT_O_NOEXEC]) {
7621 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7622 rcode = run_list(pi);
7624 /* free_pipe_list has the side effect of clearing memory.
7625 * In the long run that function can be merged with run_list,
7626 * but doing that now would hobble the debugging effort. */
7628 debug_printf_exec("run_and_free_list return %d\n", rcode);
7633 static void install_sighandlers(unsigned mask)
7635 sighandler_t old_handler;
7637 while ((mask >>= 1) != 0) {
7641 old_handler = install_sighandler(sig, pick_sighandler(sig));
7642 /* POSIX allows shell to re-enable SIGCHLD
7643 * even if it was SIG_IGN on entry.
7644 * Therefore we skip IGN check for it:
7648 if (old_handler == SIG_IGN) {
7649 /* oops... restore back to IGN, and record this fact */
7650 install_sighandler(sig, old_handler);
7652 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7654 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7659 /* Called a few times only (or even once if "sh -c") */
7660 static void install_special_sighandlers(void)
7664 /* Which signals are shell-special? */
7665 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7666 if (G_interactive_fd) {
7667 mask |= SPECIAL_INTERACTIVE_SIGS;
7668 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7669 mask |= SPECIAL_JOBSTOP_SIGS;
7671 /* Careful, do not re-install handlers we already installed */
7672 if (G.special_sig_mask != mask) {
7673 unsigned diff = mask & ~G.special_sig_mask;
7674 G.special_sig_mask = mask;
7675 install_sighandlers(diff);
7681 /* Set handlers to restore tty pgrp and exit */
7682 static void install_fatal_sighandlers(void)
7686 /* We will restore tty pgrp on these signals */
7688 + (1 << SIGILL ) * HUSH_DEBUG
7689 + (1 << SIGFPE ) * HUSH_DEBUG
7690 + (1 << SIGBUS ) * HUSH_DEBUG
7691 + (1 << SIGSEGV) * HUSH_DEBUG
7692 + (1 << SIGTRAP) * HUSH_DEBUG
7694 /* bash 3.2 seems to handle these just like 'fatal' ones */
7697 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7698 * if we aren't interactive... but in this case
7699 * we never want to restore pgrp on exit, and this fn is not called
7701 /*+ (1 << SIGHUP )*/
7702 /*+ (1 << SIGTERM)*/
7703 /*+ (1 << SIGINT )*/
7705 G_fatal_sig_mask = mask;
7707 install_sighandlers(mask);
7711 static int set_mode(int state, char mode, const char *o_opt)
7716 G.o_opt[OPT_O_NOEXEC] = state;
7719 IF_HUSH_MODE_X(G_x_mode = state;)
7723 /* "set -+o" without parameter.
7724 * in bash, set -o produces this output:
7728 * We always use the second form.
7730 const char *p = o_opt_strings;
7733 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7739 idx = index_in_strings(o_opt_strings, o_opt);
7741 G.o_opt[idx] = state;
7745 return EXIT_FAILURE;
7747 return EXIT_SUCCESS;
7750 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7751 int hush_main(int argc, char **argv)
7754 OPT_login = (1 << 0),
7758 unsigned builtin_argc;
7760 struct variable *cur_var;
7761 struct variable *shell_ver;
7764 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7765 G.last_exitcode = EXIT_SUCCESS;
7766 #if ENABLE_HUSH_FAST
7767 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7770 G.argv0_for_re_execing = argv[0];
7772 /* Deal with HUSH_VERSION */
7773 shell_ver = xzalloc(sizeof(*shell_ver));
7774 shell_ver->flg_export = 1;
7775 shell_ver->flg_read_only = 1;
7776 /* Code which handles ${var<op>...} needs writable values for all variables,
7777 * therefore we xstrdup: */
7778 shell_ver->varstr = xstrdup(hush_version_str);
7779 /* Create shell local variables from the values
7780 * currently living in the environment */
7781 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7782 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7783 G.top_var = shell_ver;
7784 cur_var = G.top_var;
7787 char *value = strchr(*e, '=');
7788 if (value) { /* paranoia */
7789 cur_var->next = xzalloc(sizeof(*cur_var));
7790 cur_var = cur_var->next;
7791 cur_var->varstr = *e;
7792 cur_var->max_len = strlen(*e);
7793 cur_var->flg_export = 1;
7797 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7798 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7799 putenv(shell_ver->varstr);
7802 set_pwd_var(/*exp:*/ 1);
7804 #if ENABLE_HUSH_BASH_COMPAT
7805 /* Set (but not export) HOSTNAME unless already set */
7806 if (!get_local_var_value("HOSTNAME")) {
7809 set_local_var_from_halves("HOSTNAME", uts.nodename);
7811 /* bash also exports SHLVL and _,
7812 * and sets (but doesn't export) the following variables:
7814 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7815 * BASH_VERSION='3.2.0(1)-release'
7817 * MACHTYPE=i386-pc-linux-gnu
7819 * PPID=<NNNNN> - we also do it elsewhere
7830 * PIPESTATUS=([0]="0")
7831 * HISTFILE=/<xxx>/.bash_history
7835 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7837 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7848 #if ENABLE_FEATURE_EDITING
7849 G.line_input_state = new_line_input_t(FOR_SHELL);
7852 /* Initialize some more globals to non-zero values */
7853 cmdedit_update_prompt();
7855 if (setjmp(die_jmp)) {
7856 /* xfunc has failed! die die die */
7857 /* no EXIT traps, this is an escape hatch! */
7859 hush_exit(xfunc_error_retval);
7862 /* Shell is non-interactive at first. We need to call
7863 * install_special_sighandlers() if we are going to execute "sh <script>",
7864 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7865 * If we later decide that we are interactive, we run install_special_sighandlers()
7866 * in order to intercept (more) signals.
7870 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7871 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7874 opt = getopt(argc, argv, "+c:xinsl"
7877 # if ENABLE_HUSH_FUNCTIONS
7887 * sh ... -c 'script'
7888 * sh ... -c 'script' ARG0 [ARG1...]
7889 * On NOMMU, if builtin_argc != 0,
7890 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7891 * "" needs to be replaced with NULL
7892 * and BARGV vector fed to builtin function.
7893 * Note: the form without ARG0 never happens:
7894 * sh ... -c 'builtin' BARGV... ""
7897 G.root_pid = getpid();
7898 G.root_ppid = getppid();
7900 G.global_argv = argv + optind;
7901 G.global_argc = argc - optind;
7903 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7904 const struct built_in_command *x;
7906 install_special_sighandlers();
7907 x = find_builtin(optarg);
7908 if (x) { /* paranoia */
7909 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7910 G.global_argv += builtin_argc;
7911 G.global_argv[-1] = NULL; /* replace "" */
7913 G.last_exitcode = x->b_function(argv + optind - 1);
7917 if (!G.global_argv[0]) {
7918 /* -c 'script' (no params): prevent empty $0 */
7919 G.global_argv--; /* points to argv[i] of 'script' */
7920 G.global_argv[0] = argv[0];
7922 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7923 install_special_sighandlers();
7924 parse_and_run_string(optarg);
7927 /* Well, we cannot just declare interactiveness,
7928 * we have to have some stuff (ctty, etc) */
7929 /* G_interactive_fd++; */
7932 /* "-s" means "read from stdin", but this is how we always
7933 * operate, so simply do nothing here. */
7939 case '<': /* "big heredoc" support */
7940 full_write1_str(optarg);
7943 unsigned long long empty_trap_mask;
7945 G.root_pid = bb_strtou(optarg, &optarg, 16);
7947 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7949 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7951 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7953 builtin_argc = bb_strtou(optarg, &optarg, 16);
7955 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7956 if (empty_trap_mask != 0) {
7958 install_special_sighandlers();
7959 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7960 for (sig = 1; sig < NSIG; sig++) {
7961 if (empty_trap_mask & (1LL << sig)) {
7962 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7963 install_sighandler(sig, SIG_IGN);
7967 # if ENABLE_HUSH_LOOPS
7969 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7975 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7977 # if ENABLE_HUSH_FUNCTIONS
7979 struct function *funcp = new_function(optarg);
7980 /* funcp->name is already set to optarg */
7981 /* funcp->body is set to NULL. It's a special case. */
7982 funcp->body_as_string = argv[optind];
7990 if (set_mode(1, opt, NULL) == 0) /* no error */
7994 fprintf(stderr, "Usage: sh [FILE]...\n"
7995 " or: sh -c command [args]...\n\n");
8001 } /* option parsing loop */
8003 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8004 G.global_argc = argc - (optind - 1);
8005 G.global_argv = argv + (optind - 1);
8006 G.global_argv[0] = argv[0];
8009 G.root_pid = getpid();
8010 G.root_ppid = getppid();
8013 /* If we are login shell... */
8014 if (flags & OPT_login) {
8016 debug_printf("sourcing /etc/profile\n");
8017 input = fopen_for_read("/etc/profile");
8018 if (input != NULL) {
8019 close_on_exec_on(fileno(input));
8020 install_special_sighandlers();
8021 parse_and_run_file(input);
8024 /* bash: after sourcing /etc/profile,
8025 * tries to source (in the given order):
8026 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8027 * stopping on first found. --noprofile turns this off.
8028 * bash also sources ~/.bash_logout on exit.
8029 * If called as sh, skips .bash_XXX files.
8033 if (G.global_argv[1]) {
8036 * "bash <script>" (which is never interactive (unless -i?))
8037 * sources $BASH_ENV here (without scanning $PATH).
8038 * If called as sh, does the same but with $ENV.
8042 debug_printf("running script '%s'\n", G.global_argv[0]);
8043 input = xfopen_for_read(G.global_argv[0]);
8044 close_on_exec_on(fileno(input));
8045 install_special_sighandlers();
8046 parse_and_run_file(input);
8047 #if ENABLE_FEATURE_CLEAN_UP
8053 /* Up to here, shell was non-interactive. Now it may become one.
8054 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8057 /* A shell is interactive if the '-i' flag was given,
8058 * or if all of the following conditions are met:
8060 * no arguments remaining or the -s flag given
8061 * standard input is a terminal
8062 * standard output is a terminal
8063 * Refer to Posix.2, the description of the 'sh' utility.
8066 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8067 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8068 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8069 if (G_saved_tty_pgrp < 0)
8070 G_saved_tty_pgrp = 0;
8072 /* try to dup stdin to high fd#, >= 255 */
8073 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8074 if (G_interactive_fd < 0) {
8075 /* try to dup to any fd */
8076 G_interactive_fd = dup(STDIN_FILENO);
8077 if (G_interactive_fd < 0) {
8079 G_interactive_fd = 0;
8080 G_saved_tty_pgrp = 0;
8083 // TODO: track & disallow any attempts of user
8084 // to (inadvertently) close/redirect G_interactive_fd
8086 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8087 if (G_interactive_fd) {
8088 close_on_exec_on(G_interactive_fd);
8090 if (G_saved_tty_pgrp) {
8091 /* If we were run as 'hush &', sleep until we are
8092 * in the foreground (tty pgrp == our pgrp).
8093 * If we get started under a job aware app (like bash),
8094 * make sure we are now in charge so we don't fight over
8095 * who gets the foreground */
8097 pid_t shell_pgrp = getpgrp();
8098 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8099 if (G_saved_tty_pgrp == shell_pgrp)
8101 /* send TTIN to ourself (should stop us) */
8102 kill(- shell_pgrp, SIGTTIN);
8106 /* Install more signal handlers */
8107 install_special_sighandlers();
8109 if (G_saved_tty_pgrp) {
8110 /* Set other signals to restore saved_tty_pgrp */
8111 install_fatal_sighandlers();
8112 /* Put ourselves in our own process group
8113 * (bash, too, does this only if ctty is available) */
8114 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8115 /* Grab control of the terminal */
8116 tcsetpgrp(G_interactive_fd, getpid());
8118 /* -1 is special - makes xfuncs longjmp, not exit
8119 * (we reset die_sleep = 0 whereever we [v]fork) */
8120 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8122 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8124 const char *hp = get_local_var_value("HISTFILE");
8126 hp = get_local_var_value("HOME");
8128 hp = concat_path_file(hp, ".hush_history");
8133 G.line_input_state->hist_file = hp;
8134 //set_local_var(xasprintf("HISTFILE=%s", ...));
8136 # if ENABLE_FEATURE_SH_HISTFILESIZE
8137 hp = get_local_var_value("HISTFILESIZE");
8138 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8143 install_special_sighandlers();
8145 #elif ENABLE_HUSH_INTERACTIVE
8146 /* No job control compiled in, only prompt/line editing */
8147 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8148 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8149 if (G_interactive_fd < 0) {
8150 /* try to dup to any fd */
8151 G_interactive_fd = dup(STDIN_FILENO);
8152 if (G_interactive_fd < 0)
8154 G_interactive_fd = 0;
8157 if (G_interactive_fd) {
8158 close_on_exec_on(G_interactive_fd);
8160 install_special_sighandlers();
8162 /* We have interactiveness code disabled */
8163 install_special_sighandlers();
8166 * if interactive but not a login shell, sources ~/.bashrc
8167 * (--norc turns this off, --rcfile <file> overrides)
8170 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8171 /* note: ash and hush share this string */
8172 printf("\n\n%s %s\n"
8173 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8176 "hush - the humble shell"
8180 parse_and_run_file(stdin);
8183 hush_exit(G.last_exitcode);
8188 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8189 int msh_main(int argc, char **argv)
8191 //bb_error_msg("msh is deprecated, please use hush instead");
8192 return hush_main(argc, argv);
8200 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8205 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8212 return applet_main_func(argc, argv - argc);
8215 static int FAST_FUNC builtin_test(char **argv)
8217 return run_applet_main(argv, test_main);
8220 static int FAST_FUNC builtin_echo(char **argv)
8222 return run_applet_main(argv, echo_main);
8226 static int FAST_FUNC builtin_printf(char **argv)
8228 return run_applet_main(argv, printf_main);
8232 static char **skip_dash_dash(char **argv)
8235 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8240 static int FAST_FUNC builtin_eval(char **argv)
8242 int rcode = EXIT_SUCCESS;
8244 argv = skip_dash_dash(argv);
8246 char *str = expand_strvec_to_string(argv);
8248 * eval "echo Hi; done" ("done" is syntax error):
8249 * "echo Hi" will not execute too.
8251 parse_and_run_string(str);
8253 rcode = G.last_exitcode;
8258 static int FAST_FUNC builtin_cd(char **argv)
8262 argv = skip_dash_dash(argv);
8264 if (newdir == NULL) {
8265 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8266 * bash says "bash: cd: HOME not set" and does nothing
8269 const char *home = get_local_var_value("HOME");
8270 newdir = home ? home : "/";
8272 if (chdir(newdir)) {
8273 /* Mimic bash message exactly */
8274 bb_perror_msg("cd: %s", newdir);
8275 return EXIT_FAILURE;
8277 /* Read current dir (get_cwd(1) is inside) and set PWD.
8278 * Note: do not enforce exporting. If PWD was unset or unexported,
8279 * set it again, but do not export. bash does the same.
8281 set_pwd_var(/*exp:*/ 0);
8282 return EXIT_SUCCESS;
8285 static int FAST_FUNC builtin_exec(char **argv)
8287 argv = skip_dash_dash(argv);
8288 if (argv[0] == NULL)
8289 return EXIT_SUCCESS; /* bash does this */
8291 /* Careful: we can end up here after [v]fork. Do not restore
8292 * tty pgrp then, only top-level shell process does that */
8293 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8294 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8296 /* TODO: if exec fails, bash does NOT exit! We do.
8297 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8298 * and tcsetpgrp, and this is inherently racy.
8300 execvp_or_die(argv);
8303 static int FAST_FUNC builtin_exit(char **argv)
8305 debug_printf_exec("%s()\n", __func__);
8307 /* interactive bash:
8308 * # trap "echo EEE" EXIT
8311 * There are stopped jobs.
8312 * (if there are _stopped_ jobs, running ones don't count)
8315 * EEE (then bash exits)
8317 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8320 /* note: EXIT trap is run by hush_exit */
8321 argv = skip_dash_dash(argv);
8322 if (argv[0] == NULL)
8323 hush_exit(G.last_exitcode);
8324 /* mimic bash: exit 123abc == exit 255 + error msg */
8325 xfunc_error_retval = 255;
8326 /* bash: exit -2 == exit 254, no error msg */
8327 hush_exit(xatoi(argv[0]) & 0xff);
8330 static void print_escaped(const char *s)
8335 const char *p = strchrnul(s, '\'');
8336 /* print 'xxxx', possibly just '' */
8337 printf("'%.*s'", (int)(p - s), s);
8342 /* s points to '; print "'''...'''" */
8344 do putchar('\''); while (*++s == '\'');
8349 #if !ENABLE_HUSH_LOCAL
8350 #define helper_export_local(argv, exp, lvl) \
8351 helper_export_local(argv, exp)
8353 static void helper_export_local(char **argv, int exp, int lvl)
8357 char *name_end = strchrnul(name, '=');
8359 /* So far we do not check that name is valid (TODO?) */
8361 if (*name_end == '\0') {
8362 struct variable *var, **vpp;
8364 vpp = get_ptr_to_local_var(name, name_end - name);
8365 var = vpp ? *vpp : NULL;
8367 if (exp == -1) { /* unexporting? */
8368 /* export -n NAME (without =VALUE) */
8370 var->flg_export = 0;
8371 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8373 } /* else: export -n NOT_EXISTING_VAR: no-op */
8376 if (exp == 1) { /* exporting? */
8377 /* export NAME (without =VALUE) */
8379 var->flg_export = 1;
8380 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8381 putenv(var->varstr);
8385 /* Exporting non-existing variable.
8386 * bash does not put it in environment,
8387 * but remembers that it is exported,
8388 * and does put it in env when it is set later.
8389 * We just set it to "" and export. */
8390 /* Or, it's "local NAME" (without =VALUE).
8391 * bash sets the value to "". */
8392 name = xasprintf("%s=", name);
8394 /* (Un)exporting/making local NAME=VALUE */
8395 name = xstrdup(name);
8397 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8401 static int FAST_FUNC builtin_export(char **argv)
8403 unsigned opt_unexport;
8405 #if ENABLE_HUSH_EXPORT_N
8406 /* "!": do not abort on errors */
8407 opt_unexport = getopt32(argv, "!n");
8408 if (opt_unexport == (uint32_t)-1)
8409 return EXIT_FAILURE;
8416 if (argv[0] == NULL) {
8423 /* ash emits: export VAR='VAL'
8424 * bash: declare -x VAR="VAL"
8425 * we follow ash example */
8426 const char *s = *e++;
8427 const char *p = strchr(s, '=');
8429 if (!p) /* wtf? take next variable */
8432 printf("export %.*s", (int)(p - s) + 1, s);
8433 print_escaped(p + 1);
8437 /*fflush_all(); - done after each builtin anyway */
8439 return EXIT_SUCCESS;
8442 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8444 return EXIT_SUCCESS;
8447 #if ENABLE_HUSH_LOCAL
8448 static int FAST_FUNC builtin_local(char **argv)
8450 if (G.func_nest_level == 0) {
8451 bb_error_msg("%s: not in a function", argv[0]);
8452 return EXIT_FAILURE; /* bash compat */
8454 helper_export_local(argv, 0, G.func_nest_level);
8455 return EXIT_SUCCESS;
8459 static int FAST_FUNC builtin_trap(char **argv)
8465 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8470 /* No args: print all trapped */
8471 for (i = 0; i < NSIG; ++i) {
8474 print_escaped(G.traps[i]);
8475 /* note: bash adds "SIG", but only if invoked
8476 * as "bash". If called as "sh", or if set -o posix,
8477 * then it prints short signal names.
8478 * We are printing short names: */
8479 printf(" %s\n", get_signame(i));
8482 /*fflush_all(); - done after each builtin anyway */
8483 return EXIT_SUCCESS;
8487 /* If first arg is a number: reset all specified signals */
8488 sig = bb_strtou(*argv, NULL, 10);
8494 sighandler_t handler;
8496 sig = get_signum(*argv++);
8497 if (sig < 0 || sig >= NSIG) {
8499 /* Mimic bash message exactly */
8500 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8505 G.traps[sig] = xstrdup(new_cmd);
8507 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8508 get_signame(sig), sig, G.traps[sig]);
8510 /* There is no signal for 0 (EXIT) */
8515 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8517 /* We are removing trap handler */
8518 handler = pick_sighandler(sig);
8519 install_sighandler(sig, handler);
8524 if (!argv[1]) { /* no second arg */
8525 bb_error_msg("trap: invalid arguments");
8526 return EXIT_FAILURE;
8529 /* First arg is "-": reset all specified to default */
8530 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8531 /* Everything else: set arg as signal handler
8532 * (includes "" case, which ignores signal) */
8533 if (argv[0][0] == '-') {
8534 if (argv[0][1] == '\0') { /* "-" */
8535 /* new_cmd remains NULL: "reset these sigs" */
8538 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8541 /* else: "-something", no special meaning */
8546 goto process_sig_list;
8549 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8550 static int FAST_FUNC builtin_type(char **argv)
8552 int ret = EXIT_SUCCESS;
8558 if (0) {} /* make conditional compile easier below */
8559 /*else if (find_alias(*argv))
8560 type = "an alias";*/
8561 #if ENABLE_HUSH_FUNCTIONS
8562 else if (find_function(*argv))
8563 type = "a function";
8565 else if (find_builtin(*argv))
8566 type = "a shell builtin";
8567 else if ((path = find_in_path(*argv)) != NULL)
8570 bb_error_msg("type: %s: not found", *argv);
8575 printf("%s is %s\n", *argv, type);
8583 /* built-in 'fg' and 'bg' handler */
8584 static int FAST_FUNC builtin_fg_bg(char **argv)
8589 if (!G_interactive_fd)
8590 return EXIT_FAILURE;
8592 /* If they gave us no args, assume they want the last backgrounded task */
8594 for (pi = G.job_list; pi; pi = pi->next) {
8595 if (pi->jobid == G.last_jobid) {
8599 bb_error_msg("%s: no current job", argv[0]);
8600 return EXIT_FAILURE;
8602 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8603 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8604 return EXIT_FAILURE;
8606 for (pi = G.job_list; pi; pi = pi->next) {
8607 if (pi->jobid == jobnum) {
8611 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8612 return EXIT_FAILURE;
8614 /* TODO: bash prints a string representation
8615 * of job being foregrounded (like "sleep 1 | cat") */
8616 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8617 /* Put the job into the foreground. */
8618 tcsetpgrp(G_interactive_fd, pi->pgrp);
8621 /* Restart the processes in the job */
8622 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8623 for (i = 0; i < pi->num_cmds; i++) {
8624 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8626 pi->stopped_cmds = 0;
8628 i = kill(- pi->pgrp, SIGCONT);
8630 if (errno == ESRCH) {
8631 delete_finished_bg_job(pi);
8632 return EXIT_SUCCESS;
8634 bb_perror_msg("kill (SIGCONT)");
8637 if (argv[0][0] == 'f') {
8639 return checkjobs_and_fg_shell(pi);
8641 return EXIT_SUCCESS;
8645 #if ENABLE_HUSH_HELP
8646 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8648 const struct built_in_command *x;
8651 "Built-in commands:\n"
8652 "------------------\n");
8653 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8655 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8658 return EXIT_SUCCESS;
8662 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
8663 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8665 show_history(G.line_input_state);
8666 return EXIT_SUCCESS;
8671 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8674 const char *status_string;
8676 for (job = G.job_list; job; job = job->next) {
8677 if (job->alive_cmds == job->stopped_cmds)
8678 status_string = "Stopped";
8680 status_string = "Running";
8682 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8684 return EXIT_SUCCESS;
8689 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8694 # ifdef M_TRIM_THRESHOLD
8695 /* Optional. Reduces probability of false positives */
8698 /* Crude attempt to find where "free memory" starts,
8699 * sans fragmentation. */
8701 l = (unsigned long)p;
8704 if (l < (unsigned long)p) l = (unsigned long)p;
8707 if (!G.memleak_value)
8708 G.memleak_value = l;
8710 l -= G.memleak_value;
8717 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8722 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8725 return EXIT_SUCCESS;
8728 /* Interruptibility of read builtin in bash
8729 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8731 * Empty trap makes read ignore corresponding signal, for any signal.
8734 * - terminates non-interactive shell;
8735 * - interrupts read in interactive shell;
8736 * if it has non-empty trap:
8737 * - executes trap and returns to command prompt in interactive shell;
8738 * - executes trap and returns to read in non-interactive shell;
8740 * - is ignored (does not interrupt) read in interactive shell;
8741 * - terminates non-interactive shell;
8742 * if it has non-empty trap:
8743 * - executes trap and returns to read;
8745 * - terminates shell (regardless of interactivity);
8746 * if it has non-empty trap:
8747 * - executes trap and returns to read;
8749 static int FAST_FUNC builtin_read(char **argv)
8759 /* "!": do not abort on errors.
8760 * Option string must start with "sr" to match BUILTIN_READ_xxx
8762 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8763 if (read_flags == (uint32_t)-1)
8764 return EXIT_FAILURE;
8766 ifs = get_local_var_value("IFS"); /* can be NULL */
8769 r = shell_builtin_read(set_local_var_from_halves,
8779 if ((uintptr_t)r == 1 && errno == EINTR) {
8780 unsigned sig = check_and_run_traps();
8781 if (sig && sig != SIGINT)
8785 if ((uintptr_t)r > 1) {
8786 bb_error_msg("%s", r);
8787 r = (char*)(uintptr_t)1;
8790 return (uintptr_t)r;
8793 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8794 * built-in 'set' handler
8796 * set [-abCefhmnuvx] [-o option] [argument...]
8797 * set [+abCefhmnuvx] [+o option] [argument...]
8798 * set -- [argument...]
8801 * Implementations shall support the options in both their hyphen and
8802 * plus-sign forms. These options can also be specified as options to sh.
8804 * Write out all variables and their values: set
8805 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8806 * Turn on the -x and -v options: set -xv
8807 * Unset all positional parameters: set --
8808 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8809 * Set the positional parameters to the expansion of x, even if x expands
8810 * with a leading '-' or '+': set -- $x
8812 * So far, we only support "set -- [argument...]" and some of the short names.
8814 static int FAST_FUNC builtin_set(char **argv)
8817 char **pp, **g_argv;
8818 char *arg = *++argv;
8822 for (e = G.top_var; e; e = e->next)
8824 return EXIT_SUCCESS;
8828 if (strcmp(arg, "--") == 0) {
8832 if (arg[0] != '+' && arg[0] != '-')
8834 for (n = 1; arg[n]; ++n) {
8835 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8837 if (arg[n] == 'o' && argv[1])
8840 } while ((arg = *++argv) != NULL);
8841 /* Now argv[0] is 1st argument */
8844 return EXIT_SUCCESS;
8847 /* NB: G.global_argv[0] ($0) is never freed/changed */
8848 g_argv = G.global_argv;
8849 if (G.global_args_malloced) {
8855 G.global_args_malloced = 1;
8856 pp = xzalloc(sizeof(pp[0]) * 2);
8857 pp[0] = g_argv[0]; /* retain $0 */
8860 /* This realloc's G.global_argv */
8861 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8868 return EXIT_SUCCESS;
8870 /* Nothing known, so abort */
8872 bb_error_msg("set: %s: invalid option", arg);
8873 return EXIT_FAILURE;
8876 static int FAST_FUNC builtin_shift(char **argv)
8879 argv = skip_dash_dash(argv);
8883 if (n >= 0 && n < G.global_argc) {
8884 if (G.global_args_malloced) {
8887 free(G.global_argv[m++]);
8890 memmove(&G.global_argv[1], &G.global_argv[n+1],
8891 G.global_argc * sizeof(G.global_argv[0]));
8892 return EXIT_SUCCESS;
8894 return EXIT_FAILURE;
8897 static int FAST_FUNC builtin_source(char **argv)
8899 char *arg_path, *filename;
8902 #if ENABLE_HUSH_FUNCTIONS
8906 argv = skip_dash_dash(argv);
8909 /* bash says: "bash: .: filename argument required" */
8910 return 2; /* bash compat */
8913 if (!strchr(filename, '/')) {
8914 arg_path = find_in_path(filename);
8916 filename = arg_path;
8918 input = fopen_or_warn(filename, "r");
8921 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8922 /* POSIX: non-interactive shell should abort here,
8923 * not merely fail. So far no one complained :)
8925 return EXIT_FAILURE;
8927 close_on_exec_on(fileno(input));
8929 #if ENABLE_HUSH_FUNCTIONS
8930 sv_flg = G.flag_return_in_progress;
8931 /* "we are inside sourced file, ok to use return" */
8932 G.flag_return_in_progress = -1;
8935 save_and_replace_G_args(&sv, argv);
8937 parse_and_run_file(input);
8941 restore_G_args(&sv, argv);
8942 #if ENABLE_HUSH_FUNCTIONS
8943 G.flag_return_in_progress = sv_flg;
8946 return G.last_exitcode;
8949 static int FAST_FUNC builtin_umask(char **argv)
8955 argv = skip_dash_dash(argv);
8957 mode_t old_mask = mask;
8960 rc = bb_parse_mode(argv[0], &mask);
8965 * bash: umask: 'q': invalid symbolic mode operator
8966 * bash: umask: 999: octal number out of range
8968 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8973 printf("%04o\n", (unsigned) mask);
8974 /* fall through and restore mask which we set to 0 */
8978 return !rc; /* rc != 0 - success */
8981 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8982 static int FAST_FUNC builtin_unset(char **argv)
8987 /* "!": do not abort on errors */
8988 /* "+": stop at 1st non-option */
8989 opts = getopt32(argv, "!+vf");
8990 if (opts == (unsigned)-1)
8991 return EXIT_FAILURE;
8993 bb_error_msg("unset: -v and -f are exclusive");
8994 return EXIT_FAILURE;
9000 if (!(opts & 2)) { /* not -f */
9001 if (unset_local_var(*argv)) {
9002 /* unset <nonexistent_var> doesn't fail.
9003 * Error is when one tries to unset RO var.
9004 * Message was printed by unset_local_var. */
9008 #if ENABLE_HUSH_FUNCTIONS
9018 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
9019 static int FAST_FUNC builtin_wait(char **argv)
9021 int ret = EXIT_SUCCESS;
9024 argv = skip_dash_dash(argv);
9025 if (argv[0] == NULL) {
9026 /* Don't care about wait results */
9027 /* Note 1: must wait until there are no more children */
9028 /* Note 2: must be interruptible */
9030 * $ sleep 3 & sleep 6 & wait
9035 * $ sleep 3 & sleep 6 & wait
9039 * ^C <-- after ~4 sec from keyboard
9044 sigset_t oldset, allsigs;
9046 /* waitpid is not interruptible by SA_RESTARTed
9047 * signals which we use. Thus, this ugly dance:
9050 /* Make sure possible SIGCHLD is stored in kernel's
9051 * pending signal mask before we call waitpid.
9052 * Or else we may race with SIGCHLD, lose it,
9053 * and get stuck in sigwaitinfo...
9055 sigfillset(&allsigs);
9056 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9058 if (!sigisemptyset(&G.pending_set)) {
9059 /* Crap! we raced with some signal! */
9064 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9065 if (errno == ECHILD) {
9066 sigprocmask(SIG_SETMASK, &oldset, NULL);
9070 /* Wait for SIGCHLD or any other signal */
9071 //sig = sigwaitinfo(&allsigs, NULL);
9072 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9073 /* Note: sigsuspend invokes signal handler */
9074 sigsuspend(&oldset);
9076 sigprocmask(SIG_SETMASK, &oldset, NULL);
9078 /* So, did we get a signal? */
9080 // raise(sig); /* run handler */
9081 sig = check_and_run_traps();
9082 if (sig /*&& sig != SIGCHLD - always true */) {
9087 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9092 /* This is probably buggy wrt interruptible-ness */
9094 pid_t pid = bb_strtou(*argv, NULL, 10);
9096 /* mimic bash message */
9097 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9098 return EXIT_FAILURE;
9100 if (waitpid(pid, &status, 0) == pid) {
9101 if (WIFSIGNALED(status))
9102 ret = 128 + WTERMSIG(status);
9103 else if (WIFEXITED(status))
9104 ret = WEXITSTATUS(status);
9108 bb_perror_msg("wait %s", *argv);
9117 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9118 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9121 def = bb_strtou(argv[1], NULL, 10);
9122 if (errno || def < def_min || argv[2]) {
9123 bb_error_msg("%s: bad arguments", argv[0]);
9131 #if ENABLE_HUSH_LOOPS
9132 static int FAST_FUNC builtin_break(char **argv)
9135 if (G.depth_of_loop == 0) {
9136 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9137 return EXIT_SUCCESS; /* bash compat */
9139 G.flag_break_continue++; /* BC_BREAK = 1 */
9141 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9142 if (depth == UINT_MAX)
9143 G.flag_break_continue = BC_BREAK;
9144 if (G.depth_of_loop < depth)
9145 G.depth_break_continue = G.depth_of_loop;
9147 return EXIT_SUCCESS;
9150 static int FAST_FUNC builtin_continue(char **argv)
9152 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9153 return builtin_break(argv);
9157 #if ENABLE_HUSH_FUNCTIONS
9158 static int FAST_FUNC builtin_return(char **argv)
9162 if (G.flag_return_in_progress != -1) {
9163 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9164 return EXIT_FAILURE; /* bash compat */
9167 G.flag_return_in_progress = 1;
9170 * out of range: wraps around at 256, does not error out
9171 * non-numeric param:
9172 * f() { false; return qwe; }; f; echo $?
9173 * bash: return: qwe: numeric argument required <== we do this
9174 * 255 <== we also do this
9176 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);