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 */
110 //config: bool "hush"
113 //config: hush is a small shell (25k). It handles the normal flow control
114 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
115 //config: case/esac. Redirections, here documents, $((arithmetic))
116 //config: and functions are supported.
118 //config: It will compile and work on no-mmu systems.
120 //config: It does not handle select, aliases, tilde expansion,
121 //config: &>file and >&file redirection of stdout+stderr.
123 //config:config HUSH_BASH_COMPAT
124 //config: bool "bash-compatible extensions"
126 //config: depends on HUSH
128 //config: Enable bash-compatible extensions.
130 //config:config HUSH_BRACE_EXPANSION
131 //config: bool "Brace expansion"
133 //config: depends on HUSH_BASH_COMPAT
135 //config: Enable {abc,def} extension.
137 //config:config HUSH_HELP
138 //config: bool "help builtin"
140 //config: depends on HUSH
142 //config: Enable help builtin in hush. Code size + ~1 kbyte.
144 //config:config HUSH_INTERACTIVE
145 //config: bool "Interactive mode"
147 //config: depends on HUSH
149 //config: Enable interactive mode (prompt and command editing).
150 //config: Without this, hush simply reads and executes commands
151 //config: from stdin just like a shell script from a file.
152 //config: No prompt, no PS1/PS2 magic shell variables.
154 //config:config HUSH_SAVEHISTORY
155 //config: bool "Save command history to .hush_history"
157 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
159 //config: Enable history saving in hush.
161 //config:config HUSH_JOB
162 //config: bool "Job control"
164 //config: depends on HUSH_INTERACTIVE
166 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
167 //config: command (not entire shell), fg/bg builtins work. Without this option,
168 //config: "cmd &" still works by simply spawning a process and immediately
169 //config: prompting for next command (or executing next command in a script),
170 //config: but no separate process group is formed.
172 //config:config HUSH_TICK
173 //config: bool "Process substitution"
175 //config: depends on HUSH
177 //config: Enable process substitution `command` and $(command) in hush.
179 //config:config HUSH_IF
180 //config: bool "Support if/then/elif/else/fi"
182 //config: depends on HUSH
184 //config: Enable if/then/elif/else/fi in hush.
186 //config:config HUSH_LOOPS
187 //config: bool "Support for, while and until loops"
189 //config: depends on HUSH
191 //config: Enable for, while and until loops in hush.
193 //config:config HUSH_CASE
194 //config: bool "Support case ... esac statement"
196 //config: depends on HUSH
198 //config: Enable case ... esac statement in hush. +400 bytes.
200 //config:config HUSH_FUNCTIONS
201 //config: bool "Support funcname() { commands; } syntax"
203 //config: depends on HUSH
205 //config: Enable support for shell functions in hush. +800 bytes.
207 //config:config HUSH_LOCAL
208 //config: bool "Support local builtin"
210 //config: depends on HUSH_FUNCTIONS
212 //config: Enable support for local variables in functions.
214 //config:config HUSH_RANDOM_SUPPORT
215 //config: bool "Pseudorandom generator and $RANDOM variable"
217 //config: depends on HUSH
219 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
220 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
222 //config:config HUSH_EXPORT_N
223 //config: bool "Support 'export -n' option"
225 //config: depends on HUSH
227 //config: export -n unexports variables. It is a bash extension.
229 //config:config HUSH_MODE_X
230 //config: bool "Support 'hush -x' option and 'set -x' command"
232 //config: depends on HUSH
234 //config: This instructs hush to print commands before execution.
235 //config: Adds ~300 bytes.
238 //config: bool "msh (deprecated: aliased to hush)"
240 //config: select HUSH
242 //config: msh is deprecated and will be removed, please migrate to hush.
245 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
246 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
247 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
248 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
250 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
251 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
253 /* -i (interactive) and -s (read stdin) are also accepted,
254 * but currently do nothing, therefore aren't shown in help.
255 * NOMMU-specific options are not meant to be used by users,
256 * therefore we don't show them either.
258 //usage:#define hush_trivial_usage
259 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
260 //usage:#define hush_full_usage "\n\n"
261 //usage: "Unix shell interpreter"
263 //usage:#define msh_trivial_usage hush_trivial_usage
264 //usage:#define msh_full_usage hush_full_usage
266 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
267 //usage:# define sh_trivial_usage hush_trivial_usage
268 //usage:# define sh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
271 //usage:# define bash_trivial_usage hush_trivial_usage
272 //usage:# define bash_full_usage hush_full_usage
277 #define LEAK_HUNTING 0
278 #define BUILD_AS_NOMMU 0
279 /* Enable/disable sanity checks. Ok to enable in production,
280 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
281 * Keeping 1 for now even in released versions.
284 /* Slightly bigger (+200 bytes), but faster hush.
285 * So far it only enables a trick with counting SIGCHLDs and forks,
286 * which allows us to do fewer waitpid's.
287 * (we can detect a case where neither forks were done nor SIGCHLDs happened
288 * and therefore waitpid will return the same result as last time)
290 #define ENABLE_HUSH_FAST 0
291 /* TODO: implement simplified code for users which do not need ${var%...} ops
292 * So far ${var%...} ops are always enabled:
294 #define ENABLE_HUSH_DOLLAR_OPS 1
299 # undef USE_FOR_NOMMU
302 # define USE_FOR_NOMMU(...) __VA_ARGS__
303 # define USE_FOR_MMU(...)
306 #include "NUM_APPLETS.h"
308 /* STANDALONE does not make sense, and won't compile */
309 # undef CONFIG_FEATURE_SH_STANDALONE
310 # undef ENABLE_FEATURE_SH_STANDALONE
311 # undef IF_FEATURE_SH_STANDALONE
312 # undef IF_NOT_FEATURE_SH_STANDALONE
313 # define ENABLE_FEATURE_SH_STANDALONE 0
314 # define IF_FEATURE_SH_STANDALONE(...)
315 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
318 #if !ENABLE_HUSH_INTERACTIVE
319 # undef ENABLE_FEATURE_EDITING
320 # define ENABLE_FEATURE_EDITING 0
321 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
322 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
323 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
324 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
327 /* Do we support ANY keywords? */
328 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
329 # define HAS_KEYWORDS 1
330 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
331 # define IF_HAS_NO_KEYWORDS(...)
333 # define HAS_KEYWORDS 0
334 # define IF_HAS_KEYWORDS(...)
335 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
338 /* If you comment out one of these below, it will be #defined later
339 * to perform debug printfs to stderr: */
340 #define debug_printf(...) do {} while (0)
341 /* Finer-grained debug switches */
342 #define debug_printf_parse(...) do {} while (0)
343 #define debug_print_tree(a, b) do {} while (0)
344 #define debug_printf_exec(...) do {} while (0)
345 #define debug_printf_env(...) do {} while (0)
346 #define debug_printf_jobs(...) do {} while (0)
347 #define debug_printf_expand(...) do {} while (0)
348 #define debug_printf_varexp(...) do {} while (0)
349 #define debug_printf_glob(...) do {} while (0)
350 #define debug_printf_list(...) do {} while (0)
351 #define debug_printf_subst(...) do {} while (0)
352 #define debug_printf_clean(...) do {} while (0)
354 #define ERR_PTR ((void*)(long)1)
356 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
358 #define _SPECIAL_VARS_STR "_*@$!?#"
359 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
360 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
361 #if ENABLE_HUSH_BASH_COMPAT
362 /* Support / and // replace ops */
363 /* Note that // is stored as \ in "encoded" string representation */
364 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
365 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
366 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
368 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
369 # define VAR_SUBST_OPS "%#:-=+?"
370 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
373 #define SPECIAL_VAR_SYMBOL 3
377 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
379 /* This supports saving pointers malloced in vfork child,
380 * to be freed in the parent.
383 typedef struct nommu_save_t {
385 struct variable *old_vars;
387 char **argv_from_re_execing;
400 #if ENABLE_HUSH_LOOPS
407 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
412 /* three pseudo-keywords support contrived "case" syntax: */
413 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
414 RES_MATCH , /* "word)" */
415 RES_CASE_BODY, /* "this command is inside CASE" */
422 typedef struct o_string {
424 int length; /* position where data is appended */
427 /* At least some part of the string was inside '' or "",
428 * possibly empty one: word"", wo''rd etc. */
429 smallint has_quoted_part;
430 smallint has_empty_slot;
431 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
434 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
436 /* Protect newly added chars against globbing
437 * by prepending \ to *, ?, [, \ */
438 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
441 MAYBE_ASSIGNMENT = 0,
442 DEFINITELY_ASSIGNMENT = 1,
444 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
447 /* Used for initialization: o_string foo = NULL_O_STRING; */
448 #define NULL_O_STRING { NULL }
450 #ifndef debug_printf_parse
451 static const char *const assignment_flag[] = {
453 "DEFINITELY_ASSIGNMENT",
459 typedef struct in_str {
461 /* eof_flag=1: last char in ->p is really an EOF */
462 char eof_flag; /* meaningless if ->p == NULL */
464 #if ENABLE_HUSH_INTERACTIVE
465 smallint promptmode; /* 0: PS1, 1: PS2 */
469 int (*get) (struct in_str *) FAST_FUNC;
470 int (*peek) (struct in_str *) FAST_FUNC;
472 #define i_getch(input) ((input)->get(input))
473 #define i_peek(input) ((input)->peek(input))
475 /* The descrip member of this structure is only used to make
476 * debugging output pretty */
477 static const struct {
479 signed char default_fd;
482 { O_RDONLY, 0, "<" },
483 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
484 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
485 { O_CREAT|O_RDWR, 1, "<>" },
486 { O_RDONLY, 0, "<<" },
487 /* Should not be needed. Bogus default_fd helps in debugging */
488 /* { O_RDONLY, 77, "<<" }, */
491 struct redir_struct {
492 struct redir_struct *next;
493 char *rd_filename; /* filename */
494 int rd_fd; /* fd to redirect */
495 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
497 smallint rd_type; /* (enum redir_type) */
498 /* note: for heredocs, rd_filename contains heredoc delimiter,
499 * and subsequently heredoc itself; and rd_dup is a bitmask:
500 * bit 0: do we need to trim leading tabs?
501 * bit 1: is heredoc quoted (<<'delim' syntax) ?
504 typedef enum redir_type {
506 REDIRECT_OVERWRITE = 1,
509 REDIRECT_HEREDOC = 4,
510 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
513 REDIRFD_SYNTAX_ERR = -2,
514 REDIRFD_TO_FILE = -1,
515 /* otherwise, rd_fd is redirected to rd_dup */
517 HEREDOC_SKIPTABS = 1,
523 pid_t pid; /* 0 if exited */
524 int assignment_cnt; /* how many argv[i] are assignments? */
525 smallint cmd_type; /* CMD_xxx */
527 #define CMD_SUBSHELL 1
528 #if ENABLE_HUSH_BASH_COMPAT
529 /* used for "[[ EXPR ]]" */
530 # define CMD_SINGLEWORD_NOGLOB 2
532 #if ENABLE_HUSH_FUNCTIONS
533 # define CMD_FUNCDEF 3
536 smalluint cmd_exitcode;
537 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
540 char *group_as_string;
542 #if ENABLE_HUSH_FUNCTIONS
543 struct function *child_func;
544 /* This field is used to prevent a bug here:
545 * while...do f1() {a;}; f1; f1() {b;}; f1; done
546 * When we execute "f1() {a;}" cmd, we create new function and clear
547 * cmd->group, cmd->group_as_string, cmd->argv[0].
548 * When we execute "f1() {b;}", we notice that f1 exists,
549 * and that its "parent cmd" struct is still "alive",
550 * we put those fields back into cmd->xxx
551 * (struct function has ->parent_cmd ptr to facilitate that).
552 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
553 * Without this trick, loop would execute a;b;b;b;...
554 * instead of correct sequence a;b;a;b;...
555 * When command is freed, it severs the link
556 * (sets ->child_func->parent_cmd to NULL).
559 char **argv; /* command name and arguments */
560 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
561 * and on execution these are substituted with their values.
562 * Substitution can make _several_ words out of one argv[n]!
563 * Example: argv[0]=='.^C*^C.' here: echo .$*.
564 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
566 struct redir_struct *redirects; /* I/O redirections */
568 /* Is there anything in this command at all? */
569 #define IS_NULL_CMD(cmd) \
570 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
574 int num_cmds; /* total number of commands in pipe */
575 int alive_cmds; /* number of commands running (not exited) */
576 int stopped_cmds; /* number of commands alive, but stopped */
578 int jobid; /* job number */
579 pid_t pgrp; /* process group ID for the job */
580 char *cmdtext; /* name of job */
582 struct command *cmds; /* array of commands in pipe */
583 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
584 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
585 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
587 typedef enum pipe_style {
593 /* Is there anything in this pipe at all? */
594 #define IS_NULL_PIPE(pi) \
595 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
597 /* This holds pointers to the various results of parsing */
598 struct parse_context {
599 /* linked list of pipes */
600 struct pipe *list_head;
601 /* last pipe (being constructed right now) */
603 /* last command in pipe (being constructed right now) */
604 struct command *command;
605 /* last redirect in command->redirects list */
606 struct redir_struct *pending_redirect;
612 smallint ctx_inverted; /* "! cmd | cmd" */
614 smallint ctx_dsemicolon; /* ";;" seen */
616 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
618 /* group we are enclosed in:
619 * example: "if pipe1; pipe2; then pipe3; fi"
620 * when we see "if" or "then", we malloc and copy current context,
621 * and make ->stack point to it. then we parse pipeN.
622 * when closing "then" / fi" / whatever is found,
623 * we move list_head into ->stack->command->group,
624 * copy ->stack into current context, and delete ->stack.
625 * (parsing of { list } and ( list ) doesn't use this method)
627 struct parse_context *stack;
631 /* On program start, environ points to initial environment.
632 * putenv adds new pointers into it, unsetenv removes them.
633 * Neither of these (de)allocates the strings.
634 * setenv allocates new strings in malloc space and does putenv,
635 * and thus setenv is unusable (leaky) for shell's purposes */
636 #define setenv(...) setenv_is_leaky_dont_use()
638 struct variable *next;
639 char *varstr; /* points to "name=" portion */
640 #if ENABLE_HUSH_LOCAL
641 unsigned func_nest_level;
643 int max_len; /* if > 0, name is part of initial env; else name is malloced */
644 smallint flg_export; /* putenv should be done on this var */
645 smallint flg_read_only;
653 #if ENABLE_HUSH_FUNCTIONS
655 struct function *next;
657 struct command *parent_cmd;
660 char *body_as_string;
666 /* set -/+o OPT support. (TODO: make it optional)
667 * bash supports the following opts:
678 * interactive-comments on
696 static const char o_opt_strings[] ALIGN1 =
699 #if ENABLE_HUSH_MODE_X
706 #if ENABLE_HUSH_MODE_X
713 /* "Globals" within this file */
714 /* Sorted roughly by size (smaller offsets == smaller code) */
716 /* interactive_fd != 0 means we are an interactive shell.
717 * If we are, then saved_tty_pgrp can also be != 0, meaning
718 * that controlling tty is available. With saved_tty_pgrp == 0,
719 * job control still works, but terminal signals
720 * (^C, ^Z, ^Y, ^\) won't work at all, and background
721 * process groups can only be created with "cmd &".
722 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
723 * to give tty to the foreground process group,
724 * and will take it back when the group is stopped (^Z)
727 #if ENABLE_HUSH_INTERACTIVE
728 /* 'interactive_fd' is a fd# open to ctty, if we have one
729 * _AND_ if we decided to act interactively */
733 # define G_interactive_fd (G.interactive_fd)
735 # define G_interactive_fd 0
737 #if ENABLE_FEATURE_EDITING
738 line_input_t *line_input_state;
743 #if ENABLE_HUSH_RANDOM_SUPPORT
749 pid_t saved_tty_pgrp;
750 struct pipe *job_list;
751 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
753 # define G_saved_tty_pgrp 0
755 char o_opt[NUM_OPT_O];
756 #if ENABLE_HUSH_MODE_X
757 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
761 smallint flag_SIGINT;
762 #if ENABLE_HUSH_LOOPS
763 smallint flag_break_continue;
765 #if ENABLE_HUSH_FUNCTIONS
766 /* 0: outside of a function (or sourced file)
767 * -1: inside of a function, ok to use return builtin
768 * 1: return is invoked, skip all till end of func
770 smallint flag_return_in_progress;
772 smallint exiting; /* used to prevent EXIT trap recursion */
773 /* These four support $?, $#, and $1 */
774 smalluint last_exitcode;
775 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
776 smalluint global_args_malloced;
777 /* how many non-NULL argv's we have. NB: $# + 1 */
781 char *argv0_for_re_execing;
783 #if ENABLE_HUSH_LOOPS
784 unsigned depth_break_continue;
785 unsigned depth_of_loop;
789 struct variable *top_var;
790 char **expanded_assignments;
791 #if ENABLE_HUSH_FUNCTIONS
792 struct function *top_func;
793 # if ENABLE_HUSH_LOCAL
794 struct variable **shadowed_vars_pp;
795 unsigned func_nest_level;
798 /* Signal and trap handling */
800 unsigned count_SIGCHLD;
801 unsigned handled_SIGCHLD;
802 smallint we_have_children;
804 /* Which signals have non-DFL handler (even with no traps set)?
805 * Set at the start to:
806 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
807 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
808 * The rest is cleared right before execv syscalls.
809 * Other than these two times, never modified.
811 unsigned special_sig_mask;
813 unsigned fatal_sig_mask;
814 # define G_fatal_sig_mask G.fatal_sig_mask
816 # define G_fatal_sig_mask 0
818 char **traps; /* char *traps[NSIG] */
819 sigset_t pending_set;
821 unsigned long memleak_value;
825 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
827 #define G (*ptr_to_globals)
828 /* Not #defining name to G.name - this quickly gets unwieldy
829 * (too many defines). Also, I actually prefer to see when a variable
830 * is global, thus "G." prefix is a useful hint */
831 #define INIT_G() do { \
832 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
833 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
834 sigfillset(&G.sa.sa_mask); \
835 G.sa.sa_flags = SA_RESTART; \
839 /* Function prototypes for builtins */
840 static int builtin_cd(char **argv) FAST_FUNC;
841 static int builtin_echo(char **argv) FAST_FUNC;
842 static int builtin_eval(char **argv) FAST_FUNC;
843 static int builtin_exec(char **argv) FAST_FUNC;
844 static int builtin_exit(char **argv) FAST_FUNC;
845 static int builtin_export(char **argv) FAST_FUNC;
847 static int builtin_fg_bg(char **argv) FAST_FUNC;
848 static int builtin_jobs(char **argv) FAST_FUNC;
851 static int builtin_help(char **argv) FAST_FUNC;
853 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
854 static int builtin_history(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),
925 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
926 BLTIN("history" , builtin_history , "Show command history"),
929 BLTIN("jobs" , builtin_jobs , "List jobs"),
931 #if ENABLE_HUSH_LOCAL
932 BLTIN("local" , builtin_local , "Set local variables"),
935 BLTIN("memleak" , builtin_memleak , NULL),
937 BLTIN("read" , builtin_read , "Input into variable"),
938 #if ENABLE_HUSH_FUNCTIONS
939 BLTIN("return" , builtin_return , "Return from a function"),
941 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
942 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
943 #if ENABLE_HUSH_BASH_COMPAT
944 BLTIN("source" , builtin_source , "Run commands in a file"),
946 BLTIN("trap" , builtin_trap , "Trap signals"),
947 BLTIN("type" , builtin_type , "Show command type"),
948 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
949 BLTIN("umask" , builtin_umask , "Set file creation mask"),
950 BLTIN("unset" , builtin_unset , "Unset variables"),
951 BLTIN("wait" , builtin_wait , "Wait for process"),
953 /* For now, echo and test are unconditionally enabled.
954 * Maybe make it configurable? */
955 static const struct built_in_command bltins2[] = {
956 BLTIN("[" , builtin_test , NULL),
957 BLTIN("echo" , builtin_echo , NULL),
959 BLTIN("printf" , builtin_printf , NULL),
961 BLTIN("pwd" , builtin_pwd , NULL),
962 BLTIN("test" , builtin_test , NULL),
969 /* prevent disasters with G.debug_indent < 0 */
970 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
971 # define debug_enter() (G.debug_indent++)
972 # define debug_leave() (G.debug_indent--)
974 # define indent() ((void)0)
975 # define debug_enter() ((void)0)
976 # define debug_leave() ((void)0)
980 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
983 #ifndef debug_printf_parse
984 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
987 #ifndef debug_printf_exec
988 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
991 #ifndef debug_printf_env
992 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
995 #ifndef debug_printf_jobs
996 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
997 # define DEBUG_JOBS 1
999 # define DEBUG_JOBS 0
1002 #ifndef debug_printf_expand
1003 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1004 # define DEBUG_EXPAND 1
1006 # define DEBUG_EXPAND 0
1009 #ifndef debug_printf_varexp
1010 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 #ifndef debug_printf_glob
1014 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1015 # define DEBUG_GLOB 1
1017 # define DEBUG_GLOB 0
1020 #ifndef debug_printf_list
1021 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1024 #ifndef debug_printf_subst
1025 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1028 #ifndef debug_printf_clean
1029 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1030 # define DEBUG_CLEAN 1
1032 # define DEBUG_CLEAN 0
1036 static void debug_print_strings(const char *prefix, char **vv)
1039 fdprintf(2, "%s:\n", prefix);
1041 fdprintf(2, " '%s'\n", *vv++);
1044 # define debug_print_strings(prefix, vv) ((void)0)
1048 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1051 static void *xxmalloc(int lineno, size_t size)
1053 void *ptr = xmalloc((size + 0xff) & ~0xff);
1054 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1057 static void *xxrealloc(int lineno, void *ptr, size_t size)
1059 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1060 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1063 static char *xxstrdup(int lineno, const char *str)
1065 char *ptr = xstrdup(str);
1066 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1069 static void xxfree(void *ptr)
1071 fdprintf(2, "free %p\n", ptr);
1074 # define xmalloc(s) xxmalloc(__LINE__, s)
1075 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1076 # define xstrdup(s) xxstrdup(__LINE__, s)
1077 # define free(p) xxfree(p)
1081 /* Syntax and runtime errors. They always abort scripts.
1082 * In interactive use they usually discard unparsed and/or unexecuted commands
1083 * and return to the prompt.
1084 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1087 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1088 # define syntax_error(lineno, msg) syntax_error(msg)
1089 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1090 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1091 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1092 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1095 static void die_if_script(unsigned lineno, const char *fmt, ...)
1100 bb_error_msg("hush.c:%u", lineno);
1103 bb_verror_msg(fmt, p, NULL);
1105 if (!G_interactive_fd)
1109 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1112 bb_error_msg("syntax error: %s", msg);
1114 bb_error_msg("syntax error");
1117 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1119 bb_error_msg("syntax error at '%s'", msg);
1122 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1124 bb_error_msg("syntax error: unterminated %s", s);
1127 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1129 char msg[2] = { ch, '\0' };
1130 syntax_error_unterm_str(lineno, msg);
1133 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1138 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1142 # undef die_if_script
1143 # undef syntax_error
1144 # undef syntax_error_at
1145 # undef syntax_error_unterm_ch
1146 # undef syntax_error_unterm_str
1147 # undef syntax_error_unexpected_ch
1149 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1150 # define syntax_error(msg) syntax_error(__LINE__, msg)
1151 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1152 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1153 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1154 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1158 #if ENABLE_HUSH_INTERACTIVE
1159 static void cmdedit_update_prompt(void);
1161 # define cmdedit_update_prompt() ((void)0)
1165 /* Utility functions
1167 /* Replace each \x with x in place, return ptr past NUL. */
1168 static char *unbackslash(char *src)
1170 char *dst = src = strchrnul(src, '\\');
1174 if ((*dst++ = *src++) == '\0')
1180 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1201 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1202 v[count1 + count2] = NULL;
1205 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1209 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1211 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1212 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1215 #define add_strings_to_strings(strings, add, need_to_dup) \
1216 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1219 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1220 static char **add_string_to_strings(char **strings, char *add)
1225 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1228 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1230 char **ptr = add_string_to_strings(strings, add);
1231 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1234 #define add_string_to_strings(strings, add) \
1235 xx_add_string_to_strings(__LINE__, strings, add)
1238 static void free_strings(char **strings)
1253 /* Helpers for setting new $n and restoring them back
1255 typedef struct save_arg_t {
1259 smallint sv_g_malloced;
1262 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1266 sv->sv_argv0 = argv[0];
1267 sv->sv_g_argv = G.global_argv;
1268 sv->sv_g_argc = G.global_argc;
1269 sv->sv_g_malloced = G.global_args_malloced;
1271 argv[0] = G.global_argv[0]; /* retain $0 */
1272 G.global_argv = argv;
1273 G.global_args_malloced = 0;
1281 static void restore_G_args(save_arg_t *sv, char **argv)
1285 if (G.global_args_malloced) {
1286 /* someone ran "set -- arg1 arg2 ...", undo */
1288 while (*++pp) /* note: does not free $0 */
1290 free(G.global_argv);
1292 argv[0] = sv->sv_argv0;
1293 G.global_argv = sv->sv_g_argv;
1294 G.global_argc = sv->sv_g_argc;
1295 G.global_args_malloced = sv->sv_g_malloced;
1299 /* Basic theory of signal handling in shell
1300 * ========================================
1301 * This does not describe what hush does, rather, it is current understanding
1302 * what it _should_ do. If it doesn't, it's a bug.
1303 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1305 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1306 * is finished or backgrounded. It is the same in interactive and
1307 * non-interactive shells, and is the same regardless of whether
1308 * a user trap handler is installed or a shell special one is in effect.
1309 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1310 * backgrounds (i.e. stops) or kills all members of currently running
1313 * Wait builtin in interruptible by signals for which user trap is set
1314 * or by SIGINT in interactive shell.
1316 * Trap handlers will execute even within trap handlers. (right?)
1318 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1319 * except for handlers set to '' (empty string).
1321 * If job control is off, backgrounded commands ("cmd &")
1322 * have SIGINT, SIGQUIT set to SIG_IGN.
1324 * Commands which are run in command substitution ("`cmd`")
1325 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1327 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1328 * by the shell from its parent.
1330 * Signals which differ from SIG_DFL action
1331 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1334 * SIGTERM (interactive): ignore
1335 * SIGHUP (interactive):
1336 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1337 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1338 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1339 * that all pipe members are stopped. Try this in bash:
1340 * while :; do :; done - ^Z does not background it
1341 * (while :; do :; done) - ^Z backgrounds it
1342 * SIGINT (interactive): wait for last pipe, ignore the rest
1343 * of the command line, show prompt. NB: ^C does not send SIGINT
1344 * to interactive shell while shell is waiting for a pipe,
1345 * since shell is bg'ed (is not in foreground process group).
1346 * Example 1: this waits 5 sec, but does not execute ls:
1347 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1348 * Example 2: this does not wait and does not execute ls:
1349 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1350 * Example 3: this does not wait 5 sec, but executes ls:
1351 * "sleep 5; ls -l" + press ^C
1352 * Example 4: this does not wait and does not execute ls:
1353 * "sleep 5 & wait; ls -l" + press ^C
1355 * (What happens to signals which are IGN on shell start?)
1356 * (What happens with signal mask on shell start?)
1358 * Old implementation
1359 * ==================
1360 * We use in-kernel pending signal mask to determine which signals were sent.
1361 * We block all signals which we don't want to take action immediately,
1362 * i.e. we block all signals which need to have special handling as described
1363 * above, and all signals which have traps set.
1364 * After each pipe execution, we extract any pending signals via sigtimedwait()
1367 * unsigned special_sig_mask: a mask of such "special" signals
1368 * sigset_t blocked_set: current blocked signal set
1371 * clear bit in blocked_set unless it is also in special_sig_mask
1372 * "trap 'cmd' SIGxxx":
1373 * set bit in blocked_set (even if 'cmd' is '')
1374 * after [v]fork, if we plan to be a shell:
1375 * unblock signals with special interactive handling
1376 * (child shell is not interactive),
1377 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1378 * after [v]fork, if we plan to exec:
1379 * POSIX says fork clears pending signal mask in child - no need to clear it.
1380 * Restore blocked signal set to one inherited by shell just prior to exec.
1382 * Note: as a result, we do not use signal handlers much. The only uses
1383 * are to count SIGCHLDs
1384 * and to restore tty pgrp on signal-induced exit.
1387 * Standard says "When a subshell is entered, traps that are not being ignored
1388 * are set to the default actions". bash interprets it so that traps which
1389 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1391 * Problem: the above approach makes it unwieldy to catch signals while
1392 * we are in read builtin, of while we read commands from stdin:
1393 * masked signals are not visible!
1395 * New implementation
1396 * ==================
1397 * We record each signal we are interested in by installing signal handler
1398 * for them - a bit like emulating kernel pending signal mask in userspace.
1399 * We are interested in: signals which need to have special handling
1400 * as described above, and all signals which have traps set.
1401 * Signals are rocorded in pending_set.
1402 * After each pipe execution, we extract any pending signals
1405 * unsigned special_sig_mask: a mask of shell-special signals.
1406 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1407 * char *traps[sig] if trap for sig is set (even if it's '').
1408 * sigset_t pending_set: set of sigs we received.
1411 * if sig is in special_sig_mask, set handler back to:
1412 * record_pending_signo, or to IGN if it's a tty stop signal
1413 * if sig is in fatal_sig_mask, set handler back to sigexit.
1414 * else: set handler back to SIG_DFL
1415 * "trap 'cmd' SIGxxx":
1416 * set handler to record_pending_signo.
1418 * set handler to SIG_IGN.
1419 * after [v]fork, if we plan to be a shell:
1420 * set signals with special interactive handling to SIG_DFL
1421 * (because child shell is not interactive),
1422 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1423 * after [v]fork, if we plan to exec:
1424 * POSIX says fork clears pending signal mask in child - no need to clear it.
1426 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1427 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1430 * Standard says "When a subshell is entered, traps that are not being ignored
1431 * are set to the default actions". bash interprets it so that traps which
1432 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1435 SPECIAL_INTERACTIVE_SIGS = 0
1440 SPECIAL_JOBSTOP_SIGS = 0
1449 static void record_pending_signo(int sig)
1451 sigaddset(&G.pending_set, sig);
1452 #if ENABLE_HUSH_FAST
1453 if (sig == SIGCHLD) {
1455 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1460 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1462 struct sigaction old_sa;
1464 /* We could use signal() to install handlers... almost:
1465 * except that we need to mask ALL signals while handlers run.
1466 * I saw signal nesting in strace, race window isn't small.
1467 * SA_RESTART is also needed, but in Linux, signal()
1468 * sets SA_RESTART too.
1470 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1471 /* sigfillset(&G.sa.sa_mask); - already done */
1472 /* G.sa.sa_flags = SA_RESTART; - already done */
1473 G.sa.sa_handler = handler;
1474 sigaction(sig, &G.sa, &old_sa);
1475 return old_sa.sa_handler;
1480 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1481 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1482 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1483 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1485 /* Restores tty foreground process group, and exits.
1486 * May be called as signal handler for fatal signal
1487 * (will resend signal to itself, producing correct exit state)
1488 * or called directly with -EXITCODE.
1489 * We also call it if xfunc is exiting. */
1490 static void sigexit(int sig) NORETURN;
1491 static void sigexit(int sig)
1493 /* Careful: we can end up here after [v]fork. Do not restore
1494 * tty pgrp then, only top-level shell process does that */
1495 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1496 /* Disable all signals: job control, SIGPIPE, etc.
1497 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1499 sigprocmask_allsigs(SIG_BLOCK);
1500 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1503 /* Not a signal, just exit */
1507 kill_myself_with_sig(sig); /* does not return */
1511 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1512 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1516 static sighandler_t pick_sighandler(unsigned sig)
1518 sighandler_t handler = SIG_DFL;
1519 if (sig < sizeof(unsigned)*8) {
1520 unsigned sigmask = (1 << sig);
1524 if (G_fatal_sig_mask & sigmask)
1528 /* sig has special handling? */
1529 if (G.special_sig_mask & sigmask) {
1530 handler = record_pending_signo;
1531 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1532 * in order to ignore them: they will be raised
1533 * in an endless loop when we try to do some
1534 * terminal ioctls! We do have to _ignore_ these.
1536 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1543 /* Restores tty foreground process group, and exits. */
1544 static void hush_exit(int exitcode) NORETURN;
1545 static void hush_exit(int exitcode)
1547 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1548 save_history(G.line_input_state);
1552 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1554 /* argv[0] is unused */
1555 argv[1] = G.traps[0];
1557 G.exiting = 1; /* prevent EXIT trap recursion */
1558 /* Note: G.traps[0] is not cleared!
1559 * "trap" will still show it, if executed
1564 #if ENABLE_FEATURE_CLEAN_UP
1566 struct variable *cur_var;
1567 if (G.cwd != bb_msg_unknown)
1569 cur_var = G.top_var;
1571 struct variable *tmp = cur_var;
1572 if (!cur_var->max_len)
1573 free(cur_var->varstr);
1574 cur_var = cur_var->next;
1582 sigexit(- (exitcode & 0xff));
1589 //TODO: return a mask of ALL handled sigs?
1590 static int check_and_run_traps(void)
1597 if (sigisemptyset(&G.pending_set))
1602 if (sigismember(&G.pending_set, sig)) {
1603 sigdelset(&G.pending_set, sig);
1606 } while (sig < NSIG);
1609 if (G.traps && G.traps[sig]) {
1610 if (G.traps[sig][0]) {
1611 /* We have user-defined handler */
1612 smalluint save_rcode;
1614 /* argv[0] is unused */
1615 argv[1] = G.traps[sig];
1617 save_rcode = G.last_exitcode;
1619 G.last_exitcode = save_rcode;
1621 } /* else: "" trap, ignoring signal */
1624 /* not a trap: special action */
1627 /* Builtin was ^C'ed, make it look prettier: */
1635 /* bash is observed to signal whole process groups,
1636 * not individual processes */
1637 for (job = G.job_list; job; job = job->next) {
1640 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1641 if (kill(- job->pgrp, SIGHUP) == 0)
1642 kill(- job->pgrp, SIGCONT);
1647 #if ENABLE_HUSH_FAST
1650 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1652 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1653 * This simplifies wait builtin a bit.
1657 default: /* ignored: */
1658 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1660 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1661 * Example: wait is not interrupted by TERM
1662 * in interactive shell, because TERM is ignored.
1671 static const char *get_cwd(int force)
1673 if (force || G.cwd == NULL) {
1674 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1675 * we must not try to free(bb_msg_unknown) */
1676 if (G.cwd == bb_msg_unknown)
1678 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1680 G.cwd = bb_msg_unknown;
1687 * Shell and environment variable support
1689 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1691 struct variable **pp;
1692 struct variable *cur;
1695 while ((cur = *pp) != NULL) {
1696 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1703 static const char* FAST_FUNC get_local_var_value(const char *name)
1705 struct variable **vpp;
1706 unsigned len = strlen(name);
1708 if (G.expanded_assignments) {
1709 char **cpp = G.expanded_assignments;
1712 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1713 return cp + len + 1;
1718 vpp = get_ptr_to_local_var(name, len);
1720 return (*vpp)->varstr + len + 1;
1722 if (strcmp(name, "PPID") == 0)
1723 return utoa(G.root_ppid);
1724 // bash compat: UID? EUID?
1725 #if ENABLE_HUSH_RANDOM_SUPPORT
1726 if (strcmp(name, "RANDOM") == 0)
1727 return utoa(next_random(&G.random_gen));
1732 /* str holds "NAME=VAL" and is expected to be malloced.
1733 * We take ownership of it.
1735 * 0: do not change export flag
1736 * (if creating new variable, flag will be 0)
1737 * 1: set export flag and putenv the variable
1738 * -1: clear export flag and unsetenv the variable
1739 * flg_read_only is set only when we handle -R var=val
1741 #if !BB_MMU && ENABLE_HUSH_LOCAL
1742 /* all params are used */
1743 #elif BB_MMU && ENABLE_HUSH_LOCAL
1744 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1745 set_local_var(str, flg_export, local_lvl)
1746 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1747 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1748 set_local_var(str, flg_export)
1749 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1750 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1751 set_local_var(str, flg_export, flg_read_only)
1753 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1755 struct variable **var_pp;
1756 struct variable *cur;
1760 eq_sign = strchr(str, '=');
1761 if (!eq_sign) { /* not expected to ever happen? */
1766 name_len = eq_sign - str + 1; /* including '=' */
1767 var_pp = &G.top_var;
1768 while ((cur = *var_pp) != NULL) {
1769 if (strncmp(cur->varstr, str, name_len) != 0) {
1770 var_pp = &cur->next;
1773 /* We found an existing var with this name */
1774 if (cur->flg_read_only) {
1778 bb_error_msg("%s: readonly variable", str);
1782 if (flg_export == -1) { // "&& cur->flg_export" ?
1783 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1788 #if ENABLE_HUSH_LOCAL
1789 if (cur->func_nest_level < local_lvl) {
1790 /* New variable is declared as local,
1791 * and existing one is global, or local
1792 * from enclosing function.
1793 * Remove and save old one: */
1794 *var_pp = cur->next;
1795 cur->next = *G.shadowed_vars_pp;
1796 *G.shadowed_vars_pp = cur;
1797 /* bash 3.2.33(1) and exported vars:
1799 * # f() { local z=a; env | grep ^z; }
1805 if (cur->flg_export)
1810 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1815 if (cur->max_len != 0) {
1816 if (cur->max_len >= strlen(str)) {
1817 /* This one is from startup env, reuse space */
1818 strcpy(cur->varstr, str);
1822 /* max_len == 0 signifies "malloced" var, which we can
1823 * (and has to) free */
1827 goto set_str_and_exp;
1830 /* Not found - create new variable struct */
1831 cur = xzalloc(sizeof(*cur));
1832 #if ENABLE_HUSH_LOCAL
1833 cur->func_nest_level = local_lvl;
1835 cur->next = *var_pp;
1841 cur->flg_read_only = flg_read_only;
1844 if (flg_export == 1)
1845 cur->flg_export = 1;
1846 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1847 cmdedit_update_prompt();
1848 if (cur->flg_export) {
1849 if (flg_export == -1) {
1850 cur->flg_export = 0;
1851 /* unsetenv was already done */
1853 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1854 return putenv(cur->varstr);
1860 /* Used at startup and after each cd */
1861 static void set_pwd_var(int exp)
1863 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1864 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1867 static int unset_local_var_len(const char *name, int name_len)
1869 struct variable *cur;
1870 struct variable **var_pp;
1873 return EXIT_SUCCESS;
1874 var_pp = &G.top_var;
1875 while ((cur = *var_pp) != NULL) {
1876 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1877 if (cur->flg_read_only) {
1878 bb_error_msg("%s: readonly variable", name);
1879 return EXIT_FAILURE;
1881 *var_pp = cur->next;
1882 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1883 bb_unsetenv(cur->varstr);
1884 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1885 cmdedit_update_prompt();
1889 return EXIT_SUCCESS;
1891 var_pp = &cur->next;
1893 return EXIT_SUCCESS;
1896 static int unset_local_var(const char *name)
1898 return unset_local_var_len(name, strlen(name));
1901 static void unset_vars(char **strings)
1909 const char *eq = strchrnul(*v, '=');
1910 unset_local_var_len(*v, (int)(eq - *v));
1916 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1918 char *var = xasprintf("%s=%s", name, val);
1919 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1924 * Helpers for "var1=val1 var2=val2 cmd" feature
1926 static void add_vars(struct variable *var)
1928 struct variable *next;
1932 var->next = G.top_var;
1934 if (var->flg_export) {
1935 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1936 putenv(var->varstr);
1938 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1944 static struct variable *set_vars_and_save_old(char **strings)
1947 struct variable *old = NULL;
1953 struct variable *var_p;
1954 struct variable **var_pp;
1957 eq = strchr(*s, '=');
1959 var_pp = get_ptr_to_local_var(*s, eq - *s);
1961 /* Remove variable from global linked list */
1963 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1964 *var_pp = var_p->next;
1965 /* Add it to returned list */
1969 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1980 static int FAST_FUNC static_get(struct in_str *i)
1991 static int FAST_FUNC static_peek(struct in_str *i)
1996 #if ENABLE_HUSH_INTERACTIVE
1998 static void cmdedit_update_prompt(void)
2000 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2001 G.PS1 = get_local_var_value("PS1");
2004 G.PS2 = get_local_var_value("PS2");
2012 static const char *setup_prompt_string(int promptmode)
2014 const char *prompt_str;
2015 debug_printf("setup_prompt_string %d ", promptmode);
2016 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2017 /* Set up the prompt */
2018 if (promptmode == 0) { /* PS1 */
2020 /* bash uses $PWD value, even if it is set by user.
2021 * It uses current dir only if PWD is unset.
2022 * We always use current dir. */
2023 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2028 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2029 debug_printf("result '%s'\n", prompt_str);
2033 static void get_user_input(struct in_str *i)
2036 const char *prompt_str;
2038 prompt_str = setup_prompt_string(i->promptmode);
2039 # if ENABLE_FEATURE_EDITING
2040 /* Enable command line editing only while a command line
2041 * is actually being read */
2043 /* Unicode support should be activated even if LANG is set
2044 * _during_ shell execution, not only if it was set when
2045 * shell was started. Therefore, re-check LANG every time:
2047 reinit_unicode(get_local_var_value("LANG"));
2050 /* buglet: SIGINT will not make new prompt to appear _at once_,
2051 * only after <Enter>. (^C will work) */
2052 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2053 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2054 check_and_run_traps();
2055 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2056 i->eof_flag = (r < 0);
2057 if (i->eof_flag) { /* EOF/error detected */
2058 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2059 G.user_input_buf[1] = '\0';
2064 if (i->last_char == '\0' || i->last_char == '\n') {
2065 /* Why check_and_run_traps here? Try this interactively:
2066 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2067 * $ <[enter], repeatedly...>
2068 * Without check_and_run_traps, handler never runs.
2070 check_and_run_traps();
2071 fputs(prompt_str, stdout);
2074 G.user_input_buf[0] = r = fgetc(i->file);
2075 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2076 } while (G.flag_SIGINT);
2077 i->eof_flag = (r == EOF);
2079 i->p = G.user_input_buf;
2082 #endif /* INTERACTIVE */
2084 /* This is the magic location that prints prompts
2085 * and gets data back from the user */
2086 static int FAST_FUNC file_get(struct in_str *i)
2090 /* If there is data waiting, eat it up */
2091 if (i->p && *i->p) {
2092 #if ENABLE_HUSH_INTERACTIVE
2096 if (i->eof_flag && !*i->p)
2098 /* note: ch is never NUL */
2100 /* need to double check i->file because we might be doing something
2101 * more complicated by now, like sourcing or substituting. */
2102 #if ENABLE_HUSH_INTERACTIVE
2103 if (G_interactive_fd && i->file == stdin) {
2106 } while (!*i->p); /* need non-empty line */
2107 i->promptmode = 1; /* PS2 */
2111 do ch = fgetc(i->file); while (ch == '\0');
2113 debug_printf("file_get: got '%c' %d\n", ch, ch);
2118 /* All callers guarantee this routine will never
2119 * be used right after a newline, so prompting is not needed.
2121 static int FAST_FUNC file_peek(struct in_str *i)
2124 if (i->p && *i->p) {
2125 if (i->eof_flag && !i->p[1])
2128 /* note: ch is never NUL */
2130 do ch = fgetc(i->file); while (ch == '\0');
2131 i->eof_flag = (ch == EOF);
2132 i->peek_buf[0] = ch;
2133 i->peek_buf[1] = '\0';
2135 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2139 static void setup_file_in_str(struct in_str *i, FILE *f)
2141 memset(i, 0, sizeof(*i));
2142 i->peek = file_peek;
2144 /* i->promptmode = 0; - PS1 (memset did it) */
2149 static void setup_string_in_str(struct in_str *i, const char *s)
2151 memset(i, 0, sizeof(*i));
2152 i->peek = static_peek;
2153 i->get = static_get;
2154 /* i->promptmode = 0; - PS1 (memset did it) */
2156 /* i->eof_flag = 0; */
2163 #define B_CHUNK (32 * sizeof(char*))
2165 static void o_reset_to_empty_unquoted(o_string *o)
2168 o->has_quoted_part = 0;
2173 static void o_free(o_string *o)
2176 memset(o, 0, sizeof(*o));
2179 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2184 static void o_grow_by(o_string *o, int len)
2186 if (o->length + len > o->maxlen) {
2187 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2188 o->data = xrealloc(o->data, 1 + o->maxlen);
2192 static void o_addchr(o_string *o, int ch)
2194 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2196 o->data[o->length] = ch;
2198 o->data[o->length] = '\0';
2201 static void o_addblock(o_string *o, const char *str, int len)
2204 memcpy(&o->data[o->length], str, len);
2206 o->data[o->length] = '\0';
2209 static void o_addstr(o_string *o, const char *str)
2211 o_addblock(o, str, strlen(str));
2215 static void nommu_addchr(o_string *o, int ch)
2221 # define nommu_addchr(o, str) ((void)0)
2224 static void o_addstr_with_NUL(o_string *o, const char *str)
2226 o_addblock(o, str, strlen(str) + 1);
2230 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2231 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2232 * Apparently, on unquoted $v bash still does globbing
2233 * ("v='*.txt'; echo $v" prints all .txt files),
2234 * but NOT brace expansion! Thus, there should be TWO independent
2235 * quoting mechanisms on $v expansion side: one protects
2236 * $v from brace expansion, and other additionally protects "$v" against globbing.
2237 * We have only second one.
2240 #if ENABLE_HUSH_BRACE_EXPANSION
2241 # define MAYBE_BRACES "{}"
2243 # define MAYBE_BRACES ""
2246 /* My analysis of quoting semantics tells me that state information
2247 * is associated with a destination, not a source.
2249 static void o_addqchr(o_string *o, int ch)
2252 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2257 o->data[o->length] = '\\';
2260 o->data[o->length] = ch;
2262 o->data[o->length] = '\0';
2265 static void o_addQchr(o_string *o, int ch)
2268 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2269 && strchr("*?[\\" MAYBE_BRACES, ch)
2272 o->data[o->length] = '\\';
2276 o->data[o->length] = ch;
2278 o->data[o->length] = '\0';
2281 static void o_addqblock(o_string *o, const char *str, int len)
2286 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2287 if (ordinary_cnt > len) /* paranoia */
2289 o_addblock(o, str, ordinary_cnt);
2290 if (ordinary_cnt == len)
2291 return; /* NUL is already added by o_addblock */
2292 str += ordinary_cnt;
2293 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2297 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2299 o->data[o->length] = '\\';
2303 o->data[o->length] = ch;
2306 o->data[o->length] = '\0';
2309 static void o_addQblock(o_string *o, const char *str, int len)
2311 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2312 o_addblock(o, str, len);
2315 o_addqblock(o, str, len);
2318 static void o_addQstr(o_string *o, const char *str)
2320 o_addQblock(o, str, strlen(str));
2323 /* A special kind of o_string for $VAR and `cmd` expansion.
2324 * It contains char* list[] at the beginning, which is grown in 16 element
2325 * increments. Actual string data starts at the next multiple of 16 * (char*).
2326 * list[i] contains an INDEX (int!) into this string data.
2327 * It means that if list[] needs to grow, data needs to be moved higher up
2328 * but list[i]'s need not be modified.
2329 * NB: remembering how many list[i]'s you have there is crucial.
2330 * o_finalize_list() operation post-processes this structure - calculates
2331 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2333 #if DEBUG_EXPAND || DEBUG_GLOB
2334 static void debug_print_list(const char *prefix, o_string *o, int n)
2336 char **list = (char**)o->data;
2337 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2341 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2342 prefix, list, n, string_start, o->length, o->maxlen,
2343 !!(o->o_expflags & EXP_FLAG_GLOB),
2345 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2348 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2349 o->data + (int)(uintptr_t)list[i] + string_start,
2350 o->data + (int)(uintptr_t)list[i] + string_start);
2354 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2356 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2360 # define debug_print_list(prefix, o, n) ((void)0)
2363 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2364 * in list[n] so that it points past last stored byte so far.
2365 * It returns n+1. */
2366 static int o_save_ptr_helper(o_string *o, int n)
2368 char **list = (char**)o->data;
2372 if (!o->has_empty_slot) {
2373 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2374 string_len = o->length - string_start;
2375 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2376 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2377 /* list[n] points to string_start, make space for 16 more pointers */
2378 o->maxlen += 0x10 * sizeof(list[0]);
2379 o->data = xrealloc(o->data, o->maxlen + 1);
2380 list = (char**)o->data;
2381 memmove(list + n + 0x10, list + n, string_len);
2382 o->length += 0x10 * sizeof(list[0]);
2384 debug_printf_list("list[%d]=%d string_start=%d\n",
2385 n, string_len, string_start);
2388 /* We have empty slot at list[n], reuse without growth */
2389 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2390 string_len = o->length - string_start;
2391 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2392 n, string_len, string_start);
2393 o->has_empty_slot = 0;
2395 o->has_quoted_part = 0;
2396 list[n] = (char*)(uintptr_t)string_len;
2400 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2401 static int o_get_last_ptr(o_string *o, int n)
2403 char **list = (char**)o->data;
2404 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2406 return ((int)(uintptr_t)list[n-1]) + string_start;
2409 #if ENABLE_HUSH_BRACE_EXPANSION
2410 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2411 * first, it processes even {a} (no commas), second,
2412 * I didn't manage to make it return strings when they don't match
2413 * existing files. Need to re-implement it.
2417 static int glob_needed(const char *s)
2426 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2432 /* Return pointer to next closing brace or to comma */
2433 static const char *next_brace_sub(const char *cp)
2437 while (*cp != '\0') {
2444 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2450 return *cp != '\0' ? cp : NULL;
2452 /* Recursive brace globber. Note: may garble pattern[]. */
2453 static int glob_brace(char *pattern, o_string *o, int n)
2455 char *new_pattern_buf;
2462 debug_printf_glob("glob_brace('%s')\n", pattern);
2468 if (*begin == '{') {
2469 /* Find the first sub-pattern and at the same time
2470 * find the rest after the closing brace */
2471 next = next_brace_sub(begin);
2473 /* An illegal expression */
2477 /* "{abc}" with no commas - illegal
2478 * brace expr, disregard and skip it */
2484 if (*begin == '\\' && begin[1] != '\0')
2488 debug_printf_glob("begin:%s\n", begin);
2489 debug_printf_glob("next:%s\n", next);
2491 /* Now find the end of the whole brace expression */
2493 while (*rest != '}') {
2494 rest = next_brace_sub(rest);
2496 /* An illegal expression */
2499 debug_printf_glob("rest:%s\n", rest);
2501 rest_len = strlen(++rest) + 1;
2503 /* We are sure the brace expression is well-formed */
2505 /* Allocate working buffer large enough for our work */
2506 new_pattern_buf = xmalloc(strlen(pattern));
2508 /* We have a brace expression. BEGIN points to the opening {,
2509 * NEXT points past the terminator of the first element, and REST
2510 * points past the final }. We will accumulate result names from
2511 * recursive runs for each brace alternative in the buffer using
2516 /* Construct the new glob expression */
2519 mempcpy(new_pattern_buf,
2520 /* We know the prefix for all sub-patterns */
2521 pattern, begin - pattern),
2525 /* Note: glob_brace() may garble new_pattern_buf[].
2526 * That's why we re-copy prefix every time (1st memcpy above).
2528 n = glob_brace(new_pattern_buf, o, n);
2530 /* We saw the last entry */
2534 next = next_brace_sub(next);
2536 free(new_pattern_buf);
2544 memset(&globdata, 0, sizeof(globdata));
2545 gr = glob(pattern, 0, NULL, &globdata);
2546 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2548 if (gr == GLOB_NOMATCH) {
2549 globfree(&globdata);
2550 /* NB: garbles parameter */
2551 unbackslash(pattern);
2552 o_addstr_with_NUL(o, pattern);
2553 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2554 return o_save_ptr_helper(o, n);
2556 if (gr == GLOB_NOSPACE)
2557 bb_error_msg_and_die(bb_msg_memory_exhausted);
2558 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2559 * but we didn't specify it. Paranoia again. */
2560 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2562 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2563 char **argv = globdata.gl_pathv;
2565 o_addstr_with_NUL(o, *argv);
2566 n = o_save_ptr_helper(o, n);
2572 globfree(&globdata);
2576 /* Performs globbing on last list[],
2577 * saving each result as a new list[].
2579 static int perform_glob(o_string *o, int n)
2581 char *pattern, *copy;
2583 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2585 return o_save_ptr_helper(o, n);
2586 pattern = o->data + o_get_last_ptr(o, n);
2587 debug_printf_glob("glob pattern '%s'\n", pattern);
2588 if (!glob_needed(pattern)) {
2589 /* unbackslash last string in o in place, fix length */
2590 o->length = unbackslash(pattern) - o->data;
2591 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2592 return o_save_ptr_helper(o, n);
2595 copy = xstrdup(pattern);
2596 /* "forget" pattern in o */
2597 o->length = pattern - o->data;
2598 n = glob_brace(copy, o, n);
2601 debug_print_list("perform_glob returning", o, n);
2605 #else /* !HUSH_BRACE_EXPANSION */
2608 static int glob_needed(const char *s)
2617 if (*s == '*' || *s == '[' || *s == '?')
2623 /* Performs globbing on last list[],
2624 * saving each result as a new list[].
2626 static int perform_glob(o_string *o, int n)
2632 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2634 return o_save_ptr_helper(o, n);
2635 pattern = o->data + o_get_last_ptr(o, n);
2636 debug_printf_glob("glob pattern '%s'\n", pattern);
2637 if (!glob_needed(pattern)) {
2639 /* unbackslash last string in o in place, fix length */
2640 o->length = unbackslash(pattern) - o->data;
2641 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2642 return o_save_ptr_helper(o, n);
2645 memset(&globdata, 0, sizeof(globdata));
2646 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2647 * If we glob "*.\*" and don't find anything, we need
2648 * to fall back to using literal "*.*", but GLOB_NOCHECK
2649 * will return "*.\*"!
2651 gr = glob(pattern, 0, NULL, &globdata);
2652 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2654 if (gr == GLOB_NOMATCH) {
2655 globfree(&globdata);
2658 if (gr == GLOB_NOSPACE)
2659 bb_error_msg_and_die(bb_msg_memory_exhausted);
2660 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2661 * but we didn't specify it. Paranoia again. */
2662 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2664 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2665 char **argv = globdata.gl_pathv;
2666 /* "forget" pattern in o */
2667 o->length = pattern - o->data;
2669 o_addstr_with_NUL(o, *argv);
2670 n = o_save_ptr_helper(o, n);
2676 globfree(&globdata);
2678 debug_print_list("perform_glob returning", o, n);
2682 #endif /* !HUSH_BRACE_EXPANSION */
2684 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2685 * Otherwise, just finish current list[] and start new */
2686 static int o_save_ptr(o_string *o, int n)
2688 if (o->o_expflags & EXP_FLAG_GLOB) {
2689 /* If o->has_empty_slot, list[n] was already globbed
2690 * (if it was requested back then when it was filled)
2691 * so don't do that again! */
2692 if (!o->has_empty_slot)
2693 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2695 return o_save_ptr_helper(o, n);
2698 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2699 static char **o_finalize_list(o_string *o, int n)
2704 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2706 debug_print_list("finalized", o, n);
2707 debug_printf_expand("finalized n:%d\n", n);
2708 list = (char**)o->data;
2709 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2713 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2718 static void free_pipe_list(struct pipe *pi);
2720 /* Returns pi->next - next pipe in the list */
2721 static struct pipe *free_pipe(struct pipe *pi)
2726 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2727 for (i = 0; i < pi->num_cmds; i++) {
2728 struct command *command;
2729 struct redir_struct *r, *rnext;
2731 command = &pi->cmds[i];
2732 debug_printf_clean(" command %d:\n", i);
2733 if (command->argv) {
2737 for (a = 0, p = command->argv; *p; a++, p++) {
2738 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2741 free_strings(command->argv);
2742 //command->argv = NULL;
2744 /* not "else if": on syntax error, we may have both! */
2745 if (command->group) {
2746 debug_printf_clean(" begin group (cmd_type:%d)\n",
2748 free_pipe_list(command->group);
2749 debug_printf_clean(" end group\n");
2750 //command->group = NULL;
2752 /* else is crucial here.
2753 * If group != NULL, child_func is meaningless */
2754 #if ENABLE_HUSH_FUNCTIONS
2755 else if (command->child_func) {
2756 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2757 command->child_func->parent_cmd = NULL;
2761 free(command->group_as_string);
2762 //command->group_as_string = NULL;
2764 for (r = command->redirects; r; r = rnext) {
2765 debug_printf_clean(" redirect %d%s",
2766 r->rd_fd, redir_table[r->rd_type].descrip);
2767 /* guard against the case >$FOO, where foo is unset or blank */
2768 if (r->rd_filename) {
2769 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2770 free(r->rd_filename);
2771 //r->rd_filename = NULL;
2773 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2777 //command->redirects = NULL;
2779 free(pi->cmds); /* children are an array, they get freed all at once */
2783 //pi->cmdtext = NULL;
2791 static void free_pipe_list(struct pipe *pi)
2795 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2797 debug_printf_clean("pipe followup code %d\n", pi->followup);
2803 /*** Parsing routines ***/
2805 #ifndef debug_print_tree
2806 static void debug_print_tree(struct pipe *pi, int lvl)
2808 static const char *const PIPE[] = {
2814 static const char *RES[] = {
2815 [RES_NONE ] = "NONE" ,
2818 [RES_THEN ] = "THEN" ,
2819 [RES_ELIF ] = "ELIF" ,
2820 [RES_ELSE ] = "ELSE" ,
2823 # if ENABLE_HUSH_LOOPS
2824 [RES_FOR ] = "FOR" ,
2825 [RES_WHILE] = "WHILE",
2826 [RES_UNTIL] = "UNTIL",
2828 [RES_DONE ] = "DONE" ,
2830 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2833 # if ENABLE_HUSH_CASE
2834 [RES_CASE ] = "CASE" ,
2835 [RES_CASE_IN ] = "CASE_IN" ,
2836 [RES_MATCH] = "MATCH",
2837 [RES_CASE_BODY] = "CASE_BODY",
2838 [RES_ESAC ] = "ESAC" ,
2840 [RES_XXXX ] = "XXXX" ,
2841 [RES_SNTX ] = "SNTX" ,
2843 static const char *const CMDTYPE[] = {
2847 # if ENABLE_HUSH_FUNCTIONS
2856 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2857 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2859 while (prn < pi->num_cmds) {
2860 struct command *command = &pi->cmds[prn];
2861 char **argv = command->argv;
2863 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2865 command->assignment_cnt);
2866 if (command->group) {
2867 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2868 CMDTYPE[command->cmd_type],
2871 , " group_as_string:", command->group_as_string
2876 debug_print_tree(command->group, lvl+1);
2880 if (argv) while (*argv) {
2881 fdprintf(2, " '%s'", *argv);
2891 #endif /* debug_print_tree */
2893 static struct pipe *new_pipe(void)
2896 pi = xzalloc(sizeof(struct pipe));
2897 /*pi->followup = 0; - deliberately invalid value */
2898 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2902 /* Command (member of a pipe) is complete, or we start a new pipe
2903 * if ctx->command is NULL.
2904 * No errors possible here.
2906 static int done_command(struct parse_context *ctx)
2908 /* The command is really already in the pipe structure, so
2909 * advance the pipe counter and make a new, null command. */
2910 struct pipe *pi = ctx->pipe;
2911 struct command *command = ctx->command;
2914 if (IS_NULL_CMD(command)) {
2915 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2919 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2920 //debug_print_tree(ctx->list_head, 20);
2922 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2925 /* Only real trickiness here is that the uncommitted
2926 * command structure is not counted in pi->num_cmds. */
2927 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2928 ctx->command = command = &pi->cmds[pi->num_cmds];
2930 memset(command, 0, sizeof(*command));
2931 return pi->num_cmds; /* used only for 0/nonzero check */
2934 static void done_pipe(struct parse_context *ctx, pipe_style type)
2938 debug_printf_parse("done_pipe entered, followup %d\n", type);
2939 /* Close previous command */
2940 not_null = done_command(ctx);
2941 ctx->pipe->followup = type;
2943 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2944 ctx->ctx_inverted = 0;
2945 ctx->pipe->res_word = ctx->ctx_res_w;
2948 /* Without this check, even just <enter> on command line generates
2949 * tree of three NOPs (!). Which is harmless but annoying.
2950 * IOW: it is safe to do it unconditionally. */
2953 || ctx->ctx_res_w == RES_FI
2955 #if ENABLE_HUSH_LOOPS
2956 || ctx->ctx_res_w == RES_DONE
2957 || ctx->ctx_res_w == RES_FOR
2958 || ctx->ctx_res_w == RES_IN
2960 #if ENABLE_HUSH_CASE
2961 || ctx->ctx_res_w == RES_ESAC
2965 debug_printf_parse("done_pipe: adding new pipe: "
2966 "not_null:%d ctx->ctx_res_w:%d\n",
2967 not_null, ctx->ctx_res_w);
2969 ctx->pipe->next = new_p;
2971 /* RES_THEN, RES_DO etc are "sticky" -
2972 * they remain set for pipes inside if/while.
2973 * This is used to control execution.
2974 * RES_FOR and RES_IN are NOT sticky (needed to support
2975 * cases where variable or value happens to match a keyword):
2977 #if ENABLE_HUSH_LOOPS
2978 if (ctx->ctx_res_w == RES_FOR
2979 || ctx->ctx_res_w == RES_IN)
2980 ctx->ctx_res_w = RES_NONE;
2982 #if ENABLE_HUSH_CASE
2983 if (ctx->ctx_res_w == RES_MATCH)
2984 ctx->ctx_res_w = RES_CASE_BODY;
2985 if (ctx->ctx_res_w == RES_CASE)
2986 ctx->ctx_res_w = RES_CASE_IN;
2988 ctx->command = NULL; /* trick done_command below */
2989 /* Create the memory for command, roughly:
2990 * ctx->pipe->cmds = new struct command;
2991 * ctx->command = &ctx->pipe->cmds[0];
2994 //debug_print_tree(ctx->list_head, 10);
2996 debug_printf_parse("done_pipe return\n");
2999 static void initialize_context(struct parse_context *ctx)
3001 memset(ctx, 0, sizeof(*ctx));
3002 ctx->pipe = ctx->list_head = new_pipe();
3003 /* Create the memory for command, roughly:
3004 * ctx->pipe->cmds = new struct command;
3005 * ctx->command = &ctx->pipe->cmds[0];
3010 /* If a reserved word is found and processed, parse context is modified
3011 * and 1 is returned.
3014 struct reserved_combo {
3017 unsigned char assignment_flag;
3021 FLAG_END = (1 << RES_NONE ),
3023 FLAG_IF = (1 << RES_IF ),
3024 FLAG_THEN = (1 << RES_THEN ),
3025 FLAG_ELIF = (1 << RES_ELIF ),
3026 FLAG_ELSE = (1 << RES_ELSE ),
3027 FLAG_FI = (1 << RES_FI ),
3029 # if ENABLE_HUSH_LOOPS
3030 FLAG_FOR = (1 << RES_FOR ),
3031 FLAG_WHILE = (1 << RES_WHILE),
3032 FLAG_UNTIL = (1 << RES_UNTIL),
3033 FLAG_DO = (1 << RES_DO ),
3034 FLAG_DONE = (1 << RES_DONE ),
3035 FLAG_IN = (1 << RES_IN ),
3037 # if ENABLE_HUSH_CASE
3038 FLAG_MATCH = (1 << RES_MATCH),
3039 FLAG_ESAC = (1 << RES_ESAC ),
3041 FLAG_START = (1 << RES_XXXX ),
3044 static const struct reserved_combo* match_reserved_word(o_string *word)
3046 /* Mostly a list of accepted follow-up reserved words.
3047 * FLAG_END means we are done with the sequence, and are ready
3048 * to turn the compound list into a command.
3049 * FLAG_START means the word must start a new compound list.
3051 static const struct reserved_combo reserved_list[] = {
3053 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3054 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3055 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3056 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3057 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3058 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3060 # if ENABLE_HUSH_LOOPS
3061 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3062 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3063 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3064 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3065 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3066 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3068 # if ENABLE_HUSH_CASE
3069 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3070 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3073 const struct reserved_combo *r;
3075 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3076 if (strcmp(word->data, r->literal) == 0)
3081 /* Return 0: not a keyword, 1: keyword
3083 static int reserved_word(o_string *word, struct parse_context *ctx)
3085 # if ENABLE_HUSH_CASE
3086 static const struct reserved_combo reserved_match = {
3087 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3090 const struct reserved_combo *r;
3092 if (word->has_quoted_part)
3094 r = match_reserved_word(word);
3098 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3099 # if ENABLE_HUSH_CASE
3100 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3101 /* "case word IN ..." - IN part starts first MATCH part */
3102 r = &reserved_match;
3105 if (r->flag == 0) { /* '!' */
3106 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3107 syntax_error("! ! command");
3108 ctx->ctx_res_w = RES_SNTX;
3110 ctx->ctx_inverted = 1;
3113 if (r->flag & FLAG_START) {
3114 struct parse_context *old;
3116 old = xmalloc(sizeof(*old));
3117 debug_printf_parse("push stack %p\n", old);
3118 *old = *ctx; /* physical copy */
3119 initialize_context(ctx);
3121 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3122 syntax_error_at(word->data);
3123 ctx->ctx_res_w = RES_SNTX;
3126 /* "{...} fi" is ok. "{...} if" is not
3128 * if { echo foo; } then { echo bar; } fi */
3129 if (ctx->command->group)
3130 done_pipe(ctx, PIPE_SEQ);
3133 ctx->ctx_res_w = r->res;
3134 ctx->old_flag = r->flag;
3135 word->o_assignment = r->assignment_flag;
3136 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3138 if (ctx->old_flag & FLAG_END) {
3139 struct parse_context *old;
3141 done_pipe(ctx, PIPE_SEQ);
3142 debug_printf_parse("pop stack %p\n", ctx->stack);
3144 old->command->group = ctx->list_head;
3145 old->command->cmd_type = CMD_NORMAL;
3147 o_addstr(&old->as_string, ctx->as_string.data);
3148 o_free_unsafe(&ctx->as_string);
3149 old->command->group_as_string = xstrdup(old->as_string.data);
3150 debug_printf_parse("pop, remembering as:'%s'\n",
3151 old->command->group_as_string);
3153 *ctx = *old; /* physical copy */
3158 #endif /* HAS_KEYWORDS */
3160 /* Word is complete, look at it and update parsing context.
3161 * Normal return is 0. Syntax errors return 1.
3162 * Note: on return, word is reset, but not o_free'd!
3164 static int done_word(o_string *word, struct parse_context *ctx)
3166 struct command *command = ctx->command;
3168 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3169 if (word->length == 0 && !word->has_quoted_part) {
3170 debug_printf_parse("done_word return 0: true null, ignored\n");
3174 if (ctx->pending_redirect) {
3175 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3176 * only if run as "bash", not "sh" */
3177 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3179 * ...the word that follows the redirection operator
3180 * shall be subjected to tilde expansion, parameter expansion,
3181 * command substitution, arithmetic expansion, and quote
3182 * removal. Pathname expansion shall not be performed
3183 * on the word by a non-interactive shell; an interactive
3184 * shell may perform it, but shall do so only when
3185 * the expansion would result in one word."
3187 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3188 /* Cater for >\file case:
3189 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3190 * Same with heredocs:
3191 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3193 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3194 unbackslash(ctx->pending_redirect->rd_filename);
3195 /* Is it <<"HEREDOC"? */
3196 if (word->has_quoted_part) {
3197 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3200 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3201 ctx->pending_redirect = NULL;
3204 # if ENABLE_HUSH_CASE
3205 if (ctx->ctx_dsemicolon
3206 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3208 /* already done when ctx_dsemicolon was set to 1: */
3209 /* ctx->ctx_res_w = RES_MATCH; */
3210 ctx->ctx_dsemicolon = 0;
3213 if (!command->argv /* if it's the first word... */
3214 # if ENABLE_HUSH_LOOPS
3215 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3216 && ctx->ctx_res_w != RES_IN
3218 # if ENABLE_HUSH_CASE
3219 && ctx->ctx_res_w != RES_CASE
3222 int reserved = reserved_word(word, ctx);
3223 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3225 o_reset_to_empty_unquoted(word);
3226 debug_printf_parse("done_word return %d\n",
3227 (ctx->ctx_res_w == RES_SNTX));
3228 return (ctx->ctx_res_w == RES_SNTX);
3230 # if ENABLE_HUSH_BASH_COMPAT
3231 if (strcmp(word->data, "[[") == 0) {
3232 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3238 if (command->group) {
3239 /* "{ echo foo; } echo bar" - bad */
3240 syntax_error_at(word->data);
3241 debug_printf_parse("done_word return 1: syntax error, "
3242 "groups and arglists don't mix\n");
3246 /* If this word wasn't an assignment, next ones definitely
3247 * can't be assignments. Even if they look like ones. */
3248 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3249 && word->o_assignment != WORD_IS_KEYWORD
3251 word->o_assignment = NOT_ASSIGNMENT;
3253 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3254 command->assignment_cnt++;
3255 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3257 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3258 word->o_assignment = MAYBE_ASSIGNMENT;
3260 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3262 if (word->has_quoted_part
3263 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3264 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3265 /* (otherwise it's known to be not empty and is already safe) */
3267 /* exclude "$@" - it can expand to no word despite "" */
3268 char *p = word->data;
3269 while (p[0] == SPECIAL_VAR_SYMBOL
3270 && (p[1] & 0x7f) == '@'
3271 && p[2] == SPECIAL_VAR_SYMBOL
3276 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3277 debug_print_strings("word appended to argv", command->argv);
3280 #if ENABLE_HUSH_LOOPS
3281 if (ctx->ctx_res_w == RES_FOR) {
3282 if (word->has_quoted_part
3283 || !is_well_formed_var_name(command->argv[0], '\0')
3285 /* bash says just "not a valid identifier" */
3286 syntax_error("not a valid identifier in for");
3289 /* Force FOR to have just one word (variable name) */
3290 /* NB: basically, this makes hush see "for v in ..."
3291 * syntax as if it is "for v; in ...". FOR and IN become
3292 * two pipe structs in parse tree. */
3293 done_pipe(ctx, PIPE_SEQ);
3296 #if ENABLE_HUSH_CASE
3297 /* Force CASE to have just one word */
3298 if (ctx->ctx_res_w == RES_CASE) {
3299 done_pipe(ctx, PIPE_SEQ);
3303 o_reset_to_empty_unquoted(word);
3305 debug_printf_parse("done_word return 0\n");
3310 /* Peek ahead in the input to find out if we have a "&n" construct,
3311 * as in "2>&1", that represents duplicating a file descriptor.
3313 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3314 * REDIRFD_SYNTAX_ERR if syntax error,
3315 * REDIRFD_TO_FILE if no & was seen,
3316 * or the number found.
3319 #define parse_redir_right_fd(as_string, input) \
3320 parse_redir_right_fd(input)
3322 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3328 return REDIRFD_TO_FILE;
3330 ch = i_getch(input); /* get the & */
3331 nommu_addchr(as_string, ch);
3334 ch = i_getch(input);
3335 nommu_addchr(as_string, ch);
3336 return REDIRFD_CLOSE;
3340 while (ch != EOF && isdigit(ch)) {
3341 d = d*10 + (ch-'0');
3343 ch = i_getch(input);
3344 nommu_addchr(as_string, ch);
3349 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3351 bb_error_msg("ambiguous redirect");
3352 return REDIRFD_SYNTAX_ERR;
3355 /* Return code is 0 normal, 1 if a syntax error is detected
3357 static int parse_redirect(struct parse_context *ctx,
3360 struct in_str *input)
3362 struct command *command = ctx->command;
3363 struct redir_struct *redir;
3364 struct redir_struct **redirp;
3367 dup_num = REDIRFD_TO_FILE;
3368 if (style != REDIRECT_HEREDOC) {
3369 /* Check for a '>&1' type redirect */
3370 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3371 if (dup_num == REDIRFD_SYNTAX_ERR)
3374 int ch = i_peek(input);
3375 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3376 if (dup_num) { /* <<-... */
3377 ch = i_getch(input);
3378 nommu_addchr(&ctx->as_string, ch);
3383 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3384 int ch = i_peek(input);
3386 /* >|FILE redirect ("clobbering" >).
3387 * Since we do not support "set -o noclobber" yet,
3388 * >| and > are the same for now. Just eat |.
3390 ch = i_getch(input);
3391 nommu_addchr(&ctx->as_string, ch);
3395 /* Create a new redir_struct and append it to the linked list */
3396 redirp = &command->redirects;
3397 while ((redir = *redirp) != NULL) {
3398 redirp = &(redir->next);
3400 *redirp = redir = xzalloc(sizeof(*redir));
3401 /* redir->next = NULL; */
3402 /* redir->rd_filename = NULL; */
3403 redir->rd_type = style;
3404 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3406 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3407 redir_table[style].descrip);
3409 redir->rd_dup = dup_num;
3410 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3411 /* Erik had a check here that the file descriptor in question
3412 * is legit; I postpone that to "run time"
3413 * A "-" representation of "close me" shows up as a -3 here */
3414 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3415 redir->rd_fd, redir->rd_dup);
3417 /* Set ctx->pending_redirect, so we know what to do at the
3418 * end of the next parsed word. */
3419 ctx->pending_redirect = redir;
3424 /* If a redirect is immediately preceded by a number, that number is
3425 * supposed to tell which file descriptor to redirect. This routine
3426 * looks for such preceding numbers. In an ideal world this routine
3427 * needs to handle all the following classes of redirects...
3428 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3429 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3430 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3431 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3433 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3435 * ... If n is quoted, the number shall not be recognized as part of
3436 * the redirection expression. For example:
3438 * writes the character 2 into file a"
3439 * We are getting it right by setting ->has_quoted_part on any \<char>
3441 * A -1 return means no valid number was found,
3442 * the caller should use the appropriate default for this redirection.
3444 static int redirect_opt_num(o_string *o)
3448 if (o->data == NULL)
3450 num = bb_strtou(o->data, NULL, 10);
3451 if (errno || num < 0)
3453 o_reset_to_empty_unquoted(o);
3458 #define fetch_till_str(as_string, input, word, skip_tabs) \
3459 fetch_till_str(input, word, skip_tabs)
3461 static char *fetch_till_str(o_string *as_string,
3462 struct in_str *input,
3466 o_string heredoc = NULL_O_STRING;
3468 int prev = 0; /* not \ */
3474 ch = i_getch(input);
3476 nommu_addchr(as_string, ch);
3477 if ((ch == '\n' || ch == EOF)
3478 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3480 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3481 heredoc.data[past_EOL] = '\0';
3482 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3483 return heredoc.data;
3485 while (ch == '\n') {
3486 o_addchr(&heredoc, ch);
3489 past_EOL = heredoc.length;
3491 ch = i_getch(input);
3493 nommu_addchr(as_string, ch);
3494 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3498 o_free_unsafe(&heredoc);
3501 o_addchr(&heredoc, ch);
3502 nommu_addchr(as_string, ch);
3503 if (prev == '\\' && ch == '\\')
3504 /* Correctly handle foo\\<eol> (not a line cont.) */
3505 prev = 0; /* not \ */
3511 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3512 * and load them all. There should be exactly heredoc_cnt of them.
3514 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3516 struct pipe *pi = ctx->list_head;
3518 while (pi && heredoc_cnt) {
3520 struct command *cmd = pi->cmds;
3522 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3524 cmd->argv ? cmd->argv[0] : "NONE");
3525 for (i = 0; i < pi->num_cmds; i++) {
3526 struct redir_struct *redir = cmd->redirects;
3528 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3529 i, cmd->argv ? cmd->argv[0] : "NONE");
3531 if (redir->rd_type == REDIRECT_HEREDOC) {
3534 redir->rd_type = REDIRECT_HEREDOC2;
3535 /* redir->rd_dup is (ab)used to indicate <<- */
3536 p = fetch_till_str(&ctx->as_string, input,
3537 redir->rd_filename, redir->rd_dup);
3539 syntax_error("unexpected EOF in here document");
3542 free(redir->rd_filename);
3543 redir->rd_filename = p;
3546 redir = redir->next;
3553 /* Should be 0. If it isn't, it's a parse error */
3555 bb_error_msg_and_die("heredoc BUG 2");
3561 static int run_list(struct pipe *pi);
3563 #define parse_stream(pstring, input, end_trigger) \
3564 parse_stream(input, end_trigger)
3566 static struct pipe *parse_stream(char **pstring,
3567 struct in_str *input,
3571 #if !ENABLE_HUSH_FUNCTIONS
3572 #define parse_group(dest, ctx, input, ch) \
3573 parse_group(ctx, input, ch)
3575 static int parse_group(o_string *dest, struct parse_context *ctx,
3576 struct in_str *input, int ch)
3578 /* dest contains characters seen prior to ( or {.
3579 * Typically it's empty, but for function defs,
3580 * it contains function name (without '()'). */
3581 struct pipe *pipe_list;
3583 struct command *command = ctx->command;
3585 debug_printf_parse("parse_group entered\n");
3586 #if ENABLE_HUSH_FUNCTIONS
3587 if (ch == '(' && !dest->has_quoted_part) {
3589 if (done_word(dest, ctx))
3592 goto skip; /* (... */
3593 if (command->argv[1]) { /* word word ... (... */
3594 syntax_error_unexpected_ch('(');
3597 /* it is "word(..." or "word (..." */
3599 ch = i_getch(input);
3600 while (ch == ' ' || ch == '\t');
3602 syntax_error_unexpected_ch(ch);
3605 nommu_addchr(&ctx->as_string, ch);
3607 ch = i_getch(input);
3608 while (ch == ' ' || ch == '\t' || ch == '\n');
3610 syntax_error_unexpected_ch(ch);
3613 nommu_addchr(&ctx->as_string, ch);
3614 command->cmd_type = CMD_FUNCDEF;
3619 #if 0 /* Prevented by caller */
3620 if (command->argv /* word [word]{... */
3621 || dest->length /* word{... */
3622 || dest->has_quoted_part /* ""{... */
3625 debug_printf_parse("parse_group return 1: "
3626 "syntax error, groups and arglists don't mix\n");
3631 #if ENABLE_HUSH_FUNCTIONS
3637 command->cmd_type = CMD_SUBSHELL;
3639 /* bash does not allow "{echo...", requires whitespace */
3640 ch = i_getch(input);
3641 if (ch != ' ' && ch != '\t' && ch != '\n') {
3642 syntax_error_unexpected_ch(ch);
3645 nommu_addchr(&ctx->as_string, ch);
3650 # define as_string NULL
3652 char *as_string = NULL;
3654 pipe_list = parse_stream(&as_string, input, endch);
3657 o_addstr(&ctx->as_string, as_string);
3659 /* empty ()/{} or parse error? */
3660 if (!pipe_list || pipe_list == ERR_PTR) {
3661 /* parse_stream already emitted error msg */
3664 debug_printf_parse("parse_group return 1: "
3665 "parse_stream returned %p\n", pipe_list);
3668 command->group = pipe_list;
3670 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3671 command->group_as_string = as_string;
3672 debug_printf_parse("end of group, remembering as:'%s'\n",
3673 command->group_as_string);
3677 debug_printf_parse("parse_group return 0\n");
3679 /* command remains "open", available for possible redirects */
3682 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3683 /* Subroutines for copying $(...) and `...` things */
3684 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3686 static int add_till_single_quote(o_string *dest, struct in_str *input)
3689 int ch = i_getch(input);
3691 syntax_error_unterm_ch('\'');
3699 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3700 static int add_till_double_quote(o_string *dest, struct in_str *input)
3703 int ch = i_getch(input);
3705 syntax_error_unterm_ch('"');
3710 if (ch == '\\') { /* \x. Copy both chars. */
3712 ch = i_getch(input);
3716 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3721 //if (ch == '$') ...
3724 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3726 * "Within the backquoted style of command substitution, backslash
3727 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3728 * The search for the matching backquote shall be satisfied by the first
3729 * backquote found without a preceding backslash; during this search,
3730 * if a non-escaped backquote is encountered within a shell comment,
3731 * a here-document, an embedded command substitution of the $(command)
3732 * form, or a quoted string, undefined results occur. A single-quoted
3733 * or double-quoted string that begins, but does not end, within the
3734 * "`...`" sequence produces undefined results."
3736 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3738 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3741 int ch = i_getch(input);
3745 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3746 ch = i_getch(input);
3750 && (!in_dquote || ch != '"')
3752 o_addchr(dest, '\\');
3756 syntax_error_unterm_ch('`');
3762 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3763 * quoting and nested ()s.
3764 * "With the $(command) style of command substitution, all characters
3765 * following the open parenthesis to the matching closing parenthesis
3766 * constitute the command. Any valid shell script can be used for command,
3767 * except a script consisting solely of redirections which produces
3768 * unspecified results."
3770 * echo $(echo '(TEST)' BEST) (TEST) BEST
3771 * echo $(echo 'TEST)' BEST) TEST) BEST
3772 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3774 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3775 * can contain arbitrary constructs, just like $(cmd).
3776 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3777 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3779 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3780 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3783 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3784 # if ENABLE_HUSH_BASH_COMPAT
3785 char end_char2 = end_ch >> 8;
3787 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3790 ch = i_getch(input);
3792 syntax_error_unterm_ch(end_ch);
3795 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3798 /* we look for closing )) of $((EXPR)) */
3799 if (i_peek(input) == end_ch) {
3800 i_getch(input); /* eat second ')' */
3805 if (ch == '(' || ch == '{') {
3806 ch = (ch == '(' ? ')' : '}');
3807 if (!add_till_closing_bracket(dest, input, ch))
3813 if (!add_till_single_quote(dest, input))
3819 if (!add_till_double_quote(dest, input))
3825 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3831 /* \x. Copy verbatim. Important for \(, \) */
3832 ch = i_getch(input);
3834 syntax_error_unterm_ch(')');
3843 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3845 /* Return code: 0 for OK, 1 for syntax error */
3847 #define parse_dollar(as_string, dest, input, quote_mask) \
3848 parse_dollar(dest, input, quote_mask)
3849 #define as_string NULL
3851 static int parse_dollar(o_string *as_string,
3853 struct in_str *input, unsigned char quote_mask)
3855 int ch = i_peek(input); /* first character after the $ */
3857 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3859 ch = i_getch(input);
3860 nommu_addchr(as_string, ch);
3862 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3864 debug_printf_parse(": '%c'\n", ch);
3865 o_addchr(dest, ch | quote_mask);
3868 if (!isalnum(ch) && ch != '_')
3870 ch = i_getch(input);
3871 nommu_addchr(as_string, ch);
3873 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3874 } else if (isdigit(ch)) {
3876 ch = i_getch(input);
3877 nommu_addchr(as_string, ch);
3878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3879 debug_printf_parse(": '%c'\n", ch);
3880 o_addchr(dest, ch | quote_mask);
3881 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3882 } else switch (ch) {
3884 case '!': /* last bg pid */
3885 case '?': /* last exit code */
3886 case '#': /* number of args */
3887 case '*': /* args */
3888 case '@': /* args */
3889 goto make_one_char_var;
3891 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3893 ch = i_getch(input); /* eat '{' */
3894 nommu_addchr(as_string, ch);
3896 ch = i_getch(input); /* first char after '{' */
3897 /* It should be ${?}, or ${#var},
3898 * or even ${?+subst} - operator acting on a special variable,
3899 * or the beginning of variable name.
3902 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3905 syntax_error_unterm_str("${name}");
3906 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3909 nommu_addchr(as_string, ch);
3912 /* It's possible to just call add_till_closing_bracket() at this point.
3913 * However, this regresses some of our testsuite cases
3914 * which check invalid constructs like ${%}.
3915 * Oh well... let's check that the var name part is fine... */
3921 debug_printf_parse(": '%c'\n", ch);
3923 ch = i_getch(input);
3924 nommu_addchr(as_string, ch);
3928 if (!isalnum(ch) && ch != '_') {
3930 unsigned char last_ch;
3931 /* handle parameter expansions
3932 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3934 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3935 goto bad_dollar_syntax;
3937 /* Eat everything until closing '}' (or ':') */
3939 if (ENABLE_HUSH_BASH_COMPAT
3941 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3943 /* It's ${var:N[:M]} thing */
3944 end_ch = '}' * 0x100 + ':';
3946 if (ENABLE_HUSH_BASH_COMPAT
3949 /* It's ${var/[/]pattern[/repl]} thing */
3950 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3952 nommu_addchr(as_string, '/');
3955 end_ch = '}' * 0x100 + '/';
3961 #if ENABLE_HUSH_DOLLAR_OPS
3962 last_ch = add_till_closing_bracket(dest, input, end_ch);
3963 if (last_ch == 0) /* error? */
3966 #error Simple code to only allow ${var} is not implemented
3969 o_addstr(as_string, dest->data + pos);
3970 o_addchr(as_string, last_ch);
3973 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3974 /* close the first block: */
3975 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3976 /* while parsing N from ${var:N[:M]}
3977 * or pattern from ${var/[/]pattern[/repl]} */
3978 if ((end_ch & 0xff) == last_ch) {
3979 /* got ':' or '/'- parse the rest */
3984 if (end_ch == '}' * 0x100 + ':') {
3985 /* it's ${var:N} - emulate :999999999 */
3986 o_addstr(dest, "999999999");
3987 } /* else: it's ${var/[/]pattern} */
3992 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3995 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3999 ch = i_getch(input);
4000 nommu_addchr(as_string, ch);
4001 # if ENABLE_SH_MATH_SUPPORT
4002 if (i_peek(input) == '(') {
4003 ch = i_getch(input);
4004 nommu_addchr(as_string, ch);
4005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4006 o_addchr(dest, /*quote_mask |*/ '+');
4009 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4010 return 0; /* error */
4012 o_addstr(as_string, dest->data + pos);
4013 o_addchr(as_string, ')');
4014 o_addchr(as_string, ')');
4016 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4020 # if ENABLE_HUSH_TICK
4021 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4022 o_addchr(dest, quote_mask | '`');
4025 if (!add_till_closing_bracket(dest, input, ')'))
4026 return 0; /* error */
4028 o_addstr(as_string, dest->data + pos);
4029 o_addchr(as_string, ')');
4031 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4037 ch = i_getch(input);
4038 nommu_addchr(as_string, ch);
4040 if (isalnum(ch)) { /* it's $_name or $_123 */
4045 /* TODO: $_ and $-: */
4046 /* $_ Shell or shell script name; or last argument of last command
4047 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4048 * but in command's env, set to full pathname used to invoke it */
4049 /* $- Option flags set by set builtin or shell options (-i etc) */
4051 o_addQchr(dest, '$');
4053 debug_printf_parse("parse_dollar return 1 (ok)\n");
4059 # if ENABLE_HUSH_BASH_COMPAT
4060 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4061 encode_string(dest, input, dquote_end, process_bkslash)
4063 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4064 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4065 encode_string(dest, input, dquote_end)
4067 #define as_string NULL
4071 # if ENABLE_HUSH_BASH_COMPAT
4072 /* all parameters are needed, no macro tricks */
4074 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4075 encode_string(as_string, dest, input, dquote_end)
4078 static int encode_string(o_string *as_string,
4080 struct in_str *input,
4082 int process_bkslash)
4084 #if !ENABLE_HUSH_BASH_COMPAT
4085 const int process_bkslash = 1;
4091 ch = i_getch(input);
4093 nommu_addchr(as_string, ch);
4094 if (ch == dquote_end) { /* may be only '"' or EOF */
4095 debug_printf_parse("encode_string return 1 (ok)\n");
4098 /* note: can't move it above ch == dquote_end check! */
4100 syntax_error_unterm_ch('"');
4101 return 0; /* error */
4105 next = i_peek(input);
4107 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4108 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4109 if (process_bkslash && ch == '\\') {
4111 syntax_error("\\<eof>");
4115 * "The backslash retains its special meaning [in "..."]
4116 * only when followed by one of the following characters:
4117 * $, `, ", \, or <newline>. A double quote may be quoted
4118 * within double quotes by preceding it with a backslash."
4119 * NB: in (unquoted) heredoc, above does not apply to ",
4120 * therefore we check for it by "next == dquote_end" cond.
4122 if (next == dquote_end || strchr("$`\\\n", next)) {
4123 ch = i_getch(input); /* eat next */
4125 goto again; /* skip \<newline> */
4126 } /* else: ch remains == '\\', and we double it below: */
4127 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4128 nommu_addchr(as_string, ch);
4132 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4133 debug_printf_parse("encode_string return 0: "
4134 "parse_dollar returned 0 (error)\n");
4139 #if ENABLE_HUSH_TICK
4141 //unsigned pos = dest->length;
4142 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4143 o_addchr(dest, 0x80 | '`');
4144 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4145 return 0; /* error */
4146 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4147 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4151 o_addQchr(dest, ch);
4157 * Scan input until EOF or end_trigger char.
4158 * Return a list of pipes to execute, or NULL on EOF
4159 * or if end_trigger character is met.
4160 * On syntax error, exit if shell is not interactive,
4161 * reset parsing machinery and start parsing anew,
4162 * or return ERR_PTR.
4164 static struct pipe *parse_stream(char **pstring,
4165 struct in_str *input,
4168 struct parse_context ctx;
4169 o_string dest = NULL_O_STRING;
4172 /* Single-quote triggers a bypass of the main loop until its mate is
4173 * found. When recursing, quote state is passed in via dest->o_expflags.
4175 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4176 end_trigger ? end_trigger : 'X');
4179 /* If very first arg is "" or '', dest.data may end up NULL.
4180 * Preventing this: */
4181 o_addchr(&dest, '\0');
4184 /* We used to separate words on $IFS here. This was wrong.
4185 * $IFS is used only for word splitting when $var is expanded,
4186 * here we should use blank chars as separators, not $IFS
4189 if (MAYBE_ASSIGNMENT != 0)
4190 dest.o_assignment = MAYBE_ASSIGNMENT;
4191 initialize_context(&ctx);
4194 const char *is_blank;
4195 const char *is_special;
4199 redir_type redir_style;
4201 ch = i_getch(input);
4202 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4203 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4208 syntax_error_unterm_str("here document");
4211 /* end_trigger == '}' case errors out earlier,
4212 * checking only ')' */
4213 if (end_trigger == ')') {
4214 syntax_error_unterm_ch('(');
4218 if (done_word(&dest, &ctx)) {
4222 done_pipe(&ctx, PIPE_SEQ);
4224 /* If we got nothing... */
4225 /* (this makes bare "&" cmd a no-op.
4226 * bash says: "syntax error near unexpected token '&'") */
4227 if (pi->num_cmds == 0
4228 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
4234 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4236 *pstring = ctx.as_string.data;
4238 o_free_unsafe(&ctx.as_string);
4241 debug_printf_parse("parse_stream return %p\n", pi);
4244 nommu_addchr(&ctx.as_string, ch);
4248 next = i_peek(input);
4250 is_special = "{}<>;&|()#'" /* special outside of "str" */
4251 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4252 /* Are { and } special here? */
4253 if (ctx.command->argv /* word [word]{... - non-special */
4254 || dest.length /* word{... - non-special */
4255 || dest.has_quoted_part /* ""{... - non-special */
4256 || (next != ';' /* }; - special */
4257 && next != ')' /* }) - special */
4258 && next != '&' /* }& and }&& ... - special */
4259 && next != '|' /* }|| ... - special */
4260 && !strchr(defifs, next) /* {word - non-special */
4263 /* They are not special, skip "{}" */
4266 is_special = strchr(is_special, ch);
4267 is_blank = strchr(defifs, ch);
4269 if (!is_special && !is_blank) { /* ordinary char */
4271 o_addQchr(&dest, ch);
4272 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4273 || dest.o_assignment == WORD_IS_KEYWORD)
4275 && is_well_formed_var_name(dest.data, '=')
4277 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4278 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4284 if (done_word(&dest, &ctx)) {
4288 /* Is this a case when newline is simply ignored?
4290 * "cmd | <newline> cmd ..."
4291 * "case ... in <newline> word) ..."
4293 if (IS_NULL_CMD(ctx.command)
4294 && dest.length == 0 && !dest.has_quoted_part
4296 /* This newline can be ignored. But...
4297 * Without check #1, interactive shell
4298 * ignores even bare <newline>,
4299 * and shows the continuation prompt:
4300 * ps1_prompt$ <enter>
4301 * ps2> _ <=== wrong, should be ps1
4302 * Without check #2, "cmd & <newline>"
4303 * is similarly mistreated.
4304 * (BTW, this makes "cmd & cmd"
4305 * and "cmd && cmd" non-orthogonal.
4306 * Really, ask yourself, why
4307 * "cmd && <newline>" doesn't start
4308 * cmd but waits for more input?
4311 struct pipe *pi = ctx.list_head;
4312 if (pi->num_cmds != 0 /* check #1 */
4313 && pi->followup != PIPE_BG /* check #2 */
4318 /* Treat newline as a command separator. */
4319 done_pipe(&ctx, PIPE_SEQ);
4320 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4322 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4327 dest.o_assignment = MAYBE_ASSIGNMENT;
4328 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4330 /* note: if (is_blank) continue;
4331 * will still trigger for us */
4335 /* "cmd}" or "cmd }..." without semicolon or &:
4336 * } is an ordinary char in this case, even inside { cmd; }
4337 * Pathological example: { ""}; } should exec "}" cmd
4340 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4341 || dest.length != 0 /* word} */
4342 || dest.has_quoted_part /* ""} */
4346 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4347 goto skip_end_trigger;
4348 /* else: } does terminate a group */
4351 if (end_trigger && end_trigger == ch
4352 && (ch != ';' || heredoc_cnt == 0)
4353 #if ENABLE_HUSH_CASE
4355 || ctx.ctx_res_w != RES_MATCH
4356 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4361 /* This is technically valid:
4362 * { cat <<HERE; }; echo Ok
4366 * but we don't support this.
4367 * We require heredoc to be in enclosing {}/(),
4370 syntax_error_unterm_str("here document");
4373 if (done_word(&dest, &ctx)) {
4376 done_pipe(&ctx, PIPE_SEQ);
4377 dest.o_assignment = MAYBE_ASSIGNMENT;
4378 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4379 /* Do we sit outside of any if's, loops or case's? */
4381 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4385 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4387 *pstring = ctx.as_string.data;
4389 o_free_unsafe(&ctx.as_string);
4392 debug_printf_parse("parse_stream return %p: "
4393 "end_trigger char found\n",
4395 return ctx.list_head;
4402 /* Catch <, > before deciding whether this word is
4403 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4406 redir_fd = redirect_opt_num(&dest);
4407 if (done_word(&dest, &ctx)) {
4410 redir_style = REDIRECT_OVERWRITE;
4412 redir_style = REDIRECT_APPEND;
4413 ch = i_getch(input);
4414 nommu_addchr(&ctx.as_string, ch);
4417 else if (next == '(') {
4418 syntax_error(">(process) not supported");
4422 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4424 continue; /* back to top of while (1) */
4426 redir_fd = redirect_opt_num(&dest);
4427 if (done_word(&dest, &ctx)) {
4430 redir_style = REDIRECT_INPUT;
4432 redir_style = REDIRECT_HEREDOC;
4434 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4435 ch = i_getch(input);
4436 nommu_addchr(&ctx.as_string, ch);
4437 } else if (next == '>') {
4438 redir_style = REDIRECT_IO;
4439 ch = i_getch(input);
4440 nommu_addchr(&ctx.as_string, ch);
4443 else if (next == '(') {
4444 syntax_error("<(process) not supported");
4448 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4450 continue; /* back to top of while (1) */
4452 if (dest.length == 0 && !dest.has_quoted_part) {
4453 /* skip "#comment" */
4456 if (ch == EOF || ch == '\n')
4459 /* note: we do not add it to &ctx.as_string */
4461 nommu_addchr(&ctx.as_string, '\n');
4462 continue; /* back to top of while (1) */
4467 /* It's "\<newline>" */
4469 /* Remove trailing '\' from ctx.as_string */
4470 ctx.as_string.data[--ctx.as_string.length] = '\0';
4472 ch = i_getch(input); /* eat it */
4473 continue; /* back to top of while (1) */
4478 if (dest.o_assignment == MAYBE_ASSIGNMENT
4479 /* check that we are not in word in "a=1 2>word b=1": */
4480 && !ctx.pending_redirect
4482 /* ch is a special char and thus this word
4483 * cannot be an assignment */
4484 dest.o_assignment = NOT_ASSIGNMENT;
4485 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4488 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4491 case '#': /* non-comment #: "echo a#b" etc */
4492 o_addQchr(&dest, ch);
4496 syntax_error("\\<eof>");
4499 ch = i_getch(input);
4500 /* note: ch != '\n' (that case does not reach this place) */
4501 o_addchr(&dest, '\\');
4502 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4503 o_addchr(&dest, ch);
4504 nommu_addchr(&ctx.as_string, ch);
4505 /* Example: echo Hello \2>file
4506 * we need to know that word 2 is quoted */
4507 dest.has_quoted_part = 1;
4510 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4511 debug_printf_parse("parse_stream parse error: "
4512 "parse_dollar returned 0 (error)\n");
4517 dest.has_quoted_part = 1;
4518 if (next == '\'' && !ctx.pending_redirect) {
4519 insert_empty_quoted_str_marker:
4520 nommu_addchr(&ctx.as_string, next);
4521 i_getch(input); /* eat second ' */
4522 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4523 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4526 ch = i_getch(input);
4528 syntax_error_unterm_ch('\'');
4531 nommu_addchr(&ctx.as_string, ch);
4534 o_addqchr(&dest, ch);
4539 dest.has_quoted_part = 1;
4540 if (next == '"' && !ctx.pending_redirect)
4541 goto insert_empty_quoted_str_marker;
4542 if (dest.o_assignment == NOT_ASSIGNMENT)
4543 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4544 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4546 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4548 #if ENABLE_HUSH_TICK
4550 USE_FOR_NOMMU(unsigned pos;)
4552 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4553 o_addchr(&dest, '`');
4554 USE_FOR_NOMMU(pos = dest.length;)
4555 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4558 o_addstr(&ctx.as_string, dest.data + pos);
4559 o_addchr(&ctx.as_string, '`');
4561 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4562 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4567 #if ENABLE_HUSH_CASE
4570 if (done_word(&dest, &ctx)) {
4573 done_pipe(&ctx, PIPE_SEQ);
4574 #if ENABLE_HUSH_CASE
4575 /* Eat multiple semicolons, detect
4576 * whether it means something special */
4581 ch = i_getch(input);
4582 nommu_addchr(&ctx.as_string, ch);
4583 if (ctx.ctx_res_w == RES_CASE_BODY) {
4584 ctx.ctx_dsemicolon = 1;
4585 ctx.ctx_res_w = RES_MATCH;
4591 /* We just finished a cmd. New one may start
4592 * with an assignment */
4593 dest.o_assignment = MAYBE_ASSIGNMENT;
4594 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4597 if (done_word(&dest, &ctx)) {
4601 ch = i_getch(input);
4602 nommu_addchr(&ctx.as_string, ch);
4603 done_pipe(&ctx, PIPE_AND);
4605 done_pipe(&ctx, PIPE_BG);
4609 if (done_word(&dest, &ctx)) {
4612 #if ENABLE_HUSH_CASE
4613 if (ctx.ctx_res_w == RES_MATCH)
4614 break; /* we are in case's "word | word)" */
4616 if (next == '|') { /* || */
4617 ch = i_getch(input);
4618 nommu_addchr(&ctx.as_string, ch);
4619 done_pipe(&ctx, PIPE_OR);
4621 /* we could pick up a file descriptor choice here
4622 * with redirect_opt_num(), but bash doesn't do it.
4623 * "echo foo 2| cat" yields "foo 2". */
4626 o_reset_to_empty_unquoted(&ctx.as_string);
4631 #if ENABLE_HUSH_CASE
4632 /* "case... in [(]word)..." - skip '(' */
4633 if (ctx.ctx_res_w == RES_MATCH
4634 && ctx.command->argv == NULL /* not (word|(... */
4635 && dest.length == 0 /* not word(... */
4636 && dest.has_quoted_part == 0 /* not ""(... */
4642 if (parse_group(&dest, &ctx, input, ch) != 0) {
4647 #if ENABLE_HUSH_CASE
4648 if (ctx.ctx_res_w == RES_MATCH)
4652 /* proper use of this character is caught by end_trigger:
4653 * if we see {, we call parse_group(..., end_trigger='}')
4654 * and it will match } earlier (not here). */
4655 syntax_error_unexpected_ch(ch);
4659 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4665 struct parse_context *pctx;
4666 IF_HAS_KEYWORDS(struct parse_context *p2;)
4668 /* Clean up allocated tree.
4669 * Sample for finding leaks on syntax error recovery path.
4670 * Run it from interactive shell, watch pmap `pidof hush`.
4671 * while if false; then false; fi; do break; fi
4672 * Samples to catch leaks at execution:
4673 * while if (true | {true;}); then echo ok; fi; do break; done
4674 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4678 /* Update pipe/command counts,
4679 * otherwise freeing may miss some */
4680 done_pipe(pctx, PIPE_SEQ);
4681 debug_printf_clean("freeing list %p from ctx %p\n",
4682 pctx->list_head, pctx);
4683 debug_print_tree(pctx->list_head, 0);
4684 free_pipe_list(pctx->list_head);
4685 debug_printf_clean("freed list %p\n", pctx->list_head);
4687 o_free_unsafe(&pctx->as_string);
4689 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4693 IF_HAS_KEYWORDS(pctx = p2;)
4694 } while (HAS_KEYWORDS && pctx);
4697 G.last_exitcode = 1;
4708 /*** Execution routines ***/
4710 /* Expansion can recurse, need forward decls: */
4711 #if !ENABLE_HUSH_BASH_COMPAT
4712 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4713 #define expand_string_to_string(str, do_unbackslash) \
4714 expand_string_to_string(str)
4716 static char *expand_string_to_string(const char *str, int do_unbackslash);
4717 #if ENABLE_HUSH_TICK
4718 static int process_command_subs(o_string *dest, const char *s);
4721 /* expand_strvec_to_strvec() takes a list of strings, expands
4722 * all variable references within and returns a pointer to
4723 * a list of expanded strings, possibly with larger number
4724 * of strings. (Think VAR="a b"; echo $VAR).
4725 * This new list is allocated as a single malloc block.
4726 * NULL-terminated list of char* pointers is at the beginning of it,
4727 * followed by strings themselves.
4728 * Caller can deallocate entire list by single free(list). */
4730 /* A horde of its helpers come first: */
4732 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4734 while (--len >= 0) {
4737 #if ENABLE_HUSH_BRACE_EXPANSION
4738 if (c == '{' || c == '}') {
4739 /* { -> \{, } -> \} */
4741 /* And now we want to add { or } and continue:
4744 * luckily, just falling throught achieves this.
4750 /* \z -> \\\z; \<eol> -> \\<eol> */
4755 o_addchr(o, *str++);
4761 /* Store given string, finalizing the word and starting new one whenever
4762 * we encounter IFS char(s). This is used for expanding variable values.
4763 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4764 * Return in *ended_with_ifs:
4765 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4767 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4769 int last_is_ifs = 0;
4774 if (!*str) /* EOL - do not finalize word */
4776 word_len = strcspn(str, G.ifs);
4778 /* We have WORD_LEN leading non-IFS chars */
4779 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4780 o_addblock(output, str, word_len);
4782 /* Protect backslashes against globbing up :)
4783 * Example: "v='\*'; echo b$v" prints "b\*"
4784 * (and does not try to glob on "*")
4786 o_addblock_duplicate_backslash(output, str, word_len);
4787 /*/ Why can't we do it easier? */
4788 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4789 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4793 if (!*str) /* EOL - do not finalize word */
4797 /* We know str here points to at least one IFS char */
4799 str += strspn(str, G.ifs); /* skip IFS chars */
4800 if (!*str) /* EOL - do not finalize word */
4803 /* Start new word... but not always! */
4804 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4805 if (output->has_quoted_part
4806 /* Case "v=' a'; echo $v":
4807 * here nothing precedes the space in $v expansion,
4808 * therefore we should not finish the word
4809 * (IOW: if there *is* word to finalize, only then do it):
4811 || (n > 0 && output->data[output->length - 1])
4813 o_addchr(output, '\0');
4814 debug_print_list("expand_on_ifs", output, n);
4815 n = o_save_ptr(output, n);
4820 *ended_with_ifs = last_is_ifs;
4821 debug_print_list("expand_on_ifs[1]", output, n);
4825 /* Helper to expand $((...)) and heredoc body. These act as if
4826 * they are in double quotes, with the exception that they are not :).
4827 * Just the rules are similar: "expand only $var and `cmd`"
4829 * Returns malloced string.
4830 * As an optimization, we return NULL if expansion is not needed.
4832 #if !ENABLE_HUSH_BASH_COMPAT
4833 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4834 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4835 encode_then_expand_string(str)
4837 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4840 struct in_str input;
4841 o_string dest = NULL_O_STRING;
4843 if (!strchr(str, '$')
4844 && !strchr(str, '\\')
4845 #if ENABLE_HUSH_TICK
4846 && !strchr(str, '`')
4852 /* We need to expand. Example:
4853 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4855 setup_string_in_str(&input, str);
4856 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4857 //TODO: error check (encode_string returns 0 on error)?
4858 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4859 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4860 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4861 o_free_unsafe(&dest);
4865 #if ENABLE_SH_MATH_SUPPORT
4866 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4868 arith_state_t math_state;
4872 math_state.lookupvar = get_local_var_value;
4873 math_state.setvar = set_local_var_from_halves;
4874 //math_state.endofname = endofname;
4875 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4876 res = arith(&math_state, exp_str ? exp_str : arg);
4879 *errmsg_p = math_state.errmsg;
4880 if (math_state.errmsg)
4881 die_if_script(math_state.errmsg);
4886 #if ENABLE_HUSH_BASH_COMPAT
4887 /* ${var/[/]pattern[/repl]} helpers */
4888 static char *strstr_pattern(char *val, const char *pattern, int *size)
4891 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4892 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4899 /* Optimization: if "*pat" did not match the start of "string",
4900 * we know that "tring", "ring" etc will not match too:
4902 if (pattern[0] == '*')
4907 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4909 char *result = NULL;
4910 unsigned res_len = 0;
4911 unsigned repl_len = strlen(repl);
4915 char *s = strstr_pattern(val, pattern, &size);
4919 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4920 memcpy(result + res_len, val, s - val);
4922 strcpy(result + res_len, repl);
4923 res_len += repl_len;
4924 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4930 if (val[0] && result) {
4931 result = xrealloc(result, res_len + strlen(val) + 1);
4932 strcpy(result + res_len, val);
4933 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4935 debug_printf_varexp("result:'%s'\n", result);
4941 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4943 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4945 const char *val = NULL;
4946 char *to_be_freed = NULL;
4951 char exp_save = exp_save; /* for compiler */
4952 char *exp_saveptr; /* points to expansion operator */
4953 char *exp_word = exp_word; /* for compiler */
4956 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4958 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4960 first_char = arg[0] = arg0 & 0x7f;
4963 if (first_char == '#' /* ${#... */
4964 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4966 /* It must be length operator: ${#var} */
4970 /* Maybe handle parameter expansion */
4971 if (exp_saveptr /* if 2nd char is one of expansion operators */
4972 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4974 /* ${?:0}, ${#[:]%0} etc */
4975 exp_saveptr = var + 1;
4977 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4978 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4980 exp_op = exp_save = *exp_saveptr;
4982 exp_word = exp_saveptr + 1;
4983 if (exp_op == ':') {
4984 exp_op = *exp_word++;
4985 //TODO: try ${var:} and ${var:bogus} in non-bash config
4986 if (ENABLE_HUSH_BASH_COMPAT
4987 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4989 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4994 *exp_saveptr = '\0';
4995 } /* else: it's not an expansion op, but bare ${var} */
4998 /* Look up the variable in question */
4999 if (isdigit(var[0])) {
5000 /* parse_dollar should have vetted var for us */
5001 int n = xatoi_positive(var);
5002 if (n < G.global_argc)
5003 val = G.global_argv[n];
5004 /* else val remains NULL: $N with too big N */
5008 val = utoa(G.root_pid);
5010 case '!': /* bg pid */
5011 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5013 case '?': /* exitcode */
5014 val = utoa(G.last_exitcode);
5016 case '#': /* argc */
5017 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5020 val = get_local_var_value(var);
5024 /* Handle any expansions */
5025 if (exp_op == 'L') {
5026 debug_printf_expand("expand: length(%s)=", val);
5027 val = utoa(val ? strlen(val) : 0);
5028 debug_printf_expand("%s\n", val);
5029 } else if (exp_op) {
5030 if (exp_op == '%' || exp_op == '#') {
5031 /* Standard-mandated substring removal ops:
5032 * ${parameter%word} - remove smallest suffix pattern
5033 * ${parameter%%word} - remove largest suffix pattern
5034 * ${parameter#word} - remove smallest prefix pattern
5035 * ${parameter##word} - remove largest prefix pattern
5037 * Word is expanded to produce a glob pattern.
5038 * Then var's value is matched to it and matching part removed.
5040 if (val && val[0]) {
5044 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5045 if (exp_op == *exp_word) /* ## or %% */
5047 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5049 exp_word = exp_exp_word;
5050 /* HACK ALERT. We depend here on the fact that
5051 * G.global_argv and results of utoa and get_local_var_value
5052 * are actually in writable memory:
5053 * scan_and_match momentarily stores NULs there. */
5055 loc = scan_and_match(t, exp_word, scan_flags);
5056 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5057 // exp_op, t, exp_word, loc);
5059 if (loc) { /* match was found */
5060 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5061 val = loc; /* take right part */
5063 val = to_be_freed = xstrndup(val, loc - val); /* left */
5067 #if ENABLE_HUSH_BASH_COMPAT
5068 else if (exp_op == '/' || exp_op == '\\') {
5069 /* It's ${var/[/]pattern[/repl]} thing.
5070 * Note that in encoded form it has TWO parts:
5071 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5072 * and if // is used, it is encoded as \:
5073 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5075 /* Empty variable always gives nothing: */
5076 // "v=''; echo ${v/*/w}" prints "", not "w"
5077 if (val && val[0]) {
5078 /* pattern uses non-standard expansion.
5079 * repl should be unbackslashed and globbed
5080 * by the usual expansion rules:
5082 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5083 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5084 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5085 * v='a bz'; echo ${v/a*z/\z} prints "z"
5086 * (note that a*z _pattern_ is never globbed!)
5088 char *pattern, *repl, *t;
5089 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5091 pattern = xstrdup(exp_word);
5092 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5093 *p++ = SPECIAL_VAR_SYMBOL;
5095 p = strchr(p, SPECIAL_VAR_SYMBOL);
5097 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5098 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5099 /* HACK ALERT. We depend here on the fact that
5100 * G.global_argv and results of utoa and get_local_var_value
5101 * are actually in writable memory:
5102 * replace_pattern momentarily stores NULs there. */
5104 to_be_freed = replace_pattern(t,
5106 (repl ? repl : exp_word),
5108 if (to_be_freed) /* at least one replace happened */
5115 else if (exp_op == ':') {
5116 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5117 /* It's ${var:N[:M]} bashism.
5118 * Note that in encoded form it has TWO parts:
5119 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5124 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5127 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5128 *p++ = SPECIAL_VAR_SYMBOL;
5130 p = strchr(p, SPECIAL_VAR_SYMBOL);
5132 len = expand_and_evaluate_arith(exp_word, &errmsg);
5135 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5136 if (len >= 0) { /* bash compat: len < 0 is illegal */
5137 if (beg < 0) /* bash compat */
5139 debug_printf_varexp("from val:'%s'\n", val);
5140 if (len == 0 || !val || beg >= strlen(val)) {
5144 /* Paranoia. What if user entered 9999999999999
5145 * which fits in arith_t but not int? */
5148 val = to_be_freed = xstrndup(val + beg, len);
5150 debug_printf_varexp("val:'%s'\n", val);
5154 die_if_script("malformed ${%s:...}", var);
5157 } else { /* one of "-=+?" */
5158 /* Standard-mandated substitution ops:
5159 * ${var?word} - indicate error if unset
5160 * If var is unset, word (or a message indicating it is unset
5161 * if word is null) is written to standard error
5162 * and the shell exits with a non-zero exit status.
5163 * Otherwise, the value of var is substituted.
5164 * ${var-word} - use default value
5165 * If var is unset, word is substituted.
5166 * ${var=word} - assign and use default value
5167 * If var is unset, word is assigned to var.
5168 * In all cases, final value of var is substituted.
5169 * ${var+word} - use alternative value
5170 * If var is unset, null is substituted.
5171 * Otherwise, word is substituted.
5173 * Word is subjected to tilde expansion, parameter expansion,
5174 * command substitution, and arithmetic expansion.
5175 * If word is not needed, it is not expanded.
5177 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5178 * but also treat null var as if it is unset.
5180 int use_word = (!val || ((exp_save == ':') && !val[0]));
5182 use_word = !use_word;
5183 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5184 (exp_save == ':') ? "true" : "false", use_word);
5186 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5188 exp_word = to_be_freed;
5189 if (exp_op == '?') {
5190 /* mimic bash message */
5191 die_if_script("%s: %s",
5193 exp_word[0] ? exp_word : "parameter null or not set"
5195 //TODO: how interactive bash aborts expansion mid-command?
5200 if (exp_op == '=') {
5201 /* ${var=[word]} or ${var:=[word]} */
5202 if (isdigit(var[0]) || var[0] == '#') {
5203 /* mimic bash message */
5204 die_if_script("$%s: cannot assign in this way", var);
5207 char *new_var = xasprintf("%s=%s", var, val);
5208 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5212 } /* one of "-=+?" */
5214 *exp_saveptr = exp_save;
5220 *to_be_freed_pp = to_be_freed;
5224 /* Expand all variable references in given string, adding words to list[]
5225 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5226 * to be filled). This routine is extremely tricky: has to deal with
5227 * variables/parameters with whitespace, $* and $@, and constructs like
5228 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5229 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5231 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5232 * expansion of right-hand side of assignment == 1-element expand.
5234 char cant_be_null = 0; /* only bit 0x80 matters */
5235 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5238 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5239 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5240 debug_print_list("expand_vars_to_list", output, n);
5241 n = o_save_ptr(output, n);
5242 debug_print_list("expand_vars_to_list[0]", output, n);
5244 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5246 char *to_be_freed = NULL;
5247 const char *val = NULL;
5248 #if ENABLE_HUSH_TICK
5249 o_string subst_result = NULL_O_STRING;
5251 #if ENABLE_SH_MATH_SUPPORT
5252 char arith_buf[sizeof(arith_t)*3 + 2];
5256 o_addchr(output, '\0');
5257 n = o_save_ptr(output, n);
5261 o_addblock(output, arg, p - arg);
5262 debug_print_list("expand_vars_to_list[1]", output, n);
5264 p = strchr(p, SPECIAL_VAR_SYMBOL);
5266 /* Fetch special var name (if it is indeed one of them)
5267 * and quote bit, force the bit on if singleword expansion -
5268 * important for not getting v=$@ expand to many words. */
5269 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5271 /* Is this variable quoted and thus expansion can't be null?
5272 * "$@" is special. Even if quoted, it can still
5273 * expand to nothing (not even an empty string),
5274 * thus it is excluded. */
5275 if ((first_ch & 0x7f) != '@')
5276 cant_be_null |= first_ch;
5278 switch (first_ch & 0x7f) {
5279 /* Highest bit in first_ch indicates that var is double-quoted */
5283 if (!G.global_argv[1])
5286 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5287 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5288 while (G.global_argv[i]) {
5289 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5290 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5291 if (G.global_argv[i++][0] && G.global_argv[i]) {
5292 /* this argv[] is not empty and not last:
5293 * put terminating NUL, start new word */
5294 o_addchr(output, '\0');
5295 debug_print_list("expand_vars_to_list[2]", output, n);
5296 n = o_save_ptr(output, n);
5297 debug_print_list("expand_vars_to_list[3]", output, n);
5301 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5302 * and in this case should treat it like '$*' - see 'else...' below */
5303 if (first_ch == ('@'|0x80) /* quoted $@ */
5304 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5307 o_addQstr(output, G.global_argv[i]);
5308 if (++i >= G.global_argc)
5310 o_addchr(output, '\0');
5311 debug_print_list("expand_vars_to_list[4]", output, n);
5312 n = o_save_ptr(output, n);
5314 } else { /* quoted $* (or v="$@" case): add as one word */
5316 o_addQstr(output, G.global_argv[i]);
5317 if (!G.global_argv[++i])
5320 o_addchr(output, G.ifs[0]);
5322 output->has_quoted_part = 1;
5326 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5327 /* "Empty variable", used to make "" etc to not disappear */
5328 output->has_quoted_part = 1;
5330 cant_be_null = 0x80;
5332 #if ENABLE_HUSH_TICK
5333 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5334 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5336 /* Can't just stuff it into output o_string,
5337 * expanded result may need to be globbed
5338 * and $IFS-splitted */
5339 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5340 G.last_exitcode = process_command_subs(&subst_result, arg);
5341 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5342 val = subst_result.data;
5345 #if ENABLE_SH_MATH_SUPPORT
5346 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5349 arg++; /* skip '+' */
5350 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5351 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5352 res = expand_and_evaluate_arith(arg, NULL);
5353 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5354 sprintf(arith_buf, ARITH_FMT, res);
5360 val = expand_one_var(&to_be_freed, arg, &p);
5361 IF_HUSH_TICK(store_val:)
5362 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5363 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5364 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5365 if (val && val[0]) {
5366 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5369 } else { /* quoted $VAR, val will be appended below */
5370 output->has_quoted_part = 1;
5371 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5372 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5376 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5378 if (val && val[0]) {
5379 o_addQstr(output, val);
5383 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5384 * Do the check to avoid writing to a const string. */
5385 if (*p != SPECIAL_VAR_SYMBOL)
5386 *p = SPECIAL_VAR_SYMBOL;
5388 #if ENABLE_HUSH_TICK
5389 o_free(&subst_result);
5392 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5396 o_addchr(output, '\0');
5397 n = o_save_ptr(output, n);
5399 debug_print_list("expand_vars_to_list[a]", output, n);
5400 /* this part is literal, and it was already pre-quoted
5401 * if needed (much earlier), do not use o_addQstr here! */
5402 o_addstr_with_NUL(output, arg);
5403 debug_print_list("expand_vars_to_list[b]", output, n);
5404 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5405 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5408 /* allow to reuse list[n] later without re-growth */
5409 output->has_empty_slot = 1;
5411 o_addchr(output, '\0');
5417 static char **expand_variables(char **argv, unsigned expflags)
5421 o_string output = NULL_O_STRING;
5423 output.o_expflags = expflags;
5427 n = expand_vars_to_list(&output, n, *argv);
5430 debug_print_list("expand_variables", &output, n);
5432 /* output.data (malloced in one block) gets returned in "list" */
5433 list = o_finalize_list(&output, n);
5434 debug_print_strings("expand_variables[1]", list);
5438 static char **expand_strvec_to_strvec(char **argv)
5440 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5443 #if ENABLE_HUSH_BASH_COMPAT
5444 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5446 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5450 /* Used for expansion of right hand of assignments,
5451 * $((...)), heredocs, variable espansion parts.
5453 * NB: should NOT do globbing!
5454 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5456 static char *expand_string_to_string(const char *str, int do_unbackslash)
5458 #if !ENABLE_HUSH_BASH_COMPAT
5459 const int do_unbackslash = 1;
5461 char *argv[2], **list;
5463 debug_printf_expand("string_to_string<='%s'\n", str);
5464 /* This is generally an optimization, but it also
5465 * handles "", which otherwise trips over !list[0] check below.
5466 * (is this ever happens that we actually get str="" here?)
5468 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5469 //TODO: Can use on strings with \ too, just unbackslash() them?
5470 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5471 return xstrdup(str);
5474 argv[0] = (char*)str;
5476 list = expand_variables(argv, do_unbackslash
5477 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5478 : EXP_FLAG_SINGLEWORD
5481 if (!list[0] || list[1])
5482 bb_error_msg_and_die("BUG in varexp2");
5483 /* actually, just move string 2*sizeof(char*) bytes back */
5484 overlapping_strcpy((char*)list, list[0]);
5486 unbackslash((char*)list);
5487 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5491 /* Used for "eval" builtin */
5492 static char* expand_strvec_to_string(char **argv)
5496 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5497 /* Convert all NULs to spaces */
5502 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5503 bb_error_msg_and_die("BUG in varexp3");
5504 /* bash uses ' ' regardless of $IFS contents */
5509 overlapping_strcpy((char*)list, list[0]);
5510 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5514 static char **expand_assignments(char **argv, int count)
5519 G.expanded_assignments = p = NULL;
5520 /* Expand assignments into one string each */
5521 for (i = 0; i < count; i++) {
5522 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5524 G.expanded_assignments = NULL;
5529 static void switch_off_special_sigs(unsigned mask)
5532 while ((mask >>= 1) != 0) {
5537 if (G.traps[sig] && !G.traps[sig][0])
5538 /* trap is '', has to remain SIG_IGN */
5541 G.traps[sig] = NULL;
5543 /* We are here only if no trap or trap was not '' */
5544 install_sighandler(sig, SIG_DFL);
5550 void re_execute_shell(char ***to_free, const char *s,
5551 char *g_argv0, char **g_argv,
5552 char **builtin_argv) NORETURN;
5554 static void reset_traps_to_defaults(void)
5556 /* This function is always called in a child shell
5557 * after fork (not vfork, NOMMU doesn't use this function).
5562 /* Child shells are not interactive.
5563 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5564 * Testcase: (while :; do :; done) + ^Z should background.
5565 * Same goes for SIGTERM, SIGHUP, SIGINT.
5567 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5568 if (!G.traps && !mask)
5569 return; /* already no traps and no special sigs */
5571 /* Switch off special sigs */
5572 switch_off_special_sigs(mask);
5574 G_fatal_sig_mask = 0;
5576 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5577 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5578 * remain set in G.special_sig_mask */
5583 /* Reset all sigs to default except ones with empty traps */
5584 for (sig = 0; sig < NSIG; sig++) {
5586 continue; /* no trap: nothing to do */
5587 if (!G.traps[sig][0])
5588 continue; /* empty trap: has to remain SIG_IGN */
5589 /* sig has non-empty trap, reset it: */
5591 G.traps[sig] = NULL;
5592 /* There is no signal for trap 0 (EXIT) */
5595 install_sighandler(sig, pick_sighandler(sig));
5601 static void re_execute_shell(char ***to_free, const char *s,
5602 char *g_argv0, char **g_argv,
5603 char **builtin_argv) NORETURN;
5604 static void re_execute_shell(char ***to_free, const char *s,
5605 char *g_argv0, char **g_argv,
5606 char **builtin_argv)
5608 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5609 /* delims + 2 * (number of bytes in printed hex numbers) */
5610 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5611 char *heredoc_argv[4];
5612 struct variable *cur;
5613 # if ENABLE_HUSH_FUNCTIONS
5614 struct function *funcp;
5618 unsigned long long empty_trap_mask;
5620 if (!g_argv0) { /* heredoc */
5621 argv = heredoc_argv;
5622 argv[0] = (char *) G.argv0_for_re_execing;
5623 argv[1] = (char *) "-<";
5624 argv[2] = (char *) s;
5626 pp = &argv[3]; /* used as pointer to empty environment */
5632 if (pp) while (*pp++)
5635 empty_trap_mask = 0;
5638 for (sig = 1; sig < NSIG; sig++) {
5639 if (G.traps[sig] && !G.traps[sig][0])
5640 empty_trap_mask |= 1LL << sig;
5644 sprintf(param_buf, NOMMU_HACK_FMT
5645 , (unsigned) G.root_pid
5646 , (unsigned) G.root_ppid
5647 , (unsigned) G.last_bg_pid
5648 , (unsigned) G.last_exitcode
5651 IF_HUSH_LOOPS(, G.depth_of_loop)
5653 # undef NOMMU_HACK_FMT
5654 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5655 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5658 for (cur = G.top_var; cur; cur = cur->next) {
5659 if (!cur->flg_export || cur->flg_read_only)
5662 # if ENABLE_HUSH_FUNCTIONS
5663 for (funcp = G.top_func; funcp; funcp = funcp->next)
5669 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5670 *pp++ = (char *) G.argv0_for_re_execing;
5672 for (cur = G.top_var; cur; cur = cur->next) {
5673 if (strcmp(cur->varstr, hush_version_str) == 0)
5675 if (cur->flg_read_only) {
5676 *pp++ = (char *) "-R";
5677 *pp++ = cur->varstr;
5678 } else if (!cur->flg_export) {
5679 *pp++ = (char *) "-V";
5680 *pp++ = cur->varstr;
5683 # if ENABLE_HUSH_FUNCTIONS
5684 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5685 *pp++ = (char *) "-F";
5686 *pp++ = funcp->name;
5687 *pp++ = funcp->body_as_string;
5690 /* We can pass activated traps here. Say, -Tnn:trap_string
5692 * However, POSIX says that subshells reset signals with traps
5694 * I tested bash-3.2 and it not only does that with true subshells
5695 * of the form ( list ), but with any forked children shells.
5696 * I set trap "echo W" WINCH; and then tried:
5698 * { echo 1; sleep 20; echo 2; } &
5699 * while true; do echo 1; sleep 20; echo 2; break; done &
5700 * true | { echo 1; sleep 20; echo 2; } | cat
5702 * In all these cases sending SIGWINCH to the child shell
5703 * did not run the trap. If I add trap "echo V" WINCH;
5704 * _inside_ group (just before echo 1), it works.
5706 * I conclude it means we don't need to pass active traps here.
5708 *pp++ = (char *) "-c";
5711 while (*++builtin_argv)
5712 *pp++ = *builtin_argv;
5713 *pp++ = (char *) "";
5718 /* *pp = NULL; - is already there */
5722 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5723 /* Don't propagate SIG_IGN to the child */
5724 if (SPECIAL_JOBSTOP_SIGS != 0)
5725 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5726 execve(bb_busybox_exec_path, argv, pp);
5727 /* Fallback. Useful for init=/bin/hush usage etc */
5728 if (argv[0][0] == '/')
5729 execve(argv[0], argv, pp);
5730 xfunc_error_retval = 127;
5731 bb_error_msg_and_die("can't re-execute the shell");
5733 #endif /* !BB_MMU */
5736 static int run_and_free_list(struct pipe *pi);
5738 /* Executing from string: eval, sh -c '...'
5739 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5740 * end_trigger controls how often we stop parsing
5741 * NUL: parse all, execute, return
5742 * ';': parse till ';' or newline, execute, repeat till EOF
5744 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5746 /* Why we need empty flag?
5747 * An obscure corner case "false; ``; echo $?":
5748 * empty command in `` should still set $? to 0.
5749 * But we can't just set $? to 0 at the start,
5750 * this breaks "false; echo `echo $?`" case.
5754 struct pipe *pipe_list;
5756 #if ENABLE_HUSH_INTERACTIVE
5757 if (end_trigger == ';')
5758 inp->promptmode = 0; /* PS1 */
5760 pipe_list = parse_stream(NULL, inp, end_trigger);
5761 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5762 /* If we are in "big" script
5763 * (not in `cmd` or something similar)...
5765 if (pipe_list == ERR_PTR && end_trigger == ';') {
5766 /* Discard cached input (rest of line) */
5767 int ch = inp->last_char;
5768 while (ch != EOF && ch != '\n') {
5769 //bb_error_msg("Discarded:'%c'", ch);
5774 /* This stream isn't empty */
5778 if (!pipe_list && empty)
5779 G.last_exitcode = 0;
5782 debug_print_tree(pipe_list, 0);
5783 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5784 run_and_free_list(pipe_list);
5786 #if ENABLE_HUSH_FUNCTIONS
5787 if (G.flag_return_in_progress == 1)
5793 static void parse_and_run_string(const char *s)
5795 struct in_str input;
5796 setup_string_in_str(&input, s);
5797 parse_and_run_stream(&input, '\0');
5800 static void parse_and_run_file(FILE *f)
5802 struct in_str input;
5803 setup_file_in_str(&input, f);
5804 parse_and_run_stream(&input, ';');
5807 #if ENABLE_HUSH_TICK
5808 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5813 char **to_free = NULL;
5817 pid = BB_MMU ? xfork() : xvfork();
5818 if (pid == 0) { /* child */
5819 disable_restore_tty_pgrp_on_exit();
5820 /* Process substitution is not considered to be usual
5821 * 'command execution'.
5822 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5829 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5830 close(channel[0]); /* NB: close _first_, then move fd! */
5831 xmove_fd(channel[1], 1);
5832 /* Prevent it from trying to handle ctrl-z etc */
5833 IF_HUSH_JOB(G.run_list_level = 1;)
5834 /* Awful hack for `trap` or $(trap).
5836 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5837 * contains an example where "trap" is executed in a subshell:
5839 * save_traps=$(trap)
5841 * eval "$save_traps"
5843 * Standard does not say that "trap" in subshell shall print
5844 * parent shell's traps. It only says that its output
5845 * must have suitable form, but then, in the above example
5846 * (which is not supposed to be normative), it implies that.
5848 * bash (and probably other shell) does implement it
5849 * (traps are reset to defaults, but "trap" still shows them),
5850 * but as a result, "trap" logic is hopelessly messed up:
5853 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5854 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5855 * # true | trap <--- trap is in subshell - no output (ditto)
5856 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5857 * trap -- 'echo Ho' SIGWINCH
5858 * # echo `(trap)` <--- in subshell in subshell - output
5859 * trap -- 'echo Ho' SIGWINCH
5860 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5861 * trap -- 'echo Ho' SIGWINCH
5863 * The rules when to forget and when to not forget traps
5864 * get really complex and nonsensical.
5866 * Our solution: ONLY bare $(trap) or `trap` is special.
5868 s = skip_whitespace(s);
5869 if (strncmp(s, "trap", 4) == 0
5870 && skip_whitespace(s + 4)[0] == '\0'
5872 static const char *const argv[] = { NULL, NULL };
5873 builtin_trap((char**)argv);
5874 exit(0); /* not _exit() - we need to fflush */
5877 reset_traps_to_defaults();
5878 parse_and_run_string(s);
5879 _exit(G.last_exitcode);
5881 /* We re-execute after vfork on NOMMU. This makes this script safe:
5882 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5883 * huge=`cat BIG` # was blocking here forever
5886 re_execute_shell(&to_free,
5896 # if ENABLE_HUSH_FAST
5898 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5899 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5900 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5902 enable_restore_tty_pgrp_on_exit();
5907 close_on_exec_on(channel[0]);
5908 return xfdopen_for_read(channel[0]);
5911 /* Return code is exit status of the process that is run. */
5912 static int process_command_subs(o_string *dest, const char *s)
5915 struct in_str pipe_str;
5917 int status, ch, eol_cnt;
5919 fp = generate_stream_from_string(s, &pid);
5921 /* Now send results of command back into original context */
5922 setup_file_in_str(&pipe_str, fp);
5924 while ((ch = i_getch(&pipe_str)) != EOF) {
5930 o_addchr(dest, '\n');
5933 o_addQchr(dest, ch);
5936 debug_printf("done reading from `cmd` pipe, closing it\n");
5938 /* We need to extract exitcode. Test case
5939 * "true; echo `sleep 1; false` $?"
5941 safe_waitpid(pid, &status, 0);
5942 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5943 return WEXITSTATUS(status);
5945 #endif /* ENABLE_HUSH_TICK */
5948 static void setup_heredoc(struct redir_struct *redir)
5950 struct fd_pair pair;
5953 /* the _body_ of heredoc (misleading field name) */
5954 const char *heredoc = redir->rd_filename;
5961 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5962 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5966 len = strlen(heredoc);
5968 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5970 xmove_fd(pair.rd, redir->rd_fd);
5972 /* Try writing without forking. Newer kernels have
5973 * dynamically growing pipes. Must use non-blocking write! */
5976 written = write(pair.wr, heredoc, len);
5987 ndelay_off(pair.wr);
5989 /* Okay, pipe buffer was not big enough */
5990 /* Note: we must not create a stray child (bastard? :)
5991 * for the unsuspecting parent process. Child creates a grandchild
5992 * and exits before parent execs the process which consumes heredoc
5993 * (that exec happens after we return from this function) */
6000 disable_restore_tty_pgrp_on_exit();
6001 pid = BB_MMU ? xfork() : xvfork();
6005 close(redir->rd_fd); /* read side of the pipe */
6007 full_write(pair.wr, heredoc, len); /* may loop or block */
6010 /* Delegate blocking writes to another process */
6011 xmove_fd(pair.wr, STDOUT_FILENO);
6012 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6016 #if ENABLE_HUSH_FAST
6018 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6020 enable_restore_tty_pgrp_on_exit();
6026 wait(NULL); /* wait till child has died */
6029 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6030 * and stderr if they are redirected. */
6031 static int setup_redirects(struct command *prog, int squirrel[])
6034 struct redir_struct *redir;
6036 for (redir = prog->redirects; redir; redir = redir->next) {
6037 if (redir->rd_type == REDIRECT_HEREDOC2) {
6038 /* rd_fd<<HERE case */
6039 if (squirrel && redir->rd_fd < 3
6040 && squirrel[redir->rd_fd] < 0
6042 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6044 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6046 debug_printf_parse("set heredoc '%s'\n",
6047 redir->rd_filename);
6048 setup_heredoc(redir);
6052 if (redir->rd_dup == REDIRFD_TO_FILE) {
6053 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6055 if (redir->rd_filename == NULL) {
6056 /* Something went wrong in the parse.
6057 * Pretend it didn't happen */
6058 bb_error_msg("bug in redirect parse");
6061 mode = redir_table[redir->rd_type].mode;
6062 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6063 openfd = open_or_warn(p, mode);
6066 /* this could get lost if stderr has been redirected, but
6067 * bash and ash both lose it as well (though zsh doesn't!) */
6068 //what the above comment tries to say?
6072 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6073 openfd = redir->rd_dup;
6076 if (openfd != redir->rd_fd) {
6077 if (squirrel && redir->rd_fd < 3
6078 && squirrel[redir->rd_fd] < 0
6080 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6082 if (openfd == REDIRFD_CLOSE) {
6083 /* "n>-" means "close me" */
6084 close(redir->rd_fd);
6086 xdup2(openfd, redir->rd_fd);
6087 if (redir->rd_dup == REDIRFD_TO_FILE)
6095 static void restore_redirects(int squirrel[])
6098 for (i = 0; i < 3; i++) {
6101 /* We simply die on error */
6107 static char *find_in_path(const char *arg)
6110 const char *PATH = get_local_var_value("PATH");
6116 const char *end = strchrnul(PATH, ':');
6117 int sz = end - PATH; /* must be int! */
6121 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6123 /* We have xxx::yyyy in $PATH,
6124 * it means "use current dir" */
6127 if (access(ret, F_OK) == 0)
6140 static const struct built_in_command *find_builtin_helper(const char *name,
6141 const struct built_in_command *x,
6142 const struct built_in_command *end)
6145 if (strcmp(name, x->b_cmd) != 0) {
6149 debug_printf_exec("found builtin '%s'\n", name);
6154 static const struct built_in_command *find_builtin1(const char *name)
6156 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6158 static const struct built_in_command *find_builtin(const char *name)
6160 const struct built_in_command *x = find_builtin1(name);
6163 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6166 #if ENABLE_HUSH_FUNCTIONS
6167 static struct function **find_function_slot(const char *name)
6169 struct function **funcpp = &G.top_func;
6171 if (strcmp(name, (*funcpp)->name) == 0) {
6174 funcpp = &(*funcpp)->next;
6179 static const struct function *find_function(const char *name)
6181 const struct function *funcp = *find_function_slot(name);
6183 debug_printf_exec("found function '%s'\n", name);
6187 /* Note: takes ownership on name ptr */
6188 static struct function *new_function(char *name)
6190 struct function **funcpp = find_function_slot(name);
6191 struct function *funcp = *funcpp;
6193 if (funcp != NULL) {
6194 struct command *cmd = funcp->parent_cmd;
6195 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6197 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6199 /* Note: if !funcp->body, do not free body_as_string!
6200 * This is a special case of "-F name body" function:
6201 * body_as_string was not malloced! */
6203 free_pipe_list(funcp->body);
6205 free(funcp->body_as_string);
6209 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6210 cmd->argv[0] = funcp->name;
6211 cmd->group = funcp->body;
6213 cmd->group_as_string = funcp->body_as_string;
6217 debug_printf_exec("remembering new function '%s'\n", name);
6218 funcp = *funcpp = xzalloc(sizeof(*funcp));
6219 /*funcp->next = NULL;*/
6226 static void unset_func(const char *name)
6228 struct function **funcpp = find_function_slot(name);
6229 struct function *funcp = *funcpp;
6231 if (funcp != NULL) {
6232 debug_printf_exec("freeing function '%s'\n", funcp->name);
6233 *funcpp = funcp->next;
6234 /* funcp is unlinked now, deleting it.
6235 * Note: if !funcp->body, the function was created by
6236 * "-F name body", do not free ->body_as_string
6237 * and ->name as they were not malloced. */
6239 free_pipe_list(funcp->body);
6242 free(funcp->body_as_string);
6250 #define exec_function(to_free, funcp, argv) \
6251 exec_function(funcp, argv)
6253 static void exec_function(char ***to_free,
6254 const struct function *funcp,
6255 char **argv) NORETURN;
6256 static void exec_function(char ***to_free,
6257 const struct function *funcp,
6263 argv[0] = G.global_argv[0];
6264 G.global_argv = argv;
6268 /* On MMU, funcp->body is always non-NULL */
6269 n = run_list(funcp->body);
6273 re_execute_shell(to_free,
6274 funcp->body_as_string,
6281 static int run_function(const struct function *funcp, char **argv)
6287 save_and_replace_G_args(&sv, argv);
6289 /* "we are in function, ok to use return" */
6290 sv_flg = G.flag_return_in_progress;
6291 G.flag_return_in_progress = -1;
6292 # if ENABLE_HUSH_LOCAL
6293 G.func_nest_level++;
6296 /* On MMU, funcp->body is always non-NULL */
6299 /* Function defined by -F */
6300 parse_and_run_string(funcp->body_as_string);
6301 rc = G.last_exitcode;
6305 rc = run_list(funcp->body);
6308 # if ENABLE_HUSH_LOCAL
6310 struct variable *var;
6311 struct variable **var_pp;
6313 var_pp = &G.top_var;
6314 while ((var = *var_pp) != NULL) {
6315 if (var->func_nest_level < G.func_nest_level) {
6316 var_pp = &var->next;
6320 if (var->flg_export)
6321 bb_unsetenv(var->varstr);
6322 /* Remove from global list */
6323 *var_pp = var->next;
6329 G.func_nest_level--;
6332 G.flag_return_in_progress = sv_flg;
6334 restore_G_args(&sv, argv);
6338 #endif /* ENABLE_HUSH_FUNCTIONS */
6342 #define exec_builtin(to_free, x, argv) \
6343 exec_builtin(x, argv)
6345 #define exec_builtin(to_free, x, argv) \
6346 exec_builtin(to_free, argv)
6348 static void exec_builtin(char ***to_free,
6349 const struct built_in_command *x,
6350 char **argv) NORETURN;
6351 static void exec_builtin(char ***to_free,
6352 const struct built_in_command *x,
6358 rcode = x->b_function(argv);
6363 /* On NOMMU, we must never block!
6364 * Example: { sleep 99 | read line; } & echo Ok
6366 re_execute_shell(to_free,
6375 static void execvp_or_die(char **argv) NORETURN;
6376 static void execvp_or_die(char **argv)
6378 debug_printf_exec("execing '%s'\n", argv[0]);
6379 /* Don't propagate SIG_IGN to the child */
6380 if (SPECIAL_JOBSTOP_SIGS != 0)
6381 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6382 execvp(argv[0], argv);
6383 bb_perror_msg("can't execute '%s'", argv[0]);
6384 _exit(127); /* bash compat */
6387 #if ENABLE_HUSH_MODE_X
6388 static void dump_cmd_in_x_mode(char **argv)
6390 if (G_x_mode && argv) {
6391 /* We want to output the line in one write op */
6399 len += strlen(argv[n++]) + 1;
6405 p += sprintf(p, " %s", argv[n++]);
6413 # define dump_cmd_in_x_mode(argv) ((void)0)
6417 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6418 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6419 #define pseudo_exec(nommu_save, command, argv_expanded) \
6420 pseudo_exec(command, argv_expanded)
6423 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6425 * Don't exit() here. If you don't exec, use _exit instead.
6426 * The at_exit handlers apparently confuse the calling process,
6427 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6428 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6429 char **argv, int assignment_cnt,
6430 char **argv_expanded) NORETURN;
6431 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6432 char **argv, int assignment_cnt,
6433 char **argv_expanded)
6437 new_env = expand_assignments(argv, assignment_cnt);
6438 dump_cmd_in_x_mode(new_env);
6440 if (!argv[assignment_cnt]) {
6441 /* Case when we are here: ... | var=val | ...
6442 * (note that we do not exit early, i.e., do not optimize out
6443 * expand_assignments(): think about ... | var=`sleep 1` | ...
6445 free_strings(new_env);
6446 _exit(EXIT_SUCCESS);
6450 set_vars_and_save_old(new_env);
6451 free(new_env); /* optional */
6452 /* we can also destroy set_vars_and_save_old's return value,
6455 nommu_save->new_env = new_env;
6456 nommu_save->old_vars = set_vars_and_save_old(new_env);
6459 if (argv_expanded) {
6460 argv = argv_expanded;
6462 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6464 nommu_save->argv = argv;
6467 dump_cmd_in_x_mode(argv);
6469 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6470 if (strchr(argv[0], '/') != NULL)
6474 /* Check if the command matches any of the builtins.
6475 * Depending on context, this might be redundant. But it's
6476 * easier to waste a few CPU cycles than it is to figure out
6477 * if this is one of those cases.
6480 /* On NOMMU, it is more expensive to re-execute shell
6481 * just in order to run echo or test builtin.
6482 * It's better to skip it here and run corresponding
6483 * non-builtin later. */
6484 const struct built_in_command *x;
6485 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6487 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6490 #if ENABLE_HUSH_FUNCTIONS
6491 /* Check if the command matches any functions */
6493 const struct function *funcp = find_function(argv[0]);
6495 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6500 #if ENABLE_FEATURE_SH_STANDALONE
6501 /* Check if the command matches any busybox applets */
6503 int a = find_applet_by_name(argv[0]);
6505 # if BB_MMU /* see above why on NOMMU it is not allowed */
6506 if (APPLET_IS_NOEXEC(a)) {
6507 debug_printf_exec("running applet '%s'\n", argv[0]);
6508 run_applet_no_and_exit(a, argv);
6511 /* Re-exec ourselves */
6512 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6513 /* Don't propagate SIG_IGN to the child */
6514 if (SPECIAL_JOBSTOP_SIGS != 0)
6515 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6516 execv(bb_busybox_exec_path, argv);
6517 /* If they called chroot or otherwise made the binary no longer
6518 * executable, fall through */
6523 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6526 execvp_or_die(argv);
6529 /* Called after [v]fork() in run_pipe
6531 static void pseudo_exec(nommu_save_t *nommu_save,
6532 struct command *command,
6533 char **argv_expanded) NORETURN;
6534 static void pseudo_exec(nommu_save_t *nommu_save,
6535 struct command *command,
6536 char **argv_expanded)
6538 if (command->argv) {
6539 pseudo_exec_argv(nommu_save, command->argv,
6540 command->assignment_cnt, argv_expanded);
6543 if (command->group) {
6544 /* Cases when we are here:
6547 * ... | ( list ) | ...
6548 * ... | { list } | ...
6552 debug_printf_exec("pseudo_exec: run_list\n");
6553 reset_traps_to_defaults();
6554 rcode = run_list(command->group);
6555 /* OK to leak memory by not calling free_pipe_list,
6556 * since this process is about to exit */
6559 re_execute_shell(&nommu_save->argv_from_re_execing,
6560 command->group_as_string,
6567 /* Case when we are here: ... | >file */
6568 debug_printf_exec("pseudo_exec'ed null command\n");
6569 _exit(EXIT_SUCCESS);
6573 static const char *get_cmdtext(struct pipe *pi)
6579 /* This is subtle. ->cmdtext is created only on first backgrounding.
6580 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6581 * On subsequent bg argv is trashed, but we won't use it */
6584 argv = pi->cmds[0].argv;
6585 if (!argv || !argv[0]) {
6586 pi->cmdtext = xzalloc(1);
6592 len += strlen(*argv) + 1;
6596 argv = pi->cmds[0].argv;
6598 len = strlen(*argv);
6599 memcpy(p, *argv, len);
6607 static void insert_bg_job(struct pipe *pi)
6609 struct pipe *job, **jobp;
6612 /* Linear search for the ID of the job to use */
6614 for (job = G.job_list; job; job = job->next)
6615 if (job->jobid >= pi->jobid)
6616 pi->jobid = job->jobid + 1;
6618 /* Add job to the list of running jobs */
6620 while ((job = *jobp) != NULL)
6622 job = *jobp = xmalloc(sizeof(*job));
6624 *job = *pi; /* physical copy */
6626 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6627 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6628 for (i = 0; i < pi->num_cmds; i++) {
6629 job->cmds[i].pid = pi->cmds[i].pid;
6630 /* all other fields are not used and stay zero */
6632 job->cmdtext = xstrdup(get_cmdtext(pi));
6634 if (G_interactive_fd)
6635 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6636 G.last_jobid = job->jobid;
6639 static void remove_bg_job(struct pipe *pi)
6641 struct pipe *prev_pipe;
6643 if (pi == G.job_list) {
6644 G.job_list = pi->next;
6646 prev_pipe = G.job_list;
6647 while (prev_pipe->next != pi)
6648 prev_pipe = prev_pipe->next;
6649 prev_pipe->next = pi->next;
6652 G.last_jobid = G.job_list->jobid;
6657 /* Remove a backgrounded job */
6658 static void delete_finished_bg_job(struct pipe *pi)
6665 /* Check to see if any processes have exited -- if they
6666 * have, figure out why and see if a job has completed */
6667 static int checkjobs(struct pipe *fg_pipe)
6677 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6679 attributes = WUNTRACED;
6680 if (fg_pipe == NULL)
6681 attributes |= WNOHANG;
6684 #if ENABLE_HUSH_FAST
6685 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6686 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6687 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6688 /* There was neither fork nor SIGCHLD since last waitpid */
6689 /* Avoid doing waitpid syscall if possible */
6690 if (!G.we_have_children) {
6694 if (fg_pipe == NULL) { /* is WNOHANG set? */
6695 /* We have children, but they did not exit
6696 * or stop yet (we saw no SIGCHLD) */
6699 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6703 /* Do we do this right?
6704 * bash-3.00# sleep 20 | false
6706 * [3]+ Stopped sleep 20 | false
6707 * bash-3.00# echo $?
6708 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6709 * [hush 1.14.0: yes we do it right]
6716 #if ENABLE_HUSH_FAST
6717 i = G.count_SIGCHLD;
6719 childpid = waitpid(-1, &status, attributes);
6720 if (childpid <= 0) {
6721 if (childpid && errno != ECHILD)
6722 bb_perror_msg("waitpid");
6723 #if ENABLE_HUSH_FAST
6724 else { /* Until next SIGCHLD, waitpid's are useless */
6725 G.we_have_children = (childpid == 0);
6726 G.handled_SIGCHLD = i;
6727 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6732 dead = WIFEXITED(status) || WIFSIGNALED(status);
6735 if (WIFSTOPPED(status))
6736 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6737 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6738 if (WIFSIGNALED(status))
6739 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6740 childpid, WTERMSIG(status), WEXITSTATUS(status));
6741 if (WIFEXITED(status))
6742 debug_printf_jobs("pid %d exited, exitcode %d\n",
6743 childpid, WEXITSTATUS(status));
6745 /* Were we asked to wait for fg pipe? */
6747 i = fg_pipe->num_cmds;
6749 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6750 if (fg_pipe->cmds[i].pid != childpid)
6754 fg_pipe->cmds[i].pid = 0;
6755 fg_pipe->alive_cmds--;
6756 ex = WEXITSTATUS(status);
6757 /* bash prints killer signal's name for *last*
6758 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6759 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6761 if (WIFSIGNALED(status)) {
6762 int sig = WTERMSIG(status);
6763 if (i == fg_pipe->num_cmds-1)
6764 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6765 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6766 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6767 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6768 * Maybe we need to use sig | 128? */
6771 fg_pipe->cmds[i].cmd_exitcode = ex;
6773 fg_pipe->stopped_cmds++;
6775 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6776 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6777 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6778 /* All processes in fg pipe have exited or stopped */
6779 i = fg_pipe->num_cmds;
6781 rcode = fg_pipe->cmds[i].cmd_exitcode;
6782 /* usually last process gives overall exitstatus,
6783 * but with "set -o pipefail", last *failed* process does */
6784 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6787 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6788 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6789 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6790 * and "killall -STOP cat" */
6791 if (G_interactive_fd) {
6793 if (fg_pipe->alive_cmds != 0)
6794 insert_bg_job(fg_pipe);
6798 if (fg_pipe->alive_cmds == 0)
6801 /* There are still running processes in the fg pipe */
6802 goto wait_more; /* do waitpid again */
6804 /* it wasnt fg_pipe, look for process in bg pipes */
6808 /* We asked to wait for bg or orphaned children */
6809 /* No need to remember exitcode in this case */
6810 for (pi = G.job_list; pi; pi = pi->next) {
6811 for (i = 0; i < pi->num_cmds; i++) {
6812 if (pi->cmds[i].pid == childpid)
6813 goto found_pi_and_prognum;
6816 /* Happens when shell is used as init process (init=/bin/sh) */
6817 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6818 continue; /* do waitpid again */
6820 found_pi_and_prognum:
6823 pi->cmds[i].pid = 0;
6825 if (!pi->alive_cmds) {
6826 if (G_interactive_fd)
6827 printf(JOB_STATUS_FORMAT, pi->jobid,
6828 "Done", pi->cmdtext);
6829 delete_finished_bg_job(pi);
6836 } /* while (waitpid succeeds)... */
6842 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6845 int rcode = checkjobs(fg_pipe);
6846 if (G_saved_tty_pgrp) {
6847 /* Job finished, move the shell to the foreground */
6848 p = getpgrp(); /* our process group id */
6849 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6850 tcsetpgrp(G_interactive_fd, p);
6856 /* Start all the jobs, but don't wait for anything to finish.
6859 * Return code is normally -1, when the caller has to wait for children
6860 * to finish to determine the exit status of the pipe. If the pipe
6861 * is a simple builtin command, however, the action is done by the
6862 * time run_pipe returns, and the exit code is provided as the
6865 * Returns -1 only if started some children. IOW: we have to
6866 * mask out retvals of builtins etc with 0xff!
6868 * The only case when we do not need to [v]fork is when the pipe
6869 * is single, non-backgrounded, non-subshell command. Examples:
6870 * cmd ; ... { list } ; ...
6871 * cmd && ... { list } && ...
6872 * cmd || ... { list } || ...
6873 * If it is, then we can run cmd as a builtin, NOFORK,
6874 * or (if SH_STANDALONE) an applet, and we can run the { list }
6875 * with run_list. If it isn't one of these, we fork and exec cmd.
6877 * Cases when we must fork:
6878 * non-single: cmd | cmd
6879 * backgrounded: cmd & { list } &
6880 * subshell: ( list ) [&]
6882 #if !ENABLE_HUSH_MODE_X
6883 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6884 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6886 static int redirect_and_varexp_helper(char ***new_env_p,
6887 struct variable **old_vars_p,
6888 struct command *command,
6890 char **argv_expanded)
6892 /* setup_redirects acts on file descriptors, not FILEs.
6893 * This is perfect for work that comes after exec().
6894 * Is it really safe for inline use? Experimentally,
6895 * things seem to work. */
6896 int rcode = setup_redirects(command, squirrel);
6898 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6899 *new_env_p = new_env;
6900 dump_cmd_in_x_mode(new_env);
6901 dump_cmd_in_x_mode(argv_expanded);
6903 *old_vars_p = set_vars_and_save_old(new_env);
6907 static NOINLINE int run_pipe(struct pipe *pi)
6909 static const char *const null_ptr = NULL;
6913 struct command *command;
6914 char **argv_expanded;
6916 /* it is not always needed, but we aim to smaller code */
6917 int squirrel[] = { -1, -1, -1 };
6920 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6923 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6924 * Result should be 3 lines: q w e, qwe, q w e
6926 G.ifs = get_local_var_value("IFS");
6930 IF_HUSH_JOB(pi->pgrp = -1;)
6931 pi->stopped_cmds = 0;
6932 command = &pi->cmds[0];
6933 argv_expanded = NULL;
6935 if (pi->num_cmds != 1
6936 || pi->followup == PIPE_BG
6937 || command->cmd_type == CMD_SUBSHELL
6944 debug_printf_exec(": group:%p argv:'%s'\n",
6945 command->group, command->argv ? command->argv[0] : "NONE");
6947 if (command->group) {
6948 #if ENABLE_HUSH_FUNCTIONS
6949 if (command->cmd_type == CMD_FUNCDEF) {
6950 /* "executing" func () { list } */
6951 struct function *funcp;
6953 funcp = new_function(command->argv[0]);
6954 /* funcp->name is already set to argv[0] */
6955 funcp->body = command->group;
6957 funcp->body_as_string = command->group_as_string;
6958 command->group_as_string = NULL;
6960 command->group = NULL;
6961 command->argv[0] = NULL;
6962 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6963 funcp->parent_cmd = command;
6964 command->child_func = funcp;
6966 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6968 return EXIT_SUCCESS;
6972 debug_printf("non-subshell group\n");
6973 rcode = 1; /* exitcode if redir failed */
6974 if (setup_redirects(command, squirrel) == 0) {
6975 debug_printf_exec(": run_list\n");
6976 rcode = run_list(command->group) & 0xff;
6978 restore_redirects(squirrel);
6979 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6981 debug_printf_exec("run_pipe: return %d\n", rcode);
6985 argv = command->argv ? command->argv : (char **) &null_ptr;
6987 const struct built_in_command *x;
6988 #if ENABLE_HUSH_FUNCTIONS
6989 const struct function *funcp;
6993 char **new_env = NULL;
6994 struct variable *old_vars = NULL;
6996 if (argv[command->assignment_cnt] == NULL) {
6997 /* Assignments, but no command */
6998 /* Ensure redirects take effect (that is, create files).
6999 * Try "a=t >file" */
7000 #if 0 /* A few cases in testsuite fail with this code. FIXME */
7001 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7002 /* Set shell variables */
7006 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7007 /* Do we need to flag set_local_var() errors?
7008 * "assignment to readonly var" and "putenv error"
7013 /* Redirect error sets $? to 1. Otherwise,
7014 * if evaluating assignment value set $?, retain it.
7015 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7017 rcode = G.last_exitcode;
7018 /* Exit, _skipping_ variable restoring code: */
7019 goto clean_up_and_ret0;
7021 #else /* Older, bigger, but more correct code */
7023 rcode = setup_redirects(command, squirrel);
7024 restore_redirects(squirrel);
7025 /* Set shell variables */
7027 bb_putchar_stderr('+');
7029 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7031 fprintf(stderr, " %s", p);
7032 debug_printf_exec("set shell var:'%s'->'%s'\n",
7034 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7035 /* Do we need to flag set_local_var() errors?
7036 * "assignment to readonly var" and "putenv error"
7041 bb_putchar_stderr('\n');
7042 /* Redirect error sets $? to 1. Otherwise,
7043 * if evaluating assignment value set $?, retain it.
7044 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7046 rcode = G.last_exitcode;
7047 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7049 debug_printf_exec("run_pipe: return %d\n", rcode);
7054 /* Expand the rest into (possibly) many strings each */
7055 #if ENABLE_HUSH_BASH_COMPAT
7056 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7057 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7061 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7064 /* if someone gives us an empty string: `cmd with empty output` */
7065 if (!argv_expanded[0]) {
7066 free(argv_expanded);
7068 return G.last_exitcode;
7071 x = find_builtin(argv_expanded[0]);
7072 #if ENABLE_HUSH_FUNCTIONS
7075 funcp = find_function(argv_expanded[0]);
7079 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7080 debug_printf("exec with redirects only\n");
7081 rcode = setup_redirects(command, NULL);
7082 goto clean_up_and_ret1;
7085 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7088 debug_printf_exec(": builtin '%s' '%s'...\n",
7089 x->b_cmd, argv_expanded[1]);
7091 rcode = x->b_function(argv_expanded) & 0xff;
7094 #if ENABLE_HUSH_FUNCTIONS
7096 # if ENABLE_HUSH_LOCAL
7097 struct variable **sv;
7098 sv = G.shadowed_vars_pp;
7099 G.shadowed_vars_pp = &old_vars;
7101 debug_printf_exec(": function '%s' '%s'...\n",
7102 funcp->name, argv_expanded[1]);
7103 rcode = run_function(funcp, argv_expanded) & 0xff;
7104 # if ENABLE_HUSH_LOCAL
7105 G.shadowed_vars_pp = sv;
7111 unset_vars(new_env);
7113 /* clean_up_and_ret0: */
7114 restore_redirects(squirrel);
7116 free(argv_expanded);
7117 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7119 debug_printf_exec("run_pipe return %d\n", rcode);
7123 if (ENABLE_FEATURE_SH_NOFORK) {
7124 int n = find_applet_by_name(argv_expanded[0]);
7125 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7126 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7128 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7129 argv_expanded[0], argv_expanded[1]);
7130 rcode = run_nofork_applet(n, argv_expanded);
7132 goto clean_up_and_ret;
7135 /* It is neither builtin nor applet. We must fork. */
7139 /* NB: argv_expanded may already be created, and that
7140 * might include `cmd` runs! Do not rerun it! We *must*
7141 * use argv_expanded if it's non-NULL */
7143 /* Going to fork a child per each pipe member */
7148 while (cmd_no < pi->num_cmds) {
7149 struct fd_pair pipefds;
7151 volatile nommu_save_t nommu_save;
7152 nommu_save.new_env = NULL;
7153 nommu_save.old_vars = NULL;
7154 nommu_save.argv = NULL;
7155 nommu_save.argv_from_re_execing = NULL;
7157 command = &pi->cmds[cmd_no];
7159 if (command->argv) {
7160 debug_printf_exec(": pipe member '%s' '%s'...\n",
7161 command->argv[0], command->argv[1]);
7163 debug_printf_exec(": pipe member with no argv\n");
7166 /* pipes are inserted between pairs of commands */
7169 if (cmd_no < pi->num_cmds)
7170 xpiped_pair(pipefds);
7172 command->pid = BB_MMU ? fork() : vfork();
7173 if (!command->pid) { /* child */
7175 disable_restore_tty_pgrp_on_exit();
7176 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7178 /* Every child adds itself to new process group
7179 * with pgid == pid_of_first_child_in_pipe */
7180 if (G.run_list_level == 1 && G_interactive_fd) {
7183 if (pgrp < 0) /* true for 1st process only */
7185 if (setpgid(0, pgrp) == 0
7186 && pi->followup != PIPE_BG
7187 && G_saved_tty_pgrp /* we have ctty */
7189 /* We do it in *every* child, not just first,
7191 tcsetpgrp(G_interactive_fd, pgrp);
7195 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7196 /* 1st cmd in backgrounded pipe
7197 * should have its stdin /dev/null'ed */
7199 if (open(bb_dev_null, O_RDONLY))
7200 xopen("/", O_RDONLY);
7202 xmove_fd(next_infd, 0);
7204 xmove_fd(pipefds.wr, 1);
7207 /* Like bash, explicit redirects override pipes,
7208 * and the pipe fd is available for dup'ing. */
7209 if (setup_redirects(command, NULL))
7212 /* Stores to nommu_save list of env vars putenv'ed
7213 * (NOMMU, on MMU we don't need that) */
7214 /* cast away volatility... */
7215 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7216 /* pseudo_exec() does not return */
7219 /* parent or error */
7220 #if ENABLE_HUSH_FAST
7222 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7224 enable_restore_tty_pgrp_on_exit();
7226 /* Clean up after vforked child */
7227 free(nommu_save.argv);
7228 free(nommu_save.argv_from_re_execing);
7229 unset_vars(nommu_save.new_env);
7230 add_vars(nommu_save.old_vars);
7232 free(argv_expanded);
7233 argv_expanded = NULL;
7234 if (command->pid < 0) { /* [v]fork failed */
7235 /* Clearly indicate, was it fork or vfork */
7236 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7240 /* Second and next children need to know pid of first one */
7242 pi->pgrp = command->pid;
7248 if (cmd_no < pi->num_cmds)
7250 /* Pass read (output) pipe end to next iteration */
7251 next_infd = pipefds.rd;
7254 if (!pi->alive_cmds) {
7256 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7261 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7265 /* NB: called by pseudo_exec, and therefore must not modify any
7266 * global data until exec/_exit (we can be a child after vfork!) */
7267 static int run_list(struct pipe *pi)
7269 #if ENABLE_HUSH_CASE
7270 char *case_word = NULL;
7272 #if ENABLE_HUSH_LOOPS
7273 struct pipe *loop_top = NULL;
7274 char **for_lcur = NULL;
7275 char **for_list = NULL;
7277 smallint last_followup;
7279 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7280 smalluint cond_code = 0;
7282 enum { cond_code = 0 };
7285 smallint rword; /* RES_foo */
7286 smallint last_rword; /* ditto */
7289 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7292 #if ENABLE_HUSH_LOOPS
7293 /* Check syntax for "for" */
7296 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7297 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7299 /* current word is FOR or IN (BOLD in comments below) */
7300 if (cpipe->next == NULL) {
7301 syntax_error("malformed for");
7303 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7306 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7307 if (cpipe->next->res_word == RES_DO)
7309 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7310 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7311 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7313 syntax_error("malformed for");
7315 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7322 /* Past this point, all code paths should jump to ret: label
7323 * in order to return, no direct "return" statements please.
7324 * This helps to ensure that no memory is leaked. */
7332 last_rword = RES_XXXX;
7334 last_followup = PIPE_SEQ;
7335 rcode = G.last_exitcode;
7337 /* Go through list of pipes, (maybe) executing them. */
7338 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7342 IF_HAS_KEYWORDS(rword = pi->res_word;)
7343 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7344 rword, cond_code, last_rword);
7345 #if ENABLE_HUSH_LOOPS
7346 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7347 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7349 /* start of a loop: remember where loop starts */
7354 /* Still in the same "if...", "then..." or "do..." branch? */
7355 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7356 if ((rcode == 0 && last_followup == PIPE_OR)
7357 || (rcode != 0 && last_followup == PIPE_AND)
7359 /* It is "<true> || CMD" or "<false> && CMD"
7360 * and we should not execute CMD */
7361 debug_printf_exec("skipped cmd because of || or &&\n");
7362 last_followup = pi->followup;
7363 goto dont_check_jobs_but_continue;
7366 last_followup = pi->followup;
7367 IF_HAS_KEYWORDS(last_rword = rword;)
7370 if (rword == RES_THEN) {
7371 /* if false; then ... fi has exitcode 0! */
7372 G.last_exitcode = rcode = EXIT_SUCCESS;
7373 /* "if <false> THEN cmd": skip cmd */
7377 if (rword == RES_ELSE || rword == RES_ELIF) {
7378 /* "if <true> then ... ELSE/ELIF cmd":
7379 * skip cmd and all following ones */
7384 #if ENABLE_HUSH_LOOPS
7385 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7387 /* first loop through for */
7389 static const char encoded_dollar_at[] ALIGN1 = {
7390 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7391 }; /* encoded representation of "$@" */
7392 static const char *const encoded_dollar_at_argv[] = {
7393 encoded_dollar_at, NULL
7394 }; /* argv list with one element: "$@" */
7397 vals = (char**)encoded_dollar_at_argv;
7398 if (pi->next->res_word == RES_IN) {
7399 /* if no variable values after "in" we skip "for" */
7400 if (!pi->next->cmds[0].argv) {
7401 G.last_exitcode = rcode = EXIT_SUCCESS;
7402 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7405 vals = pi->next->cmds[0].argv;
7406 } /* else: "for var; do..." -> assume "$@" list */
7407 /* create list of variable values */
7408 debug_print_strings("for_list made from", vals);
7409 for_list = expand_strvec_to_strvec(vals);
7410 for_lcur = for_list;
7411 debug_print_strings("for_list", for_list);
7414 /* "for" loop is over, clean up */
7420 /* Insert next value from for_lcur */
7421 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7422 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7425 if (rword == RES_IN) {
7426 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7428 if (rword == RES_DONE) {
7429 continue; /* "done" has no cmds too */
7432 #if ENABLE_HUSH_CASE
7433 if (rword == RES_CASE) {
7434 case_word = expand_strvec_to_string(pi->cmds->argv);
7437 if (rword == RES_MATCH) {
7440 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7442 /* all prev words didn't match, does this one match? */
7443 argv = pi->cmds->argv;
7445 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7446 /* TODO: which FNM_xxx flags to use? */
7447 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7449 if (cond_code == 0) { /* match! we will execute this branch */
7450 free(case_word); /* make future "word)" stop */
7458 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7460 continue; /* not matched yet, skip this pipe */
7463 /* Just pressing <enter> in shell should check for jobs.
7464 * OTOH, in non-interactive shell this is useless
7465 * and only leads to extra job checks */
7466 if (pi->num_cmds == 0) {
7467 if (G_interactive_fd)
7468 goto check_jobs_and_continue;
7472 /* After analyzing all keywords and conditions, we decided
7473 * to execute this pipe. NB: have to do checkjobs(NULL)
7474 * after run_pipe to collect any background children,
7475 * even if list execution is to be stopped. */
7476 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7479 #if ENABLE_HUSH_LOOPS
7480 G.flag_break_continue = 0;
7482 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7484 /* We ran a builtin, function, or group.
7485 * rcode is already known
7486 * and we don't need to wait for anything. */
7487 G.last_exitcode = rcode;
7488 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7489 check_and_run_traps();
7490 #if ENABLE_HUSH_LOOPS
7491 /* Was it "break" or "continue"? */
7492 if (G.flag_break_continue) {
7493 smallint fbc = G.flag_break_continue;
7494 /* We might fall into outer *loop*,
7495 * don't want to break it too */
7497 G.depth_break_continue--;
7498 if (G.depth_break_continue == 0)
7499 G.flag_break_continue = 0;
7500 /* else: e.g. "continue 2" should *break* once, *then* continue */
7501 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7502 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7506 /* "continue": simulate end of loop */
7511 #if ENABLE_HUSH_FUNCTIONS
7512 if (G.flag_return_in_progress == 1) {
7517 } else if (pi->followup == PIPE_BG) {
7518 /* What does bash do with attempts to background builtins? */
7519 /* even bash 3.2 doesn't do that well with nested bg:
7520 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7521 * I'm NOT treating inner &'s as jobs */
7522 check_and_run_traps();
7524 if (G.run_list_level == 1)
7527 /* Last command's pid goes to $! */
7528 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7529 G.last_exitcode = rcode = EXIT_SUCCESS;
7530 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7533 if (G.run_list_level == 1 && G_interactive_fd) {
7534 /* Waits for completion, then fg's main shell */
7535 rcode = checkjobs_and_fg_shell(pi);
7536 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7537 check_and_run_traps();
7540 { /* This one just waits for completion */
7541 rcode = checkjobs(pi);
7542 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7543 check_and_run_traps();
7545 G.last_exitcode = rcode;
7549 /* Analyze how result affects subsequent commands */
7551 if (rword == RES_IF || rword == RES_ELIF)
7554 check_jobs_and_continue:
7556 dont_check_jobs_but_continue: ;
7557 #if ENABLE_HUSH_LOOPS
7558 /* Beware of "while false; true; do ..."! */
7560 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7561 /* check for RES_DONE is needed for "while ...; do \n done" case */
7563 if (rword == RES_WHILE) {
7565 /* "while false; do...done" - exitcode 0 */
7566 G.last_exitcode = rcode = EXIT_SUCCESS;
7567 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7571 if (rword == RES_UNTIL) {
7573 debug_printf_exec(": until expr is true: breaking\n");
7584 #if ENABLE_HUSH_LOOPS
7589 #if ENABLE_HUSH_CASE
7593 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7597 /* Select which version we will use */
7598 static int run_and_free_list(struct pipe *pi)
7601 debug_printf_exec("run_and_free_list entered\n");
7602 if (!G.o_opt[OPT_O_NOEXEC]) {
7603 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7604 rcode = run_list(pi);
7606 /* free_pipe_list has the side effect of clearing memory.
7607 * In the long run that function can be merged with run_list,
7608 * but doing that now would hobble the debugging effort. */
7610 debug_printf_exec("run_and_free_list return %d\n", rcode);
7615 static void install_sighandlers(unsigned mask)
7617 sighandler_t old_handler;
7619 while ((mask >>= 1) != 0) {
7623 old_handler = install_sighandler(sig, pick_sighandler(sig));
7624 /* POSIX allows shell to re-enable SIGCHLD
7625 * even if it was SIG_IGN on entry.
7626 * Therefore we skip IGN check for it:
7630 if (old_handler == SIG_IGN) {
7631 /* oops... restore back to IGN, and record this fact */
7632 install_sighandler(sig, old_handler);
7634 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7636 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7641 /* Called a few times only (or even once if "sh -c") */
7642 static void install_special_sighandlers(void)
7646 /* Which signals are shell-special? */
7647 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7648 if (G_interactive_fd) {
7649 mask |= SPECIAL_INTERACTIVE_SIGS;
7650 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7651 mask |= SPECIAL_JOBSTOP_SIGS;
7653 /* Careful, do not re-install handlers we already installed */
7654 if (G.special_sig_mask != mask) {
7655 unsigned diff = mask & ~G.special_sig_mask;
7656 G.special_sig_mask = mask;
7657 install_sighandlers(diff);
7663 /* Set handlers to restore tty pgrp and exit */
7664 static void install_fatal_sighandlers(void)
7668 /* We will restore tty pgrp on these signals */
7670 + (1 << SIGILL ) * HUSH_DEBUG
7671 + (1 << SIGFPE ) * HUSH_DEBUG
7672 + (1 << SIGBUS ) * HUSH_DEBUG
7673 + (1 << SIGSEGV) * HUSH_DEBUG
7674 + (1 << SIGTRAP) * HUSH_DEBUG
7676 /* bash 3.2 seems to handle these just like 'fatal' ones */
7679 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7680 * if we aren't interactive... but in this case
7681 * we never want to restore pgrp on exit, and this fn is not called
7683 /*+ (1 << SIGHUP )*/
7684 /*+ (1 << SIGTERM)*/
7685 /*+ (1 << SIGINT )*/
7687 G_fatal_sig_mask = mask;
7689 install_sighandlers(mask);
7693 static int set_mode(int state, char mode, const char *o_opt)
7698 G.o_opt[OPT_O_NOEXEC] = state;
7701 IF_HUSH_MODE_X(G_x_mode = state;)
7705 /* "set -+o" without parameter.
7706 * in bash, set -o produces this output:
7710 * We always use the second form.
7712 const char *p = o_opt_strings;
7715 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7721 idx = index_in_strings(o_opt_strings, o_opt);
7723 G.o_opt[idx] = state;
7727 return EXIT_FAILURE;
7729 return EXIT_SUCCESS;
7732 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7733 int hush_main(int argc, char **argv)
7736 OPT_login = (1 << 0),
7740 unsigned builtin_argc;
7742 struct variable *cur_var;
7743 struct variable *shell_ver;
7746 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7747 G.last_exitcode = EXIT_SUCCESS;
7748 #if ENABLE_HUSH_FAST
7749 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7752 G.argv0_for_re_execing = argv[0];
7754 /* Deal with HUSH_VERSION */
7755 shell_ver = xzalloc(sizeof(*shell_ver));
7756 shell_ver->flg_export = 1;
7757 shell_ver->flg_read_only = 1;
7758 /* Code which handles ${var<op>...} needs writable values for all variables,
7759 * therefore we xstrdup: */
7760 shell_ver->varstr = xstrdup(hush_version_str);
7761 /* Create shell local variables from the values
7762 * currently living in the environment */
7763 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7764 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7765 G.top_var = shell_ver;
7766 cur_var = G.top_var;
7769 char *value = strchr(*e, '=');
7770 if (value) { /* paranoia */
7771 cur_var->next = xzalloc(sizeof(*cur_var));
7772 cur_var = cur_var->next;
7773 cur_var->varstr = *e;
7774 cur_var->max_len = strlen(*e);
7775 cur_var->flg_export = 1;
7779 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7780 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7781 putenv(shell_ver->varstr);
7784 set_pwd_var(/*exp:*/ 1);
7785 /* bash also exports SHLVL and _,
7786 * and sets (but doesn't export) the following variables:
7788 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7789 * BASH_VERSION='3.2.0(1)-release'
7791 * MACHTYPE=i386-pc-linux-gnu
7793 * HOSTNAME=<xxxxxxxxxx>
7794 * PPID=<NNNNN> - we also do it elsewhere
7805 * PIPESTATUS=([0]="0")
7806 * HISTFILE=/<xxx>/.bash_history
7810 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7812 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7822 #if ENABLE_FEATURE_EDITING
7823 G.line_input_state = new_line_input_t(FOR_SHELL);
7826 /* Initialize some more globals to non-zero values */
7827 cmdedit_update_prompt();
7829 if (setjmp(die_jmp)) {
7830 /* xfunc has failed! die die die */
7831 /* no EXIT traps, this is an escape hatch! */
7833 hush_exit(xfunc_error_retval);
7836 /* Shell is non-interactive at first. We need to call
7837 * install_special_sighandlers() if we are going to execute "sh <script>",
7838 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7839 * If we later decide that we are interactive, we run install_special_sighandlers()
7840 * in order to intercept (more) signals.
7844 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7845 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7848 opt = getopt(argc, argv, "+c:xinsl"
7851 # if ENABLE_HUSH_FUNCTIONS
7861 * sh ... -c 'script'
7862 * sh ... -c 'script' ARG0 [ARG1...]
7863 * On NOMMU, if builtin_argc != 0,
7864 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7865 * "" needs to be replaced with NULL
7866 * and BARGV vector fed to builtin function.
7867 * Note: the form without ARG0 never happens:
7868 * sh ... -c 'builtin' BARGV... ""
7871 G.root_pid = getpid();
7872 G.root_ppid = getppid();
7874 G.global_argv = argv + optind;
7875 G.global_argc = argc - optind;
7877 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7878 const struct built_in_command *x;
7880 install_special_sighandlers();
7881 x = find_builtin(optarg);
7882 if (x) { /* paranoia */
7883 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7884 G.global_argv += builtin_argc;
7885 G.global_argv[-1] = NULL; /* replace "" */
7887 G.last_exitcode = x->b_function(argv + optind - 1);
7891 if (!G.global_argv[0]) {
7892 /* -c 'script' (no params): prevent empty $0 */
7893 G.global_argv--; /* points to argv[i] of 'script' */
7894 G.global_argv[0] = argv[0];
7896 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7897 install_special_sighandlers();
7898 parse_and_run_string(optarg);
7901 /* Well, we cannot just declare interactiveness,
7902 * we have to have some stuff (ctty, etc) */
7903 /* G_interactive_fd++; */
7906 /* "-s" means "read from stdin", but this is how we always
7907 * operate, so simply do nothing here. */
7913 case '<': /* "big heredoc" support */
7914 full_write1_str(optarg);
7917 unsigned long long empty_trap_mask;
7919 G.root_pid = bb_strtou(optarg, &optarg, 16);
7921 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7923 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7925 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7927 builtin_argc = bb_strtou(optarg, &optarg, 16);
7929 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7930 if (empty_trap_mask != 0) {
7932 install_special_sighandlers();
7933 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7934 for (sig = 1; sig < NSIG; sig++) {
7935 if (empty_trap_mask & (1LL << sig)) {
7936 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7937 install_sighandler(sig, SIG_IGN);
7941 # if ENABLE_HUSH_LOOPS
7943 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7949 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7951 # if ENABLE_HUSH_FUNCTIONS
7953 struct function *funcp = new_function(optarg);
7954 /* funcp->name is already set to optarg */
7955 /* funcp->body is set to NULL. It's a special case. */
7956 funcp->body_as_string = argv[optind];
7964 if (set_mode(1, opt, NULL) == 0) /* no error */
7968 fprintf(stderr, "Usage: sh [FILE]...\n"
7969 " or: sh -c command [args]...\n\n");
7975 } /* option parsing loop */
7977 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7978 G.global_argc = argc - (optind - 1);
7979 G.global_argv = argv + (optind - 1);
7980 G.global_argv[0] = argv[0];
7983 G.root_pid = getpid();
7984 G.root_ppid = getppid();
7987 /* If we are login shell... */
7988 if (flags & OPT_login) {
7990 debug_printf("sourcing /etc/profile\n");
7991 input = fopen_for_read("/etc/profile");
7992 if (input != NULL) {
7993 close_on_exec_on(fileno(input));
7994 install_special_sighandlers();
7995 parse_and_run_file(input);
7998 /* bash: after sourcing /etc/profile,
7999 * tries to source (in the given order):
8000 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8001 * stopping on first found. --noprofile turns this off.
8002 * bash also sources ~/.bash_logout on exit.
8003 * If called as sh, skips .bash_XXX files.
8007 if (G.global_argv[1]) {
8010 * "bash <script>" (which is never interactive (unless -i?))
8011 * sources $BASH_ENV here (without scanning $PATH).
8012 * If called as sh, does the same but with $ENV.
8016 debug_printf("running script '%s'\n", G.global_argv[0]);
8017 input = xfopen_for_read(G.global_argv[0]);
8018 close_on_exec_on(fileno(input));
8019 install_special_sighandlers();
8020 parse_and_run_file(input);
8021 #if ENABLE_FEATURE_CLEAN_UP
8027 /* Up to here, shell was non-interactive. Now it may become one.
8028 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8031 /* A shell is interactive if the '-i' flag was given,
8032 * or if all of the following conditions are met:
8034 * no arguments remaining or the -s flag given
8035 * standard input is a terminal
8036 * standard output is a terminal
8037 * Refer to Posix.2, the description of the 'sh' utility.
8040 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8041 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8042 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8043 if (G_saved_tty_pgrp < 0)
8044 G_saved_tty_pgrp = 0;
8046 /* try to dup stdin to high fd#, >= 255 */
8047 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8048 if (G_interactive_fd < 0) {
8049 /* try to dup to any fd */
8050 G_interactive_fd = dup(STDIN_FILENO);
8051 if (G_interactive_fd < 0) {
8053 G_interactive_fd = 0;
8054 G_saved_tty_pgrp = 0;
8057 // TODO: track & disallow any attempts of user
8058 // to (inadvertently) close/redirect G_interactive_fd
8060 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8061 if (G_interactive_fd) {
8062 close_on_exec_on(G_interactive_fd);
8064 if (G_saved_tty_pgrp) {
8065 /* If we were run as 'hush &', sleep until we are
8066 * in the foreground (tty pgrp == our pgrp).
8067 * If we get started under a job aware app (like bash),
8068 * make sure we are now in charge so we don't fight over
8069 * who gets the foreground */
8071 pid_t shell_pgrp = getpgrp();
8072 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8073 if (G_saved_tty_pgrp == shell_pgrp)
8075 /* send TTIN to ourself (should stop us) */
8076 kill(- shell_pgrp, SIGTTIN);
8080 /* Install more signal handlers */
8081 install_special_sighandlers();
8083 if (G_saved_tty_pgrp) {
8084 /* Set other signals to restore saved_tty_pgrp */
8085 install_fatal_sighandlers();
8086 /* Put ourselves in our own process group
8087 * (bash, too, does this only if ctty is available) */
8088 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8089 /* Grab control of the terminal */
8090 tcsetpgrp(G_interactive_fd, getpid());
8092 /* -1 is special - makes xfuncs longjmp, not exit
8093 * (we reset die_sleep = 0 whereever we [v]fork) */
8094 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8096 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8098 const char *hp = get_local_var_value("HISTFILE");
8100 hp = get_local_var_value("HOME");
8102 hp = concat_path_file(hp, ".hush_history");
8107 G.line_input_state->hist_file = hp;
8108 //set_local_var(xasprintf("HISTFILE=%s", ...));
8110 # if ENABLE_FEATURE_SH_HISTFILESIZE
8111 hp = get_local_var_value("HISTFILESIZE");
8112 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8117 install_special_sighandlers();
8119 #elif ENABLE_HUSH_INTERACTIVE
8120 /* No job control compiled in, only prompt/line editing */
8121 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8122 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8123 if (G_interactive_fd < 0) {
8124 /* try to dup to any fd */
8125 G_interactive_fd = dup(STDIN_FILENO);
8126 if (G_interactive_fd < 0)
8128 G_interactive_fd = 0;
8131 if (G_interactive_fd) {
8132 close_on_exec_on(G_interactive_fd);
8134 install_special_sighandlers();
8136 /* We have interactiveness code disabled */
8137 install_special_sighandlers();
8140 * if interactive but not a login shell, sources ~/.bashrc
8141 * (--norc turns this off, --rcfile <file> overrides)
8144 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8145 /* note: ash and hush share this string */
8146 printf("\n\n%s %s\n"
8147 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8150 "hush - the humble shell"
8154 parse_and_run_file(stdin);
8157 hush_exit(G.last_exitcode);
8162 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8163 int msh_main(int argc, char **argv)
8165 //bb_error_msg("msh is deprecated, please use hush instead");
8166 return hush_main(argc, argv);
8174 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8179 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8186 return applet_main_func(argc, argv - argc);
8189 static int FAST_FUNC builtin_test(char **argv)
8191 return run_applet_main(argv, test_main);
8194 static int FAST_FUNC builtin_echo(char **argv)
8196 return run_applet_main(argv, echo_main);
8200 static int FAST_FUNC builtin_printf(char **argv)
8202 return run_applet_main(argv, printf_main);
8206 static char **skip_dash_dash(char **argv)
8209 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8214 static int FAST_FUNC builtin_eval(char **argv)
8216 int rcode = EXIT_SUCCESS;
8218 argv = skip_dash_dash(argv);
8220 char *str = expand_strvec_to_string(argv);
8222 * eval "echo Hi; done" ("done" is syntax error):
8223 * "echo Hi" will not execute too.
8225 parse_and_run_string(str);
8227 rcode = G.last_exitcode;
8232 static int FAST_FUNC builtin_cd(char **argv)
8236 argv = skip_dash_dash(argv);
8238 if (newdir == NULL) {
8239 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8240 * bash says "bash: cd: HOME not set" and does nothing
8243 const char *home = get_local_var_value("HOME");
8244 newdir = home ? home : "/";
8246 if (chdir(newdir)) {
8247 /* Mimic bash message exactly */
8248 bb_perror_msg("cd: %s", newdir);
8249 return EXIT_FAILURE;
8251 /* Read current dir (get_cwd(1) is inside) and set PWD.
8252 * Note: do not enforce exporting. If PWD was unset or unexported,
8253 * set it again, but do not export. bash does the same.
8255 set_pwd_var(/*exp:*/ 0);
8256 return EXIT_SUCCESS;
8259 static int FAST_FUNC builtin_exec(char **argv)
8261 argv = skip_dash_dash(argv);
8262 if (argv[0] == NULL)
8263 return EXIT_SUCCESS; /* bash does this */
8265 /* Careful: we can end up here after [v]fork. Do not restore
8266 * tty pgrp then, only top-level shell process does that */
8267 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8268 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8270 /* TODO: if exec fails, bash does NOT exit! We do.
8271 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8272 * and tcsetpgrp, and this is inherently racy.
8274 execvp_or_die(argv);
8277 static int FAST_FUNC builtin_exit(char **argv)
8279 debug_printf_exec("%s()\n", __func__);
8281 /* interactive bash:
8282 * # trap "echo EEE" EXIT
8285 * There are stopped jobs.
8286 * (if there are _stopped_ jobs, running ones don't count)
8289 * EEE (then bash exits)
8291 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8294 /* note: EXIT trap is run by hush_exit */
8295 argv = skip_dash_dash(argv);
8296 if (argv[0] == NULL)
8297 hush_exit(G.last_exitcode);
8298 /* mimic bash: exit 123abc == exit 255 + error msg */
8299 xfunc_error_retval = 255;
8300 /* bash: exit -2 == exit 254, no error msg */
8301 hush_exit(xatoi(argv[0]) & 0xff);
8304 static void print_escaped(const char *s)
8309 const char *p = strchrnul(s, '\'');
8310 /* print 'xxxx', possibly just '' */
8311 printf("'%.*s'", (int)(p - s), s);
8316 /* s points to '; print "'''...'''" */
8318 do putchar('\''); while (*++s == '\'');
8323 #if !ENABLE_HUSH_LOCAL
8324 #define helper_export_local(argv, exp, lvl) \
8325 helper_export_local(argv, exp)
8327 static void helper_export_local(char **argv, int exp, int lvl)
8331 char *name_end = strchrnul(name, '=');
8333 /* So far we do not check that name is valid (TODO?) */
8335 if (*name_end == '\0') {
8336 struct variable *var, **vpp;
8338 vpp = get_ptr_to_local_var(name, name_end - name);
8339 var = vpp ? *vpp : NULL;
8341 if (exp == -1) { /* unexporting? */
8342 /* export -n NAME (without =VALUE) */
8344 var->flg_export = 0;
8345 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8347 } /* else: export -n NOT_EXISTING_VAR: no-op */
8350 if (exp == 1) { /* exporting? */
8351 /* export NAME (without =VALUE) */
8353 var->flg_export = 1;
8354 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8355 putenv(var->varstr);
8359 /* Exporting non-existing variable.
8360 * bash does not put it in environment,
8361 * but remembers that it is exported,
8362 * and does put it in env when it is set later.
8363 * We just set it to "" and export. */
8364 /* Or, it's "local NAME" (without =VALUE).
8365 * bash sets the value to "". */
8366 name = xasprintf("%s=", name);
8368 /* (Un)exporting/making local NAME=VALUE */
8369 name = xstrdup(name);
8371 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8375 static int FAST_FUNC builtin_export(char **argv)
8377 unsigned opt_unexport;
8379 #if ENABLE_HUSH_EXPORT_N
8380 /* "!": do not abort on errors */
8381 opt_unexport = getopt32(argv, "!n");
8382 if (opt_unexport == (uint32_t)-1)
8383 return EXIT_FAILURE;
8390 if (argv[0] == NULL) {
8397 /* ash emits: export VAR='VAL'
8398 * bash: declare -x VAR="VAL"
8399 * we follow ash example */
8400 const char *s = *e++;
8401 const char *p = strchr(s, '=');
8403 if (!p) /* wtf? take next variable */
8406 printf("export %.*s", (int)(p - s) + 1, s);
8407 print_escaped(p + 1);
8411 /*fflush_all(); - done after each builtin anyway */
8413 return EXIT_SUCCESS;
8416 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8418 return EXIT_SUCCESS;
8421 #if ENABLE_HUSH_LOCAL
8422 static int FAST_FUNC builtin_local(char **argv)
8424 if (G.func_nest_level == 0) {
8425 bb_error_msg("%s: not in a function", argv[0]);
8426 return EXIT_FAILURE; /* bash compat */
8428 helper_export_local(argv, 0, G.func_nest_level);
8429 return EXIT_SUCCESS;
8433 static int FAST_FUNC builtin_trap(char **argv)
8439 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8444 /* No args: print all trapped */
8445 for (i = 0; i < NSIG; ++i) {
8448 print_escaped(G.traps[i]);
8449 /* note: bash adds "SIG", but only if invoked
8450 * as "bash". If called as "sh", or if set -o posix,
8451 * then it prints short signal names.
8452 * We are printing short names: */
8453 printf(" %s\n", get_signame(i));
8456 /*fflush_all(); - done after each builtin anyway */
8457 return EXIT_SUCCESS;
8461 /* If first arg is a number: reset all specified signals */
8462 sig = bb_strtou(*argv, NULL, 10);
8468 sighandler_t handler;
8470 sig = get_signum(*argv++);
8471 if (sig < 0 || sig >= NSIG) {
8473 /* Mimic bash message exactly */
8474 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8479 G.traps[sig] = xstrdup(new_cmd);
8481 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8482 get_signame(sig), sig, G.traps[sig]);
8484 /* There is no signal for 0 (EXIT) */
8489 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8491 /* We are removing trap handler */
8492 handler = pick_sighandler(sig);
8493 install_sighandler(sig, handler);
8498 if (!argv[1]) { /* no second arg */
8499 bb_error_msg("trap: invalid arguments");
8500 return EXIT_FAILURE;
8503 /* First arg is "-": reset all specified to default */
8504 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8505 /* Everything else: set arg as signal handler
8506 * (includes "" case, which ignores signal) */
8507 if (argv[0][0] == '-') {
8508 if (argv[0][1] == '\0') { /* "-" */
8509 /* new_cmd remains NULL: "reset these sigs" */
8512 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8515 /* else: "-something", no special meaning */
8520 goto process_sig_list;
8523 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8524 static int FAST_FUNC builtin_type(char **argv)
8526 int ret = EXIT_SUCCESS;
8532 if (0) {} /* make conditional compile easier below */
8533 /*else if (find_alias(*argv))
8534 type = "an alias";*/
8535 #if ENABLE_HUSH_FUNCTIONS
8536 else if (find_function(*argv))
8537 type = "a function";
8539 else if (find_builtin(*argv))
8540 type = "a shell builtin";
8541 else if ((path = find_in_path(*argv)) != NULL)
8544 bb_error_msg("type: %s: not found", *argv);
8549 printf("%s is %s\n", *argv, type);
8557 /* built-in 'fg' and 'bg' handler */
8558 static int FAST_FUNC builtin_fg_bg(char **argv)
8563 if (!G_interactive_fd)
8564 return EXIT_FAILURE;
8566 /* If they gave us no args, assume they want the last backgrounded task */
8568 for (pi = G.job_list; pi; pi = pi->next) {
8569 if (pi->jobid == G.last_jobid) {
8573 bb_error_msg("%s: no current job", argv[0]);
8574 return EXIT_FAILURE;
8576 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8577 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8578 return EXIT_FAILURE;
8580 for (pi = G.job_list; pi; pi = pi->next) {
8581 if (pi->jobid == jobnum) {
8585 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8586 return EXIT_FAILURE;
8588 /* TODO: bash prints a string representation
8589 * of job being foregrounded (like "sleep 1 | cat") */
8590 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8591 /* Put the job into the foreground. */
8592 tcsetpgrp(G_interactive_fd, pi->pgrp);
8595 /* Restart the processes in the job */
8596 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8597 for (i = 0; i < pi->num_cmds; i++) {
8598 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8600 pi->stopped_cmds = 0;
8602 i = kill(- pi->pgrp, SIGCONT);
8604 if (errno == ESRCH) {
8605 delete_finished_bg_job(pi);
8606 return EXIT_SUCCESS;
8608 bb_perror_msg("kill (SIGCONT)");
8611 if (argv[0][0] == 'f') {
8613 return checkjobs_and_fg_shell(pi);
8615 return EXIT_SUCCESS;
8619 #if ENABLE_HUSH_HELP
8620 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8622 const struct built_in_command *x;
8625 "Built-in commands:\n"
8626 "------------------\n");
8627 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8629 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8632 return EXIT_SUCCESS;
8636 #if MAX_HISTORY && ENABLE_FEATURE_EDITING
8637 static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8639 show_history(G.line_input_state);
8640 return EXIT_SUCCESS;
8645 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8648 const char *status_string;
8650 for (job = G.job_list; job; job = job->next) {
8651 if (job->alive_cmds == job->stopped_cmds)
8652 status_string = "Stopped";
8654 status_string = "Running";
8656 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8658 return EXIT_SUCCESS;
8663 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8668 # ifdef M_TRIM_THRESHOLD
8669 /* Optional. Reduces probability of false positives */
8672 /* Crude attempt to find where "free memory" starts,
8673 * sans fragmentation. */
8675 l = (unsigned long)p;
8678 if (l < (unsigned long)p) l = (unsigned long)p;
8681 if (!G.memleak_value)
8682 G.memleak_value = l;
8684 l -= G.memleak_value;
8691 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8696 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8699 return EXIT_SUCCESS;
8702 /* Interruptibility of read builtin in bash
8703 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8705 * Empty trap makes read ignore corresponding signal, for any signal.
8708 * - terminates non-interactive shell;
8709 * - interrupts read in interactive shell;
8710 * if it has non-empty trap:
8711 * - executes trap and returns to command prompt in interactive shell;
8712 * - executes trap and returns to read in non-interactive shell;
8714 * - is ignored (does not interrupt) read in interactive shell;
8715 * - terminates non-interactive shell;
8716 * if it has non-empty trap:
8717 * - executes trap and returns to read;
8719 * - terminates shell (regardless of interactivity);
8720 * if it has non-empty trap:
8721 * - executes trap and returns to read;
8723 static int FAST_FUNC builtin_read(char **argv)
8733 /* "!": do not abort on errors.
8734 * Option string must start with "sr" to match BUILTIN_READ_xxx
8736 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8737 if (read_flags == (uint32_t)-1)
8738 return EXIT_FAILURE;
8740 ifs = get_local_var_value("IFS"); /* can be NULL */
8743 r = shell_builtin_read(set_local_var_from_halves,
8753 if ((uintptr_t)r == 1 && errno == EINTR) {
8754 unsigned sig = check_and_run_traps();
8755 if (sig && sig != SIGINT)
8759 if ((uintptr_t)r > 1) {
8760 bb_error_msg("%s", r);
8761 r = (char*)(uintptr_t)1;
8764 return (uintptr_t)r;
8767 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8768 * built-in 'set' handler
8770 * set [-abCefhmnuvx] [-o option] [argument...]
8771 * set [+abCefhmnuvx] [+o option] [argument...]
8772 * set -- [argument...]
8775 * Implementations shall support the options in both their hyphen and
8776 * plus-sign forms. These options can also be specified as options to sh.
8778 * Write out all variables and their values: set
8779 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8780 * Turn on the -x and -v options: set -xv
8781 * Unset all positional parameters: set --
8782 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8783 * Set the positional parameters to the expansion of x, even if x expands
8784 * with a leading '-' or '+': set -- $x
8786 * So far, we only support "set -- [argument...]" and some of the short names.
8788 static int FAST_FUNC builtin_set(char **argv)
8791 char **pp, **g_argv;
8792 char *arg = *++argv;
8796 for (e = G.top_var; e; e = e->next)
8798 return EXIT_SUCCESS;
8802 if (strcmp(arg, "--") == 0) {
8806 if (arg[0] != '+' && arg[0] != '-')
8808 for (n = 1; arg[n]; ++n) {
8809 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8811 if (arg[n] == 'o' && argv[1])
8814 } while ((arg = *++argv) != NULL);
8815 /* Now argv[0] is 1st argument */
8818 return EXIT_SUCCESS;
8821 /* NB: G.global_argv[0] ($0) is never freed/changed */
8822 g_argv = G.global_argv;
8823 if (G.global_args_malloced) {
8829 G.global_args_malloced = 1;
8830 pp = xzalloc(sizeof(pp[0]) * 2);
8831 pp[0] = g_argv[0]; /* retain $0 */
8834 /* This realloc's G.global_argv */
8835 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8842 return EXIT_SUCCESS;
8844 /* Nothing known, so abort */
8846 bb_error_msg("set: %s: invalid option", arg);
8847 return EXIT_FAILURE;
8850 static int FAST_FUNC builtin_shift(char **argv)
8853 argv = skip_dash_dash(argv);
8857 if (n >= 0 && n < G.global_argc) {
8858 if (G.global_args_malloced) {
8861 free(G.global_argv[m++]);
8864 memmove(&G.global_argv[1], &G.global_argv[n+1],
8865 G.global_argc * sizeof(G.global_argv[0]));
8866 return EXIT_SUCCESS;
8868 return EXIT_FAILURE;
8871 static int FAST_FUNC builtin_source(char **argv)
8873 char *arg_path, *filename;
8876 #if ENABLE_HUSH_FUNCTIONS
8880 argv = skip_dash_dash(argv);
8883 /* bash says: "bash: .: filename argument required" */
8884 return 2; /* bash compat */
8887 if (!strchr(filename, '/')) {
8888 arg_path = find_in_path(filename);
8890 filename = arg_path;
8892 input = fopen_or_warn(filename, "r");
8895 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8896 /* POSIX: non-interactive shell should abort here,
8897 * not merely fail. So far no one complained :)
8899 return EXIT_FAILURE;
8901 close_on_exec_on(fileno(input));
8903 #if ENABLE_HUSH_FUNCTIONS
8904 sv_flg = G.flag_return_in_progress;
8905 /* "we are inside sourced file, ok to use return" */
8906 G.flag_return_in_progress = -1;
8909 save_and_replace_G_args(&sv, argv);
8911 parse_and_run_file(input);
8915 restore_G_args(&sv, argv);
8916 #if ENABLE_HUSH_FUNCTIONS
8917 G.flag_return_in_progress = sv_flg;
8920 return G.last_exitcode;
8923 static int FAST_FUNC builtin_umask(char **argv)
8929 argv = skip_dash_dash(argv);
8931 mode_t old_mask = mask;
8934 rc = bb_parse_mode(argv[0], &mask);
8939 * bash: umask: 'q': invalid symbolic mode operator
8940 * bash: umask: 999: octal number out of range
8942 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8947 printf("%04o\n", (unsigned) mask);
8948 /* fall through and restore mask which we set to 0 */
8952 return !rc; /* rc != 0 - success */
8955 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8956 static int FAST_FUNC builtin_unset(char **argv)
8961 /* "!": do not abort on errors */
8962 /* "+": stop at 1st non-option */
8963 opts = getopt32(argv, "!+vf");
8964 if (opts == (unsigned)-1)
8965 return EXIT_FAILURE;
8967 bb_error_msg("unset: -v and -f are exclusive");
8968 return EXIT_FAILURE;
8974 if (!(opts & 2)) { /* not -f */
8975 if (unset_local_var(*argv)) {
8976 /* unset <nonexistent_var> doesn't fail.
8977 * Error is when one tries to unset RO var.
8978 * Message was printed by unset_local_var. */
8982 #if ENABLE_HUSH_FUNCTIONS
8992 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8993 static int FAST_FUNC builtin_wait(char **argv)
8995 int ret = EXIT_SUCCESS;
8998 argv = skip_dash_dash(argv);
8999 if (argv[0] == NULL) {
9000 /* Don't care about wait results */
9001 /* Note 1: must wait until there are no more children */
9002 /* Note 2: must be interruptible */
9004 * $ sleep 3 & sleep 6 & wait
9009 * $ sleep 3 & sleep 6 & wait
9013 * ^C <-- after ~4 sec from keyboard
9018 sigset_t oldset, allsigs;
9020 /* waitpid is not interruptible by SA_RESTARTed
9021 * signals which we use. Thus, this ugly dance:
9024 /* Make sure possible SIGCHLD is stored in kernel's
9025 * pending signal mask before we call waitpid.
9026 * Or else we may race with SIGCHLD, lose it,
9027 * and get stuck in sigwaitinfo...
9029 sigfillset(&allsigs);
9030 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9032 if (!sigisemptyset(&G.pending_set)) {
9033 /* Crap! we raced with some signal! */
9038 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9039 if (errno == ECHILD) {
9040 sigprocmask(SIG_SETMASK, &oldset, NULL);
9044 /* Wait for SIGCHLD or any other signal */
9045 //sig = sigwaitinfo(&allsigs, NULL);
9046 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9047 /* Note: sigsuspend invokes signal handler */
9048 sigsuspend(&oldset);
9050 sigprocmask(SIG_SETMASK, &oldset, NULL);
9052 /* So, did we get a signal? */
9054 // raise(sig); /* run handler */
9055 sig = check_and_run_traps();
9056 if (sig /*&& sig != SIGCHLD - always true */) {
9061 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9066 /* This is probably buggy wrt interruptible-ness */
9068 pid_t pid = bb_strtou(*argv, NULL, 10);
9070 /* mimic bash message */
9071 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9072 return EXIT_FAILURE;
9074 if (waitpid(pid, &status, 0) == pid) {
9075 if (WIFSIGNALED(status))
9076 ret = 128 + WTERMSIG(status);
9077 else if (WIFEXITED(status))
9078 ret = WEXITSTATUS(status);
9082 bb_perror_msg("wait %s", *argv);
9091 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9092 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9095 def = bb_strtou(argv[1], NULL, 10);
9096 if (errno || def < def_min || argv[2]) {
9097 bb_error_msg("%s: bad arguments", argv[0]);
9105 #if ENABLE_HUSH_LOOPS
9106 static int FAST_FUNC builtin_break(char **argv)
9109 if (G.depth_of_loop == 0) {
9110 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9111 return EXIT_SUCCESS; /* bash compat */
9113 G.flag_break_continue++; /* BC_BREAK = 1 */
9115 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9116 if (depth == UINT_MAX)
9117 G.flag_break_continue = BC_BREAK;
9118 if (G.depth_of_loop < depth)
9119 G.depth_break_continue = G.depth_of_loop;
9121 return EXIT_SUCCESS;
9124 static int FAST_FUNC builtin_continue(char **argv)
9126 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9127 return builtin_break(argv);
9131 #if ENABLE_HUSH_FUNCTIONS
9132 static int FAST_FUNC builtin_return(char **argv)
9136 if (G.flag_return_in_progress != -1) {
9137 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9138 return EXIT_FAILURE; /* bash compat */
9141 G.flag_return_in_progress = 1;
9144 * out of range: wraps around at 256, does not error out
9145 * non-numeric param:
9146 * f() { false; return qwe; }; f; echo $?
9147 * bash: return: qwe: numeric argument required <== we do this
9148 * 255 <== we also do this
9150 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);