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> */
95 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97 #include "shell_common.h"
100 #if ENABLE_HUSH_RANDOM_SUPPORT
103 # define CLEAR_RANDOM_T(rnd) ((void)0)
106 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
109 /* Not every libc has sighandler_t. Fix it */
110 typedef void (*hush_sighandler_t)(int);
111 #define sighandler_t hush_sighandler_t
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, tilde expansion,
125 //config: &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_BRACE_EXPANSION
135 //config: bool "Brace expansion"
137 //config: depends on HUSH_BASH_COMPAT
139 //config: Enable {abc,def} extension.
141 //config:config HUSH_HELP
142 //config: bool "help builtin"
144 //config: depends on HUSH
146 //config: Enable help builtin in hush. Code size + ~1 kbyte.
148 //config:config HUSH_INTERACTIVE
149 //config: bool "Interactive mode"
151 //config: depends on HUSH
153 //config: Enable interactive mode (prompt and command editing).
154 //config: Without this, hush simply reads and executes commands
155 //config: from stdin just like a shell script from a file.
156 //config: No prompt, no PS1/PS2 magic shell variables.
158 //config:config HUSH_SAVEHISTORY
159 //config: bool "Save command history to .hush_history"
161 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163 //config: Enable history saving in hush.
165 //config:config HUSH_JOB
166 //config: bool "Job control"
168 //config: depends on HUSH_INTERACTIVE
170 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config: command (not entire shell), fg/bg builtins work. Without this option,
172 //config: "cmd &" still works by simply spawning a process and immediately
173 //config: prompting for next command (or executing next command in a script),
174 //config: but no separate process group is formed.
176 //config:config HUSH_TICK
177 //config: bool "Process substitution"
179 //config: depends on HUSH
181 //config: Enable process substitution `command` and $(command) in hush.
183 //config:config HUSH_IF
184 //config: bool "Support if/then/elif/else/fi"
186 //config: depends on HUSH
188 //config: Enable if/then/elif/else/fi in hush.
190 //config:config HUSH_LOOPS
191 //config: bool "Support for, while and until loops"
193 //config: depends on HUSH
195 //config: Enable for, while and until loops in hush.
197 //config:config HUSH_CASE
198 //config: bool "Support case ... esac statement"
200 //config: depends on HUSH
202 //config: Enable case ... esac statement in hush. +400 bytes.
204 //config:config HUSH_FUNCTIONS
205 //config: bool "Support funcname() { commands; } syntax"
207 //config: depends on HUSH
209 //config: Enable support for shell functions in hush. +800 bytes.
211 //config:config HUSH_LOCAL
212 //config: bool "Support local builtin"
214 //config: depends on HUSH_FUNCTIONS
216 //config: Enable support for local variables in functions.
218 //config:config HUSH_RANDOM_SUPPORT
219 //config: bool "Pseudorandom generator and $RANDOM variable"
221 //config: depends on HUSH
223 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
226 //config:config HUSH_EXPORT_N
227 //config: bool "Support 'export -n' option"
229 //config: depends on HUSH
231 //config: export -n unexports variables. It is a bash extension.
233 //config:config HUSH_MODE_X
234 //config: bool "Support 'hush -x' option and 'set -x' command"
236 //config: depends on HUSH
238 //config: This instructs hush to print commands before execution.
239 //config: Adds ~300 bytes.
242 //config: bool "msh (deprecated: aliased to hush)"
244 //config: select HUSH
246 //config: msh is deprecated and will be removed, please migrate to hush.
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257 /* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
262 //usage:#define hush_trivial_usage
263 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage: "Unix shell interpreter"
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage hush_full_usage
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage hush_full_usage
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
288 /* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
298 #define ENABLE_HUSH_DOLLAR_OPS 1
303 # undef USE_FOR_NOMMU
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
310 #include "NUM_APPLETS.h"
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
329 /* Do we support ANY keywords? */
330 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
331 # define HAS_KEYWORDS 1
332 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
333 # define IF_HAS_NO_KEYWORDS(...)
335 # define HAS_KEYWORDS 0
336 # define IF_HAS_KEYWORDS(...)
337 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
340 /* If you comment out one of these below, it will be #defined later
341 * to perform debug printfs to stderr: */
342 #define debug_printf(...) do {} while (0)
343 /* Finer-grained debug switches */
344 #define debug_printf_parse(...) do {} while (0)
345 #define debug_print_tree(a, b) do {} while (0)
346 #define debug_printf_exec(...) do {} while (0)
347 #define debug_printf_env(...) do {} while (0)
348 #define debug_printf_jobs(...) do {} while (0)
349 #define debug_printf_expand(...) do {} while (0)
350 #define debug_printf_varexp(...) do {} while (0)
351 #define debug_printf_glob(...) do {} while (0)
352 #define debug_printf_list(...) do {} while (0)
353 #define debug_printf_subst(...) do {} while (0)
354 #define debug_printf_clean(...) do {} while (0)
356 #define ERR_PTR ((void*)(long)1)
358 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
360 #define _SPECIAL_VARS_STR "_*@$!?#"
361 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
362 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
363 #if ENABLE_HUSH_BASH_COMPAT
364 /* Support / and // replace ops */
365 /* Note that // is stored as \ in "encoded" string representation */
366 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
367 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
368 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
370 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
371 # define VAR_SUBST_OPS "%#:-=+?"
372 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
375 #define SPECIAL_VAR_SYMBOL 3
379 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
381 /* This supports saving pointers malloced in vfork child,
382 * to be freed in the parent.
385 typedef struct nommu_save_t {
387 struct variable *old_vars;
389 char **argv_from_re_execing;
402 #if ENABLE_HUSH_LOOPS
409 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
414 /* three pseudo-keywords support contrived "case" syntax: */
415 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
416 RES_MATCH , /* "word)" */
417 RES_CASE_BODY, /* "this command is inside CASE" */
424 typedef struct o_string {
426 int length; /* position where data is appended */
429 /* At least some part of the string was inside '' or "",
430 * possibly empty one: word"", wo''rd etc. */
431 smallint has_quoted_part;
432 smallint has_empty_slot;
433 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
436 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
438 /* Protect newly added chars against globbing
439 * by prepending \ to *, ?, [, \ */
440 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
443 MAYBE_ASSIGNMENT = 0,
444 DEFINITELY_ASSIGNMENT = 1,
446 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
449 /* Used for initialization: o_string foo = NULL_O_STRING; */
450 #define NULL_O_STRING { NULL }
452 #ifndef debug_printf_parse
453 static const char *const assignment_flag[] = {
455 "DEFINITELY_ASSIGNMENT",
461 typedef struct in_str {
463 /* eof_flag=1: last char in ->p is really an EOF */
464 char eof_flag; /* meaningless if ->p == NULL */
466 #if ENABLE_HUSH_INTERACTIVE
467 smallint promptmode; /* 0: PS1, 1: PS2 */
471 int (*get) (struct in_str *) FAST_FUNC;
472 int (*peek) (struct in_str *) FAST_FUNC;
474 #define i_getch(input) ((input)->get(input))
475 #define i_peek(input) ((input)->peek(input))
477 /* The descrip member of this structure is only used to make
478 * debugging output pretty */
479 static const struct {
481 signed char default_fd;
484 { O_RDONLY, 0, "<" },
485 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
486 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
487 { O_CREAT|O_RDWR, 1, "<>" },
488 { O_RDONLY, 0, "<<" },
489 /* Should not be needed. Bogus default_fd helps in debugging */
490 /* { O_RDONLY, 77, "<<" }, */
493 struct redir_struct {
494 struct redir_struct *next;
495 char *rd_filename; /* filename */
496 int rd_fd; /* fd to redirect */
497 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
499 smallint rd_type; /* (enum redir_type) */
500 /* note: for heredocs, rd_filename contains heredoc delimiter,
501 * and subsequently heredoc itself; and rd_dup is a bitmask:
502 * bit 0: do we need to trim leading tabs?
503 * bit 1: is heredoc quoted (<<'delim' syntax) ?
506 typedef enum redir_type {
508 REDIRECT_OVERWRITE = 1,
511 REDIRECT_HEREDOC = 4,
512 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
515 REDIRFD_SYNTAX_ERR = -2,
516 REDIRFD_TO_FILE = -1,
517 /* otherwise, rd_fd is redirected to rd_dup */
519 HEREDOC_SKIPTABS = 1,
525 pid_t pid; /* 0 if exited */
526 int assignment_cnt; /* how many argv[i] are assignments? */
527 smallint is_stopped; /* is the command currently running? */
528 smallint cmd_type; /* CMD_xxx */
530 #define CMD_SUBSHELL 1
531 #if ENABLE_HUSH_BASH_COMPAT
532 /* used for "[[ EXPR ]]" */
533 # define CMD_SINGLEWORD_NOGLOB 2
535 #if ENABLE_HUSH_FUNCTIONS
536 # define CMD_FUNCDEF 3
539 smalluint cmd_exitcode;
540 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
543 char *group_as_string;
545 #if ENABLE_HUSH_FUNCTIONS
546 struct function *child_func;
547 /* This field is used to prevent a bug here:
548 * while...do f1() {a;}; f1; f1() {b;}; f1; done
549 * When we execute "f1() {a;}" cmd, we create new function and clear
550 * cmd->group, cmd->group_as_string, cmd->argv[0].
551 * When we execute "f1() {b;}", we notice that f1 exists,
552 * and that its "parent cmd" struct is still "alive",
553 * we put those fields back into cmd->xxx
554 * (struct function has ->parent_cmd ptr to facilitate that).
555 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
556 * Without this trick, loop would execute a;b;b;b;...
557 * instead of correct sequence a;b;a;b;...
558 * When command is freed, it severs the link
559 * (sets ->child_func->parent_cmd to NULL).
562 char **argv; /* command name and arguments */
563 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
564 * and on execution these are substituted with their values.
565 * Substitution can make _several_ words out of one argv[n]!
566 * Example: argv[0]=='.^C*^C.' here: echo .$*.
567 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
569 struct redir_struct *redirects; /* I/O redirections */
571 /* Is there anything in this command at all? */
572 #define IS_NULL_CMD(cmd) \
573 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
577 int num_cmds; /* total number of commands in pipe */
578 int alive_cmds; /* number of commands running (not exited) */
579 int stopped_cmds; /* number of commands alive, but stopped */
581 int jobid; /* job number */
582 pid_t pgrp; /* process group ID for the job */
583 char *cmdtext; /* name of job */
585 struct command *cmds; /* array of commands in pipe */
586 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
587 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
588 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
590 typedef enum pipe_style {
596 /* Is there anything in this pipe at all? */
597 #define IS_NULL_PIPE(pi) \
598 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
600 /* This holds pointers to the various results of parsing */
601 struct parse_context {
602 /* linked list of pipes */
603 struct pipe *list_head;
604 /* last pipe (being constructed right now) */
606 /* last command in pipe (being constructed right now) */
607 struct command *command;
608 /* last redirect in command->redirects list */
609 struct redir_struct *pending_redirect;
615 smallint ctx_inverted; /* "! cmd | cmd" */
617 smallint ctx_dsemicolon; /* ";;" seen */
619 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
621 /* group we are enclosed in:
622 * example: "if pipe1; pipe2; then pipe3; fi"
623 * when we see "if" or "then", we malloc and copy current context,
624 * and make ->stack point to it. then we parse pipeN.
625 * when closing "then" / fi" / whatever is found,
626 * we move list_head into ->stack->command->group,
627 * copy ->stack into current context, and delete ->stack.
628 * (parsing of { list } and ( list ) doesn't use this method)
630 struct parse_context *stack;
634 /* On program start, environ points to initial environment.
635 * putenv adds new pointers into it, unsetenv removes them.
636 * Neither of these (de)allocates the strings.
637 * setenv allocates new strings in malloc space and does putenv,
638 * and thus setenv is unusable (leaky) for shell's purposes */
639 #define setenv(...) setenv_is_leaky_dont_use()
641 struct variable *next;
642 char *varstr; /* points to "name=" portion */
643 #if ENABLE_HUSH_LOCAL
644 unsigned func_nest_level;
646 int max_len; /* if > 0, name is part of initial env; else name is malloced */
647 smallint flg_export; /* putenv should be done on this var */
648 smallint flg_read_only;
656 #if ENABLE_HUSH_FUNCTIONS
658 struct function *next;
660 struct command *parent_cmd;
663 char *body_as_string;
669 /* set -/+o OPT support. (TODO: make it optional)
670 * bash supports the following opts:
681 * interactive-comments on
699 static const char o_opt_strings[] ALIGN1 =
702 #if ENABLE_HUSH_MODE_X
709 #if ENABLE_HUSH_MODE_X
716 /* "Globals" within this file */
717 /* Sorted roughly by size (smaller offsets == smaller code) */
719 /* interactive_fd != 0 means we are an interactive shell.
720 * If we are, then saved_tty_pgrp can also be != 0, meaning
721 * that controlling tty is available. With saved_tty_pgrp == 0,
722 * job control still works, but terminal signals
723 * (^C, ^Z, ^Y, ^\) won't work at all, and background
724 * process groups can only be created with "cmd &".
725 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
726 * to give tty to the foreground process group,
727 * and will take it back when the group is stopped (^Z)
730 #if ENABLE_HUSH_INTERACTIVE
731 /* 'interactive_fd' is a fd# open to ctty, if we have one
732 * _AND_ if we decided to act interactively */
736 # define G_interactive_fd (G.interactive_fd)
738 # define G_interactive_fd 0
740 #if ENABLE_FEATURE_EDITING
741 line_input_t *line_input_state;
746 #if ENABLE_HUSH_RANDOM_SUPPORT
752 pid_t saved_tty_pgrp;
753 struct pipe *job_list;
754 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
756 # define G_saved_tty_pgrp 0
758 char o_opt[NUM_OPT_O];
759 #if ENABLE_HUSH_MODE_X
760 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
764 smallint flag_SIGINT;
765 #if ENABLE_HUSH_LOOPS
766 smallint flag_break_continue;
768 #if ENABLE_HUSH_FUNCTIONS
769 /* 0: outside of a function (or sourced file)
770 * -1: inside of a function, ok to use return builtin
771 * 1: return is invoked, skip all till end of func
773 smallint flag_return_in_progress;
775 smallint exiting; /* used to prevent EXIT trap recursion */
776 /* These four support $?, $#, and $1 */
777 smalluint last_exitcode;
778 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
779 smalluint global_args_malloced;
780 /* how many non-NULL argv's we have. NB: $# + 1 */
784 char *argv0_for_re_execing;
786 #if ENABLE_HUSH_LOOPS
787 unsigned depth_break_continue;
788 unsigned depth_of_loop;
792 struct variable *top_var;
793 char **expanded_assignments;
794 #if ENABLE_HUSH_FUNCTIONS
795 struct function *top_func;
796 # if ENABLE_HUSH_LOCAL
797 struct variable **shadowed_vars_pp;
798 unsigned func_nest_level;
801 /* Signal and trap handling */
803 unsigned count_SIGCHLD;
804 unsigned handled_SIGCHLD;
805 smallint we_have_children;
807 /* Which signals have non-DFL handler (even with no traps set)?
808 * Set at the start to:
809 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
810 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
811 * The rest is cleared right before execv syscalls.
812 * Other than these two times, never modified.
814 unsigned special_sig_mask;
816 unsigned fatal_sig_mask;
817 # define G_fatal_sig_mask G.fatal_sig_mask
819 # define G_fatal_sig_mask 0
821 char **traps; /* char *traps[NSIG] */
822 sigset_t pending_set;
824 unsigned long memleak_value;
828 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
830 #define G (*ptr_to_globals)
831 /* Not #defining name to G.name - this quickly gets unwieldy
832 * (too many defines). Also, I actually prefer to see when a variable
833 * is global, thus "G." prefix is a useful hint */
834 #define INIT_G() do { \
835 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
836 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
837 sigfillset(&G.sa.sa_mask); \
838 G.sa.sa_flags = SA_RESTART; \
842 /* Function prototypes for builtins */
843 static int builtin_cd(char **argv) FAST_FUNC;
844 static int builtin_echo(char **argv) FAST_FUNC;
845 static int builtin_eval(char **argv) FAST_FUNC;
846 static int builtin_exec(char **argv) FAST_FUNC;
847 static int builtin_exit(char **argv) FAST_FUNC;
848 static int builtin_export(char **argv) FAST_FUNC;
850 static int builtin_fg_bg(char **argv) FAST_FUNC;
851 static int builtin_jobs(char **argv) FAST_FUNC;
854 static int builtin_help(char **argv) FAST_FUNC;
856 #if ENABLE_HUSH_LOCAL
857 static int builtin_local(char **argv) FAST_FUNC;
860 static int builtin_memleak(char **argv) FAST_FUNC;
863 static int builtin_printf(char **argv) FAST_FUNC;
865 static int builtin_pwd(char **argv) FAST_FUNC;
866 static int builtin_read(char **argv) FAST_FUNC;
867 static int builtin_set(char **argv) FAST_FUNC;
868 static int builtin_shift(char **argv) FAST_FUNC;
869 static int builtin_source(char **argv) FAST_FUNC;
870 static int builtin_test(char **argv) FAST_FUNC;
871 static int builtin_trap(char **argv) FAST_FUNC;
872 static int builtin_type(char **argv) FAST_FUNC;
873 static int builtin_true(char **argv) FAST_FUNC;
874 static int builtin_umask(char **argv) FAST_FUNC;
875 static int builtin_unset(char **argv) FAST_FUNC;
876 static int builtin_wait(char **argv) FAST_FUNC;
877 #if ENABLE_HUSH_LOOPS
878 static int builtin_break(char **argv) FAST_FUNC;
879 static int builtin_continue(char **argv) FAST_FUNC;
881 #if ENABLE_HUSH_FUNCTIONS
882 static int builtin_return(char **argv) FAST_FUNC;
885 /* Table of built-in functions. They can be forked or not, depending on
886 * context: within pipes, they fork. As simple commands, they do not.
887 * When used in non-forking context, they can change global variables
888 * in the parent shell process. If forked, of course they cannot.
889 * For example, 'unset foo | whatever' will parse and run, but foo will
890 * still be set at the end. */
891 struct built_in_command {
893 int (*b_function)(char **argv) FAST_FUNC;
896 # define BLTIN(cmd, func, help) { cmd, func, help }
898 # define BLTIN(cmd, func, help) { cmd, func }
902 static const struct built_in_command bltins1[] = {
903 BLTIN("." , builtin_source , "Run commands in a file"),
904 BLTIN(":" , builtin_true , NULL),
906 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
908 #if ENABLE_HUSH_LOOPS
909 BLTIN("break" , builtin_break , "Exit from a loop"),
911 BLTIN("cd" , builtin_cd , "Change directory"),
912 #if ENABLE_HUSH_LOOPS
913 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
915 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
916 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
917 BLTIN("exit" , builtin_exit , "Exit"),
918 BLTIN("export" , builtin_export , "Set environment variables"),
920 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
923 BLTIN("help" , builtin_help , NULL),
926 BLTIN("jobs" , builtin_jobs , "List jobs"),
928 #if ENABLE_HUSH_LOCAL
929 BLTIN("local" , builtin_local , "Set local variables"),
932 BLTIN("memleak" , builtin_memleak , NULL),
934 BLTIN("read" , builtin_read , "Input into variable"),
935 #if ENABLE_HUSH_FUNCTIONS
936 BLTIN("return" , builtin_return , "Return from a function"),
938 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
939 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
940 #if ENABLE_HUSH_BASH_COMPAT
941 BLTIN("source" , builtin_source , "Run commands in a file"),
943 BLTIN("trap" , builtin_trap , "Trap signals"),
944 BLTIN("type" , builtin_type , "Show command type"),
945 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
946 BLTIN("umask" , builtin_umask , "Set file creation mask"),
947 BLTIN("unset" , builtin_unset , "Unset variables"),
948 BLTIN("wait" , builtin_wait , "Wait for process"),
950 /* For now, echo and test are unconditionally enabled.
951 * Maybe make it configurable? */
952 static const struct built_in_command bltins2[] = {
953 BLTIN("[" , builtin_test , NULL),
954 BLTIN("echo" , builtin_echo , NULL),
956 BLTIN("printf" , builtin_printf , NULL),
958 BLTIN("pwd" , builtin_pwd , NULL),
959 BLTIN("test" , builtin_test , NULL),
966 /* prevent disasters with G.debug_indent < 0 */
967 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
968 # define debug_enter() (G.debug_indent++)
969 # define debug_leave() (G.debug_indent--)
971 # define indent() ((void)0)
972 # define debug_enter() ((void)0)
973 # define debug_leave() ((void)0)
977 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
980 #ifndef debug_printf_parse
981 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
984 #ifndef debug_printf_exec
985 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
988 #ifndef debug_printf_env
989 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
992 #ifndef debug_printf_jobs
993 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
994 # define DEBUG_JOBS 1
996 # define DEBUG_JOBS 0
999 #ifndef debug_printf_expand
1000 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1001 # define DEBUG_EXPAND 1
1003 # define DEBUG_EXPAND 0
1006 #ifndef debug_printf_varexp
1007 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1010 #ifndef debug_printf_glob
1011 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1012 # define DEBUG_GLOB 1
1014 # define DEBUG_GLOB 0
1017 #ifndef debug_printf_list
1018 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1021 #ifndef debug_printf_subst
1022 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1025 #ifndef debug_printf_clean
1026 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1027 # define DEBUG_CLEAN 1
1029 # define DEBUG_CLEAN 0
1033 static void debug_print_strings(const char *prefix, char **vv)
1036 fdprintf(2, "%s:\n", prefix);
1038 fdprintf(2, " '%s'\n", *vv++);
1041 # define debug_print_strings(prefix, vv) ((void)0)
1045 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1048 static void *xxmalloc(int lineno, size_t size)
1050 void *ptr = xmalloc((size + 0xff) & ~0xff);
1051 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1054 static void *xxrealloc(int lineno, void *ptr, size_t size)
1056 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1057 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1060 static char *xxstrdup(int lineno, const char *str)
1062 char *ptr = xstrdup(str);
1063 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1066 static void xxfree(void *ptr)
1068 fdprintf(2, "free %p\n", ptr);
1071 # define xmalloc(s) xxmalloc(__LINE__, s)
1072 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1073 # define xstrdup(s) xxstrdup(__LINE__, s)
1074 # define free(p) xxfree(p)
1078 /* Syntax and runtime errors. They always abort scripts.
1079 * In interactive use they usually discard unparsed and/or unexecuted commands
1080 * and return to the prompt.
1081 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1084 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1085 # define syntax_error(lineno, msg) syntax_error(msg)
1086 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1087 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1088 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1089 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1092 static void die_if_script(unsigned lineno, const char *fmt, ...)
1097 bb_error_msg("hush.c:%u", lineno);
1100 bb_verror_msg(fmt, p, NULL);
1102 if (!G_interactive_fd)
1106 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1109 bb_error_msg("syntax error: %s", msg);
1111 bb_error_msg("syntax error");
1114 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1116 bb_error_msg("syntax error at '%s'", msg);
1119 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1121 bb_error_msg("syntax error: unterminated %s", s);
1124 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1126 char msg[2] = { ch, '\0' };
1127 syntax_error_unterm_str(lineno, msg);
1130 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1135 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1139 # undef die_if_script
1140 # undef syntax_error
1141 # undef syntax_error_at
1142 # undef syntax_error_unterm_ch
1143 # undef syntax_error_unterm_str
1144 # undef syntax_error_unexpected_ch
1146 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1147 # define syntax_error(msg) syntax_error(__LINE__, msg)
1148 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1149 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1150 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1151 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1155 #if ENABLE_HUSH_INTERACTIVE
1156 static void cmdedit_update_prompt(void);
1158 # define cmdedit_update_prompt() ((void)0)
1162 /* Utility functions
1164 /* Replace each \x with x in place, return ptr past NUL. */
1165 static char *unbackslash(char *src)
1167 char *dst = src = strchrnul(src, '\\');
1171 if ((*dst++ = *src++) == '\0')
1177 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1198 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1199 v[count1 + count2] = NULL;
1202 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1206 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1208 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1209 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1212 #define add_strings_to_strings(strings, add, need_to_dup) \
1213 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1216 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1217 static char **add_string_to_strings(char **strings, char *add)
1222 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1225 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1227 char **ptr = add_string_to_strings(strings, add);
1228 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1231 #define add_string_to_strings(strings, add) \
1232 xx_add_string_to_strings(__LINE__, strings, add)
1235 static void free_strings(char **strings)
1250 /* Helpers for setting new $n and restoring them back
1252 typedef struct save_arg_t {
1256 smallint sv_g_malloced;
1259 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1263 sv->sv_argv0 = argv[0];
1264 sv->sv_g_argv = G.global_argv;
1265 sv->sv_g_argc = G.global_argc;
1266 sv->sv_g_malloced = G.global_args_malloced;
1268 argv[0] = G.global_argv[0]; /* retain $0 */
1269 G.global_argv = argv;
1270 G.global_args_malloced = 0;
1278 static void restore_G_args(save_arg_t *sv, char **argv)
1282 if (G.global_args_malloced) {
1283 /* someone ran "set -- arg1 arg2 ...", undo */
1285 while (*++pp) /* note: does not free $0 */
1287 free(G.global_argv);
1289 argv[0] = sv->sv_argv0;
1290 G.global_argv = sv->sv_g_argv;
1291 G.global_argc = sv->sv_g_argc;
1292 G.global_args_malloced = sv->sv_g_malloced;
1296 /* Basic theory of signal handling in shell
1297 * ========================================
1298 * This does not describe what hush does, rather, it is current understanding
1299 * what it _should_ do. If it doesn't, it's a bug.
1300 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1302 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1303 * is finished or backgrounded. It is the same in interactive and
1304 * non-interactive shells, and is the same regardless of whether
1305 * a user trap handler is installed or a shell special one is in effect.
1306 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1307 * backgrounds (i.e. stops) or kills all members of currently running
1310 * Wait builtin in interruptible by signals for which user trap is set
1311 * or by SIGINT in interactive shell.
1313 * Trap handlers will execute even within trap handlers. (right?)
1315 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1316 * except for handlers set to '' (empty string).
1318 * If job control is off, backgrounded commands ("cmd &")
1319 * have SIGINT, SIGQUIT set to SIG_IGN.
1321 * Commands which are run in command substitution ("`cmd`")
1322 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1324 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1325 * by the shell from its parent.
1327 * Signals which differ from SIG_DFL action
1328 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1331 * SIGTERM (interactive): ignore
1332 * SIGHUP (interactive):
1333 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1334 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1335 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1336 * that all pipe members are stopped. Try this in bash:
1337 * while :; do :; done - ^Z does not background it
1338 * (while :; do :; done) - ^Z backgrounds it
1339 * SIGINT (interactive): wait for last pipe, ignore the rest
1340 * of the command line, show prompt. NB: ^C does not send SIGINT
1341 * to interactive shell while shell is waiting for a pipe,
1342 * since shell is bg'ed (is not in foreground process group).
1343 * Example 1: this waits 5 sec, but does not execute ls:
1344 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1345 * Example 2: this does not wait and does not execute ls:
1346 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1347 * Example 3: this does not wait 5 sec, but executes ls:
1348 * "sleep 5; ls -l" + press ^C
1349 * Example 4: this does not wait and does not execute ls:
1350 * "sleep 5 & wait; ls -l" + press ^C
1352 * (What happens to signals which are IGN on shell start?)
1353 * (What happens with signal mask on shell start?)
1355 * Old implementation
1356 * ==================
1357 * We use in-kernel pending signal mask to determine which signals were sent.
1358 * We block all signals which we don't want to take action immediately,
1359 * i.e. we block all signals which need to have special handling as described
1360 * above, and all signals which have traps set.
1361 * After each pipe execution, we extract any pending signals via sigtimedwait()
1364 * unsigned special_sig_mask: a mask of such "special" signals
1365 * sigset_t blocked_set: current blocked signal set
1368 * clear bit in blocked_set unless it is also in special_sig_mask
1369 * "trap 'cmd' SIGxxx":
1370 * set bit in blocked_set (even if 'cmd' is '')
1371 * after [v]fork, if we plan to be a shell:
1372 * unblock signals with special interactive handling
1373 * (child shell is not interactive),
1374 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1375 * after [v]fork, if we plan to exec:
1376 * POSIX says fork clears pending signal mask in child - no need to clear it.
1377 * Restore blocked signal set to one inherited by shell just prior to exec.
1379 * Note: as a result, we do not use signal handlers much. The only uses
1380 * are to count SIGCHLDs
1381 * and to restore tty pgrp on signal-induced exit.
1384 * Standard says "When a subshell is entered, traps that are not being ignored
1385 * are set to the default actions". bash interprets it so that traps which
1386 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1388 * Problem: the above approach makes it unwieldy to catch signals while
1389 * we are in read builtin, of while we read commands from stdin:
1390 * masked signals are not visible!
1392 * New implementation
1393 * ==================
1394 * We record each signal we are interested in by installing signal handler
1395 * for them - a bit like emulating kernel pending signal mask in userspace.
1396 * We are interested in: signals which need to have special handling
1397 * as described above, and all signals which have traps set.
1398 * Signals are rocorded in pending_set.
1399 * After each pipe execution, we extract any pending signals
1402 * unsigned special_sig_mask: a mask of shell-special signals.
1403 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1404 * char *traps[sig] if trap for sig is set (even if it's '').
1405 * sigset_t pending_set: set of sigs we received.
1408 * if sig is in special_sig_mask, set handler back to:
1409 * record_pending_signo, or to IGN if it's a tty stop signal
1410 * if sig is in fatal_sig_mask, set handler back to sigexit.
1411 * else: set handler back to SIG_DFL
1412 * "trap 'cmd' SIGxxx":
1413 * set handler to record_pending_signo.
1415 * set handler to SIG_IGN.
1416 * after [v]fork, if we plan to be a shell:
1417 * set signals with special interactive handling to SIG_DFL
1418 * (because child shell is not interactive),
1419 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1420 * after [v]fork, if we plan to exec:
1421 * POSIX says fork clears pending signal mask in child - no need to clear it.
1423 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1424 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1427 * Standard says "When a subshell is entered, traps that are not being ignored
1428 * are set to the default actions". bash interprets it so that traps which
1429 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1432 SPECIAL_INTERACTIVE_SIGS = 0
1437 SPECIAL_JOBSTOP_SIGS = 0
1446 static void record_pending_signo(int sig)
1448 sigaddset(&G.pending_set, sig);
1449 #if ENABLE_HUSH_FAST
1450 if (sig == SIGCHLD) {
1452 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1457 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1459 struct sigaction old_sa;
1461 /* We could use signal() to install handlers... almost:
1462 * except that we need to mask ALL signals while handlers run.
1463 * I saw signal nesting in strace, race window isn't small.
1464 * SA_RESTART is also needed, but in Linux, signal()
1465 * sets SA_RESTART too.
1467 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1468 /* sigfillset(&G.sa.sa_mask); - already done */
1469 /* G.sa.sa_flags = SA_RESTART; - already done */
1470 G.sa.sa_handler = handler;
1471 sigaction(sig, &G.sa, &old_sa);
1472 return old_sa.sa_handler;
1477 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1478 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1479 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1480 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1482 /* Restores tty foreground process group, and exits.
1483 * May be called as signal handler for fatal signal
1484 * (will resend signal to itself, producing correct exit state)
1485 * or called directly with -EXITCODE.
1486 * We also call it if xfunc is exiting. */
1487 static void sigexit(int sig) NORETURN;
1488 static void sigexit(int sig)
1490 /* Careful: we can end up here after [v]fork. Do not restore
1491 * tty pgrp then, only top-level shell process does that */
1492 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1493 /* Disable all signals: job control, SIGPIPE, etc.
1494 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1496 sigprocmask_allsigs(SIG_BLOCK);
1497 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1500 /* Not a signal, just exit */
1504 kill_myself_with_sig(sig); /* does not return */
1508 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1509 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1513 static sighandler_t pick_sighandler(unsigned sig)
1515 sighandler_t handler = SIG_DFL;
1516 if (sig < sizeof(unsigned)*8) {
1517 unsigned sigmask = (1 << sig);
1521 if (G_fatal_sig_mask & sigmask)
1525 /* sig has special handling? */
1526 if (G.special_sig_mask & sigmask) {
1527 handler = record_pending_signo;
1528 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1529 * in order to ignore them: they will be raised
1530 * in an endless loop when we try to do some
1531 * terminal ioctls! We do have to _ignore_ these.
1533 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1540 /* Restores tty foreground process group, and exits. */
1541 static void hush_exit(int exitcode) NORETURN;
1542 static void hush_exit(int exitcode)
1544 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1545 save_history(G.line_input_state);
1549 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1551 /* argv[0] is unused */
1552 argv[1] = G.traps[0];
1554 G.exiting = 1; /* prevent EXIT trap recursion */
1555 /* Note: G.traps[0] is not cleared!
1556 * "trap" will still show it, if executed
1561 #if ENABLE_FEATURE_CLEAN_UP
1563 struct variable *cur_var;
1564 if (G.cwd != bb_msg_unknown)
1566 cur_var = G.top_var;
1568 struct variable *tmp = cur_var;
1569 if (!cur_var->max_len)
1570 free(cur_var->varstr);
1571 cur_var = cur_var->next;
1579 sigexit(- (exitcode & 0xff));
1586 //TODO: return a mask of ALL handled sigs?
1587 static int check_and_run_traps(void)
1594 if (sigisemptyset(&G.pending_set))
1599 if (sigismember(&G.pending_set, sig)) {
1600 sigdelset(&G.pending_set, sig);
1603 } while (sig < NSIG);
1606 if (G.traps && G.traps[sig]) {
1607 if (G.traps[sig][0]) {
1608 /* We have user-defined handler */
1609 smalluint save_rcode;
1611 /* argv[0] is unused */
1612 argv[1] = G.traps[sig];
1614 save_rcode = G.last_exitcode;
1616 G.last_exitcode = save_rcode;
1618 } /* else: "" trap, ignoring signal */
1621 /* not a trap: special action */
1624 /* Builtin was ^C'ed, make it look prettier: */
1632 /* bash is observed to signal whole process groups,
1633 * not individual processes */
1634 for (job = G.job_list; job; job = job->next) {
1637 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1638 if (kill(- job->pgrp, SIGHUP) == 0)
1639 kill(- job->pgrp, SIGCONT);
1644 #if ENABLE_HUSH_FAST
1647 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1649 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1650 * This simplifies wait builtin a bit.
1654 default: /* ignored: */
1655 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1657 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1658 * Example: wait is not interrupted by TERM
1659 * in interactive shell, because TERM is ignored.
1668 static const char *get_cwd(int force)
1670 if (force || G.cwd == NULL) {
1671 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1672 * we must not try to free(bb_msg_unknown) */
1673 if (G.cwd == bb_msg_unknown)
1675 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1677 G.cwd = bb_msg_unknown;
1684 * Shell and environment variable support
1686 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1688 struct variable **pp;
1689 struct variable *cur;
1692 while ((cur = *pp) != NULL) {
1693 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1700 static const char* FAST_FUNC get_local_var_value(const char *name)
1702 struct variable **vpp;
1703 unsigned len = strlen(name);
1705 if (G.expanded_assignments) {
1706 char **cpp = G.expanded_assignments;
1709 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1710 return cp + len + 1;
1715 vpp = get_ptr_to_local_var(name, len);
1717 return (*vpp)->varstr + len + 1;
1719 if (strcmp(name, "PPID") == 0)
1720 return utoa(G.root_ppid);
1721 // bash compat: UID? EUID?
1722 #if ENABLE_HUSH_RANDOM_SUPPORT
1723 if (strcmp(name, "RANDOM") == 0)
1724 return utoa(next_random(&G.random_gen));
1729 /* str holds "NAME=VAL" and is expected to be malloced.
1730 * We take ownership of it.
1732 * 0: do not change export flag
1733 * (if creating new variable, flag will be 0)
1734 * 1: set export flag and putenv the variable
1735 * -1: clear export flag and unsetenv the variable
1736 * flg_read_only is set only when we handle -R var=val
1738 #if !BB_MMU && ENABLE_HUSH_LOCAL
1739 /* all params are used */
1740 #elif BB_MMU && ENABLE_HUSH_LOCAL
1741 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1742 set_local_var(str, flg_export, local_lvl)
1743 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1744 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1745 set_local_var(str, flg_export)
1746 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1747 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1748 set_local_var(str, flg_export, flg_read_only)
1750 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1752 struct variable **var_pp;
1753 struct variable *cur;
1757 eq_sign = strchr(str, '=');
1758 if (!eq_sign) { /* not expected to ever happen? */
1763 name_len = eq_sign - str + 1; /* including '=' */
1764 var_pp = &G.top_var;
1765 while ((cur = *var_pp) != NULL) {
1766 if (strncmp(cur->varstr, str, name_len) != 0) {
1767 var_pp = &cur->next;
1770 /* We found an existing var with this name */
1771 if (cur->flg_read_only) {
1775 bb_error_msg("%s: readonly variable", str);
1779 if (flg_export == -1) { // "&& cur->flg_export" ?
1780 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1785 #if ENABLE_HUSH_LOCAL
1786 if (cur->func_nest_level < local_lvl) {
1787 /* New variable is declared as local,
1788 * and existing one is global, or local
1789 * from enclosing function.
1790 * Remove and save old one: */
1791 *var_pp = cur->next;
1792 cur->next = *G.shadowed_vars_pp;
1793 *G.shadowed_vars_pp = cur;
1794 /* bash 3.2.33(1) and exported vars:
1796 * # f() { local z=a; env | grep ^z; }
1802 if (cur->flg_export)
1807 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1812 if (cur->max_len != 0) {
1813 if (cur->max_len >= strlen(str)) {
1814 /* This one is from startup env, reuse space */
1815 strcpy(cur->varstr, str);
1819 /* max_len == 0 signifies "malloced" var, which we can
1820 * (and has to) free */
1824 goto set_str_and_exp;
1827 /* Not found - create new variable struct */
1828 cur = xzalloc(sizeof(*cur));
1829 #if ENABLE_HUSH_LOCAL
1830 cur->func_nest_level = local_lvl;
1832 cur->next = *var_pp;
1838 cur->flg_read_only = flg_read_only;
1841 if (flg_export == 1)
1842 cur->flg_export = 1;
1843 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1844 cmdedit_update_prompt();
1845 if (cur->flg_export) {
1846 if (flg_export == -1) {
1847 cur->flg_export = 0;
1848 /* unsetenv was already done */
1850 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1851 return putenv(cur->varstr);
1857 /* Used at startup and after each cd */
1858 static void set_pwd_var(int exp)
1860 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1861 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1864 static int unset_local_var_len(const char *name, int name_len)
1866 struct variable *cur;
1867 struct variable **var_pp;
1870 return EXIT_SUCCESS;
1871 var_pp = &G.top_var;
1872 while ((cur = *var_pp) != NULL) {
1873 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1874 if (cur->flg_read_only) {
1875 bb_error_msg("%s: readonly variable", name);
1876 return EXIT_FAILURE;
1878 *var_pp = cur->next;
1879 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1880 bb_unsetenv(cur->varstr);
1881 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1882 cmdedit_update_prompt();
1886 return EXIT_SUCCESS;
1888 var_pp = &cur->next;
1890 return EXIT_SUCCESS;
1893 static int unset_local_var(const char *name)
1895 return unset_local_var_len(name, strlen(name));
1898 static void unset_vars(char **strings)
1906 const char *eq = strchrnul(*v, '=');
1907 unset_local_var_len(*v, (int)(eq - *v));
1913 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1915 char *var = xasprintf("%s=%s", name, val);
1916 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1921 * Helpers for "var1=val1 var2=val2 cmd" feature
1923 static void add_vars(struct variable *var)
1925 struct variable *next;
1929 var->next = G.top_var;
1931 if (var->flg_export) {
1932 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1933 putenv(var->varstr);
1935 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1941 static struct variable *set_vars_and_save_old(char **strings)
1944 struct variable *old = NULL;
1950 struct variable *var_p;
1951 struct variable **var_pp;
1954 eq = strchr(*s, '=');
1956 var_pp = get_ptr_to_local_var(*s, eq - *s);
1958 /* Remove variable from global linked list */
1960 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1961 *var_pp = var_p->next;
1962 /* Add it to returned list */
1966 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1977 static int FAST_FUNC static_get(struct in_str *i)
1988 static int FAST_FUNC static_peek(struct in_str *i)
1993 #if ENABLE_HUSH_INTERACTIVE
1995 static void cmdedit_update_prompt(void)
1997 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1998 G.PS1 = get_local_var_value("PS1");
2001 G.PS2 = get_local_var_value("PS2");
2009 static const char *setup_prompt_string(int promptmode)
2011 const char *prompt_str;
2012 debug_printf("setup_prompt_string %d ", promptmode);
2013 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2014 /* Set up the prompt */
2015 if (promptmode == 0) { /* PS1 */
2017 /* bash uses $PWD value, even if it is set by user.
2018 * It uses current dir only if PWD is unset.
2019 * We always use current dir. */
2020 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2025 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2026 debug_printf("result '%s'\n", prompt_str);
2030 static void get_user_input(struct in_str *i)
2033 const char *prompt_str;
2035 prompt_str = setup_prompt_string(i->promptmode);
2036 # if ENABLE_FEATURE_EDITING
2037 /* Enable command line editing only while a command line
2038 * is actually being read */
2040 /* Unicode support should be activated even if LANG is set
2041 * _during_ shell execution, not only if it was set when
2042 * shell was started. Therefore, re-check LANG every time:
2044 reinit_unicode(get_local_var_value("LANG"));
2047 /* buglet: SIGINT will not make new prompt to appear _at once_,
2048 * only after <Enter>. (^C will work) */
2049 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2050 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2051 check_and_run_traps();
2052 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2053 i->eof_flag = (r < 0);
2054 if (i->eof_flag) { /* EOF/error detected */
2055 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2056 G.user_input_buf[1] = '\0';
2061 if (i->last_char == '\0' || i->last_char == '\n') {
2062 /* Why check_and_run_traps here? Try this interactively:
2063 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2064 * $ <[enter], repeatedly...>
2065 * Without check_and_run_traps, handler never runs.
2067 check_and_run_traps();
2068 fputs(prompt_str, stdout);
2071 G.user_input_buf[0] = r = fgetc(i->file);
2072 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2073 } while (G.flag_SIGINT);
2074 i->eof_flag = (r == EOF);
2076 i->p = G.user_input_buf;
2079 #endif /* INTERACTIVE */
2081 /* This is the magic location that prints prompts
2082 * and gets data back from the user */
2083 static int FAST_FUNC file_get(struct in_str *i)
2087 /* If there is data waiting, eat it up */
2088 if (i->p && *i->p) {
2089 #if ENABLE_HUSH_INTERACTIVE
2093 if (i->eof_flag && !*i->p)
2095 /* note: ch is never NUL */
2097 /* need to double check i->file because we might be doing something
2098 * more complicated by now, like sourcing or substituting. */
2099 #if ENABLE_HUSH_INTERACTIVE
2100 if (G_interactive_fd && i->file == stdin) {
2103 } while (!*i->p); /* need non-empty line */
2104 i->promptmode = 1; /* PS2 */
2108 do ch = fgetc(i->file); while (ch == '\0');
2110 debug_printf("file_get: got '%c' %d\n", ch, ch);
2115 /* All callers guarantee this routine will never
2116 * be used right after a newline, so prompting is not needed.
2118 static int FAST_FUNC file_peek(struct in_str *i)
2121 if (i->p && *i->p) {
2122 if (i->eof_flag && !i->p[1])
2125 /* note: ch is never NUL */
2127 do ch = fgetc(i->file); while (ch == '\0');
2128 i->eof_flag = (ch == EOF);
2129 i->peek_buf[0] = ch;
2130 i->peek_buf[1] = '\0';
2132 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2136 static void setup_file_in_str(struct in_str *i, FILE *f)
2138 memset(i, 0, sizeof(*i));
2139 i->peek = file_peek;
2141 /* i->promptmode = 0; - PS1 (memset did it) */
2146 static void setup_string_in_str(struct in_str *i, const char *s)
2148 memset(i, 0, sizeof(*i));
2149 i->peek = static_peek;
2150 i->get = static_get;
2151 /* i->promptmode = 0; - PS1 (memset did it) */
2153 /* i->eof_flag = 0; */
2160 #define B_CHUNK (32 * sizeof(char*))
2162 static void o_reset_to_empty_unquoted(o_string *o)
2165 o->has_quoted_part = 0;
2170 static void o_free(o_string *o)
2173 memset(o, 0, sizeof(*o));
2176 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2181 static void o_grow_by(o_string *o, int len)
2183 if (o->length + len > o->maxlen) {
2184 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2185 o->data = xrealloc(o->data, 1 + o->maxlen);
2189 static void o_addchr(o_string *o, int ch)
2191 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2193 o->data[o->length] = ch;
2195 o->data[o->length] = '\0';
2198 static void o_addblock(o_string *o, const char *str, int len)
2201 memcpy(&o->data[o->length], str, len);
2203 o->data[o->length] = '\0';
2206 static void o_addstr(o_string *o, const char *str)
2208 o_addblock(o, str, strlen(str));
2212 static void nommu_addchr(o_string *o, int ch)
2218 # define nommu_addchr(o, str) ((void)0)
2221 static void o_addstr_with_NUL(o_string *o, const char *str)
2223 o_addblock(o, str, strlen(str) + 1);
2227 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2228 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2229 * Apparently, on unquoted $v bash still does globbing
2230 * ("v='*.txt'; echo $v" prints all .txt files),
2231 * but NOT brace expansion! Thus, there should be TWO independent
2232 * quoting mechanisms on $v expansion side: one protects
2233 * $v from brace expansion, and other additionally protects "$v" against globbing.
2234 * We have only second one.
2237 #if ENABLE_HUSH_BRACE_EXPANSION
2238 # define MAYBE_BRACES "{}"
2240 # define MAYBE_BRACES ""
2243 /* My analysis of quoting semantics tells me that state information
2244 * is associated with a destination, not a source.
2246 static void o_addqchr(o_string *o, int ch)
2249 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2254 o->data[o->length] = '\\';
2257 o->data[o->length] = ch;
2259 o->data[o->length] = '\0';
2262 static void o_addQchr(o_string *o, int ch)
2265 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2266 && strchr("*?[\\" MAYBE_BRACES, ch)
2269 o->data[o->length] = '\\';
2273 o->data[o->length] = ch;
2275 o->data[o->length] = '\0';
2278 static void o_addqblock(o_string *o, const char *str, int len)
2283 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2284 if (ordinary_cnt > len) /* paranoia */
2286 o_addblock(o, str, ordinary_cnt);
2287 if (ordinary_cnt == len)
2288 return; /* NUL is already added by o_addblock */
2289 str += ordinary_cnt;
2290 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2294 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2296 o->data[o->length] = '\\';
2300 o->data[o->length] = ch;
2303 o->data[o->length] = '\0';
2306 static void o_addQblock(o_string *o, const char *str, int len)
2308 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2309 o_addblock(o, str, len);
2312 o_addqblock(o, str, len);
2315 static void o_addQstr(o_string *o, const char *str)
2317 o_addQblock(o, str, strlen(str));
2320 /* A special kind of o_string for $VAR and `cmd` expansion.
2321 * It contains char* list[] at the beginning, which is grown in 16 element
2322 * increments. Actual string data starts at the next multiple of 16 * (char*).
2323 * list[i] contains an INDEX (int!) into this string data.
2324 * It means that if list[] needs to grow, data needs to be moved higher up
2325 * but list[i]'s need not be modified.
2326 * NB: remembering how many list[i]'s you have there is crucial.
2327 * o_finalize_list() operation post-processes this structure - calculates
2328 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2330 #if DEBUG_EXPAND || DEBUG_GLOB
2331 static void debug_print_list(const char *prefix, o_string *o, int n)
2333 char **list = (char**)o->data;
2334 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2338 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2339 prefix, list, n, string_start, o->length, o->maxlen,
2340 !!(o->o_expflags & EXP_FLAG_GLOB),
2342 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2345 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2346 o->data + (int)(uintptr_t)list[i] + string_start,
2347 o->data + (int)(uintptr_t)list[i] + string_start);
2351 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2353 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2357 # define debug_print_list(prefix, o, n) ((void)0)
2360 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2361 * in list[n] so that it points past last stored byte so far.
2362 * It returns n+1. */
2363 static int o_save_ptr_helper(o_string *o, int n)
2365 char **list = (char**)o->data;
2369 if (!o->has_empty_slot) {
2370 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2371 string_len = o->length - string_start;
2372 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2373 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2374 /* list[n] points to string_start, make space for 16 more pointers */
2375 o->maxlen += 0x10 * sizeof(list[0]);
2376 o->data = xrealloc(o->data, o->maxlen + 1);
2377 list = (char**)o->data;
2378 memmove(list + n + 0x10, list + n, string_len);
2379 o->length += 0x10 * sizeof(list[0]);
2381 debug_printf_list("list[%d]=%d string_start=%d\n",
2382 n, string_len, string_start);
2385 /* We have empty slot at list[n], reuse without growth */
2386 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2387 string_len = o->length - string_start;
2388 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2389 n, string_len, string_start);
2390 o->has_empty_slot = 0;
2392 o->has_quoted_part = 0;
2393 list[n] = (char*)(uintptr_t)string_len;
2397 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2398 static int o_get_last_ptr(o_string *o, int n)
2400 char **list = (char**)o->data;
2401 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2403 return ((int)(uintptr_t)list[n-1]) + string_start;
2406 #if ENABLE_HUSH_BRACE_EXPANSION
2407 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2408 * first, it processes even {a} (no commas), second,
2409 * I didn't manage to make it return strings when they don't match
2410 * existing files. Need to re-implement it.
2414 static int glob_needed(const char *s)
2423 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2429 /* Return pointer to next closing brace or to comma */
2430 static const char *next_brace_sub(const char *cp)
2434 while (*cp != '\0') {
2441 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2447 return *cp != '\0' ? cp : NULL;
2449 /* Recursive brace globber. Note: may garble pattern[]. */
2450 static int glob_brace(char *pattern, o_string *o, int n)
2452 char *new_pattern_buf;
2459 debug_printf_glob("glob_brace('%s')\n", pattern);
2465 if (*begin == '{') {
2466 /* Find the first sub-pattern and at the same time
2467 * find the rest after the closing brace */
2468 next = next_brace_sub(begin);
2470 /* An illegal expression */
2474 /* "{abc}" with no commas - illegal
2475 * brace expr, disregard and skip it */
2481 if (*begin == '\\' && begin[1] != '\0')
2485 debug_printf_glob("begin:%s\n", begin);
2486 debug_printf_glob("next:%s\n", next);
2488 /* Now find the end of the whole brace expression */
2490 while (*rest != '}') {
2491 rest = next_brace_sub(rest);
2493 /* An illegal expression */
2496 debug_printf_glob("rest:%s\n", rest);
2498 rest_len = strlen(++rest) + 1;
2500 /* We are sure the brace expression is well-formed */
2502 /* Allocate working buffer large enough for our work */
2503 new_pattern_buf = xmalloc(strlen(pattern));
2505 /* We have a brace expression. BEGIN points to the opening {,
2506 * NEXT points past the terminator of the first element, and REST
2507 * points past the final }. We will accumulate result names from
2508 * recursive runs for each brace alternative in the buffer using
2513 /* Construct the new glob expression */
2516 mempcpy(new_pattern_buf,
2517 /* We know the prefix for all sub-patterns */
2518 pattern, begin - pattern),
2522 /* Note: glob_brace() may garble new_pattern_buf[].
2523 * That's why we re-copy prefix every time (1st memcpy above).
2525 n = glob_brace(new_pattern_buf, o, n);
2527 /* We saw the last entry */
2531 next = next_brace_sub(next);
2533 free(new_pattern_buf);
2541 memset(&globdata, 0, sizeof(globdata));
2542 gr = glob(pattern, 0, NULL, &globdata);
2543 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2545 if (gr == GLOB_NOMATCH) {
2546 globfree(&globdata);
2547 /* NB: garbles parameter */
2548 unbackslash(pattern);
2549 o_addstr_with_NUL(o, pattern);
2550 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2551 return o_save_ptr_helper(o, n);
2553 if (gr == GLOB_NOSPACE)
2554 bb_error_msg_and_die(bb_msg_memory_exhausted);
2555 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2556 * but we didn't specify it. Paranoia again. */
2557 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2559 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2560 char **argv = globdata.gl_pathv;
2562 o_addstr_with_NUL(o, *argv);
2563 n = o_save_ptr_helper(o, n);
2569 globfree(&globdata);
2573 /* Performs globbing on last list[],
2574 * saving each result as a new list[].
2576 static int perform_glob(o_string *o, int n)
2578 char *pattern, *copy;
2580 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2582 return o_save_ptr_helper(o, n);
2583 pattern = o->data + o_get_last_ptr(o, n);
2584 debug_printf_glob("glob pattern '%s'\n", pattern);
2585 if (!glob_needed(pattern)) {
2586 /* unbackslash last string in o in place, fix length */
2587 o->length = unbackslash(pattern) - o->data;
2588 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2589 return o_save_ptr_helper(o, n);
2592 copy = xstrdup(pattern);
2593 /* "forget" pattern in o */
2594 o->length = pattern - o->data;
2595 n = glob_brace(copy, o, n);
2598 debug_print_list("perform_glob returning", o, n);
2602 #else /* !HUSH_BRACE_EXPANSION */
2605 static int glob_needed(const char *s)
2614 if (*s == '*' || *s == '[' || *s == '?')
2620 /* Performs globbing on last list[],
2621 * saving each result as a new list[].
2623 static int perform_glob(o_string *o, int n)
2629 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2631 return o_save_ptr_helper(o, n);
2632 pattern = o->data + o_get_last_ptr(o, n);
2633 debug_printf_glob("glob pattern '%s'\n", pattern);
2634 if (!glob_needed(pattern)) {
2636 /* unbackslash last string in o in place, fix length */
2637 o->length = unbackslash(pattern) - o->data;
2638 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2639 return o_save_ptr_helper(o, n);
2642 memset(&globdata, 0, sizeof(globdata));
2643 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2644 * If we glob "*.\*" and don't find anything, we need
2645 * to fall back to using literal "*.*", but GLOB_NOCHECK
2646 * will return "*.\*"!
2648 gr = glob(pattern, 0, NULL, &globdata);
2649 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2651 if (gr == GLOB_NOMATCH) {
2652 globfree(&globdata);
2655 if (gr == GLOB_NOSPACE)
2656 bb_error_msg_and_die(bb_msg_memory_exhausted);
2657 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2658 * but we didn't specify it. Paranoia again. */
2659 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2661 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2662 char **argv = globdata.gl_pathv;
2663 /* "forget" pattern in o */
2664 o->length = pattern - o->data;
2666 o_addstr_with_NUL(o, *argv);
2667 n = o_save_ptr_helper(o, n);
2673 globfree(&globdata);
2675 debug_print_list("perform_glob returning", o, n);
2679 #endif /* !HUSH_BRACE_EXPANSION */
2681 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2682 * Otherwise, just finish current list[] and start new */
2683 static int o_save_ptr(o_string *o, int n)
2685 if (o->o_expflags & EXP_FLAG_GLOB) {
2686 /* If o->has_empty_slot, list[n] was already globbed
2687 * (if it was requested back then when it was filled)
2688 * so don't do that again! */
2689 if (!o->has_empty_slot)
2690 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2692 return o_save_ptr_helper(o, n);
2695 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2696 static char **o_finalize_list(o_string *o, int n)
2701 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2703 debug_print_list("finalized", o, n);
2704 debug_printf_expand("finalized n:%d\n", n);
2705 list = (char**)o->data;
2706 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2710 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2715 static void free_pipe_list(struct pipe *pi);
2717 /* Returns pi->next - next pipe in the list */
2718 static struct pipe *free_pipe(struct pipe *pi)
2723 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2724 for (i = 0; i < pi->num_cmds; i++) {
2725 struct command *command;
2726 struct redir_struct *r, *rnext;
2728 command = &pi->cmds[i];
2729 debug_printf_clean(" command %d:\n", i);
2730 if (command->argv) {
2734 for (a = 0, p = command->argv; *p; a++, p++) {
2735 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2738 free_strings(command->argv);
2739 //command->argv = NULL;
2741 /* not "else if": on syntax error, we may have both! */
2742 if (command->group) {
2743 debug_printf_clean(" begin group (cmd_type:%d)\n",
2745 free_pipe_list(command->group);
2746 debug_printf_clean(" end group\n");
2747 //command->group = NULL;
2749 /* else is crucial here.
2750 * If group != NULL, child_func is meaningless */
2751 #if ENABLE_HUSH_FUNCTIONS
2752 else if (command->child_func) {
2753 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2754 command->child_func->parent_cmd = NULL;
2758 free(command->group_as_string);
2759 //command->group_as_string = NULL;
2761 for (r = command->redirects; r; r = rnext) {
2762 debug_printf_clean(" redirect %d%s",
2763 r->rd_fd, redir_table[r->rd_type].descrip);
2764 /* guard against the case >$FOO, where foo is unset or blank */
2765 if (r->rd_filename) {
2766 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2767 free(r->rd_filename);
2768 //r->rd_filename = NULL;
2770 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2774 //command->redirects = NULL;
2776 free(pi->cmds); /* children are an array, they get freed all at once */
2780 //pi->cmdtext = NULL;
2788 static void free_pipe_list(struct pipe *pi)
2792 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2794 debug_printf_clean("pipe followup code %d\n", pi->followup);
2800 /*** Parsing routines ***/
2802 #ifndef debug_print_tree
2803 static void debug_print_tree(struct pipe *pi, int lvl)
2805 static const char *const PIPE[] = {
2811 static const char *RES[] = {
2812 [RES_NONE ] = "NONE" ,
2815 [RES_THEN ] = "THEN" ,
2816 [RES_ELIF ] = "ELIF" ,
2817 [RES_ELSE ] = "ELSE" ,
2820 # if ENABLE_HUSH_LOOPS
2821 [RES_FOR ] = "FOR" ,
2822 [RES_WHILE] = "WHILE",
2823 [RES_UNTIL] = "UNTIL",
2825 [RES_DONE ] = "DONE" ,
2827 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2830 # if ENABLE_HUSH_CASE
2831 [RES_CASE ] = "CASE" ,
2832 [RES_CASE_IN ] = "CASE_IN" ,
2833 [RES_MATCH] = "MATCH",
2834 [RES_CASE_BODY] = "CASE_BODY",
2835 [RES_ESAC ] = "ESAC" ,
2837 [RES_XXXX ] = "XXXX" ,
2838 [RES_SNTX ] = "SNTX" ,
2840 static const char *const CMDTYPE[] = {
2844 # if ENABLE_HUSH_FUNCTIONS
2853 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2854 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2856 while (prn < pi->num_cmds) {
2857 struct command *command = &pi->cmds[prn];
2858 char **argv = command->argv;
2860 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2862 command->assignment_cnt);
2863 if (command->group) {
2864 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2865 CMDTYPE[command->cmd_type],
2868 , " group_as_string:", command->group_as_string
2873 debug_print_tree(command->group, lvl+1);
2877 if (argv) while (*argv) {
2878 fdprintf(2, " '%s'", *argv);
2888 #endif /* debug_print_tree */
2890 static struct pipe *new_pipe(void)
2893 pi = xzalloc(sizeof(struct pipe));
2894 /*pi->followup = 0; - deliberately invalid value */
2895 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2899 /* Command (member of a pipe) is complete, or we start a new pipe
2900 * if ctx->command is NULL.
2901 * No errors possible here.
2903 static int done_command(struct parse_context *ctx)
2905 /* The command is really already in the pipe structure, so
2906 * advance the pipe counter and make a new, null command. */
2907 struct pipe *pi = ctx->pipe;
2908 struct command *command = ctx->command;
2911 if (IS_NULL_CMD(command)) {
2912 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2916 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2917 //debug_print_tree(ctx->list_head, 20);
2919 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2922 /* Only real trickiness here is that the uncommitted
2923 * command structure is not counted in pi->num_cmds. */
2924 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2925 ctx->command = command = &pi->cmds[pi->num_cmds];
2927 memset(command, 0, sizeof(*command));
2928 return pi->num_cmds; /* used only for 0/nonzero check */
2931 static void done_pipe(struct parse_context *ctx, pipe_style type)
2935 debug_printf_parse("done_pipe entered, followup %d\n", type);
2936 /* Close previous command */
2937 not_null = done_command(ctx);
2938 ctx->pipe->followup = type;
2940 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2941 ctx->ctx_inverted = 0;
2942 ctx->pipe->res_word = ctx->ctx_res_w;
2945 /* Without this check, even just <enter> on command line generates
2946 * tree of three NOPs (!). Which is harmless but annoying.
2947 * IOW: it is safe to do it unconditionally. */
2950 || ctx->ctx_res_w == RES_FI
2952 #if ENABLE_HUSH_LOOPS
2953 || ctx->ctx_res_w == RES_DONE
2954 || ctx->ctx_res_w == RES_FOR
2955 || ctx->ctx_res_w == RES_IN
2957 #if ENABLE_HUSH_CASE
2958 || ctx->ctx_res_w == RES_ESAC
2962 debug_printf_parse("done_pipe: adding new pipe: "
2963 "not_null:%d ctx->ctx_res_w:%d\n",
2964 not_null, ctx->ctx_res_w);
2966 ctx->pipe->next = new_p;
2968 /* RES_THEN, RES_DO etc are "sticky" -
2969 * they remain set for pipes inside if/while.
2970 * This is used to control execution.
2971 * RES_FOR and RES_IN are NOT sticky (needed to support
2972 * cases where variable or value happens to match a keyword):
2974 #if ENABLE_HUSH_LOOPS
2975 if (ctx->ctx_res_w == RES_FOR
2976 || ctx->ctx_res_w == RES_IN)
2977 ctx->ctx_res_w = RES_NONE;
2979 #if ENABLE_HUSH_CASE
2980 if (ctx->ctx_res_w == RES_MATCH)
2981 ctx->ctx_res_w = RES_CASE_BODY;
2982 if (ctx->ctx_res_w == RES_CASE)
2983 ctx->ctx_res_w = RES_CASE_IN;
2985 ctx->command = NULL; /* trick done_command below */
2986 /* Create the memory for command, roughly:
2987 * ctx->pipe->cmds = new struct command;
2988 * ctx->command = &ctx->pipe->cmds[0];
2991 //debug_print_tree(ctx->list_head, 10);
2993 debug_printf_parse("done_pipe return\n");
2996 static void initialize_context(struct parse_context *ctx)
2998 memset(ctx, 0, sizeof(*ctx));
2999 ctx->pipe = ctx->list_head = new_pipe();
3000 /* Create the memory for command, roughly:
3001 * ctx->pipe->cmds = new struct command;
3002 * ctx->command = &ctx->pipe->cmds[0];
3007 /* If a reserved word is found and processed, parse context is modified
3008 * and 1 is returned.
3011 struct reserved_combo {
3014 unsigned char assignment_flag;
3018 FLAG_END = (1 << RES_NONE ),
3020 FLAG_IF = (1 << RES_IF ),
3021 FLAG_THEN = (1 << RES_THEN ),
3022 FLAG_ELIF = (1 << RES_ELIF ),
3023 FLAG_ELSE = (1 << RES_ELSE ),
3024 FLAG_FI = (1 << RES_FI ),
3026 # if ENABLE_HUSH_LOOPS
3027 FLAG_FOR = (1 << RES_FOR ),
3028 FLAG_WHILE = (1 << RES_WHILE),
3029 FLAG_UNTIL = (1 << RES_UNTIL),
3030 FLAG_DO = (1 << RES_DO ),
3031 FLAG_DONE = (1 << RES_DONE ),
3032 FLAG_IN = (1 << RES_IN ),
3034 # if ENABLE_HUSH_CASE
3035 FLAG_MATCH = (1 << RES_MATCH),
3036 FLAG_ESAC = (1 << RES_ESAC ),
3038 FLAG_START = (1 << RES_XXXX ),
3041 static const struct reserved_combo* match_reserved_word(o_string *word)
3043 /* Mostly a list of accepted follow-up reserved words.
3044 * FLAG_END means we are done with the sequence, and are ready
3045 * to turn the compound list into a command.
3046 * FLAG_START means the word must start a new compound list.
3048 static const struct reserved_combo reserved_list[] = {
3050 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3051 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3052 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3053 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3054 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3055 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3057 # if ENABLE_HUSH_LOOPS
3058 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3059 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3060 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3061 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3062 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3063 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3065 # if ENABLE_HUSH_CASE
3066 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3067 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3070 const struct reserved_combo *r;
3072 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3073 if (strcmp(word->data, r->literal) == 0)
3078 /* Return 0: not a keyword, 1: keyword
3080 static int reserved_word(o_string *word, struct parse_context *ctx)
3082 # if ENABLE_HUSH_CASE
3083 static const struct reserved_combo reserved_match = {
3084 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3087 const struct reserved_combo *r;
3089 if (word->has_quoted_part)
3091 r = match_reserved_word(word);
3095 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3096 # if ENABLE_HUSH_CASE
3097 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3098 /* "case word IN ..." - IN part starts first MATCH part */
3099 r = &reserved_match;
3102 if (r->flag == 0) { /* '!' */
3103 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3104 syntax_error("! ! command");
3105 ctx->ctx_res_w = RES_SNTX;
3107 ctx->ctx_inverted = 1;
3110 if (r->flag & FLAG_START) {
3111 struct parse_context *old;
3113 old = xmalloc(sizeof(*old));
3114 debug_printf_parse("push stack %p\n", old);
3115 *old = *ctx; /* physical copy */
3116 initialize_context(ctx);
3118 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3119 syntax_error_at(word->data);
3120 ctx->ctx_res_w = RES_SNTX;
3123 /* "{...} fi" is ok. "{...} if" is not
3125 * if { echo foo; } then { echo bar; } fi */
3126 if (ctx->command->group)
3127 done_pipe(ctx, PIPE_SEQ);
3130 ctx->ctx_res_w = r->res;
3131 ctx->old_flag = r->flag;
3132 word->o_assignment = r->assignment_flag;
3133 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3135 if (ctx->old_flag & FLAG_END) {
3136 struct parse_context *old;
3138 done_pipe(ctx, PIPE_SEQ);
3139 debug_printf_parse("pop stack %p\n", ctx->stack);
3141 old->command->group = ctx->list_head;
3142 old->command->cmd_type = CMD_NORMAL;
3144 o_addstr(&old->as_string, ctx->as_string.data);
3145 o_free_unsafe(&ctx->as_string);
3146 old->command->group_as_string = xstrdup(old->as_string.data);
3147 debug_printf_parse("pop, remembering as:'%s'\n",
3148 old->command->group_as_string);
3150 *ctx = *old; /* physical copy */
3155 #endif /* HAS_KEYWORDS */
3157 /* Word is complete, look at it and update parsing context.
3158 * Normal return is 0. Syntax errors return 1.
3159 * Note: on return, word is reset, but not o_free'd!
3161 static int done_word(o_string *word, struct parse_context *ctx)
3163 struct command *command = ctx->command;
3165 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3166 if (word->length == 0 && !word->has_quoted_part) {
3167 debug_printf_parse("done_word return 0: true null, ignored\n");
3171 if (ctx->pending_redirect) {
3172 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3173 * only if run as "bash", not "sh" */
3174 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3176 * ...the word that follows the redirection operator
3177 * shall be subjected to tilde expansion, parameter expansion,
3178 * command substitution, arithmetic expansion, and quote
3179 * removal. Pathname expansion shall not be performed
3180 * on the word by a non-interactive shell; an interactive
3181 * shell may perform it, but shall do so only when
3182 * the expansion would result in one word."
3184 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3185 /* Cater for >\file case:
3186 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3187 * Same with heredocs:
3188 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3190 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3191 unbackslash(ctx->pending_redirect->rd_filename);
3192 /* Is it <<"HEREDOC"? */
3193 if (word->has_quoted_part) {
3194 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3197 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3198 ctx->pending_redirect = NULL;
3201 # if ENABLE_HUSH_CASE
3202 if (ctx->ctx_dsemicolon
3203 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3205 /* already done when ctx_dsemicolon was set to 1: */
3206 /* ctx->ctx_res_w = RES_MATCH; */
3207 ctx->ctx_dsemicolon = 0;
3210 if (!command->argv /* if it's the first word... */
3211 # if ENABLE_HUSH_LOOPS
3212 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3213 && ctx->ctx_res_w != RES_IN
3215 # if ENABLE_HUSH_CASE
3216 && ctx->ctx_res_w != RES_CASE
3219 int reserved = reserved_word(word, ctx);
3220 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3222 o_reset_to_empty_unquoted(word);
3223 debug_printf_parse("done_word return %d\n",
3224 (ctx->ctx_res_w == RES_SNTX));
3225 return (ctx->ctx_res_w == RES_SNTX);
3227 # if ENABLE_HUSH_BASH_COMPAT
3228 if (strcmp(word->data, "[[") == 0) {
3229 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3235 if (command->group) {
3236 /* "{ echo foo; } echo bar" - bad */
3237 syntax_error_at(word->data);
3238 debug_printf_parse("done_word return 1: syntax error, "
3239 "groups and arglists don't mix\n");
3243 /* If this word wasn't an assignment, next ones definitely
3244 * can't be assignments. Even if they look like ones. */
3245 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3246 && word->o_assignment != WORD_IS_KEYWORD
3248 word->o_assignment = NOT_ASSIGNMENT;
3250 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3251 command->assignment_cnt++;
3252 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3254 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3255 word->o_assignment = MAYBE_ASSIGNMENT;
3257 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3259 if (word->has_quoted_part
3260 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3261 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3262 /* (otherwise it's known to be not empty and is already safe) */
3264 /* exclude "$@" - it can expand to no word despite "" */
3265 char *p = word->data;
3266 while (p[0] == SPECIAL_VAR_SYMBOL
3267 && (p[1] & 0x7f) == '@'
3268 && p[2] == SPECIAL_VAR_SYMBOL
3273 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3274 debug_print_strings("word appended to argv", command->argv);
3277 #if ENABLE_HUSH_LOOPS
3278 if (ctx->ctx_res_w == RES_FOR) {
3279 if (word->has_quoted_part
3280 || !is_well_formed_var_name(command->argv[0], '\0')
3282 /* bash says just "not a valid identifier" */
3283 syntax_error("not a valid identifier in for");
3286 /* Force FOR to have just one word (variable name) */
3287 /* NB: basically, this makes hush see "for v in ..."
3288 * syntax as if it is "for v; in ...". FOR and IN become
3289 * two pipe structs in parse tree. */
3290 done_pipe(ctx, PIPE_SEQ);
3293 #if ENABLE_HUSH_CASE
3294 /* Force CASE to have just one word */
3295 if (ctx->ctx_res_w == RES_CASE) {
3296 done_pipe(ctx, PIPE_SEQ);
3300 o_reset_to_empty_unquoted(word);
3302 debug_printf_parse("done_word return 0\n");
3307 /* Peek ahead in the input to find out if we have a "&n" construct,
3308 * as in "2>&1", that represents duplicating a file descriptor.
3310 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3311 * REDIRFD_SYNTAX_ERR if syntax error,
3312 * REDIRFD_TO_FILE if no & was seen,
3313 * or the number found.
3316 #define parse_redir_right_fd(as_string, input) \
3317 parse_redir_right_fd(input)
3319 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3325 return REDIRFD_TO_FILE;
3327 ch = i_getch(input); /* get the & */
3328 nommu_addchr(as_string, ch);
3331 ch = i_getch(input);
3332 nommu_addchr(as_string, ch);
3333 return REDIRFD_CLOSE;
3337 while (ch != EOF && isdigit(ch)) {
3338 d = d*10 + (ch-'0');
3340 ch = i_getch(input);
3341 nommu_addchr(as_string, ch);
3346 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3348 bb_error_msg("ambiguous redirect");
3349 return REDIRFD_SYNTAX_ERR;
3352 /* Return code is 0 normal, 1 if a syntax error is detected
3354 static int parse_redirect(struct parse_context *ctx,
3357 struct in_str *input)
3359 struct command *command = ctx->command;
3360 struct redir_struct *redir;
3361 struct redir_struct **redirp;
3364 dup_num = REDIRFD_TO_FILE;
3365 if (style != REDIRECT_HEREDOC) {
3366 /* Check for a '>&1' type redirect */
3367 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3368 if (dup_num == REDIRFD_SYNTAX_ERR)
3371 int ch = i_peek(input);
3372 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3373 if (dup_num) { /* <<-... */
3374 ch = i_getch(input);
3375 nommu_addchr(&ctx->as_string, ch);
3380 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3381 int ch = i_peek(input);
3383 /* >|FILE redirect ("clobbering" >).
3384 * Since we do not support "set -o noclobber" yet,
3385 * >| and > are the same for now. Just eat |.
3387 ch = i_getch(input);
3388 nommu_addchr(&ctx->as_string, ch);
3392 /* Create a new redir_struct and append it to the linked list */
3393 redirp = &command->redirects;
3394 while ((redir = *redirp) != NULL) {
3395 redirp = &(redir->next);
3397 *redirp = redir = xzalloc(sizeof(*redir));
3398 /* redir->next = NULL; */
3399 /* redir->rd_filename = NULL; */
3400 redir->rd_type = style;
3401 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3403 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3404 redir_table[style].descrip);
3406 redir->rd_dup = dup_num;
3407 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3408 /* Erik had a check here that the file descriptor in question
3409 * is legit; I postpone that to "run time"
3410 * A "-" representation of "close me" shows up as a -3 here */
3411 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3412 redir->rd_fd, redir->rd_dup);
3414 /* Set ctx->pending_redirect, so we know what to do at the
3415 * end of the next parsed word. */
3416 ctx->pending_redirect = redir;
3421 /* If a redirect is immediately preceded by a number, that number is
3422 * supposed to tell which file descriptor to redirect. This routine
3423 * looks for such preceding numbers. In an ideal world this routine
3424 * needs to handle all the following classes of redirects...
3425 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3426 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3427 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3428 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3430 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3432 * ... If n is quoted, the number shall not be recognized as part of
3433 * the redirection expression. For example:
3435 * writes the character 2 into file a"
3436 * We are getting it right by setting ->has_quoted_part on any \<char>
3438 * A -1 return means no valid number was found,
3439 * the caller should use the appropriate default for this redirection.
3441 static int redirect_opt_num(o_string *o)
3445 if (o->data == NULL)
3447 num = bb_strtou(o->data, NULL, 10);
3448 if (errno || num < 0)
3450 o_reset_to_empty_unquoted(o);
3455 #define fetch_till_str(as_string, input, word, skip_tabs) \
3456 fetch_till_str(input, word, skip_tabs)
3458 static char *fetch_till_str(o_string *as_string,
3459 struct in_str *input,
3463 o_string heredoc = NULL_O_STRING;
3465 int prev = 0; /* not \ */
3471 ch = i_getch(input);
3473 nommu_addchr(as_string, ch);
3474 if ((ch == '\n' || ch == EOF)
3475 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3477 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3478 heredoc.data[past_EOL] = '\0';
3479 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3480 return heredoc.data;
3482 while (ch == '\n') {
3483 o_addchr(&heredoc, ch);
3486 past_EOL = heredoc.length;
3488 ch = i_getch(input);
3490 nommu_addchr(as_string, ch);
3491 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3495 o_free_unsafe(&heredoc);
3498 o_addchr(&heredoc, ch);
3499 nommu_addchr(as_string, ch);
3500 if (prev == '\\' && ch == '\\')
3501 /* Correctly handle foo\\<eol> (not a line cont.) */
3502 prev = 0; /* not \ */
3508 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3509 * and load them all. There should be exactly heredoc_cnt of them.
3511 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3513 struct pipe *pi = ctx->list_head;
3515 while (pi && heredoc_cnt) {
3517 struct command *cmd = pi->cmds;
3519 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3521 cmd->argv ? cmd->argv[0] : "NONE");
3522 for (i = 0; i < pi->num_cmds; i++) {
3523 struct redir_struct *redir = cmd->redirects;
3525 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3526 i, cmd->argv ? cmd->argv[0] : "NONE");
3528 if (redir->rd_type == REDIRECT_HEREDOC) {
3531 redir->rd_type = REDIRECT_HEREDOC2;
3532 /* redir->rd_dup is (ab)used to indicate <<- */
3533 p = fetch_till_str(&ctx->as_string, input,
3534 redir->rd_filename, redir->rd_dup);
3536 syntax_error("unexpected EOF in here document");
3539 free(redir->rd_filename);
3540 redir->rd_filename = p;
3543 redir = redir->next;
3550 /* Should be 0. If it isn't, it's a parse error */
3552 bb_error_msg_and_die("heredoc BUG 2");
3558 static int run_list(struct pipe *pi);
3560 #define parse_stream(pstring, input, end_trigger) \
3561 parse_stream(input, end_trigger)
3563 static struct pipe *parse_stream(char **pstring,
3564 struct in_str *input,
3568 #if !ENABLE_HUSH_FUNCTIONS
3569 #define parse_group(dest, ctx, input, ch) \
3570 parse_group(ctx, input, ch)
3572 static int parse_group(o_string *dest, struct parse_context *ctx,
3573 struct in_str *input, int ch)
3575 /* dest contains characters seen prior to ( or {.
3576 * Typically it's empty, but for function defs,
3577 * it contains function name (without '()'). */
3578 struct pipe *pipe_list;
3580 struct command *command = ctx->command;
3582 debug_printf_parse("parse_group entered\n");
3583 #if ENABLE_HUSH_FUNCTIONS
3584 if (ch == '(' && !dest->has_quoted_part) {
3586 if (done_word(dest, ctx))
3589 goto skip; /* (... */
3590 if (command->argv[1]) { /* word word ... (... */
3591 syntax_error_unexpected_ch('(');
3594 /* it is "word(..." or "word (..." */
3596 ch = i_getch(input);
3597 while (ch == ' ' || ch == '\t');
3599 syntax_error_unexpected_ch(ch);
3602 nommu_addchr(&ctx->as_string, ch);
3604 ch = i_getch(input);
3605 while (ch == ' ' || ch == '\t' || ch == '\n');
3607 syntax_error_unexpected_ch(ch);
3610 nommu_addchr(&ctx->as_string, ch);
3611 command->cmd_type = CMD_FUNCDEF;
3616 #if 0 /* Prevented by caller */
3617 if (command->argv /* word [word]{... */
3618 || dest->length /* word{... */
3619 || dest->has_quoted_part /* ""{... */
3622 debug_printf_parse("parse_group return 1: "
3623 "syntax error, groups and arglists don't mix\n");
3628 #if ENABLE_HUSH_FUNCTIONS
3634 command->cmd_type = CMD_SUBSHELL;
3636 /* bash does not allow "{echo...", requires whitespace */
3637 ch = i_getch(input);
3638 if (ch != ' ' && ch != '\t' && ch != '\n') {
3639 syntax_error_unexpected_ch(ch);
3642 nommu_addchr(&ctx->as_string, ch);
3647 # define as_string NULL
3649 char *as_string = NULL;
3651 pipe_list = parse_stream(&as_string, input, endch);
3654 o_addstr(&ctx->as_string, as_string);
3656 /* empty ()/{} or parse error? */
3657 if (!pipe_list || pipe_list == ERR_PTR) {
3658 /* parse_stream already emitted error msg */
3661 debug_printf_parse("parse_group return 1: "
3662 "parse_stream returned %p\n", pipe_list);
3665 command->group = pipe_list;
3667 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3668 command->group_as_string = as_string;
3669 debug_printf_parse("end of group, remembering as:'%s'\n",
3670 command->group_as_string);
3674 debug_printf_parse("parse_group return 0\n");
3676 /* command remains "open", available for possible redirects */
3679 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3680 /* Subroutines for copying $(...) and `...` things */
3681 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3683 static int add_till_single_quote(o_string *dest, struct in_str *input)
3686 int ch = i_getch(input);
3688 syntax_error_unterm_ch('\'');
3696 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3697 static int add_till_double_quote(o_string *dest, struct in_str *input)
3700 int ch = i_getch(input);
3702 syntax_error_unterm_ch('"');
3707 if (ch == '\\') { /* \x. Copy both chars. */
3709 ch = i_getch(input);
3713 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3718 //if (ch == '$') ...
3721 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3723 * "Within the backquoted style of command substitution, backslash
3724 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3725 * The search for the matching backquote shall be satisfied by the first
3726 * backquote found without a preceding backslash; during this search,
3727 * if a non-escaped backquote is encountered within a shell comment,
3728 * a here-document, an embedded command substitution of the $(command)
3729 * form, or a quoted string, undefined results occur. A single-quoted
3730 * or double-quoted string that begins, but does not end, within the
3731 * "`...`" sequence produces undefined results."
3733 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3735 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3738 int ch = i_getch(input);
3742 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3743 ch = i_getch(input);
3747 && (!in_dquote || ch != '"')
3749 o_addchr(dest, '\\');
3753 syntax_error_unterm_ch('`');
3759 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3760 * quoting and nested ()s.
3761 * "With the $(command) style of command substitution, all characters
3762 * following the open parenthesis to the matching closing parenthesis
3763 * constitute the command. Any valid shell script can be used for command,
3764 * except a script consisting solely of redirections which produces
3765 * unspecified results."
3767 * echo $(echo '(TEST)' BEST) (TEST) BEST
3768 * echo $(echo 'TEST)' BEST) TEST) BEST
3769 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3771 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3772 * can contain arbitrary constructs, just like $(cmd).
3773 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3774 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3776 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3777 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3780 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3781 # if ENABLE_HUSH_BASH_COMPAT
3782 char end_char2 = end_ch >> 8;
3784 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3787 ch = i_getch(input);
3789 syntax_error_unterm_ch(end_ch);
3792 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3795 /* we look for closing )) of $((EXPR)) */
3796 if (i_peek(input) == end_ch) {
3797 i_getch(input); /* eat second ')' */
3802 if (ch == '(' || ch == '{') {
3803 ch = (ch == '(' ? ')' : '}');
3804 if (!add_till_closing_bracket(dest, input, ch))
3810 if (!add_till_single_quote(dest, input))
3816 if (!add_till_double_quote(dest, input))
3822 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3828 /* \x. Copy verbatim. Important for \(, \) */
3829 ch = i_getch(input);
3831 syntax_error_unterm_ch(')');
3840 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3842 /* Return code: 0 for OK, 1 for syntax error */
3844 #define parse_dollar(as_string, dest, input, quote_mask) \
3845 parse_dollar(dest, input, quote_mask)
3846 #define as_string NULL
3848 static int parse_dollar(o_string *as_string,
3850 struct in_str *input, unsigned char quote_mask)
3852 int ch = i_peek(input); /* first character after the $ */
3854 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3856 ch = i_getch(input);
3857 nommu_addchr(as_string, ch);
3859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3861 debug_printf_parse(": '%c'\n", ch);
3862 o_addchr(dest, ch | quote_mask);
3865 if (!isalnum(ch) && ch != '_')
3867 ch = i_getch(input);
3868 nommu_addchr(as_string, ch);
3870 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3871 } else if (isdigit(ch)) {
3873 ch = i_getch(input);
3874 nommu_addchr(as_string, ch);
3875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3876 debug_printf_parse(": '%c'\n", ch);
3877 o_addchr(dest, ch | quote_mask);
3878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3879 } else switch (ch) {
3881 case '!': /* last bg pid */
3882 case '?': /* last exit code */
3883 case '#': /* number of args */
3884 case '*': /* args */
3885 case '@': /* args */
3886 goto make_one_char_var;
3888 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3890 ch = i_getch(input); /* eat '{' */
3891 nommu_addchr(as_string, ch);
3893 ch = i_getch(input); /* first char after '{' */
3894 /* It should be ${?}, or ${#var},
3895 * or even ${?+subst} - operator acting on a special variable,
3896 * or the beginning of variable name.
3899 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3902 syntax_error_unterm_str("${name}");
3903 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3906 nommu_addchr(as_string, ch);
3909 /* It's possible to just call add_till_closing_bracket() at this point.
3910 * However, this regresses some of our testsuite cases
3911 * which check invalid constructs like ${%}.
3912 * Oh well... let's check that the var name part is fine... */
3918 debug_printf_parse(": '%c'\n", ch);
3920 ch = i_getch(input);
3921 nommu_addchr(as_string, ch);
3925 if (!isalnum(ch) && ch != '_') {
3927 unsigned char last_ch;
3928 /* handle parameter expansions
3929 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3931 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3932 goto bad_dollar_syntax;
3934 /* Eat everything until closing '}' (or ':') */
3936 if (ENABLE_HUSH_BASH_COMPAT
3938 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3940 /* It's ${var:N[:M]} thing */
3941 end_ch = '}' * 0x100 + ':';
3943 if (ENABLE_HUSH_BASH_COMPAT
3946 /* It's ${var/[/]pattern[/repl]} thing */
3947 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3949 nommu_addchr(as_string, '/');
3952 end_ch = '}' * 0x100 + '/';
3958 #if ENABLE_HUSH_DOLLAR_OPS
3959 last_ch = add_till_closing_bracket(dest, input, end_ch);
3960 if (last_ch == 0) /* error? */
3963 #error Simple code to only allow ${var} is not implemented
3966 o_addstr(as_string, dest->data + pos);
3967 o_addchr(as_string, last_ch);
3970 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3971 /* close the first block: */
3972 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3973 /* while parsing N from ${var:N[:M]}
3974 * or pattern from ${var/[/]pattern[/repl]} */
3975 if ((end_ch & 0xff) == last_ch) {
3976 /* got ':' or '/'- parse the rest */
3981 if (end_ch == '}' * 0x100 + ':') {
3982 /* it's ${var:N} - emulate :999999999 */
3983 o_addstr(dest, "999999999");
3984 } /* else: it's ${var/[/]pattern} */
3989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3992 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3996 ch = i_getch(input);
3997 nommu_addchr(as_string, ch);
3998 # if ENABLE_SH_MATH_SUPPORT
3999 if (i_peek(input) == '(') {
4000 ch = i_getch(input);
4001 nommu_addchr(as_string, ch);
4002 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4003 o_addchr(dest, /*quote_mask |*/ '+');
4006 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4007 return 0; /* error */
4009 o_addstr(as_string, dest->data + pos);
4010 o_addchr(as_string, ')');
4011 o_addchr(as_string, ')');
4013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4017 # if ENABLE_HUSH_TICK
4018 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4019 o_addchr(dest, quote_mask | '`');
4022 if (!add_till_closing_bracket(dest, input, ')'))
4023 return 0; /* error */
4025 o_addstr(as_string, dest->data + pos);
4026 o_addchr(as_string, ')');
4028 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4034 ch = i_getch(input);
4035 nommu_addchr(as_string, ch);
4037 if (isalnum(ch)) { /* it's $_name or $_123 */
4042 /* TODO: $_ and $-: */
4043 /* $_ Shell or shell script name; or last argument of last command
4044 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4045 * but in command's env, set to full pathname used to invoke it */
4046 /* $- Option flags set by set builtin or shell options (-i etc) */
4048 o_addQchr(dest, '$');
4050 debug_printf_parse("parse_dollar return 1 (ok)\n");
4056 # if ENABLE_HUSH_BASH_COMPAT
4057 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4058 encode_string(dest, input, dquote_end, process_bkslash)
4060 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4061 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4062 encode_string(dest, input, dquote_end)
4064 #define as_string NULL
4068 # if ENABLE_HUSH_BASH_COMPAT
4069 /* all parameters are needed, no macro tricks */
4071 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4072 encode_string(as_string, dest, input, dquote_end)
4075 static int encode_string(o_string *as_string,
4077 struct in_str *input,
4079 int process_bkslash)
4081 #if !ENABLE_HUSH_BASH_COMPAT
4082 const int process_bkslash = 1;
4088 ch = i_getch(input);
4090 nommu_addchr(as_string, ch);
4091 if (ch == dquote_end) { /* may be only '"' or EOF */
4092 debug_printf_parse("encode_string return 1 (ok)\n");
4095 /* note: can't move it above ch == dquote_end check! */
4097 syntax_error_unterm_ch('"');
4098 return 0; /* error */
4102 next = i_peek(input);
4104 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4105 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4106 if (process_bkslash && ch == '\\') {
4108 syntax_error("\\<eof>");
4112 * "The backslash retains its special meaning [in "..."]
4113 * only when followed by one of the following characters:
4114 * $, `, ", \, or <newline>. A double quote may be quoted
4115 * within double quotes by preceding it with a backslash."
4116 * NB: in (unquoted) heredoc, above does not apply to ",
4117 * therefore we check for it by "next == dquote_end" cond.
4119 if (next == dquote_end || strchr("$`\\\n", next)) {
4120 ch = i_getch(input); /* eat next */
4122 goto again; /* skip \<newline> */
4123 } /* else: ch remains == '\\', and we double it below: */
4124 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4125 nommu_addchr(as_string, ch);
4129 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4130 debug_printf_parse("encode_string return 0: "
4131 "parse_dollar returned 0 (error)\n");
4136 #if ENABLE_HUSH_TICK
4138 //unsigned pos = dest->length;
4139 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4140 o_addchr(dest, 0x80 | '`');
4141 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4142 return 0; /* error */
4143 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4144 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4148 o_addQchr(dest, ch);
4154 * Scan input until EOF or end_trigger char.
4155 * Return a list of pipes to execute, or NULL on EOF
4156 * or if end_trigger character is met.
4157 * On syntax error, exit if shell is not interactive,
4158 * reset parsing machinery and start parsing anew,
4159 * or return ERR_PTR.
4161 static struct pipe *parse_stream(char **pstring,
4162 struct in_str *input,
4165 struct parse_context ctx;
4166 o_string dest = NULL_O_STRING;
4169 /* Single-quote triggers a bypass of the main loop until its mate is
4170 * found. When recursing, quote state is passed in via dest->o_expflags.
4172 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4173 end_trigger ? end_trigger : 'X');
4176 /* If very first arg is "" or '', dest.data may end up NULL.
4177 * Preventing this: */
4178 o_addchr(&dest, '\0');
4181 /* We used to separate words on $IFS here. This was wrong.
4182 * $IFS is used only for word splitting when $var is expanded,
4183 * here we should use blank chars as separators, not $IFS
4186 if (MAYBE_ASSIGNMENT != 0)
4187 dest.o_assignment = MAYBE_ASSIGNMENT;
4188 initialize_context(&ctx);
4191 const char *is_blank;
4192 const char *is_special;
4196 redir_type redir_style;
4198 ch = i_getch(input);
4199 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4200 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4205 syntax_error_unterm_str("here document");
4208 /* end_trigger == '}' case errors out earlier,
4209 * checking only ')' */
4210 if (end_trigger == ')') {
4211 syntax_error_unterm_ch('(');
4215 if (done_word(&dest, &ctx)) {
4219 done_pipe(&ctx, PIPE_SEQ);
4221 /* If we got nothing... */
4222 /* (this makes bare "&" cmd a no-op.
4223 * bash says: "syntax error near unexpected token '&'") */
4224 if (pi->num_cmds == 0
4225 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4231 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4233 *pstring = ctx.as_string.data;
4235 o_free_unsafe(&ctx.as_string);
4238 debug_printf_parse("parse_stream return %p\n", pi);
4241 nommu_addchr(&ctx.as_string, ch);
4245 next = i_peek(input);
4247 is_special = "{}<>;&|()#'" /* special outside of "str" */
4248 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4249 /* Are { and } special here? */
4250 if (ctx.command->argv /* word [word]{... - non-special */
4251 || dest.length /* word{... - non-special */
4252 || dest.has_quoted_part /* ""{... - non-special */
4253 || (next != ';' /* }; - special */
4254 && next != ')' /* }) - special */
4255 && next != '&' /* }& and }&& ... - special */
4256 && next != '|' /* }|| ... - special */
4257 && !strchr(defifs, next) /* {word - non-special */
4260 /* They are not special, skip "{}" */
4263 is_special = strchr(is_special, ch);
4264 is_blank = strchr(defifs, ch);
4266 if (!is_special && !is_blank) { /* ordinary char */
4268 o_addQchr(&dest, ch);
4269 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4270 || dest.o_assignment == WORD_IS_KEYWORD)
4272 && is_well_formed_var_name(dest.data, '=')
4274 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4275 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4281 if (done_word(&dest, &ctx)) {
4285 /* Is this a case when newline is simply ignored?
4287 * "cmd | <newline> cmd ..."
4288 * "case ... in <newline> word) ..."
4290 if (IS_NULL_CMD(ctx.command)
4291 && dest.length == 0 && !dest.has_quoted_part
4293 /* This newline can be ignored. But...
4294 * Without check #1, interactive shell
4295 * ignores even bare <newline>,
4296 * and shows the continuation prompt:
4297 * ps1_prompt$ <enter>
4298 * ps2> _ <=== wrong, should be ps1
4299 * Without check #2, "cmd & <newline>"
4300 * is similarly mistreated.
4301 * (BTW, this makes "cmd & cmd"
4302 * and "cmd && cmd" non-orthogonal.
4303 * Really, ask yourself, why
4304 * "cmd && <newline>" doesn't start
4305 * cmd but waits for more input?
4308 struct pipe *pi = ctx.list_head;
4309 if (pi->num_cmds != 0 /* check #1 */
4310 && pi->followup != PIPE_BG /* check #2 */
4315 /* Treat newline as a command separator. */
4316 done_pipe(&ctx, PIPE_SEQ);
4317 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4319 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4324 dest.o_assignment = MAYBE_ASSIGNMENT;
4325 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4327 /* note: if (is_blank) continue;
4328 * will still trigger for us */
4332 /* "cmd}" or "cmd }..." without semicolon or &:
4333 * } is an ordinary char in this case, even inside { cmd; }
4334 * Pathological example: { ""}; } should exec "}" cmd
4337 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4338 || dest.length != 0 /* word} */
4339 || dest.has_quoted_part /* ""} */
4343 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4344 goto skip_end_trigger;
4345 /* else: } does terminate a group */
4348 if (end_trigger && end_trigger == ch
4349 && (ch != ';' || heredoc_cnt == 0)
4350 #if ENABLE_HUSH_CASE
4352 || ctx.ctx_res_w != RES_MATCH
4353 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4358 /* This is technically valid:
4359 * { cat <<HERE; }; echo Ok
4363 * but we don't support this.
4364 * We require heredoc to be in enclosing {}/(),
4367 syntax_error_unterm_str("here document");
4370 if (done_word(&dest, &ctx)) {
4373 done_pipe(&ctx, PIPE_SEQ);
4374 dest.o_assignment = MAYBE_ASSIGNMENT;
4375 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4376 /* Do we sit outside of any if's, loops or case's? */
4378 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4382 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4384 *pstring = ctx.as_string.data;
4386 o_free_unsafe(&ctx.as_string);
4389 debug_printf_parse("parse_stream return %p: "
4390 "end_trigger char found\n",
4392 return ctx.list_head;
4399 /* Catch <, > before deciding whether this word is
4400 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4403 redir_fd = redirect_opt_num(&dest);
4404 if (done_word(&dest, &ctx)) {
4407 redir_style = REDIRECT_OVERWRITE;
4409 redir_style = REDIRECT_APPEND;
4410 ch = i_getch(input);
4411 nommu_addchr(&ctx.as_string, ch);
4414 else if (next == '(') {
4415 syntax_error(">(process) not supported");
4419 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4421 continue; /* back to top of while (1) */
4423 redir_fd = redirect_opt_num(&dest);
4424 if (done_word(&dest, &ctx)) {
4427 redir_style = REDIRECT_INPUT;
4429 redir_style = REDIRECT_HEREDOC;
4431 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4432 ch = i_getch(input);
4433 nommu_addchr(&ctx.as_string, ch);
4434 } else if (next == '>') {
4435 redir_style = REDIRECT_IO;
4436 ch = i_getch(input);
4437 nommu_addchr(&ctx.as_string, ch);
4440 else if (next == '(') {
4441 syntax_error("<(process) not supported");
4445 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4447 continue; /* back to top of while (1) */
4449 if (dest.length == 0 && !dest.has_quoted_part) {
4450 /* skip "#comment" */
4453 if (ch == EOF || ch == '\n')
4456 /* note: we do not add it to &ctx.as_string */
4458 nommu_addchr(&ctx.as_string, '\n');
4459 continue; /* back to top of while (1) */
4464 /* It's "\<newline>" */
4466 /* Remove trailing '\' from ctx.as_string */
4467 ctx.as_string.data[--ctx.as_string.length] = '\0';
4469 ch = i_getch(input); /* eat it */
4470 continue; /* back to top of while (1) */
4475 if (dest.o_assignment == MAYBE_ASSIGNMENT
4476 /* check that we are not in word in "a=1 2>word b=1": */
4477 && !ctx.pending_redirect
4479 /* ch is a special char and thus this word
4480 * cannot be an assignment */
4481 dest.o_assignment = NOT_ASSIGNMENT;
4482 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4485 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4488 case '#': /* non-comment #: "echo a#b" etc */
4489 o_addQchr(&dest, ch);
4493 syntax_error("\\<eof>");
4496 ch = i_getch(input);
4497 /* note: ch != '\n' (that case does not reach this place) */
4498 o_addchr(&dest, '\\');
4499 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4500 o_addchr(&dest, ch);
4501 nommu_addchr(&ctx.as_string, ch);
4502 /* Example: echo Hello \2>file
4503 * we need to know that word 2 is quoted */
4504 dest.has_quoted_part = 1;
4507 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4508 debug_printf_parse("parse_stream parse error: "
4509 "parse_dollar returned 0 (error)\n");
4514 dest.has_quoted_part = 1;
4515 if (next == '\'' && !ctx.pending_redirect) {
4516 insert_empty_quoted_str_marker:
4517 nommu_addchr(&ctx.as_string, next);
4518 i_getch(input); /* eat second ' */
4519 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4520 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4523 ch = i_getch(input);
4525 syntax_error_unterm_ch('\'');
4528 nommu_addchr(&ctx.as_string, ch);
4531 o_addqchr(&dest, ch);
4536 dest.has_quoted_part = 1;
4537 if (next == '"' && !ctx.pending_redirect)
4538 goto insert_empty_quoted_str_marker;
4539 if (dest.o_assignment == NOT_ASSIGNMENT)
4540 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4541 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4543 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4545 #if ENABLE_HUSH_TICK
4547 USE_FOR_NOMMU(unsigned pos;)
4549 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4550 o_addchr(&dest, '`');
4551 USE_FOR_NOMMU(pos = dest.length;)
4552 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4555 o_addstr(&ctx.as_string, dest.data + pos);
4556 o_addchr(&ctx.as_string, '`');
4558 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4559 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4564 #if ENABLE_HUSH_CASE
4567 if (done_word(&dest, &ctx)) {
4570 done_pipe(&ctx, PIPE_SEQ);
4571 #if ENABLE_HUSH_CASE
4572 /* Eat multiple semicolons, detect
4573 * whether it means something special */
4578 ch = i_getch(input);
4579 nommu_addchr(&ctx.as_string, ch);
4580 if (ctx.ctx_res_w == RES_CASE_BODY) {
4581 ctx.ctx_dsemicolon = 1;
4582 ctx.ctx_res_w = RES_MATCH;
4588 /* We just finished a cmd. New one may start
4589 * with an assignment */
4590 dest.o_assignment = MAYBE_ASSIGNMENT;
4591 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4594 if (done_word(&dest, &ctx)) {
4598 ch = i_getch(input);
4599 nommu_addchr(&ctx.as_string, ch);
4600 done_pipe(&ctx, PIPE_AND);
4602 done_pipe(&ctx, PIPE_BG);
4606 if (done_word(&dest, &ctx)) {
4609 #if ENABLE_HUSH_CASE
4610 if (ctx.ctx_res_w == RES_MATCH)
4611 break; /* we are in case's "word | word)" */
4613 if (next == '|') { /* || */
4614 ch = i_getch(input);
4615 nommu_addchr(&ctx.as_string, ch);
4616 done_pipe(&ctx, PIPE_OR);
4618 /* we could pick up a file descriptor choice here
4619 * with redirect_opt_num(), but bash doesn't do it.
4620 * "echo foo 2| cat" yields "foo 2". */
4623 o_reset_to_empty_unquoted(&ctx.as_string);
4628 #if ENABLE_HUSH_CASE
4629 /* "case... in [(]word)..." - skip '(' */
4630 if (ctx.ctx_res_w == RES_MATCH
4631 && ctx.command->argv == NULL /* not (word|(... */
4632 && dest.length == 0 /* not word(... */
4633 && dest.has_quoted_part == 0 /* not ""(... */
4639 if (parse_group(&dest, &ctx, input, ch) != 0) {
4644 #if ENABLE_HUSH_CASE
4645 if (ctx.ctx_res_w == RES_MATCH)
4649 /* proper use of this character is caught by end_trigger:
4650 * if we see {, we call parse_group(..., end_trigger='}')
4651 * and it will match } earlier (not here). */
4652 syntax_error_unexpected_ch(ch);
4656 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4662 struct parse_context *pctx;
4663 IF_HAS_KEYWORDS(struct parse_context *p2;)
4665 /* Clean up allocated tree.
4666 * Sample for finding leaks on syntax error recovery path.
4667 * Run it from interactive shell, watch pmap `pidof hush`.
4668 * while if false; then false; fi; do break; fi
4669 * Samples to catch leaks at execution:
4670 * while if (true | {true;}); then echo ok; fi; do break; done
4671 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4675 /* Update pipe/command counts,
4676 * otherwise freeing may miss some */
4677 done_pipe(pctx, PIPE_SEQ);
4678 debug_printf_clean("freeing list %p from ctx %p\n",
4679 pctx->list_head, pctx);
4680 debug_print_tree(pctx->list_head, 0);
4681 free_pipe_list(pctx->list_head);
4682 debug_printf_clean("freed list %p\n", pctx->list_head);
4684 o_free_unsafe(&pctx->as_string);
4686 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4690 IF_HAS_KEYWORDS(pctx = p2;)
4691 } while (HAS_KEYWORDS && pctx);
4694 G.last_exitcode = 1;
4705 /*** Execution routines ***/
4707 /* Expansion can recurse, need forward decls: */
4708 #if !ENABLE_HUSH_BASH_COMPAT
4709 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4710 #define expand_string_to_string(str, do_unbackslash) \
4711 expand_string_to_string(str)
4713 static char *expand_string_to_string(const char *str, int do_unbackslash);
4714 #if ENABLE_HUSH_TICK
4715 static int process_command_subs(o_string *dest, const char *s);
4718 /* expand_strvec_to_strvec() takes a list of strings, expands
4719 * all variable references within and returns a pointer to
4720 * a list of expanded strings, possibly with larger number
4721 * of strings. (Think VAR="a b"; echo $VAR).
4722 * This new list is allocated as a single malloc block.
4723 * NULL-terminated list of char* pointers is at the beginning of it,
4724 * followed by strings themselves.
4725 * Caller can deallocate entire list by single free(list). */
4727 /* A horde of its helpers come first: */
4729 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4731 while (--len >= 0) {
4734 #if ENABLE_HUSH_BRACE_EXPANSION
4735 if (c == '{' || c == '}') {
4736 /* { -> \{, } -> \} */
4738 /* And now we want to add { or } and continue:
4741 * luckily, just falling throught achieves this.
4747 /* \z -> \\\z; \<eol> -> \\<eol> */
4752 o_addchr(o, *str++);
4758 /* Store given string, finalizing the word and starting new one whenever
4759 * we encounter IFS char(s). This is used for expanding variable values.
4760 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4761 * Return in *ended_with_ifs:
4762 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4764 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4766 int last_is_ifs = 0;
4771 if (!*str) /* EOL - do not finalize word */
4773 word_len = strcspn(str, G.ifs);
4775 /* We have WORD_LEN leading non-IFS chars */
4776 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4777 o_addblock(output, str, word_len);
4779 /* Protect backslashes against globbing up :)
4780 * Example: "v='\*'; echo b$v" prints "b\*"
4781 * (and does not try to glob on "*")
4783 o_addblock_duplicate_backslash(output, str, word_len);
4784 /*/ Why can't we do it easier? */
4785 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4786 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4790 if (!*str) /* EOL - do not finalize word */
4794 /* We know str here points to at least one IFS char */
4796 str += strspn(str, G.ifs); /* skip IFS chars */
4797 if (!*str) /* EOL - do not finalize word */
4800 /* Start new word... but not always! */
4801 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4802 if (output->has_quoted_part
4803 /* Case "v=' a'; echo $v":
4804 * here nothing precedes the space in $v expansion,
4805 * therefore we should not finish the word
4806 * (IOW: if there *is* word to finalize, only then do it):
4808 || (n > 0 && output->data[output->length - 1])
4810 o_addchr(output, '\0');
4811 debug_print_list("expand_on_ifs", output, n);
4812 n = o_save_ptr(output, n);
4817 *ended_with_ifs = last_is_ifs;
4818 debug_print_list("expand_on_ifs[1]", output, n);
4822 /* Helper to expand $((...)) and heredoc body. These act as if
4823 * they are in double quotes, with the exception that they are not :).
4824 * Just the rules are similar: "expand only $var and `cmd`"
4826 * Returns malloced string.
4827 * As an optimization, we return NULL if expansion is not needed.
4829 #if !ENABLE_HUSH_BASH_COMPAT
4830 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4831 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4832 encode_then_expand_string(str)
4834 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4837 struct in_str input;
4838 o_string dest = NULL_O_STRING;
4840 if (!strchr(str, '$')
4841 && !strchr(str, '\\')
4842 #if ENABLE_HUSH_TICK
4843 && !strchr(str, '`')
4849 /* We need to expand. Example:
4850 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4852 setup_string_in_str(&input, str);
4853 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4854 //TODO: error check (encode_string returns 0 on error)?
4855 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4856 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4857 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4858 o_free_unsafe(&dest);
4862 #if ENABLE_SH_MATH_SUPPORT
4863 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4865 arith_state_t math_state;
4869 math_state.lookupvar = get_local_var_value;
4870 math_state.setvar = set_local_var_from_halves;
4871 //math_state.endofname = endofname;
4872 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4873 res = arith(&math_state, exp_str ? exp_str : arg);
4876 *errmsg_p = math_state.errmsg;
4877 if (math_state.errmsg)
4878 die_if_script(math_state.errmsg);
4883 #if ENABLE_HUSH_BASH_COMPAT
4884 /* ${var/[/]pattern[/repl]} helpers */
4885 static char *strstr_pattern(char *val, const char *pattern, int *size)
4888 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4889 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4896 /* Optimization: if "*pat" did not match the start of "string",
4897 * we know that "tring", "ring" etc will not match too:
4899 if (pattern[0] == '*')
4904 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4906 char *result = NULL;
4907 unsigned res_len = 0;
4908 unsigned repl_len = strlen(repl);
4912 char *s = strstr_pattern(val, pattern, &size);
4916 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4917 memcpy(result + res_len, val, s - val);
4919 strcpy(result + res_len, repl);
4920 res_len += repl_len;
4921 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4927 if (val[0] && result) {
4928 result = xrealloc(result, res_len + strlen(val) + 1);
4929 strcpy(result + res_len, val);
4930 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4932 debug_printf_varexp("result:'%s'\n", result);
4938 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4940 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4942 const char *val = NULL;
4943 char *to_be_freed = NULL;
4948 char exp_save = exp_save; /* for compiler */
4949 char *exp_saveptr; /* points to expansion operator */
4950 char *exp_word = exp_word; /* for compiler */
4953 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4955 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4957 first_char = arg[0] = arg0 & 0x7f;
4960 if (first_char == '#' /* ${#... */
4961 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4963 /* It must be length operator: ${#var} */
4967 /* Maybe handle parameter expansion */
4968 if (exp_saveptr /* if 2nd char is one of expansion operators */
4969 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4971 /* ${?:0}, ${#[:]%0} etc */
4972 exp_saveptr = var + 1;
4974 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4975 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4977 exp_op = exp_save = *exp_saveptr;
4979 exp_word = exp_saveptr + 1;
4980 if (exp_op == ':') {
4981 exp_op = *exp_word++;
4982 //TODO: try ${var:} and ${var:bogus} in non-bash config
4983 if (ENABLE_HUSH_BASH_COMPAT
4984 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4986 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4991 *exp_saveptr = '\0';
4992 } /* else: it's not an expansion op, but bare ${var} */
4995 /* Look up the variable in question */
4996 if (isdigit(var[0])) {
4997 /* parse_dollar should have vetted var for us */
4998 int n = xatoi_positive(var);
4999 if (n < G.global_argc)
5000 val = G.global_argv[n];
5001 /* else val remains NULL: $N with too big N */
5005 val = utoa(G.root_pid);
5007 case '!': /* bg pid */
5008 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5010 case '?': /* exitcode */
5011 val = utoa(G.last_exitcode);
5013 case '#': /* argc */
5014 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5017 val = get_local_var_value(var);
5021 /* Handle any expansions */
5022 if (exp_op == 'L') {
5023 debug_printf_expand("expand: length(%s)=", val);
5024 val = utoa(val ? strlen(val) : 0);
5025 debug_printf_expand("%s\n", val);
5026 } else if (exp_op) {
5027 if (exp_op == '%' || exp_op == '#') {
5028 /* Standard-mandated substring removal ops:
5029 * ${parameter%word} - remove smallest suffix pattern
5030 * ${parameter%%word} - remove largest suffix pattern
5031 * ${parameter#word} - remove smallest prefix pattern
5032 * ${parameter##word} - remove largest prefix pattern
5034 * Word is expanded to produce a glob pattern.
5035 * Then var's value is matched to it and matching part removed.
5037 if (val && val[0]) {
5041 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5042 if (exp_op == *exp_word) /* ## or %% */
5044 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5046 exp_word = exp_exp_word;
5047 /* HACK ALERT. We depend here on the fact that
5048 * G.global_argv and results of utoa and get_local_var_value
5049 * are actually in writable memory:
5050 * scan_and_match momentarily stores NULs there. */
5052 loc = scan_and_match(t, exp_word, scan_flags);
5053 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5054 // exp_op, t, exp_word, loc);
5056 if (loc) { /* match was found */
5057 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5058 val = loc; /* take right part */
5060 val = to_be_freed = xstrndup(val, loc - val); /* left */
5064 #if ENABLE_HUSH_BASH_COMPAT
5065 else if (exp_op == '/' || exp_op == '\\') {
5066 /* It's ${var/[/]pattern[/repl]} thing.
5067 * Note that in encoded form it has TWO parts:
5068 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5069 * and if // is used, it is encoded as \:
5070 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5072 /* Empty variable always gives nothing: */
5073 // "v=''; echo ${v/*/w}" prints "", not "w"
5074 if (val && val[0]) {
5075 /* pattern uses non-standard expansion.
5076 * repl should be unbackslashed and globbed
5077 * by the usual expansion rules:
5079 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5080 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5081 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5082 * v='a bz'; echo ${v/a*z/\z} prints "z"
5083 * (note that a*z _pattern_ is never globbed!)
5085 char *pattern, *repl, *t;
5086 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5088 pattern = xstrdup(exp_word);
5089 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5090 *p++ = SPECIAL_VAR_SYMBOL;
5092 p = strchr(p, SPECIAL_VAR_SYMBOL);
5094 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5095 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5096 /* HACK ALERT. We depend here on the fact that
5097 * G.global_argv and results of utoa and get_local_var_value
5098 * are actually in writable memory:
5099 * replace_pattern momentarily stores NULs there. */
5101 to_be_freed = replace_pattern(t,
5103 (repl ? repl : exp_word),
5105 if (to_be_freed) /* at least one replace happened */
5112 else if (exp_op == ':') {
5113 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5114 /* It's ${var:N[:M]} bashism.
5115 * Note that in encoded form it has TWO parts:
5116 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5121 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5124 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5125 *p++ = SPECIAL_VAR_SYMBOL;
5127 p = strchr(p, SPECIAL_VAR_SYMBOL);
5129 len = expand_and_evaluate_arith(exp_word, &errmsg);
5132 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5133 if (len >= 0) { /* bash compat: len < 0 is illegal */
5134 if (beg < 0) /* bash compat */
5136 debug_printf_varexp("from val:'%s'\n", val);
5137 if (len == 0 || !val || beg >= strlen(val)) {
5141 /* Paranoia. What if user entered 9999999999999
5142 * which fits in arith_t but not int? */
5145 val = to_be_freed = xstrndup(val + beg, len);
5147 debug_printf_varexp("val:'%s'\n", val);
5151 die_if_script("malformed ${%s:...}", var);
5154 } else { /* one of "-=+?" */
5155 /* Standard-mandated substitution ops:
5156 * ${var?word} - indicate error if unset
5157 * If var is unset, word (or a message indicating it is unset
5158 * if word is null) is written to standard error
5159 * and the shell exits with a non-zero exit status.
5160 * Otherwise, the value of var is substituted.
5161 * ${var-word} - use default value
5162 * If var is unset, word is substituted.
5163 * ${var=word} - assign and use default value
5164 * If var is unset, word is assigned to var.
5165 * In all cases, final value of var is substituted.
5166 * ${var+word} - use alternative value
5167 * If var is unset, null is substituted.
5168 * Otherwise, word is substituted.
5170 * Word is subjected to tilde expansion, parameter expansion,
5171 * command substitution, and arithmetic expansion.
5172 * If word is not needed, it is not expanded.
5174 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5175 * but also treat null var as if it is unset.
5177 int use_word = (!val || ((exp_save == ':') && !val[0]));
5179 use_word = !use_word;
5180 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5181 (exp_save == ':') ? "true" : "false", use_word);
5183 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5185 exp_word = to_be_freed;
5186 if (exp_op == '?') {
5187 /* mimic bash message */
5188 die_if_script("%s: %s",
5190 exp_word[0] ? exp_word : "parameter null or not set"
5192 //TODO: how interactive bash aborts expansion mid-command?
5197 if (exp_op == '=') {
5198 /* ${var=[word]} or ${var:=[word]} */
5199 if (isdigit(var[0]) || var[0] == '#') {
5200 /* mimic bash message */
5201 die_if_script("$%s: cannot assign in this way", var);
5204 char *new_var = xasprintf("%s=%s", var, val);
5205 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5209 } /* one of "-=+?" */
5211 *exp_saveptr = exp_save;
5217 *to_be_freed_pp = to_be_freed;
5221 /* Expand all variable references in given string, adding words to list[]
5222 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5223 * to be filled). This routine is extremely tricky: has to deal with
5224 * variables/parameters with whitespace, $* and $@, and constructs like
5225 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5226 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5228 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5229 * expansion of right-hand side of assignment == 1-element expand.
5231 char cant_be_null = 0; /* only bit 0x80 matters */
5232 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5235 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5236 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5237 debug_print_list("expand_vars_to_list", output, n);
5238 n = o_save_ptr(output, n);
5239 debug_print_list("expand_vars_to_list[0]", output, n);
5241 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5243 char *to_be_freed = NULL;
5244 const char *val = NULL;
5245 #if ENABLE_HUSH_TICK
5246 o_string subst_result = NULL_O_STRING;
5248 #if ENABLE_SH_MATH_SUPPORT
5249 char arith_buf[sizeof(arith_t)*3 + 2];
5253 o_addchr(output, '\0');
5254 n = o_save_ptr(output, n);
5258 o_addblock(output, arg, p - arg);
5259 debug_print_list("expand_vars_to_list[1]", output, n);
5261 p = strchr(p, SPECIAL_VAR_SYMBOL);
5263 /* Fetch special var name (if it is indeed one of them)
5264 * and quote bit, force the bit on if singleword expansion -
5265 * important for not getting v=$@ expand to many words. */
5266 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5268 /* Is this variable quoted and thus expansion can't be null?
5269 * "$@" is special. Even if quoted, it can still
5270 * expand to nothing (not even an empty string),
5271 * thus it is excluded. */
5272 if ((first_ch & 0x7f) != '@')
5273 cant_be_null |= first_ch;
5275 switch (first_ch & 0x7f) {
5276 /* Highest bit in first_ch indicates that var is double-quoted */
5280 if (!G.global_argv[1])
5283 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5284 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5285 while (G.global_argv[i]) {
5286 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5287 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5288 if (G.global_argv[i++][0] && G.global_argv[i]) {
5289 /* this argv[] is not empty and not last:
5290 * put terminating NUL, start new word */
5291 o_addchr(output, '\0');
5292 debug_print_list("expand_vars_to_list[2]", output, n);
5293 n = o_save_ptr(output, n);
5294 debug_print_list("expand_vars_to_list[3]", output, n);
5298 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5299 * and in this case should treat it like '$*' - see 'else...' below */
5300 if (first_ch == ('@'|0x80) /* quoted $@ */
5301 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5304 o_addQstr(output, G.global_argv[i]);
5305 if (++i >= G.global_argc)
5307 o_addchr(output, '\0');
5308 debug_print_list("expand_vars_to_list[4]", output, n);
5309 n = o_save_ptr(output, n);
5311 } else { /* quoted $* (or v="$@" case): add as one word */
5313 o_addQstr(output, G.global_argv[i]);
5314 if (!G.global_argv[++i])
5317 o_addchr(output, G.ifs[0]);
5319 output->has_quoted_part = 1;
5323 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5324 /* "Empty variable", used to make "" etc to not disappear */
5325 output->has_quoted_part = 1;
5327 cant_be_null = 0x80;
5329 #if ENABLE_HUSH_TICK
5330 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5331 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5333 /* Can't just stuff it into output o_string,
5334 * expanded result may need to be globbed
5335 * and $IFS-splitted */
5336 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5337 G.last_exitcode = process_command_subs(&subst_result, arg);
5338 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5339 val = subst_result.data;
5342 #if ENABLE_SH_MATH_SUPPORT
5343 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5346 arg++; /* skip '+' */
5347 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5348 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5349 res = expand_and_evaluate_arith(arg, NULL);
5350 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5351 sprintf(arith_buf, ARITH_FMT, res);
5357 val = expand_one_var(&to_be_freed, arg, &p);
5358 IF_HUSH_TICK(store_val:)
5359 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5360 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5361 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5362 if (val && val[0]) {
5363 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5366 } else { /* quoted $VAR, val will be appended below */
5367 output->has_quoted_part = 1;
5368 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5369 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5373 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5375 if (val && val[0]) {
5376 o_addQstr(output, val);
5380 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5381 * Do the check to avoid writing to a const string. */
5382 if (*p != SPECIAL_VAR_SYMBOL)
5383 *p = SPECIAL_VAR_SYMBOL;
5385 #if ENABLE_HUSH_TICK
5386 o_free(&subst_result);
5389 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5393 o_addchr(output, '\0');
5394 n = o_save_ptr(output, n);
5396 debug_print_list("expand_vars_to_list[a]", output, n);
5397 /* this part is literal, and it was already pre-quoted
5398 * if needed (much earlier), do not use o_addQstr here! */
5399 o_addstr_with_NUL(output, arg);
5400 debug_print_list("expand_vars_to_list[b]", output, n);
5401 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5402 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5405 /* allow to reuse list[n] later without re-growth */
5406 output->has_empty_slot = 1;
5408 o_addchr(output, '\0');
5414 static char **expand_variables(char **argv, unsigned expflags)
5418 o_string output = NULL_O_STRING;
5420 output.o_expflags = expflags;
5424 n = expand_vars_to_list(&output, n, *argv);
5427 debug_print_list("expand_variables", &output, n);
5429 /* output.data (malloced in one block) gets returned in "list" */
5430 list = o_finalize_list(&output, n);
5431 debug_print_strings("expand_variables[1]", list);
5435 static char **expand_strvec_to_strvec(char **argv)
5437 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5440 #if ENABLE_HUSH_BASH_COMPAT
5441 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5443 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5447 /* Used for expansion of right hand of assignments,
5448 * $((...)), heredocs, variable espansion parts.
5450 * NB: should NOT do globbing!
5451 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5453 static char *expand_string_to_string(const char *str, int do_unbackslash)
5455 #if !ENABLE_HUSH_BASH_COMPAT
5456 const int do_unbackslash = 1;
5458 char *argv[2], **list;
5460 debug_printf_expand("string_to_string<='%s'\n", str);
5461 /* This is generally an optimization, but it also
5462 * handles "", which otherwise trips over !list[0] check below.
5463 * (is this ever happens that we actually get str="" here?)
5465 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5466 //TODO: Can use on strings with \ too, just unbackslash() them?
5467 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5468 return xstrdup(str);
5471 argv[0] = (char*)str;
5473 list = expand_variables(argv, do_unbackslash
5474 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5475 : EXP_FLAG_SINGLEWORD
5478 if (!list[0] || list[1])
5479 bb_error_msg_and_die("BUG in varexp2");
5480 /* actually, just move string 2*sizeof(char*) bytes back */
5481 overlapping_strcpy((char*)list, list[0]);
5483 unbackslash((char*)list);
5484 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5488 /* Used for "eval" builtin */
5489 static char* expand_strvec_to_string(char **argv)
5493 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5494 /* Convert all NULs to spaces */
5499 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5500 bb_error_msg_and_die("BUG in varexp3");
5501 /* bash uses ' ' regardless of $IFS contents */
5506 overlapping_strcpy((char*)list, list[0]);
5507 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5511 static char **expand_assignments(char **argv, int count)
5516 G.expanded_assignments = p = NULL;
5517 /* Expand assignments into one string each */
5518 for (i = 0; i < count; i++) {
5519 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5521 G.expanded_assignments = NULL;
5526 static void switch_off_special_sigs(unsigned mask)
5529 while ((mask >>= 1) != 0) {
5534 if (G.traps[sig] && !G.traps[sig][0])
5535 /* trap is '', has to remain SIG_IGN */
5538 G.traps[sig] = NULL;
5540 /* We are here only if no trap or trap was not '' */
5541 install_sighandler(sig, SIG_DFL);
5547 void re_execute_shell(char ***to_free, const char *s,
5548 char *g_argv0, char **g_argv,
5549 char **builtin_argv) NORETURN;
5551 static void reset_traps_to_defaults(void)
5553 /* This function is always called in a child shell
5554 * after fork (not vfork, NOMMU doesn't use this function).
5559 /* Child shells are not interactive.
5560 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5561 * Testcase: (while :; do :; done) + ^Z should background.
5562 * Same goes for SIGTERM, SIGHUP, SIGINT.
5564 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5565 if (!G.traps && !mask)
5566 return; /* already no traps and no special sigs */
5568 /* Switch off special sigs */
5569 switch_off_special_sigs(mask);
5571 G_fatal_sig_mask = 0;
5573 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5574 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5575 * remain set in G.special_sig_mask */
5580 /* Reset all sigs to default except ones with empty traps */
5581 for (sig = 0; sig < NSIG; sig++) {
5583 continue; /* no trap: nothing to do */
5584 if (!G.traps[sig][0])
5585 continue; /* empty trap: has to remain SIG_IGN */
5586 /* sig has non-empty trap, reset it: */
5588 G.traps[sig] = NULL;
5589 /* There is no signal for trap 0 (EXIT) */
5592 install_sighandler(sig, pick_sighandler(sig));
5598 static void re_execute_shell(char ***to_free, const char *s,
5599 char *g_argv0, char **g_argv,
5600 char **builtin_argv) NORETURN;
5601 static void re_execute_shell(char ***to_free, const char *s,
5602 char *g_argv0, char **g_argv,
5603 char **builtin_argv)
5605 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5606 /* delims + 2 * (number of bytes in printed hex numbers) */
5607 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5608 char *heredoc_argv[4];
5609 struct variable *cur;
5610 # if ENABLE_HUSH_FUNCTIONS
5611 struct function *funcp;
5615 unsigned long long empty_trap_mask;
5617 if (!g_argv0) { /* heredoc */
5618 argv = heredoc_argv;
5619 argv[0] = (char *) G.argv0_for_re_execing;
5620 argv[1] = (char *) "-<";
5621 argv[2] = (char *) s;
5623 pp = &argv[3]; /* used as pointer to empty environment */
5629 if (pp) while (*pp++)
5632 empty_trap_mask = 0;
5635 for (sig = 1; sig < NSIG; sig++) {
5636 if (G.traps[sig] && !G.traps[sig][0])
5637 empty_trap_mask |= 1LL << sig;
5641 sprintf(param_buf, NOMMU_HACK_FMT
5642 , (unsigned) G.root_pid
5643 , (unsigned) G.root_ppid
5644 , (unsigned) G.last_bg_pid
5645 , (unsigned) G.last_exitcode
5648 IF_HUSH_LOOPS(, G.depth_of_loop)
5650 # undef NOMMU_HACK_FMT
5651 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5652 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5655 for (cur = G.top_var; cur; cur = cur->next) {
5656 if (!cur->flg_export || cur->flg_read_only)
5659 # if ENABLE_HUSH_FUNCTIONS
5660 for (funcp = G.top_func; funcp; funcp = funcp->next)
5666 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5667 *pp++ = (char *) G.argv0_for_re_execing;
5669 for (cur = G.top_var; cur; cur = cur->next) {
5670 if (strcmp(cur->varstr, hush_version_str) == 0)
5672 if (cur->flg_read_only) {
5673 *pp++ = (char *) "-R";
5674 *pp++ = cur->varstr;
5675 } else if (!cur->flg_export) {
5676 *pp++ = (char *) "-V";
5677 *pp++ = cur->varstr;
5680 # if ENABLE_HUSH_FUNCTIONS
5681 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5682 *pp++ = (char *) "-F";
5683 *pp++ = funcp->name;
5684 *pp++ = funcp->body_as_string;
5687 /* We can pass activated traps here. Say, -Tnn:trap_string
5689 * However, POSIX says that subshells reset signals with traps
5691 * I tested bash-3.2 and it not only does that with true subshells
5692 * of the form ( list ), but with any forked children shells.
5693 * I set trap "echo W" WINCH; and then tried:
5695 * { echo 1; sleep 20; echo 2; } &
5696 * while true; do echo 1; sleep 20; echo 2; break; done &
5697 * true | { echo 1; sleep 20; echo 2; } | cat
5699 * In all these cases sending SIGWINCH to the child shell
5700 * did not run the trap. If I add trap "echo V" WINCH;
5701 * _inside_ group (just before echo 1), it works.
5703 * I conclude it means we don't need to pass active traps here.
5705 *pp++ = (char *) "-c";
5708 while (*++builtin_argv)
5709 *pp++ = *builtin_argv;
5710 *pp++ = (char *) "";
5715 /* *pp = NULL; - is already there */
5719 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5720 /* Don't propagate SIG_IGN to the child */
5721 if (SPECIAL_JOBSTOP_SIGS != 0)
5722 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5723 execve(bb_busybox_exec_path, argv, pp);
5724 /* Fallback. Useful for init=/bin/hush usage etc */
5725 if (argv[0][0] == '/')
5726 execve(argv[0], argv, pp);
5727 xfunc_error_retval = 127;
5728 bb_error_msg_and_die("can't re-execute the shell");
5730 #endif /* !BB_MMU */
5733 static int run_and_free_list(struct pipe *pi);
5735 /* Executing from string: eval, sh -c '...'
5736 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5737 * end_trigger controls how often we stop parsing
5738 * NUL: parse all, execute, return
5739 * ';': parse till ';' or newline, execute, repeat till EOF
5741 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5743 /* Why we need empty flag?
5744 * An obscure corner case "false; ``; echo $?":
5745 * empty command in `` should still set $? to 0.
5746 * But we can't just set $? to 0 at the start,
5747 * this breaks "false; echo `echo $?`" case.
5751 struct pipe *pipe_list;
5753 #if ENABLE_HUSH_INTERACTIVE
5754 if (end_trigger == ';')
5755 inp->promptmode = 0; /* PS1 */
5757 pipe_list = parse_stream(NULL, inp, end_trigger);
5758 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5759 /* If we are in "big" script
5760 * (not in `cmd` or something similar)...
5762 if (pipe_list == ERR_PTR && end_trigger == ';') {
5763 /* Discard cached input (rest of line) */
5764 int ch = inp->last_char;
5765 while (ch != EOF && ch != '\n') {
5766 //bb_error_msg("Discarded:'%c'", ch);
5771 /* This stream isn't empty */
5775 if (!pipe_list && empty)
5776 G.last_exitcode = 0;
5779 debug_print_tree(pipe_list, 0);
5780 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5781 run_and_free_list(pipe_list);
5783 #if ENABLE_HUSH_FUNCTIONS
5784 if (G.flag_return_in_progress == 1)
5790 static void parse_and_run_string(const char *s)
5792 struct in_str input;
5793 setup_string_in_str(&input, s);
5794 parse_and_run_stream(&input, '\0');
5797 static void parse_and_run_file(FILE *f)
5799 struct in_str input;
5800 setup_file_in_str(&input, f);
5801 parse_and_run_stream(&input, ';');
5804 #if ENABLE_HUSH_TICK
5805 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5810 char **to_free = NULL;
5814 pid = BB_MMU ? xfork() : xvfork();
5815 if (pid == 0) { /* child */
5816 disable_restore_tty_pgrp_on_exit();
5817 /* Process substitution is not considered to be usual
5818 * 'command execution'.
5819 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5826 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5827 close(channel[0]); /* NB: close _first_, then move fd! */
5828 xmove_fd(channel[1], 1);
5829 /* Prevent it from trying to handle ctrl-z etc */
5830 IF_HUSH_JOB(G.run_list_level = 1;)
5831 /* Awful hack for `trap` or $(trap).
5833 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5834 * contains an example where "trap" is executed in a subshell:
5836 * save_traps=$(trap)
5838 * eval "$save_traps"
5840 * Standard does not say that "trap" in subshell shall print
5841 * parent shell's traps. It only says that its output
5842 * must have suitable form, but then, in the above example
5843 * (which is not supposed to be normative), it implies that.
5845 * bash (and probably other shell) does implement it
5846 * (traps are reset to defaults, but "trap" still shows them),
5847 * but as a result, "trap" logic is hopelessly messed up:
5850 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5851 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5852 * # true | trap <--- trap is in subshell - no output (ditto)
5853 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5854 * trap -- 'echo Ho' SIGWINCH
5855 * # echo `(trap)` <--- in subshell in subshell - output
5856 * trap -- 'echo Ho' SIGWINCH
5857 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5858 * trap -- 'echo Ho' SIGWINCH
5860 * The rules when to forget and when to not forget traps
5861 * get really complex and nonsensical.
5863 * Our solution: ONLY bare $(trap) or `trap` is special.
5865 s = skip_whitespace(s);
5866 if (strncmp(s, "trap", 4) == 0
5867 && skip_whitespace(s + 4)[0] == '\0'
5869 static const char *const argv[] = { NULL, NULL };
5870 builtin_trap((char**)argv);
5871 exit(0); /* not _exit() - we need to fflush */
5874 reset_traps_to_defaults();
5875 parse_and_run_string(s);
5876 _exit(G.last_exitcode);
5878 /* We re-execute after vfork on NOMMU. This makes this script safe:
5879 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5880 * huge=`cat BIG` # was blocking here forever
5883 re_execute_shell(&to_free,
5893 # if ENABLE_HUSH_FAST
5895 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5896 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5897 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5899 enable_restore_tty_pgrp_on_exit();
5904 close_on_exec_on(channel[0]);
5905 return xfdopen_for_read(channel[0]);
5908 /* Return code is exit status of the process that is run. */
5909 static int process_command_subs(o_string *dest, const char *s)
5912 struct in_str pipe_str;
5914 int status, ch, eol_cnt;
5916 fp = generate_stream_from_string(s, &pid);
5918 /* Now send results of command back into original context */
5919 setup_file_in_str(&pipe_str, fp);
5921 while ((ch = i_getch(&pipe_str)) != EOF) {
5927 o_addchr(dest, '\n');
5930 o_addQchr(dest, ch);
5933 debug_printf("done reading from `cmd` pipe, closing it\n");
5935 /* We need to extract exitcode. Test case
5936 * "true; echo `sleep 1; false` $?"
5938 safe_waitpid(pid, &status, 0);
5939 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5940 return WEXITSTATUS(status);
5942 #endif /* ENABLE_HUSH_TICK */
5945 static void setup_heredoc(struct redir_struct *redir)
5947 struct fd_pair pair;
5950 /* the _body_ of heredoc (misleading field name) */
5951 const char *heredoc = redir->rd_filename;
5958 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5959 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5963 len = strlen(heredoc);
5965 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5967 xmove_fd(pair.rd, redir->rd_fd);
5969 /* Try writing without forking. Newer kernels have
5970 * dynamically growing pipes. Must use non-blocking write! */
5973 written = write(pair.wr, heredoc, len);
5984 ndelay_off(pair.wr);
5986 /* Okay, pipe buffer was not big enough */
5987 /* Note: we must not create a stray child (bastard? :)
5988 * for the unsuspecting parent process. Child creates a grandchild
5989 * and exits before parent execs the process which consumes heredoc
5990 * (that exec happens after we return from this function) */
5997 disable_restore_tty_pgrp_on_exit();
5998 pid = BB_MMU ? xfork() : xvfork();
6002 close(redir->rd_fd); /* read side of the pipe */
6004 full_write(pair.wr, heredoc, len); /* may loop or block */
6007 /* Delegate blocking writes to another process */
6008 xmove_fd(pair.wr, STDOUT_FILENO);
6009 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6013 #if ENABLE_HUSH_FAST
6015 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6017 enable_restore_tty_pgrp_on_exit();
6023 wait(NULL); /* wait till child has died */
6026 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6027 * and stderr if they are redirected. */
6028 static int setup_redirects(struct command *prog, int squirrel[])
6031 struct redir_struct *redir;
6033 for (redir = prog->redirects; redir; redir = redir->next) {
6034 if (redir->rd_type == REDIRECT_HEREDOC2) {
6035 /* rd_fd<<HERE case */
6036 if (squirrel && redir->rd_fd < 3
6037 && squirrel[redir->rd_fd] < 0
6039 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6041 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6043 debug_printf_parse("set heredoc '%s'\n",
6044 redir->rd_filename);
6045 setup_heredoc(redir);
6049 if (redir->rd_dup == REDIRFD_TO_FILE) {
6050 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6052 if (redir->rd_filename == NULL) {
6053 /* Something went wrong in the parse.
6054 * Pretend it didn't happen */
6055 bb_error_msg("bug in redirect parse");
6058 mode = redir_table[redir->rd_type].mode;
6059 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6060 openfd = open_or_warn(p, mode);
6063 /* this could get lost if stderr has been redirected, but
6064 * bash and ash both lose it as well (though zsh doesn't!) */
6065 //what the above comment tries to say?
6069 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6070 openfd = redir->rd_dup;
6073 if (openfd != redir->rd_fd) {
6074 if (squirrel && redir->rd_fd < 3
6075 && squirrel[redir->rd_fd] < 0
6077 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6079 if (openfd == REDIRFD_CLOSE) {
6080 /* "n>-" means "close me" */
6081 close(redir->rd_fd);
6083 xdup2(openfd, redir->rd_fd);
6084 if (redir->rd_dup == REDIRFD_TO_FILE)
6092 static void restore_redirects(int squirrel[])
6095 for (i = 0; i < 3; i++) {
6098 /* We simply die on error */
6104 static char *find_in_path(const char *arg)
6107 const char *PATH = get_local_var_value("PATH");
6113 const char *end = strchrnul(PATH, ':');
6114 int sz = end - PATH; /* must be int! */
6118 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6120 /* We have xxx::yyyy in $PATH,
6121 * it means "use current dir" */
6124 if (access(ret, F_OK) == 0)
6137 static const struct built_in_command *find_builtin_helper(const char *name,
6138 const struct built_in_command *x,
6139 const struct built_in_command *end)
6142 if (strcmp(name, x->b_cmd) != 0) {
6146 debug_printf_exec("found builtin '%s'\n", name);
6151 static const struct built_in_command *find_builtin1(const char *name)
6153 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6155 static const struct built_in_command *find_builtin(const char *name)
6157 const struct built_in_command *x = find_builtin1(name);
6160 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6163 #if ENABLE_HUSH_FUNCTIONS
6164 static struct function **find_function_slot(const char *name)
6166 struct function **funcpp = &G.top_func;
6168 if (strcmp(name, (*funcpp)->name) == 0) {
6171 funcpp = &(*funcpp)->next;
6176 static const struct function *find_function(const char *name)
6178 const struct function *funcp = *find_function_slot(name);
6180 debug_printf_exec("found function '%s'\n", name);
6184 /* Note: takes ownership on name ptr */
6185 static struct function *new_function(char *name)
6187 struct function **funcpp = find_function_slot(name);
6188 struct function *funcp = *funcpp;
6190 if (funcp != NULL) {
6191 struct command *cmd = funcp->parent_cmd;
6192 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6194 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6196 /* Note: if !funcp->body, do not free body_as_string!
6197 * This is a special case of "-F name body" function:
6198 * body_as_string was not malloced! */
6200 free_pipe_list(funcp->body);
6202 free(funcp->body_as_string);
6206 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6207 cmd->argv[0] = funcp->name;
6208 cmd->group = funcp->body;
6210 cmd->group_as_string = funcp->body_as_string;
6214 debug_printf_exec("remembering new function '%s'\n", name);
6215 funcp = *funcpp = xzalloc(sizeof(*funcp));
6216 /*funcp->next = NULL;*/
6223 static void unset_func(const char *name)
6225 struct function **funcpp = find_function_slot(name);
6226 struct function *funcp = *funcpp;
6228 if (funcp != NULL) {
6229 debug_printf_exec("freeing function '%s'\n", funcp->name);
6230 *funcpp = funcp->next;
6231 /* funcp is unlinked now, deleting it.
6232 * Note: if !funcp->body, the function was created by
6233 * "-F name body", do not free ->body_as_string
6234 * and ->name as they were not malloced. */
6236 free_pipe_list(funcp->body);
6239 free(funcp->body_as_string);
6247 #define exec_function(to_free, funcp, argv) \
6248 exec_function(funcp, argv)
6250 static void exec_function(char ***to_free,
6251 const struct function *funcp,
6252 char **argv) NORETURN;
6253 static void exec_function(char ***to_free,
6254 const struct function *funcp,
6260 argv[0] = G.global_argv[0];
6261 G.global_argv = argv;
6265 /* On MMU, funcp->body is always non-NULL */
6266 n = run_list(funcp->body);
6270 re_execute_shell(to_free,
6271 funcp->body_as_string,
6278 static int run_function(const struct function *funcp, char **argv)
6284 save_and_replace_G_args(&sv, argv);
6286 /* "we are in function, ok to use return" */
6287 sv_flg = G.flag_return_in_progress;
6288 G.flag_return_in_progress = -1;
6289 # if ENABLE_HUSH_LOCAL
6290 G.func_nest_level++;
6293 /* On MMU, funcp->body is always non-NULL */
6296 /* Function defined by -F */
6297 parse_and_run_string(funcp->body_as_string);
6298 rc = G.last_exitcode;
6302 rc = run_list(funcp->body);
6305 # if ENABLE_HUSH_LOCAL
6307 struct variable *var;
6308 struct variable **var_pp;
6310 var_pp = &G.top_var;
6311 while ((var = *var_pp) != NULL) {
6312 if (var->func_nest_level < G.func_nest_level) {
6313 var_pp = &var->next;
6317 if (var->flg_export)
6318 bb_unsetenv(var->varstr);
6319 /* Remove from global list */
6320 *var_pp = var->next;
6326 G.func_nest_level--;
6329 G.flag_return_in_progress = sv_flg;
6331 restore_G_args(&sv, argv);
6335 #endif /* ENABLE_HUSH_FUNCTIONS */
6339 #define exec_builtin(to_free, x, argv) \
6340 exec_builtin(x, argv)
6342 #define exec_builtin(to_free, x, argv) \
6343 exec_builtin(to_free, argv)
6345 static void exec_builtin(char ***to_free,
6346 const struct built_in_command *x,
6347 char **argv) NORETURN;
6348 static void exec_builtin(char ***to_free,
6349 const struct built_in_command *x,
6355 rcode = x->b_function(argv);
6360 /* On NOMMU, we must never block!
6361 * Example: { sleep 99 | read line; } & echo Ok
6363 re_execute_shell(to_free,
6372 static void execvp_or_die(char **argv) NORETURN;
6373 static void execvp_or_die(char **argv)
6375 debug_printf_exec("execing '%s'\n", argv[0]);
6376 /* Don't propagate SIG_IGN to the child */
6377 if (SPECIAL_JOBSTOP_SIGS != 0)
6378 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6379 execvp(argv[0], argv);
6380 bb_perror_msg("can't execute '%s'", argv[0]);
6381 _exit(127); /* bash compat */
6384 #if ENABLE_HUSH_MODE_X
6385 static void dump_cmd_in_x_mode(char **argv)
6387 if (G_x_mode && argv) {
6388 /* We want to output the line in one write op */
6396 len += strlen(argv[n++]) + 1;
6402 p += sprintf(p, " %s", argv[n++]);
6410 # define dump_cmd_in_x_mode(argv) ((void)0)
6414 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6415 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6416 #define pseudo_exec(nommu_save, command, argv_expanded) \
6417 pseudo_exec(command, argv_expanded)
6420 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6422 * Don't exit() here. If you don't exec, use _exit instead.
6423 * The at_exit handlers apparently confuse the calling process,
6424 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6425 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6426 char **argv, int assignment_cnt,
6427 char **argv_expanded) NORETURN;
6428 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6429 char **argv, int assignment_cnt,
6430 char **argv_expanded)
6434 new_env = expand_assignments(argv, assignment_cnt);
6435 dump_cmd_in_x_mode(new_env);
6437 if (!argv[assignment_cnt]) {
6438 /* Case when we are here: ... | var=val | ...
6439 * (note that we do not exit early, i.e., do not optimize out
6440 * expand_assignments(): think about ... | var=`sleep 1` | ...
6442 free_strings(new_env);
6443 _exit(EXIT_SUCCESS);
6447 set_vars_and_save_old(new_env);
6448 free(new_env); /* optional */
6449 /* we can also destroy set_vars_and_save_old's return value,
6452 nommu_save->new_env = new_env;
6453 nommu_save->old_vars = set_vars_and_save_old(new_env);
6456 if (argv_expanded) {
6457 argv = argv_expanded;
6459 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6461 nommu_save->argv = argv;
6464 dump_cmd_in_x_mode(argv);
6466 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6467 if (strchr(argv[0], '/') != NULL)
6471 /* Check if the command matches any of the builtins.
6472 * Depending on context, this might be redundant. But it's
6473 * easier to waste a few CPU cycles than it is to figure out
6474 * if this is one of those cases.
6477 /* On NOMMU, it is more expensive to re-execute shell
6478 * just in order to run echo or test builtin.
6479 * It's better to skip it here and run corresponding
6480 * non-builtin later. */
6481 const struct built_in_command *x;
6482 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6484 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6487 #if ENABLE_HUSH_FUNCTIONS
6488 /* Check if the command matches any functions */
6490 const struct function *funcp = find_function(argv[0]);
6492 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6497 #if ENABLE_FEATURE_SH_STANDALONE
6498 /* Check if the command matches any busybox applets */
6500 int a = find_applet_by_name(argv[0]);
6502 # if BB_MMU /* see above why on NOMMU it is not allowed */
6503 if (APPLET_IS_NOEXEC(a)) {
6504 debug_printf_exec("running applet '%s'\n", argv[0]);
6505 run_applet_no_and_exit(a, argv);
6508 /* Re-exec ourselves */
6509 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6510 /* Don't propagate SIG_IGN to the child */
6511 if (SPECIAL_JOBSTOP_SIGS != 0)
6512 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6513 execv(bb_busybox_exec_path, argv);
6514 /* If they called chroot or otherwise made the binary no longer
6515 * executable, fall through */
6520 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6523 execvp_or_die(argv);
6526 /* Called after [v]fork() in run_pipe
6528 static void pseudo_exec(nommu_save_t *nommu_save,
6529 struct command *command,
6530 char **argv_expanded) NORETURN;
6531 static void pseudo_exec(nommu_save_t *nommu_save,
6532 struct command *command,
6533 char **argv_expanded)
6535 if (command->argv) {
6536 pseudo_exec_argv(nommu_save, command->argv,
6537 command->assignment_cnt, argv_expanded);
6540 if (command->group) {
6541 /* Cases when we are here:
6544 * ... | ( list ) | ...
6545 * ... | { list } | ...
6549 debug_printf_exec("pseudo_exec: run_list\n");
6550 reset_traps_to_defaults();
6551 rcode = run_list(command->group);
6552 /* OK to leak memory by not calling free_pipe_list,
6553 * since this process is about to exit */
6556 re_execute_shell(&nommu_save->argv_from_re_execing,
6557 command->group_as_string,
6564 /* Case when we are here: ... | >file */
6565 debug_printf_exec("pseudo_exec'ed null command\n");
6566 _exit(EXIT_SUCCESS);
6570 static const char *get_cmdtext(struct pipe *pi)
6576 /* This is subtle. ->cmdtext is created only on first backgrounding.
6577 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6578 * On subsequent bg argv is trashed, but we won't use it */
6581 argv = pi->cmds[0].argv;
6582 if (!argv || !argv[0]) {
6583 pi->cmdtext = xzalloc(1);
6589 len += strlen(*argv) + 1;
6593 argv = pi->cmds[0].argv;
6595 len = strlen(*argv);
6596 memcpy(p, *argv, len);
6604 static void insert_bg_job(struct pipe *pi)
6606 struct pipe *job, **jobp;
6609 /* Linear search for the ID of the job to use */
6611 for (job = G.job_list; job; job = job->next)
6612 if (job->jobid >= pi->jobid)
6613 pi->jobid = job->jobid + 1;
6615 /* Add job to the list of running jobs */
6617 while ((job = *jobp) != NULL)
6619 job = *jobp = xmalloc(sizeof(*job));
6621 *job = *pi; /* physical copy */
6623 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6624 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6625 for (i = 0; i < pi->num_cmds; i++) {
6626 job->cmds[i].pid = pi->cmds[i].pid;
6627 /* all other fields are not used and stay zero */
6629 job->cmdtext = xstrdup(get_cmdtext(pi));
6631 if (G_interactive_fd)
6632 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6633 G.last_jobid = job->jobid;
6636 static void remove_bg_job(struct pipe *pi)
6638 struct pipe *prev_pipe;
6640 if (pi == G.job_list) {
6641 G.job_list = pi->next;
6643 prev_pipe = G.job_list;
6644 while (prev_pipe->next != pi)
6645 prev_pipe = prev_pipe->next;
6646 prev_pipe->next = pi->next;
6649 G.last_jobid = G.job_list->jobid;
6654 /* Remove a backgrounded job */
6655 static void delete_finished_bg_job(struct pipe *pi)
6662 /* Check to see if any processes have exited -- if they
6663 * have, figure out why and see if a job has completed */
6664 static int checkjobs(struct pipe *fg_pipe)
6674 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6676 attributes = WUNTRACED;
6677 if (fg_pipe == NULL)
6678 attributes |= WNOHANG;
6681 #if ENABLE_HUSH_FAST
6682 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6683 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6684 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6685 /* There was neither fork nor SIGCHLD since last waitpid */
6686 /* Avoid doing waitpid syscall if possible */
6687 if (!G.we_have_children) {
6691 if (fg_pipe == NULL) { /* is WNOHANG set? */
6692 /* We have children, but they did not exit
6693 * or stop yet (we saw no SIGCHLD) */
6696 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6700 /* Do we do this right?
6701 * bash-3.00# sleep 20 | false
6703 * [3]+ Stopped sleep 20 | false
6704 * bash-3.00# echo $?
6705 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6706 * [hush 1.14.0: yes we do it right]
6713 #if ENABLE_HUSH_FAST
6714 i = G.count_SIGCHLD;
6716 childpid = waitpid(-1, &status, attributes);
6717 if (childpid <= 0) {
6718 if (childpid && errno != ECHILD)
6719 bb_perror_msg("waitpid");
6720 #if ENABLE_HUSH_FAST
6721 else { /* Until next SIGCHLD, waitpid's are useless */
6722 G.we_have_children = (childpid == 0);
6723 G.handled_SIGCHLD = i;
6724 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6729 dead = WIFEXITED(status) || WIFSIGNALED(status);
6732 if (WIFSTOPPED(status))
6733 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6734 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6735 if (WIFSIGNALED(status))
6736 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6737 childpid, WTERMSIG(status), WEXITSTATUS(status));
6738 if (WIFEXITED(status))
6739 debug_printf_jobs("pid %d exited, exitcode %d\n",
6740 childpid, WEXITSTATUS(status));
6742 /* Were we asked to wait for fg pipe? */
6744 i = fg_pipe->num_cmds;
6746 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6747 if (fg_pipe->cmds[i].pid != childpid)
6751 fg_pipe->cmds[i].pid = 0;
6752 fg_pipe->alive_cmds--;
6753 ex = WEXITSTATUS(status);
6754 /* bash prints killer signal's name for *last*
6755 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6756 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6758 if (WIFSIGNALED(status)) {
6759 int sig = WTERMSIG(status);
6760 if (i == fg_pipe->num_cmds-1)
6761 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6762 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6763 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6764 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6765 * Maybe we need to use sig | 128? */
6768 fg_pipe->cmds[i].cmd_exitcode = ex;
6770 fg_pipe->cmds[i].is_stopped = 1;
6771 fg_pipe->stopped_cmds++;
6773 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6774 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6775 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6776 /* All processes in fg pipe have exited or stopped */
6777 i = fg_pipe->num_cmds;
6779 rcode = fg_pipe->cmds[i].cmd_exitcode;
6780 /* usually last process gives overall exitstatus,
6781 * but with "set -o pipefail", last *failed* process does */
6782 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6785 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6786 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6787 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6788 * and "killall -STOP cat" */
6789 if (G_interactive_fd) {
6791 if (fg_pipe->alive_cmds != 0)
6792 insert_bg_job(fg_pipe);
6796 if (fg_pipe->alive_cmds == 0)
6799 /* There are still running processes in the fg pipe */
6800 goto wait_more; /* do waitpid again */
6802 /* it wasnt fg_pipe, look for process in bg pipes */
6806 /* We asked to wait for bg or orphaned children */
6807 /* No need to remember exitcode in this case */
6808 for (pi = G.job_list; pi; pi = pi->next) {
6809 for (i = 0; i < pi->num_cmds; i++) {
6810 if (pi->cmds[i].pid == childpid)
6811 goto found_pi_and_prognum;
6814 /* Happens when shell is used as init process (init=/bin/sh) */
6815 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6816 continue; /* do waitpid again */
6818 found_pi_and_prognum:
6821 pi->cmds[i].pid = 0;
6823 if (!pi->alive_cmds) {
6824 if (G_interactive_fd)
6825 printf(JOB_STATUS_FORMAT, pi->jobid,
6826 "Done", pi->cmdtext);
6827 delete_finished_bg_job(pi);
6831 pi->cmds[i].is_stopped = 1;
6835 } /* while (waitpid succeeds)... */
6841 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6844 int rcode = checkjobs(fg_pipe);
6845 if (G_saved_tty_pgrp) {
6846 /* Job finished, move the shell to the foreground */
6847 p = getpgrp(); /* our process group id */
6848 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6849 tcsetpgrp(G_interactive_fd, p);
6855 /* Start all the jobs, but don't wait for anything to finish.
6858 * Return code is normally -1, when the caller has to wait for children
6859 * to finish to determine the exit status of the pipe. If the pipe
6860 * is a simple builtin command, however, the action is done by the
6861 * time run_pipe returns, and the exit code is provided as the
6864 * Returns -1 only if started some children. IOW: we have to
6865 * mask out retvals of builtins etc with 0xff!
6867 * The only case when we do not need to [v]fork is when the pipe
6868 * is single, non-backgrounded, non-subshell command. Examples:
6869 * cmd ; ... { list } ; ...
6870 * cmd && ... { list } && ...
6871 * cmd || ... { list } || ...
6872 * If it is, then we can run cmd as a builtin, NOFORK,
6873 * or (if SH_STANDALONE) an applet, and we can run the { list }
6874 * with run_list. If it isn't one of these, we fork and exec cmd.
6876 * Cases when we must fork:
6877 * non-single: cmd | cmd
6878 * backgrounded: cmd & { list } &
6879 * subshell: ( list ) [&]
6881 #if !ENABLE_HUSH_MODE_X
6882 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6883 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6885 static int redirect_and_varexp_helper(char ***new_env_p,
6886 struct variable **old_vars_p,
6887 struct command *command,
6889 char **argv_expanded)
6891 /* setup_redirects acts on file descriptors, not FILEs.
6892 * This is perfect for work that comes after exec().
6893 * Is it really safe for inline use? Experimentally,
6894 * things seem to work. */
6895 int rcode = setup_redirects(command, squirrel);
6897 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6898 *new_env_p = new_env;
6899 dump_cmd_in_x_mode(new_env);
6900 dump_cmd_in_x_mode(argv_expanded);
6902 *old_vars_p = set_vars_and_save_old(new_env);
6906 static NOINLINE int run_pipe(struct pipe *pi)
6908 static const char *const null_ptr = NULL;
6912 struct command *command;
6913 char **argv_expanded;
6915 /* it is not always needed, but we aim to smaller code */
6916 int squirrel[] = { -1, -1, -1 };
6919 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6922 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6923 * Result should be 3 lines: q w e, qwe, q w e
6925 G.ifs = get_local_var_value("IFS");
6929 IF_HUSH_JOB(pi->pgrp = -1;)
6930 pi->stopped_cmds = 0;
6931 command = &pi->cmds[0];
6932 argv_expanded = NULL;
6934 if (pi->num_cmds != 1
6935 || pi->followup == PIPE_BG
6936 || command->cmd_type == CMD_SUBSHELL
6943 debug_printf_exec(": group:%p argv:'%s'\n",
6944 command->group, command->argv ? command->argv[0] : "NONE");
6946 if (command->group) {
6947 #if ENABLE_HUSH_FUNCTIONS
6948 if (command->cmd_type == CMD_FUNCDEF) {
6949 /* "executing" func () { list } */
6950 struct function *funcp;
6952 funcp = new_function(command->argv[0]);
6953 /* funcp->name is already set to argv[0] */
6954 funcp->body = command->group;
6956 funcp->body_as_string = command->group_as_string;
6957 command->group_as_string = NULL;
6959 command->group = NULL;
6960 command->argv[0] = NULL;
6961 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6962 funcp->parent_cmd = command;
6963 command->child_func = funcp;
6965 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6967 return EXIT_SUCCESS;
6971 debug_printf("non-subshell group\n");
6972 rcode = 1; /* exitcode if redir failed */
6973 if (setup_redirects(command, squirrel) == 0) {
6974 debug_printf_exec(": run_list\n");
6975 rcode = run_list(command->group) & 0xff;
6977 restore_redirects(squirrel);
6978 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6980 debug_printf_exec("run_pipe: return %d\n", rcode);
6984 argv = command->argv ? command->argv : (char **) &null_ptr;
6986 const struct built_in_command *x;
6987 #if ENABLE_HUSH_FUNCTIONS
6988 const struct function *funcp;
6992 char **new_env = NULL;
6993 struct variable *old_vars = NULL;
6995 if (argv[command->assignment_cnt] == NULL) {
6996 /* Assignments, but no command */
6997 /* Ensure redirects take effect (that is, create files).
6998 * Try "a=t >file" */
6999 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7000 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7001 /* Set shell variables */
7005 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7006 /* Do we need to flag set_local_var() errors?
7007 * "assignment to readonly var" and "putenv error"
7012 /* Redirect error sets $? to 1. Otherwise,
7013 * if evaluating assignment value set $?, retain it.
7014 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7016 rcode = G.last_exitcode;
7017 /* Exit, _skipping_ variable restoring code: */
7018 goto clean_up_and_ret0;
7020 #else /* Older, bigger, but more correct code */
7022 rcode = setup_redirects(command, squirrel);
7023 restore_redirects(squirrel);
7024 /* Set shell variables */
7026 bb_putchar_stderr('+');
7028 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7030 fprintf(stderr, " %s", p);
7031 debug_printf_exec("set shell var:'%s'->'%s'\n",
7033 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7034 /* Do we need to flag set_local_var() errors?
7035 * "assignment to readonly var" and "putenv error"
7040 bb_putchar_stderr('\n');
7041 /* Redirect error sets $? to 1. Otherwise,
7042 * if evaluating assignment value set $?, retain it.
7043 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7045 rcode = G.last_exitcode;
7046 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7048 debug_printf_exec("run_pipe: return %d\n", rcode);
7053 /* Expand the rest into (possibly) many strings each */
7054 #if ENABLE_HUSH_BASH_COMPAT
7055 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7056 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7060 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7063 /* if someone gives us an empty string: `cmd with empty output` */
7064 if (!argv_expanded[0]) {
7065 free(argv_expanded);
7067 return G.last_exitcode;
7070 x = find_builtin(argv_expanded[0]);
7071 #if ENABLE_HUSH_FUNCTIONS
7074 funcp = find_function(argv_expanded[0]);
7078 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7079 debug_printf("exec with redirects only\n");
7080 rcode = setup_redirects(command, NULL);
7081 goto clean_up_and_ret1;
7084 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7087 debug_printf_exec(": builtin '%s' '%s'...\n",
7088 x->b_cmd, argv_expanded[1]);
7090 rcode = x->b_function(argv_expanded) & 0xff;
7093 #if ENABLE_HUSH_FUNCTIONS
7095 # if ENABLE_HUSH_LOCAL
7096 struct variable **sv;
7097 sv = G.shadowed_vars_pp;
7098 G.shadowed_vars_pp = &old_vars;
7100 debug_printf_exec(": function '%s' '%s'...\n",
7101 funcp->name, argv_expanded[1]);
7102 rcode = run_function(funcp, argv_expanded) & 0xff;
7103 # if ENABLE_HUSH_LOCAL
7104 G.shadowed_vars_pp = sv;
7110 unset_vars(new_env);
7112 /* clean_up_and_ret0: */
7113 restore_redirects(squirrel);
7115 free(argv_expanded);
7116 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7118 debug_printf_exec("run_pipe return %d\n", rcode);
7122 if (ENABLE_FEATURE_SH_NOFORK) {
7123 int n = find_applet_by_name(argv_expanded[0]);
7124 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7125 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7127 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7128 argv_expanded[0], argv_expanded[1]);
7129 rcode = run_nofork_applet(n, argv_expanded);
7131 goto clean_up_and_ret;
7134 /* It is neither builtin nor applet. We must fork. */
7138 /* NB: argv_expanded may already be created, and that
7139 * might include `cmd` runs! Do not rerun it! We *must*
7140 * use argv_expanded if it's non-NULL */
7142 /* Going to fork a child per each pipe member */
7147 while (cmd_no < pi->num_cmds) {
7148 struct fd_pair pipefds;
7150 volatile nommu_save_t nommu_save;
7151 nommu_save.new_env = NULL;
7152 nommu_save.old_vars = NULL;
7153 nommu_save.argv = NULL;
7154 nommu_save.argv_from_re_execing = NULL;
7156 command = &pi->cmds[cmd_no];
7158 if (command->argv) {
7159 debug_printf_exec(": pipe member '%s' '%s'...\n",
7160 command->argv[0], command->argv[1]);
7162 debug_printf_exec(": pipe member with no argv\n");
7165 /* pipes are inserted between pairs of commands */
7168 if (cmd_no < pi->num_cmds)
7169 xpiped_pair(pipefds);
7171 command->pid = BB_MMU ? fork() : vfork();
7172 if (!command->pid) { /* child */
7174 disable_restore_tty_pgrp_on_exit();
7175 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7177 /* Every child adds itself to new process group
7178 * with pgid == pid_of_first_child_in_pipe */
7179 if (G.run_list_level == 1 && G_interactive_fd) {
7182 if (pgrp < 0) /* true for 1st process only */
7184 if (setpgid(0, pgrp) == 0
7185 && pi->followup != PIPE_BG
7186 && G_saved_tty_pgrp /* we have ctty */
7188 /* We do it in *every* child, not just first,
7190 tcsetpgrp(G_interactive_fd, pgrp);
7194 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7195 /* 1st cmd in backgrounded pipe
7196 * should have its stdin /dev/null'ed */
7198 if (open(bb_dev_null, O_RDONLY))
7199 xopen("/", O_RDONLY);
7201 xmove_fd(next_infd, 0);
7203 xmove_fd(pipefds.wr, 1);
7206 /* Like bash, explicit redirects override pipes,
7207 * and the pipe fd is available for dup'ing. */
7208 if (setup_redirects(command, NULL))
7211 /* Stores to nommu_save list of env vars putenv'ed
7212 * (NOMMU, on MMU we don't need that) */
7213 /* cast away volatility... */
7214 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7215 /* pseudo_exec() does not return */
7218 /* parent or error */
7219 #if ENABLE_HUSH_FAST
7221 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7223 enable_restore_tty_pgrp_on_exit();
7225 /* Clean up after vforked child */
7226 free(nommu_save.argv);
7227 free(nommu_save.argv_from_re_execing);
7228 unset_vars(nommu_save.new_env);
7229 add_vars(nommu_save.old_vars);
7231 free(argv_expanded);
7232 argv_expanded = NULL;
7233 if (command->pid < 0) { /* [v]fork failed */
7234 /* Clearly indicate, was it fork or vfork */
7235 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7239 /* Second and next children need to know pid of first one */
7241 pi->pgrp = command->pid;
7247 if (cmd_no < pi->num_cmds)
7249 /* Pass read (output) pipe end to next iteration */
7250 next_infd = pipefds.rd;
7253 if (!pi->alive_cmds) {
7255 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7260 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7264 /* NB: called by pseudo_exec, and therefore must not modify any
7265 * global data until exec/_exit (we can be a child after vfork!) */
7266 static int run_list(struct pipe *pi)
7268 #if ENABLE_HUSH_CASE
7269 char *case_word = NULL;
7271 #if ENABLE_HUSH_LOOPS
7272 struct pipe *loop_top = NULL;
7273 char **for_lcur = NULL;
7274 char **for_list = NULL;
7276 smallint last_followup;
7278 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7279 smalluint cond_code = 0;
7281 enum { cond_code = 0 };
7284 smallint rword; /* RES_foo */
7285 smallint last_rword; /* ditto */
7288 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7291 #if ENABLE_HUSH_LOOPS
7292 /* Check syntax for "for" */
7295 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7296 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7298 /* current word is FOR or IN (BOLD in comments below) */
7299 if (cpipe->next == NULL) {
7300 syntax_error("malformed for");
7302 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7305 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7306 if (cpipe->next->res_word == RES_DO)
7308 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7309 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7310 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7312 syntax_error("malformed for");
7314 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7321 /* Past this point, all code paths should jump to ret: label
7322 * in order to return, no direct "return" statements please.
7323 * This helps to ensure that no memory is leaked. */
7331 last_rword = RES_XXXX;
7333 last_followup = PIPE_SEQ;
7334 rcode = G.last_exitcode;
7336 /* Go through list of pipes, (maybe) executing them. */
7337 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7341 IF_HAS_KEYWORDS(rword = pi->res_word;)
7342 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7343 rword, cond_code, last_rword);
7344 #if ENABLE_HUSH_LOOPS
7345 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7346 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7348 /* start of a loop: remember where loop starts */
7353 /* Still in the same "if...", "then..." or "do..." branch? */
7354 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7355 if ((rcode == 0 && last_followup == PIPE_OR)
7356 || (rcode != 0 && last_followup == PIPE_AND)
7358 /* It is "<true> || CMD" or "<false> && CMD"
7359 * and we should not execute CMD */
7360 debug_printf_exec("skipped cmd because of || or &&\n");
7361 last_followup = pi->followup;
7365 last_followup = pi->followup;
7366 IF_HAS_KEYWORDS(last_rword = rword;)
7369 if (rword == RES_THEN) {
7370 /* if false; then ... fi has exitcode 0! */
7371 G.last_exitcode = rcode = EXIT_SUCCESS;
7372 /* "if <false> THEN cmd": skip cmd */
7376 if (rword == RES_ELSE || rword == RES_ELIF) {
7377 /* "if <true> then ... ELSE/ELIF cmd":
7378 * skip cmd and all following ones */
7383 #if ENABLE_HUSH_LOOPS
7384 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7386 /* first loop through for */
7388 static const char encoded_dollar_at[] ALIGN1 = {
7389 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7390 }; /* encoded representation of "$@" */
7391 static const char *const encoded_dollar_at_argv[] = {
7392 encoded_dollar_at, NULL
7393 }; /* argv list with one element: "$@" */
7396 vals = (char**)encoded_dollar_at_argv;
7397 if (pi->next->res_word == RES_IN) {
7398 /* if no variable values after "in" we skip "for" */
7399 if (!pi->next->cmds[0].argv) {
7400 G.last_exitcode = rcode = EXIT_SUCCESS;
7401 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7404 vals = pi->next->cmds[0].argv;
7405 } /* else: "for var; do..." -> assume "$@" list */
7406 /* create list of variable values */
7407 debug_print_strings("for_list made from", vals);
7408 for_list = expand_strvec_to_strvec(vals);
7409 for_lcur = for_list;
7410 debug_print_strings("for_list", for_list);
7413 /* "for" loop is over, clean up */
7419 /* Insert next value from for_lcur */
7420 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7421 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7424 if (rword == RES_IN) {
7425 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7427 if (rword == RES_DONE) {
7428 continue; /* "done" has no cmds too */
7431 #if ENABLE_HUSH_CASE
7432 if (rword == RES_CASE) {
7433 case_word = expand_strvec_to_string(pi->cmds->argv);
7436 if (rword == RES_MATCH) {
7439 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7441 /* all prev words didn't match, does this one match? */
7442 argv = pi->cmds->argv;
7444 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7445 /* TODO: which FNM_xxx flags to use? */
7446 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7448 if (cond_code == 0) { /* match! we will execute this branch */
7449 free(case_word); /* make future "word)" stop */
7457 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7459 continue; /* not matched yet, skip this pipe */
7462 /* Just pressing <enter> in shell should check for jobs.
7463 * OTOH, in non-interactive shell this is useless
7464 * and only leads to extra job checks */
7465 if (pi->num_cmds == 0) {
7466 if (G_interactive_fd)
7467 goto check_jobs_and_continue;
7471 /* After analyzing all keywords and conditions, we decided
7472 * to execute this pipe. NB: have to do checkjobs(NULL)
7473 * after run_pipe to collect any background children,
7474 * even if list execution is to be stopped. */
7475 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7478 #if ENABLE_HUSH_LOOPS
7479 G.flag_break_continue = 0;
7481 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7483 /* We ran a builtin, function, or group.
7484 * rcode is already known
7485 * and we don't need to wait for anything. */
7486 G.last_exitcode = rcode;
7487 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7488 check_and_run_traps();
7489 #if ENABLE_HUSH_LOOPS
7490 /* Was it "break" or "continue"? */
7491 if (G.flag_break_continue) {
7492 smallint fbc = G.flag_break_continue;
7493 /* We might fall into outer *loop*,
7494 * don't want to break it too */
7496 G.depth_break_continue--;
7497 if (G.depth_break_continue == 0)
7498 G.flag_break_continue = 0;
7499 /* else: e.g. "continue 2" should *break* once, *then* continue */
7500 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7501 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7502 goto check_jobs_and_break;
7503 /* "continue": simulate end of loop */
7508 #if ENABLE_HUSH_FUNCTIONS
7509 if (G.flag_return_in_progress == 1) {
7510 /* same as "goto check_jobs_and_break" */
7515 } else if (pi->followup == PIPE_BG) {
7516 /* What does bash do with attempts to background builtins? */
7517 /* even bash 3.2 doesn't do that well with nested bg:
7518 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7519 * I'm NOT treating inner &'s as jobs */
7520 check_and_run_traps();
7522 if (G.run_list_level == 1)
7525 /* Last command's pid goes to $! */
7526 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7527 G.last_exitcode = rcode = EXIT_SUCCESS;
7528 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7531 if (G.run_list_level == 1 && G_interactive_fd) {
7532 /* Waits for completion, then fg's main shell */
7533 rcode = checkjobs_and_fg_shell(pi);
7534 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7535 check_and_run_traps();
7538 { /* This one just waits for completion */
7539 rcode = checkjobs(pi);
7540 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7541 check_and_run_traps();
7543 G.last_exitcode = rcode;
7547 /* Analyze how result affects subsequent commands */
7549 if (rword == RES_IF || rword == RES_ELIF)
7552 #if ENABLE_HUSH_LOOPS
7553 /* Beware of "while false; true; do ..."! */
7555 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7556 /* check for RES_DONE is needed for "while ...; do \n done" case */
7558 if (rword == RES_WHILE) {
7560 /* "while false; do...done" - exitcode 0 */
7561 G.last_exitcode = rcode = EXIT_SUCCESS;
7562 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7563 goto check_jobs_and_break;
7566 if (rword == RES_UNTIL) {
7568 debug_printf_exec(": until expr is true: breaking\n");
7569 check_jobs_and_break:
7577 check_jobs_and_continue:
7584 #if ENABLE_HUSH_LOOPS
7589 #if ENABLE_HUSH_CASE
7593 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7597 /* Select which version we will use */
7598 static int run_and_free_list(struct pipe *pi)
7601 debug_printf_exec("run_and_free_list entered\n");
7602 if (!G.o_opt[OPT_O_NOEXEC]) {
7603 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7604 rcode = run_list(pi);
7606 /* free_pipe_list has the side effect of clearing memory.
7607 * In the long run that function can be merged with run_list,
7608 * but doing that now would hobble the debugging effort. */
7610 debug_printf_exec("run_and_free_list return %d\n", rcode);
7615 static void install_sighandlers(unsigned mask)
7617 sighandler_t old_handler;
7619 while ((mask >>= 1) != 0) {
7623 old_handler = install_sighandler(sig, pick_sighandler(sig));
7624 /* POSIX allows shell to re-enable SIGCHLD
7625 * even if it was SIG_IGN on entry.
7626 * Therefore we skip IGN check for it:
7630 if (old_handler == SIG_IGN) {
7631 /* oops... restore back to IGN, and record this fact */
7632 install_sighandler(sig, old_handler);
7634 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7636 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7641 /* Called a few times only (or even once if "sh -c") */
7642 static void install_special_sighandlers(void)
7646 /* Which signals are shell-special? */
7647 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7648 if (G_interactive_fd) {
7649 mask |= SPECIAL_INTERACTIVE_SIGS;
7650 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7651 mask |= SPECIAL_JOBSTOP_SIGS;
7653 /* Careful, do not re-install handlers we already installed */
7654 if (G.special_sig_mask != mask) {
7655 unsigned diff = mask & ~G.special_sig_mask;
7656 G.special_sig_mask = mask;
7657 install_sighandlers(diff);
7663 /* Set handlers to restore tty pgrp and exit */
7664 static void install_fatal_sighandlers(void)
7668 /* We will restore tty pgrp on these signals */
7670 + (1 << SIGILL ) * HUSH_DEBUG
7671 + (1 << SIGFPE ) * HUSH_DEBUG
7672 + (1 << SIGBUS ) * HUSH_DEBUG
7673 + (1 << SIGSEGV) * HUSH_DEBUG
7674 + (1 << SIGTRAP) * HUSH_DEBUG
7676 /* bash 3.2 seems to handle these just like 'fatal' ones */
7679 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7680 * if we aren't interactive... but in this case
7681 * we never want to restore pgrp on exit, and this fn is not called
7683 /*+ (1 << SIGHUP )*/
7684 /*+ (1 << SIGTERM)*/
7685 /*+ (1 << SIGINT )*/
7687 G_fatal_sig_mask = mask;
7689 install_sighandlers(mask);
7693 static int set_mode(int state, char mode, const char *o_opt)
7698 G.o_opt[OPT_O_NOEXEC] = state;
7701 IF_HUSH_MODE_X(G_x_mode = state;)
7705 /* "set -+o" without parameter.
7706 * in bash, set -o produces this output:
7710 * We always use the second form.
7712 const char *p = o_opt_strings;
7715 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7721 idx = index_in_strings(o_opt_strings, o_opt);
7723 G.o_opt[idx] = state;
7727 return EXIT_FAILURE;
7729 return EXIT_SUCCESS;
7732 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7733 int hush_main(int argc, char **argv)
7736 OPT_login = (1 << 0),
7740 unsigned builtin_argc;
7742 struct variable *cur_var;
7743 struct variable *shell_ver;
7746 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7747 G.last_exitcode = EXIT_SUCCESS;
7748 #if ENABLE_HUSH_FAST
7749 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7752 G.argv0_for_re_execing = argv[0];
7754 /* Deal with HUSH_VERSION */
7755 shell_ver = xzalloc(sizeof(*shell_ver));
7756 shell_ver->flg_export = 1;
7757 shell_ver->flg_read_only = 1;
7758 /* Code which handles ${var<op>...} needs writable values for all variables,
7759 * therefore we xstrdup: */
7760 shell_ver->varstr = xstrdup(hush_version_str);
7761 /* Create shell local variables from the values
7762 * currently living in the environment */
7763 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7764 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7765 G.top_var = shell_ver;
7766 cur_var = G.top_var;
7769 char *value = strchr(*e, '=');
7770 if (value) { /* paranoia */
7771 cur_var->next = xzalloc(sizeof(*cur_var));
7772 cur_var = cur_var->next;
7773 cur_var->varstr = *e;
7774 cur_var->max_len = strlen(*e);
7775 cur_var->flg_export = 1;
7779 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7780 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7781 putenv(shell_ver->varstr);
7784 set_pwd_var(/*exp:*/ 1);
7785 /* bash also exports SHLVL and _,
7786 * and sets (but doesn't export) the following variables:
7788 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7789 * BASH_VERSION='3.2.0(1)-release'
7791 * MACHTYPE=i386-pc-linux-gnu
7793 * HOSTNAME=<xxxxxxxxxx>
7794 * PPID=<NNNNN> - we also do it elsewhere
7805 * PIPESTATUS=([0]="0")
7806 * HISTFILE=/<xxx>/.bash_history
7810 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7812 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7822 #if ENABLE_FEATURE_EDITING
7823 G.line_input_state = new_line_input_t(FOR_SHELL);
7826 /* Initialize some more globals to non-zero values */
7827 cmdedit_update_prompt();
7829 if (setjmp(die_jmp)) {
7830 /* xfunc has failed! die die die */
7831 /* no EXIT traps, this is an escape hatch! */
7833 hush_exit(xfunc_error_retval);
7836 /* Shell is non-interactive at first. We need to call
7837 * install_special_sighandlers() if we are going to execute "sh <script>",
7838 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7839 * If we later decide that we are interactive, we run install_special_sighandlers()
7840 * in order to intercept (more) signals.
7844 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7845 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7848 opt = getopt(argc, argv, "+c:xinsl"
7851 # if ENABLE_HUSH_FUNCTIONS
7861 * sh ... -c 'script'
7862 * sh ... -c 'script' ARG0 [ARG1...]
7863 * On NOMMU, if builtin_argc != 0,
7864 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7865 * "" needs to be replaced with NULL
7866 * and BARGV vector fed to builtin function.
7867 * Note: the form without ARG0 never happens:
7868 * sh ... -c 'builtin' BARGV... ""
7871 G.root_pid = getpid();
7872 G.root_ppid = getppid();
7874 G.global_argv = argv + optind;
7875 G.global_argc = argc - optind;
7877 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7878 const struct built_in_command *x;
7880 install_special_sighandlers();
7881 x = find_builtin(optarg);
7882 if (x) { /* paranoia */
7883 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7884 G.global_argv += builtin_argc;
7885 G.global_argv[-1] = NULL; /* replace "" */
7887 G.last_exitcode = x->b_function(argv + optind - 1);
7891 if (!G.global_argv[0]) {
7892 /* -c 'script' (no params): prevent empty $0 */
7893 G.global_argv--; /* points to argv[i] of 'script' */
7894 G.global_argv[0] = argv[0];
7896 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7897 install_special_sighandlers();
7898 parse_and_run_string(optarg);
7901 /* Well, we cannot just declare interactiveness,
7902 * we have to have some stuff (ctty, etc) */
7903 /* G_interactive_fd++; */
7906 /* "-s" means "read from stdin", but this is how we always
7907 * operate, so simply do nothing here. */
7913 case '<': /* "big heredoc" support */
7914 full_write1_str(optarg);
7917 unsigned long long empty_trap_mask;
7919 G.root_pid = bb_strtou(optarg, &optarg, 16);
7921 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7923 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7925 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7927 builtin_argc = bb_strtou(optarg, &optarg, 16);
7929 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7930 if (empty_trap_mask != 0) {
7932 install_special_sighandlers();
7933 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7934 for (sig = 1; sig < NSIG; sig++) {
7935 if (empty_trap_mask & (1LL << sig)) {
7936 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7937 install_sighandler(sig, SIG_IGN);
7941 # if ENABLE_HUSH_LOOPS
7943 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7949 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7951 # if ENABLE_HUSH_FUNCTIONS
7953 struct function *funcp = new_function(optarg);
7954 /* funcp->name is already set to optarg */
7955 /* funcp->body is set to NULL. It's a special case. */
7956 funcp->body_as_string = argv[optind];
7964 if (set_mode(1, opt, NULL) == 0) /* no error */
7968 fprintf(stderr, "Usage: sh [FILE]...\n"
7969 " or: sh -c command [args]...\n\n");
7975 } /* option parsing loop */
7977 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7978 G.global_argc = argc - (optind - 1);
7979 G.global_argv = argv + (optind - 1);
7980 G.global_argv[0] = argv[0];
7983 G.root_pid = getpid();
7984 G.root_ppid = getppid();
7987 /* If we are login shell... */
7988 if (flags & OPT_login) {
7990 debug_printf("sourcing /etc/profile\n");
7991 input = fopen_for_read("/etc/profile");
7992 if (input != NULL) {
7993 close_on_exec_on(fileno(input));
7994 install_special_sighandlers();
7995 parse_and_run_file(input);
7998 /* bash: after sourcing /etc/profile,
7999 * tries to source (in the given order):
8000 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8001 * stopping on first found. --noprofile turns this off.
8002 * bash also sources ~/.bash_logout on exit.
8003 * If called as sh, skips .bash_XXX files.
8007 if (G.global_argv[1]) {
8010 * "bash <script>" (which is never interactive (unless -i?))
8011 * sources $BASH_ENV here (without scanning $PATH).
8012 * If called as sh, does the same but with $ENV.
8016 debug_printf("running script '%s'\n", G.global_argv[0]);
8017 input = xfopen_for_read(G.global_argv[0]);
8018 close_on_exec_on(fileno(input));
8019 install_special_sighandlers();
8020 parse_and_run_file(input);
8021 #if ENABLE_FEATURE_CLEAN_UP
8027 /* Up to here, shell was non-interactive. Now it may become one.
8028 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8031 /* A shell is interactive if the '-i' flag was given,
8032 * or if all of the following conditions are met:
8034 * no arguments remaining or the -s flag given
8035 * standard input is a terminal
8036 * standard output is a terminal
8037 * Refer to Posix.2, the description of the 'sh' utility.
8040 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8041 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8042 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8043 if (G_saved_tty_pgrp < 0)
8044 G_saved_tty_pgrp = 0;
8046 /* try to dup stdin to high fd#, >= 255 */
8047 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8048 if (G_interactive_fd < 0) {
8049 /* try to dup to any fd */
8050 G_interactive_fd = dup(STDIN_FILENO);
8051 if (G_interactive_fd < 0) {
8053 G_interactive_fd = 0;
8054 G_saved_tty_pgrp = 0;
8057 // TODO: track & disallow any attempts of user
8058 // to (inadvertently) close/redirect G_interactive_fd
8060 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8061 if (G_interactive_fd) {
8062 close_on_exec_on(G_interactive_fd);
8064 if (G_saved_tty_pgrp) {
8065 /* If we were run as 'hush &', sleep until we are
8066 * in the foreground (tty pgrp == our pgrp).
8067 * If we get started under a job aware app (like bash),
8068 * make sure we are now in charge so we don't fight over
8069 * who gets the foreground */
8071 pid_t shell_pgrp = getpgrp();
8072 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8073 if (G_saved_tty_pgrp == shell_pgrp)
8075 /* send TTIN to ourself (should stop us) */
8076 kill(- shell_pgrp, SIGTTIN);
8080 /* Install more signal handlers */
8081 install_special_sighandlers();
8083 if (G_saved_tty_pgrp) {
8084 /* Set other signals to restore saved_tty_pgrp */
8085 install_fatal_sighandlers();
8086 /* Put ourselves in our own process group
8087 * (bash, too, does this only if ctty is available) */
8088 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8089 /* Grab control of the terminal */
8090 tcsetpgrp(G_interactive_fd, getpid());
8092 /* -1 is special - makes xfuncs longjmp, not exit
8093 * (we reset die_sleep = 0 whereever we [v]fork) */
8094 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8096 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8098 const char *hp = get_local_var_value("HISTFILE");
8100 hp = get_local_var_value("HOME");
8102 hp = concat_path_file(hp, ".hush_history");
8107 G.line_input_state->hist_file = hp;
8108 //set_local_var(xasprintf("HISTFILE=%s", ...));
8110 # if ENABLE_FEATURE_SH_HISTFILESIZE
8111 hp = get_local_var_value("HISTFILESIZE");
8112 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8117 install_special_sighandlers();
8119 #elif ENABLE_HUSH_INTERACTIVE
8120 /* No job control compiled in, only prompt/line editing */
8121 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8122 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8123 if (G_interactive_fd < 0) {
8124 /* try to dup to any fd */
8125 G_interactive_fd = dup(STDIN_FILENO);
8126 if (G_interactive_fd < 0)
8128 G_interactive_fd = 0;
8131 if (G_interactive_fd) {
8132 close_on_exec_on(G_interactive_fd);
8134 install_special_sighandlers();
8136 /* We have interactiveness code disabled */
8137 install_special_sighandlers();
8140 * if interactive but not a login shell, sources ~/.bashrc
8141 * (--norc turns this off, --rcfile <file> overrides)
8144 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8145 /* note: ash and hush share this string */
8146 printf("\n\n%s %s\n"
8147 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8150 "hush - the humble shell"
8154 parse_and_run_file(stdin);
8157 hush_exit(G.last_exitcode);
8162 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8163 int msh_main(int argc, char **argv)
8165 //bb_error_msg("msh is deprecated, please use hush instead");
8166 return hush_main(argc, argv);
8174 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8179 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8186 return applet_main_func(argc, argv - argc);
8189 static int FAST_FUNC builtin_test(char **argv)
8191 return run_applet_main(argv, test_main);
8194 static int FAST_FUNC builtin_echo(char **argv)
8196 return run_applet_main(argv, echo_main);
8200 static int FAST_FUNC builtin_printf(char **argv)
8202 return run_applet_main(argv, printf_main);
8206 static char **skip_dash_dash(char **argv)
8209 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8214 static int FAST_FUNC builtin_eval(char **argv)
8216 int rcode = EXIT_SUCCESS;
8218 argv = skip_dash_dash(argv);
8220 char *str = expand_strvec_to_string(argv);
8222 * eval "echo Hi; done" ("done" is syntax error):
8223 * "echo Hi" will not execute too.
8225 parse_and_run_string(str);
8227 rcode = G.last_exitcode;
8232 static int FAST_FUNC builtin_cd(char **argv)
8236 argv = skip_dash_dash(argv);
8238 if (newdir == NULL) {
8239 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8240 * bash says "bash: cd: HOME not set" and does nothing
8243 const char *home = get_local_var_value("HOME");
8244 newdir = home ? home : "/";
8246 if (chdir(newdir)) {
8247 /* Mimic bash message exactly */
8248 bb_perror_msg("cd: %s", newdir);
8249 return EXIT_FAILURE;
8251 /* Read current dir (get_cwd(1) is inside) and set PWD.
8252 * Note: do not enforce exporting. If PWD was unset or unexported,
8253 * set it again, but do not export. bash does the same.
8255 set_pwd_var(/*exp:*/ 0);
8256 return EXIT_SUCCESS;
8259 static int FAST_FUNC builtin_exec(char **argv)
8261 argv = skip_dash_dash(argv);
8262 if (argv[0] == NULL)
8263 return EXIT_SUCCESS; /* bash does this */
8265 /* Careful: we can end up here after [v]fork. Do not restore
8266 * tty pgrp then, only top-level shell process does that */
8267 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8268 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8270 /* TODO: if exec fails, bash does NOT exit! We do.
8271 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8272 * and tcsetpgrp, and this is inherently racy.
8274 execvp_or_die(argv);
8277 static int FAST_FUNC builtin_exit(char **argv)
8279 debug_printf_exec("%s()\n", __func__);
8281 /* interactive bash:
8282 * # trap "echo EEE" EXIT
8285 * There are stopped jobs.
8286 * (if there are _stopped_ jobs, running ones don't count)
8289 # EEE (then bash exits)
8291 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8294 /* note: EXIT trap is run by hush_exit */
8295 argv = skip_dash_dash(argv);
8296 if (argv[0] == NULL)
8297 hush_exit(G.last_exitcode);
8298 /* mimic bash: exit 123abc == exit 255 + error msg */
8299 xfunc_error_retval = 255;
8300 /* bash: exit -2 == exit 254, no error msg */
8301 hush_exit(xatoi(argv[0]) & 0xff);
8304 static void print_escaped(const char *s)
8309 const char *p = strchrnul(s, '\'');
8310 /* print 'xxxx', possibly just '' */
8311 printf("'%.*s'", (int)(p - s), s);
8316 /* s points to '; print "'''...'''" */
8318 do putchar('\''); while (*++s == '\'');
8323 #if !ENABLE_HUSH_LOCAL
8324 #define helper_export_local(argv, exp, lvl) \
8325 helper_export_local(argv, exp)
8327 static void helper_export_local(char **argv, int exp, int lvl)
8331 char *name_end = strchrnul(name, '=');
8333 /* So far we do not check that name is valid (TODO?) */
8335 if (*name_end == '\0') {
8336 struct variable *var, **vpp;
8338 vpp = get_ptr_to_local_var(name, name_end - name);
8339 var = vpp ? *vpp : NULL;
8341 if (exp == -1) { /* unexporting? */
8342 /* export -n NAME (without =VALUE) */
8344 var->flg_export = 0;
8345 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8347 } /* else: export -n NOT_EXISTING_VAR: no-op */
8350 if (exp == 1) { /* exporting? */
8351 /* export NAME (without =VALUE) */
8353 var->flg_export = 1;
8354 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8355 putenv(var->varstr);
8359 /* Exporting non-existing variable.
8360 * bash does not put it in environment,
8361 * but remembers that it is exported,
8362 * and does put it in env when it is set later.
8363 * We just set it to "" and export. */
8364 /* Or, it's "local NAME" (without =VALUE).
8365 * bash sets the value to "". */
8366 name = xasprintf("%s=", name);
8368 /* (Un)exporting/making local NAME=VALUE */
8369 name = xstrdup(name);
8371 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8375 static int FAST_FUNC builtin_export(char **argv)
8377 unsigned opt_unexport;
8379 #if ENABLE_HUSH_EXPORT_N
8380 /* "!": do not abort on errors */
8381 opt_unexport = getopt32(argv, "!n");
8382 if (opt_unexport == (uint32_t)-1)
8383 return EXIT_FAILURE;
8390 if (argv[0] == NULL) {
8397 /* ash emits: export VAR='VAL'
8398 * bash: declare -x VAR="VAL"
8399 * we follow ash example */
8400 const char *s = *e++;
8401 const char *p = strchr(s, '=');
8403 if (!p) /* wtf? take next variable */
8406 printf("export %.*s", (int)(p - s) + 1, s);
8407 print_escaped(p + 1);
8411 /*fflush_all(); - done after each builtin anyway */
8413 return EXIT_SUCCESS;
8416 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8418 return EXIT_SUCCESS;
8421 #if ENABLE_HUSH_LOCAL
8422 static int FAST_FUNC builtin_local(char **argv)
8424 if (G.func_nest_level == 0) {
8425 bb_error_msg("%s: not in a function", argv[0]);
8426 return EXIT_FAILURE; /* bash compat */
8428 helper_export_local(argv, 0, G.func_nest_level);
8429 return EXIT_SUCCESS;
8433 static int FAST_FUNC builtin_trap(char **argv)
8439 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8444 /* No args: print all trapped */
8445 for (i = 0; i < NSIG; ++i) {
8448 print_escaped(G.traps[i]);
8449 /* note: bash adds "SIG", but only if invoked
8450 * as "bash". If called as "sh", or if set -o posix,
8451 * then it prints short signal names.
8452 * We are printing short names: */
8453 printf(" %s\n", get_signame(i));
8456 /*fflush_all(); - done after each builtin anyway */
8457 return EXIT_SUCCESS;
8461 /* If first arg is a number: reset all specified signals */
8462 sig = bb_strtou(*argv, NULL, 10);
8468 sighandler_t handler;
8470 sig = get_signum(*argv++);
8471 if (sig < 0 || sig >= NSIG) {
8473 /* Mimic bash message exactly */
8474 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8479 G.traps[sig] = xstrdup(new_cmd);
8481 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8482 get_signame(sig), sig, G.traps[sig]);
8484 /* There is no signal for 0 (EXIT) */
8489 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8491 /* We are removing trap handler */
8492 handler = pick_sighandler(sig);
8493 install_sighandler(sig, handler);
8498 if (!argv[1]) { /* no second arg */
8499 bb_error_msg("trap: invalid arguments");
8500 return EXIT_FAILURE;
8503 /* First arg is "-": reset all specified to default */
8504 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8505 /* Everything else: set arg as signal handler
8506 * (includes "" case, which ignores signal) */
8507 if (argv[0][0] == '-') {
8508 if (argv[0][1] == '\0') { /* "-" */
8509 /* new_cmd remains NULL: "reset these sigs" */
8512 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8515 /* else: "-something", no special meaning */
8520 goto process_sig_list;
8523 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8524 static int FAST_FUNC builtin_type(char **argv)
8526 int ret = EXIT_SUCCESS;
8532 if (0) {} /* make conditional compile easier below */
8533 /*else if (find_alias(*argv))
8534 type = "an alias";*/
8535 #if ENABLE_HUSH_FUNCTIONS
8536 else if (find_function(*argv))
8537 type = "a function";
8539 else if (find_builtin(*argv))
8540 type = "a shell builtin";
8541 else if ((path = find_in_path(*argv)) != NULL)
8544 bb_error_msg("type: %s: not found", *argv);
8549 printf("%s is %s\n", *argv, type);
8557 /* built-in 'fg' and 'bg' handler */
8558 static int FAST_FUNC builtin_fg_bg(char **argv)
8563 if (!G_interactive_fd)
8564 return EXIT_FAILURE;
8566 /* If they gave us no args, assume they want the last backgrounded task */
8568 for (pi = G.job_list; pi; pi = pi->next) {
8569 if (pi->jobid == G.last_jobid) {
8573 bb_error_msg("%s: no current job", argv[0]);
8574 return EXIT_FAILURE;
8576 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8577 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8578 return EXIT_FAILURE;
8580 for (pi = G.job_list; pi; pi = pi->next) {
8581 if (pi->jobid == jobnum) {
8585 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8586 return EXIT_FAILURE;
8588 /* TODO: bash prints a string representation
8589 * of job being foregrounded (like "sleep 1 | cat") */
8590 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8591 /* Put the job into the foreground. */
8592 tcsetpgrp(G_interactive_fd, pi->pgrp);
8595 /* Restart the processes in the job */
8596 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8597 for (i = 0; i < pi->num_cmds; i++) {
8598 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8599 pi->cmds[i].is_stopped = 0;
8601 pi->stopped_cmds = 0;
8603 i = kill(- pi->pgrp, SIGCONT);
8605 if (errno == ESRCH) {
8606 delete_finished_bg_job(pi);
8607 return EXIT_SUCCESS;
8609 bb_perror_msg("kill (SIGCONT)");
8612 if (argv[0][0] == 'f') {
8614 return checkjobs_and_fg_shell(pi);
8616 return EXIT_SUCCESS;
8620 #if ENABLE_HUSH_HELP
8621 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8623 const struct built_in_command *x;
8626 "Built-in commands:\n"
8627 "------------------\n");
8628 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8630 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8633 return EXIT_SUCCESS;
8638 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8641 const char *status_string;
8643 for (job = G.job_list; job; job = job->next) {
8644 if (job->alive_cmds == job->stopped_cmds)
8645 status_string = "Stopped";
8647 status_string = "Running";
8649 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8651 return EXIT_SUCCESS;
8656 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8661 # ifdef M_TRIM_THRESHOLD
8662 /* Optional. Reduces probability of false positives */
8665 /* Crude attempt to find where "free memory" starts,
8666 * sans fragmentation. */
8668 l = (unsigned long)p;
8671 if (l < (unsigned long)p) l = (unsigned long)p;
8674 if (!G.memleak_value)
8675 G.memleak_value = l;
8677 l -= G.memleak_value;
8684 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8689 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8692 return EXIT_SUCCESS;
8695 /* Interruptibility of read builtin in bash
8696 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8698 * Empty trap makes read ignore corresponding signal, for any signal.
8701 * - terminates non-interactive shell;
8702 * - interrupts read in interactive shell;
8703 * if it has non-empty trap:
8704 * - executes trap and returns to command prompt in interactive shell;
8705 * - executes trap and returns to read in non-interactive shell;
8707 * - is ignored (does not interrupt) read in interactive shell;
8708 * - terminates non-interactive shell;
8709 * if it has non-empty trap:
8710 * - executes trap and returns to read;
8712 * - terminates shell (regardless of interactivity);
8713 * if it has non-empty trap:
8714 * - executes trap and returns to read;
8716 static int FAST_FUNC builtin_read(char **argv)
8726 /* "!": do not abort on errors.
8727 * Option string must start with "sr" to match BUILTIN_READ_xxx
8729 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8730 if (read_flags == (uint32_t)-1)
8731 return EXIT_FAILURE;
8733 ifs = get_local_var_value("IFS"); /* can be NULL */
8736 r = shell_builtin_read(set_local_var_from_halves,
8746 if ((uintptr_t)r == 1 && errno == EINTR) {
8747 unsigned sig = check_and_run_traps();
8748 if (sig && sig != SIGINT)
8752 if ((uintptr_t)r > 1) {
8753 bb_error_msg("%s", r);
8754 r = (char*)(uintptr_t)1;
8757 return (uintptr_t)r;
8760 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8761 * built-in 'set' handler
8763 * set [-abCefhmnuvx] [-o option] [argument...]
8764 * set [+abCefhmnuvx] [+o option] [argument...]
8765 * set -- [argument...]
8768 * Implementations shall support the options in both their hyphen and
8769 * plus-sign forms. These options can also be specified as options to sh.
8771 * Write out all variables and their values: set
8772 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8773 * Turn on the -x and -v options: set -xv
8774 * Unset all positional parameters: set --
8775 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8776 * Set the positional parameters to the expansion of x, even if x expands
8777 * with a leading '-' or '+': set -- $x
8779 * So far, we only support "set -- [argument...]" and some of the short names.
8781 static int FAST_FUNC builtin_set(char **argv)
8784 char **pp, **g_argv;
8785 char *arg = *++argv;
8789 for (e = G.top_var; e; e = e->next)
8791 return EXIT_SUCCESS;
8795 if (strcmp(arg, "--") == 0) {
8799 if (arg[0] != '+' && arg[0] != '-')
8801 for (n = 1; arg[n]; ++n) {
8802 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8804 if (arg[n] == 'o' && argv[1])
8807 } while ((arg = *++argv) != NULL);
8808 /* Now argv[0] is 1st argument */
8811 return EXIT_SUCCESS;
8814 /* NB: G.global_argv[0] ($0) is never freed/changed */
8815 g_argv = G.global_argv;
8816 if (G.global_args_malloced) {
8822 G.global_args_malloced = 1;
8823 pp = xzalloc(sizeof(pp[0]) * 2);
8824 pp[0] = g_argv[0]; /* retain $0 */
8827 /* This realloc's G.global_argv */
8828 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8835 return EXIT_SUCCESS;
8837 /* Nothing known, so abort */
8839 bb_error_msg("set: %s: invalid option", arg);
8840 return EXIT_FAILURE;
8843 static int FAST_FUNC builtin_shift(char **argv)
8846 argv = skip_dash_dash(argv);
8850 if (n >= 0 && n < G.global_argc) {
8851 if (G.global_args_malloced) {
8854 free(G.global_argv[m++]);
8857 memmove(&G.global_argv[1], &G.global_argv[n+1],
8858 G.global_argc * sizeof(G.global_argv[0]));
8859 return EXIT_SUCCESS;
8861 return EXIT_FAILURE;
8864 static int FAST_FUNC builtin_source(char **argv)
8866 char *arg_path, *filename;
8869 #if ENABLE_HUSH_FUNCTIONS
8873 argv = skip_dash_dash(argv);
8876 /* bash says: "bash: .: filename argument required" */
8877 return 2; /* bash compat */
8880 if (!strchr(filename, '/')) {
8881 arg_path = find_in_path(filename);
8883 filename = arg_path;
8885 input = fopen_or_warn(filename, "r");
8888 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8889 return EXIT_FAILURE;
8891 close_on_exec_on(fileno(input));
8893 #if ENABLE_HUSH_FUNCTIONS
8894 sv_flg = G.flag_return_in_progress;
8895 /* "we are inside sourced file, ok to use return" */
8896 G.flag_return_in_progress = -1;
8898 save_and_replace_G_args(&sv, argv);
8900 parse_and_run_file(input);
8903 restore_G_args(&sv, argv);
8904 #if ENABLE_HUSH_FUNCTIONS
8905 G.flag_return_in_progress = sv_flg;
8908 return G.last_exitcode;
8911 static int FAST_FUNC builtin_umask(char **argv)
8917 argv = skip_dash_dash(argv);
8919 mode_t old_mask = mask;
8922 rc = bb_parse_mode(argv[0], &mask);
8927 * bash: umask: 'q': invalid symbolic mode operator
8928 * bash: umask: 999: octal number out of range
8930 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8935 printf("%04o\n", (unsigned) mask);
8936 /* fall through and restore mask which we set to 0 */
8940 return !rc; /* rc != 0 - success */
8943 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8944 static int FAST_FUNC builtin_unset(char **argv)
8949 /* "!": do not abort on errors */
8950 /* "+": stop at 1st non-option */
8951 opts = getopt32(argv, "!+vf");
8952 if (opts == (unsigned)-1)
8953 return EXIT_FAILURE;
8955 bb_error_msg("unset: -v and -f are exclusive");
8956 return EXIT_FAILURE;
8962 if (!(opts & 2)) { /* not -f */
8963 if (unset_local_var(*argv)) {
8964 /* unset <nonexistent_var> doesn't fail.
8965 * Error is when one tries to unset RO var.
8966 * Message was printed by unset_local_var. */
8970 #if ENABLE_HUSH_FUNCTIONS
8980 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8981 static int FAST_FUNC builtin_wait(char **argv)
8983 int ret = EXIT_SUCCESS;
8986 argv = skip_dash_dash(argv);
8987 if (argv[0] == NULL) {
8988 /* Don't care about wait results */
8989 /* Note 1: must wait until there are no more children */
8990 /* Note 2: must be interruptible */
8992 * $ sleep 3 & sleep 6 & wait
8997 * $ sleep 3 & sleep 6 & wait
9001 * ^C <-- after ~4 sec from keyboard
9006 sigset_t oldset, allsigs;
9008 /* waitpid is not interruptible by SA_RESTARTed
9009 * signals which we use. Thus, this ugly dance:
9012 /* Make sure possible SIGCHLD is stored in kernel's
9013 * pending signal mask before we call waitpid.
9014 * Or else we may race with SIGCHLD, lose it,
9015 * and get stuck in sigwaitinfo...
9017 sigfillset(&allsigs);
9018 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9020 if (!sigisemptyset(&G.pending_set)) {
9021 /* Crap! we raced with some signal! */
9026 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9027 if (errno == ECHILD) {
9028 sigprocmask(SIG_SETMASK, &oldset, NULL);
9032 /* Wait for SIGCHLD or any other signal */
9033 //sig = sigwaitinfo(&allsigs, NULL);
9034 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9035 /* Note: sigsuspend invokes signal handler */
9036 sigsuspend(&oldset);
9038 sigprocmask(SIG_SETMASK, &oldset, NULL);
9040 /* So, did we get a signal? */
9042 // raise(sig); /* run handler */
9043 sig = check_and_run_traps();
9044 if (sig /*&& sig != SIGCHLD - always true */) {
9049 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9054 /* This is probably buggy wrt interruptible-ness */
9056 pid_t pid = bb_strtou(*argv, NULL, 10);
9058 /* mimic bash message */
9059 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9060 return EXIT_FAILURE;
9062 if (waitpid(pid, &status, 0) == pid) {
9063 if (WIFSIGNALED(status))
9064 ret = 128 + WTERMSIG(status);
9065 else if (WIFEXITED(status))
9066 ret = WEXITSTATUS(status);
9070 bb_perror_msg("wait %s", *argv);
9079 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9080 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9083 def = bb_strtou(argv[1], NULL, 10);
9084 if (errno || def < def_min || argv[2]) {
9085 bb_error_msg("%s: bad arguments", argv[0]);
9093 #if ENABLE_HUSH_LOOPS
9094 static int FAST_FUNC builtin_break(char **argv)
9097 if (G.depth_of_loop == 0) {
9098 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9099 return EXIT_SUCCESS; /* bash compat */
9101 G.flag_break_continue++; /* BC_BREAK = 1 */
9103 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9104 if (depth == UINT_MAX)
9105 G.flag_break_continue = BC_BREAK;
9106 if (G.depth_of_loop < depth)
9107 G.depth_break_continue = G.depth_of_loop;
9109 return EXIT_SUCCESS;
9112 static int FAST_FUNC builtin_continue(char **argv)
9114 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9115 return builtin_break(argv);
9119 #if ENABLE_HUSH_FUNCTIONS
9120 static int FAST_FUNC builtin_return(char **argv)
9124 if (G.flag_return_in_progress != -1) {
9125 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9126 return EXIT_FAILURE; /* bash compat */
9129 G.flag_return_in_progress = 1;
9132 * out of range: wraps around at 256, does not error out
9133 * non-numeric param:
9134 * f() { false; return qwe; }; f; echo $?
9135 * bash: return: qwe: numeric argument required <== we do this
9136 * 255 <== we also do this
9138 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);