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)
1545 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1547 /* argv[0] is unused */
1548 argv[1] = G.traps[0];
1550 G.exiting = 1; /* prevent EXIT trap recursion */
1551 /* Note: G.traps[0] is not cleared!
1552 * "trap" will still show it, if executed
1557 #if ENABLE_FEATURE_CLEAN_UP
1559 struct variable *cur_var;
1560 if (G.cwd != bb_msg_unknown)
1562 cur_var = G.top_var;
1564 struct variable *tmp = cur_var;
1565 if (!cur_var->max_len)
1566 free(cur_var->varstr);
1567 cur_var = cur_var->next;
1575 sigexit(- (exitcode & 0xff));
1582 //TODO: return a mask of ALL handled sigs?
1583 static int check_and_run_traps(void)
1590 if (sigisemptyset(&G.pending_set))
1595 if (sigismember(&G.pending_set, sig)) {
1596 sigdelset(&G.pending_set, sig);
1599 } while (sig < NSIG);
1602 if (G.traps && G.traps[sig]) {
1603 if (G.traps[sig][0]) {
1604 /* We have user-defined handler */
1605 smalluint save_rcode;
1607 /* argv[0] is unused */
1608 argv[1] = G.traps[sig];
1610 save_rcode = G.last_exitcode;
1612 G.last_exitcode = save_rcode;
1614 } /* else: "" trap, ignoring signal */
1617 /* not a trap: special action */
1620 /* Builtin was ^C'ed, make it look prettier: */
1628 /* bash is observed to signal whole process groups,
1629 * not individual processes */
1630 for (job = G.job_list; job; job = job->next) {
1633 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1634 if (kill(- job->pgrp, SIGHUP) == 0)
1635 kill(- job->pgrp, SIGCONT);
1640 #if ENABLE_HUSH_FAST
1643 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1645 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1646 * This simplifies wait builtin a bit.
1650 default: /* ignored: */
1651 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1653 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1654 * Example: wait is not interrupted by TERM
1655 * in interactive shell, because TERM is ignored.
1664 static const char *get_cwd(int force)
1666 if (force || G.cwd == NULL) {
1667 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1668 * we must not try to free(bb_msg_unknown) */
1669 if (G.cwd == bb_msg_unknown)
1671 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1673 G.cwd = bb_msg_unknown;
1680 * Shell and environment variable support
1682 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1684 struct variable **pp;
1685 struct variable *cur;
1688 while ((cur = *pp) != NULL) {
1689 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1696 static const char* FAST_FUNC get_local_var_value(const char *name)
1698 struct variable **vpp;
1699 unsigned len = strlen(name);
1701 if (G.expanded_assignments) {
1702 char **cpp = G.expanded_assignments;
1705 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1706 return cp + len + 1;
1711 vpp = get_ptr_to_local_var(name, len);
1713 return (*vpp)->varstr + len + 1;
1715 if (strcmp(name, "PPID") == 0)
1716 return utoa(G.root_ppid);
1717 // bash compat: UID? EUID?
1718 #if ENABLE_HUSH_RANDOM_SUPPORT
1719 if (strcmp(name, "RANDOM") == 0)
1720 return utoa(next_random(&G.random_gen));
1725 /* str holds "NAME=VAL" and is expected to be malloced.
1726 * We take ownership of it.
1728 * 0: do not change export flag
1729 * (if creating new variable, flag will be 0)
1730 * 1: set export flag and putenv the variable
1731 * -1: clear export flag and unsetenv the variable
1732 * flg_read_only is set only when we handle -R var=val
1734 #if !BB_MMU && ENABLE_HUSH_LOCAL
1735 /* all params are used */
1736 #elif BB_MMU && ENABLE_HUSH_LOCAL
1737 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1738 set_local_var(str, flg_export, local_lvl)
1739 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1740 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1741 set_local_var(str, flg_export)
1742 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1743 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1744 set_local_var(str, flg_export, flg_read_only)
1746 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1748 struct variable **var_pp;
1749 struct variable *cur;
1753 eq_sign = strchr(str, '=');
1754 if (!eq_sign) { /* not expected to ever happen? */
1759 name_len = eq_sign - str + 1; /* including '=' */
1760 var_pp = &G.top_var;
1761 while ((cur = *var_pp) != NULL) {
1762 if (strncmp(cur->varstr, str, name_len) != 0) {
1763 var_pp = &cur->next;
1766 /* We found an existing var with this name */
1767 if (cur->flg_read_only) {
1771 bb_error_msg("%s: readonly variable", str);
1775 if (flg_export == -1) { // "&& cur->flg_export" ?
1776 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1781 #if ENABLE_HUSH_LOCAL
1782 if (cur->func_nest_level < local_lvl) {
1783 /* New variable is declared as local,
1784 * and existing one is global, or local
1785 * from enclosing function.
1786 * Remove and save old one: */
1787 *var_pp = cur->next;
1788 cur->next = *G.shadowed_vars_pp;
1789 *G.shadowed_vars_pp = cur;
1790 /* bash 3.2.33(1) and exported vars:
1792 * # f() { local z=a; env | grep ^z; }
1798 if (cur->flg_export)
1803 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1808 if (cur->max_len != 0) {
1809 if (cur->max_len >= strlen(str)) {
1810 /* This one is from startup env, reuse space */
1811 strcpy(cur->varstr, str);
1815 /* max_len == 0 signifies "malloced" var, which we can
1816 * (and has to) free */
1820 goto set_str_and_exp;
1823 /* Not found - create new variable struct */
1824 cur = xzalloc(sizeof(*cur));
1825 #if ENABLE_HUSH_LOCAL
1826 cur->func_nest_level = local_lvl;
1828 cur->next = *var_pp;
1834 cur->flg_read_only = flg_read_only;
1837 if (flg_export == 1)
1838 cur->flg_export = 1;
1839 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1840 cmdedit_update_prompt();
1841 if (cur->flg_export) {
1842 if (flg_export == -1) {
1843 cur->flg_export = 0;
1844 /* unsetenv was already done */
1846 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1847 return putenv(cur->varstr);
1853 /* Used at startup and after each cd */
1854 static void set_pwd_var(int exp)
1856 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1857 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1860 static int unset_local_var_len(const char *name, int name_len)
1862 struct variable *cur;
1863 struct variable **var_pp;
1866 return EXIT_SUCCESS;
1867 var_pp = &G.top_var;
1868 while ((cur = *var_pp) != NULL) {
1869 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1870 if (cur->flg_read_only) {
1871 bb_error_msg("%s: readonly variable", name);
1872 return EXIT_FAILURE;
1874 *var_pp = cur->next;
1875 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1876 bb_unsetenv(cur->varstr);
1877 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1878 cmdedit_update_prompt();
1882 return EXIT_SUCCESS;
1884 var_pp = &cur->next;
1886 return EXIT_SUCCESS;
1889 static int unset_local_var(const char *name)
1891 return unset_local_var_len(name, strlen(name));
1894 static void unset_vars(char **strings)
1902 const char *eq = strchrnul(*v, '=');
1903 unset_local_var_len(*v, (int)(eq - *v));
1909 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1911 char *var = xasprintf("%s=%s", name, val);
1912 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1917 * Helpers for "var1=val1 var2=val2 cmd" feature
1919 static void add_vars(struct variable *var)
1921 struct variable *next;
1925 var->next = G.top_var;
1927 if (var->flg_export) {
1928 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1929 putenv(var->varstr);
1931 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1937 static struct variable *set_vars_and_save_old(char **strings)
1940 struct variable *old = NULL;
1946 struct variable *var_p;
1947 struct variable **var_pp;
1950 eq = strchr(*s, '=');
1952 var_pp = get_ptr_to_local_var(*s, eq - *s);
1954 /* Remove variable from global linked list */
1956 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1957 *var_pp = var_p->next;
1958 /* Add it to returned list */
1962 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1973 static int FAST_FUNC static_get(struct in_str *i)
1984 static int FAST_FUNC static_peek(struct in_str *i)
1989 #if ENABLE_HUSH_INTERACTIVE
1991 static void cmdedit_update_prompt(void)
1993 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1994 G.PS1 = get_local_var_value("PS1");
1997 G.PS2 = get_local_var_value("PS2");
2005 static const char *setup_prompt_string(int promptmode)
2007 const char *prompt_str;
2008 debug_printf("setup_prompt_string %d ", promptmode);
2009 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2010 /* Set up the prompt */
2011 if (promptmode == 0) { /* PS1 */
2013 /* bash uses $PWD value, even if it is set by user.
2014 * It uses current dir only if PWD is unset.
2015 * We always use current dir. */
2016 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2021 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2022 debug_printf("result '%s'\n", prompt_str);
2026 static void get_user_input(struct in_str *i)
2029 const char *prompt_str;
2031 prompt_str = setup_prompt_string(i->promptmode);
2032 # if ENABLE_FEATURE_EDITING
2033 /* Enable command line editing only while a command line
2034 * is actually being read */
2036 /* Unicode support should be activated even if LANG is set
2037 * _during_ shell execution, not only if it was set when
2038 * shell was started. Therefore, re-check LANG every time:
2040 reinit_unicode(get_local_var_value("LANG"));
2043 /* buglet: SIGINT will not make new prompt to appear _at once_,
2044 * only after <Enter>. (^C will work) */
2045 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2046 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2047 check_and_run_traps();
2048 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2049 i->eof_flag = (r < 0);
2050 if (i->eof_flag) { /* EOF/error detected */
2051 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2052 G.user_input_buf[1] = '\0';
2057 if (i->last_char == '\0' || i->last_char == '\n') {
2058 /* Why check_and_run_traps here? Try this interactively:
2059 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2060 * $ <[enter], repeatedly...>
2061 * Without check_and_run_traps, handler never runs.
2063 check_and_run_traps();
2064 fputs(prompt_str, stdout);
2067 G.user_input_buf[0] = r = fgetc(i->file);
2068 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2069 } while (G.flag_SIGINT);
2070 i->eof_flag = (r == EOF);
2072 i->p = G.user_input_buf;
2075 #endif /* INTERACTIVE */
2077 /* This is the magic location that prints prompts
2078 * and gets data back from the user */
2079 static int FAST_FUNC file_get(struct in_str *i)
2083 /* If there is data waiting, eat it up */
2084 if (i->p && *i->p) {
2085 #if ENABLE_HUSH_INTERACTIVE
2089 if (i->eof_flag && !*i->p)
2091 /* note: ch is never NUL */
2093 /* need to double check i->file because we might be doing something
2094 * more complicated by now, like sourcing or substituting. */
2095 #if ENABLE_HUSH_INTERACTIVE
2096 if (G_interactive_fd && i->file == stdin) {
2099 } while (!*i->p); /* need non-empty line */
2100 i->promptmode = 1; /* PS2 */
2104 do ch = fgetc(i->file); while (ch == '\0');
2106 debug_printf("file_get: got '%c' %d\n", ch, ch);
2111 /* All callers guarantee this routine will never
2112 * be used right after a newline, so prompting is not needed.
2114 static int FAST_FUNC file_peek(struct in_str *i)
2117 if (i->p && *i->p) {
2118 if (i->eof_flag && !i->p[1])
2121 /* note: ch is never NUL */
2123 do ch = fgetc(i->file); while (ch == '\0');
2124 i->eof_flag = (ch == EOF);
2125 i->peek_buf[0] = ch;
2126 i->peek_buf[1] = '\0';
2128 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2132 static void setup_file_in_str(struct in_str *i, FILE *f)
2134 memset(i, 0, sizeof(*i));
2135 i->peek = file_peek;
2137 /* i->promptmode = 0; - PS1 (memset did it) */
2142 static void setup_string_in_str(struct in_str *i, const char *s)
2144 memset(i, 0, sizeof(*i));
2145 i->peek = static_peek;
2146 i->get = static_get;
2147 /* i->promptmode = 0; - PS1 (memset did it) */
2149 /* i->eof_flag = 0; */
2156 #define B_CHUNK (32 * sizeof(char*))
2158 static void o_reset_to_empty_unquoted(o_string *o)
2161 o->has_quoted_part = 0;
2166 static void o_free(o_string *o)
2169 memset(o, 0, sizeof(*o));
2172 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2177 static void o_grow_by(o_string *o, int len)
2179 if (o->length + len > o->maxlen) {
2180 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2181 o->data = xrealloc(o->data, 1 + o->maxlen);
2185 static void o_addchr(o_string *o, int ch)
2187 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2189 o->data[o->length] = ch;
2191 o->data[o->length] = '\0';
2194 static void o_addblock(o_string *o, const char *str, int len)
2197 memcpy(&o->data[o->length], str, len);
2199 o->data[o->length] = '\0';
2202 static void o_addstr(o_string *o, const char *str)
2204 o_addblock(o, str, strlen(str));
2208 static void nommu_addchr(o_string *o, int ch)
2214 # define nommu_addchr(o, str) ((void)0)
2217 static void o_addstr_with_NUL(o_string *o, const char *str)
2219 o_addblock(o, str, strlen(str) + 1);
2223 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2224 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2225 * Apparently, on unquoted $v bash still does globbing
2226 * ("v='*.txt'; echo $v" prints all .txt files),
2227 * but NOT brace expansion! Thus, there should be TWO independent
2228 * quoting mechanisms on $v expansion side: one protects
2229 * $v from brace expansion, and other additionally protects "$v" against globbing.
2230 * We have only second one.
2233 #if ENABLE_HUSH_BRACE_EXPANSION
2234 # define MAYBE_BRACES "{}"
2236 # define MAYBE_BRACES ""
2239 /* My analysis of quoting semantics tells me that state information
2240 * is associated with a destination, not a source.
2242 static void o_addqchr(o_string *o, int ch)
2245 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2250 o->data[o->length] = '\\';
2253 o->data[o->length] = ch;
2255 o->data[o->length] = '\0';
2258 static void o_addQchr(o_string *o, int ch)
2261 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2262 && strchr("*?[\\" MAYBE_BRACES, ch)
2265 o->data[o->length] = '\\';
2269 o->data[o->length] = ch;
2271 o->data[o->length] = '\0';
2274 static void o_addqblock(o_string *o, const char *str, int len)
2279 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2280 if (ordinary_cnt > len) /* paranoia */
2282 o_addblock(o, str, ordinary_cnt);
2283 if (ordinary_cnt == len)
2284 return; /* NUL is already added by o_addblock */
2285 str += ordinary_cnt;
2286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2290 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2292 o->data[o->length] = '\\';
2296 o->data[o->length] = ch;
2299 o->data[o->length] = '\0';
2302 static void o_addQblock(o_string *o, const char *str, int len)
2304 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2305 o_addblock(o, str, len);
2308 o_addqblock(o, str, len);
2311 static void o_addQstr(o_string *o, const char *str)
2313 o_addQblock(o, str, strlen(str));
2316 /* A special kind of o_string for $VAR and `cmd` expansion.
2317 * It contains char* list[] at the beginning, which is grown in 16 element
2318 * increments. Actual string data starts at the next multiple of 16 * (char*).
2319 * list[i] contains an INDEX (int!) into this string data.
2320 * It means that if list[] needs to grow, data needs to be moved higher up
2321 * but list[i]'s need not be modified.
2322 * NB: remembering how many list[i]'s you have there is crucial.
2323 * o_finalize_list() operation post-processes this structure - calculates
2324 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2326 #if DEBUG_EXPAND || DEBUG_GLOB
2327 static void debug_print_list(const char *prefix, o_string *o, int n)
2329 char **list = (char**)o->data;
2330 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2334 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2335 prefix, list, n, string_start, o->length, o->maxlen,
2336 !!(o->o_expflags & EXP_FLAG_GLOB),
2338 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2341 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2342 o->data + (int)(uintptr_t)list[i] + string_start,
2343 o->data + (int)(uintptr_t)list[i] + string_start);
2347 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2349 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2353 # define debug_print_list(prefix, o, n) ((void)0)
2356 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2357 * in list[n] so that it points past last stored byte so far.
2358 * It returns n+1. */
2359 static int o_save_ptr_helper(o_string *o, int n)
2361 char **list = (char**)o->data;
2365 if (!o->has_empty_slot) {
2366 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2367 string_len = o->length - string_start;
2368 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2369 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2370 /* list[n] points to string_start, make space for 16 more pointers */
2371 o->maxlen += 0x10 * sizeof(list[0]);
2372 o->data = xrealloc(o->data, o->maxlen + 1);
2373 list = (char**)o->data;
2374 memmove(list + n + 0x10, list + n, string_len);
2375 o->length += 0x10 * sizeof(list[0]);
2377 debug_printf_list("list[%d]=%d string_start=%d\n",
2378 n, string_len, string_start);
2381 /* We have empty slot at list[n], reuse without growth */
2382 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2383 string_len = o->length - string_start;
2384 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2385 n, string_len, string_start);
2386 o->has_empty_slot = 0;
2388 o->has_quoted_part = 0;
2389 list[n] = (char*)(uintptr_t)string_len;
2393 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2394 static int o_get_last_ptr(o_string *o, int n)
2396 char **list = (char**)o->data;
2397 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2399 return ((int)(uintptr_t)list[n-1]) + string_start;
2402 #if ENABLE_HUSH_BRACE_EXPANSION
2403 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2404 * first, it processes even {a} (no commas), second,
2405 * I didn't manage to make it return strings when they don't match
2406 * existing files. Need to re-implement it.
2410 static int glob_needed(const char *s)
2419 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2425 /* Return pointer to next closing brace or to comma */
2426 static const char *next_brace_sub(const char *cp)
2430 while (*cp != '\0') {
2437 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2443 return *cp != '\0' ? cp : NULL;
2445 /* Recursive brace globber. Note: may garble pattern[]. */
2446 static int glob_brace(char *pattern, o_string *o, int n)
2448 char *new_pattern_buf;
2455 debug_printf_glob("glob_brace('%s')\n", pattern);
2461 if (*begin == '{') {
2462 /* Find the first sub-pattern and at the same time
2463 * find the rest after the closing brace */
2464 next = next_brace_sub(begin);
2466 /* An illegal expression */
2470 /* "{abc}" with no commas - illegal
2471 * brace expr, disregard and skip it */
2477 if (*begin == '\\' && begin[1] != '\0')
2481 debug_printf_glob("begin:%s\n", begin);
2482 debug_printf_glob("next:%s\n", next);
2484 /* Now find the end of the whole brace expression */
2486 while (*rest != '}') {
2487 rest = next_brace_sub(rest);
2489 /* An illegal expression */
2492 debug_printf_glob("rest:%s\n", rest);
2494 rest_len = strlen(++rest) + 1;
2496 /* We are sure the brace expression is well-formed */
2498 /* Allocate working buffer large enough for our work */
2499 new_pattern_buf = xmalloc(strlen(pattern));
2501 /* We have a brace expression. BEGIN points to the opening {,
2502 * NEXT points past the terminator of the first element, and REST
2503 * points past the final }. We will accumulate result names from
2504 * recursive runs for each brace alternative in the buffer using
2509 /* Construct the new glob expression */
2512 mempcpy(new_pattern_buf,
2513 /* We know the prefix for all sub-patterns */
2514 pattern, begin - pattern),
2518 /* Note: glob_brace() may garble new_pattern_buf[].
2519 * That's why we re-copy prefix every time (1st memcpy above).
2521 n = glob_brace(new_pattern_buf, o, n);
2523 /* We saw the last entry */
2527 next = next_brace_sub(next);
2529 free(new_pattern_buf);
2537 memset(&globdata, 0, sizeof(globdata));
2538 gr = glob(pattern, 0, NULL, &globdata);
2539 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2541 if (gr == GLOB_NOMATCH) {
2542 globfree(&globdata);
2543 /* NB: garbles parameter */
2544 unbackslash(pattern);
2545 o_addstr_with_NUL(o, pattern);
2546 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2547 return o_save_ptr_helper(o, n);
2549 if (gr == GLOB_NOSPACE)
2550 bb_error_msg_and_die(bb_msg_memory_exhausted);
2551 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2552 * but we didn't specify it. Paranoia again. */
2553 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2555 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2556 char **argv = globdata.gl_pathv;
2558 o_addstr_with_NUL(o, *argv);
2559 n = o_save_ptr_helper(o, n);
2565 globfree(&globdata);
2569 /* Performs globbing on last list[],
2570 * saving each result as a new list[].
2572 static int perform_glob(o_string *o, int n)
2574 char *pattern, *copy;
2576 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2578 return o_save_ptr_helper(o, n);
2579 pattern = o->data + o_get_last_ptr(o, n);
2580 debug_printf_glob("glob pattern '%s'\n", pattern);
2581 if (!glob_needed(pattern)) {
2582 /* unbackslash last string in o in place, fix length */
2583 o->length = unbackslash(pattern) - o->data;
2584 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2585 return o_save_ptr_helper(o, n);
2588 copy = xstrdup(pattern);
2589 /* "forget" pattern in o */
2590 o->length = pattern - o->data;
2591 n = glob_brace(copy, o, n);
2594 debug_print_list("perform_glob returning", o, n);
2598 #else /* !HUSH_BRACE_EXPANSION */
2601 static int glob_needed(const char *s)
2610 if (*s == '*' || *s == '[' || *s == '?')
2616 /* Performs globbing on last list[],
2617 * saving each result as a new list[].
2619 static int perform_glob(o_string *o, int n)
2625 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2627 return o_save_ptr_helper(o, n);
2628 pattern = o->data + o_get_last_ptr(o, n);
2629 debug_printf_glob("glob pattern '%s'\n", pattern);
2630 if (!glob_needed(pattern)) {
2632 /* unbackslash last string in o in place, fix length */
2633 o->length = unbackslash(pattern) - o->data;
2634 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2635 return o_save_ptr_helper(o, n);
2638 memset(&globdata, 0, sizeof(globdata));
2639 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2640 * If we glob "*.\*" and don't find anything, we need
2641 * to fall back to using literal "*.*", but GLOB_NOCHECK
2642 * will return "*.\*"!
2644 gr = glob(pattern, 0, NULL, &globdata);
2645 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2647 if (gr == GLOB_NOMATCH) {
2648 globfree(&globdata);
2651 if (gr == GLOB_NOSPACE)
2652 bb_error_msg_and_die(bb_msg_memory_exhausted);
2653 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2654 * but we didn't specify it. Paranoia again. */
2655 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2657 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2658 char **argv = globdata.gl_pathv;
2659 /* "forget" pattern in o */
2660 o->length = pattern - o->data;
2662 o_addstr_with_NUL(o, *argv);
2663 n = o_save_ptr_helper(o, n);
2669 globfree(&globdata);
2671 debug_print_list("perform_glob returning", o, n);
2675 #endif /* !HUSH_BRACE_EXPANSION */
2677 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2678 * Otherwise, just finish current list[] and start new */
2679 static int o_save_ptr(o_string *o, int n)
2681 if (o->o_expflags & EXP_FLAG_GLOB) {
2682 /* If o->has_empty_slot, list[n] was already globbed
2683 * (if it was requested back then when it was filled)
2684 * so don't do that again! */
2685 if (!o->has_empty_slot)
2686 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2688 return o_save_ptr_helper(o, n);
2691 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2692 static char **o_finalize_list(o_string *o, int n)
2697 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2699 debug_print_list("finalized", o, n);
2700 debug_printf_expand("finalized n:%d\n", n);
2701 list = (char**)o->data;
2702 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2706 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2711 static void free_pipe_list(struct pipe *pi);
2713 /* Returns pi->next - next pipe in the list */
2714 static struct pipe *free_pipe(struct pipe *pi)
2719 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2720 for (i = 0; i < pi->num_cmds; i++) {
2721 struct command *command;
2722 struct redir_struct *r, *rnext;
2724 command = &pi->cmds[i];
2725 debug_printf_clean(" command %d:\n", i);
2726 if (command->argv) {
2730 for (a = 0, p = command->argv; *p; a++, p++) {
2731 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2734 free_strings(command->argv);
2735 //command->argv = NULL;
2737 /* not "else if": on syntax error, we may have both! */
2738 if (command->group) {
2739 debug_printf_clean(" begin group (cmd_type:%d)\n",
2741 free_pipe_list(command->group);
2742 debug_printf_clean(" end group\n");
2743 //command->group = NULL;
2745 /* else is crucial here.
2746 * If group != NULL, child_func is meaningless */
2747 #if ENABLE_HUSH_FUNCTIONS
2748 else if (command->child_func) {
2749 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2750 command->child_func->parent_cmd = NULL;
2754 free(command->group_as_string);
2755 //command->group_as_string = NULL;
2757 for (r = command->redirects; r; r = rnext) {
2758 debug_printf_clean(" redirect %d%s",
2759 r->rd_fd, redir_table[r->rd_type].descrip);
2760 /* guard against the case >$FOO, where foo is unset or blank */
2761 if (r->rd_filename) {
2762 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2763 free(r->rd_filename);
2764 //r->rd_filename = NULL;
2766 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2770 //command->redirects = NULL;
2772 free(pi->cmds); /* children are an array, they get freed all at once */
2776 //pi->cmdtext = NULL;
2784 static void free_pipe_list(struct pipe *pi)
2788 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2790 debug_printf_clean("pipe followup code %d\n", pi->followup);
2796 /*** Parsing routines ***/
2798 #ifndef debug_print_tree
2799 static void debug_print_tree(struct pipe *pi, int lvl)
2801 static const char *const PIPE[] = {
2807 static const char *RES[] = {
2808 [RES_NONE ] = "NONE" ,
2811 [RES_THEN ] = "THEN" ,
2812 [RES_ELIF ] = "ELIF" ,
2813 [RES_ELSE ] = "ELSE" ,
2816 # if ENABLE_HUSH_LOOPS
2817 [RES_FOR ] = "FOR" ,
2818 [RES_WHILE] = "WHILE",
2819 [RES_UNTIL] = "UNTIL",
2821 [RES_DONE ] = "DONE" ,
2823 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2826 # if ENABLE_HUSH_CASE
2827 [RES_CASE ] = "CASE" ,
2828 [RES_CASE_IN ] = "CASE_IN" ,
2829 [RES_MATCH] = "MATCH",
2830 [RES_CASE_BODY] = "CASE_BODY",
2831 [RES_ESAC ] = "ESAC" ,
2833 [RES_XXXX ] = "XXXX" ,
2834 [RES_SNTX ] = "SNTX" ,
2836 static const char *const CMDTYPE[] = {
2840 # if ENABLE_HUSH_FUNCTIONS
2849 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2850 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2852 while (prn < pi->num_cmds) {
2853 struct command *command = &pi->cmds[prn];
2854 char **argv = command->argv;
2856 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2858 command->assignment_cnt);
2859 if (command->group) {
2860 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2861 CMDTYPE[command->cmd_type],
2864 , " group_as_string:", command->group_as_string
2869 debug_print_tree(command->group, lvl+1);
2873 if (argv) while (*argv) {
2874 fdprintf(2, " '%s'", *argv);
2884 #endif /* debug_print_tree */
2886 static struct pipe *new_pipe(void)
2889 pi = xzalloc(sizeof(struct pipe));
2890 /*pi->followup = 0; - deliberately invalid value */
2891 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2895 /* Command (member of a pipe) is complete, or we start a new pipe
2896 * if ctx->command is NULL.
2897 * No errors possible here.
2899 static int done_command(struct parse_context *ctx)
2901 /* The command is really already in the pipe structure, so
2902 * advance the pipe counter and make a new, null command. */
2903 struct pipe *pi = ctx->pipe;
2904 struct command *command = ctx->command;
2907 if (IS_NULL_CMD(command)) {
2908 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2912 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2913 //debug_print_tree(ctx->list_head, 20);
2915 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2918 /* Only real trickiness here is that the uncommitted
2919 * command structure is not counted in pi->num_cmds. */
2920 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2921 ctx->command = command = &pi->cmds[pi->num_cmds];
2923 memset(command, 0, sizeof(*command));
2924 return pi->num_cmds; /* used only for 0/nonzero check */
2927 static void done_pipe(struct parse_context *ctx, pipe_style type)
2931 debug_printf_parse("done_pipe entered, followup %d\n", type);
2932 /* Close previous command */
2933 not_null = done_command(ctx);
2934 ctx->pipe->followup = type;
2936 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2937 ctx->ctx_inverted = 0;
2938 ctx->pipe->res_word = ctx->ctx_res_w;
2941 /* Without this check, even just <enter> on command line generates
2942 * tree of three NOPs (!). Which is harmless but annoying.
2943 * IOW: it is safe to do it unconditionally. */
2946 || ctx->ctx_res_w == RES_FI
2948 #if ENABLE_HUSH_LOOPS
2949 || ctx->ctx_res_w == RES_DONE
2950 || ctx->ctx_res_w == RES_FOR
2951 || ctx->ctx_res_w == RES_IN
2953 #if ENABLE_HUSH_CASE
2954 || ctx->ctx_res_w == RES_ESAC
2958 debug_printf_parse("done_pipe: adding new pipe: "
2959 "not_null:%d ctx->ctx_res_w:%d\n",
2960 not_null, ctx->ctx_res_w);
2962 ctx->pipe->next = new_p;
2964 /* RES_THEN, RES_DO etc are "sticky" -
2965 * they remain set for pipes inside if/while.
2966 * This is used to control execution.
2967 * RES_FOR and RES_IN are NOT sticky (needed to support
2968 * cases where variable or value happens to match a keyword):
2970 #if ENABLE_HUSH_LOOPS
2971 if (ctx->ctx_res_w == RES_FOR
2972 || ctx->ctx_res_w == RES_IN)
2973 ctx->ctx_res_w = RES_NONE;
2975 #if ENABLE_HUSH_CASE
2976 if (ctx->ctx_res_w == RES_MATCH)
2977 ctx->ctx_res_w = RES_CASE_BODY;
2978 if (ctx->ctx_res_w == RES_CASE)
2979 ctx->ctx_res_w = RES_CASE_IN;
2981 ctx->command = NULL; /* trick done_command below */
2982 /* Create the memory for command, roughly:
2983 * ctx->pipe->cmds = new struct command;
2984 * ctx->command = &ctx->pipe->cmds[0];
2987 //debug_print_tree(ctx->list_head, 10);
2989 debug_printf_parse("done_pipe return\n");
2992 static void initialize_context(struct parse_context *ctx)
2994 memset(ctx, 0, sizeof(*ctx));
2995 ctx->pipe = ctx->list_head = new_pipe();
2996 /* Create the memory for command, roughly:
2997 * ctx->pipe->cmds = new struct command;
2998 * ctx->command = &ctx->pipe->cmds[0];
3003 /* If a reserved word is found and processed, parse context is modified
3004 * and 1 is returned.
3007 struct reserved_combo {
3010 unsigned char assignment_flag;
3014 FLAG_END = (1 << RES_NONE ),
3016 FLAG_IF = (1 << RES_IF ),
3017 FLAG_THEN = (1 << RES_THEN ),
3018 FLAG_ELIF = (1 << RES_ELIF ),
3019 FLAG_ELSE = (1 << RES_ELSE ),
3020 FLAG_FI = (1 << RES_FI ),
3022 # if ENABLE_HUSH_LOOPS
3023 FLAG_FOR = (1 << RES_FOR ),
3024 FLAG_WHILE = (1 << RES_WHILE),
3025 FLAG_UNTIL = (1 << RES_UNTIL),
3026 FLAG_DO = (1 << RES_DO ),
3027 FLAG_DONE = (1 << RES_DONE ),
3028 FLAG_IN = (1 << RES_IN ),
3030 # if ENABLE_HUSH_CASE
3031 FLAG_MATCH = (1 << RES_MATCH),
3032 FLAG_ESAC = (1 << RES_ESAC ),
3034 FLAG_START = (1 << RES_XXXX ),
3037 static const struct reserved_combo* match_reserved_word(o_string *word)
3039 /* Mostly a list of accepted follow-up reserved words.
3040 * FLAG_END means we are done with the sequence, and are ready
3041 * to turn the compound list into a command.
3042 * FLAG_START means the word must start a new compound list.
3044 static const struct reserved_combo reserved_list[] = {
3046 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3047 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3048 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3049 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3050 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3051 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3053 # if ENABLE_HUSH_LOOPS
3054 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3055 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3056 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3057 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3058 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3059 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3061 # if ENABLE_HUSH_CASE
3062 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3063 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3066 const struct reserved_combo *r;
3068 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3069 if (strcmp(word->data, r->literal) == 0)
3074 /* Return 0: not a keyword, 1: keyword
3076 static int reserved_word(o_string *word, struct parse_context *ctx)
3078 # if ENABLE_HUSH_CASE
3079 static const struct reserved_combo reserved_match = {
3080 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3083 const struct reserved_combo *r;
3085 if (word->has_quoted_part)
3087 r = match_reserved_word(word);
3091 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3092 # if ENABLE_HUSH_CASE
3093 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3094 /* "case word IN ..." - IN part starts first MATCH part */
3095 r = &reserved_match;
3098 if (r->flag == 0) { /* '!' */
3099 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3100 syntax_error("! ! command");
3101 ctx->ctx_res_w = RES_SNTX;
3103 ctx->ctx_inverted = 1;
3106 if (r->flag & FLAG_START) {
3107 struct parse_context *old;
3109 old = xmalloc(sizeof(*old));
3110 debug_printf_parse("push stack %p\n", old);
3111 *old = *ctx; /* physical copy */
3112 initialize_context(ctx);
3114 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3115 syntax_error_at(word->data);
3116 ctx->ctx_res_w = RES_SNTX;
3119 /* "{...} fi" is ok. "{...} if" is not
3121 * if { echo foo; } then { echo bar; } fi */
3122 if (ctx->command->group)
3123 done_pipe(ctx, PIPE_SEQ);
3126 ctx->ctx_res_w = r->res;
3127 ctx->old_flag = r->flag;
3128 word->o_assignment = r->assignment_flag;
3129 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3131 if (ctx->old_flag & FLAG_END) {
3132 struct parse_context *old;
3134 done_pipe(ctx, PIPE_SEQ);
3135 debug_printf_parse("pop stack %p\n", ctx->stack);
3137 old->command->group = ctx->list_head;
3138 old->command->cmd_type = CMD_NORMAL;
3140 o_addstr(&old->as_string, ctx->as_string.data);
3141 o_free_unsafe(&ctx->as_string);
3142 old->command->group_as_string = xstrdup(old->as_string.data);
3143 debug_printf_parse("pop, remembering as:'%s'\n",
3144 old->command->group_as_string);
3146 *ctx = *old; /* physical copy */
3151 #endif /* HAS_KEYWORDS */
3153 /* Word is complete, look at it and update parsing context.
3154 * Normal return is 0. Syntax errors return 1.
3155 * Note: on return, word is reset, but not o_free'd!
3157 static int done_word(o_string *word, struct parse_context *ctx)
3159 struct command *command = ctx->command;
3161 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3162 if (word->length == 0 && !word->has_quoted_part) {
3163 debug_printf_parse("done_word return 0: true null, ignored\n");
3167 if (ctx->pending_redirect) {
3168 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3169 * only if run as "bash", not "sh" */
3170 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3172 * ...the word that follows the redirection operator
3173 * shall be subjected to tilde expansion, parameter expansion,
3174 * command substitution, arithmetic expansion, and quote
3175 * removal. Pathname expansion shall not be performed
3176 * on the word by a non-interactive shell; an interactive
3177 * shell may perform it, but shall do so only when
3178 * the expansion would result in one word."
3180 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3181 /* Cater for >\file case:
3182 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3183 * Same with heredocs:
3184 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3186 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3187 unbackslash(ctx->pending_redirect->rd_filename);
3188 /* Is it <<"HEREDOC"? */
3189 if (word->has_quoted_part) {
3190 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3193 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3194 ctx->pending_redirect = NULL;
3197 # if ENABLE_HUSH_CASE
3198 if (ctx->ctx_dsemicolon
3199 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3201 /* already done when ctx_dsemicolon was set to 1: */
3202 /* ctx->ctx_res_w = RES_MATCH; */
3203 ctx->ctx_dsemicolon = 0;
3206 if (!command->argv /* if it's the first word... */
3207 # if ENABLE_HUSH_LOOPS
3208 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3209 && ctx->ctx_res_w != RES_IN
3211 # if ENABLE_HUSH_CASE
3212 && ctx->ctx_res_w != RES_CASE
3215 int reserved = reserved_word(word, ctx);
3216 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3218 o_reset_to_empty_unquoted(word);
3219 debug_printf_parse("done_word return %d\n",
3220 (ctx->ctx_res_w == RES_SNTX));
3221 return (ctx->ctx_res_w == RES_SNTX);
3223 # if ENABLE_HUSH_BASH_COMPAT
3224 if (strcmp(word->data, "[[") == 0) {
3225 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3231 if (command->group) {
3232 /* "{ echo foo; } echo bar" - bad */
3233 syntax_error_at(word->data);
3234 debug_printf_parse("done_word return 1: syntax error, "
3235 "groups and arglists don't mix\n");
3239 /* If this word wasn't an assignment, next ones definitely
3240 * can't be assignments. Even if they look like ones. */
3241 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3242 && word->o_assignment != WORD_IS_KEYWORD
3244 word->o_assignment = NOT_ASSIGNMENT;
3246 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3247 command->assignment_cnt++;
3248 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3250 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3251 word->o_assignment = MAYBE_ASSIGNMENT;
3253 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3255 if (word->has_quoted_part
3256 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3257 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3258 /* (otherwise it's known to be not empty and is already safe) */
3260 /* exclude "$@" - it can expand to no word despite "" */
3261 char *p = word->data;
3262 while (p[0] == SPECIAL_VAR_SYMBOL
3263 && (p[1] & 0x7f) == '@'
3264 && p[2] == SPECIAL_VAR_SYMBOL
3269 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3270 debug_print_strings("word appended to argv", command->argv);
3273 #if ENABLE_HUSH_LOOPS
3274 if (ctx->ctx_res_w == RES_FOR) {
3275 if (word->has_quoted_part
3276 || !is_well_formed_var_name(command->argv[0], '\0')
3278 /* bash says just "not a valid identifier" */
3279 syntax_error("not a valid identifier in for");
3282 /* Force FOR to have just one word (variable name) */
3283 /* NB: basically, this makes hush see "for v in ..."
3284 * syntax as if it is "for v; in ...". FOR and IN become
3285 * two pipe structs in parse tree. */
3286 done_pipe(ctx, PIPE_SEQ);
3289 #if ENABLE_HUSH_CASE
3290 /* Force CASE to have just one word */
3291 if (ctx->ctx_res_w == RES_CASE) {
3292 done_pipe(ctx, PIPE_SEQ);
3296 o_reset_to_empty_unquoted(word);
3298 debug_printf_parse("done_word return 0\n");
3303 /* Peek ahead in the input to find out if we have a "&n" construct,
3304 * as in "2>&1", that represents duplicating a file descriptor.
3306 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3307 * REDIRFD_SYNTAX_ERR if syntax error,
3308 * REDIRFD_TO_FILE if no & was seen,
3309 * or the number found.
3312 #define parse_redir_right_fd(as_string, input) \
3313 parse_redir_right_fd(input)
3315 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3321 return REDIRFD_TO_FILE;
3323 ch = i_getch(input); /* get the & */
3324 nommu_addchr(as_string, ch);
3327 ch = i_getch(input);
3328 nommu_addchr(as_string, ch);
3329 return REDIRFD_CLOSE;
3333 while (ch != EOF && isdigit(ch)) {
3334 d = d*10 + (ch-'0');
3336 ch = i_getch(input);
3337 nommu_addchr(as_string, ch);
3342 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3344 bb_error_msg("ambiguous redirect");
3345 return REDIRFD_SYNTAX_ERR;
3348 /* Return code is 0 normal, 1 if a syntax error is detected
3350 static int parse_redirect(struct parse_context *ctx,
3353 struct in_str *input)
3355 struct command *command = ctx->command;
3356 struct redir_struct *redir;
3357 struct redir_struct **redirp;
3360 dup_num = REDIRFD_TO_FILE;
3361 if (style != REDIRECT_HEREDOC) {
3362 /* Check for a '>&1' type redirect */
3363 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3364 if (dup_num == REDIRFD_SYNTAX_ERR)
3367 int ch = i_peek(input);
3368 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3369 if (dup_num) { /* <<-... */
3370 ch = i_getch(input);
3371 nommu_addchr(&ctx->as_string, ch);
3376 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3377 int ch = i_peek(input);
3379 /* >|FILE redirect ("clobbering" >).
3380 * Since we do not support "set -o noclobber" yet,
3381 * >| and > are the same for now. Just eat |.
3383 ch = i_getch(input);
3384 nommu_addchr(&ctx->as_string, ch);
3388 /* Create a new redir_struct and append it to the linked list */
3389 redirp = &command->redirects;
3390 while ((redir = *redirp) != NULL) {
3391 redirp = &(redir->next);
3393 *redirp = redir = xzalloc(sizeof(*redir));
3394 /* redir->next = NULL; */
3395 /* redir->rd_filename = NULL; */
3396 redir->rd_type = style;
3397 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3399 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3400 redir_table[style].descrip);
3402 redir->rd_dup = dup_num;
3403 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3404 /* Erik had a check here that the file descriptor in question
3405 * is legit; I postpone that to "run time"
3406 * A "-" representation of "close me" shows up as a -3 here */
3407 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3408 redir->rd_fd, redir->rd_dup);
3410 /* Set ctx->pending_redirect, so we know what to do at the
3411 * end of the next parsed word. */
3412 ctx->pending_redirect = redir;
3417 /* If a redirect is immediately preceded by a number, that number is
3418 * supposed to tell which file descriptor to redirect. This routine
3419 * looks for such preceding numbers. In an ideal world this routine
3420 * needs to handle all the following classes of redirects...
3421 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3422 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3423 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3424 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3426 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3428 * ... If n is quoted, the number shall not be recognized as part of
3429 * the redirection expression. For example:
3431 * writes the character 2 into file a"
3432 * We are getting it right by setting ->has_quoted_part on any \<char>
3434 * A -1 return means no valid number was found,
3435 * the caller should use the appropriate default for this redirection.
3437 static int redirect_opt_num(o_string *o)
3441 if (o->data == NULL)
3443 num = bb_strtou(o->data, NULL, 10);
3444 if (errno || num < 0)
3446 o_reset_to_empty_unquoted(o);
3451 #define fetch_till_str(as_string, input, word, skip_tabs) \
3452 fetch_till_str(input, word, skip_tabs)
3454 static char *fetch_till_str(o_string *as_string,
3455 struct in_str *input,
3459 o_string heredoc = NULL_O_STRING;
3461 int prev = 0; /* not \ */
3467 ch = i_getch(input);
3469 nommu_addchr(as_string, ch);
3470 if ((ch == '\n' || ch == EOF)
3471 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3473 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3474 heredoc.data[past_EOL] = '\0';
3475 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3476 return heredoc.data;
3478 while (ch == '\n') {
3479 o_addchr(&heredoc, ch);
3482 past_EOL = heredoc.length;
3484 ch = i_getch(input);
3486 nommu_addchr(as_string, ch);
3487 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3491 o_free_unsafe(&heredoc);
3494 o_addchr(&heredoc, ch);
3495 nommu_addchr(as_string, ch);
3496 if (prev == '\\' && ch == '\\')
3497 /* Correctly handle foo\\<eol> (not a line cont.) */
3498 prev = 0; /* not \ */
3504 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3505 * and load them all. There should be exactly heredoc_cnt of them.
3507 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3509 struct pipe *pi = ctx->list_head;
3511 while (pi && heredoc_cnt) {
3513 struct command *cmd = pi->cmds;
3515 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3517 cmd->argv ? cmd->argv[0] : "NONE");
3518 for (i = 0; i < pi->num_cmds; i++) {
3519 struct redir_struct *redir = cmd->redirects;
3521 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3522 i, cmd->argv ? cmd->argv[0] : "NONE");
3524 if (redir->rd_type == REDIRECT_HEREDOC) {
3527 redir->rd_type = REDIRECT_HEREDOC2;
3528 /* redir->rd_dup is (ab)used to indicate <<- */
3529 p = fetch_till_str(&ctx->as_string, input,
3530 redir->rd_filename, redir->rd_dup);
3532 syntax_error("unexpected EOF in here document");
3535 free(redir->rd_filename);
3536 redir->rd_filename = p;
3539 redir = redir->next;
3546 /* Should be 0. If it isn't, it's a parse error */
3548 bb_error_msg_and_die("heredoc BUG 2");
3554 static int run_list(struct pipe *pi);
3556 #define parse_stream(pstring, input, end_trigger) \
3557 parse_stream(input, end_trigger)
3559 static struct pipe *parse_stream(char **pstring,
3560 struct in_str *input,
3564 #if !ENABLE_HUSH_FUNCTIONS
3565 #define parse_group(dest, ctx, input, ch) \
3566 parse_group(ctx, input, ch)
3568 static int parse_group(o_string *dest, struct parse_context *ctx,
3569 struct in_str *input, int ch)
3571 /* dest contains characters seen prior to ( or {.
3572 * Typically it's empty, but for function defs,
3573 * it contains function name (without '()'). */
3574 struct pipe *pipe_list;
3576 struct command *command = ctx->command;
3578 debug_printf_parse("parse_group entered\n");
3579 #if ENABLE_HUSH_FUNCTIONS
3580 if (ch == '(' && !dest->has_quoted_part) {
3582 if (done_word(dest, ctx))
3585 goto skip; /* (... */
3586 if (command->argv[1]) { /* word word ... (... */
3587 syntax_error_unexpected_ch('(');
3590 /* it is "word(..." or "word (..." */
3592 ch = i_getch(input);
3593 while (ch == ' ' || ch == '\t');
3595 syntax_error_unexpected_ch(ch);
3598 nommu_addchr(&ctx->as_string, ch);
3600 ch = i_getch(input);
3601 while (ch == ' ' || ch == '\t' || ch == '\n');
3603 syntax_error_unexpected_ch(ch);
3606 nommu_addchr(&ctx->as_string, ch);
3607 command->cmd_type = CMD_FUNCDEF;
3612 #if 0 /* Prevented by caller */
3613 if (command->argv /* word [word]{... */
3614 || dest->length /* word{... */
3615 || dest->has_quoted_part /* ""{... */
3618 debug_printf_parse("parse_group return 1: "
3619 "syntax error, groups and arglists don't mix\n");
3624 #if ENABLE_HUSH_FUNCTIONS
3630 command->cmd_type = CMD_SUBSHELL;
3632 /* bash does not allow "{echo...", requires whitespace */
3633 ch = i_getch(input);
3634 if (ch != ' ' && ch != '\t' && ch != '\n') {
3635 syntax_error_unexpected_ch(ch);
3638 nommu_addchr(&ctx->as_string, ch);
3643 # define as_string NULL
3645 char *as_string = NULL;
3647 pipe_list = parse_stream(&as_string, input, endch);
3650 o_addstr(&ctx->as_string, as_string);
3652 /* empty ()/{} or parse error? */
3653 if (!pipe_list || pipe_list == ERR_PTR) {
3654 /* parse_stream already emitted error msg */
3657 debug_printf_parse("parse_group return 1: "
3658 "parse_stream returned %p\n", pipe_list);
3661 command->group = pipe_list;
3663 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3664 command->group_as_string = as_string;
3665 debug_printf_parse("end of group, remembering as:'%s'\n",
3666 command->group_as_string);
3670 debug_printf_parse("parse_group return 0\n");
3672 /* command remains "open", available for possible redirects */
3675 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3676 /* Subroutines for copying $(...) and `...` things */
3677 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3679 static int add_till_single_quote(o_string *dest, struct in_str *input)
3682 int ch = i_getch(input);
3684 syntax_error_unterm_ch('\'');
3692 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3693 static int add_till_double_quote(o_string *dest, struct in_str *input)
3696 int ch = i_getch(input);
3698 syntax_error_unterm_ch('"');
3703 if (ch == '\\') { /* \x. Copy both chars. */
3705 ch = i_getch(input);
3709 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3714 //if (ch == '$') ...
3717 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3719 * "Within the backquoted style of command substitution, backslash
3720 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3721 * The search for the matching backquote shall be satisfied by the first
3722 * backquote found without a preceding backslash; during this search,
3723 * if a non-escaped backquote is encountered within a shell comment,
3724 * a here-document, an embedded command substitution of the $(command)
3725 * form, or a quoted string, undefined results occur. A single-quoted
3726 * or double-quoted string that begins, but does not end, within the
3727 * "`...`" sequence produces undefined results."
3729 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3731 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3734 int ch = i_getch(input);
3738 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3739 ch = i_getch(input);
3743 && (!in_dquote || ch != '"')
3745 o_addchr(dest, '\\');
3749 syntax_error_unterm_ch('`');
3755 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3756 * quoting and nested ()s.
3757 * "With the $(command) style of command substitution, all characters
3758 * following the open parenthesis to the matching closing parenthesis
3759 * constitute the command. Any valid shell script can be used for command,
3760 * except a script consisting solely of redirections which produces
3761 * unspecified results."
3763 * echo $(echo '(TEST)' BEST) (TEST) BEST
3764 * echo $(echo 'TEST)' BEST) TEST) BEST
3765 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3767 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3768 * can contain arbitrary constructs, just like $(cmd).
3769 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3770 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3772 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3773 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3776 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3777 # if ENABLE_HUSH_BASH_COMPAT
3778 char end_char2 = end_ch >> 8;
3780 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3783 ch = i_getch(input);
3785 syntax_error_unterm_ch(end_ch);
3788 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3791 /* we look for closing )) of $((EXPR)) */
3792 if (i_peek(input) == end_ch) {
3793 i_getch(input); /* eat second ')' */
3798 if (ch == '(' || ch == '{') {
3799 ch = (ch == '(' ? ')' : '}');
3800 if (!add_till_closing_bracket(dest, input, ch))
3806 if (!add_till_single_quote(dest, input))
3812 if (!add_till_double_quote(dest, input))
3818 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3824 /* \x. Copy verbatim. Important for \(, \) */
3825 ch = i_getch(input);
3827 syntax_error_unterm_ch(')');
3836 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3838 /* Return code: 0 for OK, 1 for syntax error */
3840 #define parse_dollar(as_string, dest, input, quote_mask) \
3841 parse_dollar(dest, input, quote_mask)
3842 #define as_string NULL
3844 static int parse_dollar(o_string *as_string,
3846 struct in_str *input, unsigned char quote_mask)
3848 int ch = i_peek(input); /* first character after the $ */
3850 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3852 ch = i_getch(input);
3853 nommu_addchr(as_string, ch);
3855 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3857 debug_printf_parse(": '%c'\n", ch);
3858 o_addchr(dest, ch | quote_mask);
3861 if (!isalnum(ch) && ch != '_')
3863 ch = i_getch(input);
3864 nommu_addchr(as_string, ch);
3866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3867 } else if (isdigit(ch)) {
3869 ch = i_getch(input);
3870 nommu_addchr(as_string, ch);
3871 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3872 debug_printf_parse(": '%c'\n", ch);
3873 o_addchr(dest, ch | quote_mask);
3874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3875 } else switch (ch) {
3877 case '!': /* last bg pid */
3878 case '?': /* last exit code */
3879 case '#': /* number of args */
3880 case '*': /* args */
3881 case '@': /* args */
3882 goto make_one_char_var;
3884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3886 ch = i_getch(input); /* eat '{' */
3887 nommu_addchr(as_string, ch);
3889 ch = i_getch(input); /* first char after '{' */
3890 /* It should be ${?}, or ${#var},
3891 * or even ${?+subst} - operator acting on a special variable,
3892 * or the beginning of variable name.
3895 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3898 syntax_error_unterm_str("${name}");
3899 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3902 nommu_addchr(as_string, ch);
3905 /* It's possible to just call add_till_closing_bracket() at this point.
3906 * However, this regresses some of our testsuite cases
3907 * which check invalid constructs like ${%}.
3908 * Oh well... let's check that the var name part is fine... */
3914 debug_printf_parse(": '%c'\n", ch);
3916 ch = i_getch(input);
3917 nommu_addchr(as_string, ch);
3921 if (!isalnum(ch) && ch != '_') {
3923 unsigned char last_ch;
3924 /* handle parameter expansions
3925 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3927 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3928 goto bad_dollar_syntax;
3930 /* Eat everything until closing '}' (or ':') */
3932 if (ENABLE_HUSH_BASH_COMPAT
3934 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3936 /* It's ${var:N[:M]} thing */
3937 end_ch = '}' * 0x100 + ':';
3939 if (ENABLE_HUSH_BASH_COMPAT
3942 /* It's ${var/[/]pattern[/repl]} thing */
3943 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3945 nommu_addchr(as_string, '/');
3948 end_ch = '}' * 0x100 + '/';
3954 #if ENABLE_HUSH_DOLLAR_OPS
3955 last_ch = add_till_closing_bracket(dest, input, end_ch);
3956 if (last_ch == 0) /* error? */
3959 #error Simple code to only allow ${var} is not implemented
3962 o_addstr(as_string, dest->data + pos);
3963 o_addchr(as_string, last_ch);
3966 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3967 /* close the first block: */
3968 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3969 /* while parsing N from ${var:N[:M]}
3970 * or pattern from ${var/[/]pattern[/repl]} */
3971 if ((end_ch & 0xff) == last_ch) {
3972 /* got ':' or '/'- parse the rest */
3977 if (end_ch == '}' * 0x100 + ':') {
3978 /* it's ${var:N} - emulate :999999999 */
3979 o_addstr(dest, "999999999");
3980 } /* else: it's ${var/[/]pattern} */
3985 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3988 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3992 ch = i_getch(input);
3993 nommu_addchr(as_string, ch);
3994 # if ENABLE_SH_MATH_SUPPORT
3995 if (i_peek(input) == '(') {
3996 ch = i_getch(input);
3997 nommu_addchr(as_string, ch);
3998 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3999 o_addchr(dest, /*quote_mask |*/ '+');
4002 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4003 return 0; /* error */
4005 o_addstr(as_string, dest->data + pos);
4006 o_addchr(as_string, ')');
4007 o_addchr(as_string, ')');
4009 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4013 # if ENABLE_HUSH_TICK
4014 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4015 o_addchr(dest, quote_mask | '`');
4018 if (!add_till_closing_bracket(dest, input, ')'))
4019 return 0; /* error */
4021 o_addstr(as_string, dest->data + pos);
4022 o_addchr(as_string, ')');
4024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4030 ch = i_getch(input);
4031 nommu_addchr(as_string, ch);
4033 if (isalnum(ch)) { /* it's $_name or $_123 */
4038 /* TODO: $_ and $-: */
4039 /* $_ Shell or shell script name; or last argument of last command
4040 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4041 * but in command's env, set to full pathname used to invoke it */
4042 /* $- Option flags set by set builtin or shell options (-i etc) */
4044 o_addQchr(dest, '$');
4046 debug_printf_parse("parse_dollar return 1 (ok)\n");
4052 # if ENABLE_HUSH_BASH_COMPAT
4053 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4054 encode_string(dest, input, dquote_end, process_bkslash)
4056 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4057 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4058 encode_string(dest, input, dquote_end)
4060 #define as_string NULL
4064 # if ENABLE_HUSH_BASH_COMPAT
4065 /* all parameters are needed, no macro tricks */
4067 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4068 encode_string(as_string, dest, input, dquote_end)
4071 static int encode_string(o_string *as_string,
4073 struct in_str *input,
4075 int process_bkslash)
4077 #if !ENABLE_HUSH_BASH_COMPAT
4078 const int process_bkslash = 1;
4084 ch = i_getch(input);
4086 nommu_addchr(as_string, ch);
4087 if (ch == dquote_end) { /* may be only '"' or EOF */
4088 debug_printf_parse("encode_string return 1 (ok)\n");
4091 /* note: can't move it above ch == dquote_end check! */
4093 syntax_error_unterm_ch('"');
4094 return 0; /* error */
4098 next = i_peek(input);
4100 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4101 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4102 if (process_bkslash && ch == '\\') {
4104 syntax_error("\\<eof>");
4108 * "The backslash retains its special meaning [in "..."]
4109 * only when followed by one of the following characters:
4110 * $, `, ", \, or <newline>. A double quote may be quoted
4111 * within double quotes by preceding it with a backslash."
4112 * NB: in (unquoted) heredoc, above does not apply to ",
4113 * therefore we check for it by "next == dquote_end" cond.
4115 if (next == dquote_end || strchr("$`\\\n", next)) {
4116 ch = i_getch(input); /* eat next */
4118 goto again; /* skip \<newline> */
4119 } /* else: ch remains == '\\', and we double it below: */
4120 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4121 nommu_addchr(as_string, ch);
4125 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4126 debug_printf_parse("encode_string return 0: "
4127 "parse_dollar returned 0 (error)\n");
4132 #if ENABLE_HUSH_TICK
4134 //unsigned pos = dest->length;
4135 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4136 o_addchr(dest, 0x80 | '`');
4137 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4138 return 0; /* error */
4139 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4140 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4144 o_addQchr(dest, ch);
4150 * Scan input until EOF or end_trigger char.
4151 * Return a list of pipes to execute, or NULL on EOF
4152 * or if end_trigger character is met.
4153 * On syntax error, exit if shell is not interactive,
4154 * reset parsing machinery and start parsing anew,
4155 * or return ERR_PTR.
4157 static struct pipe *parse_stream(char **pstring,
4158 struct in_str *input,
4161 struct parse_context ctx;
4162 o_string dest = NULL_O_STRING;
4165 /* Single-quote triggers a bypass of the main loop until its mate is
4166 * found. When recursing, quote state is passed in via dest->o_expflags.
4168 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4169 end_trigger ? end_trigger : 'X');
4172 /* If very first arg is "" or '', dest.data may end up NULL.
4173 * Preventing this: */
4174 o_addchr(&dest, '\0');
4177 /* We used to separate words on $IFS here. This was wrong.
4178 * $IFS is used only for word splitting when $var is expanded,
4179 * here we should use blank chars as separators, not $IFS
4182 if (MAYBE_ASSIGNMENT != 0)
4183 dest.o_assignment = MAYBE_ASSIGNMENT;
4184 initialize_context(&ctx);
4187 const char *is_blank;
4188 const char *is_special;
4192 redir_type redir_style;
4194 ch = i_getch(input);
4195 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4196 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4201 syntax_error_unterm_str("here document");
4204 /* end_trigger == '}' case errors out earlier,
4205 * checking only ')' */
4206 if (end_trigger == ')') {
4207 syntax_error_unterm_ch('(');
4211 if (done_word(&dest, &ctx)) {
4215 done_pipe(&ctx, PIPE_SEQ);
4217 /* If we got nothing... */
4218 /* (this makes bare "&" cmd a no-op.
4219 * bash says: "syntax error near unexpected token '&'") */
4220 if (pi->num_cmds == 0
4221 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4227 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4229 *pstring = ctx.as_string.data;
4231 o_free_unsafe(&ctx.as_string);
4234 debug_printf_parse("parse_stream return %p\n", pi);
4237 nommu_addchr(&ctx.as_string, ch);
4241 next = i_peek(input);
4243 is_special = "{}<>;&|()#'" /* special outside of "str" */
4244 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4245 /* Are { and } special here? */
4246 if (ctx.command->argv /* word [word]{... - non-special */
4247 || dest.length /* word{... - non-special */
4248 || dest.has_quoted_part /* ""{... - non-special */
4249 || (next != ';' /* }; - special */
4250 && next != ')' /* }) - special */
4251 && next != '&' /* }& and }&& ... - special */
4252 && next != '|' /* }|| ... - special */
4253 && !strchr(defifs, next) /* {word - non-special */
4256 /* They are not special, skip "{}" */
4259 is_special = strchr(is_special, ch);
4260 is_blank = strchr(defifs, ch);
4262 if (!is_special && !is_blank) { /* ordinary char */
4264 o_addQchr(&dest, ch);
4265 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4266 || dest.o_assignment == WORD_IS_KEYWORD)
4268 && is_well_formed_var_name(dest.data, '=')
4270 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4271 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4277 if (done_word(&dest, &ctx)) {
4281 /* Is this a case when newline is simply ignored?
4283 * "cmd | <newline> cmd ..."
4284 * "case ... in <newline> word) ..."
4286 if (IS_NULL_CMD(ctx.command)
4287 && dest.length == 0 && !dest.has_quoted_part
4289 /* This newline can be ignored. But...
4290 * Without check #1, interactive shell
4291 * ignores even bare <newline>,
4292 * and shows the continuation prompt:
4293 * ps1_prompt$ <enter>
4294 * ps2> _ <=== wrong, should be ps1
4295 * Without check #2, "cmd & <newline>"
4296 * is similarly mistreated.
4297 * (BTW, this makes "cmd & cmd"
4298 * and "cmd && cmd" non-orthogonal.
4299 * Really, ask yourself, why
4300 * "cmd && <newline>" doesn't start
4301 * cmd but waits for more input?
4304 struct pipe *pi = ctx.list_head;
4305 if (pi->num_cmds != 0 /* check #1 */
4306 && pi->followup != PIPE_BG /* check #2 */
4311 /* Treat newline as a command separator. */
4312 done_pipe(&ctx, PIPE_SEQ);
4313 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4315 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4320 dest.o_assignment = MAYBE_ASSIGNMENT;
4321 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4323 /* note: if (is_blank) continue;
4324 * will still trigger for us */
4328 /* "cmd}" or "cmd }..." without semicolon or &:
4329 * } is an ordinary char in this case, even inside { cmd; }
4330 * Pathological example: { ""}; } should exec "}" cmd
4333 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4334 || dest.length != 0 /* word} */
4335 || dest.has_quoted_part /* ""} */
4339 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4340 goto skip_end_trigger;
4341 /* else: } does terminate a group */
4344 if (end_trigger && end_trigger == ch
4345 && (ch != ';' || heredoc_cnt == 0)
4346 #if ENABLE_HUSH_CASE
4348 || ctx.ctx_res_w != RES_MATCH
4349 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4354 /* This is technically valid:
4355 * { cat <<HERE; }; echo Ok
4359 * but we don't support this.
4360 * We require heredoc to be in enclosing {}/(),
4363 syntax_error_unterm_str("here document");
4366 if (done_word(&dest, &ctx)) {
4369 done_pipe(&ctx, PIPE_SEQ);
4370 dest.o_assignment = MAYBE_ASSIGNMENT;
4371 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4372 /* Do we sit outside of any if's, loops or case's? */
4374 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4378 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4380 *pstring = ctx.as_string.data;
4382 o_free_unsafe(&ctx.as_string);
4385 debug_printf_parse("parse_stream return %p: "
4386 "end_trigger char found\n",
4388 return ctx.list_head;
4395 /* Catch <, > before deciding whether this word is
4396 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4399 redir_fd = redirect_opt_num(&dest);
4400 if (done_word(&dest, &ctx)) {
4403 redir_style = REDIRECT_OVERWRITE;
4405 redir_style = REDIRECT_APPEND;
4406 ch = i_getch(input);
4407 nommu_addchr(&ctx.as_string, ch);
4410 else if (next == '(') {
4411 syntax_error(">(process) not supported");
4415 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4417 continue; /* back to top of while (1) */
4419 redir_fd = redirect_opt_num(&dest);
4420 if (done_word(&dest, &ctx)) {
4423 redir_style = REDIRECT_INPUT;
4425 redir_style = REDIRECT_HEREDOC;
4427 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4428 ch = i_getch(input);
4429 nommu_addchr(&ctx.as_string, ch);
4430 } else if (next == '>') {
4431 redir_style = REDIRECT_IO;
4432 ch = i_getch(input);
4433 nommu_addchr(&ctx.as_string, ch);
4436 else if (next == '(') {
4437 syntax_error("<(process) not supported");
4441 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4443 continue; /* back to top of while (1) */
4445 if (dest.length == 0 && !dest.has_quoted_part) {
4446 /* skip "#comment" */
4449 if (ch == EOF || ch == '\n')
4452 /* note: we do not add it to &ctx.as_string */
4454 nommu_addchr(&ctx.as_string, '\n');
4455 continue; /* back to top of while (1) */
4460 /* It's "\<newline>" */
4462 /* Remove trailing '\' from ctx.as_string */
4463 ctx.as_string.data[--ctx.as_string.length] = '\0';
4465 ch = i_getch(input); /* eat it */
4466 continue; /* back to top of while (1) */
4471 if (dest.o_assignment == MAYBE_ASSIGNMENT
4472 /* check that we are not in word in "a=1 2>word b=1": */
4473 && !ctx.pending_redirect
4475 /* ch is a special char and thus this word
4476 * cannot be an assignment */
4477 dest.o_assignment = NOT_ASSIGNMENT;
4478 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4481 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4484 case '#': /* non-comment #: "echo a#b" etc */
4485 o_addQchr(&dest, ch);
4489 syntax_error("\\<eof>");
4492 ch = i_getch(input);
4493 /* note: ch != '\n' (that case does not reach this place) */
4494 o_addchr(&dest, '\\');
4495 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4496 o_addchr(&dest, ch);
4497 nommu_addchr(&ctx.as_string, ch);
4498 /* Example: echo Hello \2>file
4499 * we need to know that word 2 is quoted */
4500 dest.has_quoted_part = 1;
4503 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4504 debug_printf_parse("parse_stream parse error: "
4505 "parse_dollar returned 0 (error)\n");
4510 dest.has_quoted_part = 1;
4511 if (next == '\'' && !ctx.pending_redirect) {
4512 insert_empty_quoted_str_marker:
4513 nommu_addchr(&ctx.as_string, next);
4514 i_getch(input); /* eat second ' */
4515 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4516 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4519 ch = i_getch(input);
4521 syntax_error_unterm_ch('\'');
4524 nommu_addchr(&ctx.as_string, ch);
4527 o_addqchr(&dest, ch);
4532 dest.has_quoted_part = 1;
4533 if (next == '"' && !ctx.pending_redirect)
4534 goto insert_empty_quoted_str_marker;
4535 if (dest.o_assignment == NOT_ASSIGNMENT)
4536 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4537 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4539 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4541 #if ENABLE_HUSH_TICK
4543 USE_FOR_NOMMU(unsigned pos;)
4545 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4546 o_addchr(&dest, '`');
4547 USE_FOR_NOMMU(pos = dest.length;)
4548 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4551 o_addstr(&ctx.as_string, dest.data + pos);
4552 o_addchr(&ctx.as_string, '`');
4554 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4555 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4560 #if ENABLE_HUSH_CASE
4563 if (done_word(&dest, &ctx)) {
4566 done_pipe(&ctx, PIPE_SEQ);
4567 #if ENABLE_HUSH_CASE
4568 /* Eat multiple semicolons, detect
4569 * whether it means something special */
4574 ch = i_getch(input);
4575 nommu_addchr(&ctx.as_string, ch);
4576 if (ctx.ctx_res_w == RES_CASE_BODY) {
4577 ctx.ctx_dsemicolon = 1;
4578 ctx.ctx_res_w = RES_MATCH;
4584 /* We just finished a cmd. New one may start
4585 * with an assignment */
4586 dest.o_assignment = MAYBE_ASSIGNMENT;
4587 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4590 if (done_word(&dest, &ctx)) {
4594 ch = i_getch(input);
4595 nommu_addchr(&ctx.as_string, ch);
4596 done_pipe(&ctx, PIPE_AND);
4598 done_pipe(&ctx, PIPE_BG);
4602 if (done_word(&dest, &ctx)) {
4605 #if ENABLE_HUSH_CASE
4606 if (ctx.ctx_res_w == RES_MATCH)
4607 break; /* we are in case's "word | word)" */
4609 if (next == '|') { /* || */
4610 ch = i_getch(input);
4611 nommu_addchr(&ctx.as_string, ch);
4612 done_pipe(&ctx, PIPE_OR);
4614 /* we could pick up a file descriptor choice here
4615 * with redirect_opt_num(), but bash doesn't do it.
4616 * "echo foo 2| cat" yields "foo 2". */
4619 o_reset_to_empty_unquoted(&ctx.as_string);
4624 #if ENABLE_HUSH_CASE
4625 /* "case... in [(]word)..." - skip '(' */
4626 if (ctx.ctx_res_w == RES_MATCH
4627 && ctx.command->argv == NULL /* not (word|(... */
4628 && dest.length == 0 /* not word(... */
4629 && dest.has_quoted_part == 0 /* not ""(... */
4635 if (parse_group(&dest, &ctx, input, ch) != 0) {
4640 #if ENABLE_HUSH_CASE
4641 if (ctx.ctx_res_w == RES_MATCH)
4645 /* proper use of this character is caught by end_trigger:
4646 * if we see {, we call parse_group(..., end_trigger='}')
4647 * and it will match } earlier (not here). */
4648 syntax_error_unexpected_ch(ch);
4652 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4658 struct parse_context *pctx;
4659 IF_HAS_KEYWORDS(struct parse_context *p2;)
4661 /* Clean up allocated tree.
4662 * Sample for finding leaks on syntax error recovery path.
4663 * Run it from interactive shell, watch pmap `pidof hush`.
4664 * while if false; then false; fi; do break; fi
4665 * Samples to catch leaks at execution:
4666 * while if (true | {true;}); then echo ok; fi; do break; done
4667 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4671 /* Update pipe/command counts,
4672 * otherwise freeing may miss some */
4673 done_pipe(pctx, PIPE_SEQ);
4674 debug_printf_clean("freeing list %p from ctx %p\n",
4675 pctx->list_head, pctx);
4676 debug_print_tree(pctx->list_head, 0);
4677 free_pipe_list(pctx->list_head);
4678 debug_printf_clean("freed list %p\n", pctx->list_head);
4680 o_free_unsafe(&pctx->as_string);
4682 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4686 IF_HAS_KEYWORDS(pctx = p2;)
4687 } while (HAS_KEYWORDS && pctx);
4690 G.last_exitcode = 1;
4701 /*** Execution routines ***/
4703 /* Expansion can recurse, need forward decls: */
4704 #if !ENABLE_HUSH_BASH_COMPAT
4705 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4706 #define expand_string_to_string(str, do_unbackslash) \
4707 expand_string_to_string(str)
4709 static char *expand_string_to_string(const char *str, int do_unbackslash);
4710 #if ENABLE_HUSH_TICK
4711 static int process_command_subs(o_string *dest, const char *s);
4714 /* expand_strvec_to_strvec() takes a list of strings, expands
4715 * all variable references within and returns a pointer to
4716 * a list of expanded strings, possibly with larger number
4717 * of strings. (Think VAR="a b"; echo $VAR).
4718 * This new list is allocated as a single malloc block.
4719 * NULL-terminated list of char* pointers is at the beginning of it,
4720 * followed by strings themselves.
4721 * Caller can deallocate entire list by single free(list). */
4723 /* A horde of its helpers come first: */
4725 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4727 while (--len >= 0) {
4730 #if ENABLE_HUSH_BRACE_EXPANSION
4731 if (c == '{' || c == '}') {
4732 /* { -> \{, } -> \} */
4734 /* And now we want to add { or } and continue:
4737 * luckily, just falling throught achieves this.
4743 /* \z -> \\\z; \<eol> -> \\<eol> */
4748 o_addchr(o, *str++);
4754 /* Store given string, finalizing the word and starting new one whenever
4755 * we encounter IFS char(s). This is used for expanding variable values.
4756 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4757 * Return in *ended_with_ifs:
4758 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4760 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4762 int last_is_ifs = 0;
4767 if (!*str) /* EOL - do not finalize word */
4769 word_len = strcspn(str, G.ifs);
4771 /* We have WORD_LEN leading non-IFS chars */
4772 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4773 o_addblock(output, str, word_len);
4775 /* Protect backslashes against globbing up :)
4776 * Example: "v='\*'; echo b$v" prints "b\*"
4777 * (and does not try to glob on "*")
4779 o_addblock_duplicate_backslash(output, str, word_len);
4780 /*/ Why can't we do it easier? */
4781 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4782 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4786 if (!*str) /* EOL - do not finalize word */
4790 /* We know str here points to at least one IFS char */
4792 str += strspn(str, G.ifs); /* skip IFS chars */
4793 if (!*str) /* EOL - do not finalize word */
4796 /* Start new word... but not always! */
4797 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4798 if (output->has_quoted_part
4799 /* Case "v=' a'; echo $v":
4800 * here nothing precedes the space in $v expansion,
4801 * therefore we should not finish the word
4802 * (IOW: if there *is* word to finalize, only then do it):
4804 || (n > 0 && output->data[output->length - 1])
4806 o_addchr(output, '\0');
4807 debug_print_list("expand_on_ifs", output, n);
4808 n = o_save_ptr(output, n);
4813 *ended_with_ifs = last_is_ifs;
4814 debug_print_list("expand_on_ifs[1]", output, n);
4818 /* Helper to expand $((...)) and heredoc body. These act as if
4819 * they are in double quotes, with the exception that they are not :).
4820 * Just the rules are similar: "expand only $var and `cmd`"
4822 * Returns malloced string.
4823 * As an optimization, we return NULL if expansion is not needed.
4825 #if !ENABLE_HUSH_BASH_COMPAT
4826 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4827 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4828 encode_then_expand_string(str)
4830 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4833 struct in_str input;
4834 o_string dest = NULL_O_STRING;
4836 if (!strchr(str, '$')
4837 && !strchr(str, '\\')
4838 #if ENABLE_HUSH_TICK
4839 && !strchr(str, '`')
4845 /* We need to expand. Example:
4846 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4848 setup_string_in_str(&input, str);
4849 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4850 //TODO: error check (encode_string returns 0 on error)?
4851 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4852 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4853 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4854 o_free_unsafe(&dest);
4858 #if ENABLE_SH_MATH_SUPPORT
4859 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4861 arith_state_t math_state;
4865 math_state.lookupvar = get_local_var_value;
4866 math_state.setvar = set_local_var_from_halves;
4867 //math_state.endofname = endofname;
4868 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4869 res = arith(&math_state, exp_str ? exp_str : arg);
4872 *errmsg_p = math_state.errmsg;
4873 if (math_state.errmsg)
4874 die_if_script(math_state.errmsg);
4879 #if ENABLE_HUSH_BASH_COMPAT
4880 /* ${var/[/]pattern[/repl]} helpers */
4881 static char *strstr_pattern(char *val, const char *pattern, int *size)
4884 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4885 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4892 /* Optimization: if "*pat" did not match the start of "string",
4893 * we know that "tring", "ring" etc will not match too:
4895 if (pattern[0] == '*')
4900 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4902 char *result = NULL;
4903 unsigned res_len = 0;
4904 unsigned repl_len = strlen(repl);
4908 char *s = strstr_pattern(val, pattern, &size);
4912 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4913 memcpy(result + res_len, val, s - val);
4915 strcpy(result + res_len, repl);
4916 res_len += repl_len;
4917 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4923 if (val[0] && result) {
4924 result = xrealloc(result, res_len + strlen(val) + 1);
4925 strcpy(result + res_len, val);
4926 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4928 debug_printf_varexp("result:'%s'\n", result);
4934 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4936 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4938 const char *val = NULL;
4939 char *to_be_freed = NULL;
4944 char exp_save = exp_save; /* for compiler */
4945 char *exp_saveptr; /* points to expansion operator */
4946 char *exp_word = exp_word; /* for compiler */
4949 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4951 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4953 first_char = arg[0] = arg0 & 0x7f;
4956 if (first_char == '#' /* ${#... */
4957 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4959 /* It must be length operator: ${#var} */
4963 /* Maybe handle parameter expansion */
4964 if (exp_saveptr /* if 2nd char is one of expansion operators */
4965 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4967 /* ${?:0}, ${#[:]%0} etc */
4968 exp_saveptr = var + 1;
4970 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4971 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4973 exp_op = exp_save = *exp_saveptr;
4975 exp_word = exp_saveptr + 1;
4976 if (exp_op == ':') {
4977 exp_op = *exp_word++;
4978 //TODO: try ${var:} and ${var:bogus} in non-bash config
4979 if (ENABLE_HUSH_BASH_COMPAT
4980 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4982 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4987 *exp_saveptr = '\0';
4988 } /* else: it's not an expansion op, but bare ${var} */
4991 /* Look up the variable in question */
4992 if (isdigit(var[0])) {
4993 /* parse_dollar should have vetted var for us */
4994 int n = xatoi_positive(var);
4995 if (n < G.global_argc)
4996 val = G.global_argv[n];
4997 /* else val remains NULL: $N with too big N */
5001 val = utoa(G.root_pid);
5003 case '!': /* bg pid */
5004 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5006 case '?': /* exitcode */
5007 val = utoa(G.last_exitcode);
5009 case '#': /* argc */
5010 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5013 val = get_local_var_value(var);
5017 /* Handle any expansions */
5018 if (exp_op == 'L') {
5019 debug_printf_expand("expand: length(%s)=", val);
5020 val = utoa(val ? strlen(val) : 0);
5021 debug_printf_expand("%s\n", val);
5022 } else if (exp_op) {
5023 if (exp_op == '%' || exp_op == '#') {
5024 /* Standard-mandated substring removal ops:
5025 * ${parameter%word} - remove smallest suffix pattern
5026 * ${parameter%%word} - remove largest suffix pattern
5027 * ${parameter#word} - remove smallest prefix pattern
5028 * ${parameter##word} - remove largest prefix pattern
5030 * Word is expanded to produce a glob pattern.
5031 * Then var's value is matched to it and matching part removed.
5033 if (val && val[0]) {
5037 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5038 if (exp_op == *exp_word) /* ## or %% */
5040 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5042 exp_word = exp_exp_word;
5043 /* HACK ALERT. We depend here on the fact that
5044 * G.global_argv and results of utoa and get_local_var_value
5045 * are actually in writable memory:
5046 * scan_and_match momentarily stores NULs there. */
5048 loc = scan_and_match(t, exp_word, scan_flags);
5049 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5050 // exp_op, t, exp_word, loc);
5052 if (loc) { /* match was found */
5053 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5054 val = loc; /* take right part */
5056 val = to_be_freed = xstrndup(val, loc - val); /* left */
5060 #if ENABLE_HUSH_BASH_COMPAT
5061 else if (exp_op == '/' || exp_op == '\\') {
5062 /* It's ${var/[/]pattern[/repl]} thing.
5063 * Note that in encoded form it has TWO parts:
5064 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5065 * and if // is used, it is encoded as \:
5066 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5068 /* Empty variable always gives nothing: */
5069 // "v=''; echo ${v/*/w}" prints "", not "w"
5070 if (val && val[0]) {
5071 /* pattern uses non-standard expansion.
5072 * repl should be unbackslashed and globbed
5073 * by the usual expansion rules:
5075 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5076 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5077 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5078 * v='a bz'; echo ${v/a*z/\z} prints "z"
5079 * (note that a*z _pattern_ is never globbed!)
5081 char *pattern, *repl, *t;
5082 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5084 pattern = xstrdup(exp_word);
5085 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5086 *p++ = SPECIAL_VAR_SYMBOL;
5088 p = strchr(p, SPECIAL_VAR_SYMBOL);
5090 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5091 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5092 /* HACK ALERT. We depend here on the fact that
5093 * G.global_argv and results of utoa and get_local_var_value
5094 * are actually in writable memory:
5095 * replace_pattern momentarily stores NULs there. */
5097 to_be_freed = replace_pattern(t,
5099 (repl ? repl : exp_word),
5101 if (to_be_freed) /* at least one replace happened */
5108 else if (exp_op == ':') {
5109 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5110 /* It's ${var:N[:M]} bashism.
5111 * Note that in encoded form it has TWO parts:
5112 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5117 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5120 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5121 *p++ = SPECIAL_VAR_SYMBOL;
5123 p = strchr(p, SPECIAL_VAR_SYMBOL);
5125 len = expand_and_evaluate_arith(exp_word, &errmsg);
5128 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5129 if (len >= 0) { /* bash compat: len < 0 is illegal */
5130 if (beg < 0) /* bash compat */
5132 debug_printf_varexp("from val:'%s'\n", val);
5133 if (len == 0 || !val || beg >= strlen(val)) {
5137 /* Paranoia. What if user entered 9999999999999
5138 * which fits in arith_t but not int? */
5141 val = to_be_freed = xstrndup(val + beg, len);
5143 debug_printf_varexp("val:'%s'\n", val);
5147 die_if_script("malformed ${%s:...}", var);
5150 } else { /* one of "-=+?" */
5151 /* Standard-mandated substitution ops:
5152 * ${var?word} - indicate error if unset
5153 * If var is unset, word (or a message indicating it is unset
5154 * if word is null) is written to standard error
5155 * and the shell exits with a non-zero exit status.
5156 * Otherwise, the value of var is substituted.
5157 * ${var-word} - use default value
5158 * If var is unset, word is substituted.
5159 * ${var=word} - assign and use default value
5160 * If var is unset, word is assigned to var.
5161 * In all cases, final value of var is substituted.
5162 * ${var+word} - use alternative value
5163 * If var is unset, null is substituted.
5164 * Otherwise, word is substituted.
5166 * Word is subjected to tilde expansion, parameter expansion,
5167 * command substitution, and arithmetic expansion.
5168 * If word is not needed, it is not expanded.
5170 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5171 * but also treat null var as if it is unset.
5173 int use_word = (!val || ((exp_save == ':') && !val[0]));
5175 use_word = !use_word;
5176 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5177 (exp_save == ':') ? "true" : "false", use_word);
5179 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5181 exp_word = to_be_freed;
5182 if (exp_op == '?') {
5183 /* mimic bash message */
5184 die_if_script("%s: %s",
5186 exp_word[0] ? exp_word : "parameter null or not set"
5188 //TODO: how interactive bash aborts expansion mid-command?
5193 if (exp_op == '=') {
5194 /* ${var=[word]} or ${var:=[word]} */
5195 if (isdigit(var[0]) || var[0] == '#') {
5196 /* mimic bash message */
5197 die_if_script("$%s: cannot assign in this way", var);
5200 char *new_var = xasprintf("%s=%s", var, val);
5201 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5205 } /* one of "-=+?" */
5207 *exp_saveptr = exp_save;
5213 *to_be_freed_pp = to_be_freed;
5217 /* Expand all variable references in given string, adding words to list[]
5218 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5219 * to be filled). This routine is extremely tricky: has to deal with
5220 * variables/parameters with whitespace, $* and $@, and constructs like
5221 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5222 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5224 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5225 * expansion of right-hand side of assignment == 1-element expand.
5227 char cant_be_null = 0; /* only bit 0x80 matters */
5228 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5231 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5232 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5233 debug_print_list("expand_vars_to_list", output, n);
5234 n = o_save_ptr(output, n);
5235 debug_print_list("expand_vars_to_list[0]", output, n);
5237 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5239 char *to_be_freed = NULL;
5240 const char *val = NULL;
5241 #if ENABLE_HUSH_TICK
5242 o_string subst_result = NULL_O_STRING;
5244 #if ENABLE_SH_MATH_SUPPORT
5245 char arith_buf[sizeof(arith_t)*3 + 2];
5249 o_addchr(output, '\0');
5250 n = o_save_ptr(output, n);
5254 o_addblock(output, arg, p - arg);
5255 debug_print_list("expand_vars_to_list[1]", output, n);
5257 p = strchr(p, SPECIAL_VAR_SYMBOL);
5259 /* Fetch special var name (if it is indeed one of them)
5260 * and quote bit, force the bit on if singleword expansion -
5261 * important for not getting v=$@ expand to many words. */
5262 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5264 /* Is this variable quoted and thus expansion can't be null?
5265 * "$@" is special. Even if quoted, it can still
5266 * expand to nothing (not even an empty string),
5267 * thus it is excluded. */
5268 if ((first_ch & 0x7f) != '@')
5269 cant_be_null |= first_ch;
5271 switch (first_ch & 0x7f) {
5272 /* Highest bit in first_ch indicates that var is double-quoted */
5276 if (!G.global_argv[1])
5279 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5280 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5281 while (G.global_argv[i]) {
5282 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5283 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5284 if (G.global_argv[i++][0] && G.global_argv[i]) {
5285 /* this argv[] is not empty and not last:
5286 * put terminating NUL, start new word */
5287 o_addchr(output, '\0');
5288 debug_print_list("expand_vars_to_list[2]", output, n);
5289 n = o_save_ptr(output, n);
5290 debug_print_list("expand_vars_to_list[3]", output, n);
5294 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5295 * and in this case should treat it like '$*' - see 'else...' below */
5296 if (first_ch == ('@'|0x80) /* quoted $@ */
5297 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5300 o_addQstr(output, G.global_argv[i]);
5301 if (++i >= G.global_argc)
5303 o_addchr(output, '\0');
5304 debug_print_list("expand_vars_to_list[4]", output, n);
5305 n = o_save_ptr(output, n);
5307 } else { /* quoted $* (or v="$@" case): add as one word */
5309 o_addQstr(output, G.global_argv[i]);
5310 if (!G.global_argv[++i])
5313 o_addchr(output, G.ifs[0]);
5315 output->has_quoted_part = 1;
5319 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5320 /* "Empty variable", used to make "" etc to not disappear */
5321 output->has_quoted_part = 1;
5323 cant_be_null = 0x80;
5325 #if ENABLE_HUSH_TICK
5326 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5327 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5329 /* Can't just stuff it into output o_string,
5330 * expanded result may need to be globbed
5331 * and $IFS-splitted */
5332 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5333 G.last_exitcode = process_command_subs(&subst_result, arg);
5334 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5335 val = subst_result.data;
5338 #if ENABLE_SH_MATH_SUPPORT
5339 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5342 arg++; /* skip '+' */
5343 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5344 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5345 res = expand_and_evaluate_arith(arg, NULL);
5346 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5347 sprintf(arith_buf, ARITH_FMT, res);
5353 val = expand_one_var(&to_be_freed, arg, &p);
5354 IF_HUSH_TICK(store_val:)
5355 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5356 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5357 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5358 if (val && val[0]) {
5359 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5362 } else { /* quoted $VAR, val will be appended below */
5363 output->has_quoted_part = 1;
5364 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5365 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5369 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5371 if (val && val[0]) {
5372 o_addQstr(output, val);
5376 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5377 * Do the check to avoid writing to a const string. */
5378 if (*p != SPECIAL_VAR_SYMBOL)
5379 *p = SPECIAL_VAR_SYMBOL;
5381 #if ENABLE_HUSH_TICK
5382 o_free(&subst_result);
5385 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5389 o_addchr(output, '\0');
5390 n = o_save_ptr(output, n);
5392 debug_print_list("expand_vars_to_list[a]", output, n);
5393 /* this part is literal, and it was already pre-quoted
5394 * if needed (much earlier), do not use o_addQstr here! */
5395 o_addstr_with_NUL(output, arg);
5396 debug_print_list("expand_vars_to_list[b]", output, n);
5397 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5398 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5401 /* allow to reuse list[n] later without re-growth */
5402 output->has_empty_slot = 1;
5404 o_addchr(output, '\0');
5410 static char **expand_variables(char **argv, unsigned expflags)
5414 o_string output = NULL_O_STRING;
5416 output.o_expflags = expflags;
5420 n = expand_vars_to_list(&output, n, *argv);
5423 debug_print_list("expand_variables", &output, n);
5425 /* output.data (malloced in one block) gets returned in "list" */
5426 list = o_finalize_list(&output, n);
5427 debug_print_strings("expand_variables[1]", list);
5431 static char **expand_strvec_to_strvec(char **argv)
5433 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5436 #if ENABLE_HUSH_BASH_COMPAT
5437 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5439 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5443 /* Used for expansion of right hand of assignments,
5444 * $((...)), heredocs, variable espansion parts.
5446 * NB: should NOT do globbing!
5447 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5449 static char *expand_string_to_string(const char *str, int do_unbackslash)
5451 #if !ENABLE_HUSH_BASH_COMPAT
5452 const int do_unbackslash = 1;
5454 char *argv[2], **list;
5456 debug_printf_expand("string_to_string<='%s'\n", str);
5457 /* This is generally an optimization, but it also
5458 * handles "", which otherwise trips over !list[0] check below.
5459 * (is this ever happens that we actually get str="" here?)
5461 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5462 //TODO: Can use on strings with \ too, just unbackslash() them?
5463 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5464 return xstrdup(str);
5467 argv[0] = (char*)str;
5469 list = expand_variables(argv, do_unbackslash
5470 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5471 : EXP_FLAG_SINGLEWORD
5474 if (!list[0] || list[1])
5475 bb_error_msg_and_die("BUG in varexp2");
5476 /* actually, just move string 2*sizeof(char*) bytes back */
5477 overlapping_strcpy((char*)list, list[0]);
5479 unbackslash((char*)list);
5480 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5484 /* Used for "eval" builtin */
5485 static char* expand_strvec_to_string(char **argv)
5489 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5490 /* Convert all NULs to spaces */
5495 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5496 bb_error_msg_and_die("BUG in varexp3");
5497 /* bash uses ' ' regardless of $IFS contents */
5502 overlapping_strcpy((char*)list, list[0]);
5503 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5507 static char **expand_assignments(char **argv, int count)
5512 G.expanded_assignments = p = NULL;
5513 /* Expand assignments into one string each */
5514 for (i = 0; i < count; i++) {
5515 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5517 G.expanded_assignments = NULL;
5522 static void switch_off_special_sigs(unsigned mask)
5525 while ((mask >>= 1) != 0) {
5530 if (G.traps[sig] && !G.traps[sig][0])
5531 /* trap is '', has to remain SIG_IGN */
5534 G.traps[sig] = NULL;
5536 /* We are here only if no trap or trap was not '' */
5537 install_sighandler(sig, SIG_DFL);
5543 void re_execute_shell(char ***to_free, const char *s,
5544 char *g_argv0, char **g_argv,
5545 char **builtin_argv) NORETURN;
5547 static void reset_traps_to_defaults(void)
5549 /* This function is always called in a child shell
5550 * after fork (not vfork, NOMMU doesn't use this function).
5555 /* Child shells are not interactive.
5556 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5557 * Testcase: (while :; do :; done) + ^Z should background.
5558 * Same goes for SIGTERM, SIGHUP, SIGINT.
5560 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5561 if (!G.traps && !mask)
5562 return; /* already no traps and no special sigs */
5564 /* Switch off special sigs */
5565 switch_off_special_sigs(mask);
5567 G_fatal_sig_mask = 0;
5569 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5570 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5571 * remain set in G.special_sig_mask */
5576 /* Reset all sigs to default except ones with empty traps */
5577 for (sig = 0; sig < NSIG; sig++) {
5579 continue; /* no trap: nothing to do */
5580 if (!G.traps[sig][0])
5581 continue; /* empty trap: has to remain SIG_IGN */
5582 /* sig has non-empty trap, reset it: */
5584 G.traps[sig] = NULL;
5585 /* There is no signal for trap 0 (EXIT) */
5588 install_sighandler(sig, pick_sighandler(sig));
5594 static void re_execute_shell(char ***to_free, const char *s,
5595 char *g_argv0, char **g_argv,
5596 char **builtin_argv) NORETURN;
5597 static void re_execute_shell(char ***to_free, const char *s,
5598 char *g_argv0, char **g_argv,
5599 char **builtin_argv)
5601 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5602 /* delims + 2 * (number of bytes in printed hex numbers) */
5603 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5604 char *heredoc_argv[4];
5605 struct variable *cur;
5606 # if ENABLE_HUSH_FUNCTIONS
5607 struct function *funcp;
5611 unsigned long long empty_trap_mask;
5613 if (!g_argv0) { /* heredoc */
5614 argv = heredoc_argv;
5615 argv[0] = (char *) G.argv0_for_re_execing;
5616 argv[1] = (char *) "-<";
5617 argv[2] = (char *) s;
5619 pp = &argv[3]; /* used as pointer to empty environment */
5625 if (pp) while (*pp++)
5628 empty_trap_mask = 0;
5631 for (sig = 1; sig < NSIG; sig++) {
5632 if (G.traps[sig] && !G.traps[sig][0])
5633 empty_trap_mask |= 1LL << sig;
5637 sprintf(param_buf, NOMMU_HACK_FMT
5638 , (unsigned) G.root_pid
5639 , (unsigned) G.root_ppid
5640 , (unsigned) G.last_bg_pid
5641 , (unsigned) G.last_exitcode
5644 IF_HUSH_LOOPS(, G.depth_of_loop)
5646 # undef NOMMU_HACK_FMT
5647 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5648 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5651 for (cur = G.top_var; cur; cur = cur->next) {
5652 if (!cur->flg_export || cur->flg_read_only)
5655 # if ENABLE_HUSH_FUNCTIONS
5656 for (funcp = G.top_func; funcp; funcp = funcp->next)
5662 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5663 *pp++ = (char *) G.argv0_for_re_execing;
5665 for (cur = G.top_var; cur; cur = cur->next) {
5666 if (strcmp(cur->varstr, hush_version_str) == 0)
5668 if (cur->flg_read_only) {
5669 *pp++ = (char *) "-R";
5670 *pp++ = cur->varstr;
5671 } else if (!cur->flg_export) {
5672 *pp++ = (char *) "-V";
5673 *pp++ = cur->varstr;
5676 # if ENABLE_HUSH_FUNCTIONS
5677 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5678 *pp++ = (char *) "-F";
5679 *pp++ = funcp->name;
5680 *pp++ = funcp->body_as_string;
5683 /* We can pass activated traps here. Say, -Tnn:trap_string
5685 * However, POSIX says that subshells reset signals with traps
5687 * I tested bash-3.2 and it not only does that with true subshells
5688 * of the form ( list ), but with any forked children shells.
5689 * I set trap "echo W" WINCH; and then tried:
5691 * { echo 1; sleep 20; echo 2; } &
5692 * while true; do echo 1; sleep 20; echo 2; break; done &
5693 * true | { echo 1; sleep 20; echo 2; } | cat
5695 * In all these cases sending SIGWINCH to the child shell
5696 * did not run the trap. If I add trap "echo V" WINCH;
5697 * _inside_ group (just before echo 1), it works.
5699 * I conclude it means we don't need to pass active traps here.
5701 *pp++ = (char *) "-c";
5704 while (*++builtin_argv)
5705 *pp++ = *builtin_argv;
5706 *pp++ = (char *) "";
5711 /* *pp = NULL; - is already there */
5715 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5716 /* Don't propagate SIG_IGN to the child */
5717 if (SPECIAL_JOBSTOP_SIGS != 0)
5718 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5719 execve(bb_busybox_exec_path, argv, pp);
5720 /* Fallback. Useful for init=/bin/hush usage etc */
5721 if (argv[0][0] == '/')
5722 execve(argv[0], argv, pp);
5723 xfunc_error_retval = 127;
5724 bb_error_msg_and_die("can't re-execute the shell");
5726 #endif /* !BB_MMU */
5729 static int run_and_free_list(struct pipe *pi);
5731 /* Executing from string: eval, sh -c '...'
5732 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5733 * end_trigger controls how often we stop parsing
5734 * NUL: parse all, execute, return
5735 * ';': parse till ';' or newline, execute, repeat till EOF
5737 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5739 /* Why we need empty flag?
5740 * An obscure corner case "false; ``; echo $?":
5741 * empty command in `` should still set $? to 0.
5742 * But we can't just set $? to 0 at the start,
5743 * this breaks "false; echo `echo $?`" case.
5747 struct pipe *pipe_list;
5749 #if ENABLE_HUSH_INTERACTIVE
5750 if (end_trigger == ';')
5751 inp->promptmode = 0; /* PS1 */
5753 pipe_list = parse_stream(NULL, inp, end_trigger);
5754 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5755 /* If we are in "big" script
5756 * (not in `cmd` or something similar)...
5758 if (pipe_list == ERR_PTR && end_trigger == ';') {
5759 /* Discard cached input (rest of line) */
5760 int ch = inp->last_char;
5761 while (ch != EOF && ch != '\n') {
5762 //bb_error_msg("Discarded:'%c'", ch);
5767 /* This stream isn't empty */
5771 if (!pipe_list && empty)
5772 G.last_exitcode = 0;
5775 debug_print_tree(pipe_list, 0);
5776 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5777 run_and_free_list(pipe_list);
5779 #if ENABLE_HUSH_FUNCTIONS
5780 if (G.flag_return_in_progress == 1)
5786 static void parse_and_run_string(const char *s)
5788 struct in_str input;
5789 setup_string_in_str(&input, s);
5790 parse_and_run_stream(&input, '\0');
5793 static void parse_and_run_file(FILE *f)
5795 struct in_str input;
5796 setup_file_in_str(&input, f);
5797 parse_and_run_stream(&input, ';');
5800 #if ENABLE_HUSH_TICK
5801 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5806 char **to_free = NULL;
5810 pid = BB_MMU ? xfork() : xvfork();
5811 if (pid == 0) { /* child */
5812 disable_restore_tty_pgrp_on_exit();
5813 /* Process substitution is not considered to be usual
5814 * 'command execution'.
5815 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5822 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5823 close(channel[0]); /* NB: close _first_, then move fd! */
5824 xmove_fd(channel[1], 1);
5825 /* Prevent it from trying to handle ctrl-z etc */
5826 IF_HUSH_JOB(G.run_list_level = 1;)
5827 /* Awful hack for `trap` or $(trap).
5829 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5830 * contains an example where "trap" is executed in a subshell:
5832 * save_traps=$(trap)
5834 * eval "$save_traps"
5836 * Standard does not say that "trap" in subshell shall print
5837 * parent shell's traps. It only says that its output
5838 * must have suitable form, but then, in the above example
5839 * (which is not supposed to be normative), it implies that.
5841 * bash (and probably other shell) does implement it
5842 * (traps are reset to defaults, but "trap" still shows them),
5843 * but as a result, "trap" logic is hopelessly messed up:
5846 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5847 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5848 * # true | trap <--- trap is in subshell - no output (ditto)
5849 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5850 * trap -- 'echo Ho' SIGWINCH
5851 * # echo `(trap)` <--- in subshell in subshell - output
5852 * trap -- 'echo Ho' SIGWINCH
5853 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5854 * trap -- 'echo Ho' SIGWINCH
5856 * The rules when to forget and when to not forget traps
5857 * get really complex and nonsensical.
5859 * Our solution: ONLY bare $(trap) or `trap` is special.
5861 s = skip_whitespace(s);
5862 if (strncmp(s, "trap", 4) == 0
5863 && skip_whitespace(s + 4)[0] == '\0'
5865 static const char *const argv[] = { NULL, NULL };
5866 builtin_trap((char**)argv);
5867 exit(0); /* not _exit() - we need to fflush */
5870 reset_traps_to_defaults();
5871 parse_and_run_string(s);
5872 _exit(G.last_exitcode);
5874 /* We re-execute after vfork on NOMMU. This makes this script safe:
5875 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5876 * huge=`cat BIG` # was blocking here forever
5879 re_execute_shell(&to_free,
5889 # if ENABLE_HUSH_FAST
5891 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5892 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5893 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5895 enable_restore_tty_pgrp_on_exit();
5900 close_on_exec_on(channel[0]);
5901 return xfdopen_for_read(channel[0]);
5904 /* Return code is exit status of the process that is run. */
5905 static int process_command_subs(o_string *dest, const char *s)
5908 struct in_str pipe_str;
5910 int status, ch, eol_cnt;
5912 fp = generate_stream_from_string(s, &pid);
5914 /* Now send results of command back into original context */
5915 setup_file_in_str(&pipe_str, fp);
5917 while ((ch = i_getch(&pipe_str)) != EOF) {
5923 o_addchr(dest, '\n');
5926 o_addQchr(dest, ch);
5929 debug_printf("done reading from `cmd` pipe, closing it\n");
5931 /* We need to extract exitcode. Test case
5932 * "true; echo `sleep 1; false` $?"
5934 safe_waitpid(pid, &status, 0);
5935 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5936 return WEXITSTATUS(status);
5938 #endif /* ENABLE_HUSH_TICK */
5941 static void setup_heredoc(struct redir_struct *redir)
5943 struct fd_pair pair;
5946 /* the _body_ of heredoc (misleading field name) */
5947 const char *heredoc = redir->rd_filename;
5954 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5955 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5959 len = strlen(heredoc);
5961 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5963 xmove_fd(pair.rd, redir->rd_fd);
5965 /* Try writing without forking. Newer kernels have
5966 * dynamically growing pipes. Must use non-blocking write! */
5969 written = write(pair.wr, heredoc, len);
5980 ndelay_off(pair.wr);
5982 /* Okay, pipe buffer was not big enough */
5983 /* Note: we must not create a stray child (bastard? :)
5984 * for the unsuspecting parent process. Child creates a grandchild
5985 * and exits before parent execs the process which consumes heredoc
5986 * (that exec happens after we return from this function) */
5993 disable_restore_tty_pgrp_on_exit();
5994 pid = BB_MMU ? xfork() : xvfork();
5998 close(redir->rd_fd); /* read side of the pipe */
6000 full_write(pair.wr, heredoc, len); /* may loop or block */
6003 /* Delegate blocking writes to another process */
6004 xmove_fd(pair.wr, STDOUT_FILENO);
6005 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6009 #if ENABLE_HUSH_FAST
6011 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6013 enable_restore_tty_pgrp_on_exit();
6019 wait(NULL); /* wait till child has died */
6022 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6023 * and stderr if they are redirected. */
6024 static int setup_redirects(struct command *prog, int squirrel[])
6027 struct redir_struct *redir;
6029 for (redir = prog->redirects; redir; redir = redir->next) {
6030 if (redir->rd_type == REDIRECT_HEREDOC2) {
6031 /* rd_fd<<HERE case */
6032 if (squirrel && redir->rd_fd < 3
6033 && squirrel[redir->rd_fd] < 0
6035 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6037 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6039 debug_printf_parse("set heredoc '%s'\n",
6040 redir->rd_filename);
6041 setup_heredoc(redir);
6045 if (redir->rd_dup == REDIRFD_TO_FILE) {
6046 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6048 if (redir->rd_filename == NULL) {
6049 /* Something went wrong in the parse.
6050 * Pretend it didn't happen */
6051 bb_error_msg("bug in redirect parse");
6054 mode = redir_table[redir->rd_type].mode;
6055 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6056 openfd = open_or_warn(p, mode);
6059 /* this could get lost if stderr has been redirected, but
6060 * bash and ash both lose it as well (though zsh doesn't!) */
6061 //what the above comment tries to say?
6065 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6066 openfd = redir->rd_dup;
6069 if (openfd != redir->rd_fd) {
6070 if (squirrel && redir->rd_fd < 3
6071 && squirrel[redir->rd_fd] < 0
6073 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6075 if (openfd == REDIRFD_CLOSE) {
6076 /* "n>-" means "close me" */
6077 close(redir->rd_fd);
6079 xdup2(openfd, redir->rd_fd);
6080 if (redir->rd_dup == REDIRFD_TO_FILE)
6088 static void restore_redirects(int squirrel[])
6091 for (i = 0; i < 3; i++) {
6094 /* We simply die on error */
6100 static char *find_in_path(const char *arg)
6103 const char *PATH = get_local_var_value("PATH");
6109 const char *end = strchrnul(PATH, ':');
6110 int sz = end - PATH; /* must be int! */
6114 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6116 /* We have xxx::yyyy in $PATH,
6117 * it means "use current dir" */
6120 if (access(ret, F_OK) == 0)
6133 static const struct built_in_command *find_builtin_helper(const char *name,
6134 const struct built_in_command *x,
6135 const struct built_in_command *end)
6138 if (strcmp(name, x->b_cmd) != 0) {
6142 debug_printf_exec("found builtin '%s'\n", name);
6147 static const struct built_in_command *find_builtin1(const char *name)
6149 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6151 static const struct built_in_command *find_builtin(const char *name)
6153 const struct built_in_command *x = find_builtin1(name);
6156 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6159 #if ENABLE_HUSH_FUNCTIONS
6160 static struct function **find_function_slot(const char *name)
6162 struct function **funcpp = &G.top_func;
6164 if (strcmp(name, (*funcpp)->name) == 0) {
6167 funcpp = &(*funcpp)->next;
6172 static const struct function *find_function(const char *name)
6174 const struct function *funcp = *find_function_slot(name);
6176 debug_printf_exec("found function '%s'\n", name);
6180 /* Note: takes ownership on name ptr */
6181 static struct function *new_function(char *name)
6183 struct function **funcpp = find_function_slot(name);
6184 struct function *funcp = *funcpp;
6186 if (funcp != NULL) {
6187 struct command *cmd = funcp->parent_cmd;
6188 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6190 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6192 /* Note: if !funcp->body, do not free body_as_string!
6193 * This is a special case of "-F name body" function:
6194 * body_as_string was not malloced! */
6196 free_pipe_list(funcp->body);
6198 free(funcp->body_as_string);
6202 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6203 cmd->argv[0] = funcp->name;
6204 cmd->group = funcp->body;
6206 cmd->group_as_string = funcp->body_as_string;
6210 debug_printf_exec("remembering new function '%s'\n", name);
6211 funcp = *funcpp = xzalloc(sizeof(*funcp));
6212 /*funcp->next = NULL;*/
6219 static void unset_func(const char *name)
6221 struct function **funcpp = find_function_slot(name);
6222 struct function *funcp = *funcpp;
6224 if (funcp != NULL) {
6225 debug_printf_exec("freeing function '%s'\n", funcp->name);
6226 *funcpp = funcp->next;
6227 /* funcp is unlinked now, deleting it.
6228 * Note: if !funcp->body, the function was created by
6229 * "-F name body", do not free ->body_as_string
6230 * and ->name as they were not malloced. */
6232 free_pipe_list(funcp->body);
6235 free(funcp->body_as_string);
6243 #define exec_function(to_free, funcp, argv) \
6244 exec_function(funcp, argv)
6246 static void exec_function(char ***to_free,
6247 const struct function *funcp,
6248 char **argv) NORETURN;
6249 static void exec_function(char ***to_free,
6250 const struct function *funcp,
6256 argv[0] = G.global_argv[0];
6257 G.global_argv = argv;
6261 /* On MMU, funcp->body is always non-NULL */
6262 n = run_list(funcp->body);
6266 re_execute_shell(to_free,
6267 funcp->body_as_string,
6274 static int run_function(const struct function *funcp, char **argv)
6280 save_and_replace_G_args(&sv, argv);
6282 /* "we are in function, ok to use return" */
6283 sv_flg = G.flag_return_in_progress;
6284 G.flag_return_in_progress = -1;
6285 # if ENABLE_HUSH_LOCAL
6286 G.func_nest_level++;
6289 /* On MMU, funcp->body is always non-NULL */
6292 /* Function defined by -F */
6293 parse_and_run_string(funcp->body_as_string);
6294 rc = G.last_exitcode;
6298 rc = run_list(funcp->body);
6301 # if ENABLE_HUSH_LOCAL
6303 struct variable *var;
6304 struct variable **var_pp;
6306 var_pp = &G.top_var;
6307 while ((var = *var_pp) != NULL) {
6308 if (var->func_nest_level < G.func_nest_level) {
6309 var_pp = &var->next;
6313 if (var->flg_export)
6314 bb_unsetenv(var->varstr);
6315 /* Remove from global list */
6316 *var_pp = var->next;
6322 G.func_nest_level--;
6325 G.flag_return_in_progress = sv_flg;
6327 restore_G_args(&sv, argv);
6331 #endif /* ENABLE_HUSH_FUNCTIONS */
6335 #define exec_builtin(to_free, x, argv) \
6336 exec_builtin(x, argv)
6338 #define exec_builtin(to_free, x, argv) \
6339 exec_builtin(to_free, argv)
6341 static void exec_builtin(char ***to_free,
6342 const struct built_in_command *x,
6343 char **argv) NORETURN;
6344 static void exec_builtin(char ***to_free,
6345 const struct built_in_command *x,
6351 rcode = x->b_function(argv);
6356 /* On NOMMU, we must never block!
6357 * Example: { sleep 99 | read line; } & echo Ok
6359 re_execute_shell(to_free,
6368 static void execvp_or_die(char **argv) NORETURN;
6369 static void execvp_or_die(char **argv)
6371 debug_printf_exec("execing '%s'\n", argv[0]);
6372 /* Don't propagate SIG_IGN to the child */
6373 if (SPECIAL_JOBSTOP_SIGS != 0)
6374 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6375 execvp(argv[0], argv);
6376 bb_perror_msg("can't execute '%s'", argv[0]);
6377 _exit(127); /* bash compat */
6380 #if ENABLE_HUSH_MODE_X
6381 static void dump_cmd_in_x_mode(char **argv)
6383 if (G_x_mode && argv) {
6384 /* We want to output the line in one write op */
6392 len += strlen(argv[n++]) + 1;
6398 p += sprintf(p, " %s", argv[n++]);
6406 # define dump_cmd_in_x_mode(argv) ((void)0)
6410 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6411 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6412 #define pseudo_exec(nommu_save, command, argv_expanded) \
6413 pseudo_exec(command, argv_expanded)
6416 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6418 * Don't exit() here. If you don't exec, use _exit instead.
6419 * The at_exit handlers apparently confuse the calling process,
6420 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6421 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6422 char **argv, int assignment_cnt,
6423 char **argv_expanded) NORETURN;
6424 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6425 char **argv, int assignment_cnt,
6426 char **argv_expanded)
6430 new_env = expand_assignments(argv, assignment_cnt);
6431 dump_cmd_in_x_mode(new_env);
6433 if (!argv[assignment_cnt]) {
6434 /* Case when we are here: ... | var=val | ...
6435 * (note that we do not exit early, i.e., do not optimize out
6436 * expand_assignments(): think about ... | var=`sleep 1` | ...
6438 free_strings(new_env);
6439 _exit(EXIT_SUCCESS);
6443 set_vars_and_save_old(new_env);
6444 free(new_env); /* optional */
6445 /* we can also destroy set_vars_and_save_old's return value,
6448 nommu_save->new_env = new_env;
6449 nommu_save->old_vars = set_vars_and_save_old(new_env);
6452 if (argv_expanded) {
6453 argv = argv_expanded;
6455 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6457 nommu_save->argv = argv;
6460 dump_cmd_in_x_mode(argv);
6462 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6463 if (strchr(argv[0], '/') != NULL)
6467 /* Check if the command matches any of the builtins.
6468 * Depending on context, this might be redundant. But it's
6469 * easier to waste a few CPU cycles than it is to figure out
6470 * if this is one of those cases.
6473 /* On NOMMU, it is more expensive to re-execute shell
6474 * just in order to run echo or test builtin.
6475 * It's better to skip it here and run corresponding
6476 * non-builtin later. */
6477 const struct built_in_command *x;
6478 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6480 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6483 #if ENABLE_HUSH_FUNCTIONS
6484 /* Check if the command matches any functions */
6486 const struct function *funcp = find_function(argv[0]);
6488 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6493 #if ENABLE_FEATURE_SH_STANDALONE
6494 /* Check if the command matches any busybox applets */
6496 int a = find_applet_by_name(argv[0]);
6498 # if BB_MMU /* see above why on NOMMU it is not allowed */
6499 if (APPLET_IS_NOEXEC(a)) {
6500 debug_printf_exec("running applet '%s'\n", argv[0]);
6501 run_applet_no_and_exit(a, argv);
6504 /* Re-exec ourselves */
6505 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6506 /* Don't propagate SIG_IGN to the child */
6507 if (SPECIAL_JOBSTOP_SIGS != 0)
6508 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6509 execv(bb_busybox_exec_path, argv);
6510 /* If they called chroot or otherwise made the binary no longer
6511 * executable, fall through */
6516 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6519 execvp_or_die(argv);
6522 /* Called after [v]fork() in run_pipe
6524 static void pseudo_exec(nommu_save_t *nommu_save,
6525 struct command *command,
6526 char **argv_expanded) NORETURN;
6527 static void pseudo_exec(nommu_save_t *nommu_save,
6528 struct command *command,
6529 char **argv_expanded)
6531 if (command->argv) {
6532 pseudo_exec_argv(nommu_save, command->argv,
6533 command->assignment_cnt, argv_expanded);
6536 if (command->group) {
6537 /* Cases when we are here:
6540 * ... | ( list ) | ...
6541 * ... | { list } | ...
6545 debug_printf_exec("pseudo_exec: run_list\n");
6546 reset_traps_to_defaults();
6547 rcode = run_list(command->group);
6548 /* OK to leak memory by not calling free_pipe_list,
6549 * since this process is about to exit */
6552 re_execute_shell(&nommu_save->argv_from_re_execing,
6553 command->group_as_string,
6560 /* Case when we are here: ... | >file */
6561 debug_printf_exec("pseudo_exec'ed null command\n");
6562 _exit(EXIT_SUCCESS);
6566 static const char *get_cmdtext(struct pipe *pi)
6572 /* This is subtle. ->cmdtext is created only on first backgrounding.
6573 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6574 * On subsequent bg argv is trashed, but we won't use it */
6577 argv = pi->cmds[0].argv;
6578 if (!argv || !argv[0]) {
6579 pi->cmdtext = xzalloc(1);
6585 len += strlen(*argv) + 1;
6589 argv = pi->cmds[0].argv;
6591 len = strlen(*argv);
6592 memcpy(p, *argv, len);
6600 static void insert_bg_job(struct pipe *pi)
6602 struct pipe *job, **jobp;
6605 /* Linear search for the ID of the job to use */
6607 for (job = G.job_list; job; job = job->next)
6608 if (job->jobid >= pi->jobid)
6609 pi->jobid = job->jobid + 1;
6611 /* Add job to the list of running jobs */
6613 while ((job = *jobp) != NULL)
6615 job = *jobp = xmalloc(sizeof(*job));
6617 *job = *pi; /* physical copy */
6619 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6620 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6621 for (i = 0; i < pi->num_cmds; i++) {
6622 job->cmds[i].pid = pi->cmds[i].pid;
6623 /* all other fields are not used and stay zero */
6625 job->cmdtext = xstrdup(get_cmdtext(pi));
6627 if (G_interactive_fd)
6628 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6629 G.last_jobid = job->jobid;
6632 static void remove_bg_job(struct pipe *pi)
6634 struct pipe *prev_pipe;
6636 if (pi == G.job_list) {
6637 G.job_list = pi->next;
6639 prev_pipe = G.job_list;
6640 while (prev_pipe->next != pi)
6641 prev_pipe = prev_pipe->next;
6642 prev_pipe->next = pi->next;
6645 G.last_jobid = G.job_list->jobid;
6650 /* Remove a backgrounded job */
6651 static void delete_finished_bg_job(struct pipe *pi)
6658 /* Check to see if any processes have exited -- if they
6659 * have, figure out why and see if a job has completed */
6660 static int checkjobs(struct pipe *fg_pipe)
6670 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6672 attributes = WUNTRACED;
6673 if (fg_pipe == NULL)
6674 attributes |= WNOHANG;
6677 #if ENABLE_HUSH_FAST
6678 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6679 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6680 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6681 /* There was neither fork nor SIGCHLD since last waitpid */
6682 /* Avoid doing waitpid syscall if possible */
6683 if (!G.we_have_children) {
6687 if (fg_pipe == NULL) { /* is WNOHANG set? */
6688 /* We have children, but they did not exit
6689 * or stop yet (we saw no SIGCHLD) */
6692 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6696 /* Do we do this right?
6697 * bash-3.00# sleep 20 | false
6699 * [3]+ Stopped sleep 20 | false
6700 * bash-3.00# echo $?
6701 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6702 * [hush 1.14.0: yes we do it right]
6709 #if ENABLE_HUSH_FAST
6710 i = G.count_SIGCHLD;
6712 childpid = waitpid(-1, &status, attributes);
6713 if (childpid <= 0) {
6714 if (childpid && errno != ECHILD)
6715 bb_perror_msg("waitpid");
6716 #if ENABLE_HUSH_FAST
6717 else { /* Until next SIGCHLD, waitpid's are useless */
6718 G.we_have_children = (childpid == 0);
6719 G.handled_SIGCHLD = i;
6720 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6725 dead = WIFEXITED(status) || WIFSIGNALED(status);
6728 if (WIFSTOPPED(status))
6729 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6730 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6731 if (WIFSIGNALED(status))
6732 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6733 childpid, WTERMSIG(status), WEXITSTATUS(status));
6734 if (WIFEXITED(status))
6735 debug_printf_jobs("pid %d exited, exitcode %d\n",
6736 childpid, WEXITSTATUS(status));
6738 /* Were we asked to wait for fg pipe? */
6740 i = fg_pipe->num_cmds;
6742 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6743 if (fg_pipe->cmds[i].pid != childpid)
6747 fg_pipe->cmds[i].pid = 0;
6748 fg_pipe->alive_cmds--;
6749 ex = WEXITSTATUS(status);
6750 /* bash prints killer signal's name for *last*
6751 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6752 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6754 if (WIFSIGNALED(status)) {
6755 int sig = WTERMSIG(status);
6756 if (i == fg_pipe->num_cmds-1)
6757 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6758 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6759 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6760 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6761 * Maybe we need to use sig | 128? */
6764 fg_pipe->cmds[i].cmd_exitcode = ex;
6766 fg_pipe->cmds[i].is_stopped = 1;
6767 fg_pipe->stopped_cmds++;
6769 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6770 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6771 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6772 /* All processes in fg pipe have exited or stopped */
6773 i = fg_pipe->num_cmds;
6775 rcode = fg_pipe->cmds[i].cmd_exitcode;
6776 /* usually last process gives overall exitstatus,
6777 * but with "set -o pipefail", last *failed* process does */
6778 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6781 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6782 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6783 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6784 * and "killall -STOP cat" */
6785 if (G_interactive_fd) {
6787 if (fg_pipe->alive_cmds != 0)
6788 insert_bg_job(fg_pipe);
6792 if (fg_pipe->alive_cmds == 0)
6795 /* There are still running processes in the fg pipe */
6796 goto wait_more; /* do waitpid again */
6798 /* it wasnt fg_pipe, look for process in bg pipes */
6802 /* We asked to wait for bg or orphaned children */
6803 /* No need to remember exitcode in this case */
6804 for (pi = G.job_list; pi; pi = pi->next) {
6805 for (i = 0; i < pi->num_cmds; i++) {
6806 if (pi->cmds[i].pid == childpid)
6807 goto found_pi_and_prognum;
6810 /* Happens when shell is used as init process (init=/bin/sh) */
6811 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6812 continue; /* do waitpid again */
6814 found_pi_and_prognum:
6817 pi->cmds[i].pid = 0;
6819 if (!pi->alive_cmds) {
6820 if (G_interactive_fd)
6821 printf(JOB_STATUS_FORMAT, pi->jobid,
6822 "Done", pi->cmdtext);
6823 delete_finished_bg_job(pi);
6827 pi->cmds[i].is_stopped = 1;
6831 } /* while (waitpid succeeds)... */
6837 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6840 int rcode = checkjobs(fg_pipe);
6841 if (G_saved_tty_pgrp) {
6842 /* Job finished, move the shell to the foreground */
6843 p = getpgrp(); /* our process group id */
6844 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6845 tcsetpgrp(G_interactive_fd, p);
6851 /* Start all the jobs, but don't wait for anything to finish.
6854 * Return code is normally -1, when the caller has to wait for children
6855 * to finish to determine the exit status of the pipe. If the pipe
6856 * is a simple builtin command, however, the action is done by the
6857 * time run_pipe returns, and the exit code is provided as the
6860 * Returns -1 only if started some children. IOW: we have to
6861 * mask out retvals of builtins etc with 0xff!
6863 * The only case when we do not need to [v]fork is when the pipe
6864 * is single, non-backgrounded, non-subshell command. Examples:
6865 * cmd ; ... { list } ; ...
6866 * cmd && ... { list } && ...
6867 * cmd || ... { list } || ...
6868 * If it is, then we can run cmd as a builtin, NOFORK,
6869 * or (if SH_STANDALONE) an applet, and we can run the { list }
6870 * with run_list. If it isn't one of these, we fork and exec cmd.
6872 * Cases when we must fork:
6873 * non-single: cmd | cmd
6874 * backgrounded: cmd & { list } &
6875 * subshell: ( list ) [&]
6877 #if !ENABLE_HUSH_MODE_X
6878 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6879 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6881 static int redirect_and_varexp_helper(char ***new_env_p,
6882 struct variable **old_vars_p,
6883 struct command *command,
6885 char **argv_expanded)
6887 /* setup_redirects acts on file descriptors, not FILEs.
6888 * This is perfect for work that comes after exec().
6889 * Is it really safe for inline use? Experimentally,
6890 * things seem to work. */
6891 int rcode = setup_redirects(command, squirrel);
6893 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6894 *new_env_p = new_env;
6895 dump_cmd_in_x_mode(new_env);
6896 dump_cmd_in_x_mode(argv_expanded);
6898 *old_vars_p = set_vars_and_save_old(new_env);
6902 static NOINLINE int run_pipe(struct pipe *pi)
6904 static const char *const null_ptr = NULL;
6908 struct command *command;
6909 char **argv_expanded;
6911 /* it is not always needed, but we aim to smaller code */
6912 int squirrel[] = { -1, -1, -1 };
6915 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6918 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6919 * Result should be 3 lines: q w e, qwe, q w e
6921 G.ifs = get_local_var_value("IFS");
6925 IF_HUSH_JOB(pi->pgrp = -1;)
6926 pi->stopped_cmds = 0;
6927 command = &pi->cmds[0];
6928 argv_expanded = NULL;
6930 if (pi->num_cmds != 1
6931 || pi->followup == PIPE_BG
6932 || command->cmd_type == CMD_SUBSHELL
6939 debug_printf_exec(": group:%p argv:'%s'\n",
6940 command->group, command->argv ? command->argv[0] : "NONE");
6942 if (command->group) {
6943 #if ENABLE_HUSH_FUNCTIONS
6944 if (command->cmd_type == CMD_FUNCDEF) {
6945 /* "executing" func () { list } */
6946 struct function *funcp;
6948 funcp = new_function(command->argv[0]);
6949 /* funcp->name is already set to argv[0] */
6950 funcp->body = command->group;
6952 funcp->body_as_string = command->group_as_string;
6953 command->group_as_string = NULL;
6955 command->group = NULL;
6956 command->argv[0] = NULL;
6957 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6958 funcp->parent_cmd = command;
6959 command->child_func = funcp;
6961 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6963 return EXIT_SUCCESS;
6967 debug_printf("non-subshell group\n");
6968 rcode = 1; /* exitcode if redir failed */
6969 if (setup_redirects(command, squirrel) == 0) {
6970 debug_printf_exec(": run_list\n");
6971 rcode = run_list(command->group) & 0xff;
6973 restore_redirects(squirrel);
6974 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6976 debug_printf_exec("run_pipe: return %d\n", rcode);
6980 argv = command->argv ? command->argv : (char **) &null_ptr;
6982 const struct built_in_command *x;
6983 #if ENABLE_HUSH_FUNCTIONS
6984 const struct function *funcp;
6988 char **new_env = NULL;
6989 struct variable *old_vars = NULL;
6991 if (argv[command->assignment_cnt] == NULL) {
6992 /* Assignments, but no command */
6993 /* Ensure redirects take effect (that is, create files).
6994 * Try "a=t >file" */
6995 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6996 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6997 /* Set shell variables */
7001 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7002 /* Do we need to flag set_local_var() errors?
7003 * "assignment to readonly var" and "putenv error"
7008 /* Redirect error sets $? to 1. Otherwise,
7009 * if evaluating assignment value set $?, retain it.
7010 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7012 rcode = G.last_exitcode;
7013 /* Exit, _skipping_ variable restoring code: */
7014 goto clean_up_and_ret0;
7016 #else /* Older, bigger, but more correct code */
7018 rcode = setup_redirects(command, squirrel);
7019 restore_redirects(squirrel);
7020 /* Set shell variables */
7022 bb_putchar_stderr('+');
7024 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7026 fprintf(stderr, " %s", p);
7027 debug_printf_exec("set shell var:'%s'->'%s'\n",
7029 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7030 /* Do we need to flag set_local_var() errors?
7031 * "assignment to readonly var" and "putenv error"
7036 bb_putchar_stderr('\n');
7037 /* Redirect error sets $? to 1. Otherwise,
7038 * if evaluating assignment value set $?, retain it.
7039 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7041 rcode = G.last_exitcode;
7042 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7044 debug_printf_exec("run_pipe: return %d\n", rcode);
7049 /* Expand the rest into (possibly) many strings each */
7050 #if ENABLE_HUSH_BASH_COMPAT
7051 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7052 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7056 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7059 /* if someone gives us an empty string: `cmd with empty output` */
7060 if (!argv_expanded[0]) {
7061 free(argv_expanded);
7063 return G.last_exitcode;
7066 x = find_builtin(argv_expanded[0]);
7067 #if ENABLE_HUSH_FUNCTIONS
7070 funcp = find_function(argv_expanded[0]);
7074 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7075 debug_printf("exec with redirects only\n");
7076 rcode = setup_redirects(command, NULL);
7077 goto clean_up_and_ret1;
7080 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7083 debug_printf_exec(": builtin '%s' '%s'...\n",
7084 x->b_cmd, argv_expanded[1]);
7086 rcode = x->b_function(argv_expanded) & 0xff;
7089 #if ENABLE_HUSH_FUNCTIONS
7091 # if ENABLE_HUSH_LOCAL
7092 struct variable **sv;
7093 sv = G.shadowed_vars_pp;
7094 G.shadowed_vars_pp = &old_vars;
7096 debug_printf_exec(": function '%s' '%s'...\n",
7097 funcp->name, argv_expanded[1]);
7098 rcode = run_function(funcp, argv_expanded) & 0xff;
7099 # if ENABLE_HUSH_LOCAL
7100 G.shadowed_vars_pp = sv;
7106 unset_vars(new_env);
7108 /* clean_up_and_ret0: */
7109 restore_redirects(squirrel);
7111 free(argv_expanded);
7112 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7114 debug_printf_exec("run_pipe return %d\n", rcode);
7118 if (ENABLE_FEATURE_SH_NOFORK) {
7119 int n = find_applet_by_name(argv_expanded[0]);
7120 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7121 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7123 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7124 argv_expanded[0], argv_expanded[1]);
7125 rcode = run_nofork_applet(n, argv_expanded);
7127 goto clean_up_and_ret;
7130 /* It is neither builtin nor applet. We must fork. */
7134 /* NB: argv_expanded may already be created, and that
7135 * might include `cmd` runs! Do not rerun it! We *must*
7136 * use argv_expanded if it's non-NULL */
7138 /* Going to fork a child per each pipe member */
7143 while (cmd_no < pi->num_cmds) {
7144 struct fd_pair pipefds;
7146 volatile nommu_save_t nommu_save;
7147 nommu_save.new_env = NULL;
7148 nommu_save.old_vars = NULL;
7149 nommu_save.argv = NULL;
7150 nommu_save.argv_from_re_execing = NULL;
7152 command = &pi->cmds[cmd_no];
7154 if (command->argv) {
7155 debug_printf_exec(": pipe member '%s' '%s'...\n",
7156 command->argv[0], command->argv[1]);
7158 debug_printf_exec(": pipe member with no argv\n");
7161 /* pipes are inserted between pairs of commands */
7164 if (cmd_no < pi->num_cmds)
7165 xpiped_pair(pipefds);
7167 command->pid = BB_MMU ? fork() : vfork();
7168 if (!command->pid) { /* child */
7170 disable_restore_tty_pgrp_on_exit();
7171 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7173 /* Every child adds itself to new process group
7174 * with pgid == pid_of_first_child_in_pipe */
7175 if (G.run_list_level == 1 && G_interactive_fd) {
7178 if (pgrp < 0) /* true for 1st process only */
7180 if (setpgid(0, pgrp) == 0
7181 && pi->followup != PIPE_BG
7182 && G_saved_tty_pgrp /* we have ctty */
7184 /* We do it in *every* child, not just first,
7186 tcsetpgrp(G_interactive_fd, pgrp);
7190 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7191 /* 1st cmd in backgrounded pipe
7192 * should have its stdin /dev/null'ed */
7194 if (open(bb_dev_null, O_RDONLY))
7195 xopen("/", O_RDONLY);
7197 xmove_fd(next_infd, 0);
7199 xmove_fd(pipefds.wr, 1);
7202 /* Like bash, explicit redirects override pipes,
7203 * and the pipe fd is available for dup'ing. */
7204 if (setup_redirects(command, NULL))
7207 /* Stores to nommu_save list of env vars putenv'ed
7208 * (NOMMU, on MMU we don't need that) */
7209 /* cast away volatility... */
7210 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7211 /* pseudo_exec() does not return */
7214 /* parent or error */
7215 #if ENABLE_HUSH_FAST
7217 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7219 enable_restore_tty_pgrp_on_exit();
7221 /* Clean up after vforked child */
7222 free(nommu_save.argv);
7223 free(nommu_save.argv_from_re_execing);
7224 unset_vars(nommu_save.new_env);
7225 add_vars(nommu_save.old_vars);
7227 free(argv_expanded);
7228 argv_expanded = NULL;
7229 if (command->pid < 0) { /* [v]fork failed */
7230 /* Clearly indicate, was it fork or vfork */
7231 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7235 /* Second and next children need to know pid of first one */
7237 pi->pgrp = command->pid;
7243 if (cmd_no < pi->num_cmds)
7245 /* Pass read (output) pipe end to next iteration */
7246 next_infd = pipefds.rd;
7249 if (!pi->alive_cmds) {
7251 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7256 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7260 /* NB: called by pseudo_exec, and therefore must not modify any
7261 * global data until exec/_exit (we can be a child after vfork!) */
7262 static int run_list(struct pipe *pi)
7264 #if ENABLE_HUSH_CASE
7265 char *case_word = NULL;
7267 #if ENABLE_HUSH_LOOPS
7268 struct pipe *loop_top = NULL;
7269 char **for_lcur = NULL;
7270 char **for_list = NULL;
7272 smallint last_followup;
7274 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7275 smalluint cond_code = 0;
7277 enum { cond_code = 0 };
7280 smallint rword; /* RES_foo */
7281 smallint last_rword; /* ditto */
7284 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7287 #if ENABLE_HUSH_LOOPS
7288 /* Check syntax for "for" */
7291 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7292 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7294 /* current word is FOR or IN (BOLD in comments below) */
7295 if (cpipe->next == NULL) {
7296 syntax_error("malformed for");
7298 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7301 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7302 if (cpipe->next->res_word == RES_DO)
7304 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7305 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7306 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7308 syntax_error("malformed for");
7310 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7317 /* Past this point, all code paths should jump to ret: label
7318 * in order to return, no direct "return" statements please.
7319 * This helps to ensure that no memory is leaked. */
7327 last_rword = RES_XXXX;
7329 last_followup = PIPE_SEQ;
7330 rcode = G.last_exitcode;
7332 /* Go through list of pipes, (maybe) executing them. */
7333 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7337 IF_HAS_KEYWORDS(rword = pi->res_word;)
7338 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7339 rword, cond_code, last_rword);
7340 #if ENABLE_HUSH_LOOPS
7341 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7342 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7344 /* start of a loop: remember where loop starts */
7349 /* Still in the same "if...", "then..." or "do..." branch? */
7350 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7351 if ((rcode == 0 && last_followup == PIPE_OR)
7352 || (rcode != 0 && last_followup == PIPE_AND)
7354 /* It is "<true> || CMD" or "<false> && CMD"
7355 * and we should not execute CMD */
7356 debug_printf_exec("skipped cmd because of || or &&\n");
7357 last_followup = pi->followup;
7361 last_followup = pi->followup;
7362 IF_HAS_KEYWORDS(last_rword = rword;)
7365 if (rword == RES_THEN) {
7366 /* if false; then ... fi has exitcode 0! */
7367 G.last_exitcode = rcode = EXIT_SUCCESS;
7368 /* "if <false> THEN cmd": skip cmd */
7372 if (rword == RES_ELSE || rword == RES_ELIF) {
7373 /* "if <true> then ... ELSE/ELIF cmd":
7374 * skip cmd and all following ones */
7379 #if ENABLE_HUSH_LOOPS
7380 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7382 /* first loop through for */
7384 static const char encoded_dollar_at[] ALIGN1 = {
7385 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7386 }; /* encoded representation of "$@" */
7387 static const char *const encoded_dollar_at_argv[] = {
7388 encoded_dollar_at, NULL
7389 }; /* argv list with one element: "$@" */
7392 vals = (char**)encoded_dollar_at_argv;
7393 if (pi->next->res_word == RES_IN) {
7394 /* if no variable values after "in" we skip "for" */
7395 if (!pi->next->cmds[0].argv) {
7396 G.last_exitcode = rcode = EXIT_SUCCESS;
7397 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7400 vals = pi->next->cmds[0].argv;
7401 } /* else: "for var; do..." -> assume "$@" list */
7402 /* create list of variable values */
7403 debug_print_strings("for_list made from", vals);
7404 for_list = expand_strvec_to_strvec(vals);
7405 for_lcur = for_list;
7406 debug_print_strings("for_list", for_list);
7409 /* "for" loop is over, clean up */
7415 /* Insert next value from for_lcur */
7416 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7417 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7420 if (rword == RES_IN) {
7421 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7423 if (rword == RES_DONE) {
7424 continue; /* "done" has no cmds too */
7427 #if ENABLE_HUSH_CASE
7428 if (rword == RES_CASE) {
7429 case_word = expand_strvec_to_string(pi->cmds->argv);
7432 if (rword == RES_MATCH) {
7435 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7437 /* all prev words didn't match, does this one match? */
7438 argv = pi->cmds->argv;
7440 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7441 /* TODO: which FNM_xxx flags to use? */
7442 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7444 if (cond_code == 0) { /* match! we will execute this branch */
7445 free(case_word); /* make future "word)" stop */
7453 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7455 continue; /* not matched yet, skip this pipe */
7458 /* Just pressing <enter> in shell should check for jobs.
7459 * OTOH, in non-interactive shell this is useless
7460 * and only leads to extra job checks */
7461 if (pi->num_cmds == 0) {
7462 if (G_interactive_fd)
7463 goto check_jobs_and_continue;
7467 /* After analyzing all keywords and conditions, we decided
7468 * to execute this pipe. NB: have to do checkjobs(NULL)
7469 * after run_pipe to collect any background children,
7470 * even if list execution is to be stopped. */
7471 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7474 #if ENABLE_HUSH_LOOPS
7475 G.flag_break_continue = 0;
7477 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7479 /* We ran a builtin, function, or group.
7480 * rcode is already known
7481 * and we don't need to wait for anything. */
7482 G.last_exitcode = rcode;
7483 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7484 check_and_run_traps();
7485 #if ENABLE_HUSH_LOOPS
7486 /* Was it "break" or "continue"? */
7487 if (G.flag_break_continue) {
7488 smallint fbc = G.flag_break_continue;
7489 /* We might fall into outer *loop*,
7490 * don't want to break it too */
7492 G.depth_break_continue--;
7493 if (G.depth_break_continue == 0)
7494 G.flag_break_continue = 0;
7495 /* else: e.g. "continue 2" should *break* once, *then* continue */
7496 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7497 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7498 goto check_jobs_and_break;
7499 /* "continue": simulate end of loop */
7504 #if ENABLE_HUSH_FUNCTIONS
7505 if (G.flag_return_in_progress == 1) {
7506 /* same as "goto check_jobs_and_break" */
7511 } else if (pi->followup == PIPE_BG) {
7512 /* What does bash do with attempts to background builtins? */
7513 /* even bash 3.2 doesn't do that well with nested bg:
7514 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7515 * I'm NOT treating inner &'s as jobs */
7516 check_and_run_traps();
7518 if (G.run_list_level == 1)
7521 /* Last command's pid goes to $! */
7522 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7523 G.last_exitcode = rcode = EXIT_SUCCESS;
7524 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7527 if (G.run_list_level == 1 && G_interactive_fd) {
7528 /* Waits for completion, then fg's main shell */
7529 rcode = checkjobs_and_fg_shell(pi);
7530 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7531 check_and_run_traps();
7534 { /* This one just waits for completion */
7535 rcode = checkjobs(pi);
7536 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7537 check_and_run_traps();
7539 G.last_exitcode = rcode;
7543 /* Analyze how result affects subsequent commands */
7545 if (rword == RES_IF || rword == RES_ELIF)
7548 #if ENABLE_HUSH_LOOPS
7549 /* Beware of "while false; true; do ..."! */
7551 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7552 /* check for RES_DONE is needed for "while ...; do \n done" case */
7554 if (rword == RES_WHILE) {
7556 /* "while false; do...done" - exitcode 0 */
7557 G.last_exitcode = rcode = EXIT_SUCCESS;
7558 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7559 goto check_jobs_and_break;
7562 if (rword == RES_UNTIL) {
7564 debug_printf_exec(": until expr is true: breaking\n");
7565 check_jobs_and_break:
7573 check_jobs_and_continue:
7580 #if ENABLE_HUSH_LOOPS
7585 #if ENABLE_HUSH_CASE
7589 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7593 /* Select which version we will use */
7594 static int run_and_free_list(struct pipe *pi)
7597 debug_printf_exec("run_and_free_list entered\n");
7598 if (!G.o_opt[OPT_O_NOEXEC]) {
7599 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7600 rcode = run_list(pi);
7602 /* free_pipe_list has the side effect of clearing memory.
7603 * In the long run that function can be merged with run_list,
7604 * but doing that now would hobble the debugging effort. */
7606 debug_printf_exec("run_and_free_list return %d\n", rcode);
7611 static void install_sighandlers(unsigned mask)
7613 sighandler_t old_handler;
7615 while ((mask >>= 1) != 0) {
7619 old_handler = install_sighandler(sig, pick_sighandler(sig));
7620 /* POSIX allows shell to re-enable SIGCHLD
7621 * even if it was SIG_IGN on entry.
7622 * Therefore we skip IGN check for it:
7626 if (old_handler == SIG_IGN) {
7627 /* oops... restore back to IGN, and record this fact */
7628 install_sighandler(sig, old_handler);
7630 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7632 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7637 /* Called a few times only (or even once if "sh -c") */
7638 static void install_special_sighandlers(void)
7642 /* Which signals are shell-special? */
7643 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7644 if (G_interactive_fd) {
7645 mask |= SPECIAL_INTERACTIVE_SIGS;
7646 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7647 mask |= SPECIAL_JOBSTOP_SIGS;
7649 /* Careful, do not re-install handlers we already installed */
7650 if (G.special_sig_mask != mask) {
7651 unsigned diff = mask & ~G.special_sig_mask;
7652 G.special_sig_mask = mask;
7653 install_sighandlers(diff);
7659 /* Set handlers to restore tty pgrp and exit */
7660 static void install_fatal_sighandlers(void)
7664 /* We will restore tty pgrp on these signals */
7666 + (1 << SIGILL ) * HUSH_DEBUG
7667 + (1 << SIGFPE ) * HUSH_DEBUG
7668 + (1 << SIGBUS ) * HUSH_DEBUG
7669 + (1 << SIGSEGV) * HUSH_DEBUG
7670 + (1 << SIGTRAP) * HUSH_DEBUG
7672 /* bash 3.2 seems to handle these just like 'fatal' ones */
7675 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7676 * if we aren't interactive... but in this case
7677 * we never want to restore pgrp on exit, and this fn is not called
7679 /*+ (1 << SIGHUP )*/
7680 /*+ (1 << SIGTERM)*/
7681 /*+ (1 << SIGINT )*/
7683 G_fatal_sig_mask = mask;
7685 install_sighandlers(mask);
7689 static int set_mode(int state, char mode, const char *o_opt)
7694 G.o_opt[OPT_O_NOEXEC] = state;
7697 IF_HUSH_MODE_X(G_x_mode = state;)
7701 /* "set -+o" without parameter.
7702 * in bash, set -o produces this output:
7706 * We always use the second form.
7708 const char *p = o_opt_strings;
7711 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7717 idx = index_in_strings(o_opt_strings, o_opt);
7719 G.o_opt[idx] = state;
7723 return EXIT_FAILURE;
7725 return EXIT_SUCCESS;
7728 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7729 int hush_main(int argc, char **argv)
7732 OPT_login = (1 << 0),
7736 unsigned builtin_argc;
7738 struct variable *cur_var;
7739 struct variable *shell_ver;
7742 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7743 G.last_exitcode = EXIT_SUCCESS;
7744 #if ENABLE_HUSH_FAST
7745 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7748 G.argv0_for_re_execing = argv[0];
7750 /* Deal with HUSH_VERSION */
7751 shell_ver = xzalloc(sizeof(*shell_ver));
7752 shell_ver->flg_export = 1;
7753 shell_ver->flg_read_only = 1;
7754 /* Code which handles ${var<op>...} needs writable values for all variables,
7755 * therefore we xstrdup: */
7756 shell_ver->varstr = xstrdup(hush_version_str);
7757 /* Create shell local variables from the values
7758 * currently living in the environment */
7759 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7760 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7761 G.top_var = shell_ver;
7762 cur_var = G.top_var;
7765 char *value = strchr(*e, '=');
7766 if (value) { /* paranoia */
7767 cur_var->next = xzalloc(sizeof(*cur_var));
7768 cur_var = cur_var->next;
7769 cur_var->varstr = *e;
7770 cur_var->max_len = strlen(*e);
7771 cur_var->flg_export = 1;
7775 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7776 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7777 putenv(shell_ver->varstr);
7780 set_pwd_var(/*exp:*/ 1);
7781 /* bash also exports SHLVL and _,
7782 * and sets (but doesn't export) the following variables:
7784 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7785 * BASH_VERSION='3.2.0(1)-release'
7787 * MACHTYPE=i386-pc-linux-gnu
7789 * HOSTNAME=<xxxxxxxxxx>
7790 * PPID=<NNNNN> - we also do it elsewhere
7801 * PIPESTATUS=([0]="0")
7802 * HISTFILE=/<xxx>/.bash_history
7806 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7808 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7818 #if ENABLE_FEATURE_EDITING
7819 G.line_input_state = new_line_input_t(FOR_SHELL);
7820 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7822 const char *hp = get_local_var_value("HISTFILE");
7824 hp = get_local_var_value("HOME");
7826 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7827 //set_local_var(xasprintf("HISTFILE=%s", ...));
7830 # if ENABLE_FEATURE_SH_HISTFILESIZE
7831 hp = get_local_var_value("HISTFILESIZE");
7832 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7838 /* Initialize some more globals to non-zero values */
7839 cmdedit_update_prompt();
7841 if (setjmp(die_jmp)) {
7842 /* xfunc has failed! die die die */
7843 /* no EXIT traps, this is an escape hatch! */
7845 hush_exit(xfunc_error_retval);
7848 /* Shell is non-interactive at first. We need to call
7849 * install_special_sighandlers() if we are going to execute "sh <script>",
7850 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7851 * If we later decide that we are interactive, we run install_special_sighandlers()
7852 * in order to intercept (more) signals.
7856 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7857 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7860 opt = getopt(argc, argv, "+c:xinsl"
7863 # if ENABLE_HUSH_FUNCTIONS
7873 * sh ... -c 'script'
7874 * sh ... -c 'script' ARG0 [ARG1...]
7875 * On NOMMU, if builtin_argc != 0,
7876 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7877 * "" needs to be replaced with NULL
7878 * and BARGV vector fed to builtin function.
7879 * Note: the form without ARG0 never happens:
7880 * sh ... -c 'builtin' BARGV... ""
7883 G.root_pid = getpid();
7884 G.root_ppid = getppid();
7886 G.global_argv = argv + optind;
7887 G.global_argc = argc - optind;
7889 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7890 const struct built_in_command *x;
7892 install_special_sighandlers();
7893 x = find_builtin(optarg);
7894 if (x) { /* paranoia */
7895 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7896 G.global_argv += builtin_argc;
7897 G.global_argv[-1] = NULL; /* replace "" */
7899 G.last_exitcode = x->b_function(argv + optind - 1);
7903 if (!G.global_argv[0]) {
7904 /* -c 'script' (no params): prevent empty $0 */
7905 G.global_argv--; /* points to argv[i] of 'script' */
7906 G.global_argv[0] = argv[0];
7908 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7909 install_special_sighandlers();
7910 parse_and_run_string(optarg);
7913 /* Well, we cannot just declare interactiveness,
7914 * we have to have some stuff (ctty, etc) */
7915 /* G_interactive_fd++; */
7918 /* "-s" means "read from stdin", but this is how we always
7919 * operate, so simply do nothing here. */
7925 case '<': /* "big heredoc" support */
7926 full_write1_str(optarg);
7929 unsigned long long empty_trap_mask;
7931 G.root_pid = bb_strtou(optarg, &optarg, 16);
7933 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7935 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7937 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7939 builtin_argc = bb_strtou(optarg, &optarg, 16);
7941 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7942 if (empty_trap_mask != 0) {
7944 install_special_sighandlers();
7945 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7946 for (sig = 1; sig < NSIG; sig++) {
7947 if (empty_trap_mask & (1LL << sig)) {
7948 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7949 install_sighandler(sig, SIG_IGN);
7953 # if ENABLE_HUSH_LOOPS
7955 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7961 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7963 # if ENABLE_HUSH_FUNCTIONS
7965 struct function *funcp = new_function(optarg);
7966 /* funcp->name is already set to optarg */
7967 /* funcp->body is set to NULL. It's a special case. */
7968 funcp->body_as_string = argv[optind];
7976 if (set_mode(1, opt, NULL) == 0) /* no error */
7980 fprintf(stderr, "Usage: sh [FILE]...\n"
7981 " or: sh -c command [args]...\n\n");
7987 } /* option parsing loop */
7989 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7990 G.global_argc = argc - (optind - 1);
7991 G.global_argv = argv + (optind - 1);
7992 G.global_argv[0] = argv[0];
7995 G.root_pid = getpid();
7996 G.root_ppid = getppid();
7999 /* If we are login shell... */
8000 if (flags & OPT_login) {
8002 debug_printf("sourcing /etc/profile\n");
8003 input = fopen_for_read("/etc/profile");
8004 if (input != NULL) {
8005 close_on_exec_on(fileno(input));
8006 install_special_sighandlers();
8007 parse_and_run_file(input);
8010 /* bash: after sourcing /etc/profile,
8011 * tries to source (in the given order):
8012 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8013 * stopping on first found. --noprofile turns this off.
8014 * bash also sources ~/.bash_logout on exit.
8015 * If called as sh, skips .bash_XXX files.
8019 if (G.global_argv[1]) {
8022 * "bash <script>" (which is never interactive (unless -i?))
8023 * sources $BASH_ENV here (without scanning $PATH).
8024 * If called as sh, does the same but with $ENV.
8028 debug_printf("running script '%s'\n", G.global_argv[0]);
8029 input = xfopen_for_read(G.global_argv[0]);
8030 close_on_exec_on(fileno(input));
8031 install_special_sighandlers();
8032 parse_and_run_file(input);
8033 #if ENABLE_FEATURE_CLEAN_UP
8039 /* Up to here, shell was non-interactive. Now it may become one.
8040 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8043 /* A shell is interactive if the '-i' flag was given,
8044 * or if all of the following conditions are met:
8046 * no arguments remaining or the -s flag given
8047 * standard input is a terminal
8048 * standard output is a terminal
8049 * Refer to Posix.2, the description of the 'sh' utility.
8052 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8053 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8054 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8055 if (G_saved_tty_pgrp < 0)
8056 G_saved_tty_pgrp = 0;
8058 /* try to dup stdin to high fd#, >= 255 */
8059 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8060 if (G_interactive_fd < 0) {
8061 /* try to dup to any fd */
8062 G_interactive_fd = dup(STDIN_FILENO);
8063 if (G_interactive_fd < 0) {
8065 G_interactive_fd = 0;
8066 G_saved_tty_pgrp = 0;
8069 // TODO: track & disallow any attempts of user
8070 // to (inadvertently) close/redirect G_interactive_fd
8072 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8073 if (G_interactive_fd) {
8074 close_on_exec_on(G_interactive_fd);
8076 if (G_saved_tty_pgrp) {
8077 /* If we were run as 'hush &', sleep until we are
8078 * in the foreground (tty pgrp == our pgrp).
8079 * If we get started under a job aware app (like bash),
8080 * make sure we are now in charge so we don't fight over
8081 * who gets the foreground */
8083 pid_t shell_pgrp = getpgrp();
8084 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8085 if (G_saved_tty_pgrp == shell_pgrp)
8087 /* send TTIN to ourself (should stop us) */
8088 kill(- shell_pgrp, SIGTTIN);
8092 /* Install more signal handlers */
8093 install_special_sighandlers();
8095 if (G_saved_tty_pgrp) {
8096 /* Set other signals to restore saved_tty_pgrp */
8097 install_fatal_sighandlers();
8098 /* Put ourselves in our own process group
8099 * (bash, too, does this only if ctty is available) */
8100 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8101 /* Grab control of the terminal */
8102 tcsetpgrp(G_interactive_fd, getpid());
8104 /* -1 is special - makes xfuncs longjmp, not exit
8105 * (we reset die_sleep = 0 whereever we [v]fork) */
8106 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8108 install_special_sighandlers();
8110 #elif ENABLE_HUSH_INTERACTIVE
8111 /* No job control compiled in, only prompt/line editing */
8112 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8113 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8114 if (G_interactive_fd < 0) {
8115 /* try to dup to any fd */
8116 G_interactive_fd = dup(STDIN_FILENO);
8117 if (G_interactive_fd < 0)
8119 G_interactive_fd = 0;
8122 if (G_interactive_fd) {
8123 close_on_exec_on(G_interactive_fd);
8125 install_special_sighandlers();
8127 /* We have interactiveness code disabled */
8128 install_special_sighandlers();
8131 * if interactive but not a login shell, sources ~/.bashrc
8132 * (--norc turns this off, --rcfile <file> overrides)
8135 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8136 /* note: ash and hush share this string */
8137 printf("\n\n%s %s\n"
8138 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8141 "hush - the humble shell"
8145 parse_and_run_file(stdin);
8148 hush_exit(G.last_exitcode);
8153 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8154 int msh_main(int argc, char **argv)
8156 //bb_error_msg("msh is deprecated, please use hush instead");
8157 return hush_main(argc, argv);
8165 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8170 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8177 return applet_main_func(argc, argv - argc);
8180 static int FAST_FUNC builtin_test(char **argv)
8182 return run_applet_main(argv, test_main);
8185 static int FAST_FUNC builtin_echo(char **argv)
8187 return run_applet_main(argv, echo_main);
8191 static int FAST_FUNC builtin_printf(char **argv)
8193 return run_applet_main(argv, printf_main);
8197 static char **skip_dash_dash(char **argv)
8200 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8205 static int FAST_FUNC builtin_eval(char **argv)
8207 int rcode = EXIT_SUCCESS;
8209 argv = skip_dash_dash(argv);
8211 char *str = expand_strvec_to_string(argv);
8213 * eval "echo Hi; done" ("done" is syntax error):
8214 * "echo Hi" will not execute too.
8216 parse_and_run_string(str);
8218 rcode = G.last_exitcode;
8223 static int FAST_FUNC builtin_cd(char **argv)
8227 argv = skip_dash_dash(argv);
8229 if (newdir == NULL) {
8230 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8231 * bash says "bash: cd: HOME not set" and does nothing
8234 const char *home = get_local_var_value("HOME");
8235 newdir = home ? home : "/";
8237 if (chdir(newdir)) {
8238 /* Mimic bash message exactly */
8239 bb_perror_msg("cd: %s", newdir);
8240 return EXIT_FAILURE;
8242 /* Read current dir (get_cwd(1) is inside) and set PWD.
8243 * Note: do not enforce exporting. If PWD was unset or unexported,
8244 * set it again, but do not export. bash does the same.
8246 set_pwd_var(/*exp:*/ 0);
8247 return EXIT_SUCCESS;
8250 static int FAST_FUNC builtin_exec(char **argv)
8252 argv = skip_dash_dash(argv);
8253 if (argv[0] == NULL)
8254 return EXIT_SUCCESS; /* bash does this */
8256 /* Careful: we can end up here after [v]fork. Do not restore
8257 * tty pgrp then, only top-level shell process does that */
8258 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8259 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8261 /* TODO: if exec fails, bash does NOT exit! We do.
8262 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8263 * and tcsetpgrp, and this is inherently racy.
8265 execvp_or_die(argv);
8268 static int FAST_FUNC builtin_exit(char **argv)
8270 debug_printf_exec("%s()\n", __func__);
8272 /* interactive bash:
8273 * # trap "echo EEE" EXIT
8276 * There are stopped jobs.
8277 * (if there are _stopped_ jobs, running ones don't count)
8280 # EEE (then bash exits)
8282 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8285 /* note: EXIT trap is run by hush_exit */
8286 argv = skip_dash_dash(argv);
8287 if (argv[0] == NULL)
8288 hush_exit(G.last_exitcode);
8289 /* mimic bash: exit 123abc == exit 255 + error msg */
8290 xfunc_error_retval = 255;
8291 /* bash: exit -2 == exit 254, no error msg */
8292 hush_exit(xatoi(argv[0]) & 0xff);
8295 static void print_escaped(const char *s)
8300 const char *p = strchrnul(s, '\'');
8301 /* print 'xxxx', possibly just '' */
8302 printf("'%.*s'", (int)(p - s), s);
8307 /* s points to '; print "'''...'''" */
8309 do putchar('\''); while (*++s == '\'');
8314 #if !ENABLE_HUSH_LOCAL
8315 #define helper_export_local(argv, exp, lvl) \
8316 helper_export_local(argv, exp)
8318 static void helper_export_local(char **argv, int exp, int lvl)
8322 char *name_end = strchrnul(name, '=');
8324 /* So far we do not check that name is valid (TODO?) */
8326 if (*name_end == '\0') {
8327 struct variable *var, **vpp;
8329 vpp = get_ptr_to_local_var(name, name_end - name);
8330 var = vpp ? *vpp : NULL;
8332 if (exp == -1) { /* unexporting? */
8333 /* export -n NAME (without =VALUE) */
8335 var->flg_export = 0;
8336 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8338 } /* else: export -n NOT_EXISTING_VAR: no-op */
8341 if (exp == 1) { /* exporting? */
8342 /* export NAME (without =VALUE) */
8344 var->flg_export = 1;
8345 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8346 putenv(var->varstr);
8350 /* Exporting non-existing variable.
8351 * bash does not put it in environment,
8352 * but remembers that it is exported,
8353 * and does put it in env when it is set later.
8354 * We just set it to "" and export. */
8355 /* Or, it's "local NAME" (without =VALUE).
8356 * bash sets the value to "". */
8357 name = xasprintf("%s=", name);
8359 /* (Un)exporting/making local NAME=VALUE */
8360 name = xstrdup(name);
8362 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8366 static int FAST_FUNC builtin_export(char **argv)
8368 unsigned opt_unexport;
8370 #if ENABLE_HUSH_EXPORT_N
8371 /* "!": do not abort on errors */
8372 opt_unexport = getopt32(argv, "!n");
8373 if (opt_unexport == (uint32_t)-1)
8374 return EXIT_FAILURE;
8381 if (argv[0] == NULL) {
8388 /* ash emits: export VAR='VAL'
8389 * bash: declare -x VAR="VAL"
8390 * we follow ash example */
8391 const char *s = *e++;
8392 const char *p = strchr(s, '=');
8394 if (!p) /* wtf? take next variable */
8397 printf("export %.*s", (int)(p - s) + 1, s);
8398 print_escaped(p + 1);
8402 /*fflush_all(); - done after each builtin anyway */
8404 return EXIT_SUCCESS;
8407 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8409 return EXIT_SUCCESS;
8412 #if ENABLE_HUSH_LOCAL
8413 static int FAST_FUNC builtin_local(char **argv)
8415 if (G.func_nest_level == 0) {
8416 bb_error_msg("%s: not in a function", argv[0]);
8417 return EXIT_FAILURE; /* bash compat */
8419 helper_export_local(argv, 0, G.func_nest_level);
8420 return EXIT_SUCCESS;
8424 static int FAST_FUNC builtin_trap(char **argv)
8430 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8435 /* No args: print all trapped */
8436 for (i = 0; i < NSIG; ++i) {
8439 print_escaped(G.traps[i]);
8440 /* note: bash adds "SIG", but only if invoked
8441 * as "bash". If called as "sh", or if set -o posix,
8442 * then it prints short signal names.
8443 * We are printing short names: */
8444 printf(" %s\n", get_signame(i));
8447 /*fflush_all(); - done after each builtin anyway */
8448 return EXIT_SUCCESS;
8452 /* If first arg is a number: reset all specified signals */
8453 sig = bb_strtou(*argv, NULL, 10);
8459 sighandler_t handler;
8461 sig = get_signum(*argv++);
8462 if (sig < 0 || sig >= NSIG) {
8464 /* Mimic bash message exactly */
8465 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8470 G.traps[sig] = xstrdup(new_cmd);
8472 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8473 get_signame(sig), sig, G.traps[sig]);
8475 /* There is no signal for 0 (EXIT) */
8480 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8482 /* We are removing trap handler */
8483 handler = pick_sighandler(sig);
8484 install_sighandler(sig, handler);
8489 if (!argv[1]) { /* no second arg */
8490 bb_error_msg("trap: invalid arguments");
8491 return EXIT_FAILURE;
8494 /* First arg is "-": reset all specified to default */
8495 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8496 /* Everything else: set arg as signal handler
8497 * (includes "" case, which ignores signal) */
8498 if (argv[0][0] == '-') {
8499 if (argv[0][1] == '\0') { /* "-" */
8500 /* new_cmd remains NULL: "reset these sigs" */
8503 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8506 /* else: "-something", no special meaning */
8511 goto process_sig_list;
8514 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8515 static int FAST_FUNC builtin_type(char **argv)
8517 int ret = EXIT_SUCCESS;
8523 if (0) {} /* make conditional compile easier below */
8524 /*else if (find_alias(*argv))
8525 type = "an alias";*/
8526 #if ENABLE_HUSH_FUNCTIONS
8527 else if (find_function(*argv))
8528 type = "a function";
8530 else if (find_builtin(*argv))
8531 type = "a shell builtin";
8532 else if ((path = find_in_path(*argv)) != NULL)
8535 bb_error_msg("type: %s: not found", *argv);
8540 printf("%s is %s\n", *argv, type);
8548 /* built-in 'fg' and 'bg' handler */
8549 static int FAST_FUNC builtin_fg_bg(char **argv)
8554 if (!G_interactive_fd)
8555 return EXIT_FAILURE;
8557 /* If they gave us no args, assume they want the last backgrounded task */
8559 for (pi = G.job_list; pi; pi = pi->next) {
8560 if (pi->jobid == G.last_jobid) {
8564 bb_error_msg("%s: no current job", argv[0]);
8565 return EXIT_FAILURE;
8567 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8568 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8569 return EXIT_FAILURE;
8571 for (pi = G.job_list; pi; pi = pi->next) {
8572 if (pi->jobid == jobnum) {
8576 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8577 return EXIT_FAILURE;
8579 /* TODO: bash prints a string representation
8580 * of job being foregrounded (like "sleep 1 | cat") */
8581 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8582 /* Put the job into the foreground. */
8583 tcsetpgrp(G_interactive_fd, pi->pgrp);
8586 /* Restart the processes in the job */
8587 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8588 for (i = 0; i < pi->num_cmds; i++) {
8589 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8590 pi->cmds[i].is_stopped = 0;
8592 pi->stopped_cmds = 0;
8594 i = kill(- pi->pgrp, SIGCONT);
8596 if (errno == ESRCH) {
8597 delete_finished_bg_job(pi);
8598 return EXIT_SUCCESS;
8600 bb_perror_msg("kill (SIGCONT)");
8603 if (argv[0][0] == 'f') {
8605 return checkjobs_and_fg_shell(pi);
8607 return EXIT_SUCCESS;
8611 #if ENABLE_HUSH_HELP
8612 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8614 const struct built_in_command *x;
8617 "Built-in commands:\n"
8618 "------------------\n");
8619 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8621 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8624 return EXIT_SUCCESS;
8629 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8632 const char *status_string;
8634 for (job = G.job_list; job; job = job->next) {
8635 if (job->alive_cmds == job->stopped_cmds)
8636 status_string = "Stopped";
8638 status_string = "Running";
8640 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8642 return EXIT_SUCCESS;
8647 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8652 # ifdef M_TRIM_THRESHOLD
8653 /* Optional. Reduces probability of false positives */
8656 /* Crude attempt to find where "free memory" starts,
8657 * sans fragmentation. */
8659 l = (unsigned long)p;
8662 if (l < (unsigned long)p) l = (unsigned long)p;
8665 if (!G.memleak_value)
8666 G.memleak_value = l;
8668 l -= G.memleak_value;
8675 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8680 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8683 return EXIT_SUCCESS;
8686 /* Interruptibility of read builtin in bash
8687 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8689 * Empty trap makes read ignore corresponding signal, for any signal.
8692 * - terminates non-interactive shell;
8693 * - interrupts read in interactive shell;
8694 * if it has non-empty trap:
8695 * - executes trap and returns to command prompt in interactive shell;
8696 * - executes trap and returns to read in non-interactive shell;
8698 * - is ignored (does not interrupt) read in interactive shell;
8699 * - terminates non-interactive shell;
8700 * if it has non-empty trap:
8701 * - executes trap and returns to read;
8703 * - terminates shell (regardless of interactivity);
8704 * if it has non-empty trap:
8705 * - executes trap and returns to read;
8707 static int FAST_FUNC builtin_read(char **argv)
8717 /* "!": do not abort on errors.
8718 * Option string must start with "sr" to match BUILTIN_READ_xxx
8720 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8721 if (read_flags == (uint32_t)-1)
8722 return EXIT_FAILURE;
8724 ifs = get_local_var_value("IFS"); /* can be NULL */
8727 r = shell_builtin_read(set_local_var_from_halves,
8737 if ((uintptr_t)r == 1 && errno == EINTR) {
8738 unsigned sig = check_and_run_traps();
8739 if (sig && sig != SIGINT)
8743 if ((uintptr_t)r > 1) {
8744 bb_error_msg("%s", r);
8745 r = (char*)(uintptr_t)1;
8748 return (uintptr_t)r;
8751 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8752 * built-in 'set' handler
8754 * set [-abCefhmnuvx] [-o option] [argument...]
8755 * set [+abCefhmnuvx] [+o option] [argument...]
8756 * set -- [argument...]
8759 * Implementations shall support the options in both their hyphen and
8760 * plus-sign forms. These options can also be specified as options to sh.
8762 * Write out all variables and their values: set
8763 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8764 * Turn on the -x and -v options: set -xv
8765 * Unset all positional parameters: set --
8766 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8767 * Set the positional parameters to the expansion of x, even if x expands
8768 * with a leading '-' or '+': set -- $x
8770 * So far, we only support "set -- [argument...]" and some of the short names.
8772 static int FAST_FUNC builtin_set(char **argv)
8775 char **pp, **g_argv;
8776 char *arg = *++argv;
8780 for (e = G.top_var; e; e = e->next)
8782 return EXIT_SUCCESS;
8786 if (strcmp(arg, "--") == 0) {
8790 if (arg[0] != '+' && arg[0] != '-')
8792 for (n = 1; arg[n]; ++n) {
8793 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8795 if (arg[n] == 'o' && argv[1])
8798 } while ((arg = *++argv) != NULL);
8799 /* Now argv[0] is 1st argument */
8802 return EXIT_SUCCESS;
8805 /* NB: G.global_argv[0] ($0) is never freed/changed */
8806 g_argv = G.global_argv;
8807 if (G.global_args_malloced) {
8813 G.global_args_malloced = 1;
8814 pp = xzalloc(sizeof(pp[0]) * 2);
8815 pp[0] = g_argv[0]; /* retain $0 */
8818 /* This realloc's G.global_argv */
8819 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8826 return EXIT_SUCCESS;
8828 /* Nothing known, so abort */
8830 bb_error_msg("set: %s: invalid option", arg);
8831 return EXIT_FAILURE;
8834 static int FAST_FUNC builtin_shift(char **argv)
8837 argv = skip_dash_dash(argv);
8841 if (n >= 0 && n < G.global_argc) {
8842 if (G.global_args_malloced) {
8845 free(G.global_argv[m++]);
8848 memmove(&G.global_argv[1], &G.global_argv[n+1],
8849 G.global_argc * sizeof(G.global_argv[0]));
8850 return EXIT_SUCCESS;
8852 return EXIT_FAILURE;
8855 static int FAST_FUNC builtin_source(char **argv)
8857 char *arg_path, *filename;
8860 #if ENABLE_HUSH_FUNCTIONS
8864 argv = skip_dash_dash(argv);
8867 /* bash says: "bash: .: filename argument required" */
8868 return 2; /* bash compat */
8871 if (!strchr(filename, '/')) {
8872 arg_path = find_in_path(filename);
8874 filename = arg_path;
8876 input = fopen_or_warn(filename, "r");
8879 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8880 return EXIT_FAILURE;
8882 close_on_exec_on(fileno(input));
8884 #if ENABLE_HUSH_FUNCTIONS
8885 sv_flg = G.flag_return_in_progress;
8886 /* "we are inside sourced file, ok to use return" */
8887 G.flag_return_in_progress = -1;
8889 save_and_replace_G_args(&sv, argv);
8891 parse_and_run_file(input);
8894 restore_G_args(&sv, argv);
8895 #if ENABLE_HUSH_FUNCTIONS
8896 G.flag_return_in_progress = sv_flg;
8899 return G.last_exitcode;
8902 static int FAST_FUNC builtin_umask(char **argv)
8908 argv = skip_dash_dash(argv);
8910 mode_t old_mask = mask;
8913 rc = bb_parse_mode(argv[0], &mask);
8918 * bash: umask: 'q': invalid symbolic mode operator
8919 * bash: umask: 999: octal number out of range
8921 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8926 printf("%04o\n", (unsigned) mask);
8927 /* fall through and restore mask which we set to 0 */
8931 return !rc; /* rc != 0 - success */
8934 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8935 static int FAST_FUNC builtin_unset(char **argv)
8940 /* "!": do not abort on errors */
8941 /* "+": stop at 1st non-option */
8942 opts = getopt32(argv, "!+vf");
8943 if (opts == (unsigned)-1)
8944 return EXIT_FAILURE;
8946 bb_error_msg("unset: -v and -f are exclusive");
8947 return EXIT_FAILURE;
8953 if (!(opts & 2)) { /* not -f */
8954 if (unset_local_var(*argv)) {
8955 /* unset <nonexistent_var> doesn't fail.
8956 * Error is when one tries to unset RO var.
8957 * Message was printed by unset_local_var. */
8961 #if ENABLE_HUSH_FUNCTIONS
8971 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8972 static int FAST_FUNC builtin_wait(char **argv)
8974 int ret = EXIT_SUCCESS;
8977 argv = skip_dash_dash(argv);
8978 if (argv[0] == NULL) {
8979 /* Don't care about wait results */
8980 /* Note 1: must wait until there are no more children */
8981 /* Note 2: must be interruptible */
8983 * $ sleep 3 & sleep 6 & wait
8988 * $ sleep 3 & sleep 6 & wait
8992 * ^C <-- after ~4 sec from keyboard
8997 sigset_t oldset, allsigs;
8999 /* waitpid is not interruptible by SA_RESTARTed
9000 * signals which we use. Thus, this ugly dance:
9003 /* Make sure possible SIGCHLD is stored in kernel's
9004 * pending signal mask before we call waitpid.
9005 * Or else we may race with SIGCHLD, lose it,
9006 * and get stuck in sigwaitinfo...
9008 sigfillset(&allsigs);
9009 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9011 if (!sigisemptyset(&G.pending_set)) {
9012 /* Crap! we raced with some signal! */
9017 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9018 if (errno == ECHILD) {
9019 sigprocmask(SIG_SETMASK, &oldset, NULL);
9023 /* Wait for SIGCHLD or any other signal */
9024 //sig = sigwaitinfo(&allsigs, NULL);
9025 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9026 /* Note: sigsuspend invokes signal handler */
9027 sigsuspend(&oldset);
9029 sigprocmask(SIG_SETMASK, &oldset, NULL);
9031 /* So, did we get a signal? */
9033 // raise(sig); /* run handler */
9034 sig = check_and_run_traps();
9035 if (sig /*&& sig != SIGCHLD - always true */) {
9040 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9045 /* This is probably buggy wrt interruptible-ness */
9047 pid_t pid = bb_strtou(*argv, NULL, 10);
9049 /* mimic bash message */
9050 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9051 return EXIT_FAILURE;
9053 if (waitpid(pid, &status, 0) == pid) {
9054 if (WIFSIGNALED(status))
9055 ret = 128 + WTERMSIG(status);
9056 else if (WIFEXITED(status))
9057 ret = WEXITSTATUS(status);
9061 bb_perror_msg("wait %s", *argv);
9070 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9071 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9074 def = bb_strtou(argv[1], NULL, 10);
9075 if (errno || def < def_min || argv[2]) {
9076 bb_error_msg("%s: bad arguments", argv[0]);
9084 #if ENABLE_HUSH_LOOPS
9085 static int FAST_FUNC builtin_break(char **argv)
9088 if (G.depth_of_loop == 0) {
9089 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9090 return EXIT_SUCCESS; /* bash compat */
9092 G.flag_break_continue++; /* BC_BREAK = 1 */
9094 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9095 if (depth == UINT_MAX)
9096 G.flag_break_continue = BC_BREAK;
9097 if (G.depth_of_loop < depth)
9098 G.depth_break_continue = G.depth_of_loop;
9100 return EXIT_SUCCESS;
9103 static int FAST_FUNC builtin_continue(char **argv)
9105 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9106 return builtin_break(argv);
9110 #if ENABLE_HUSH_FUNCTIONS
9111 static int FAST_FUNC builtin_return(char **argv)
9115 if (G.flag_return_in_progress != -1) {
9116 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9117 return EXIT_FAILURE; /* bash compat */
9120 G.flag_return_in_progress = 1;
9123 * out of range: wraps around at 256, does not error out
9124 * non-numeric param:
9125 * f() { false; return qwe; }; f; echo $?
9126 * bash: return: qwe: numeric argument required <== we do this
9127 * 255 <== we also do this
9129 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);