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: "[-nx] [-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
325 /* Do we support ANY keywords? */
326 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
327 # define HAS_KEYWORDS 1
328 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
329 # define IF_HAS_NO_KEYWORDS(...)
331 # define HAS_KEYWORDS 0
332 # define IF_HAS_KEYWORDS(...)
333 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
336 /* If you comment out one of these below, it will be #defined later
337 * to perform debug printfs to stderr: */
338 #define debug_printf(...) do {} while (0)
339 /* Finer-grained debug switches */
340 #define debug_printf_parse(...) do {} while (0)
341 #define debug_print_tree(a, b) do {} while (0)
342 #define debug_printf_exec(...) do {} while (0)
343 #define debug_printf_env(...) do {} while (0)
344 #define debug_printf_jobs(...) do {} while (0)
345 #define debug_printf_expand(...) do {} while (0)
346 #define debug_printf_varexp(...) do {} while (0)
347 #define debug_printf_glob(...) do {} while (0)
348 #define debug_printf_list(...) do {} while (0)
349 #define debug_printf_subst(...) do {} while (0)
350 #define debug_printf_clean(...) do {} while (0)
352 #define ERR_PTR ((void*)(long)1)
354 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
356 #define _SPECIAL_VARS_STR "_*@$!?#"
357 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
358 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
359 #if ENABLE_HUSH_BASH_COMPAT
360 /* Support / and // replace ops */
361 /* Note that // is stored as \ in "encoded" string representation */
362 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
363 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
364 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
366 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
367 # define VAR_SUBST_OPS "%#:-=+?"
368 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
371 #define SPECIAL_VAR_SYMBOL 3
375 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
377 /* This supports saving pointers malloced in vfork child,
378 * to be freed in the parent.
381 typedef struct nommu_save_t {
383 struct variable *old_vars;
385 char **argv_from_re_execing;
398 #if ENABLE_HUSH_LOOPS
405 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
410 /* three pseudo-keywords support contrived "case" syntax: */
411 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
412 RES_MATCH , /* "word)" */
413 RES_CASE_BODY, /* "this command is inside CASE" */
420 typedef struct o_string {
422 int length; /* position where data is appended */
425 /* At least some part of the string was inside '' or "",
426 * possibly empty one: word"", wo''rd etc. */
427 smallint has_quoted_part;
428 smallint has_empty_slot;
429 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
432 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
434 /* Protect newly added chars against globbing
435 * by prepending \ to *, ?, [, \ */
436 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
439 MAYBE_ASSIGNMENT = 0,
440 DEFINITELY_ASSIGNMENT = 1,
442 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
445 /* Used for initialization: o_string foo = NULL_O_STRING; */
446 #define NULL_O_STRING { NULL }
448 typedef struct in_str {
450 /* eof_flag=1: last char in ->p is really an EOF */
451 char eof_flag; /* meaningless if ->p == NULL */
453 #if ENABLE_HUSH_INTERACTIVE
454 smallint promptmode; /* 0: PS1, 1: PS2 */
458 int (*get) (struct in_str *) FAST_FUNC;
459 int (*peek) (struct in_str *) FAST_FUNC;
461 #define i_getch(input) ((input)->get(input))
462 #define i_peek(input) ((input)->peek(input))
464 /* The descrip member of this structure is only used to make
465 * debugging output pretty */
466 static const struct {
468 signed char default_fd;
471 { O_RDONLY, 0, "<" },
472 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
473 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
474 { O_CREAT|O_RDWR, 1, "<>" },
475 { O_RDONLY, 0, "<<" },
476 /* Should not be needed. Bogus default_fd helps in debugging */
477 /* { O_RDONLY, 77, "<<" }, */
480 struct redir_struct {
481 struct redir_struct *next;
482 char *rd_filename; /* filename */
483 int rd_fd; /* fd to redirect */
484 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
486 smallint rd_type; /* (enum redir_type) */
487 /* note: for heredocs, rd_filename contains heredoc delimiter,
488 * and subsequently heredoc itself; and rd_dup is a bitmask:
489 * bit 0: do we need to trim leading tabs?
490 * bit 1: is heredoc quoted (<<'delim' syntax) ?
493 typedef enum redir_type {
495 REDIRECT_OVERWRITE = 1,
498 REDIRECT_HEREDOC = 4,
499 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
502 REDIRFD_SYNTAX_ERR = -2,
503 REDIRFD_TO_FILE = -1,
504 /* otherwise, rd_fd is redirected to rd_dup */
506 HEREDOC_SKIPTABS = 1,
512 pid_t pid; /* 0 if exited */
513 int assignment_cnt; /* how many argv[i] are assignments? */
514 smallint is_stopped; /* is the command currently running? */
515 smallint cmd_type; /* CMD_xxx */
517 #define CMD_SUBSHELL 1
518 #if ENABLE_HUSH_BASH_COMPAT
519 /* used for "[[ EXPR ]]" */
520 # define CMD_SINGLEWORD_NOGLOB 2
522 #if ENABLE_HUSH_FUNCTIONS
523 # define CMD_FUNCDEF 3
526 smalluint cmd_exitcode;
527 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
530 char *group_as_string;
532 #if ENABLE_HUSH_FUNCTIONS
533 struct function *child_func;
534 /* This field is used to prevent a bug here:
535 * while...do f1() {a;}; f1; f1() {b;}; f1; done
536 * When we execute "f1() {a;}" cmd, we create new function and clear
537 * cmd->group, cmd->group_as_string, cmd->argv[0].
538 * When we execute "f1() {b;}", we notice that f1 exists,
539 * and that its "parent cmd" struct is still "alive",
540 * we put those fields back into cmd->xxx
541 * (struct function has ->parent_cmd ptr to facilitate that).
542 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
543 * Without this trick, loop would execute a;b;b;b;...
544 * instead of correct sequence a;b;a;b;...
545 * When command is freed, it severs the link
546 * (sets ->child_func->parent_cmd to NULL).
549 char **argv; /* command name and arguments */
550 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
551 * and on execution these are substituted with their values.
552 * Substitution can make _several_ words out of one argv[n]!
553 * Example: argv[0]=='.^C*^C.' here: echo .$*.
554 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
556 struct redir_struct *redirects; /* I/O redirections */
558 /* Is there anything in this command at all? */
559 #define IS_NULL_CMD(cmd) \
560 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
564 int num_cmds; /* total number of commands in pipe */
565 int alive_cmds; /* number of commands running (not exited) */
566 int stopped_cmds; /* number of commands alive, but stopped */
568 int jobid; /* job number */
569 pid_t pgrp; /* process group ID for the job */
570 char *cmdtext; /* name of job */
572 struct command *cmds; /* array of commands in pipe */
573 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
574 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
575 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
577 typedef enum pipe_style {
583 /* Is there anything in this pipe at all? */
584 #define IS_NULL_PIPE(pi) \
585 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
587 /* This holds pointers to the various results of parsing */
588 struct parse_context {
589 /* linked list of pipes */
590 struct pipe *list_head;
591 /* last pipe (being constructed right now) */
593 /* last command in pipe (being constructed right now) */
594 struct command *command;
595 /* last redirect in command->redirects list */
596 struct redir_struct *pending_redirect;
602 smallint ctx_inverted; /* "! cmd | cmd" */
604 smallint ctx_dsemicolon; /* ";;" seen */
606 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
608 /* group we are enclosed in:
609 * example: "if pipe1; pipe2; then pipe3; fi"
610 * when we see "if" or "then", we malloc and copy current context,
611 * and make ->stack point to it. then we parse pipeN.
612 * when closing "then" / fi" / whatever is found,
613 * we move list_head into ->stack->command->group,
614 * copy ->stack into current context, and delete ->stack.
615 * (parsing of { list } and ( list ) doesn't use this method)
617 struct parse_context *stack;
621 /* On program start, environ points to initial environment.
622 * putenv adds new pointers into it, unsetenv removes them.
623 * Neither of these (de)allocates the strings.
624 * setenv allocates new strings in malloc space and does putenv,
625 * and thus setenv is unusable (leaky) for shell's purposes */
626 #define setenv(...) setenv_is_leaky_dont_use()
628 struct variable *next;
629 char *varstr; /* points to "name=" portion */
630 #if ENABLE_HUSH_LOCAL
631 unsigned func_nest_level;
633 int max_len; /* if > 0, name is part of initial env; else name is malloced */
634 smallint flg_export; /* putenv should be done on this var */
635 smallint flg_read_only;
643 #if ENABLE_HUSH_FUNCTIONS
645 struct function *next;
647 struct command *parent_cmd;
650 char *body_as_string;
656 /* set -/+o OPT support. (TODO: make it optional)
657 * bash supports the following opts:
668 * interactive-comments on
686 static const char o_opt_strings[] ALIGN1 =
689 #if ENABLE_HUSH_MODE_X
696 #if ENABLE_HUSH_MODE_X
703 /* "Globals" within this file */
704 /* Sorted roughly by size (smaller offsets == smaller code) */
706 /* interactive_fd != 0 means we are an interactive shell.
707 * If we are, then saved_tty_pgrp can also be != 0, meaning
708 * that controlling tty is available. With saved_tty_pgrp == 0,
709 * job control still works, but terminal signals
710 * (^C, ^Z, ^Y, ^\) won't work at all, and background
711 * process groups can only be created with "cmd &".
712 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
713 * to give tty to the foreground process group,
714 * and will take it back when the group is stopped (^Z)
717 #if ENABLE_HUSH_INTERACTIVE
718 /* 'interactive_fd' is a fd# open to ctty, if we have one
719 * _AND_ if we decided to act interactively */
723 # define G_interactive_fd (G.interactive_fd)
725 # define G_interactive_fd 0
727 #if ENABLE_FEATURE_EDITING
728 line_input_t *line_input_state;
733 #if ENABLE_HUSH_RANDOM_SUPPORT
739 pid_t saved_tty_pgrp;
740 struct pipe *job_list;
741 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
743 # define G_saved_tty_pgrp 0
745 char o_opt[NUM_OPT_O];
746 #if ENABLE_HUSH_MODE_X
747 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
751 smallint flag_SIGINT;
752 #if ENABLE_HUSH_LOOPS
753 smallint flag_break_continue;
755 #if ENABLE_HUSH_FUNCTIONS
756 /* 0: outside of a function (or sourced file)
757 * -1: inside of a function, ok to use return builtin
758 * 1: return is invoked, skip all till end of func
760 smallint flag_return_in_progress;
762 smallint exiting; /* used to prevent EXIT trap recursion */
763 /* These four support $?, $#, and $1 */
764 smalluint last_exitcode;
765 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
766 smalluint global_args_malloced;
767 smalluint inherited_set_is_saved;
768 /* how many non-NULL argv's we have. NB: $# + 1 */
772 char *argv0_for_re_execing;
774 #if ENABLE_HUSH_LOOPS
775 unsigned depth_break_continue;
776 unsigned depth_of_loop;
780 struct variable *top_var;
781 char **expanded_assignments;
782 #if ENABLE_HUSH_FUNCTIONS
783 struct function *top_func;
784 # if ENABLE_HUSH_LOCAL
785 struct variable **shadowed_vars_pp;
786 unsigned func_nest_level;
789 /* Signal and trap handling */
791 unsigned count_SIGCHLD;
792 unsigned handled_SIGCHLD;
793 smallint we_have_children;
795 /* which signals have non-DFL handler (even with no traps set)? */
796 unsigned non_DFL_mask;
797 char **traps; /* char *traps[NSIG] */
798 /* Signal mask on the entry to the (top-level) shell. Never modified. */
799 sigset_t inherited_set;
800 /* Starts equal to inherited_set,
801 * but shell-special signals are added and SIGCHLD is removed.
802 * When a trap is set/cleared, signal is added to/removed from it:
804 sigset_t blocked_set;
806 sigset_t detected_set;
808 unsigned long memleak_value;
811 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
813 #define G (*ptr_to_globals)
814 /* Not #defining name to G.name - this quickly gets unwieldy
815 * (too many defines). Also, I actually prefer to see when a variable
816 * is global, thus "G." prefix is a useful hint */
817 #define INIT_G() do { \
818 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
822 /* Function prototypes for builtins */
823 static int builtin_cd(char **argv) FAST_FUNC;
824 static int builtin_echo(char **argv) FAST_FUNC;
825 static int builtin_eval(char **argv) FAST_FUNC;
826 static int builtin_exec(char **argv) FAST_FUNC;
827 static int builtin_exit(char **argv) FAST_FUNC;
828 static int builtin_export(char **argv) FAST_FUNC;
830 static int builtin_fg_bg(char **argv) FAST_FUNC;
831 static int builtin_jobs(char **argv) FAST_FUNC;
834 static int builtin_help(char **argv) FAST_FUNC;
836 #if ENABLE_HUSH_LOCAL
837 static int builtin_local(char **argv) FAST_FUNC;
840 static int builtin_memleak(char **argv) FAST_FUNC;
843 static int builtin_printf(char **argv) FAST_FUNC;
845 static int builtin_pwd(char **argv) FAST_FUNC;
846 static int builtin_read(char **argv) FAST_FUNC;
847 static int builtin_set(char **argv) FAST_FUNC;
848 static int builtin_shift(char **argv) FAST_FUNC;
849 static int builtin_source(char **argv) FAST_FUNC;
850 static int builtin_test(char **argv) FAST_FUNC;
851 static int builtin_trap(char **argv) FAST_FUNC;
852 static int builtin_type(char **argv) FAST_FUNC;
853 static int builtin_true(char **argv) FAST_FUNC;
854 static int builtin_umask(char **argv) FAST_FUNC;
855 static int builtin_unset(char **argv) FAST_FUNC;
856 static int builtin_wait(char **argv) FAST_FUNC;
857 #if ENABLE_HUSH_LOOPS
858 static int builtin_break(char **argv) FAST_FUNC;
859 static int builtin_continue(char **argv) FAST_FUNC;
861 #if ENABLE_HUSH_FUNCTIONS
862 static int builtin_return(char **argv) FAST_FUNC;
865 /* Table of built-in functions. They can be forked or not, depending on
866 * context: within pipes, they fork. As simple commands, they do not.
867 * When used in non-forking context, they can change global variables
868 * in the parent shell process. If forked, of course they cannot.
869 * For example, 'unset foo | whatever' will parse and run, but foo will
870 * still be set at the end. */
871 struct built_in_command {
873 int (*b_function)(char **argv) FAST_FUNC;
876 # define BLTIN(cmd, func, help) { cmd, func, help }
878 # define BLTIN(cmd, func, help) { cmd, func }
882 static const struct built_in_command bltins1[] = {
883 BLTIN("." , builtin_source , "Run commands in a file"),
884 BLTIN(":" , builtin_true , NULL),
886 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
888 #if ENABLE_HUSH_LOOPS
889 BLTIN("break" , builtin_break , "Exit from a loop"),
891 BLTIN("cd" , builtin_cd , "Change directory"),
892 #if ENABLE_HUSH_LOOPS
893 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
895 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
896 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
897 BLTIN("exit" , builtin_exit , "Exit"),
898 BLTIN("export" , builtin_export , "Set environment variables"),
900 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
903 BLTIN("help" , builtin_help , NULL),
906 BLTIN("jobs" , builtin_jobs , "List jobs"),
908 #if ENABLE_HUSH_LOCAL
909 BLTIN("local" , builtin_local , "Set local variables"),
912 BLTIN("memleak" , builtin_memleak , NULL),
914 BLTIN("read" , builtin_read , "Input into variable"),
915 #if ENABLE_HUSH_FUNCTIONS
916 BLTIN("return" , builtin_return , "Return from a function"),
918 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
919 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
920 #if ENABLE_HUSH_BASH_COMPAT
921 BLTIN("source" , builtin_source , "Run commands in a file"),
923 BLTIN("trap" , builtin_trap , "Trap signals"),
924 BLTIN("type" , builtin_type , "Show command type"),
925 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
926 BLTIN("umask" , builtin_umask , "Set file creation mask"),
927 BLTIN("unset" , builtin_unset , "Unset variables"),
928 BLTIN("wait" , builtin_wait , "Wait for process"),
930 /* For now, echo and test are unconditionally enabled.
931 * Maybe make it configurable? */
932 static const struct built_in_command bltins2[] = {
933 BLTIN("[" , builtin_test , NULL),
934 BLTIN("echo" , builtin_echo , NULL),
936 BLTIN("printf" , builtin_printf , NULL),
938 BLTIN("pwd" , builtin_pwd , NULL),
939 BLTIN("test" , builtin_test , NULL),
946 /* prevent disasters with G.debug_indent < 0 */
947 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
948 # define debug_enter() (G.debug_indent++)
949 # define debug_leave() (G.debug_indent--)
951 # define indent() ((void)0)
952 # define debug_enter() ((void)0)
953 # define debug_leave() ((void)0)
957 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
960 #ifndef debug_printf_parse
961 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
964 #ifndef debug_printf_exec
965 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
968 #ifndef debug_printf_env
969 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
972 #ifndef debug_printf_jobs
973 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
974 # define DEBUG_JOBS 1
976 # define DEBUG_JOBS 0
979 #ifndef debug_printf_expand
980 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
981 # define DEBUG_EXPAND 1
983 # define DEBUG_EXPAND 0
986 #ifndef debug_printf_varexp
987 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
990 #ifndef debug_printf_glob
991 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
992 # define DEBUG_GLOB 1
994 # define DEBUG_GLOB 0
997 #ifndef debug_printf_list
998 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1001 #ifndef debug_printf_subst
1002 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1005 #ifndef debug_printf_clean
1006 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1007 # define DEBUG_CLEAN 1
1009 # define DEBUG_CLEAN 0
1013 static void debug_print_strings(const char *prefix, char **vv)
1016 fdprintf(2, "%s:\n", prefix);
1018 fdprintf(2, " '%s'\n", *vv++);
1021 # define debug_print_strings(prefix, vv) ((void)0)
1025 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1028 static void *xxmalloc(int lineno, size_t size)
1030 void *ptr = xmalloc((size + 0xff) & ~0xff);
1031 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1034 static void *xxrealloc(int lineno, void *ptr, size_t size)
1036 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1037 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1040 static char *xxstrdup(int lineno, const char *str)
1042 char *ptr = xstrdup(str);
1043 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1046 static void xxfree(void *ptr)
1048 fdprintf(2, "free %p\n", ptr);
1051 # define xmalloc(s) xxmalloc(__LINE__, s)
1052 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1053 # define xstrdup(s) xxstrdup(__LINE__, s)
1054 # define free(p) xxfree(p)
1058 /* Syntax and runtime errors. They always abort scripts.
1059 * In interactive use they usually discard unparsed and/or unexecuted commands
1060 * and return to the prompt.
1061 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1064 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1065 # define syntax_error(lineno, msg) syntax_error(msg)
1066 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1067 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1068 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1069 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1072 static void die_if_script(unsigned lineno, const char *fmt, ...)
1077 bb_error_msg("hush.c:%u", lineno);
1080 bb_verror_msg(fmt, p, NULL);
1082 if (!G_interactive_fd)
1086 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1089 bb_error_msg("syntax error: %s", msg);
1091 bb_error_msg("syntax error");
1094 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1096 bb_error_msg("syntax error at '%s'", msg);
1099 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1101 bb_error_msg("syntax error: unterminated %s", s);
1104 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1106 char msg[2] = { ch, '\0' };
1107 syntax_error_unterm_str(lineno, msg);
1110 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1115 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1119 # undef die_if_script
1120 # undef syntax_error
1121 # undef syntax_error_at
1122 # undef syntax_error_unterm_ch
1123 # undef syntax_error_unterm_str
1124 # undef syntax_error_unexpected_ch
1126 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1127 # define syntax_error(msg) syntax_error(__LINE__, msg)
1128 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1129 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1130 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1131 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1135 #if ENABLE_HUSH_INTERACTIVE
1136 static void cmdedit_update_prompt(void);
1138 # define cmdedit_update_prompt() ((void)0)
1142 /* Utility functions
1144 /* Replace each \x with x in place, return ptr past NUL. */
1145 static char *unbackslash(char *src)
1147 char *dst = src = strchrnul(src, '\\');
1151 if ((*dst++ = *src++) == '\0')
1157 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1178 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1179 v[count1 + count2] = NULL;
1182 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1186 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1188 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1189 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1192 #define add_strings_to_strings(strings, add, need_to_dup) \
1193 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1196 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1197 static char **add_string_to_strings(char **strings, char *add)
1202 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1205 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1207 char **ptr = add_string_to_strings(strings, add);
1208 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1211 #define add_string_to_strings(strings, add) \
1212 xx_add_string_to_strings(__LINE__, strings, add)
1215 static void free_strings(char **strings)
1230 /* Helpers for setting new $n and restoring them back
1232 typedef struct save_arg_t {
1236 smallint sv_g_malloced;
1239 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1243 sv->sv_argv0 = argv[0];
1244 sv->sv_g_argv = G.global_argv;
1245 sv->sv_g_argc = G.global_argc;
1246 sv->sv_g_malloced = G.global_args_malloced;
1248 argv[0] = G.global_argv[0]; /* retain $0 */
1249 G.global_argv = argv;
1250 G.global_args_malloced = 0;
1258 static void restore_G_args(save_arg_t *sv, char **argv)
1262 if (G.global_args_malloced) {
1263 /* someone ran "set -- arg1 arg2 ...", undo */
1265 while (*++pp) /* note: does not free $0 */
1267 free(G.global_argv);
1269 argv[0] = sv->sv_argv0;
1270 G.global_argv = sv->sv_g_argv;
1271 G.global_argc = sv->sv_g_argc;
1272 G.global_args_malloced = sv->sv_g_malloced;
1276 /* Basic theory of signal handling in shell
1277 * ========================================
1278 * This does not describe what hush does, rather, it is current understanding
1279 * what it _should_ do. If it doesn't, it's a bug.
1280 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1282 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1283 * is finished or backgrounded. It is the same in interactive and
1284 * non-interactive shells, and is the same regardless of whether
1285 * a user trap handler is installed or a shell special one is in effect.
1286 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1287 * backgrounds (i.e. stops) or kills all members of currently running
1290 * Wait builtin in interruptible by signals for which user trap is set
1291 * or by SIGINT in interactive shell.
1293 * Trap handlers will execute even within trap handlers. (right?)
1295 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1296 * except for handlers set to '' (empty string).
1298 * If job control is off, backgrounded commands ("cmd &")
1299 * have SIGINT, SIGQUIT set to SIG_IGN.
1301 * Commands which are run in command substitution ("`cmd`")
1302 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1304 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1305 * by the shell from its parent.
1307 * Signals which differ from SIG_DFL action
1308 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1311 * SIGTERM (interactive): ignore
1312 * SIGHUP (interactive):
1313 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1314 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1315 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1316 * that all pipe members are stopped. Try this in bash:
1317 * while :; do :; done - ^Z does not background it
1318 * (while :; do :; done) - ^Z backgrounds it
1319 * SIGINT (interactive): wait for last pipe, ignore the rest
1320 * of the command line, show prompt. NB: ^C does not send SIGINT
1321 * to interactive shell while shell is waiting for a pipe,
1322 * since shell is bg'ed (is not in foreground process group).
1323 * Example 1: this waits 5 sec, but does not execute ls:
1324 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1325 * Example 2: this does not wait and does not execute ls:
1326 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1327 * Example 3: this does not wait 5 sec, but executes ls:
1328 * "sleep 5; ls -l" + press ^C
1329 * Example 4: this does not wait and does not execute ls:
1330 * "sleep 5 & wait; ls -l" + press ^C
1332 * (What happens to signals which are IGN on shell start?)
1333 * (What happens with signal mask on shell start?)
1335 * Implementation in hush
1336 * ======================
1337 * We use in-kernel pending signal mask to determine which signals were sent.
1338 * We block all signals which we don't want to take action immediately,
1339 * i.e. we block all signals which need to have special handling as described
1340 * above, and all signals which have traps set.
1341 * After each pipe execution, we extract any pending signals via sigtimedwait()
1344 * unsigned non_DFL_mask: a mask of such "special" signals
1345 * sigset_t blocked_set: current blocked signal set
1348 * clear bit in blocked_set unless it is also in non_DFL_mask
1349 * "trap 'cmd' SIGxxx":
1350 * set bit in blocked_set (even if 'cmd' is '')
1351 * after [v]fork, if we plan to be a shell:
1352 * unblock signals with special interactive handling
1353 * (child shell is not interactive),
1354 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1355 * after [v]fork, if we plan to exec:
1356 * POSIX says fork clears pending signal mask in child - no need to clear it.
1357 * Restore blocked signal set to one inherited by shell just prior to exec.
1359 * Note: as a result, we do not use signal handlers much. The only uses
1360 * are to count SIGCHLDs
1361 * and to restore tty pgrp on signal-induced exit.
1364 * Standard says "When a subshell is entered, traps that are not being ignored
1365 * are set to the default actions". bash interprets it so that traps which
1366 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1369 SPECIAL_INTERACTIVE_SIGS = 0
1374 SPECIAL_JOB_SIGS = 0
1382 static void sigprocmask_set(sigset_t *set)
1384 sigprocmask(SIG_SETMASK, set, NULL);
1387 #if ENABLE_HUSH_FAST
1388 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1391 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1397 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1398 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1399 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1400 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1402 /* Restores tty foreground process group, and exits.
1403 * May be called as signal handler for fatal signal
1404 * (will resend signal to itself, producing correct exit state)
1405 * or called directly with -EXITCODE.
1406 * We also call it if xfunc is exiting. */
1407 static void sigexit(int sig) NORETURN;
1408 static void sigexit(int sig)
1410 /* Disable all signals: job control, SIGPIPE, etc. */
1411 sigprocmask_allsigs(SIG_BLOCK);
1413 /* Careful: we can end up here after [v]fork. Do not restore
1414 * tty pgrp then, only top-level shell process does that */
1415 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1416 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1418 /* Not a signal, just exit */
1422 kill_myself_with_sig(sig); /* does not return */
1426 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1427 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1431 /* Restores tty foreground process group, and exits. */
1432 static void hush_exit(int exitcode) NORETURN;
1433 static void hush_exit(int exitcode)
1436 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1437 /* Prevent recursion:
1438 * trap "echo Hi; exit" EXIT; exit
1441 /* argv[0] is unused */
1442 argv[1] = G.traps[0];
1444 G.exiting = 1; /* prevent EXIT trap recursion */
1445 /* Note: G.traps[0] is not cleared!
1446 * "trap" will still show it, if executed
1451 #if ENABLE_FEATURE_CLEAN_UP
1453 struct variable *cur_var;
1454 if (G.cwd != bb_msg_unknown)
1456 cur_var = G.top_var;
1458 struct variable *tmp = cur_var;
1459 if (!cur_var->max_len)
1460 free(cur_var->varstr);
1461 cur_var = cur_var->next;
1469 sigexit(- (exitcode & 0xff));
1476 static int check_and_run_traps(int sig)
1478 /* I want it in rodata, not in bss.
1479 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1480 * initializer. But other compilers may still use bss.
1481 * TODO: find more portable solution.
1483 static const struct timespec zero_timespec = { 0, 0 };
1484 smalluint save_rcode;
1491 if (!sigisemptyset(&G.detected_set)) {
1495 if (sigismember(&G.detected_set, sig)) {
1496 sigdelset(&G.detected_set, sig);
1499 } while (sig < NSIG);
1502 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1506 if (G.traps && G.traps[sig]) {
1507 if (G.traps[sig][0]) {
1508 /* We have user-defined handler */
1510 /* argv[0] is unused */
1511 argv[1] = G.traps[sig];
1513 save_rcode = G.last_exitcode;
1515 G.last_exitcode = save_rcode;
1517 } /* else: "" trap, ignoring signal */
1520 /* not a trap: special action */
1522 #if ENABLE_HUSH_FAST
1525 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1529 /* Builtin was ^C'ed, make it look prettier: */
1537 /* bash is observed to signal whole process groups,
1538 * not individual processes */
1539 for (job = G.job_list; job; job = job->next) {
1542 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1543 if (kill(- job->pgrp, SIGHUP) == 0)
1544 kill(- job->pgrp, SIGCONT);
1549 default: /* ignored: */
1550 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1552 * we dont do 'last_sig = sig' here -> NOT returning this sig.
1553 * example: wait is not interrupted by TERM
1554 * in interactive shell, because TERM is ignored.
1563 static const char *get_cwd(int force)
1565 if (force || G.cwd == NULL) {
1566 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1567 * we must not try to free(bb_msg_unknown) */
1568 if (G.cwd == bb_msg_unknown)
1570 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1572 G.cwd = bb_msg_unknown;
1579 * Shell and environment variable support
1581 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1583 struct variable **pp;
1584 struct variable *cur;
1587 while ((cur = *pp) != NULL) {
1588 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1595 static const char* FAST_FUNC get_local_var_value(const char *name)
1597 struct variable **vpp;
1598 unsigned len = strlen(name);
1600 if (G.expanded_assignments) {
1601 char **cpp = G.expanded_assignments;
1604 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1605 return cp + len + 1;
1610 vpp = get_ptr_to_local_var(name, len);
1612 return (*vpp)->varstr + len + 1;
1614 if (strcmp(name, "PPID") == 0)
1615 return utoa(G.root_ppid);
1616 // bash compat: UID? EUID?
1617 #if ENABLE_HUSH_RANDOM_SUPPORT
1618 if (strcmp(name, "RANDOM") == 0)
1619 return utoa(next_random(&G.random_gen));
1624 /* str holds "NAME=VAL" and is expected to be malloced.
1625 * We take ownership of it.
1627 * 0: do not change export flag
1628 * (if creating new variable, flag will be 0)
1629 * 1: set export flag and putenv the variable
1630 * -1: clear export flag and unsetenv the variable
1631 * flg_read_only is set only when we handle -R var=val
1633 #if !BB_MMU && ENABLE_HUSH_LOCAL
1634 /* all params are used */
1635 #elif BB_MMU && ENABLE_HUSH_LOCAL
1636 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1637 set_local_var(str, flg_export, local_lvl)
1638 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1639 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1640 set_local_var(str, flg_export)
1641 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1642 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1643 set_local_var(str, flg_export, flg_read_only)
1645 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1647 struct variable **var_pp;
1648 struct variable *cur;
1652 eq_sign = strchr(str, '=');
1653 if (!eq_sign) { /* not expected to ever happen? */
1658 name_len = eq_sign - str + 1; /* including '=' */
1659 var_pp = &G.top_var;
1660 while ((cur = *var_pp) != NULL) {
1661 if (strncmp(cur->varstr, str, name_len) != 0) {
1662 var_pp = &cur->next;
1665 /* We found an existing var with this name */
1666 if (cur->flg_read_only) {
1670 bb_error_msg("%s: readonly variable", str);
1674 if (flg_export == -1) { // "&& cur->flg_export" ?
1675 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1680 #if ENABLE_HUSH_LOCAL
1681 if (cur->func_nest_level < local_lvl) {
1682 /* New variable is declared as local,
1683 * and existing one is global, or local
1684 * from enclosing function.
1685 * Remove and save old one: */
1686 *var_pp = cur->next;
1687 cur->next = *G.shadowed_vars_pp;
1688 *G.shadowed_vars_pp = cur;
1689 /* bash 3.2.33(1) and exported vars:
1691 * # f() { local z=a; env | grep ^z; }
1697 if (cur->flg_export)
1702 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1707 if (cur->max_len != 0) {
1708 if (cur->max_len >= strlen(str)) {
1709 /* This one is from startup env, reuse space */
1710 strcpy(cur->varstr, str);
1714 /* max_len == 0 signifies "malloced" var, which we can
1715 * (and has to) free */
1719 goto set_str_and_exp;
1722 /* Not found - create new variable struct */
1723 cur = xzalloc(sizeof(*cur));
1724 #if ENABLE_HUSH_LOCAL
1725 cur->func_nest_level = local_lvl;
1727 cur->next = *var_pp;
1733 cur->flg_read_only = flg_read_only;
1736 if (flg_export == 1)
1737 cur->flg_export = 1;
1738 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1739 cmdedit_update_prompt();
1740 if (cur->flg_export) {
1741 if (flg_export == -1) {
1742 cur->flg_export = 0;
1743 /* unsetenv was already done */
1745 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1746 return putenv(cur->varstr);
1752 /* Used at startup and after each cd */
1753 static void set_pwd_var(int exp)
1755 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1756 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1759 static int unset_local_var_len(const char *name, int name_len)
1761 struct variable *cur;
1762 struct variable **var_pp;
1765 return EXIT_SUCCESS;
1766 var_pp = &G.top_var;
1767 while ((cur = *var_pp) != NULL) {
1768 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1769 if (cur->flg_read_only) {
1770 bb_error_msg("%s: readonly variable", name);
1771 return EXIT_FAILURE;
1773 *var_pp = cur->next;
1774 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1775 bb_unsetenv(cur->varstr);
1776 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1777 cmdedit_update_prompt();
1781 return EXIT_SUCCESS;
1783 var_pp = &cur->next;
1785 return EXIT_SUCCESS;
1788 static int unset_local_var(const char *name)
1790 return unset_local_var_len(name, strlen(name));
1793 static void unset_vars(char **strings)
1801 const char *eq = strchrnul(*v, '=');
1802 unset_local_var_len(*v, (int)(eq - *v));
1808 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1810 char *var = xasprintf("%s=%s", name, val);
1811 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1816 * Helpers for "var1=val1 var2=val2 cmd" feature
1818 static void add_vars(struct variable *var)
1820 struct variable *next;
1824 var->next = G.top_var;
1826 if (var->flg_export) {
1827 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1828 putenv(var->varstr);
1830 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1836 static struct variable *set_vars_and_save_old(char **strings)
1839 struct variable *old = NULL;
1845 struct variable *var_p;
1846 struct variable **var_pp;
1849 eq = strchr(*s, '=');
1851 var_pp = get_ptr_to_local_var(*s, eq - *s);
1853 /* Remove variable from global linked list */
1855 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1856 *var_pp = var_p->next;
1857 /* Add it to returned list */
1861 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1872 static int FAST_FUNC static_get(struct in_str *i)
1883 static int FAST_FUNC static_peek(struct in_str *i)
1888 #if ENABLE_HUSH_INTERACTIVE
1890 static void cmdedit_update_prompt(void)
1892 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1893 G.PS1 = get_local_var_value("PS1");
1896 G.PS2 = get_local_var_value("PS2");
1904 static const char *setup_prompt_string(int promptmode)
1906 const char *prompt_str;
1907 debug_printf("setup_prompt_string %d ", promptmode);
1908 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1909 /* Set up the prompt */
1910 if (promptmode == 0) { /* PS1 */
1912 /* bash uses $PWD value, even if it is set by user.
1913 * It uses current dir only if PWD is unset.
1914 * We always use current dir. */
1915 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1920 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1921 debug_printf("result '%s'\n", prompt_str);
1925 static void get_user_input(struct in_str *i)
1928 const char *prompt_str;
1930 prompt_str = setup_prompt_string(i->promptmode);
1931 # if ENABLE_FEATURE_EDITING
1932 /* Enable command line editing only while a command line
1933 * is actually being read */
1935 /* Unicode support should be activated even if LANG is set
1936 * _during_ shell execution, not only if it was set when
1937 * shell was started. Therefore, re-check LANG every time:
1939 reinit_unicode(get_local_var_value("LANG"));
1942 /* buglet: SIGINT will not make new prompt to appear _at once_,
1943 * only after <Enter>. (^C will work) */
1944 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1945 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1946 check_and_run_traps(0);
1947 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1948 i->eof_flag = (r < 0);
1949 if (i->eof_flag) { /* EOF/error detected */
1950 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1951 G.user_input_buf[1] = '\0';
1956 if (i->last_char == '\0' || i->last_char == '\n') {
1957 /* Why check_and_run_traps here? Try this interactively:
1958 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
1959 * $ <[enter], repeatedly...>
1960 * Without check_and_run_traps, handler never runs.
1962 check_and_run_traps(0);
1963 fputs(prompt_str, stdout);
1966 G.user_input_buf[0] = r = fgetc(i->file);
1967 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1968 } while (G.flag_SIGINT);
1969 i->eof_flag = (r == EOF);
1971 i->p = G.user_input_buf;
1974 #endif /* INTERACTIVE */
1976 /* This is the magic location that prints prompts
1977 * and gets data back from the user */
1978 static int FAST_FUNC file_get(struct in_str *i)
1982 /* If there is data waiting, eat it up */
1983 if (i->p && *i->p) {
1984 #if ENABLE_HUSH_INTERACTIVE
1988 if (i->eof_flag && !*i->p)
1990 /* note: ch is never NUL */
1992 /* need to double check i->file because we might be doing something
1993 * more complicated by now, like sourcing or substituting. */
1994 #if ENABLE_HUSH_INTERACTIVE
1995 if (G_interactive_fd && i->file == stdin) {
1998 } while (!*i->p); /* need non-empty line */
1999 i->promptmode = 1; /* PS2 */
2003 do ch = fgetc(i->file); while (ch == '\0');
2005 debug_printf("file_get: got '%c' %d\n", ch, ch);
2010 /* All callers guarantee this routine will never
2011 * be used right after a newline, so prompting is not needed.
2013 static int FAST_FUNC file_peek(struct in_str *i)
2016 if (i->p && *i->p) {
2017 if (i->eof_flag && !i->p[1])
2020 /* note: ch is never NUL */
2022 do ch = fgetc(i->file); while (ch == '\0');
2023 i->eof_flag = (ch == EOF);
2024 i->peek_buf[0] = ch;
2025 i->peek_buf[1] = '\0';
2027 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2031 static void setup_file_in_str(struct in_str *i, FILE *f)
2033 memset(i, 0, sizeof(*i));
2034 i->peek = file_peek;
2036 /* i->promptmode = 0; - PS1 (memset did it) */
2041 static void setup_string_in_str(struct in_str *i, const char *s)
2043 memset(i, 0, sizeof(*i));
2044 i->peek = static_peek;
2045 i->get = static_get;
2046 /* i->promptmode = 0; - PS1 (memset did it) */
2048 /* i->eof_flag = 0; */
2055 #define B_CHUNK (32 * sizeof(char*))
2057 static void o_reset_to_empty_unquoted(o_string *o)
2060 o->has_quoted_part = 0;
2065 static void o_free(o_string *o)
2068 memset(o, 0, sizeof(*o));
2071 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2076 static void o_grow_by(o_string *o, int len)
2078 if (o->length + len > o->maxlen) {
2079 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2080 o->data = xrealloc(o->data, 1 + o->maxlen);
2084 static void o_addchr(o_string *o, int ch)
2086 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2088 o->data[o->length] = ch;
2090 o->data[o->length] = '\0';
2093 static void o_addblock(o_string *o, const char *str, int len)
2096 memcpy(&o->data[o->length], str, len);
2098 o->data[o->length] = '\0';
2101 static void o_addstr(o_string *o, const char *str)
2103 o_addblock(o, str, strlen(str));
2107 static void nommu_addchr(o_string *o, int ch)
2113 # define nommu_addchr(o, str) ((void)0)
2116 static void o_addstr_with_NUL(o_string *o, const char *str)
2118 o_addblock(o, str, strlen(str) + 1);
2122 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2123 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2124 * Apparently, on unquoted $v bash still does globbing
2125 * ("v='*.txt'; echo $v" prints all .txt files),
2126 * but NOT brace expansion! Thus, there should be TWO independent
2127 * quoting mechanisms on $v expansion side: one protects
2128 * $v from brace expansion, and other additionally protects "$v" against globbing.
2129 * We have only second one.
2132 #if ENABLE_HUSH_BRACE_EXPANSION
2133 # define MAYBE_BRACES "{}"
2135 # define MAYBE_BRACES ""
2138 /* My analysis of quoting semantics tells me that state information
2139 * is associated with a destination, not a source.
2141 static void o_addqchr(o_string *o, int ch)
2144 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2149 o->data[o->length] = '\\';
2152 o->data[o->length] = ch;
2154 o->data[o->length] = '\0';
2157 static void o_addQchr(o_string *o, int ch)
2160 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2161 && strchr("*?[\\" MAYBE_BRACES, ch)
2164 o->data[o->length] = '\\';
2168 o->data[o->length] = ch;
2170 o->data[o->length] = '\0';
2173 static void o_addqblock(o_string *o, const char *str, int len)
2178 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2179 if (ordinary_cnt > len) /* paranoia */
2181 o_addblock(o, str, ordinary_cnt);
2182 if (ordinary_cnt == len)
2184 str += ordinary_cnt;
2185 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2189 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2191 o->data[o->length] = '\\';
2195 o->data[o->length] = ch;
2197 o->data[o->length] = '\0';
2201 static void o_addQblock(o_string *o, const char *str, int len)
2203 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2204 o_addblock(o, str, len);
2207 o_addqblock(o, str, len);
2210 static void o_addQstr(o_string *o, const char *str)
2212 o_addQblock(o, str, strlen(str));
2215 /* A special kind of o_string for $VAR and `cmd` expansion.
2216 * It contains char* list[] at the beginning, which is grown in 16 element
2217 * increments. Actual string data starts at the next multiple of 16 * (char*).
2218 * list[i] contains an INDEX (int!) into this string data.
2219 * It means that if list[] needs to grow, data needs to be moved higher up
2220 * but list[i]'s need not be modified.
2221 * NB: remembering how many list[i]'s you have there is crucial.
2222 * o_finalize_list() operation post-processes this structure - calculates
2223 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2225 #if DEBUG_EXPAND || DEBUG_GLOB
2226 static void debug_print_list(const char *prefix, o_string *o, int n)
2228 char **list = (char**)o->data;
2229 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2233 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2234 prefix, list, n, string_start, o->length, o->maxlen,
2235 !!(o->o_expflags & EXP_FLAG_GLOB),
2237 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2240 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2241 o->data + (int)(uintptr_t)list[i] + string_start,
2242 o->data + (int)(uintptr_t)list[i] + string_start);
2246 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2248 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2252 # define debug_print_list(prefix, o, n) ((void)0)
2255 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2256 * in list[n] so that it points past last stored byte so far.
2257 * It returns n+1. */
2258 static int o_save_ptr_helper(o_string *o, int n)
2260 char **list = (char**)o->data;
2264 if (!o->has_empty_slot) {
2265 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2266 string_len = o->length - string_start;
2267 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2268 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2269 /* list[n] points to string_start, make space for 16 more pointers */
2270 o->maxlen += 0x10 * sizeof(list[0]);
2271 o->data = xrealloc(o->data, o->maxlen + 1);
2272 list = (char**)o->data;
2273 memmove(list + n + 0x10, list + n, string_len);
2274 o->length += 0x10 * sizeof(list[0]);
2276 debug_printf_list("list[%d]=%d string_start=%d\n",
2277 n, string_len, string_start);
2280 /* We have empty slot at list[n], reuse without growth */
2281 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2282 string_len = o->length - string_start;
2283 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2284 n, string_len, string_start);
2285 o->has_empty_slot = 0;
2287 list[n] = (char*)(uintptr_t)string_len;
2291 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2292 static int o_get_last_ptr(o_string *o, int n)
2294 char **list = (char**)o->data;
2295 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2297 return ((int)(uintptr_t)list[n-1]) + string_start;
2300 #if ENABLE_HUSH_BRACE_EXPANSION
2301 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2302 * first, it processes even {a} (no commas), second,
2303 * I didn't manage to make it return strings when they don't match
2304 * existing files. Need to re-implement it.
2308 static int glob_needed(const char *s)
2317 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2323 /* Return pointer to next closing brace or to comma */
2324 static const char *next_brace_sub(const char *cp)
2328 while (*cp != '\0') {
2335 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2341 return *cp != '\0' ? cp : NULL;
2343 /* Recursive brace globber. Note: may garble pattern[]. */
2344 static int glob_brace(char *pattern, o_string *o, int n)
2346 char *new_pattern_buf;
2353 debug_printf_glob("glob_brace('%s')\n", pattern);
2359 if (*begin == '{') {
2360 /* Find the first sub-pattern and at the same time
2361 * find the rest after the closing brace */
2362 next = next_brace_sub(begin);
2364 /* An illegal expression */
2368 /* "{abc}" with no commas - illegal
2369 * brace expr, disregard and skip it */
2375 if (*begin == '\\' && begin[1] != '\0')
2379 debug_printf_glob("begin:%s\n", begin);
2380 debug_printf_glob("next:%s\n", next);
2382 /* Now find the end of the whole brace expression */
2384 while (*rest != '}') {
2385 rest = next_brace_sub(rest);
2387 /* An illegal expression */
2390 debug_printf_glob("rest:%s\n", rest);
2392 rest_len = strlen(++rest) + 1;
2394 /* We are sure the brace expression is well-formed */
2396 /* Allocate working buffer large enough for our work */
2397 new_pattern_buf = xmalloc(strlen(pattern));
2399 /* We have a brace expression. BEGIN points to the opening {,
2400 * NEXT points past the terminator of the first element, and REST
2401 * points past the final }. We will accumulate result names from
2402 * recursive runs for each brace alternative in the buffer using
2407 /* Construct the new glob expression */
2410 mempcpy(new_pattern_buf,
2411 /* We know the prefix for all sub-patterns */
2412 pattern, begin - pattern),
2416 /* Note: glob_brace() may garble new_pattern_buf[].
2417 * That's why we re-copy prefix every time (1st memcpy above).
2419 n = glob_brace(new_pattern_buf, o, n);
2421 /* We saw the last entry */
2425 next = next_brace_sub(next);
2427 free(new_pattern_buf);
2435 memset(&globdata, 0, sizeof(globdata));
2436 gr = glob(pattern, 0, NULL, &globdata);
2437 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2439 if (gr == GLOB_NOMATCH) {
2440 globfree(&globdata);
2441 /* NB: garbles parameter */
2442 unbackslash(pattern);
2443 o_addstr_with_NUL(o, pattern);
2444 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2445 return o_save_ptr_helper(o, n);
2447 if (gr == GLOB_NOSPACE)
2448 bb_error_msg_and_die(bb_msg_memory_exhausted);
2449 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2450 * but we didn't specify it. Paranoia again. */
2451 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2453 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2454 char **argv = globdata.gl_pathv;
2456 o_addstr_with_NUL(o, *argv);
2457 n = o_save_ptr_helper(o, n);
2463 globfree(&globdata);
2467 /* Performs globbing on last list[],
2468 * saving each result as a new list[].
2470 static int perform_glob(o_string *o, int n)
2472 char *pattern, *copy;
2474 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2476 return o_save_ptr_helper(o, n);
2477 pattern = o->data + o_get_last_ptr(o, n);
2478 debug_printf_glob("glob pattern '%s'\n", pattern);
2479 if (!glob_needed(pattern)) {
2480 /* unbackslash last string in o in place, fix length */
2481 o->length = unbackslash(pattern) - o->data;
2482 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2483 return o_save_ptr_helper(o, n);
2486 copy = xstrdup(pattern);
2487 /* "forget" pattern in o */
2488 o->length = pattern - o->data;
2489 n = glob_brace(copy, o, n);
2492 debug_print_list("perform_glob returning", o, n);
2496 #else /* !HUSH_BRACE_EXPANSION */
2499 static int glob_needed(const char *s)
2508 if (*s == '*' || *s == '[' || *s == '?')
2514 /* Performs globbing on last list[],
2515 * saving each result as a new list[].
2517 static int perform_glob(o_string *o, int n)
2523 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2525 return o_save_ptr_helper(o, n);
2526 pattern = o->data + o_get_last_ptr(o, n);
2527 debug_printf_glob("glob pattern '%s'\n", pattern);
2528 if (!glob_needed(pattern)) {
2530 /* unbackslash last string in o in place, fix length */
2531 o->length = unbackslash(pattern) - o->data;
2532 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2533 return o_save_ptr_helper(o, n);
2536 memset(&globdata, 0, sizeof(globdata));
2537 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2538 * If we glob "*.\*" and don't find anything, we need
2539 * to fall back to using literal "*.*", but GLOB_NOCHECK
2540 * will return "*.\*"!
2542 gr = glob(pattern, 0, NULL, &globdata);
2543 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2545 if (gr == GLOB_NOMATCH) {
2546 globfree(&globdata);
2549 if (gr == GLOB_NOSPACE)
2550 bb_error_msg_and_die(bb_msg_memory_exhausted);
2551 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2552 * but we didn't specify it. Paranoia again. */
2553 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2555 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2556 char **argv = globdata.gl_pathv;
2557 /* "forget" pattern in o */
2558 o->length = pattern - o->data;
2560 o_addstr_with_NUL(o, *argv);
2561 n = o_save_ptr_helper(o, n);
2567 globfree(&globdata);
2569 debug_print_list("perform_glob returning", o, n);
2573 #endif /* !HUSH_BRACE_EXPANSION */
2575 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2576 * Otherwise, just finish current list[] and start new */
2577 static int o_save_ptr(o_string *o, int n)
2579 if (o->o_expflags & EXP_FLAG_GLOB) {
2580 /* If o->has_empty_slot, list[n] was already globbed
2581 * (if it was requested back then when it was filled)
2582 * so don't do that again! */
2583 if (!o->has_empty_slot)
2584 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2586 return o_save_ptr_helper(o, n);
2589 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2590 static char **o_finalize_list(o_string *o, int n)
2595 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2597 debug_print_list("finalized", o, n);
2598 debug_printf_expand("finalized n:%d\n", n);
2599 list = (char**)o->data;
2600 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2604 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2609 static void free_pipe_list(struct pipe *pi);
2611 /* Returns pi->next - next pipe in the list */
2612 static struct pipe *free_pipe(struct pipe *pi)
2617 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2618 for (i = 0; i < pi->num_cmds; i++) {
2619 struct command *command;
2620 struct redir_struct *r, *rnext;
2622 command = &pi->cmds[i];
2623 debug_printf_clean(" command %d:\n", i);
2624 if (command->argv) {
2628 for (a = 0, p = command->argv; *p; a++, p++) {
2629 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2632 free_strings(command->argv);
2633 //command->argv = NULL;
2635 /* not "else if": on syntax error, we may have both! */
2636 if (command->group) {
2637 debug_printf_clean(" begin group (cmd_type:%d)\n",
2639 free_pipe_list(command->group);
2640 debug_printf_clean(" end group\n");
2641 //command->group = NULL;
2643 /* else is crucial here.
2644 * If group != NULL, child_func is meaningless */
2645 #if ENABLE_HUSH_FUNCTIONS
2646 else if (command->child_func) {
2647 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2648 command->child_func->parent_cmd = NULL;
2652 free(command->group_as_string);
2653 //command->group_as_string = NULL;
2655 for (r = command->redirects; r; r = rnext) {
2656 debug_printf_clean(" redirect %d%s",
2657 r->rd_fd, redir_table[r->rd_type].descrip);
2658 /* guard against the case >$FOO, where foo is unset or blank */
2659 if (r->rd_filename) {
2660 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2661 free(r->rd_filename);
2662 //r->rd_filename = NULL;
2664 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2668 //command->redirects = NULL;
2670 free(pi->cmds); /* children are an array, they get freed all at once */
2674 //pi->cmdtext = NULL;
2682 static void free_pipe_list(struct pipe *pi)
2686 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2688 debug_printf_clean("pipe followup code %d\n", pi->followup);
2694 /*** Parsing routines ***/
2696 #ifndef debug_print_tree
2697 static void debug_print_tree(struct pipe *pi, int lvl)
2699 static const char *const PIPE[] = {
2705 static const char *RES[] = {
2706 [RES_NONE ] = "NONE" ,
2709 [RES_THEN ] = "THEN" ,
2710 [RES_ELIF ] = "ELIF" ,
2711 [RES_ELSE ] = "ELSE" ,
2714 # if ENABLE_HUSH_LOOPS
2715 [RES_FOR ] = "FOR" ,
2716 [RES_WHILE] = "WHILE",
2717 [RES_UNTIL] = "UNTIL",
2719 [RES_DONE ] = "DONE" ,
2721 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2724 # if ENABLE_HUSH_CASE
2725 [RES_CASE ] = "CASE" ,
2726 [RES_CASE_IN ] = "CASE_IN" ,
2727 [RES_MATCH] = "MATCH",
2728 [RES_CASE_BODY] = "CASE_BODY",
2729 [RES_ESAC ] = "ESAC" ,
2731 [RES_XXXX ] = "XXXX" ,
2732 [RES_SNTX ] = "SNTX" ,
2734 static const char *const CMDTYPE[] = {
2738 # if ENABLE_HUSH_FUNCTIONS
2747 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2748 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2750 while (prn < pi->num_cmds) {
2751 struct command *command = &pi->cmds[prn];
2752 char **argv = command->argv;
2754 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2756 command->assignment_cnt);
2757 if (command->group) {
2758 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2759 CMDTYPE[command->cmd_type],
2762 , " group_as_string:", command->group_as_string
2767 debug_print_tree(command->group, lvl+1);
2771 if (argv) while (*argv) {
2772 fdprintf(2, " '%s'", *argv);
2782 #endif /* debug_print_tree */
2784 static struct pipe *new_pipe(void)
2787 pi = xzalloc(sizeof(struct pipe));
2788 /*pi->followup = 0; - deliberately invalid value */
2789 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2793 /* Command (member of a pipe) is complete, or we start a new pipe
2794 * if ctx->command is NULL.
2795 * No errors possible here.
2797 static int done_command(struct parse_context *ctx)
2799 /* The command is really already in the pipe structure, so
2800 * advance the pipe counter and make a new, null command. */
2801 struct pipe *pi = ctx->pipe;
2802 struct command *command = ctx->command;
2805 if (IS_NULL_CMD(command)) {
2806 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2810 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2811 //debug_print_tree(ctx->list_head, 20);
2813 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2816 /* Only real trickiness here is that the uncommitted
2817 * command structure is not counted in pi->num_cmds. */
2818 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2819 ctx->command = command = &pi->cmds[pi->num_cmds];
2821 memset(command, 0, sizeof(*command));
2822 return pi->num_cmds; /* used only for 0/nonzero check */
2825 static void done_pipe(struct parse_context *ctx, pipe_style type)
2829 debug_printf_parse("done_pipe entered, followup %d\n", type);
2830 /* Close previous command */
2831 not_null = done_command(ctx);
2832 ctx->pipe->followup = type;
2834 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2835 ctx->ctx_inverted = 0;
2836 ctx->pipe->res_word = ctx->ctx_res_w;
2839 /* Without this check, even just <enter> on command line generates
2840 * tree of three NOPs (!). Which is harmless but annoying.
2841 * IOW: it is safe to do it unconditionally. */
2844 || ctx->ctx_res_w == RES_FI
2846 #if ENABLE_HUSH_LOOPS
2847 || ctx->ctx_res_w == RES_DONE
2848 || ctx->ctx_res_w == RES_FOR
2849 || ctx->ctx_res_w == RES_IN
2851 #if ENABLE_HUSH_CASE
2852 || ctx->ctx_res_w == RES_ESAC
2856 debug_printf_parse("done_pipe: adding new pipe: "
2857 "not_null:%d ctx->ctx_res_w:%d\n",
2858 not_null, ctx->ctx_res_w);
2860 ctx->pipe->next = new_p;
2862 /* RES_THEN, RES_DO etc are "sticky" -
2863 * they remain set for pipes inside if/while.
2864 * This is used to control execution.
2865 * RES_FOR and RES_IN are NOT sticky (needed to support
2866 * cases where variable or value happens to match a keyword):
2868 #if ENABLE_HUSH_LOOPS
2869 if (ctx->ctx_res_w == RES_FOR
2870 || ctx->ctx_res_w == RES_IN)
2871 ctx->ctx_res_w = RES_NONE;
2873 #if ENABLE_HUSH_CASE
2874 if (ctx->ctx_res_w == RES_MATCH)
2875 ctx->ctx_res_w = RES_CASE_BODY;
2876 if (ctx->ctx_res_w == RES_CASE)
2877 ctx->ctx_res_w = RES_CASE_IN;
2879 ctx->command = NULL; /* trick done_command below */
2880 /* Create the memory for command, roughly:
2881 * ctx->pipe->cmds = new struct command;
2882 * ctx->command = &ctx->pipe->cmds[0];
2885 //debug_print_tree(ctx->list_head, 10);
2887 debug_printf_parse("done_pipe return\n");
2890 static void initialize_context(struct parse_context *ctx)
2892 memset(ctx, 0, sizeof(*ctx));
2893 ctx->pipe = ctx->list_head = new_pipe();
2894 /* Create the memory for command, roughly:
2895 * ctx->pipe->cmds = new struct command;
2896 * ctx->command = &ctx->pipe->cmds[0];
2901 /* If a reserved word is found and processed, parse context is modified
2902 * and 1 is returned.
2905 struct reserved_combo {
2908 unsigned char assignment_flag;
2912 FLAG_END = (1 << RES_NONE ),
2914 FLAG_IF = (1 << RES_IF ),
2915 FLAG_THEN = (1 << RES_THEN ),
2916 FLAG_ELIF = (1 << RES_ELIF ),
2917 FLAG_ELSE = (1 << RES_ELSE ),
2918 FLAG_FI = (1 << RES_FI ),
2920 # if ENABLE_HUSH_LOOPS
2921 FLAG_FOR = (1 << RES_FOR ),
2922 FLAG_WHILE = (1 << RES_WHILE),
2923 FLAG_UNTIL = (1 << RES_UNTIL),
2924 FLAG_DO = (1 << RES_DO ),
2925 FLAG_DONE = (1 << RES_DONE ),
2926 FLAG_IN = (1 << RES_IN ),
2928 # if ENABLE_HUSH_CASE
2929 FLAG_MATCH = (1 << RES_MATCH),
2930 FLAG_ESAC = (1 << RES_ESAC ),
2932 FLAG_START = (1 << RES_XXXX ),
2935 static const struct reserved_combo* match_reserved_word(o_string *word)
2937 /* Mostly a list of accepted follow-up reserved words.
2938 * FLAG_END means we are done with the sequence, and are ready
2939 * to turn the compound list into a command.
2940 * FLAG_START means the word must start a new compound list.
2942 static const struct reserved_combo reserved_list[] = {
2944 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2945 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2946 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2947 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2948 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2949 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2951 # if ENABLE_HUSH_LOOPS
2952 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2953 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2954 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2955 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2956 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2957 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2959 # if ENABLE_HUSH_CASE
2960 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2961 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2964 const struct reserved_combo *r;
2966 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2967 if (strcmp(word->data, r->literal) == 0)
2972 /* Return 0: not a keyword, 1: keyword
2974 static int reserved_word(o_string *word, struct parse_context *ctx)
2976 # if ENABLE_HUSH_CASE
2977 static const struct reserved_combo reserved_match = {
2978 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2981 const struct reserved_combo *r;
2983 if (word->has_quoted_part)
2985 r = match_reserved_word(word);
2989 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2990 # if ENABLE_HUSH_CASE
2991 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2992 /* "case word IN ..." - IN part starts first MATCH part */
2993 r = &reserved_match;
2996 if (r->flag == 0) { /* '!' */
2997 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2998 syntax_error("! ! command");
2999 ctx->ctx_res_w = RES_SNTX;
3001 ctx->ctx_inverted = 1;
3004 if (r->flag & FLAG_START) {
3005 struct parse_context *old;
3007 old = xmalloc(sizeof(*old));
3008 debug_printf_parse("push stack %p\n", old);
3009 *old = *ctx; /* physical copy */
3010 initialize_context(ctx);
3012 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3013 syntax_error_at(word->data);
3014 ctx->ctx_res_w = RES_SNTX;
3017 /* "{...} fi" is ok. "{...} if" is not
3019 * if { echo foo; } then { echo bar; } fi */
3020 if (ctx->command->group)
3021 done_pipe(ctx, PIPE_SEQ);
3024 ctx->ctx_res_w = r->res;
3025 ctx->old_flag = r->flag;
3026 word->o_assignment = r->assignment_flag;
3028 if (ctx->old_flag & FLAG_END) {
3029 struct parse_context *old;
3031 done_pipe(ctx, PIPE_SEQ);
3032 debug_printf_parse("pop stack %p\n", ctx->stack);
3034 old->command->group = ctx->list_head;
3035 old->command->cmd_type = CMD_NORMAL;
3037 o_addstr(&old->as_string, ctx->as_string.data);
3038 o_free_unsafe(&ctx->as_string);
3039 old->command->group_as_string = xstrdup(old->as_string.data);
3040 debug_printf_parse("pop, remembering as:'%s'\n",
3041 old->command->group_as_string);
3043 *ctx = *old; /* physical copy */
3048 #endif /* HAS_KEYWORDS */
3050 /* Word is complete, look at it and update parsing context.
3051 * Normal return is 0. Syntax errors return 1.
3052 * Note: on return, word is reset, but not o_free'd!
3054 static int done_word(o_string *word, struct parse_context *ctx)
3056 struct command *command = ctx->command;
3058 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3059 if (word->length == 0 && !word->has_quoted_part) {
3060 debug_printf_parse("done_word return 0: true null, ignored\n");
3064 if (ctx->pending_redirect) {
3065 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3066 * only if run as "bash", not "sh" */
3067 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3069 * ...the word that follows the redirection operator
3070 * shall be subjected to tilde expansion, parameter expansion,
3071 * command substitution, arithmetic expansion, and quote
3072 * removal. Pathname expansion shall not be performed
3073 * on the word by a non-interactive shell; an interactive
3074 * shell may perform it, but shall do so only when
3075 * the expansion would result in one word."
3077 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3078 /* Cater for >\file case:
3079 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3080 * Same with heredocs:
3081 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3083 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3084 unbackslash(ctx->pending_redirect->rd_filename);
3085 /* Is it <<"HEREDOC"? */
3086 if (word->has_quoted_part) {
3087 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3090 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3091 ctx->pending_redirect = NULL;
3093 /* If this word wasn't an assignment, next ones definitely
3094 * can't be assignments. Even if they look like ones. */
3095 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3096 && word->o_assignment != WORD_IS_KEYWORD
3098 word->o_assignment = NOT_ASSIGNMENT;
3100 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3101 command->assignment_cnt++;
3102 word->o_assignment = MAYBE_ASSIGNMENT;
3106 # if ENABLE_HUSH_CASE
3107 if (ctx->ctx_dsemicolon
3108 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3110 /* already done when ctx_dsemicolon was set to 1: */
3111 /* ctx->ctx_res_w = RES_MATCH; */
3112 ctx->ctx_dsemicolon = 0;
3115 if (!command->argv /* if it's the first word... */
3116 # if ENABLE_HUSH_LOOPS
3117 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3118 && ctx->ctx_res_w != RES_IN
3120 # if ENABLE_HUSH_CASE
3121 && ctx->ctx_res_w != RES_CASE
3124 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3125 if (reserved_word(word, ctx)) {
3126 o_reset_to_empty_unquoted(word);
3127 debug_printf_parse("done_word return %d\n",
3128 (ctx->ctx_res_w == RES_SNTX));
3129 return (ctx->ctx_res_w == RES_SNTX);
3131 # if ENABLE_HUSH_BASH_COMPAT
3132 if (strcmp(word->data, "[[") == 0) {
3133 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3139 if (command->group) {
3140 /* "{ echo foo; } echo bar" - bad */
3141 syntax_error_at(word->data);
3142 debug_printf_parse("done_word return 1: syntax error, "
3143 "groups and arglists don't mix\n");
3146 if (word->has_quoted_part
3147 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3148 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3149 /* (otherwise it's known to be not empty and is already safe) */
3151 /* exclude "$@" - it can expand to no word despite "" */
3152 char *p = word->data;
3153 while (p[0] == SPECIAL_VAR_SYMBOL
3154 && (p[1] & 0x7f) == '@'
3155 && p[2] == SPECIAL_VAR_SYMBOL
3159 if (p == word->data || p[0] != '\0') {
3160 /* saw no "$@", or not only "$@" but some
3161 * real text is there too */
3162 /* insert "empty variable" reference, this makes
3163 * e.g. "", $empty"" etc to not disappear */
3164 o_addchr(word, SPECIAL_VAR_SYMBOL);
3165 o_addchr(word, SPECIAL_VAR_SYMBOL);
3168 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3169 debug_print_strings("word appended to argv", command->argv);
3172 #if ENABLE_HUSH_LOOPS
3173 if (ctx->ctx_res_w == RES_FOR) {
3174 if (word->has_quoted_part
3175 || !is_well_formed_var_name(command->argv[0], '\0')
3177 /* bash says just "not a valid identifier" */
3178 syntax_error("not a valid identifier in for");
3181 /* Force FOR to have just one word (variable name) */
3182 /* NB: basically, this makes hush see "for v in ..."
3183 * syntax as if it is "for v; in ...". FOR and IN become
3184 * two pipe structs in parse tree. */
3185 done_pipe(ctx, PIPE_SEQ);
3188 #if ENABLE_HUSH_CASE
3189 /* Force CASE to have just one word */
3190 if (ctx->ctx_res_w == RES_CASE) {
3191 done_pipe(ctx, PIPE_SEQ);
3195 o_reset_to_empty_unquoted(word);
3197 debug_printf_parse("done_word return 0\n");
3202 /* Peek ahead in the input to find out if we have a "&n" construct,
3203 * as in "2>&1", that represents duplicating a file descriptor.
3205 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3206 * REDIRFD_SYNTAX_ERR if syntax error,
3207 * REDIRFD_TO_FILE if no & was seen,
3208 * or the number found.
3211 #define parse_redir_right_fd(as_string, input) \
3212 parse_redir_right_fd(input)
3214 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3220 return REDIRFD_TO_FILE;
3222 ch = i_getch(input); /* get the & */
3223 nommu_addchr(as_string, ch);
3226 ch = i_getch(input);
3227 nommu_addchr(as_string, ch);
3228 return REDIRFD_CLOSE;
3232 while (ch != EOF && isdigit(ch)) {
3233 d = d*10 + (ch-'0');
3235 ch = i_getch(input);
3236 nommu_addchr(as_string, ch);
3241 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3243 bb_error_msg("ambiguous redirect");
3244 return REDIRFD_SYNTAX_ERR;
3247 /* Return code is 0 normal, 1 if a syntax error is detected
3249 static int parse_redirect(struct parse_context *ctx,
3252 struct in_str *input)
3254 struct command *command = ctx->command;
3255 struct redir_struct *redir;
3256 struct redir_struct **redirp;
3259 dup_num = REDIRFD_TO_FILE;
3260 if (style != REDIRECT_HEREDOC) {
3261 /* Check for a '>&1' type redirect */
3262 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3263 if (dup_num == REDIRFD_SYNTAX_ERR)
3266 int ch = i_peek(input);
3267 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3268 if (dup_num) { /* <<-... */
3269 ch = i_getch(input);
3270 nommu_addchr(&ctx->as_string, ch);
3275 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3276 int ch = i_peek(input);
3278 /* >|FILE redirect ("clobbering" >).
3279 * Since we do not support "set -o noclobber" yet,
3280 * >| and > are the same for now. Just eat |.
3282 ch = i_getch(input);
3283 nommu_addchr(&ctx->as_string, ch);
3287 /* Create a new redir_struct and append it to the linked list */
3288 redirp = &command->redirects;
3289 while ((redir = *redirp) != NULL) {
3290 redirp = &(redir->next);
3292 *redirp = redir = xzalloc(sizeof(*redir));
3293 /* redir->next = NULL; */
3294 /* redir->rd_filename = NULL; */
3295 redir->rd_type = style;
3296 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3298 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3299 redir_table[style].descrip);
3301 redir->rd_dup = dup_num;
3302 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3303 /* Erik had a check here that the file descriptor in question
3304 * is legit; I postpone that to "run time"
3305 * A "-" representation of "close me" shows up as a -3 here */
3306 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3307 redir->rd_fd, redir->rd_dup);
3309 /* Set ctx->pending_redirect, so we know what to do at the
3310 * end of the next parsed word. */
3311 ctx->pending_redirect = redir;
3316 /* If a redirect is immediately preceded by a number, that number is
3317 * supposed to tell which file descriptor to redirect. This routine
3318 * looks for such preceding numbers. In an ideal world this routine
3319 * needs to handle all the following classes of redirects...
3320 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3321 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3322 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3323 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3325 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3327 * ... If n is quoted, the number shall not be recognized as part of
3328 * the redirection expression. For example:
3330 * writes the character 2 into file a"
3331 * We are getting it right by setting ->has_quoted_part on any \<char>
3333 * A -1 return means no valid number was found,
3334 * the caller should use the appropriate default for this redirection.
3336 static int redirect_opt_num(o_string *o)
3340 if (o->data == NULL)
3342 num = bb_strtou(o->data, NULL, 10);
3343 if (errno || num < 0)
3345 o_reset_to_empty_unquoted(o);
3350 #define fetch_till_str(as_string, input, word, skip_tabs) \
3351 fetch_till_str(input, word, skip_tabs)
3353 static char *fetch_till_str(o_string *as_string,
3354 struct in_str *input,
3358 o_string heredoc = NULL_O_STRING;
3360 int prev = 0; /* not \ */
3366 ch = i_getch(input);
3368 nommu_addchr(as_string, ch);
3369 if ((ch == '\n' || ch == EOF)
3370 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3372 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3373 heredoc.data[past_EOL] = '\0';
3374 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3375 return heredoc.data;
3377 while (ch == '\n') {
3378 o_addchr(&heredoc, ch);
3381 past_EOL = heredoc.length;
3383 ch = i_getch(input);
3385 nommu_addchr(as_string, ch);
3386 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3390 o_free_unsafe(&heredoc);
3393 o_addchr(&heredoc, ch);
3394 nommu_addchr(as_string, ch);
3395 if (prev == '\\' && ch == '\\')
3396 /* Correctly handle foo\\<eol> (not a line cont.) */
3397 prev = 0; /* not \ */
3403 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3404 * and load them all. There should be exactly heredoc_cnt of them.
3406 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3408 struct pipe *pi = ctx->list_head;
3410 while (pi && heredoc_cnt) {
3412 struct command *cmd = pi->cmds;
3414 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3416 cmd->argv ? cmd->argv[0] : "NONE");
3417 for (i = 0; i < pi->num_cmds; i++) {
3418 struct redir_struct *redir = cmd->redirects;
3420 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3421 i, cmd->argv ? cmd->argv[0] : "NONE");
3423 if (redir->rd_type == REDIRECT_HEREDOC) {
3426 redir->rd_type = REDIRECT_HEREDOC2;
3427 /* redir->rd_dup is (ab)used to indicate <<- */
3428 p = fetch_till_str(&ctx->as_string, input,
3429 redir->rd_filename, redir->rd_dup);
3431 syntax_error("unexpected EOF in here document");
3434 free(redir->rd_filename);
3435 redir->rd_filename = p;
3438 redir = redir->next;
3445 /* Should be 0. If it isn't, it's a parse error */
3447 bb_error_msg_and_die("heredoc BUG 2");
3453 static int run_list(struct pipe *pi);
3455 #define parse_stream(pstring, input, end_trigger) \
3456 parse_stream(input, end_trigger)
3458 static struct pipe *parse_stream(char **pstring,
3459 struct in_str *input,
3463 #if !ENABLE_HUSH_FUNCTIONS
3464 #define parse_group(dest, ctx, input, ch) \
3465 parse_group(ctx, input, ch)
3467 static int parse_group(o_string *dest, struct parse_context *ctx,
3468 struct in_str *input, int ch)
3470 /* dest contains characters seen prior to ( or {.
3471 * Typically it's empty, but for function defs,
3472 * it contains function name (without '()'). */
3473 struct pipe *pipe_list;
3475 struct command *command = ctx->command;
3477 debug_printf_parse("parse_group entered\n");
3478 #if ENABLE_HUSH_FUNCTIONS
3479 if (ch == '(' && !dest->has_quoted_part) {
3481 if (done_word(dest, ctx))
3484 goto skip; /* (... */
3485 if (command->argv[1]) { /* word word ... (... */
3486 syntax_error_unexpected_ch('(');
3489 /* it is "word(..." or "word (..." */
3491 ch = i_getch(input);
3492 while (ch == ' ' || ch == '\t');
3494 syntax_error_unexpected_ch(ch);
3497 nommu_addchr(&ctx->as_string, ch);
3499 ch = i_getch(input);
3500 while (ch == ' ' || ch == '\t' || ch == '\n');
3502 syntax_error_unexpected_ch(ch);
3505 nommu_addchr(&ctx->as_string, ch);
3506 command->cmd_type = CMD_FUNCDEF;
3511 #if 0 /* Prevented by caller */
3512 if (command->argv /* word [word]{... */
3513 || dest->length /* word{... */
3514 || dest->has_quoted_part /* ""{... */
3517 debug_printf_parse("parse_group return 1: "
3518 "syntax error, groups and arglists don't mix\n");
3523 #if ENABLE_HUSH_FUNCTIONS
3529 command->cmd_type = CMD_SUBSHELL;
3531 /* bash does not allow "{echo...", requires whitespace */
3532 ch = i_getch(input);
3533 if (ch != ' ' && ch != '\t' && ch != '\n') {
3534 syntax_error_unexpected_ch(ch);
3537 nommu_addchr(&ctx->as_string, ch);
3542 # define as_string NULL
3544 char *as_string = NULL;
3546 pipe_list = parse_stream(&as_string, input, endch);
3549 o_addstr(&ctx->as_string, as_string);
3551 /* empty ()/{} or parse error? */
3552 if (!pipe_list || pipe_list == ERR_PTR) {
3553 /* parse_stream already emitted error msg */
3556 debug_printf_parse("parse_group return 1: "
3557 "parse_stream returned %p\n", pipe_list);
3560 command->group = pipe_list;
3562 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3563 command->group_as_string = as_string;
3564 debug_printf_parse("end of group, remembering as:'%s'\n",
3565 command->group_as_string);
3569 debug_printf_parse("parse_group return 0\n");
3571 /* command remains "open", available for possible redirects */
3574 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3575 /* Subroutines for copying $(...) and `...` things */
3576 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3578 static int add_till_single_quote(o_string *dest, struct in_str *input)
3581 int ch = i_getch(input);
3583 syntax_error_unterm_ch('\'');
3591 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3592 static int add_till_double_quote(o_string *dest, struct in_str *input)
3595 int ch = i_getch(input);
3597 syntax_error_unterm_ch('"');
3602 if (ch == '\\') { /* \x. Copy both chars. */
3604 ch = i_getch(input);
3608 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3613 //if (ch == '$') ...
3616 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3618 * "Within the backquoted style of command substitution, backslash
3619 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3620 * The search for the matching backquote shall be satisfied by the first
3621 * backquote found without a preceding backslash; during this search,
3622 * if a non-escaped backquote is encountered within a shell comment,
3623 * a here-document, an embedded command substitution of the $(command)
3624 * form, or a quoted string, undefined results occur. A single-quoted
3625 * or double-quoted string that begins, but does not end, within the
3626 * "`...`" sequence produces undefined results."
3628 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3630 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3633 int ch = i_getch(input);
3637 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3638 ch = i_getch(input);
3642 && (!in_dquote || ch != '"')
3644 o_addchr(dest, '\\');
3648 syntax_error_unterm_ch('`');
3654 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3655 * quoting and nested ()s.
3656 * "With the $(command) style of command substitution, all characters
3657 * following the open parenthesis to the matching closing parenthesis
3658 * constitute the command. Any valid shell script can be used for command,
3659 * except a script consisting solely of redirections which produces
3660 * unspecified results."
3662 * echo $(echo '(TEST)' BEST) (TEST) BEST
3663 * echo $(echo 'TEST)' BEST) TEST) BEST
3664 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3666 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3667 * can contain arbitrary constructs, just like $(cmd).
3668 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3669 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3671 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3672 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3675 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3676 # if ENABLE_HUSH_BASH_COMPAT
3677 char end_char2 = end_ch >> 8;
3679 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3682 ch = i_getch(input);
3684 syntax_error_unterm_ch(end_ch);
3687 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3690 /* we look for closing )) of $((EXPR)) */
3691 if (i_peek(input) == end_ch) {
3692 i_getch(input); /* eat second ')' */
3697 if (ch == '(' || ch == '{') {
3698 ch = (ch == '(' ? ')' : '}');
3699 if (!add_till_closing_bracket(dest, input, ch))
3705 if (!add_till_single_quote(dest, input))
3711 if (!add_till_double_quote(dest, input))
3717 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3723 /* \x. Copy verbatim. Important for \(, \) */
3724 ch = i_getch(input);
3726 syntax_error_unterm_ch(')');
3735 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3737 /* Return code: 0 for OK, 1 for syntax error */
3739 #define parse_dollar(as_string, dest, input, quote_mask) \
3740 parse_dollar(dest, input, quote_mask)
3741 #define as_string NULL
3743 static int parse_dollar(o_string *as_string,
3745 struct in_str *input, unsigned char quote_mask)
3747 int ch = i_peek(input); /* first character after the $ */
3749 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3751 ch = i_getch(input);
3752 nommu_addchr(as_string, ch);
3754 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3756 debug_printf_parse(": '%c'\n", ch);
3757 o_addchr(dest, ch | quote_mask);
3760 if (!isalnum(ch) && ch != '_')
3762 ch = i_getch(input);
3763 nommu_addchr(as_string, ch);
3765 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3766 } else if (isdigit(ch)) {
3768 ch = i_getch(input);
3769 nommu_addchr(as_string, ch);
3770 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3771 debug_printf_parse(": '%c'\n", ch);
3772 o_addchr(dest, ch | quote_mask);
3773 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3774 } else switch (ch) {
3776 case '!': /* last bg pid */
3777 case '?': /* last exit code */
3778 case '#': /* number of args */
3779 case '*': /* args */
3780 case '@': /* args */
3781 goto make_one_char_var;
3783 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3785 ch = i_getch(input); /* eat '{' */
3786 nommu_addchr(as_string, ch);
3788 ch = i_getch(input); /* first char after '{' */
3789 /* It should be ${?}, or ${#var},
3790 * or even ${?+subst} - operator acting on a special variable,
3791 * or the beginning of variable name.
3794 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3797 syntax_error_unterm_str("${name}");
3798 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3801 nommu_addchr(as_string, ch);
3804 /* It's possible to just call add_till_closing_bracket() at this point.
3805 * However, this regresses some of our testsuite cases
3806 * which check invalid constructs like ${%}.
3807 * Oh well... let's check that the var name part is fine... */
3813 debug_printf_parse(": '%c'\n", ch);
3815 ch = i_getch(input);
3816 nommu_addchr(as_string, ch);
3820 if (!isalnum(ch) && ch != '_') {
3822 unsigned char last_ch;
3823 /* handle parameter expansions
3824 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3826 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3827 goto bad_dollar_syntax;
3829 /* Eat everything until closing '}' (or ':') */
3831 if (ENABLE_HUSH_BASH_COMPAT
3833 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3835 /* It's ${var:N[:M]} thing */
3836 end_ch = '}' * 0x100 + ':';
3838 if (ENABLE_HUSH_BASH_COMPAT
3841 /* It's ${var/[/]pattern[/repl]} thing */
3842 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3844 nommu_addchr(as_string, '/');
3847 end_ch = '}' * 0x100 + '/';
3853 #if ENABLE_HUSH_DOLLAR_OPS
3854 last_ch = add_till_closing_bracket(dest, input, end_ch);
3855 if (last_ch == 0) /* error? */
3858 #error Simple code to only allow ${var} is not implemented
3861 o_addstr(as_string, dest->data + pos);
3862 o_addchr(as_string, last_ch);
3865 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3866 /* close the first block: */
3867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3868 /* while parsing N from ${var:N[:M]}
3869 * or pattern from ${var/[/]pattern[/repl]} */
3870 if ((end_ch & 0xff) == last_ch) {
3871 /* got ':' or '/'- parse the rest */
3876 if (end_ch == '}' * 0x100 + ':') {
3877 /* it's ${var:N} - emulate :999999999 */
3878 o_addstr(dest, "999999999");
3879 } /* else: it's ${var/[/]pattern} */
3884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3887 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3891 ch = i_getch(input);
3892 nommu_addchr(as_string, ch);
3893 # if ENABLE_SH_MATH_SUPPORT
3894 if (i_peek(input) == '(') {
3895 ch = i_getch(input);
3896 nommu_addchr(as_string, ch);
3897 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3898 o_addchr(dest, /*quote_mask |*/ '+');
3901 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3902 return 0; /* error */
3904 o_addstr(as_string, dest->data + pos);
3905 o_addchr(as_string, ')');
3906 o_addchr(as_string, ')');
3908 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3912 # if ENABLE_HUSH_TICK
3913 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3914 o_addchr(dest, quote_mask | '`');
3917 if (!add_till_closing_bracket(dest, input, ')'))
3918 return 0; /* error */
3920 o_addstr(as_string, dest->data + pos);
3921 o_addchr(as_string, ')');
3923 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3929 ch = i_getch(input);
3930 nommu_addchr(as_string, ch);
3932 if (isalnum(ch)) { /* it's $_name or $_123 */
3937 /* TODO: $_ and $-: */
3938 /* $_ Shell or shell script name; or last argument of last command
3939 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3940 * but in command's env, set to full pathname used to invoke it */
3941 /* $- Option flags set by set builtin or shell options (-i etc) */
3943 o_addQchr(dest, '$');
3945 debug_printf_parse("parse_dollar return 1 (ok)\n");
3951 # if ENABLE_HUSH_BASH_COMPAT
3952 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3953 encode_string(dest, input, dquote_end, process_bkslash)
3955 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3956 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3957 encode_string(dest, input, dquote_end)
3959 #define as_string NULL
3963 # if ENABLE_HUSH_BASH_COMPAT
3964 /* all parameters are needed, no macro tricks */
3966 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3967 encode_string(as_string, dest, input, dquote_end)
3970 static int encode_string(o_string *as_string,
3972 struct in_str *input,
3974 int process_bkslash)
3976 #if !ENABLE_HUSH_BASH_COMPAT
3977 const int process_bkslash = 1;
3983 ch = i_getch(input);
3985 nommu_addchr(as_string, ch);
3986 if (ch == dquote_end) { /* may be only '"' or EOF */
3987 debug_printf_parse("encode_string return 1 (ok)\n");
3990 /* note: can't move it above ch == dquote_end check! */
3992 syntax_error_unterm_ch('"');
3993 return 0; /* error */
3997 next = i_peek(input);
3999 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4000 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4001 if (process_bkslash && ch == '\\') {
4003 syntax_error("\\<eof>");
4007 * "The backslash retains its special meaning [in "..."]
4008 * only when followed by one of the following characters:
4009 * $, `, ", \, or <newline>. A double quote may be quoted
4010 * within double quotes by preceding it with a backslash."
4011 * NB: in (unquoted) heredoc, above does not apply to ",
4012 * therefore we check for it by "next == dquote_end" cond.
4014 if (next == dquote_end || strchr("$`\\\n", next)) {
4015 ch = i_getch(input); /* eat next */
4017 goto again; /* skip \<newline> */
4018 } /* else: ch remains == '\\', and we double it below: */
4019 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4020 nommu_addchr(as_string, ch);
4024 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4025 debug_printf_parse("encode_string return 0: "
4026 "parse_dollar returned 0 (error)\n");
4031 #if ENABLE_HUSH_TICK
4033 //unsigned pos = dest->length;
4034 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4035 o_addchr(dest, 0x80 | '`');
4036 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4037 return 0; /* error */
4038 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4039 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4043 o_addQchr(dest, ch);
4049 * Scan input until EOF or end_trigger char.
4050 * Return a list of pipes to execute, or NULL on EOF
4051 * or if end_trigger character is met.
4052 * On syntax error, exit if shell is not interactive,
4053 * reset parsing machinery and start parsing anew,
4054 * or return ERR_PTR.
4056 static struct pipe *parse_stream(char **pstring,
4057 struct in_str *input,
4060 struct parse_context ctx;
4061 o_string dest = NULL_O_STRING;
4064 /* Single-quote triggers a bypass of the main loop until its mate is
4065 * found. When recursing, quote state is passed in via dest->o_expflags.
4067 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4068 end_trigger ? end_trigger : 'X');
4071 /* If very first arg is "" or '', dest.data may end up NULL.
4072 * Preventing this: */
4073 o_addchr(&dest, '\0');
4076 /* We used to separate words on $IFS here. This was wrong.
4077 * $IFS is used only for word splitting when $var is expanded,
4078 * here we should use blank chars as separators, not $IFS
4081 if (MAYBE_ASSIGNMENT != 0)
4082 dest.o_assignment = MAYBE_ASSIGNMENT;
4083 initialize_context(&ctx);
4086 const char *is_blank;
4087 const char *is_special;
4091 redir_type redir_style;
4093 ch = i_getch(input);
4094 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4095 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4100 syntax_error_unterm_str("here document");
4103 /* end_trigger == '}' case errors out earlier,
4104 * checking only ')' */
4105 if (end_trigger == ')') {
4106 syntax_error_unterm_ch('(');
4110 if (done_word(&dest, &ctx)) {
4114 done_pipe(&ctx, PIPE_SEQ);
4116 /* If we got nothing... */
4117 /* (this makes bare "&" cmd a no-op.
4118 * bash says: "syntax error near unexpected token '&'") */
4119 if (pi->num_cmds == 0
4120 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4126 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4128 *pstring = ctx.as_string.data;
4130 o_free_unsafe(&ctx.as_string);
4133 debug_printf_parse("parse_stream return %p\n", pi);
4136 nommu_addchr(&ctx.as_string, ch);
4140 next = i_peek(input);
4142 is_special = "{}<>;&|()#'" /* special outside of "str" */
4143 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4144 /* Are { and } special here? */
4145 if (ctx.command->argv /* word [word]{... - non-special */
4146 || dest.length /* word{... - non-special */
4147 || dest.has_quoted_part /* ""{... - non-special */
4148 || (next != ';' /* }; - special */
4149 && next != ')' /* }) - special */
4150 && next != '&' /* }& and }&& ... - special */
4151 && next != '|' /* }|| ... - special */
4152 && !strchr(defifs, next) /* {word - non-special */
4155 /* They are not special, skip "{}" */
4158 is_special = strchr(is_special, ch);
4159 is_blank = strchr(defifs, ch);
4161 if (!is_special && !is_blank) { /* ordinary char */
4163 o_addQchr(&dest, ch);
4164 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4165 || dest.o_assignment == WORD_IS_KEYWORD)
4167 && is_well_formed_var_name(dest.data, '=')
4169 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4175 if (done_word(&dest, &ctx)) {
4179 /* Is this a case when newline is simply ignored?
4181 * "cmd | <newline> cmd ..."
4182 * "case ... in <newline> word) ..."
4184 if (IS_NULL_CMD(ctx.command)
4185 && dest.length == 0 && !dest.has_quoted_part
4187 /* This newline can be ignored. But...
4188 * Without check #1, interactive shell
4189 * ignores even bare <newline>,
4190 * and shows the continuation prompt:
4191 * ps1_prompt$ <enter>
4192 * ps2> _ <=== wrong, should be ps1
4193 * Without check #2, "cmd & <newline>"
4194 * is similarly mistreated.
4195 * (BTW, this makes "cmd & cmd"
4196 * and "cmd && cmd" non-orthogonal.
4197 * Really, ask yourself, why
4198 * "cmd && <newline>" doesn't start
4199 * cmd but waits for more input?
4202 struct pipe *pi = ctx.list_head;
4203 if (pi->num_cmds != 0 /* check #1 */
4204 && pi->followup != PIPE_BG /* check #2 */
4209 /* Treat newline as a command separator. */
4210 done_pipe(&ctx, PIPE_SEQ);
4211 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4213 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4218 dest.o_assignment = MAYBE_ASSIGNMENT;
4220 /* note: if (is_blank) continue;
4221 * will still trigger for us */
4225 /* "cmd}" or "cmd }..." without semicolon or &:
4226 * } is an ordinary char in this case, even inside { cmd; }
4227 * Pathological example: { ""}; } should exec "}" cmd
4230 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4231 || dest.length != 0 /* word} */
4232 || dest.has_quoted_part /* ""} */
4236 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4237 goto skip_end_trigger;
4238 /* else: } does terminate a group */
4241 if (end_trigger && end_trigger == ch
4242 && (ch != ';' || heredoc_cnt == 0)
4243 #if ENABLE_HUSH_CASE
4245 || ctx.ctx_res_w != RES_MATCH
4246 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4251 /* This is technically valid:
4252 * { cat <<HERE; }; echo Ok
4256 * but we don't support this.
4257 * We require heredoc to be in enclosing {}/(),
4260 syntax_error_unterm_str("here document");
4263 if (done_word(&dest, &ctx)) {
4266 done_pipe(&ctx, PIPE_SEQ);
4267 dest.o_assignment = MAYBE_ASSIGNMENT;
4268 /* Do we sit outside of any if's, loops or case's? */
4270 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4274 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4276 *pstring = ctx.as_string.data;
4278 o_free_unsafe(&ctx.as_string);
4281 debug_printf_parse("parse_stream return %p: "
4282 "end_trigger char found\n",
4284 return ctx.list_head;
4291 /* Catch <, > before deciding whether this word is
4292 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4295 redir_fd = redirect_opt_num(&dest);
4296 if (done_word(&dest, &ctx)) {
4299 redir_style = REDIRECT_OVERWRITE;
4301 redir_style = REDIRECT_APPEND;
4302 ch = i_getch(input);
4303 nommu_addchr(&ctx.as_string, ch);
4306 else if (next == '(') {
4307 syntax_error(">(process) not supported");
4311 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4313 continue; /* back to top of while (1) */
4315 redir_fd = redirect_opt_num(&dest);
4316 if (done_word(&dest, &ctx)) {
4319 redir_style = REDIRECT_INPUT;
4321 redir_style = REDIRECT_HEREDOC;
4323 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4324 ch = i_getch(input);
4325 nommu_addchr(&ctx.as_string, ch);
4326 } else if (next == '>') {
4327 redir_style = REDIRECT_IO;
4328 ch = i_getch(input);
4329 nommu_addchr(&ctx.as_string, ch);
4332 else if (next == '(') {
4333 syntax_error("<(process) not supported");
4337 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4339 continue; /* back to top of while (1) */
4341 if (dest.length == 0 && !dest.has_quoted_part) {
4342 /* skip "#comment" */
4345 if (ch == EOF || ch == '\n')
4348 /* note: we do not add it to &ctx.as_string */
4350 nommu_addchr(&ctx.as_string, '\n');
4351 continue; /* back to top of while (1) */
4356 /* It's "\<newline>" */
4358 /* Remove trailing '\' from ctx.as_string */
4359 ctx.as_string.data[--ctx.as_string.length] = '\0';
4361 ch = i_getch(input); /* eat it */
4362 continue; /* back to top of while (1) */
4367 if (dest.o_assignment == MAYBE_ASSIGNMENT
4368 /* check that we are not in word in "a=1 2>word b=1": */
4369 && !ctx.pending_redirect
4371 /* ch is a special char and thus this word
4372 * cannot be an assignment */
4373 dest.o_assignment = NOT_ASSIGNMENT;
4376 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4379 case '#': /* non-comment #: "echo a#b" etc */
4380 o_addQchr(&dest, ch);
4384 syntax_error("\\<eof>");
4387 ch = i_getch(input);
4388 /* note: ch != '\n' (that case does not reach this place) */
4389 o_addchr(&dest, '\\');
4390 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4391 o_addchr(&dest, ch);
4392 nommu_addchr(&ctx.as_string, ch);
4393 /* Example: echo Hello \2>file
4394 * we need to know that word 2 is quoted */
4395 dest.has_quoted_part = 1;
4398 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4399 debug_printf_parse("parse_stream parse error: "
4400 "parse_dollar returned 0 (error)\n");
4405 dest.has_quoted_part = 1;
4407 ch = i_getch(input);
4409 syntax_error_unterm_ch('\'');
4412 nommu_addchr(&ctx.as_string, ch);
4415 o_addqchr(&dest, ch);
4419 dest.has_quoted_part = 1;
4420 if (dest.o_assignment == NOT_ASSIGNMENT)
4421 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4422 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4424 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4426 #if ENABLE_HUSH_TICK
4430 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4431 o_addchr(&dest, '`');
4433 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4436 o_addstr(&ctx.as_string, dest.data + pos);
4437 o_addchr(&ctx.as_string, '`');
4439 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4440 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4445 #if ENABLE_HUSH_CASE
4448 if (done_word(&dest, &ctx)) {
4451 done_pipe(&ctx, PIPE_SEQ);
4452 #if ENABLE_HUSH_CASE
4453 /* Eat multiple semicolons, detect
4454 * whether it means something special */
4459 ch = i_getch(input);
4460 nommu_addchr(&ctx.as_string, ch);
4461 if (ctx.ctx_res_w == RES_CASE_BODY) {
4462 ctx.ctx_dsemicolon = 1;
4463 ctx.ctx_res_w = RES_MATCH;
4469 /* We just finished a cmd. New one may start
4470 * with an assignment */
4471 dest.o_assignment = MAYBE_ASSIGNMENT;
4474 if (done_word(&dest, &ctx)) {
4478 ch = i_getch(input);
4479 nommu_addchr(&ctx.as_string, ch);
4480 done_pipe(&ctx, PIPE_AND);
4482 done_pipe(&ctx, PIPE_BG);
4486 if (done_word(&dest, &ctx)) {
4489 #if ENABLE_HUSH_CASE
4490 if (ctx.ctx_res_w == RES_MATCH)
4491 break; /* we are in case's "word | word)" */
4493 if (next == '|') { /* || */
4494 ch = i_getch(input);
4495 nommu_addchr(&ctx.as_string, ch);
4496 done_pipe(&ctx, PIPE_OR);
4498 /* we could pick up a file descriptor choice here
4499 * with redirect_opt_num(), but bash doesn't do it.
4500 * "echo foo 2| cat" yields "foo 2". */
4503 o_reset_to_empty_unquoted(&ctx.as_string);
4508 #if ENABLE_HUSH_CASE
4509 /* "case... in [(]word)..." - skip '(' */
4510 if (ctx.ctx_res_w == RES_MATCH
4511 && ctx.command->argv == NULL /* not (word|(... */
4512 && dest.length == 0 /* not word(... */
4513 && dest.has_quoted_part == 0 /* not ""(... */
4519 if (parse_group(&dest, &ctx, input, ch) != 0) {
4524 #if ENABLE_HUSH_CASE
4525 if (ctx.ctx_res_w == RES_MATCH)
4529 /* proper use of this character is caught by end_trigger:
4530 * if we see {, we call parse_group(..., end_trigger='}')
4531 * and it will match } earlier (not here). */
4532 syntax_error_unexpected_ch(ch);
4536 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4542 struct parse_context *pctx;
4543 IF_HAS_KEYWORDS(struct parse_context *p2;)
4545 /* Clean up allocated tree.
4546 * Sample for finding leaks on syntax error recovery path.
4547 * Run it from interactive shell, watch pmap `pidof hush`.
4548 * while if false; then false; fi; do break; fi
4549 * Samples to catch leaks at execution:
4550 * while if (true | {true;}); then echo ok; fi; do break; done
4551 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4555 /* Update pipe/command counts,
4556 * otherwise freeing may miss some */
4557 done_pipe(pctx, PIPE_SEQ);
4558 debug_printf_clean("freeing list %p from ctx %p\n",
4559 pctx->list_head, pctx);
4560 debug_print_tree(pctx->list_head, 0);
4561 free_pipe_list(pctx->list_head);
4562 debug_printf_clean("freed list %p\n", pctx->list_head);
4564 o_free_unsafe(&pctx->as_string);
4566 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4570 IF_HAS_KEYWORDS(pctx = p2;)
4571 } while (HAS_KEYWORDS && pctx);
4574 G.last_exitcode = 1;
4585 /*** Execution routines ***/
4587 /* Expansion can recurse, need forward decls: */
4588 #if !ENABLE_HUSH_BASH_COMPAT
4589 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4590 #define expand_string_to_string(str, do_unbackslash) \
4591 expand_string_to_string(str)
4593 static char *expand_string_to_string(const char *str, int do_unbackslash);
4594 #if ENABLE_HUSH_TICK
4595 static int process_command_subs(o_string *dest, const char *s);
4598 /* expand_strvec_to_strvec() takes a list of strings, expands
4599 * all variable references within and returns a pointer to
4600 * a list of expanded strings, possibly with larger number
4601 * of strings. (Think VAR="a b"; echo $VAR).
4602 * This new list is allocated as a single malloc block.
4603 * NULL-terminated list of char* pointers is at the beginning of it,
4604 * followed by strings themselves.
4605 * Caller can deallocate entire list by single free(list). */
4607 /* A horde of its helpers come first: */
4609 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4611 while (--len >= 0) {
4614 #if ENABLE_HUSH_BRACE_EXPANSION
4615 if (c == '{' || c == '}') {
4616 /* { -> \{, } -> \} */
4618 /* And now we want to add { or } and continue:
4621 * luckily, just falling throught achieves this.
4627 /* \z -> \\\z; \<eol> -> \\<eol> */
4632 o_addchr(o, *str++);
4638 /* Store given string, finalizing the word and starting new one whenever
4639 * we encounter IFS char(s). This is used for expanding variable values.
4640 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4641 static int expand_on_ifs(o_string *output, int n, const char *str)
4644 int word_len = strcspn(str, G.ifs);
4646 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4647 o_addblock(output, str, word_len);
4649 /* Protect backslashes against globbing up :)
4650 * Example: "v='\*'; echo b$v" prints "b\*"
4651 * (and does not try to glob on "*")
4653 o_addblock_duplicate_backslash(output, str, word_len);
4654 /*/ Why can't we do it easier? */
4655 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4656 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4660 if (!*str) /* EOL - do not finalize word */
4662 o_addchr(output, '\0');
4663 debug_print_list("expand_on_ifs", output, n);
4664 n = o_save_ptr(output, n);
4665 str += strspn(str, G.ifs); /* skip ifs chars */
4667 debug_print_list("expand_on_ifs[1]", output, n);
4671 /* Helper to expand $((...)) and heredoc body. These act as if
4672 * they are in double quotes, with the exception that they are not :).
4673 * Just the rules are similar: "expand only $var and `cmd`"
4675 * Returns malloced string.
4676 * As an optimization, we return NULL if expansion is not needed.
4678 #if !ENABLE_HUSH_BASH_COMPAT
4679 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4680 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4681 encode_then_expand_string(str)
4683 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4686 struct in_str input;
4687 o_string dest = NULL_O_STRING;
4689 if (!strchr(str, '$')
4690 && !strchr(str, '\\')
4691 #if ENABLE_HUSH_TICK
4692 && !strchr(str, '`')
4698 /* We need to expand. Example:
4699 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4701 setup_string_in_str(&input, str);
4702 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4703 //TODO: error check (encode_string returns 0 on error)?
4704 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4705 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4706 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4707 o_free_unsafe(&dest);
4711 #if ENABLE_SH_MATH_SUPPORT
4712 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4714 arith_state_t math_state;
4718 math_state.lookupvar = get_local_var_value;
4719 math_state.setvar = set_local_var_from_halves;
4720 //math_state.endofname = endofname;
4721 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4722 res = arith(&math_state, exp_str ? exp_str : arg);
4725 *errmsg_p = math_state.errmsg;
4726 if (math_state.errmsg)
4727 die_if_script(math_state.errmsg);
4732 #if ENABLE_HUSH_BASH_COMPAT
4733 /* ${var/[/]pattern[/repl]} helpers */
4734 static char *strstr_pattern(char *val, const char *pattern, int *size)
4737 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4738 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4745 /* Optimization: if "*pat" did not match the start of "string",
4746 * we know that "tring", "ring" etc will not match too:
4748 if (pattern[0] == '*')
4753 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4755 char *result = NULL;
4756 unsigned res_len = 0;
4757 unsigned repl_len = strlen(repl);
4761 char *s = strstr_pattern(val, pattern, &size);
4765 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4766 memcpy(result + res_len, val, s - val);
4768 strcpy(result + res_len, repl);
4769 res_len += repl_len;
4770 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4776 if (val[0] && result) {
4777 result = xrealloc(result, res_len + strlen(val) + 1);
4778 strcpy(result + res_len, val);
4779 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4781 debug_printf_varexp("result:'%s'\n", result);
4787 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4789 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4791 const char *val = NULL;
4792 char *to_be_freed = NULL;
4797 char exp_save = exp_save; /* for compiler */
4798 char *exp_saveptr; /* points to expansion operator */
4799 char *exp_word = exp_word; /* for compiler */
4802 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4804 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4806 first_char = arg[0] = arg0 & 0x7f;
4809 if (first_char == '#' /* ${#... */
4810 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4812 /* It must be length operator: ${#var} */
4816 /* Maybe handle parameter expansion */
4817 if (exp_saveptr /* if 2nd char is one of expansion operators */
4818 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4820 /* ${?:0}, ${#[:]%0} etc */
4821 exp_saveptr = var + 1;
4823 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4824 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4826 exp_op = exp_save = *exp_saveptr;
4828 exp_word = exp_saveptr + 1;
4829 if (exp_op == ':') {
4830 exp_op = *exp_word++;
4831 //TODO: try ${var:} and ${var:bogus} in non-bash config
4832 if (ENABLE_HUSH_BASH_COMPAT
4833 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4835 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4840 *exp_saveptr = '\0';
4841 } /* else: it's not an expansion op, but bare ${var} */
4844 /* Look up the variable in question */
4845 if (isdigit(var[0])) {
4846 /* parse_dollar should have vetted var for us */
4847 int n = xatoi_positive(var);
4848 if (n < G.global_argc)
4849 val = G.global_argv[n];
4850 /* else val remains NULL: $N with too big N */
4854 val = utoa(G.root_pid);
4856 case '!': /* bg pid */
4857 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4859 case '?': /* exitcode */
4860 val = utoa(G.last_exitcode);
4862 case '#': /* argc */
4863 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4866 val = get_local_var_value(var);
4870 /* Handle any expansions */
4871 if (exp_op == 'L') {
4872 debug_printf_expand("expand: length(%s)=", val);
4873 val = utoa(val ? strlen(val) : 0);
4874 debug_printf_expand("%s\n", val);
4875 } else if (exp_op) {
4876 if (exp_op == '%' || exp_op == '#') {
4877 /* Standard-mandated substring removal ops:
4878 * ${parameter%word} - remove smallest suffix pattern
4879 * ${parameter%%word} - remove largest suffix pattern
4880 * ${parameter#word} - remove smallest prefix pattern
4881 * ${parameter##word} - remove largest prefix pattern
4883 * Word is expanded to produce a glob pattern.
4884 * Then var's value is matched to it and matching part removed.
4886 if (val && val[0]) {
4890 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4891 if (exp_op == *exp_word) /* ## or %% */
4893 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4895 exp_word = exp_exp_word;
4896 /* HACK ALERT. We depend here on the fact that
4897 * G.global_argv and results of utoa and get_local_var_value
4898 * are actually in writable memory:
4899 * scan_and_match momentarily stores NULs there. */
4901 loc = scan_and_match(t, exp_word, scan_flags);
4902 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4903 // exp_op, t, exp_word, loc);
4905 if (loc) { /* match was found */
4906 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4907 val = loc; /* take right part */
4909 val = to_be_freed = xstrndup(val, loc - val); /* left */
4913 #if ENABLE_HUSH_BASH_COMPAT
4914 else if (exp_op == '/' || exp_op == '\\') {
4915 /* It's ${var/[/]pattern[/repl]} thing.
4916 * Note that in encoded form it has TWO parts:
4917 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4918 * and if // is used, it is encoded as \:
4919 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4921 /* Empty variable always gives nothing: */
4922 // "v=''; echo ${v/*/w}" prints "", not "w"
4923 if (val && val[0]) {
4924 /* pattern uses non-standard expansion.
4925 * repl should be unbackslashed and globbed
4926 * by the usual expansion rules:
4928 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4929 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4930 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4931 * v='a bz'; echo ${v/a*z/\z} prints "z"
4932 * (note that a*z _pattern_ is never globbed!)
4934 char *pattern, *repl, *t;
4935 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4937 pattern = xstrdup(exp_word);
4938 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4939 *p++ = SPECIAL_VAR_SYMBOL;
4941 p = strchr(p, SPECIAL_VAR_SYMBOL);
4943 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4944 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4945 /* HACK ALERT. We depend here on the fact that
4946 * G.global_argv and results of utoa and get_local_var_value
4947 * are actually in writable memory:
4948 * replace_pattern momentarily stores NULs there. */
4950 to_be_freed = replace_pattern(t,
4952 (repl ? repl : exp_word),
4954 if (to_be_freed) /* at least one replace happened */
4961 else if (exp_op == ':') {
4962 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4963 /* It's ${var:N[:M]} bashism.
4964 * Note that in encoded form it has TWO parts:
4965 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4970 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4973 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4974 *p++ = SPECIAL_VAR_SYMBOL;
4976 p = strchr(p, SPECIAL_VAR_SYMBOL);
4978 len = expand_and_evaluate_arith(exp_word, &errmsg);
4981 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4982 if (len >= 0) { /* bash compat: len < 0 is illegal */
4983 if (beg < 0) /* bash compat */
4985 debug_printf_varexp("from val:'%s'\n", val);
4986 if (len == 0 || !val || beg >= strlen(val)) {
4990 /* Paranoia. What if user entered 9999999999999
4991 * which fits in arith_t but not int? */
4994 val = to_be_freed = xstrndup(val + beg, len);
4996 debug_printf_varexp("val:'%s'\n", val);
5000 die_if_script("malformed ${%s:...}", var);
5003 } else { /* one of "-=+?" */
5004 /* Standard-mandated substitution ops:
5005 * ${var?word} - indicate error if unset
5006 * If var is unset, word (or a message indicating it is unset
5007 * if word is null) is written to standard error
5008 * and the shell exits with a non-zero exit status.
5009 * Otherwise, the value of var is substituted.
5010 * ${var-word} - use default value
5011 * If var is unset, word is substituted.
5012 * ${var=word} - assign and use default value
5013 * If var is unset, word is assigned to var.
5014 * In all cases, final value of var is substituted.
5015 * ${var+word} - use alternative value
5016 * If var is unset, null is substituted.
5017 * Otherwise, word is substituted.
5019 * Word is subjected to tilde expansion, parameter expansion,
5020 * command substitution, and arithmetic expansion.
5021 * If word is not needed, it is not expanded.
5023 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5024 * but also treat null var as if it is unset.
5026 int use_word = (!val || ((exp_save == ':') && !val[0]));
5028 use_word = !use_word;
5029 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5030 (exp_save == ':') ? "true" : "false", use_word);
5032 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5034 exp_word = to_be_freed;
5035 if (exp_op == '?') {
5036 /* mimic bash message */
5037 die_if_script("%s: %s",
5039 exp_word[0] ? exp_word : "parameter null or not set"
5041 //TODO: how interactive bash aborts expansion mid-command?
5046 if (exp_op == '=') {
5047 /* ${var=[word]} or ${var:=[word]} */
5048 if (isdigit(var[0]) || var[0] == '#') {
5049 /* mimic bash message */
5050 die_if_script("$%s: cannot assign in this way", var);
5053 char *new_var = xasprintf("%s=%s", var, val);
5054 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5058 } /* one of "-=+?" */
5060 *exp_saveptr = exp_save;
5066 *to_be_freed_pp = to_be_freed;
5070 /* Expand all variable references in given string, adding words to list[]
5071 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5072 * to be filled). This routine is extremely tricky: has to deal with
5073 * variables/parameters with whitespace, $* and $@, and constructs like
5074 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5075 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5077 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5078 * expansion of right-hand side of assignment == 1-element expand.
5080 char cant_be_null = 0; /* only bit 0x80 matters */
5083 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5084 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5085 debug_print_list("expand_vars_to_list", output, n);
5086 n = o_save_ptr(output, n);
5087 debug_print_list("expand_vars_to_list[0]", output, n);
5089 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5091 char *to_be_freed = NULL;
5092 const char *val = NULL;
5093 #if ENABLE_HUSH_TICK
5094 o_string subst_result = NULL_O_STRING;
5096 #if ENABLE_SH_MATH_SUPPORT
5097 char arith_buf[sizeof(arith_t)*3 + 2];
5099 o_addblock(output, arg, p - arg);
5100 debug_print_list("expand_vars_to_list[1]", output, n);
5102 p = strchr(p, SPECIAL_VAR_SYMBOL);
5104 /* Fetch special var name (if it is indeed one of them)
5105 * and quote bit, force the bit on if singleword expansion -
5106 * important for not getting v=$@ expand to many words. */
5107 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5109 /* Is this variable quoted and thus expansion can't be null?
5110 * "$@" is special. Even if quoted, it can still
5111 * expand to nothing (not even an empty string),
5112 * thus it is excluded. */
5113 if ((first_ch & 0x7f) != '@')
5114 cant_be_null |= first_ch;
5116 switch (first_ch & 0x7f) {
5117 /* Highest bit in first_ch indicates that var is double-quoted */
5121 if (!G.global_argv[1])
5124 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5125 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5126 while (G.global_argv[i]) {
5127 n = expand_on_ifs(output, n, G.global_argv[i]);
5128 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5129 if (G.global_argv[i++][0] && G.global_argv[i]) {
5130 /* this argv[] is not empty and not last:
5131 * put terminating NUL, start new word */
5132 o_addchr(output, '\0');
5133 debug_print_list("expand_vars_to_list[2]", output, n);
5134 n = o_save_ptr(output, n);
5135 debug_print_list("expand_vars_to_list[3]", output, n);
5139 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5140 * and in this case should treat it like '$*' - see 'else...' below */
5141 if (first_ch == ('@'|0x80) /* quoted $@ */
5142 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5145 o_addQstr(output, G.global_argv[i]);
5146 if (++i >= G.global_argc)
5148 o_addchr(output, '\0');
5149 debug_print_list("expand_vars_to_list[4]", output, n);
5150 n = o_save_ptr(output, n);
5152 } else { /* quoted $* (or v="$@" case): add as one word */
5154 o_addQstr(output, G.global_argv[i]);
5155 if (!G.global_argv[++i])
5158 o_addchr(output, G.ifs[0]);
5163 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5164 /* "Empty variable", used to make "" etc to not disappear */
5166 cant_be_null = 0x80;
5168 #if ENABLE_HUSH_TICK
5169 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5170 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5172 /* Can't just stuff it into output o_string,
5173 * expanded result may need to be globbed
5174 * and $IFS-splitted */
5175 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5176 G.last_exitcode = process_command_subs(&subst_result, arg);
5177 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5178 val = subst_result.data;
5181 #if ENABLE_SH_MATH_SUPPORT
5182 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5185 arg++; /* skip '+' */
5186 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5187 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5188 res = expand_and_evaluate_arith(arg, NULL);
5189 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5190 sprintf(arith_buf, ARITH_FMT, res);
5196 val = expand_one_var(&to_be_freed, arg, &p);
5197 IF_HUSH_TICK(store_val:)
5198 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5199 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5200 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5201 if (val && val[0]) {
5202 n = expand_on_ifs(output, n, val);
5205 } else { /* quoted $VAR, val will be appended below */
5206 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5207 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5211 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5213 if (val && val[0]) {
5214 o_addQstr(output, val);
5218 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5219 * Do the check to avoid writing to a const string. */
5220 if (*p != SPECIAL_VAR_SYMBOL)
5221 *p = SPECIAL_VAR_SYMBOL;
5223 #if ENABLE_HUSH_TICK
5224 o_free(&subst_result);
5227 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5230 debug_print_list("expand_vars_to_list[a]", output, n);
5231 /* this part is literal, and it was already pre-quoted
5232 * if needed (much earlier), do not use o_addQstr here! */
5233 o_addstr_with_NUL(output, arg);
5234 debug_print_list("expand_vars_to_list[b]", output, n);
5235 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5236 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5239 /* allow to reuse list[n] later without re-growth */
5240 output->has_empty_slot = 1;
5242 o_addchr(output, '\0');
5248 static char **expand_variables(char **argv, unsigned expflags)
5252 o_string output = NULL_O_STRING;
5254 output.o_expflags = expflags;
5258 n = expand_vars_to_list(&output, n, *argv);
5261 debug_print_list("expand_variables", &output, n);
5263 /* output.data (malloced in one block) gets returned in "list" */
5264 list = o_finalize_list(&output, n);
5265 debug_print_strings("expand_variables[1]", list);
5269 static char **expand_strvec_to_strvec(char **argv)
5271 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5274 #if ENABLE_HUSH_BASH_COMPAT
5275 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5277 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5281 /* Used for expansion of right hand of assignments,
5282 * $((...)), heredocs, variable espansion parts.
5284 * NB: should NOT do globbing!
5285 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5287 static char *expand_string_to_string(const char *str, int do_unbackslash)
5289 #if !ENABLE_HUSH_BASH_COMPAT
5290 const int do_unbackslash = 1;
5292 char *argv[2], **list;
5294 debug_printf_expand("string_to_string<='%s'\n", str);
5295 /* This is generally an optimization, but it also
5296 * handles "", which otherwise trips over !list[0] check below.
5297 * (is this ever happens that we actually get str="" here?)
5299 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5300 //TODO: Can use on strings with \ too, just unbackslash() them?
5301 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5302 return xstrdup(str);
5305 argv[0] = (char*)str;
5307 list = expand_variables(argv, do_unbackslash
5308 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5309 : EXP_FLAG_SINGLEWORD
5312 if (!list[0] || list[1])
5313 bb_error_msg_and_die("BUG in varexp2");
5314 /* actually, just move string 2*sizeof(char*) bytes back */
5315 overlapping_strcpy((char*)list, list[0]);
5317 unbackslash((char*)list);
5318 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5322 /* Used for "eval" builtin */
5323 static char* expand_strvec_to_string(char **argv)
5327 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5328 /* Convert all NULs to spaces */
5333 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5334 bb_error_msg_and_die("BUG in varexp3");
5335 /* bash uses ' ' regardless of $IFS contents */
5340 overlapping_strcpy((char*)list, list[0]);
5341 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5345 static char **expand_assignments(char **argv, int count)
5350 G.expanded_assignments = p = NULL;
5351 /* Expand assignments into one string each */
5352 for (i = 0; i < count; i++) {
5353 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5355 G.expanded_assignments = NULL;
5362 void re_execute_shell(char ***to_free, const char *s,
5363 char *g_argv0, char **g_argv,
5364 char **builtin_argv) NORETURN;
5366 static void reset_traps_to_defaults(void)
5368 /* This function is always called in a child shell
5369 * after fork (not vfork, NOMMU doesn't use this function).
5374 /* Child shells are not interactive.
5375 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5376 * Testcase: (while :; do :; done) + ^Z should background.
5377 * Same goes for SIGTERM, SIGHUP, SIGINT.
5379 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5380 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5382 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5383 * Stupid. It can be done with *single* &= op, but we can't use
5384 * the fact that G.blocked_set is implemented as a bitmask
5386 mask = SPECIAL_INTERACTIVE_SIGS;
5388 while ((mask >>= 1) != 0) {
5391 /* Careful. Only if no trap or trap is not "" */
5392 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5393 sigdelset(&G.blocked_set, sig);
5396 /* Our homegrown sig mask is saner to work with :) */
5397 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5399 /* Resetting all traps to default except empty ones */
5400 mask = G.non_DFL_mask;
5401 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5402 if (!G.traps[sig] || !G.traps[sig][0])
5405 G.traps[sig] = NULL;
5406 /* There is no signal for 0 (EXIT) */
5409 /* There was a trap handler, we just removed it.
5410 * But if sig still has non-DFL handling,
5411 * we should not unblock the sig. */
5414 sigdelset(&G.blocked_set, sig);
5416 sigprocmask_set(&G.blocked_set);
5421 static void re_execute_shell(char ***to_free, const char *s,
5422 char *g_argv0, char **g_argv,
5423 char **builtin_argv) NORETURN;
5424 static void re_execute_shell(char ***to_free, const char *s,
5425 char *g_argv0, char **g_argv,
5426 char **builtin_argv)
5428 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5429 /* delims + 2 * (number of bytes in printed hex numbers) */
5430 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5431 char *heredoc_argv[4];
5432 struct variable *cur;
5433 # if ENABLE_HUSH_FUNCTIONS
5434 struct function *funcp;
5438 unsigned long long empty_trap_mask;
5440 if (!g_argv0) { /* heredoc */
5441 argv = heredoc_argv;
5442 argv[0] = (char *) G.argv0_for_re_execing;
5443 argv[1] = (char *) "-<";
5444 argv[2] = (char *) s;
5446 pp = &argv[3]; /* used as pointer to empty environment */
5452 if (pp) while (*pp++)
5455 empty_trap_mask = 0;
5458 for (sig = 1; sig < NSIG; sig++) {
5459 if (G.traps[sig] && !G.traps[sig][0])
5460 empty_trap_mask |= 1LL << sig;
5464 sprintf(param_buf, NOMMU_HACK_FMT
5465 , (unsigned) G.root_pid
5466 , (unsigned) G.root_ppid
5467 , (unsigned) G.last_bg_pid
5468 , (unsigned) G.last_exitcode
5471 IF_HUSH_LOOPS(, G.depth_of_loop)
5473 # undef NOMMU_HACK_FMT
5474 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5475 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5478 for (cur = G.top_var; cur; cur = cur->next) {
5479 if (!cur->flg_export || cur->flg_read_only)
5482 # if ENABLE_HUSH_FUNCTIONS
5483 for (funcp = G.top_func; funcp; funcp = funcp->next)
5489 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5490 *pp++ = (char *) G.argv0_for_re_execing;
5492 for (cur = G.top_var; cur; cur = cur->next) {
5493 if (strcmp(cur->varstr, hush_version_str) == 0)
5495 if (cur->flg_read_only) {
5496 *pp++ = (char *) "-R";
5497 *pp++ = cur->varstr;
5498 } else if (!cur->flg_export) {
5499 *pp++ = (char *) "-V";
5500 *pp++ = cur->varstr;
5503 # if ENABLE_HUSH_FUNCTIONS
5504 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5505 *pp++ = (char *) "-F";
5506 *pp++ = funcp->name;
5507 *pp++ = funcp->body_as_string;
5510 /* We can pass activated traps here. Say, -Tnn:trap_string
5512 * However, POSIX says that subshells reset signals with traps
5514 * I tested bash-3.2 and it not only does that with true subshells
5515 * of the form ( list ), but with any forked children shells.
5516 * I set trap "echo W" WINCH; and then tried:
5518 * { echo 1; sleep 20; echo 2; } &
5519 * while true; do echo 1; sleep 20; echo 2; break; done &
5520 * true | { echo 1; sleep 20; echo 2; } | cat
5522 * In all these cases sending SIGWINCH to the child shell
5523 * did not run the trap. If I add trap "echo V" WINCH;
5524 * _inside_ group (just before echo 1), it works.
5526 * I conclude it means we don't need to pass active traps here.
5527 * Even if we would use signal handlers instead of signal masking
5528 * in order to implement trap handling,
5529 * exec syscall below resets signals to SIG_DFL for us.
5531 *pp++ = (char *) "-c";
5534 while (*++builtin_argv)
5535 *pp++ = *builtin_argv;
5536 *pp++ = (char *) "";
5541 /* *pp = NULL; - is already there */
5545 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5546 sigprocmask_set(&G.inherited_set);
5547 execve(bb_busybox_exec_path, argv, pp);
5548 /* Fallback. Useful for init=/bin/hush usage etc */
5549 if (argv[0][0] == '/')
5550 execve(argv[0], argv, pp);
5551 xfunc_error_retval = 127;
5552 bb_error_msg_and_die("can't re-execute the shell");
5554 #endif /* !BB_MMU */
5557 static int run_and_free_list(struct pipe *pi);
5559 /* Executing from string: eval, sh -c '...'
5560 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5561 * end_trigger controls how often we stop parsing
5562 * NUL: parse all, execute, return
5563 * ';': parse till ';' or newline, execute, repeat till EOF
5565 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5567 /* Why we need empty flag?
5568 * An obscure corner case "false; ``; echo $?":
5569 * empty command in `` should still set $? to 0.
5570 * But we can't just set $? to 0 at the start,
5571 * this breaks "false; echo `echo $?`" case.
5575 struct pipe *pipe_list;
5577 #if ENABLE_HUSH_INTERACTIVE
5578 if (end_trigger == ';')
5579 inp->promptmode = 0; /* PS1 */
5581 pipe_list = parse_stream(NULL, inp, end_trigger);
5582 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5583 /* If we are in "big" script
5584 * (not in `cmd` or something similar)...
5586 if (pipe_list == ERR_PTR && end_trigger == ';') {
5587 /* Discard cached input (rest of line) */
5588 int ch = inp->last_char;
5589 while (ch != EOF && ch != '\n') {
5590 //bb_error_msg("Discarded:'%c'", ch);
5595 /* This stream isn't empty */
5599 if (!pipe_list && empty)
5600 G.last_exitcode = 0;
5603 debug_print_tree(pipe_list, 0);
5604 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5605 run_and_free_list(pipe_list);
5607 #if ENABLE_HUSH_FUNCTIONS
5608 if (G.flag_return_in_progress == 1)
5614 static void parse_and_run_string(const char *s)
5616 struct in_str input;
5617 setup_string_in_str(&input, s);
5618 parse_and_run_stream(&input, '\0');
5621 static void parse_and_run_file(FILE *f)
5623 struct in_str input;
5624 setup_file_in_str(&input, f);
5625 parse_and_run_stream(&input, ';');
5628 #if ENABLE_HUSH_TICK
5629 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5634 char **to_free = NULL;
5638 pid = BB_MMU ? xfork() : xvfork();
5639 if (pid == 0) { /* child */
5640 disable_restore_tty_pgrp_on_exit();
5641 /* Process substitution is not considered to be usual
5642 * 'command execution'.
5643 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5650 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5651 close(channel[0]); /* NB: close _first_, then move fd! */
5652 xmove_fd(channel[1], 1);
5653 /* Prevent it from trying to handle ctrl-z etc */
5654 IF_HUSH_JOB(G.run_list_level = 1;)
5655 /* Awful hack for `trap` or $(trap).
5657 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5658 * contains an example where "trap" is executed in a subshell:
5660 * save_traps=$(trap)
5662 * eval "$save_traps"
5664 * Standard does not say that "trap" in subshell shall print
5665 * parent shell's traps. It only says that its output
5666 * must have suitable form, but then, in the above example
5667 * (which is not supposed to be normative), it implies that.
5669 * bash (and probably other shell) does implement it
5670 * (traps are reset to defaults, but "trap" still shows them),
5671 * but as a result, "trap" logic is hopelessly messed up:
5674 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5675 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5676 * # true | trap <--- trap is in subshell - no output (ditto)
5677 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5678 * trap -- 'echo Ho' SIGWINCH
5679 * # echo `(trap)` <--- in subshell in subshell - output
5680 * trap -- 'echo Ho' SIGWINCH
5681 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5682 * trap -- 'echo Ho' SIGWINCH
5684 * The rules when to forget and when to not forget traps
5685 * get really complex and nonsensical.
5687 * Our solution: ONLY bare $(trap) or `trap` is special.
5689 s = skip_whitespace(s);
5690 if (strncmp(s, "trap", 4) == 0
5691 && skip_whitespace(s + 4)[0] == '\0'
5693 static const char *const argv[] = { NULL, NULL };
5694 builtin_trap((char**)argv);
5695 exit(0); /* not _exit() - we need to fflush */
5698 reset_traps_to_defaults();
5699 parse_and_run_string(s);
5700 _exit(G.last_exitcode);
5702 /* We re-execute after vfork on NOMMU. This makes this script safe:
5703 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5704 * huge=`cat BIG` # was blocking here forever
5707 re_execute_shell(&to_free,
5717 # if ENABLE_HUSH_FAST
5719 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5720 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5721 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5723 enable_restore_tty_pgrp_on_exit();
5728 close_on_exec_on(channel[0]);
5729 return xfdopen_for_read(channel[0]);
5732 /* Return code is exit status of the process that is run. */
5733 static int process_command_subs(o_string *dest, const char *s)
5736 struct in_str pipe_str;
5738 int status, ch, eol_cnt;
5740 fp = generate_stream_from_string(s, &pid);
5742 /* Now send results of command back into original context */
5743 setup_file_in_str(&pipe_str, fp);
5745 while ((ch = i_getch(&pipe_str)) != EOF) {
5751 o_addchr(dest, '\n');
5754 o_addQchr(dest, ch);
5757 debug_printf("done reading from `cmd` pipe, closing it\n");
5759 /* We need to extract exitcode. Test case
5760 * "true; echo `sleep 1; false` $?"
5762 safe_waitpid(pid, &status, 0);
5763 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5764 return WEXITSTATUS(status);
5766 #endif /* ENABLE_HUSH_TICK */
5769 static void setup_heredoc(struct redir_struct *redir)
5771 struct fd_pair pair;
5774 /* the _body_ of heredoc (misleading field name) */
5775 const char *heredoc = redir->rd_filename;
5782 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5783 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5787 len = strlen(heredoc);
5789 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5791 xmove_fd(pair.rd, redir->rd_fd);
5793 /* Try writing without forking. Newer kernels have
5794 * dynamically growing pipes. Must use non-blocking write! */
5797 written = write(pair.wr, heredoc, len);
5808 ndelay_off(pair.wr);
5810 /* Okay, pipe buffer was not big enough */
5811 /* Note: we must not create a stray child (bastard? :)
5812 * for the unsuspecting parent process. Child creates a grandchild
5813 * and exits before parent execs the process which consumes heredoc
5814 * (that exec happens after we return from this function) */
5821 disable_restore_tty_pgrp_on_exit();
5822 pid = BB_MMU ? xfork() : xvfork();
5826 close(redir->rd_fd); /* read side of the pipe */
5828 full_write(pair.wr, heredoc, len); /* may loop or block */
5831 /* Delegate blocking writes to another process */
5832 xmove_fd(pair.wr, STDOUT_FILENO);
5833 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5837 #if ENABLE_HUSH_FAST
5839 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5841 enable_restore_tty_pgrp_on_exit();
5847 wait(NULL); /* wait till child has died */
5850 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5851 * and stderr if they are redirected. */
5852 static int setup_redirects(struct command *prog, int squirrel[])
5855 struct redir_struct *redir;
5857 for (redir = prog->redirects; redir; redir = redir->next) {
5858 if (redir->rd_type == REDIRECT_HEREDOC2) {
5859 /* rd_fd<<HERE case */
5860 if (squirrel && redir->rd_fd < 3
5861 && squirrel[redir->rd_fd] < 0
5863 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5865 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5867 debug_printf_parse("set heredoc '%s'\n",
5868 redir->rd_filename);
5869 setup_heredoc(redir);
5873 if (redir->rd_dup == REDIRFD_TO_FILE) {
5874 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5876 if (redir->rd_filename == NULL) {
5877 /* Something went wrong in the parse.
5878 * Pretend it didn't happen */
5879 bb_error_msg("bug in redirect parse");
5882 mode = redir_table[redir->rd_type].mode;
5883 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5884 openfd = open_or_warn(p, mode);
5887 /* this could get lost if stderr has been redirected, but
5888 * bash and ash both lose it as well (though zsh doesn't!) */
5889 //what the above comment tries to say?
5893 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5894 openfd = redir->rd_dup;
5897 if (openfd != redir->rd_fd) {
5898 if (squirrel && redir->rd_fd < 3
5899 && squirrel[redir->rd_fd] < 0
5901 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5903 if (openfd == REDIRFD_CLOSE) {
5904 /* "n>-" means "close me" */
5905 close(redir->rd_fd);
5907 xdup2(openfd, redir->rd_fd);
5908 if (redir->rd_dup == REDIRFD_TO_FILE)
5916 static void restore_redirects(int squirrel[])
5919 for (i = 0; i < 3; i++) {
5922 /* We simply die on error */
5928 static char *find_in_path(const char *arg)
5931 const char *PATH = get_local_var_value("PATH");
5937 const char *end = strchrnul(PATH, ':');
5938 int sz = end - PATH; /* must be int! */
5942 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5944 /* We have xxx::yyyy in $PATH,
5945 * it means "use current dir" */
5948 if (access(ret, F_OK) == 0)
5961 static const struct built_in_command *find_builtin_helper(const char *name,
5962 const struct built_in_command *x,
5963 const struct built_in_command *end)
5966 if (strcmp(name, x->b_cmd) != 0) {
5970 debug_printf_exec("found builtin '%s'\n", name);
5975 static const struct built_in_command *find_builtin1(const char *name)
5977 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5979 static const struct built_in_command *find_builtin(const char *name)
5981 const struct built_in_command *x = find_builtin1(name);
5984 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5987 #if ENABLE_HUSH_FUNCTIONS
5988 static struct function **find_function_slot(const char *name)
5990 struct function **funcpp = &G.top_func;
5992 if (strcmp(name, (*funcpp)->name) == 0) {
5995 funcpp = &(*funcpp)->next;
6000 static const struct function *find_function(const char *name)
6002 const struct function *funcp = *find_function_slot(name);
6004 debug_printf_exec("found function '%s'\n", name);
6008 /* Note: takes ownership on name ptr */
6009 static struct function *new_function(char *name)
6011 struct function **funcpp = find_function_slot(name);
6012 struct function *funcp = *funcpp;
6014 if (funcp != NULL) {
6015 struct command *cmd = funcp->parent_cmd;
6016 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6018 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6020 /* Note: if !funcp->body, do not free body_as_string!
6021 * This is a special case of "-F name body" function:
6022 * body_as_string was not malloced! */
6024 free_pipe_list(funcp->body);
6026 free(funcp->body_as_string);
6030 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6031 cmd->argv[0] = funcp->name;
6032 cmd->group = funcp->body;
6034 cmd->group_as_string = funcp->body_as_string;
6038 debug_printf_exec("remembering new function '%s'\n", name);
6039 funcp = *funcpp = xzalloc(sizeof(*funcp));
6040 /*funcp->next = NULL;*/
6047 static void unset_func(const char *name)
6049 struct function **funcpp = find_function_slot(name);
6050 struct function *funcp = *funcpp;
6052 if (funcp != NULL) {
6053 debug_printf_exec("freeing function '%s'\n", funcp->name);
6054 *funcpp = funcp->next;
6055 /* funcp is unlinked now, deleting it.
6056 * Note: if !funcp->body, the function was created by
6057 * "-F name body", do not free ->body_as_string
6058 * and ->name as they were not malloced. */
6060 free_pipe_list(funcp->body);
6063 free(funcp->body_as_string);
6071 #define exec_function(to_free, funcp, argv) \
6072 exec_function(funcp, argv)
6074 static void exec_function(char ***to_free,
6075 const struct function *funcp,
6076 char **argv) NORETURN;
6077 static void exec_function(char ***to_free,
6078 const struct function *funcp,
6084 argv[0] = G.global_argv[0];
6085 G.global_argv = argv;
6089 /* On MMU, funcp->body is always non-NULL */
6090 n = run_list(funcp->body);
6094 re_execute_shell(to_free,
6095 funcp->body_as_string,
6102 static int run_function(const struct function *funcp, char **argv)
6108 save_and_replace_G_args(&sv, argv);
6110 /* "we are in function, ok to use return" */
6111 sv_flg = G.flag_return_in_progress;
6112 G.flag_return_in_progress = -1;
6113 # if ENABLE_HUSH_LOCAL
6114 G.func_nest_level++;
6117 /* On MMU, funcp->body is always non-NULL */
6120 /* Function defined by -F */
6121 parse_and_run_string(funcp->body_as_string);
6122 rc = G.last_exitcode;
6126 rc = run_list(funcp->body);
6129 # if ENABLE_HUSH_LOCAL
6131 struct variable *var;
6132 struct variable **var_pp;
6134 var_pp = &G.top_var;
6135 while ((var = *var_pp) != NULL) {
6136 if (var->func_nest_level < G.func_nest_level) {
6137 var_pp = &var->next;
6141 if (var->flg_export)
6142 bb_unsetenv(var->varstr);
6143 /* Remove from global list */
6144 *var_pp = var->next;
6150 G.func_nest_level--;
6153 G.flag_return_in_progress = sv_flg;
6155 restore_G_args(&sv, argv);
6159 #endif /* ENABLE_HUSH_FUNCTIONS */
6163 #define exec_builtin(to_free, x, argv) \
6164 exec_builtin(x, argv)
6166 #define exec_builtin(to_free, x, argv) \
6167 exec_builtin(to_free, argv)
6169 static void exec_builtin(char ***to_free,
6170 const struct built_in_command *x,
6171 char **argv) NORETURN;
6172 static void exec_builtin(char ***to_free,
6173 const struct built_in_command *x,
6179 rcode = x->b_function(argv);
6184 /* On NOMMU, we must never block!
6185 * Example: { sleep 99 | read line; } & echo Ok
6187 re_execute_shell(to_free,
6196 static void execvp_or_die(char **argv) NORETURN;
6197 static void execvp_or_die(char **argv)
6199 debug_printf_exec("execing '%s'\n", argv[0]);
6200 sigprocmask_set(&G.inherited_set);
6201 execvp(argv[0], argv);
6202 bb_perror_msg("can't execute '%s'", argv[0]);
6203 _exit(127); /* bash compat */
6206 #if ENABLE_HUSH_MODE_X
6207 static void dump_cmd_in_x_mode(char **argv)
6209 if (G_x_mode && argv) {
6210 /* We want to output the line in one write op */
6218 len += strlen(argv[n++]) + 1;
6224 p += sprintf(p, " %s", argv[n++]);
6232 # define dump_cmd_in_x_mode(argv) ((void)0)
6236 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6237 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6238 #define pseudo_exec(nommu_save, command, argv_expanded) \
6239 pseudo_exec(command, argv_expanded)
6242 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6244 * Don't exit() here. If you don't exec, use _exit instead.
6245 * The at_exit handlers apparently confuse the calling process,
6246 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6247 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6248 char **argv, int assignment_cnt,
6249 char **argv_expanded) NORETURN;
6250 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6251 char **argv, int assignment_cnt,
6252 char **argv_expanded)
6256 new_env = expand_assignments(argv, assignment_cnt);
6257 dump_cmd_in_x_mode(new_env);
6259 if (!argv[assignment_cnt]) {
6260 /* Case when we are here: ... | var=val | ...
6261 * (note that we do not exit early, i.e., do not optimize out
6262 * expand_assignments(): think about ... | var=`sleep 1` | ...
6264 free_strings(new_env);
6265 _exit(EXIT_SUCCESS);
6269 set_vars_and_save_old(new_env);
6270 free(new_env); /* optional */
6271 /* we can also destroy set_vars_and_save_old's return value,
6274 nommu_save->new_env = new_env;
6275 nommu_save->old_vars = set_vars_and_save_old(new_env);
6278 if (argv_expanded) {
6279 argv = argv_expanded;
6281 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6283 nommu_save->argv = argv;
6286 dump_cmd_in_x_mode(argv);
6288 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6289 if (strchr(argv[0], '/') != NULL)
6293 /* Check if the command matches any of the builtins.
6294 * Depending on context, this might be redundant. But it's
6295 * easier to waste a few CPU cycles than it is to figure out
6296 * if this is one of those cases.
6299 /* On NOMMU, it is more expensive to re-execute shell
6300 * just in order to run echo or test builtin.
6301 * It's better to skip it here and run corresponding
6302 * non-builtin later. */
6303 const struct built_in_command *x;
6304 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6306 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6309 #if ENABLE_HUSH_FUNCTIONS
6310 /* Check if the command matches any functions */
6312 const struct function *funcp = find_function(argv[0]);
6314 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6319 #if ENABLE_FEATURE_SH_STANDALONE
6320 /* Check if the command matches any busybox applets */
6322 int a = find_applet_by_name(argv[0]);
6324 # if BB_MMU /* see above why on NOMMU it is not allowed */
6325 if (APPLET_IS_NOEXEC(a)) {
6326 debug_printf_exec("running applet '%s'\n", argv[0]);
6327 run_applet_no_and_exit(a, argv);
6330 /* Re-exec ourselves */
6331 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6332 sigprocmask_set(&G.inherited_set);
6333 execv(bb_busybox_exec_path, argv);
6334 /* If they called chroot or otherwise made the binary no longer
6335 * executable, fall through */
6340 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6343 execvp_or_die(argv);
6346 /* Called after [v]fork() in run_pipe
6348 static void pseudo_exec(nommu_save_t *nommu_save,
6349 struct command *command,
6350 char **argv_expanded) NORETURN;
6351 static void pseudo_exec(nommu_save_t *nommu_save,
6352 struct command *command,
6353 char **argv_expanded)
6355 if (command->argv) {
6356 pseudo_exec_argv(nommu_save, command->argv,
6357 command->assignment_cnt, argv_expanded);
6360 if (command->group) {
6361 /* Cases when we are here:
6364 * ... | ( list ) | ...
6365 * ... | { list } | ...
6369 debug_printf_exec("pseudo_exec: run_list\n");
6370 reset_traps_to_defaults();
6371 rcode = run_list(command->group);
6372 /* OK to leak memory by not calling free_pipe_list,
6373 * since this process is about to exit */
6376 re_execute_shell(&nommu_save->argv_from_re_execing,
6377 command->group_as_string,
6384 /* Case when we are here: ... | >file */
6385 debug_printf_exec("pseudo_exec'ed null command\n");
6386 _exit(EXIT_SUCCESS);
6390 static const char *get_cmdtext(struct pipe *pi)
6396 /* This is subtle. ->cmdtext is created only on first backgrounding.
6397 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6398 * On subsequent bg argv is trashed, but we won't use it */
6401 argv = pi->cmds[0].argv;
6402 if (!argv || !argv[0]) {
6403 pi->cmdtext = xzalloc(1);
6409 len += strlen(*argv) + 1;
6413 argv = pi->cmds[0].argv;
6415 len = strlen(*argv);
6416 memcpy(p, *argv, len);
6424 static void insert_bg_job(struct pipe *pi)
6426 struct pipe *job, **jobp;
6429 /* Linear search for the ID of the job to use */
6431 for (job = G.job_list; job; job = job->next)
6432 if (job->jobid >= pi->jobid)
6433 pi->jobid = job->jobid + 1;
6435 /* Add job to the list of running jobs */
6437 while ((job = *jobp) != NULL)
6439 job = *jobp = xmalloc(sizeof(*job));
6441 *job = *pi; /* physical copy */
6443 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6444 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6445 for (i = 0; i < pi->num_cmds; i++) {
6446 job->cmds[i].pid = pi->cmds[i].pid;
6447 /* all other fields are not used and stay zero */
6449 job->cmdtext = xstrdup(get_cmdtext(pi));
6451 if (G_interactive_fd)
6452 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6453 G.last_jobid = job->jobid;
6456 static void remove_bg_job(struct pipe *pi)
6458 struct pipe *prev_pipe;
6460 if (pi == G.job_list) {
6461 G.job_list = pi->next;
6463 prev_pipe = G.job_list;
6464 while (prev_pipe->next != pi)
6465 prev_pipe = prev_pipe->next;
6466 prev_pipe->next = pi->next;
6469 G.last_jobid = G.job_list->jobid;
6474 /* Remove a backgrounded job */
6475 static void delete_finished_bg_job(struct pipe *pi)
6482 /* Check to see if any processes have exited -- if they
6483 * have, figure out why and see if a job has completed */
6484 static int checkjobs(struct pipe *fg_pipe)
6494 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6496 attributes = WUNTRACED;
6497 if (fg_pipe == NULL)
6498 attributes |= WNOHANG;
6501 #if ENABLE_HUSH_FAST
6502 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6503 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6504 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6505 /* There was neither fork nor SIGCHLD since last waitpid */
6506 /* Avoid doing waitpid syscall if possible */
6507 if (!G.we_have_children) {
6511 if (fg_pipe == NULL) { /* is WNOHANG set? */
6512 /* We have children, but they did not exit
6513 * or stop yet (we saw no SIGCHLD) */
6516 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6520 /* Do we do this right?
6521 * bash-3.00# sleep 20 | false
6523 * [3]+ Stopped sleep 20 | false
6524 * bash-3.00# echo $?
6525 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6526 * [hush 1.14.0: yes we do it right]
6533 #if ENABLE_HUSH_FAST
6534 i = G.count_SIGCHLD;
6536 childpid = waitpid(-1, &status, attributes);
6537 if (childpid <= 0) {
6538 if (childpid && errno != ECHILD)
6539 bb_perror_msg("waitpid");
6540 #if ENABLE_HUSH_FAST
6541 else { /* Until next SIGCHLD, waitpid's are useless */
6542 G.we_have_children = (childpid == 0);
6543 G.handled_SIGCHLD = i;
6544 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6549 dead = WIFEXITED(status) || WIFSIGNALED(status);
6552 if (WIFSTOPPED(status))
6553 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6554 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6555 if (WIFSIGNALED(status))
6556 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6557 childpid, WTERMSIG(status), WEXITSTATUS(status));
6558 if (WIFEXITED(status))
6559 debug_printf_jobs("pid %d exited, exitcode %d\n",
6560 childpid, WEXITSTATUS(status));
6562 /* Were we asked to wait for fg pipe? */
6564 i = fg_pipe->num_cmds;
6566 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6567 if (fg_pipe->cmds[i].pid != childpid)
6571 fg_pipe->cmds[i].pid = 0;
6572 fg_pipe->alive_cmds--;
6573 ex = WEXITSTATUS(status);
6574 /* bash prints killer signal's name for *last*
6575 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6576 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6578 if (WIFSIGNALED(status)) {
6579 int sig = WTERMSIG(status);
6580 if (i == fg_pipe->num_cmds-1)
6581 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6582 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6583 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6584 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6585 * Maybe we need to use sig | 128? */
6588 fg_pipe->cmds[i].cmd_exitcode = ex;
6590 fg_pipe->cmds[i].is_stopped = 1;
6591 fg_pipe->stopped_cmds++;
6593 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6594 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6595 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6596 /* All processes in fg pipe have exited or stopped */
6597 i = fg_pipe->num_cmds;
6599 rcode = fg_pipe->cmds[i].cmd_exitcode;
6600 /* usually last process gives overall exitstatus,
6601 * but with "set -o pipefail", last *failed* process does */
6602 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6605 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6606 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6607 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6608 * and "killall -STOP cat" */
6609 if (G_interactive_fd) {
6611 if (fg_pipe->alive_cmds != 0)
6612 insert_bg_job(fg_pipe);
6616 if (fg_pipe->alive_cmds == 0)
6619 /* There are still running processes in the fg pipe */
6620 goto wait_more; /* do waitpid again */
6622 /* it wasnt fg_pipe, look for process in bg pipes */
6626 /* We asked to wait for bg or orphaned children */
6627 /* No need to remember exitcode in this case */
6628 for (pi = G.job_list; pi; pi = pi->next) {
6629 for (i = 0; i < pi->num_cmds; i++) {
6630 if (pi->cmds[i].pid == childpid)
6631 goto found_pi_and_prognum;
6634 /* Happens when shell is used as init process (init=/bin/sh) */
6635 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6636 continue; /* do waitpid again */
6638 found_pi_and_prognum:
6641 pi->cmds[i].pid = 0;
6643 if (!pi->alive_cmds) {
6644 if (G_interactive_fd)
6645 printf(JOB_STATUS_FORMAT, pi->jobid,
6646 "Done", pi->cmdtext);
6647 delete_finished_bg_job(pi);
6651 pi->cmds[i].is_stopped = 1;
6655 } /* while (waitpid succeeds)... */
6661 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6664 int rcode = checkjobs(fg_pipe);
6665 if (G_saved_tty_pgrp) {
6666 /* Job finished, move the shell to the foreground */
6667 p = getpgrp(); /* our process group id */
6668 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6669 tcsetpgrp(G_interactive_fd, p);
6675 /* Start all the jobs, but don't wait for anything to finish.
6678 * Return code is normally -1, when the caller has to wait for children
6679 * to finish to determine the exit status of the pipe. If the pipe
6680 * is a simple builtin command, however, the action is done by the
6681 * time run_pipe returns, and the exit code is provided as the
6684 * Returns -1 only if started some children. IOW: we have to
6685 * mask out retvals of builtins etc with 0xff!
6687 * The only case when we do not need to [v]fork is when the pipe
6688 * is single, non-backgrounded, non-subshell command. Examples:
6689 * cmd ; ... { list } ; ...
6690 * cmd && ... { list } && ...
6691 * cmd || ... { list } || ...
6692 * If it is, then we can run cmd as a builtin, NOFORK,
6693 * or (if SH_STANDALONE) an applet, and we can run the { list }
6694 * with run_list. If it isn't one of these, we fork and exec cmd.
6696 * Cases when we must fork:
6697 * non-single: cmd | cmd
6698 * backgrounded: cmd & { list } &
6699 * subshell: ( list ) [&]
6701 #if !ENABLE_HUSH_MODE_X
6702 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6703 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6705 static int redirect_and_varexp_helper(char ***new_env_p,
6706 struct variable **old_vars_p,
6707 struct command *command,
6709 char **argv_expanded)
6711 /* setup_redirects acts on file descriptors, not FILEs.
6712 * This is perfect for work that comes after exec().
6713 * Is it really safe for inline use? Experimentally,
6714 * things seem to work. */
6715 int rcode = setup_redirects(command, squirrel);
6717 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6718 *new_env_p = new_env;
6719 dump_cmd_in_x_mode(new_env);
6720 dump_cmd_in_x_mode(argv_expanded);
6722 *old_vars_p = set_vars_and_save_old(new_env);
6726 static NOINLINE int run_pipe(struct pipe *pi)
6728 static const char *const null_ptr = NULL;
6732 struct command *command;
6733 char **argv_expanded;
6735 /* it is not always needed, but we aim to smaller code */
6736 int squirrel[] = { -1, -1, -1 };
6739 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6742 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6743 * Result should be 3 lines: q w e, qwe, q w e
6745 G.ifs = get_local_var_value("IFS");
6749 IF_HUSH_JOB(pi->pgrp = -1;)
6750 pi->stopped_cmds = 0;
6751 command = &pi->cmds[0];
6752 argv_expanded = NULL;
6754 if (pi->num_cmds != 1
6755 || pi->followup == PIPE_BG
6756 || command->cmd_type == CMD_SUBSHELL
6763 debug_printf_exec(": group:%p argv:'%s'\n",
6764 command->group, command->argv ? command->argv[0] : "NONE");
6766 if (command->group) {
6767 #if ENABLE_HUSH_FUNCTIONS
6768 if (command->cmd_type == CMD_FUNCDEF) {
6769 /* "executing" func () { list } */
6770 struct function *funcp;
6772 funcp = new_function(command->argv[0]);
6773 /* funcp->name is already set to argv[0] */
6774 funcp->body = command->group;
6776 funcp->body_as_string = command->group_as_string;
6777 command->group_as_string = NULL;
6779 command->group = NULL;
6780 command->argv[0] = NULL;
6781 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6782 funcp->parent_cmd = command;
6783 command->child_func = funcp;
6785 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6787 return EXIT_SUCCESS;
6791 debug_printf("non-subshell group\n");
6792 rcode = 1; /* exitcode if redir failed */
6793 if (setup_redirects(command, squirrel) == 0) {
6794 debug_printf_exec(": run_list\n");
6795 rcode = run_list(command->group) & 0xff;
6797 restore_redirects(squirrel);
6798 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6800 debug_printf_exec("run_pipe: return %d\n", rcode);
6804 argv = command->argv ? command->argv : (char **) &null_ptr;
6806 const struct built_in_command *x;
6807 #if ENABLE_HUSH_FUNCTIONS
6808 const struct function *funcp;
6812 char **new_env = NULL;
6813 struct variable *old_vars = NULL;
6815 if (argv[command->assignment_cnt] == NULL) {
6816 /* Assignments, but no command */
6817 /* Ensure redirects take effect (that is, create files).
6818 * Try "a=t >file" */
6819 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6820 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6821 /* Set shell variables */
6825 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6826 /* Do we need to flag set_local_var() errors?
6827 * "assignment to readonly var" and "putenv error"
6832 /* Redirect error sets $? to 1. Otherwise,
6833 * if evaluating assignment value set $?, retain it.
6834 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6836 rcode = G.last_exitcode;
6837 /* Exit, _skipping_ variable restoring code: */
6838 goto clean_up_and_ret0;
6840 #else /* Older, bigger, but more correct code */
6842 rcode = setup_redirects(command, squirrel);
6843 restore_redirects(squirrel);
6844 /* Set shell variables */
6846 bb_putchar_stderr('+');
6848 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6850 fprintf(stderr, " %s", p);
6851 debug_printf_exec("set shell var:'%s'->'%s'\n",
6853 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6854 /* Do we need to flag set_local_var() errors?
6855 * "assignment to readonly var" and "putenv error"
6860 bb_putchar_stderr('\n');
6861 /* Redirect error sets $? to 1. Otherwise,
6862 * if evaluating assignment value set $?, retain it.
6863 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6865 rcode = G.last_exitcode;
6866 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6868 debug_printf_exec("run_pipe: return %d\n", rcode);
6873 /* Expand the rest into (possibly) many strings each */
6874 #if ENABLE_HUSH_BASH_COMPAT
6875 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6876 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6880 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6883 /* if someone gives us an empty string: `cmd with empty output` */
6884 if (!argv_expanded[0]) {
6885 free(argv_expanded);
6887 return G.last_exitcode;
6890 x = find_builtin(argv_expanded[0]);
6891 #if ENABLE_HUSH_FUNCTIONS
6894 funcp = find_function(argv_expanded[0]);
6898 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6899 debug_printf("exec with redirects only\n");
6900 rcode = setup_redirects(command, NULL);
6901 goto clean_up_and_ret1;
6904 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6907 debug_printf_exec(": builtin '%s' '%s'...\n",
6908 x->b_cmd, argv_expanded[1]);
6910 rcode = x->b_function(argv_expanded) & 0xff;
6913 #if ENABLE_HUSH_FUNCTIONS
6915 # if ENABLE_HUSH_LOCAL
6916 struct variable **sv;
6917 sv = G.shadowed_vars_pp;
6918 G.shadowed_vars_pp = &old_vars;
6920 debug_printf_exec(": function '%s' '%s'...\n",
6921 funcp->name, argv_expanded[1]);
6922 rcode = run_function(funcp, argv_expanded) & 0xff;
6923 # if ENABLE_HUSH_LOCAL
6924 G.shadowed_vars_pp = sv;
6930 unset_vars(new_env);
6932 /* clean_up_and_ret0: */
6933 restore_redirects(squirrel);
6935 free(argv_expanded);
6936 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6938 debug_printf_exec("run_pipe return %d\n", rcode);
6942 if (ENABLE_FEATURE_SH_NOFORK) {
6943 int n = find_applet_by_name(argv_expanded[0]);
6944 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6945 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6947 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6948 argv_expanded[0], argv_expanded[1]);
6949 rcode = run_nofork_applet(n, argv_expanded);
6951 goto clean_up_and_ret;
6954 /* It is neither builtin nor applet. We must fork. */
6958 /* NB: argv_expanded may already be created, and that
6959 * might include `cmd` runs! Do not rerun it! We *must*
6960 * use argv_expanded if it's non-NULL */
6962 /* Going to fork a child per each pipe member */
6967 while (cmd_no < pi->num_cmds) {
6968 struct fd_pair pipefds;
6970 volatile nommu_save_t nommu_save;
6971 nommu_save.new_env = NULL;
6972 nommu_save.old_vars = NULL;
6973 nommu_save.argv = NULL;
6974 nommu_save.argv_from_re_execing = NULL;
6976 command = &pi->cmds[cmd_no];
6978 if (command->argv) {
6979 debug_printf_exec(": pipe member '%s' '%s'...\n",
6980 command->argv[0], command->argv[1]);
6982 debug_printf_exec(": pipe member with no argv\n");
6985 /* pipes are inserted between pairs of commands */
6988 if (cmd_no < pi->num_cmds)
6989 xpiped_pair(pipefds);
6991 command->pid = BB_MMU ? fork() : vfork();
6992 if (!command->pid) { /* child */
6994 disable_restore_tty_pgrp_on_exit();
6995 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6997 /* Every child adds itself to new process group
6998 * with pgid == pid_of_first_child_in_pipe */
6999 if (G.run_list_level == 1 && G_interactive_fd) {
7002 if (pgrp < 0) /* true for 1st process only */
7004 if (setpgid(0, pgrp) == 0
7005 && pi->followup != PIPE_BG
7006 && G_saved_tty_pgrp /* we have ctty */
7008 /* We do it in *every* child, not just first,
7010 tcsetpgrp(G_interactive_fd, pgrp);
7014 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7015 /* 1st cmd in backgrounded pipe
7016 * should have its stdin /dev/null'ed */
7018 if (open(bb_dev_null, O_RDONLY))
7019 xopen("/", O_RDONLY);
7021 xmove_fd(next_infd, 0);
7023 xmove_fd(pipefds.wr, 1);
7026 /* Like bash, explicit redirects override pipes,
7027 * and the pipe fd is available for dup'ing. */
7028 if (setup_redirects(command, NULL))
7031 /* Restore default handlers just prior to exec */
7032 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
7034 /* Stores to nommu_save list of env vars putenv'ed
7035 * (NOMMU, on MMU we don't need that) */
7036 /* cast away volatility... */
7037 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7038 /* pseudo_exec() does not return */
7041 /* parent or error */
7042 #if ENABLE_HUSH_FAST
7044 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7046 enable_restore_tty_pgrp_on_exit();
7048 /* Clean up after vforked child */
7049 free(nommu_save.argv);
7050 free(nommu_save.argv_from_re_execing);
7051 unset_vars(nommu_save.new_env);
7052 add_vars(nommu_save.old_vars);
7054 free(argv_expanded);
7055 argv_expanded = NULL;
7056 if (command->pid < 0) { /* [v]fork failed */
7057 /* Clearly indicate, was it fork or vfork */
7058 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7062 /* Second and next children need to know pid of first one */
7064 pi->pgrp = command->pid;
7070 if (cmd_no < pi->num_cmds)
7072 /* Pass read (output) pipe end to next iteration */
7073 next_infd = pipefds.rd;
7076 if (!pi->alive_cmds) {
7078 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7083 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7087 /* NB: called by pseudo_exec, and therefore must not modify any
7088 * global data until exec/_exit (we can be a child after vfork!) */
7089 static int run_list(struct pipe *pi)
7091 #if ENABLE_HUSH_CASE
7092 char *case_word = NULL;
7094 #if ENABLE_HUSH_LOOPS
7095 struct pipe *loop_top = NULL;
7096 char **for_lcur = NULL;
7097 char **for_list = NULL;
7099 smallint last_followup;
7101 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7102 smalluint cond_code = 0;
7104 enum { cond_code = 0 };
7107 smallint rword; /* RES_foo */
7108 smallint last_rword; /* ditto */
7111 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7114 #if ENABLE_HUSH_LOOPS
7115 /* Check syntax for "for" */
7118 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7119 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7121 /* current word is FOR or IN (BOLD in comments below) */
7122 if (cpipe->next == NULL) {
7123 syntax_error("malformed for");
7125 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7128 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7129 if (cpipe->next->res_word == RES_DO)
7131 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7132 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7133 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7135 syntax_error("malformed for");
7137 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7144 /* Past this point, all code paths should jump to ret: label
7145 * in order to return, no direct "return" statements please.
7146 * This helps to ensure that no memory is leaked. */
7154 last_rword = RES_XXXX;
7156 last_followup = PIPE_SEQ;
7157 rcode = G.last_exitcode;
7159 /* Go through list of pipes, (maybe) executing them. */
7160 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7164 IF_HAS_KEYWORDS(rword = pi->res_word;)
7165 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7166 rword, cond_code, last_rword);
7167 #if ENABLE_HUSH_LOOPS
7168 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7169 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7171 /* start of a loop: remember where loop starts */
7176 /* Still in the same "if...", "then..." or "do..." branch? */
7177 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7178 if ((rcode == 0 && last_followup == PIPE_OR)
7179 || (rcode != 0 && last_followup == PIPE_AND)
7181 /* It is "<true> || CMD" or "<false> && CMD"
7182 * and we should not execute CMD */
7183 debug_printf_exec("skipped cmd because of || or &&\n");
7184 last_followup = pi->followup;
7188 last_followup = pi->followup;
7189 IF_HAS_KEYWORDS(last_rword = rword;)
7192 if (rword == RES_THEN) {
7193 /* if false; then ... fi has exitcode 0! */
7194 G.last_exitcode = rcode = EXIT_SUCCESS;
7195 /* "if <false> THEN cmd": skip cmd */
7199 if (rword == RES_ELSE || rword == RES_ELIF) {
7200 /* "if <true> then ... ELSE/ELIF cmd":
7201 * skip cmd and all following ones */
7206 #if ENABLE_HUSH_LOOPS
7207 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7209 /* first loop through for */
7211 static const char encoded_dollar_at[] ALIGN1 = {
7212 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7213 }; /* encoded representation of "$@" */
7214 static const char *const encoded_dollar_at_argv[] = {
7215 encoded_dollar_at, NULL
7216 }; /* argv list with one element: "$@" */
7219 vals = (char**)encoded_dollar_at_argv;
7220 if (pi->next->res_word == RES_IN) {
7221 /* if no variable values after "in" we skip "for" */
7222 if (!pi->next->cmds[0].argv) {
7223 G.last_exitcode = rcode = EXIT_SUCCESS;
7224 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7227 vals = pi->next->cmds[0].argv;
7228 } /* else: "for var; do..." -> assume "$@" list */
7229 /* create list of variable values */
7230 debug_print_strings("for_list made from", vals);
7231 for_list = expand_strvec_to_strvec(vals);
7232 for_lcur = for_list;
7233 debug_print_strings("for_list", for_list);
7236 /* "for" loop is over, clean up */
7242 /* Insert next value from for_lcur */
7243 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7244 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7247 if (rword == RES_IN) {
7248 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7250 if (rword == RES_DONE) {
7251 continue; /* "done" has no cmds too */
7254 #if ENABLE_HUSH_CASE
7255 if (rword == RES_CASE) {
7256 case_word = expand_strvec_to_string(pi->cmds->argv);
7259 if (rword == RES_MATCH) {
7262 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7264 /* all prev words didn't match, does this one match? */
7265 argv = pi->cmds->argv;
7267 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7268 /* TODO: which FNM_xxx flags to use? */
7269 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7271 if (cond_code == 0) { /* match! we will execute this branch */
7272 free(case_word); /* make future "word)" stop */
7280 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7282 continue; /* not matched yet, skip this pipe */
7285 /* Just pressing <enter> in shell should check for jobs.
7286 * OTOH, in non-interactive shell this is useless
7287 * and only leads to extra job checks */
7288 if (pi->num_cmds == 0) {
7289 if (G_interactive_fd)
7290 goto check_jobs_and_continue;
7294 /* After analyzing all keywords and conditions, we decided
7295 * to execute this pipe. NB: have to do checkjobs(NULL)
7296 * after run_pipe to collect any background children,
7297 * even if list execution is to be stopped. */
7298 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7301 #if ENABLE_HUSH_LOOPS
7302 G.flag_break_continue = 0;
7304 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7306 /* We ran a builtin, function, or group.
7307 * rcode is already known
7308 * and we don't need to wait for anything. */
7309 G.last_exitcode = rcode;
7310 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7311 check_and_run_traps(0);
7312 #if ENABLE_HUSH_LOOPS
7313 /* Was it "break" or "continue"? */
7314 if (G.flag_break_continue) {
7315 smallint fbc = G.flag_break_continue;
7316 /* We might fall into outer *loop*,
7317 * don't want to break it too */
7319 G.depth_break_continue--;
7320 if (G.depth_break_continue == 0)
7321 G.flag_break_continue = 0;
7322 /* else: e.g. "continue 2" should *break* once, *then* continue */
7323 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7324 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7325 goto check_jobs_and_break;
7326 /* "continue": simulate end of loop */
7331 #if ENABLE_HUSH_FUNCTIONS
7332 if (G.flag_return_in_progress == 1) {
7333 /* same as "goto check_jobs_and_break" */
7338 } else if (pi->followup == PIPE_BG) {
7339 /* What does bash do with attempts to background builtins? */
7340 /* even bash 3.2 doesn't do that well with nested bg:
7341 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7342 * I'm NOT treating inner &'s as jobs */
7343 check_and_run_traps(0);
7345 if (G.run_list_level == 1)
7348 /* Last command's pid goes to $! */
7349 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7350 G.last_exitcode = rcode = EXIT_SUCCESS;
7351 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7354 if (G.run_list_level == 1 && G_interactive_fd) {
7355 /* Waits for completion, then fg's main shell */
7356 rcode = checkjobs_and_fg_shell(pi);
7357 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7358 check_and_run_traps(0);
7361 { /* This one just waits for completion */
7362 rcode = checkjobs(pi);
7363 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7364 check_and_run_traps(0);
7366 G.last_exitcode = rcode;
7370 /* Analyze how result affects subsequent commands */
7372 if (rword == RES_IF || rword == RES_ELIF)
7375 #if ENABLE_HUSH_LOOPS
7376 /* Beware of "while false; true; do ..."! */
7377 if (pi->next && pi->next->res_word == RES_DO) {
7378 if (rword == RES_WHILE) {
7380 /* "while false; do...done" - exitcode 0 */
7381 G.last_exitcode = rcode = EXIT_SUCCESS;
7382 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7383 goto check_jobs_and_break;
7386 if (rword == RES_UNTIL) {
7388 debug_printf_exec(": until expr is true: breaking\n");
7389 check_jobs_and_break:
7397 check_jobs_and_continue:
7404 #if ENABLE_HUSH_LOOPS
7409 #if ENABLE_HUSH_CASE
7413 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7417 /* Select which version we will use */
7418 static int run_and_free_list(struct pipe *pi)
7421 debug_printf_exec("run_and_free_list entered\n");
7422 if (!G.o_opt[OPT_O_NOEXEC]) {
7423 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7424 rcode = run_list(pi);
7426 /* free_pipe_list has the side effect of clearing memory.
7427 * In the long run that function can be merged with run_list,
7428 * but doing that now would hobble the debugging effort. */
7430 debug_printf_exec("run_and_free_list return %d\n", rcode);
7435 /* Called a few times only (or even once if "sh -c") */
7436 static void init_sigmasks(void)
7441 /* POSIX allows shell to re-enable SIGCHLD
7442 * even if it was SIG_IGN on entry */
7443 #if ENABLE_HUSH_FAST
7444 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7446 if (!G.inherited_set_is_saved) {
7447 #if ENABLE_HUSH_FAST
7448 signal(SIGCHLD, SIGCHLD_handler);
7450 signal(SIGCHLD, SIG_DFL);
7452 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7453 G.inherited_set = G.blocked_set;
7456 /* Which signals are shell-special? */
7457 mask = (1 << SIGQUIT);
7458 if (G_interactive_fd) {
7459 mask |= SPECIAL_INTERACTIVE_SIGS;
7460 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7461 mask |= SPECIAL_JOB_SIGS;
7463 G.non_DFL_mask = mask;
7465 /* Block them. And unblock SIGCHLD */
7467 while ((mask >>= 1) != 0) {
7470 sigaddset(&G.blocked_set, sig);
7472 sigdelset(&G.blocked_set, SIGCHLD);
7474 if (memcmp(&G.inherited_set, &G.blocked_set, sizeof(G.inherited_set)) != 0)
7475 sigprocmask_set(&G.blocked_set);
7477 G.inherited_set_is_saved = 1;
7482 /* Set handlers to restore tty pgrp and exit */
7483 static void set_fatal_handlers_to_sigexit(void)
7485 void (*handler)(int);
7486 unsigned fatal_sigs, sig;
7488 /* We will restore tty pgrp on these signals */
7490 + (1 << SIGILL ) * HUSH_DEBUG
7491 + (1 << SIGFPE ) * HUSH_DEBUG
7492 + (1 << SIGBUS ) * HUSH_DEBUG
7493 + (1 << SIGSEGV) * HUSH_DEBUG
7494 + (1 << SIGTRAP) * HUSH_DEBUG
7496 /* bash 3.2 seems to handle these just like 'fatal' ones */
7499 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7500 * if we aren't interactive... but in this case
7501 * we never want to restore pgrp on exit, and this fn is not called */
7502 /*+ (1 << SIGHUP )*/
7503 /*+ (1 << SIGTERM)*/
7504 /*+ (1 << SIGINT )*/
7507 /* non_DFL_mask'ed signals are, well, masked,
7508 * no need to set handler for them.
7510 fatal_sigs &= ~G.non_DFL_mask;
7512 /* For each sig in fatal_sigs... */
7514 while ((fatal_sigs >>= 1) != 0) {
7516 if (!(fatal_sigs & 1))
7518 handler = signal(sig, sigexit);
7519 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7520 signal(sig, handler);
7525 static int set_mode(int state, char mode, const char *o_opt)
7530 G.o_opt[OPT_O_NOEXEC] = state;
7533 IF_HUSH_MODE_X(G_x_mode = state;)
7537 /* "set -+o" without parameter.
7538 * in bash, set -o produces this output:
7542 * We always use the second form.
7544 const char *p = o_opt_strings;
7547 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7553 idx = index_in_strings(o_opt_strings, o_opt);
7555 G.o_opt[idx] = state;
7559 return EXIT_FAILURE;
7561 return EXIT_SUCCESS;
7564 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7565 int hush_main(int argc, char **argv)
7568 unsigned builtin_argc;
7570 struct variable *cur_var;
7571 struct variable *shell_ver;
7574 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7575 G.last_exitcode = EXIT_SUCCESS;
7577 G.argv0_for_re_execing = argv[0];
7579 /* Deal with HUSH_VERSION */
7580 shell_ver = xzalloc(sizeof(*shell_ver));
7581 shell_ver->flg_export = 1;
7582 shell_ver->flg_read_only = 1;
7583 /* Code which handles ${var<op>...} needs writable values for all variables,
7584 * therefore we xstrdup: */
7585 shell_ver->varstr = xstrdup(hush_version_str);
7586 /* Create shell local variables from the values
7587 * currently living in the environment */
7588 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7589 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7590 G.top_var = shell_ver;
7591 cur_var = G.top_var;
7594 char *value = strchr(*e, '=');
7595 if (value) { /* paranoia */
7596 cur_var->next = xzalloc(sizeof(*cur_var));
7597 cur_var = cur_var->next;
7598 cur_var->varstr = *e;
7599 cur_var->max_len = strlen(*e);
7600 cur_var->flg_export = 1;
7604 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7605 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7606 putenv(shell_ver->varstr);
7609 set_pwd_var(/*exp:*/ 1);
7610 /* bash also exports SHLVL and _,
7611 * and sets (but doesn't export) the following variables:
7613 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7614 * BASH_VERSION='3.2.0(1)-release'
7616 * MACHTYPE=i386-pc-linux-gnu
7618 * HOSTNAME=<xxxxxxxxxx>
7619 * PPID=<NNNNN> - we also do it elsewhere
7630 * PIPESTATUS=([0]="0")
7631 * HISTFILE=/<xxx>/.bash_history
7635 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7637 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7647 #if ENABLE_FEATURE_EDITING
7648 G.line_input_state = new_line_input_t(FOR_SHELL);
7649 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7651 const char *hp = get_local_var_value("HISTFILE");
7653 hp = get_local_var_value("HOME");
7655 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7656 //set_local_var(xasprintf("HISTFILE=%s", ...));
7659 # if ENABLE_FEATURE_SH_HISTFILESIZE
7660 hp = get_local_var_value("HISTFILESIZE");
7661 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7667 G.global_argc = argc;
7668 G.global_argv = argv;
7669 /* Initialize some more globals to non-zero values */
7670 cmdedit_update_prompt();
7672 if (setjmp(die_jmp)) {
7673 /* xfunc has failed! die die die */
7674 /* no EXIT traps, this is an escape hatch! */
7676 hush_exit(xfunc_error_retval);
7679 /* Shell is non-interactive at first. We need to call
7680 * init_sigmasks() if we are going to execute "sh <script>",
7681 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7682 * If we later decide that we are interactive, we run init_sigmasks()
7683 * in order to intercept (more) signals.
7687 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7690 opt = getopt(argc, argv, "+c:xins"
7693 # if ENABLE_HUSH_FUNCTIONS
7703 * sh ... -c 'script'
7704 * sh ... -c 'script' ARG0 [ARG1...]
7705 * On NOMMU, if builtin_argc != 0,
7706 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7707 * "" needs to be replaced with NULL
7708 * and BARGV vector fed to builtin function.
7709 * Note: the form without ARG0 never happens:
7710 * sh ... -c 'builtin' BARGV... ""
7713 G.root_pid = getpid();
7714 G.root_ppid = getppid();
7716 G.global_argv = argv + optind;
7717 G.global_argc = argc - optind;
7719 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7720 const struct built_in_command *x;
7723 x = find_builtin(optarg);
7724 if (x) { /* paranoia */
7725 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7726 G.global_argv += builtin_argc;
7727 G.global_argv[-1] = NULL; /* replace "" */
7729 G.last_exitcode = x->b_function(argv + optind - 1);
7733 if (!G.global_argv[0]) {
7734 /* -c 'script' (no params): prevent empty $0 */
7735 G.global_argv--; /* points to argv[i] of 'script' */
7736 G.global_argv[0] = argv[0];
7738 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7740 parse_and_run_string(optarg);
7743 /* Well, we cannot just declare interactiveness,
7744 * we have to have some stuff (ctty, etc) */
7745 /* G_interactive_fd++; */
7748 /* "-s" means "read from stdin", but this is how we always
7749 * operate, so simply do nothing here. */
7752 case '<': /* "big heredoc" support */
7753 full_write1_str(optarg);
7756 unsigned long long empty_trap_mask;
7758 G.root_pid = bb_strtou(optarg, &optarg, 16);
7760 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7762 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7764 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7766 builtin_argc = bb_strtou(optarg, &optarg, 16);
7768 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7769 if (empty_trap_mask != 0) {
7772 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7773 for (sig = 1; sig < NSIG; sig++) {
7774 if (empty_trap_mask & (1LL << sig)) {
7775 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7776 sigaddset(&G.blocked_set, sig);
7779 sigprocmask_set(&G.blocked_set);
7781 # if ENABLE_HUSH_LOOPS
7783 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7789 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7791 # if ENABLE_HUSH_FUNCTIONS
7793 struct function *funcp = new_function(optarg);
7794 /* funcp->name is already set to optarg */
7795 /* funcp->body is set to NULL. It's a special case. */
7796 funcp->body_as_string = argv[optind];
7804 if (set_mode(1, opt, NULL) == 0) /* no error */
7808 fprintf(stderr, "Usage: sh [FILE]...\n"
7809 " or: sh -c command [args]...\n\n");
7815 } /* option parsing loop */
7818 G.root_pid = getpid();
7819 G.root_ppid = getppid();
7822 /* If we are login shell... */
7823 if (argv[0] && argv[0][0] == '-') {
7825 debug_printf("sourcing /etc/profile\n");
7826 input = fopen_for_read("/etc/profile");
7827 if (input != NULL) {
7828 close_on_exec_on(fileno(input));
7830 parse_and_run_file(input);
7833 /* bash: after sourcing /etc/profile,
7834 * tries to source (in the given order):
7835 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7836 * stopping on first found. --noprofile turns this off.
7837 * bash also sources ~/.bash_logout on exit.
7838 * If called as sh, skips .bash_XXX files.
7845 * "bash <script>" (which is never interactive (unless -i?))
7846 * sources $BASH_ENV here (without scanning $PATH).
7847 * If called as sh, does the same but with $ENV.
7849 debug_printf("running script '%s'\n", argv[optind]);
7850 G.global_argv = argv + optind;
7851 G.global_argc = argc - optind;
7852 input = xfopen_for_read(argv[optind]);
7853 close_on_exec_on(fileno(input));
7855 parse_and_run_file(input);
7856 #if ENABLE_FEATURE_CLEAN_UP
7862 /* Up to here, shell was non-interactive. Now it may become one.
7863 * NB: don't forget to (re)run init_sigmasks() as needed.
7866 /* A shell is interactive if the '-i' flag was given,
7867 * or if all of the following conditions are met:
7869 * no arguments remaining or the -s flag given
7870 * standard input is a terminal
7871 * standard output is a terminal
7872 * Refer to Posix.2, the description of the 'sh' utility.
7875 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7876 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7877 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7878 if (G_saved_tty_pgrp < 0)
7879 G_saved_tty_pgrp = 0;
7881 /* try to dup stdin to high fd#, >= 255 */
7882 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7883 if (G_interactive_fd < 0) {
7884 /* try to dup to any fd */
7885 G_interactive_fd = dup(STDIN_FILENO);
7886 if (G_interactive_fd < 0) {
7888 G_interactive_fd = 0;
7889 G_saved_tty_pgrp = 0;
7892 // TODO: track & disallow any attempts of user
7893 // to (inadvertently) close/redirect G_interactive_fd
7895 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7896 if (G_interactive_fd) {
7897 close_on_exec_on(G_interactive_fd);
7899 if (G_saved_tty_pgrp) {
7900 /* If we were run as 'hush &', sleep until we are
7901 * in the foreground (tty pgrp == our pgrp).
7902 * If we get started under a job aware app (like bash),
7903 * make sure we are now in charge so we don't fight over
7904 * who gets the foreground */
7906 pid_t shell_pgrp = getpgrp();
7907 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7908 if (G_saved_tty_pgrp == shell_pgrp)
7910 /* send TTIN to ourself (should stop us) */
7911 kill(- shell_pgrp, SIGTTIN);
7915 /* Block some signals */
7918 if (G_saved_tty_pgrp) {
7919 /* Set other signals to restore saved_tty_pgrp */
7920 set_fatal_handlers_to_sigexit();
7921 /* Put ourselves in our own process group
7922 * (bash, too, does this only if ctty is available) */
7923 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7924 /* Grab control of the terminal */
7925 tcsetpgrp(G_interactive_fd, getpid());
7927 /* -1 is special - makes xfuncs longjmp, not exit
7928 * (we reset die_sleep = 0 whereever we [v]fork) */
7929 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7933 #elif ENABLE_HUSH_INTERACTIVE
7934 /* No job control compiled in, only prompt/line editing */
7935 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7936 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7937 if (G_interactive_fd < 0) {
7938 /* try to dup to any fd */
7939 G_interactive_fd = dup(STDIN_FILENO);
7940 if (G_interactive_fd < 0)
7942 G_interactive_fd = 0;
7945 if (G_interactive_fd) {
7946 close_on_exec_on(G_interactive_fd);
7950 /* We have interactiveness code disabled */
7954 * if interactive but not a login shell, sources ~/.bashrc
7955 * (--norc turns this off, --rcfile <file> overrides)
7958 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7959 /* note: ash and hush share this string */
7960 printf("\n\n%s %s\n"
7961 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7964 "hush - the humble shell"
7968 parse_and_run_file(stdin);
7971 hush_exit(G.last_exitcode);
7976 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7977 int msh_main(int argc, char **argv)
7979 //bb_error_msg("msh is deprecated, please use hush instead");
7980 return hush_main(argc, argv);
7988 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7993 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8000 return applet_main_func(argc, argv - argc);
8003 static int FAST_FUNC builtin_test(char **argv)
8005 return run_applet_main(argv, test_main);
8008 static int FAST_FUNC builtin_echo(char **argv)
8010 return run_applet_main(argv, echo_main);
8014 static int FAST_FUNC builtin_printf(char **argv)
8016 return run_applet_main(argv, printf_main);
8020 static char **skip_dash_dash(char **argv)
8023 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8028 static int FAST_FUNC builtin_eval(char **argv)
8030 int rcode = EXIT_SUCCESS;
8032 argv = skip_dash_dash(argv);
8034 char *str = expand_strvec_to_string(argv);
8036 * eval "echo Hi; done" ("done" is syntax error):
8037 * "echo Hi" will not execute too.
8039 parse_and_run_string(str);
8041 rcode = G.last_exitcode;
8046 static int FAST_FUNC builtin_cd(char **argv)
8050 argv = skip_dash_dash(argv);
8052 if (newdir == NULL) {
8053 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8054 * bash says "bash: cd: HOME not set" and does nothing
8057 const char *home = get_local_var_value("HOME");
8058 newdir = home ? home : "/";
8060 if (chdir(newdir)) {
8061 /* Mimic bash message exactly */
8062 bb_perror_msg("cd: %s", newdir);
8063 return EXIT_FAILURE;
8065 /* Read current dir (get_cwd(1) is inside) and set PWD.
8066 * Note: do not enforce exporting. If PWD was unset or unexported,
8067 * set it again, but do not export. bash does the same.
8069 set_pwd_var(/*exp:*/ 0);
8070 return EXIT_SUCCESS;
8073 static int FAST_FUNC builtin_exec(char **argv)
8075 argv = skip_dash_dash(argv);
8076 if (argv[0] == NULL)
8077 return EXIT_SUCCESS; /* bash does this */
8079 /* Careful: we can end up here after [v]fork. Do not restore
8080 * tty pgrp then, only top-level shell process does that */
8081 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8082 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8084 /* TODO: if exec fails, bash does NOT exit! We do.
8085 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8086 * and tcsetpgrp, and this is inherently racy.
8088 execvp_or_die(argv);
8091 static int FAST_FUNC builtin_exit(char **argv)
8093 debug_printf_exec("%s()\n", __func__);
8095 /* interactive bash:
8096 * # trap "echo EEE" EXIT
8099 * There are stopped jobs.
8100 * (if there are _stopped_ jobs, running ones don't count)
8103 # EEE (then bash exits)
8105 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8108 /* note: EXIT trap is run by hush_exit */
8109 argv = skip_dash_dash(argv);
8110 if (argv[0] == NULL)
8111 hush_exit(G.last_exitcode);
8112 /* mimic bash: exit 123abc == exit 255 + error msg */
8113 xfunc_error_retval = 255;
8114 /* bash: exit -2 == exit 254, no error msg */
8115 hush_exit(xatoi(argv[0]) & 0xff);
8118 static void print_escaped(const char *s)
8123 const char *p = strchrnul(s, '\'');
8124 /* print 'xxxx', possibly just '' */
8125 printf("'%.*s'", (int)(p - s), s);
8130 /* s points to '; print "'''...'''" */
8132 do putchar('\''); while (*++s == '\'');
8137 #if !ENABLE_HUSH_LOCAL
8138 #define helper_export_local(argv, exp, lvl) \
8139 helper_export_local(argv, exp)
8141 static void helper_export_local(char **argv, int exp, int lvl)
8145 char *name_end = strchrnul(name, '=');
8147 /* So far we do not check that name is valid (TODO?) */
8149 if (*name_end == '\0') {
8150 struct variable *var, **vpp;
8152 vpp = get_ptr_to_local_var(name, name_end - name);
8153 var = vpp ? *vpp : NULL;
8155 if (exp == -1) { /* unexporting? */
8156 /* export -n NAME (without =VALUE) */
8158 var->flg_export = 0;
8159 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8161 } /* else: export -n NOT_EXISTING_VAR: no-op */
8164 if (exp == 1) { /* exporting? */
8165 /* export NAME (without =VALUE) */
8167 var->flg_export = 1;
8168 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8169 putenv(var->varstr);
8173 /* Exporting non-existing variable.
8174 * bash does not put it in environment,
8175 * but remembers that it is exported,
8176 * and does put it in env when it is set later.
8177 * We just set it to "" and export. */
8178 /* Or, it's "local NAME" (without =VALUE).
8179 * bash sets the value to "". */
8180 name = xasprintf("%s=", name);
8182 /* (Un)exporting/making local NAME=VALUE */
8183 name = xstrdup(name);
8185 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8189 static int FAST_FUNC builtin_export(char **argv)
8191 unsigned opt_unexport;
8193 #if ENABLE_HUSH_EXPORT_N
8194 /* "!": do not abort on errors */
8195 opt_unexport = getopt32(argv, "!n");
8196 if (opt_unexport == (uint32_t)-1)
8197 return EXIT_FAILURE;
8204 if (argv[0] == NULL) {
8211 /* ash emits: export VAR='VAL'
8212 * bash: declare -x VAR="VAL"
8213 * we follow ash example */
8214 const char *s = *e++;
8215 const char *p = strchr(s, '=');
8217 if (!p) /* wtf? take next variable */
8220 printf("export %.*s", (int)(p - s) + 1, s);
8221 print_escaped(p + 1);
8225 /*fflush_all(); - done after each builtin anyway */
8227 return EXIT_SUCCESS;
8230 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8232 return EXIT_SUCCESS;
8235 #if ENABLE_HUSH_LOCAL
8236 static int FAST_FUNC builtin_local(char **argv)
8238 if (G.func_nest_level == 0) {
8239 bb_error_msg("%s: not in a function", argv[0]);
8240 return EXIT_FAILURE; /* bash compat */
8242 helper_export_local(argv, 0, G.func_nest_level);
8243 return EXIT_SUCCESS;
8247 static int FAST_FUNC builtin_trap(char **argv)
8253 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8258 /* No args: print all trapped */
8259 for (i = 0; i < NSIG; ++i) {
8262 print_escaped(G.traps[i]);
8263 /* note: bash adds "SIG", but only if invoked
8264 * as "bash". If called as "sh", or if set -o posix,
8265 * then it prints short signal names.
8266 * We are printing short names: */
8267 printf(" %s\n", get_signame(i));
8270 /*fflush_all(); - done after each builtin anyway */
8271 return EXIT_SUCCESS;
8275 /* If first arg is a number: reset all specified signals */
8276 sig = bb_strtou(*argv, NULL, 10);
8282 sig = get_signum(*argv++);
8283 if (sig < 0 || sig >= NSIG) {
8285 /* Mimic bash message exactly */
8286 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8291 G.traps[sig] = xstrdup(new_cmd);
8293 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8294 get_signame(sig), sig, G.traps[sig]);
8296 /* There is no signal for 0 (EXIT) */
8301 sigaddset(&G.blocked_set, sig);
8303 /* There was a trap handler, we are removing it
8304 * (if sig has non-DFL handling,
8305 * we don't need to do anything) */
8306 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8308 sigdelset(&G.blocked_set, sig);
8311 sigprocmask_set(&G.blocked_set);
8315 if (!argv[1]) { /* no second arg */
8316 bb_error_msg("trap: invalid arguments");
8317 return EXIT_FAILURE;
8320 /* First arg is "-": reset all specified to default */
8321 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8322 /* Everything else: set arg as signal handler
8323 * (includes "" case, which ignores signal) */
8324 if (argv[0][0] == '-') {
8325 if (argv[0][1] == '\0') { /* "-" */
8326 /* new_cmd remains NULL: "reset these sigs" */
8329 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8332 /* else: "-something", no special meaning */
8337 goto process_sig_list;
8340 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8341 static int FAST_FUNC builtin_type(char **argv)
8343 int ret = EXIT_SUCCESS;
8349 if (0) {} /* make conditional compile easier below */
8350 /*else if (find_alias(*argv))
8351 type = "an alias";*/
8352 #if ENABLE_HUSH_FUNCTIONS
8353 else if (find_function(*argv))
8354 type = "a function";
8356 else if (find_builtin(*argv))
8357 type = "a shell builtin";
8358 else if ((path = find_in_path(*argv)) != NULL)
8361 bb_error_msg("type: %s: not found", *argv);
8366 printf("%s is %s\n", *argv, type);
8374 /* built-in 'fg' and 'bg' handler */
8375 static int FAST_FUNC builtin_fg_bg(char **argv)
8380 if (!G_interactive_fd)
8381 return EXIT_FAILURE;
8383 /* If they gave us no args, assume they want the last backgrounded task */
8385 for (pi = G.job_list; pi; pi = pi->next) {
8386 if (pi->jobid == G.last_jobid) {
8390 bb_error_msg("%s: no current job", argv[0]);
8391 return EXIT_FAILURE;
8393 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8394 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8395 return EXIT_FAILURE;
8397 for (pi = G.job_list; pi; pi = pi->next) {
8398 if (pi->jobid == jobnum) {
8402 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8403 return EXIT_FAILURE;
8405 /* TODO: bash prints a string representation
8406 * of job being foregrounded (like "sleep 1 | cat") */
8407 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8408 /* Put the job into the foreground. */
8409 tcsetpgrp(G_interactive_fd, pi->pgrp);
8412 /* Restart the processes in the job */
8413 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8414 for (i = 0; i < pi->num_cmds; i++) {
8415 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8416 pi->cmds[i].is_stopped = 0;
8418 pi->stopped_cmds = 0;
8420 i = kill(- pi->pgrp, SIGCONT);
8422 if (errno == ESRCH) {
8423 delete_finished_bg_job(pi);
8424 return EXIT_SUCCESS;
8426 bb_perror_msg("kill (SIGCONT)");
8429 if (argv[0][0] == 'f') {
8431 return checkjobs_and_fg_shell(pi);
8433 return EXIT_SUCCESS;
8437 #if ENABLE_HUSH_HELP
8438 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8440 const struct built_in_command *x;
8443 "Built-in commands:\n"
8444 "------------------\n");
8445 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8447 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8450 return EXIT_SUCCESS;
8455 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8458 const char *status_string;
8460 for (job = G.job_list; job; job = job->next) {
8461 if (job->alive_cmds == job->stopped_cmds)
8462 status_string = "Stopped";
8464 status_string = "Running";
8466 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8468 return EXIT_SUCCESS;
8473 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8478 # ifdef M_TRIM_THRESHOLD
8479 /* Optional. Reduces probability of false positives */
8482 /* Crude attempt to find where "free memory" starts,
8483 * sans fragmentation. */
8485 l = (unsigned long)p;
8488 if (l < (unsigned long)p) l = (unsigned long)p;
8491 if (!G.memleak_value)
8492 G.memleak_value = l;
8494 l -= G.memleak_value;
8501 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8506 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8509 return EXIT_SUCCESS;
8512 /* Interruptibility of read builtin in bash
8513 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8515 * Empty trap makes read ignore corresponding signal, for any signal.
8518 * - terminates non-interactive shell;
8519 * - interrupts read in interactive shell;
8520 * if it has non-empty trap:
8521 * - executes trap and returns to command prompt in interactive shell;
8522 * - executes trap and returns to read in non-interactive shell;
8524 * - is ignored (does not interrupt) read in interactive shell;
8525 * - terminates non-interactive shell;
8526 * if it has non-empty trap:
8527 * - executes trap and returns to read;
8529 * - terminates shell (regardless of interactivity);
8530 * if it has non-empty trap:
8531 * - executes trap and returns to read;
8534 static void record_signal(int sig)
8536 sigaddset(&G.detected_set, sig);
8538 static int FAST_FUNC builtin_read(char **argv)
8547 sigset_t saved_blkd_set;
8549 /* "!": do not abort on errors.
8550 * Option string must start with "sr" to match BUILTIN_READ_xxx
8552 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8553 if (read_flags == (uint32_t)-1)
8554 return EXIT_FAILURE;
8556 ifs = get_local_var_value("IFS"); /* can be NULL */
8559 /* We need to temporarily unblock and record signals around read */
8561 saved_blkd_set = G.blocked_set;
8564 struct sigaction sa, old_sa;
8566 memset(&sa, 0, sizeof(sa));
8567 sigfillset(&sa.sa_mask);
8568 /*sa.sa_flags = 0;*/
8569 sa.sa_handler = record_signal;
8574 if (sigismember(&G.blocked_set, sig)) {
8575 char *sig_trap = (G.traps && G.traps[sig]) ? G.traps[sig] : NULL;
8576 /* If has a nonempty trap... */
8577 if ((sig_trap && sig_trap[0])
8578 /* ...or has no trap and is SIGINT or SIGHUP */
8579 || (!sig_trap && (sig == SIGINT || sig == SIGHUP))
8581 sigaction(sig, &sa, &old_sa);
8582 if (old_sa.sa_handler == SIG_IGN) /* oops... restore back to IGN! */
8583 sigaction_set(sig, &old_sa);
8585 sigdelset(&G.blocked_set, sig);
8588 } while (sig < NSIG-1);
8591 if (memcmp(&saved_blkd_set, &G.blocked_set, sizeof(saved_blkd_set)) != 0)
8592 sigprocmask_set(&G.blocked_set);
8594 r = shell_builtin_read(set_local_var_from_halves,
8604 if (memcmp(&saved_blkd_set, &G.blocked_set, sizeof(saved_blkd_set)) != 0) {
8605 G.blocked_set = saved_blkd_set;
8606 sigprocmask_set(&G.blocked_set);
8609 if ((uintptr_t)r == 1 && errno == EINTR) {
8610 unsigned sig = check_and_run_traps(0);
8611 if (sig && sig != SIGINT)
8615 if ((uintptr_t)r > 1) {
8616 bb_error_msg("%s", r);
8617 r = (char*)(uintptr_t)1;
8620 return (uintptr_t)r;
8623 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8624 * built-in 'set' handler
8626 * set [-abCefhmnuvx] [-o option] [argument...]
8627 * set [+abCefhmnuvx] [+o option] [argument...]
8628 * set -- [argument...]
8631 * Implementations shall support the options in both their hyphen and
8632 * plus-sign forms. These options can also be specified as options to sh.
8634 * Write out all variables and their values: set
8635 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8636 * Turn on the -x and -v options: set -xv
8637 * Unset all positional parameters: set --
8638 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8639 * Set the positional parameters to the expansion of x, even if x expands
8640 * with a leading '-' or '+': set -- $x
8642 * So far, we only support "set -- [argument...]" and some of the short names.
8644 static int FAST_FUNC builtin_set(char **argv)
8647 char **pp, **g_argv;
8648 char *arg = *++argv;
8652 for (e = G.top_var; e; e = e->next)
8654 return EXIT_SUCCESS;
8658 if (strcmp(arg, "--") == 0) {
8662 if (arg[0] != '+' && arg[0] != '-')
8664 for (n = 1; arg[n]; ++n) {
8665 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8667 if (arg[n] == 'o' && argv[1])
8670 } while ((arg = *++argv) != NULL);
8671 /* Now argv[0] is 1st argument */
8674 return EXIT_SUCCESS;
8677 /* NB: G.global_argv[0] ($0) is never freed/changed */
8678 g_argv = G.global_argv;
8679 if (G.global_args_malloced) {
8685 G.global_args_malloced = 1;
8686 pp = xzalloc(sizeof(pp[0]) * 2);
8687 pp[0] = g_argv[0]; /* retain $0 */
8690 /* This realloc's G.global_argv */
8691 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8698 return EXIT_SUCCESS;
8700 /* Nothing known, so abort */
8702 bb_error_msg("set: %s: invalid option", arg);
8703 return EXIT_FAILURE;
8706 static int FAST_FUNC builtin_shift(char **argv)
8709 argv = skip_dash_dash(argv);
8713 if (n >= 0 && n < G.global_argc) {
8714 if (G.global_args_malloced) {
8717 free(G.global_argv[m++]);
8720 memmove(&G.global_argv[1], &G.global_argv[n+1],
8721 G.global_argc * sizeof(G.global_argv[0]));
8722 return EXIT_SUCCESS;
8724 return EXIT_FAILURE;
8727 static int FAST_FUNC builtin_source(char **argv)
8729 char *arg_path, *filename;
8732 #if ENABLE_HUSH_FUNCTIONS
8736 argv = skip_dash_dash(argv);
8739 /* bash says: "bash: .: filename argument required" */
8740 return 2; /* bash compat */
8743 if (!strchr(filename, '/')) {
8744 arg_path = find_in_path(filename);
8746 filename = arg_path;
8748 input = fopen_or_warn(filename, "r");
8751 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8752 return EXIT_FAILURE;
8754 close_on_exec_on(fileno(input));
8756 #if ENABLE_HUSH_FUNCTIONS
8757 sv_flg = G.flag_return_in_progress;
8758 /* "we are inside sourced file, ok to use return" */
8759 G.flag_return_in_progress = -1;
8761 save_and_replace_G_args(&sv, argv);
8763 parse_and_run_file(input);
8766 restore_G_args(&sv, argv);
8767 #if ENABLE_HUSH_FUNCTIONS
8768 G.flag_return_in_progress = sv_flg;
8771 return G.last_exitcode;
8774 static int FAST_FUNC builtin_umask(char **argv)
8780 argv = skip_dash_dash(argv);
8782 mode_t old_mask = mask;
8785 rc = bb_parse_mode(argv[0], &mask);
8790 * bash: umask: 'q': invalid symbolic mode operator
8791 * bash: umask: 999: octal number out of range
8793 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8798 printf("%04o\n", (unsigned) mask);
8799 /* fall through and restore mask which we set to 0 */
8803 return !rc; /* rc != 0 - success */
8806 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8807 static int FAST_FUNC builtin_unset(char **argv)
8812 /* "!": do not abort on errors */
8813 /* "+": stop at 1st non-option */
8814 opts = getopt32(argv, "!+vf");
8815 if (opts == (unsigned)-1)
8816 return EXIT_FAILURE;
8818 bb_error_msg("unset: -v and -f are exclusive");
8819 return EXIT_FAILURE;
8825 if (!(opts & 2)) { /* not -f */
8826 if (unset_local_var(*argv)) {
8827 /* unset <nonexistent_var> doesn't fail.
8828 * Error is when one tries to unset RO var.
8829 * Message was printed by unset_local_var. */
8833 #if ENABLE_HUSH_FUNCTIONS
8843 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8844 static int FAST_FUNC builtin_wait(char **argv)
8846 int ret = EXIT_SUCCESS;
8849 argv = skip_dash_dash(argv);
8850 if (argv[0] == NULL) {
8851 /* Don't care about wait results */
8852 /* Note 1: must wait until there are no more children */
8853 /* Note 2: must be interruptible */
8855 * $ sleep 3 & sleep 6 & wait
8860 * $ sleep 3 & sleep 6 & wait
8864 * ^C <-- after ~4 sec from keyboard
8867 sigaddset(&G.blocked_set, SIGCHLD);
8868 sigprocmask_set(&G.blocked_set);
8871 if (errno == ECHILD)
8873 /* Wait for SIGCHLD or any other signal of interest */
8874 /* sigtimedwait with infinite timeout: */
8875 sig = sigwaitinfo(&G.blocked_set, NULL);
8877 sig = check_and_run_traps(sig);
8878 if (sig && sig != SIGCHLD) { /* see note 2 */
8884 sigdelset(&G.blocked_set, SIGCHLD);
8885 sigprocmask_set(&G.blocked_set);
8889 /* This is probably buggy wrt interruptible-ness */
8891 pid_t pid = bb_strtou(*argv, NULL, 10);
8893 /* mimic bash message */
8894 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8895 return EXIT_FAILURE;
8897 if (waitpid(pid, &status, 0) == pid) {
8898 if (WIFSIGNALED(status))
8899 ret = 128 + WTERMSIG(status);
8900 else if (WIFEXITED(status))
8901 ret = WEXITSTATUS(status);
8905 bb_perror_msg("wait %s", *argv);
8914 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8915 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8918 def = bb_strtou(argv[1], NULL, 10);
8919 if (errno || def < def_min || argv[2]) {
8920 bb_error_msg("%s: bad arguments", argv[0]);
8928 #if ENABLE_HUSH_LOOPS
8929 static int FAST_FUNC builtin_break(char **argv)
8932 if (G.depth_of_loop == 0) {
8933 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8934 return EXIT_SUCCESS; /* bash compat */
8936 G.flag_break_continue++; /* BC_BREAK = 1 */
8938 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8939 if (depth == UINT_MAX)
8940 G.flag_break_continue = BC_BREAK;
8941 if (G.depth_of_loop < depth)
8942 G.depth_break_continue = G.depth_of_loop;
8944 return EXIT_SUCCESS;
8947 static int FAST_FUNC builtin_continue(char **argv)
8949 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8950 return builtin_break(argv);
8954 #if ENABLE_HUSH_FUNCTIONS
8955 static int FAST_FUNC builtin_return(char **argv)
8959 if (G.flag_return_in_progress != -1) {
8960 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8961 return EXIT_FAILURE; /* bash compat */
8964 G.flag_return_in_progress = 1;
8967 * out of range: wraps around at 256, does not error out
8968 * non-numeric param:
8969 * f() { false; return qwe; }; f; echo $?
8970 * bash: return: qwe: numeric argument required <== we do this
8971 * 255 <== we also do this
8973 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);