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 #if ENABLE_HUSH_FAST
1383 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1386 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1392 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1393 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1394 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1395 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1397 /* Restores tty foreground process group, and exits.
1398 * May be called as signal handler for fatal signal
1399 * (will resend signal to itself, producing correct exit state)
1400 * or called directly with -EXITCODE.
1401 * We also call it if xfunc is exiting. */
1402 static void sigexit(int sig) NORETURN;
1403 static void sigexit(int sig)
1405 /* Disable all signals: job control, SIGPIPE, etc. */
1406 sigprocmask_allsigs(SIG_BLOCK);
1408 /* Careful: we can end up here after [v]fork. Do not restore
1409 * tty pgrp then, only top-level shell process does that */
1410 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1411 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1413 /* Not a signal, just exit */
1417 kill_myself_with_sig(sig); /* does not return */
1421 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1422 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1426 /* Restores tty foreground process group, and exits. */
1427 static void hush_exit(int exitcode) NORETURN;
1428 static void hush_exit(int exitcode)
1431 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1432 /* Prevent recursion:
1433 * trap "echo Hi; exit" EXIT; exit
1436 /* argv[0] is unused */
1437 argv[1] = G.traps[0];
1439 G.exiting = 1; /* prevent EXIT trap recursion */
1440 /* Note: G.traps[0] is not cleared!
1441 * "trap" will still show it, if executed
1446 #if ENABLE_FEATURE_CLEAN_UP
1448 struct variable *cur_var;
1449 if (G.cwd != bb_msg_unknown)
1451 cur_var = G.top_var;
1453 struct variable *tmp = cur_var;
1454 if (!cur_var->max_len)
1455 free(cur_var->varstr);
1456 cur_var = cur_var->next;
1464 sigexit(- (exitcode & 0xff));
1471 static int check_and_run_traps(int sig)
1473 /* I want it in rodata, not in bss.
1474 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1475 * initializer. But other compilers may still use bss.
1476 * TODO: find more portable solution.
1478 static const struct timespec zero_timespec = { 0, 0 };
1479 smalluint save_rcode;
1486 if (!sigisemptyset(&G.detected_set)) {
1490 if (sigismember(&G.detected_set, sig)) {
1491 sigdelset(&G.detected_set, sig);
1494 } while (sig < NSIG);
1497 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1501 if (G.traps && G.traps[sig]) {
1502 if (G.traps[sig][0]) {
1503 /* We have user-defined handler */
1505 /* argv[0] is unused */
1506 argv[1] = G.traps[sig];
1508 save_rcode = G.last_exitcode;
1510 G.last_exitcode = save_rcode;
1512 } /* else: "" trap, ignoring signal */
1515 /* not a trap: special action */
1517 #if ENABLE_HUSH_FAST
1520 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1524 /* Builtin was ^C'ed, make it look prettier: */
1532 /* bash is observed to signal whole process groups,
1533 * not individual processes */
1534 for (job = G.job_list; job; job = job->next) {
1537 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1538 if (kill(- job->pgrp, SIGHUP) == 0)
1539 kill(- job->pgrp, SIGCONT);
1544 default: /* ignored: */
1545 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1547 * we dont do 'last_sig = sig' here -> NOT returning this sig.
1548 * example: wait is not interrupted by TERM
1549 * in interactive shell, because TERM is ignored.
1558 static const char *get_cwd(int force)
1560 if (force || G.cwd == NULL) {
1561 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1562 * we must not try to free(bb_msg_unknown) */
1563 if (G.cwd == bb_msg_unknown)
1565 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1567 G.cwd = bb_msg_unknown;
1574 * Shell and environment variable support
1576 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1578 struct variable **pp;
1579 struct variable *cur;
1582 while ((cur = *pp) != NULL) {
1583 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1590 static const char* FAST_FUNC get_local_var_value(const char *name)
1592 struct variable **vpp;
1593 unsigned len = strlen(name);
1595 if (G.expanded_assignments) {
1596 char **cpp = G.expanded_assignments;
1599 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1600 return cp + len + 1;
1605 vpp = get_ptr_to_local_var(name, len);
1607 return (*vpp)->varstr + len + 1;
1609 if (strcmp(name, "PPID") == 0)
1610 return utoa(G.root_ppid);
1611 // bash compat: UID? EUID?
1612 #if ENABLE_HUSH_RANDOM_SUPPORT
1613 if (strcmp(name, "RANDOM") == 0)
1614 return utoa(next_random(&G.random_gen));
1619 /* str holds "NAME=VAL" and is expected to be malloced.
1620 * We take ownership of it.
1622 * 0: do not change export flag
1623 * (if creating new variable, flag will be 0)
1624 * 1: set export flag and putenv the variable
1625 * -1: clear export flag and unsetenv the variable
1626 * flg_read_only is set only when we handle -R var=val
1628 #if !BB_MMU && ENABLE_HUSH_LOCAL
1629 /* all params are used */
1630 #elif BB_MMU && ENABLE_HUSH_LOCAL
1631 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1632 set_local_var(str, flg_export, local_lvl)
1633 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1634 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1635 set_local_var(str, flg_export)
1636 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1637 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1638 set_local_var(str, flg_export, flg_read_only)
1640 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1642 struct variable **var_pp;
1643 struct variable *cur;
1647 eq_sign = strchr(str, '=');
1648 if (!eq_sign) { /* not expected to ever happen? */
1653 name_len = eq_sign - str + 1; /* including '=' */
1654 var_pp = &G.top_var;
1655 while ((cur = *var_pp) != NULL) {
1656 if (strncmp(cur->varstr, str, name_len) != 0) {
1657 var_pp = &cur->next;
1660 /* We found an existing var with this name */
1661 if (cur->flg_read_only) {
1665 bb_error_msg("%s: readonly variable", str);
1669 if (flg_export == -1) { // "&& cur->flg_export" ?
1670 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1675 #if ENABLE_HUSH_LOCAL
1676 if (cur->func_nest_level < local_lvl) {
1677 /* New variable is declared as local,
1678 * and existing one is global, or local
1679 * from enclosing function.
1680 * Remove and save old one: */
1681 *var_pp = cur->next;
1682 cur->next = *G.shadowed_vars_pp;
1683 *G.shadowed_vars_pp = cur;
1684 /* bash 3.2.33(1) and exported vars:
1686 * # f() { local z=a; env | grep ^z; }
1692 if (cur->flg_export)
1697 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1702 if (cur->max_len != 0) {
1703 if (cur->max_len >= strlen(str)) {
1704 /* This one is from startup env, reuse space */
1705 strcpy(cur->varstr, str);
1709 /* max_len == 0 signifies "malloced" var, which we can
1710 * (and has to) free */
1714 goto set_str_and_exp;
1717 /* Not found - create new variable struct */
1718 cur = xzalloc(sizeof(*cur));
1719 #if ENABLE_HUSH_LOCAL
1720 cur->func_nest_level = local_lvl;
1722 cur->next = *var_pp;
1728 cur->flg_read_only = flg_read_only;
1731 if (flg_export == 1)
1732 cur->flg_export = 1;
1733 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1734 cmdedit_update_prompt();
1735 if (cur->flg_export) {
1736 if (flg_export == -1) {
1737 cur->flg_export = 0;
1738 /* unsetenv was already done */
1740 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1741 return putenv(cur->varstr);
1747 /* Used at startup and after each cd */
1748 static void set_pwd_var(int exp)
1750 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1751 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1754 static int unset_local_var_len(const char *name, int name_len)
1756 struct variable *cur;
1757 struct variable **var_pp;
1760 return EXIT_SUCCESS;
1761 var_pp = &G.top_var;
1762 while ((cur = *var_pp) != NULL) {
1763 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1764 if (cur->flg_read_only) {
1765 bb_error_msg("%s: readonly variable", name);
1766 return EXIT_FAILURE;
1768 *var_pp = cur->next;
1769 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1770 bb_unsetenv(cur->varstr);
1771 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1772 cmdedit_update_prompt();
1776 return EXIT_SUCCESS;
1778 var_pp = &cur->next;
1780 return EXIT_SUCCESS;
1783 static int unset_local_var(const char *name)
1785 return unset_local_var_len(name, strlen(name));
1788 static void unset_vars(char **strings)
1796 const char *eq = strchrnul(*v, '=');
1797 unset_local_var_len(*v, (int)(eq - *v));
1803 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1805 char *var = xasprintf("%s=%s", name, val);
1806 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1811 * Helpers for "var1=val1 var2=val2 cmd" feature
1813 static void add_vars(struct variable *var)
1815 struct variable *next;
1819 var->next = G.top_var;
1821 if (var->flg_export) {
1822 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1823 putenv(var->varstr);
1825 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1831 static struct variable *set_vars_and_save_old(char **strings)
1834 struct variable *old = NULL;
1840 struct variable *var_p;
1841 struct variable **var_pp;
1844 eq = strchr(*s, '=');
1846 var_pp = get_ptr_to_local_var(*s, eq - *s);
1848 /* Remove variable from global linked list */
1850 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1851 *var_pp = var_p->next;
1852 /* Add it to returned list */
1856 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1867 static int FAST_FUNC static_get(struct in_str *i)
1878 static int FAST_FUNC static_peek(struct in_str *i)
1883 #if ENABLE_HUSH_INTERACTIVE
1885 static void cmdedit_update_prompt(void)
1887 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1888 G.PS1 = get_local_var_value("PS1");
1891 G.PS2 = get_local_var_value("PS2");
1899 static const char *setup_prompt_string(int promptmode)
1901 const char *prompt_str;
1902 debug_printf("setup_prompt_string %d ", promptmode);
1903 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1904 /* Set up the prompt */
1905 if (promptmode == 0) { /* PS1 */
1907 /* bash uses $PWD value, even if it is set by user.
1908 * It uses current dir only if PWD is unset.
1909 * We always use current dir. */
1910 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1915 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1916 debug_printf("result '%s'\n", prompt_str);
1920 static void get_user_input(struct in_str *i)
1923 const char *prompt_str;
1925 prompt_str = setup_prompt_string(i->promptmode);
1926 # if ENABLE_FEATURE_EDITING
1927 /* Enable command line editing only while a command line
1928 * is actually being read */
1930 /* Unicode support should be activated even if LANG is set
1931 * _during_ shell execution, not only if it was set when
1932 * shell was started. Therefore, re-check LANG every time:
1934 reinit_unicode(get_local_var_value("LANG"));
1937 /* buglet: SIGINT will not make new prompt to appear _at once_,
1938 * only after <Enter>. (^C will work) */
1939 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1940 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1941 check_and_run_traps(0);
1942 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1943 i->eof_flag = (r < 0);
1944 if (i->eof_flag) { /* EOF/error detected */
1945 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1946 G.user_input_buf[1] = '\0';
1951 if (i->last_char == '\0' || i->last_char == '\n') {
1952 /* Why check_and_run_traps here? Try this interactively:
1953 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
1954 * $ <[enter], repeatedly...>
1955 * Without check_and_run_traps, handler never runs.
1957 check_and_run_traps(0);
1958 fputs(prompt_str, stdout);
1961 G.user_input_buf[0] = r = fgetc(i->file);
1962 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1963 } while (G.flag_SIGINT);
1964 i->eof_flag = (r == EOF);
1966 i->p = G.user_input_buf;
1969 #endif /* INTERACTIVE */
1971 /* This is the magic location that prints prompts
1972 * and gets data back from the user */
1973 static int FAST_FUNC file_get(struct in_str *i)
1977 /* If there is data waiting, eat it up */
1978 if (i->p && *i->p) {
1979 #if ENABLE_HUSH_INTERACTIVE
1983 if (i->eof_flag && !*i->p)
1985 /* note: ch is never NUL */
1987 /* need to double check i->file because we might be doing something
1988 * more complicated by now, like sourcing or substituting. */
1989 #if ENABLE_HUSH_INTERACTIVE
1990 if (G_interactive_fd && i->file == stdin) {
1993 } while (!*i->p); /* need non-empty line */
1994 i->promptmode = 1; /* PS2 */
1998 do ch = fgetc(i->file); while (ch == '\0');
2000 debug_printf("file_get: got '%c' %d\n", ch, ch);
2005 /* All callers guarantee this routine will never
2006 * be used right after a newline, so prompting is not needed.
2008 static int FAST_FUNC file_peek(struct in_str *i)
2011 if (i->p && *i->p) {
2012 if (i->eof_flag && !i->p[1])
2015 /* note: ch is never NUL */
2017 do ch = fgetc(i->file); while (ch == '\0');
2018 i->eof_flag = (ch == EOF);
2019 i->peek_buf[0] = ch;
2020 i->peek_buf[1] = '\0';
2022 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2026 static void setup_file_in_str(struct in_str *i, FILE *f)
2028 memset(i, 0, sizeof(*i));
2029 i->peek = file_peek;
2031 /* i->promptmode = 0; - PS1 (memset did it) */
2036 static void setup_string_in_str(struct in_str *i, const char *s)
2038 memset(i, 0, sizeof(*i));
2039 i->peek = static_peek;
2040 i->get = static_get;
2041 /* i->promptmode = 0; - PS1 (memset did it) */
2043 /* i->eof_flag = 0; */
2050 #define B_CHUNK (32 * sizeof(char*))
2052 static void o_reset_to_empty_unquoted(o_string *o)
2055 o->has_quoted_part = 0;
2060 static void o_free(o_string *o)
2063 memset(o, 0, sizeof(*o));
2066 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2071 static void o_grow_by(o_string *o, int len)
2073 if (o->length + len > o->maxlen) {
2074 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2075 o->data = xrealloc(o->data, 1 + o->maxlen);
2079 static void o_addchr(o_string *o, int ch)
2081 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2083 o->data[o->length] = ch;
2085 o->data[o->length] = '\0';
2088 static void o_addblock(o_string *o, const char *str, int len)
2091 memcpy(&o->data[o->length], str, len);
2093 o->data[o->length] = '\0';
2096 static void o_addstr(o_string *o, const char *str)
2098 o_addblock(o, str, strlen(str));
2102 static void nommu_addchr(o_string *o, int ch)
2108 # define nommu_addchr(o, str) ((void)0)
2111 static void o_addstr_with_NUL(o_string *o, const char *str)
2113 o_addblock(o, str, strlen(str) + 1);
2117 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2118 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2119 * Apparently, on unquoted $v bash still does globbing
2120 * ("v='*.txt'; echo $v" prints all .txt files),
2121 * but NOT brace expansion! Thus, there should be TWO independent
2122 * quoting mechanisms on $v expansion side: one protects
2123 * $v from brace expansion, and other additionally protects "$v" against globbing.
2124 * We have only second one.
2127 #if ENABLE_HUSH_BRACE_EXPANSION
2128 # define MAYBE_BRACES "{}"
2130 # define MAYBE_BRACES ""
2133 /* My analysis of quoting semantics tells me that state information
2134 * is associated with a destination, not a source.
2136 static void o_addqchr(o_string *o, int ch)
2139 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2144 o->data[o->length] = '\\';
2147 o->data[o->length] = ch;
2149 o->data[o->length] = '\0';
2152 static void o_addQchr(o_string *o, int ch)
2155 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2156 && strchr("*?[\\" MAYBE_BRACES, ch)
2159 o->data[o->length] = '\\';
2163 o->data[o->length] = ch;
2165 o->data[o->length] = '\0';
2168 static void o_addqblock(o_string *o, const char *str, int len)
2173 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2174 if (ordinary_cnt > len) /* paranoia */
2176 o_addblock(o, str, ordinary_cnt);
2177 if (ordinary_cnt == len)
2179 str += ordinary_cnt;
2180 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2184 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2186 o->data[o->length] = '\\';
2190 o->data[o->length] = ch;
2192 o->data[o->length] = '\0';
2196 static void o_addQblock(o_string *o, const char *str, int len)
2198 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2199 o_addblock(o, str, len);
2202 o_addqblock(o, str, len);
2205 static void o_addQstr(o_string *o, const char *str)
2207 o_addQblock(o, str, strlen(str));
2210 /* A special kind of o_string for $VAR and `cmd` expansion.
2211 * It contains char* list[] at the beginning, which is grown in 16 element
2212 * increments. Actual string data starts at the next multiple of 16 * (char*).
2213 * list[i] contains an INDEX (int!) into this string data.
2214 * It means that if list[] needs to grow, data needs to be moved higher up
2215 * but list[i]'s need not be modified.
2216 * NB: remembering how many list[i]'s you have there is crucial.
2217 * o_finalize_list() operation post-processes this structure - calculates
2218 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2220 #if DEBUG_EXPAND || DEBUG_GLOB
2221 static void debug_print_list(const char *prefix, o_string *o, int n)
2223 char **list = (char**)o->data;
2224 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2228 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2229 prefix, list, n, string_start, o->length, o->maxlen,
2230 !!(o->o_expflags & EXP_FLAG_GLOB),
2232 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2235 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2236 o->data + (int)(uintptr_t)list[i] + string_start,
2237 o->data + (int)(uintptr_t)list[i] + string_start);
2241 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2243 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2247 # define debug_print_list(prefix, o, n) ((void)0)
2250 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2251 * in list[n] so that it points past last stored byte so far.
2252 * It returns n+1. */
2253 static int o_save_ptr_helper(o_string *o, int n)
2255 char **list = (char**)o->data;
2259 if (!o->has_empty_slot) {
2260 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2261 string_len = o->length - string_start;
2262 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2263 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2264 /* list[n] points to string_start, make space for 16 more pointers */
2265 o->maxlen += 0x10 * sizeof(list[0]);
2266 o->data = xrealloc(o->data, o->maxlen + 1);
2267 list = (char**)o->data;
2268 memmove(list + n + 0x10, list + n, string_len);
2269 o->length += 0x10 * sizeof(list[0]);
2271 debug_printf_list("list[%d]=%d string_start=%d\n",
2272 n, string_len, string_start);
2275 /* We have empty slot at list[n], reuse without growth */
2276 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2277 string_len = o->length - string_start;
2278 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2279 n, string_len, string_start);
2280 o->has_empty_slot = 0;
2282 list[n] = (char*)(uintptr_t)string_len;
2286 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2287 static int o_get_last_ptr(o_string *o, int n)
2289 char **list = (char**)o->data;
2290 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2292 return ((int)(uintptr_t)list[n-1]) + string_start;
2295 #if ENABLE_HUSH_BRACE_EXPANSION
2296 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2297 * first, it processes even {a} (no commas), second,
2298 * I didn't manage to make it return strings when they don't match
2299 * existing files. Need to re-implement it.
2303 static int glob_needed(const char *s)
2312 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2318 /* Return pointer to next closing brace or to comma */
2319 static const char *next_brace_sub(const char *cp)
2323 while (*cp != '\0') {
2330 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2336 return *cp != '\0' ? cp : NULL;
2338 /* Recursive brace globber. Note: may garble pattern[]. */
2339 static int glob_brace(char *pattern, o_string *o, int n)
2341 char *new_pattern_buf;
2348 debug_printf_glob("glob_brace('%s')\n", pattern);
2354 if (*begin == '{') {
2355 /* Find the first sub-pattern and at the same time
2356 * find the rest after the closing brace */
2357 next = next_brace_sub(begin);
2359 /* An illegal expression */
2363 /* "{abc}" with no commas - illegal
2364 * brace expr, disregard and skip it */
2370 if (*begin == '\\' && begin[1] != '\0')
2374 debug_printf_glob("begin:%s\n", begin);
2375 debug_printf_glob("next:%s\n", next);
2377 /* Now find the end of the whole brace expression */
2379 while (*rest != '}') {
2380 rest = next_brace_sub(rest);
2382 /* An illegal expression */
2385 debug_printf_glob("rest:%s\n", rest);
2387 rest_len = strlen(++rest) + 1;
2389 /* We are sure the brace expression is well-formed */
2391 /* Allocate working buffer large enough for our work */
2392 new_pattern_buf = xmalloc(strlen(pattern));
2394 /* We have a brace expression. BEGIN points to the opening {,
2395 * NEXT points past the terminator of the first element, and REST
2396 * points past the final }. We will accumulate result names from
2397 * recursive runs for each brace alternative in the buffer using
2402 /* Construct the new glob expression */
2405 mempcpy(new_pattern_buf,
2406 /* We know the prefix for all sub-patterns */
2407 pattern, begin - pattern),
2411 /* Note: glob_brace() may garble new_pattern_buf[].
2412 * That's why we re-copy prefix every time (1st memcpy above).
2414 n = glob_brace(new_pattern_buf, o, n);
2416 /* We saw the last entry */
2420 next = next_brace_sub(next);
2422 free(new_pattern_buf);
2430 memset(&globdata, 0, sizeof(globdata));
2431 gr = glob(pattern, 0, NULL, &globdata);
2432 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2434 if (gr == GLOB_NOMATCH) {
2435 globfree(&globdata);
2436 /* NB: garbles parameter */
2437 unbackslash(pattern);
2438 o_addstr_with_NUL(o, pattern);
2439 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2440 return o_save_ptr_helper(o, n);
2442 if (gr == GLOB_NOSPACE)
2443 bb_error_msg_and_die(bb_msg_memory_exhausted);
2444 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2445 * but we didn't specify it. Paranoia again. */
2446 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2448 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2449 char **argv = globdata.gl_pathv;
2451 o_addstr_with_NUL(o, *argv);
2452 n = o_save_ptr_helper(o, n);
2458 globfree(&globdata);
2462 /* Performs globbing on last list[],
2463 * saving each result as a new list[].
2465 static int perform_glob(o_string *o, int n)
2467 char *pattern, *copy;
2469 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2471 return o_save_ptr_helper(o, n);
2472 pattern = o->data + o_get_last_ptr(o, n);
2473 debug_printf_glob("glob pattern '%s'\n", pattern);
2474 if (!glob_needed(pattern)) {
2475 /* unbackslash last string in o in place, fix length */
2476 o->length = unbackslash(pattern) - o->data;
2477 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2478 return o_save_ptr_helper(o, n);
2481 copy = xstrdup(pattern);
2482 /* "forget" pattern in o */
2483 o->length = pattern - o->data;
2484 n = glob_brace(copy, o, n);
2487 debug_print_list("perform_glob returning", o, n);
2491 #else /* !HUSH_BRACE_EXPANSION */
2494 static int glob_needed(const char *s)
2503 if (*s == '*' || *s == '[' || *s == '?')
2509 /* Performs globbing on last list[],
2510 * saving each result as a new list[].
2512 static int perform_glob(o_string *o, int n)
2518 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2520 return o_save_ptr_helper(o, n);
2521 pattern = o->data + o_get_last_ptr(o, n);
2522 debug_printf_glob("glob pattern '%s'\n", pattern);
2523 if (!glob_needed(pattern)) {
2525 /* unbackslash last string in o in place, fix length */
2526 o->length = unbackslash(pattern) - o->data;
2527 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2528 return o_save_ptr_helper(o, n);
2531 memset(&globdata, 0, sizeof(globdata));
2532 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2533 * If we glob "*.\*" and don't find anything, we need
2534 * to fall back to using literal "*.*", but GLOB_NOCHECK
2535 * will return "*.\*"!
2537 gr = glob(pattern, 0, NULL, &globdata);
2538 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2540 if (gr == GLOB_NOMATCH) {
2541 globfree(&globdata);
2544 if (gr == GLOB_NOSPACE)
2545 bb_error_msg_and_die(bb_msg_memory_exhausted);
2546 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2547 * but we didn't specify it. Paranoia again. */
2548 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2550 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2551 char **argv = globdata.gl_pathv;
2552 /* "forget" pattern in o */
2553 o->length = pattern - o->data;
2555 o_addstr_with_NUL(o, *argv);
2556 n = o_save_ptr_helper(o, n);
2562 globfree(&globdata);
2564 debug_print_list("perform_glob returning", o, n);
2568 #endif /* !HUSH_BRACE_EXPANSION */
2570 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2571 * Otherwise, just finish current list[] and start new */
2572 static int o_save_ptr(o_string *o, int n)
2574 if (o->o_expflags & EXP_FLAG_GLOB) {
2575 /* If o->has_empty_slot, list[n] was already globbed
2576 * (if it was requested back then when it was filled)
2577 * so don't do that again! */
2578 if (!o->has_empty_slot)
2579 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2581 return o_save_ptr_helper(o, n);
2584 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2585 static char **o_finalize_list(o_string *o, int n)
2590 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2592 debug_print_list("finalized", o, n);
2593 debug_printf_expand("finalized n:%d\n", n);
2594 list = (char**)o->data;
2595 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2599 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2604 static void free_pipe_list(struct pipe *pi);
2606 /* Returns pi->next - next pipe in the list */
2607 static struct pipe *free_pipe(struct pipe *pi)
2612 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2613 for (i = 0; i < pi->num_cmds; i++) {
2614 struct command *command;
2615 struct redir_struct *r, *rnext;
2617 command = &pi->cmds[i];
2618 debug_printf_clean(" command %d:\n", i);
2619 if (command->argv) {
2623 for (a = 0, p = command->argv; *p; a++, p++) {
2624 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2627 free_strings(command->argv);
2628 //command->argv = NULL;
2630 /* not "else if": on syntax error, we may have both! */
2631 if (command->group) {
2632 debug_printf_clean(" begin group (cmd_type:%d)\n",
2634 free_pipe_list(command->group);
2635 debug_printf_clean(" end group\n");
2636 //command->group = NULL;
2638 /* else is crucial here.
2639 * If group != NULL, child_func is meaningless */
2640 #if ENABLE_HUSH_FUNCTIONS
2641 else if (command->child_func) {
2642 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2643 command->child_func->parent_cmd = NULL;
2647 free(command->group_as_string);
2648 //command->group_as_string = NULL;
2650 for (r = command->redirects; r; r = rnext) {
2651 debug_printf_clean(" redirect %d%s",
2652 r->rd_fd, redir_table[r->rd_type].descrip);
2653 /* guard against the case >$FOO, where foo is unset or blank */
2654 if (r->rd_filename) {
2655 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2656 free(r->rd_filename);
2657 //r->rd_filename = NULL;
2659 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2663 //command->redirects = NULL;
2665 free(pi->cmds); /* children are an array, they get freed all at once */
2669 //pi->cmdtext = NULL;
2677 static void free_pipe_list(struct pipe *pi)
2681 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2683 debug_printf_clean("pipe followup code %d\n", pi->followup);
2689 /*** Parsing routines ***/
2691 #ifndef debug_print_tree
2692 static void debug_print_tree(struct pipe *pi, int lvl)
2694 static const char *const PIPE[] = {
2700 static const char *RES[] = {
2701 [RES_NONE ] = "NONE" ,
2704 [RES_THEN ] = "THEN" ,
2705 [RES_ELIF ] = "ELIF" ,
2706 [RES_ELSE ] = "ELSE" ,
2709 # if ENABLE_HUSH_LOOPS
2710 [RES_FOR ] = "FOR" ,
2711 [RES_WHILE] = "WHILE",
2712 [RES_UNTIL] = "UNTIL",
2714 [RES_DONE ] = "DONE" ,
2716 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2719 # if ENABLE_HUSH_CASE
2720 [RES_CASE ] = "CASE" ,
2721 [RES_CASE_IN ] = "CASE_IN" ,
2722 [RES_MATCH] = "MATCH",
2723 [RES_CASE_BODY] = "CASE_BODY",
2724 [RES_ESAC ] = "ESAC" ,
2726 [RES_XXXX ] = "XXXX" ,
2727 [RES_SNTX ] = "SNTX" ,
2729 static const char *const CMDTYPE[] = {
2733 # if ENABLE_HUSH_FUNCTIONS
2742 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2743 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2745 while (prn < pi->num_cmds) {
2746 struct command *command = &pi->cmds[prn];
2747 char **argv = command->argv;
2749 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2751 command->assignment_cnt);
2752 if (command->group) {
2753 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2754 CMDTYPE[command->cmd_type],
2757 , " group_as_string:", command->group_as_string
2762 debug_print_tree(command->group, lvl+1);
2766 if (argv) while (*argv) {
2767 fdprintf(2, " '%s'", *argv);
2777 #endif /* debug_print_tree */
2779 static struct pipe *new_pipe(void)
2782 pi = xzalloc(sizeof(struct pipe));
2783 /*pi->followup = 0; - deliberately invalid value */
2784 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2788 /* Command (member of a pipe) is complete, or we start a new pipe
2789 * if ctx->command is NULL.
2790 * No errors possible here.
2792 static int done_command(struct parse_context *ctx)
2794 /* The command is really already in the pipe structure, so
2795 * advance the pipe counter and make a new, null command. */
2796 struct pipe *pi = ctx->pipe;
2797 struct command *command = ctx->command;
2800 if (IS_NULL_CMD(command)) {
2801 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2805 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2806 //debug_print_tree(ctx->list_head, 20);
2808 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2811 /* Only real trickiness here is that the uncommitted
2812 * command structure is not counted in pi->num_cmds. */
2813 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2814 ctx->command = command = &pi->cmds[pi->num_cmds];
2816 memset(command, 0, sizeof(*command));
2817 return pi->num_cmds; /* used only for 0/nonzero check */
2820 static void done_pipe(struct parse_context *ctx, pipe_style type)
2824 debug_printf_parse("done_pipe entered, followup %d\n", type);
2825 /* Close previous command */
2826 not_null = done_command(ctx);
2827 ctx->pipe->followup = type;
2829 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2830 ctx->ctx_inverted = 0;
2831 ctx->pipe->res_word = ctx->ctx_res_w;
2834 /* Without this check, even just <enter> on command line generates
2835 * tree of three NOPs (!). Which is harmless but annoying.
2836 * IOW: it is safe to do it unconditionally. */
2839 || ctx->ctx_res_w == RES_FI
2841 #if ENABLE_HUSH_LOOPS
2842 || ctx->ctx_res_w == RES_DONE
2843 || ctx->ctx_res_w == RES_FOR
2844 || ctx->ctx_res_w == RES_IN
2846 #if ENABLE_HUSH_CASE
2847 || ctx->ctx_res_w == RES_ESAC
2851 debug_printf_parse("done_pipe: adding new pipe: "
2852 "not_null:%d ctx->ctx_res_w:%d\n",
2853 not_null, ctx->ctx_res_w);
2855 ctx->pipe->next = new_p;
2857 /* RES_THEN, RES_DO etc are "sticky" -
2858 * they remain set for pipes inside if/while.
2859 * This is used to control execution.
2860 * RES_FOR and RES_IN are NOT sticky (needed to support
2861 * cases where variable or value happens to match a keyword):
2863 #if ENABLE_HUSH_LOOPS
2864 if (ctx->ctx_res_w == RES_FOR
2865 || ctx->ctx_res_w == RES_IN)
2866 ctx->ctx_res_w = RES_NONE;
2868 #if ENABLE_HUSH_CASE
2869 if (ctx->ctx_res_w == RES_MATCH)
2870 ctx->ctx_res_w = RES_CASE_BODY;
2871 if (ctx->ctx_res_w == RES_CASE)
2872 ctx->ctx_res_w = RES_CASE_IN;
2874 ctx->command = NULL; /* trick done_command below */
2875 /* Create the memory for command, roughly:
2876 * ctx->pipe->cmds = new struct command;
2877 * ctx->command = &ctx->pipe->cmds[0];
2880 //debug_print_tree(ctx->list_head, 10);
2882 debug_printf_parse("done_pipe return\n");
2885 static void initialize_context(struct parse_context *ctx)
2887 memset(ctx, 0, sizeof(*ctx));
2888 ctx->pipe = ctx->list_head = new_pipe();
2889 /* Create the memory for command, roughly:
2890 * ctx->pipe->cmds = new struct command;
2891 * ctx->command = &ctx->pipe->cmds[0];
2896 /* If a reserved word is found and processed, parse context is modified
2897 * and 1 is returned.
2900 struct reserved_combo {
2903 unsigned char assignment_flag;
2907 FLAG_END = (1 << RES_NONE ),
2909 FLAG_IF = (1 << RES_IF ),
2910 FLAG_THEN = (1 << RES_THEN ),
2911 FLAG_ELIF = (1 << RES_ELIF ),
2912 FLAG_ELSE = (1 << RES_ELSE ),
2913 FLAG_FI = (1 << RES_FI ),
2915 # if ENABLE_HUSH_LOOPS
2916 FLAG_FOR = (1 << RES_FOR ),
2917 FLAG_WHILE = (1 << RES_WHILE),
2918 FLAG_UNTIL = (1 << RES_UNTIL),
2919 FLAG_DO = (1 << RES_DO ),
2920 FLAG_DONE = (1 << RES_DONE ),
2921 FLAG_IN = (1 << RES_IN ),
2923 # if ENABLE_HUSH_CASE
2924 FLAG_MATCH = (1 << RES_MATCH),
2925 FLAG_ESAC = (1 << RES_ESAC ),
2927 FLAG_START = (1 << RES_XXXX ),
2930 static const struct reserved_combo* match_reserved_word(o_string *word)
2932 /* Mostly a list of accepted follow-up reserved words.
2933 * FLAG_END means we are done with the sequence, and are ready
2934 * to turn the compound list into a command.
2935 * FLAG_START means the word must start a new compound list.
2937 static const struct reserved_combo reserved_list[] = {
2939 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2940 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2941 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2942 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2943 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2944 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2946 # if ENABLE_HUSH_LOOPS
2947 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2948 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2949 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2950 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2951 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2952 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2954 # if ENABLE_HUSH_CASE
2955 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2956 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2959 const struct reserved_combo *r;
2961 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2962 if (strcmp(word->data, r->literal) == 0)
2967 /* Return 0: not a keyword, 1: keyword
2969 static int reserved_word(o_string *word, struct parse_context *ctx)
2971 # if ENABLE_HUSH_CASE
2972 static const struct reserved_combo reserved_match = {
2973 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2976 const struct reserved_combo *r;
2978 if (word->has_quoted_part)
2980 r = match_reserved_word(word);
2984 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2985 # if ENABLE_HUSH_CASE
2986 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2987 /* "case word IN ..." - IN part starts first MATCH part */
2988 r = &reserved_match;
2991 if (r->flag == 0) { /* '!' */
2992 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2993 syntax_error("! ! command");
2994 ctx->ctx_res_w = RES_SNTX;
2996 ctx->ctx_inverted = 1;
2999 if (r->flag & FLAG_START) {
3000 struct parse_context *old;
3002 old = xmalloc(sizeof(*old));
3003 debug_printf_parse("push stack %p\n", old);
3004 *old = *ctx; /* physical copy */
3005 initialize_context(ctx);
3007 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3008 syntax_error_at(word->data);
3009 ctx->ctx_res_w = RES_SNTX;
3012 /* "{...} fi" is ok. "{...} if" is not
3014 * if { echo foo; } then { echo bar; } fi */
3015 if (ctx->command->group)
3016 done_pipe(ctx, PIPE_SEQ);
3019 ctx->ctx_res_w = r->res;
3020 ctx->old_flag = r->flag;
3021 word->o_assignment = r->assignment_flag;
3023 if (ctx->old_flag & FLAG_END) {
3024 struct parse_context *old;
3026 done_pipe(ctx, PIPE_SEQ);
3027 debug_printf_parse("pop stack %p\n", ctx->stack);
3029 old->command->group = ctx->list_head;
3030 old->command->cmd_type = CMD_NORMAL;
3032 o_addstr(&old->as_string, ctx->as_string.data);
3033 o_free_unsafe(&ctx->as_string);
3034 old->command->group_as_string = xstrdup(old->as_string.data);
3035 debug_printf_parse("pop, remembering as:'%s'\n",
3036 old->command->group_as_string);
3038 *ctx = *old; /* physical copy */
3043 #endif /* HAS_KEYWORDS */
3045 /* Word is complete, look at it and update parsing context.
3046 * Normal return is 0. Syntax errors return 1.
3047 * Note: on return, word is reset, but not o_free'd!
3049 static int done_word(o_string *word, struct parse_context *ctx)
3051 struct command *command = ctx->command;
3053 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3054 if (word->length == 0 && !word->has_quoted_part) {
3055 debug_printf_parse("done_word return 0: true null, ignored\n");
3059 if (ctx->pending_redirect) {
3060 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3061 * only if run as "bash", not "sh" */
3062 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3064 * ...the word that follows the redirection operator
3065 * shall be subjected to tilde expansion, parameter expansion,
3066 * command substitution, arithmetic expansion, and quote
3067 * removal. Pathname expansion shall not be performed
3068 * on the word by a non-interactive shell; an interactive
3069 * shell may perform it, but shall do so only when
3070 * the expansion would result in one word."
3072 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3073 /* Cater for >\file case:
3074 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3075 * Same with heredocs:
3076 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3078 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3079 unbackslash(ctx->pending_redirect->rd_filename);
3080 /* Is it <<"HEREDOC"? */
3081 if (word->has_quoted_part) {
3082 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3085 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3086 ctx->pending_redirect = NULL;
3088 /* If this word wasn't an assignment, next ones definitely
3089 * can't be assignments. Even if they look like ones. */
3090 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3091 && word->o_assignment != WORD_IS_KEYWORD
3093 word->o_assignment = NOT_ASSIGNMENT;
3095 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3096 command->assignment_cnt++;
3097 word->o_assignment = MAYBE_ASSIGNMENT;
3101 # if ENABLE_HUSH_CASE
3102 if (ctx->ctx_dsemicolon
3103 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3105 /* already done when ctx_dsemicolon was set to 1: */
3106 /* ctx->ctx_res_w = RES_MATCH; */
3107 ctx->ctx_dsemicolon = 0;
3110 if (!command->argv /* if it's the first word... */
3111 # if ENABLE_HUSH_LOOPS
3112 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3113 && ctx->ctx_res_w != RES_IN
3115 # if ENABLE_HUSH_CASE
3116 && ctx->ctx_res_w != RES_CASE
3119 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3120 if (reserved_word(word, ctx)) {
3121 o_reset_to_empty_unquoted(word);
3122 debug_printf_parse("done_word return %d\n",
3123 (ctx->ctx_res_w == RES_SNTX));
3124 return (ctx->ctx_res_w == RES_SNTX);
3126 # if ENABLE_HUSH_BASH_COMPAT
3127 if (strcmp(word->data, "[[") == 0) {
3128 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3134 if (command->group) {
3135 /* "{ echo foo; } echo bar" - bad */
3136 syntax_error_at(word->data);
3137 debug_printf_parse("done_word return 1: syntax error, "
3138 "groups and arglists don't mix\n");
3141 if (word->has_quoted_part
3142 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3143 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3144 /* (otherwise it's known to be not empty and is already safe) */
3146 /* exclude "$@" - it can expand to no word despite "" */
3147 char *p = word->data;
3148 while (p[0] == SPECIAL_VAR_SYMBOL
3149 && (p[1] & 0x7f) == '@'
3150 && p[2] == SPECIAL_VAR_SYMBOL
3154 if (p == word->data || p[0] != '\0') {
3155 /* saw no "$@", or not only "$@" but some
3156 * real text is there too */
3157 /* insert "empty variable" reference, this makes
3158 * e.g. "", $empty"" etc to not disappear */
3159 o_addchr(word, SPECIAL_VAR_SYMBOL);
3160 o_addchr(word, SPECIAL_VAR_SYMBOL);
3163 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3164 debug_print_strings("word appended to argv", command->argv);
3167 #if ENABLE_HUSH_LOOPS
3168 if (ctx->ctx_res_w == RES_FOR) {
3169 if (word->has_quoted_part
3170 || !is_well_formed_var_name(command->argv[0], '\0')
3172 /* bash says just "not a valid identifier" */
3173 syntax_error("not a valid identifier in for");
3176 /* Force FOR to have just one word (variable name) */
3177 /* NB: basically, this makes hush see "for v in ..."
3178 * syntax as if it is "for v; in ...". FOR and IN become
3179 * two pipe structs in parse tree. */
3180 done_pipe(ctx, PIPE_SEQ);
3183 #if ENABLE_HUSH_CASE
3184 /* Force CASE to have just one word */
3185 if (ctx->ctx_res_w == RES_CASE) {
3186 done_pipe(ctx, PIPE_SEQ);
3190 o_reset_to_empty_unquoted(word);
3192 debug_printf_parse("done_word return 0\n");
3197 /* Peek ahead in the input to find out if we have a "&n" construct,
3198 * as in "2>&1", that represents duplicating a file descriptor.
3200 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3201 * REDIRFD_SYNTAX_ERR if syntax error,
3202 * REDIRFD_TO_FILE if no & was seen,
3203 * or the number found.
3206 #define parse_redir_right_fd(as_string, input) \
3207 parse_redir_right_fd(input)
3209 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3215 return REDIRFD_TO_FILE;
3217 ch = i_getch(input); /* get the & */
3218 nommu_addchr(as_string, ch);
3221 ch = i_getch(input);
3222 nommu_addchr(as_string, ch);
3223 return REDIRFD_CLOSE;
3227 while (ch != EOF && isdigit(ch)) {
3228 d = d*10 + (ch-'0');
3230 ch = i_getch(input);
3231 nommu_addchr(as_string, ch);
3236 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3238 bb_error_msg("ambiguous redirect");
3239 return REDIRFD_SYNTAX_ERR;
3242 /* Return code is 0 normal, 1 if a syntax error is detected
3244 static int parse_redirect(struct parse_context *ctx,
3247 struct in_str *input)
3249 struct command *command = ctx->command;
3250 struct redir_struct *redir;
3251 struct redir_struct **redirp;
3254 dup_num = REDIRFD_TO_FILE;
3255 if (style != REDIRECT_HEREDOC) {
3256 /* Check for a '>&1' type redirect */
3257 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3258 if (dup_num == REDIRFD_SYNTAX_ERR)
3261 int ch = i_peek(input);
3262 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3263 if (dup_num) { /* <<-... */
3264 ch = i_getch(input);
3265 nommu_addchr(&ctx->as_string, ch);
3270 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3271 int ch = i_peek(input);
3273 /* >|FILE redirect ("clobbering" >).
3274 * Since we do not support "set -o noclobber" yet,
3275 * >| and > are the same for now. Just eat |.
3277 ch = i_getch(input);
3278 nommu_addchr(&ctx->as_string, ch);
3282 /* Create a new redir_struct and append it to the linked list */
3283 redirp = &command->redirects;
3284 while ((redir = *redirp) != NULL) {
3285 redirp = &(redir->next);
3287 *redirp = redir = xzalloc(sizeof(*redir));
3288 /* redir->next = NULL; */
3289 /* redir->rd_filename = NULL; */
3290 redir->rd_type = style;
3291 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3293 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3294 redir_table[style].descrip);
3296 redir->rd_dup = dup_num;
3297 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3298 /* Erik had a check here that the file descriptor in question
3299 * is legit; I postpone that to "run time"
3300 * A "-" representation of "close me" shows up as a -3 here */
3301 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3302 redir->rd_fd, redir->rd_dup);
3304 /* Set ctx->pending_redirect, so we know what to do at the
3305 * end of the next parsed word. */
3306 ctx->pending_redirect = redir;
3311 /* If a redirect is immediately preceded by a number, that number is
3312 * supposed to tell which file descriptor to redirect. This routine
3313 * looks for such preceding numbers. In an ideal world this routine
3314 * needs to handle all the following classes of redirects...
3315 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3316 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3317 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3318 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3320 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3322 * ... If n is quoted, the number shall not be recognized as part of
3323 * the redirection expression. For example:
3325 * writes the character 2 into file a"
3326 * We are getting it right by setting ->has_quoted_part on any \<char>
3328 * A -1 return means no valid number was found,
3329 * the caller should use the appropriate default for this redirection.
3331 static int redirect_opt_num(o_string *o)
3335 if (o->data == NULL)
3337 num = bb_strtou(o->data, NULL, 10);
3338 if (errno || num < 0)
3340 o_reset_to_empty_unquoted(o);
3345 #define fetch_till_str(as_string, input, word, skip_tabs) \
3346 fetch_till_str(input, word, skip_tabs)
3348 static char *fetch_till_str(o_string *as_string,
3349 struct in_str *input,
3353 o_string heredoc = NULL_O_STRING;
3355 int prev = 0; /* not \ */
3361 ch = i_getch(input);
3363 nommu_addchr(as_string, ch);
3364 if ((ch == '\n' || ch == EOF)
3365 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3367 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3368 heredoc.data[past_EOL] = '\0';
3369 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3370 return heredoc.data;
3372 while (ch == '\n') {
3373 o_addchr(&heredoc, ch);
3376 past_EOL = heredoc.length;
3378 ch = i_getch(input);
3380 nommu_addchr(as_string, ch);
3381 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3385 o_free_unsafe(&heredoc);
3388 o_addchr(&heredoc, ch);
3389 nommu_addchr(as_string, ch);
3390 if (prev == '\\' && ch == '\\')
3391 /* Correctly handle foo\\<eol> (not a line cont.) */
3392 prev = 0; /* not \ */
3398 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3399 * and load them all. There should be exactly heredoc_cnt of them.
3401 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3403 struct pipe *pi = ctx->list_head;
3405 while (pi && heredoc_cnt) {
3407 struct command *cmd = pi->cmds;
3409 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3411 cmd->argv ? cmd->argv[0] : "NONE");
3412 for (i = 0; i < pi->num_cmds; i++) {
3413 struct redir_struct *redir = cmd->redirects;
3415 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3416 i, cmd->argv ? cmd->argv[0] : "NONE");
3418 if (redir->rd_type == REDIRECT_HEREDOC) {
3421 redir->rd_type = REDIRECT_HEREDOC2;
3422 /* redir->rd_dup is (ab)used to indicate <<- */
3423 p = fetch_till_str(&ctx->as_string, input,
3424 redir->rd_filename, redir->rd_dup);
3426 syntax_error("unexpected EOF in here document");
3429 free(redir->rd_filename);
3430 redir->rd_filename = p;
3433 redir = redir->next;
3440 /* Should be 0. If it isn't, it's a parse error */
3442 bb_error_msg_and_die("heredoc BUG 2");
3448 static int run_list(struct pipe *pi);
3450 #define parse_stream(pstring, input, end_trigger) \
3451 parse_stream(input, end_trigger)
3453 static struct pipe *parse_stream(char **pstring,
3454 struct in_str *input,
3458 #if !ENABLE_HUSH_FUNCTIONS
3459 #define parse_group(dest, ctx, input, ch) \
3460 parse_group(ctx, input, ch)
3462 static int parse_group(o_string *dest, struct parse_context *ctx,
3463 struct in_str *input, int ch)
3465 /* dest contains characters seen prior to ( or {.
3466 * Typically it's empty, but for function defs,
3467 * it contains function name (without '()'). */
3468 struct pipe *pipe_list;
3470 struct command *command = ctx->command;
3472 debug_printf_parse("parse_group entered\n");
3473 #if ENABLE_HUSH_FUNCTIONS
3474 if (ch == '(' && !dest->has_quoted_part) {
3476 if (done_word(dest, ctx))
3479 goto skip; /* (... */
3480 if (command->argv[1]) { /* word word ... (... */
3481 syntax_error_unexpected_ch('(');
3484 /* it is "word(..." or "word (..." */
3486 ch = i_getch(input);
3487 while (ch == ' ' || ch == '\t');
3489 syntax_error_unexpected_ch(ch);
3492 nommu_addchr(&ctx->as_string, ch);
3494 ch = i_getch(input);
3495 while (ch == ' ' || ch == '\t' || ch == '\n');
3497 syntax_error_unexpected_ch(ch);
3500 nommu_addchr(&ctx->as_string, ch);
3501 command->cmd_type = CMD_FUNCDEF;
3506 #if 0 /* Prevented by caller */
3507 if (command->argv /* word [word]{... */
3508 || dest->length /* word{... */
3509 || dest->has_quoted_part /* ""{... */
3512 debug_printf_parse("parse_group return 1: "
3513 "syntax error, groups and arglists don't mix\n");
3518 #if ENABLE_HUSH_FUNCTIONS
3524 command->cmd_type = CMD_SUBSHELL;
3526 /* bash does not allow "{echo...", requires whitespace */
3527 ch = i_getch(input);
3528 if (ch != ' ' && ch != '\t' && ch != '\n') {
3529 syntax_error_unexpected_ch(ch);
3532 nommu_addchr(&ctx->as_string, ch);
3537 # define as_string NULL
3539 char *as_string = NULL;
3541 pipe_list = parse_stream(&as_string, input, endch);
3544 o_addstr(&ctx->as_string, as_string);
3546 /* empty ()/{} or parse error? */
3547 if (!pipe_list || pipe_list == ERR_PTR) {
3548 /* parse_stream already emitted error msg */
3551 debug_printf_parse("parse_group return 1: "
3552 "parse_stream returned %p\n", pipe_list);
3555 command->group = pipe_list;
3557 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3558 command->group_as_string = as_string;
3559 debug_printf_parse("end of group, remembering as:'%s'\n",
3560 command->group_as_string);
3564 debug_printf_parse("parse_group return 0\n");
3566 /* command remains "open", available for possible redirects */
3569 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3570 /* Subroutines for copying $(...) and `...` things */
3571 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3573 static int add_till_single_quote(o_string *dest, struct in_str *input)
3576 int ch = i_getch(input);
3578 syntax_error_unterm_ch('\'');
3586 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3587 static int add_till_double_quote(o_string *dest, struct in_str *input)
3590 int ch = i_getch(input);
3592 syntax_error_unterm_ch('"');
3597 if (ch == '\\') { /* \x. Copy both chars. */
3599 ch = i_getch(input);
3603 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3608 //if (ch == '$') ...
3611 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3613 * "Within the backquoted style of command substitution, backslash
3614 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3615 * The search for the matching backquote shall be satisfied by the first
3616 * backquote found without a preceding backslash; during this search,
3617 * if a non-escaped backquote is encountered within a shell comment,
3618 * a here-document, an embedded command substitution of the $(command)
3619 * form, or a quoted string, undefined results occur. A single-quoted
3620 * or double-quoted string that begins, but does not end, within the
3621 * "`...`" sequence produces undefined results."
3623 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3625 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3628 int ch = i_getch(input);
3632 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3633 ch = i_getch(input);
3637 && (!in_dquote || ch != '"')
3639 o_addchr(dest, '\\');
3643 syntax_error_unterm_ch('`');
3649 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3650 * quoting and nested ()s.
3651 * "With the $(command) style of command substitution, all characters
3652 * following the open parenthesis to the matching closing parenthesis
3653 * constitute the command. Any valid shell script can be used for command,
3654 * except a script consisting solely of redirections which produces
3655 * unspecified results."
3657 * echo $(echo '(TEST)' BEST) (TEST) BEST
3658 * echo $(echo 'TEST)' BEST) TEST) BEST
3659 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3661 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3662 * can contain arbitrary constructs, just like $(cmd).
3663 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3664 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3666 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3667 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3670 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3671 # if ENABLE_HUSH_BASH_COMPAT
3672 char end_char2 = end_ch >> 8;
3674 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3677 ch = i_getch(input);
3679 syntax_error_unterm_ch(end_ch);
3682 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3685 /* we look for closing )) of $((EXPR)) */
3686 if (i_peek(input) == end_ch) {
3687 i_getch(input); /* eat second ')' */
3692 if (ch == '(' || ch == '{') {
3693 ch = (ch == '(' ? ')' : '}');
3694 if (!add_till_closing_bracket(dest, input, ch))
3700 if (!add_till_single_quote(dest, input))
3706 if (!add_till_double_quote(dest, input))
3712 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3718 /* \x. Copy verbatim. Important for \(, \) */
3719 ch = i_getch(input);
3721 syntax_error_unterm_ch(')');
3730 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3732 /* Return code: 0 for OK, 1 for syntax error */
3734 #define parse_dollar(as_string, dest, input, quote_mask) \
3735 parse_dollar(dest, input, quote_mask)
3736 #define as_string NULL
3738 static int parse_dollar(o_string *as_string,
3740 struct in_str *input, unsigned char quote_mask)
3742 int ch = i_peek(input); /* first character after the $ */
3744 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3746 ch = i_getch(input);
3747 nommu_addchr(as_string, ch);
3749 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3751 debug_printf_parse(": '%c'\n", ch);
3752 o_addchr(dest, ch | quote_mask);
3755 if (!isalnum(ch) && ch != '_')
3757 ch = i_getch(input);
3758 nommu_addchr(as_string, ch);
3760 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3761 } else if (isdigit(ch)) {
3763 ch = i_getch(input);
3764 nommu_addchr(as_string, ch);
3765 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3766 debug_printf_parse(": '%c'\n", ch);
3767 o_addchr(dest, ch | quote_mask);
3768 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3769 } else switch (ch) {
3771 case '!': /* last bg pid */
3772 case '?': /* last exit code */
3773 case '#': /* number of args */
3774 case '*': /* args */
3775 case '@': /* args */
3776 goto make_one_char_var;
3778 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3780 ch = i_getch(input); /* eat '{' */
3781 nommu_addchr(as_string, ch);
3783 ch = i_getch(input); /* first char after '{' */
3784 /* It should be ${?}, or ${#var},
3785 * or even ${?+subst} - operator acting on a special variable,
3786 * or the beginning of variable name.
3789 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3792 syntax_error_unterm_str("${name}");
3793 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3796 nommu_addchr(as_string, ch);
3799 /* It's possible to just call add_till_closing_bracket() at this point.
3800 * However, this regresses some of our testsuite cases
3801 * which check invalid constructs like ${%}.
3802 * Oh well... let's check that the var name part is fine... */
3808 debug_printf_parse(": '%c'\n", ch);
3810 ch = i_getch(input);
3811 nommu_addchr(as_string, ch);
3815 if (!isalnum(ch) && ch != '_') {
3817 unsigned char last_ch;
3818 /* handle parameter expansions
3819 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3821 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3822 goto bad_dollar_syntax;
3824 /* Eat everything until closing '}' (or ':') */
3826 if (ENABLE_HUSH_BASH_COMPAT
3828 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3830 /* It's ${var:N[:M]} thing */
3831 end_ch = '}' * 0x100 + ':';
3833 if (ENABLE_HUSH_BASH_COMPAT
3836 /* It's ${var/[/]pattern[/repl]} thing */
3837 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3839 nommu_addchr(as_string, '/');
3842 end_ch = '}' * 0x100 + '/';
3848 #if ENABLE_HUSH_DOLLAR_OPS
3849 last_ch = add_till_closing_bracket(dest, input, end_ch);
3850 if (last_ch == 0) /* error? */
3853 #error Simple code to only allow ${var} is not implemented
3856 o_addstr(as_string, dest->data + pos);
3857 o_addchr(as_string, last_ch);
3860 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3861 /* close the first block: */
3862 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3863 /* while parsing N from ${var:N[:M]}
3864 * or pattern from ${var/[/]pattern[/repl]} */
3865 if ((end_ch & 0xff) == last_ch) {
3866 /* got ':' or '/'- parse the rest */
3871 if (end_ch == '}' * 0x100 + ':') {
3872 /* it's ${var:N} - emulate :999999999 */
3873 o_addstr(dest, "999999999");
3874 } /* else: it's ${var/[/]pattern} */
3879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3882 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3886 ch = i_getch(input);
3887 nommu_addchr(as_string, ch);
3888 # if ENABLE_SH_MATH_SUPPORT
3889 if (i_peek(input) == '(') {
3890 ch = i_getch(input);
3891 nommu_addchr(as_string, ch);
3892 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3893 o_addchr(dest, /*quote_mask |*/ '+');
3896 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3897 return 0; /* error */
3899 o_addstr(as_string, dest->data + pos);
3900 o_addchr(as_string, ')');
3901 o_addchr(as_string, ')');
3903 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3907 # if ENABLE_HUSH_TICK
3908 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3909 o_addchr(dest, quote_mask | '`');
3912 if (!add_till_closing_bracket(dest, input, ')'))
3913 return 0; /* error */
3915 o_addstr(as_string, dest->data + pos);
3916 o_addchr(as_string, ')');
3918 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3924 ch = i_getch(input);
3925 nommu_addchr(as_string, ch);
3927 if (isalnum(ch)) { /* it's $_name or $_123 */
3932 /* TODO: $_ and $-: */
3933 /* $_ Shell or shell script name; or last argument of last command
3934 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3935 * but in command's env, set to full pathname used to invoke it */
3936 /* $- Option flags set by set builtin or shell options (-i etc) */
3938 o_addQchr(dest, '$');
3940 debug_printf_parse("parse_dollar return 1 (ok)\n");
3946 # if ENABLE_HUSH_BASH_COMPAT
3947 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3948 encode_string(dest, input, dquote_end, process_bkslash)
3950 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3951 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3952 encode_string(dest, input, dquote_end)
3954 #define as_string NULL
3958 # if ENABLE_HUSH_BASH_COMPAT
3959 /* all parameters are needed, no macro tricks */
3961 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3962 encode_string(as_string, dest, input, dquote_end)
3965 static int encode_string(o_string *as_string,
3967 struct in_str *input,
3969 int process_bkslash)
3971 #if !ENABLE_HUSH_BASH_COMPAT
3972 const int process_bkslash = 1;
3978 ch = i_getch(input);
3980 nommu_addchr(as_string, ch);
3981 if (ch == dquote_end) { /* may be only '"' or EOF */
3982 debug_printf_parse("encode_string return 1 (ok)\n");
3985 /* note: can't move it above ch == dquote_end check! */
3987 syntax_error_unterm_ch('"');
3988 return 0; /* error */
3992 next = i_peek(input);
3994 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3995 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3996 if (process_bkslash && ch == '\\') {
3998 syntax_error("\\<eof>");
4002 * "The backslash retains its special meaning [in "..."]
4003 * only when followed by one of the following characters:
4004 * $, `, ", \, or <newline>. A double quote may be quoted
4005 * within double quotes by preceding it with a backslash."
4006 * NB: in (unquoted) heredoc, above does not apply to ",
4007 * therefore we check for it by "next == dquote_end" cond.
4009 if (next == dquote_end || strchr("$`\\\n", next)) {
4010 ch = i_getch(input); /* eat next */
4012 goto again; /* skip \<newline> */
4013 } /* else: ch remains == '\\', and we double it below: */
4014 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4015 nommu_addchr(as_string, ch);
4019 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4020 debug_printf_parse("encode_string return 0: "
4021 "parse_dollar returned 0 (error)\n");
4026 #if ENABLE_HUSH_TICK
4028 //unsigned pos = dest->length;
4029 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4030 o_addchr(dest, 0x80 | '`');
4031 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4032 return 0; /* error */
4033 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4034 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4038 o_addQchr(dest, ch);
4044 * Scan input until EOF or end_trigger char.
4045 * Return a list of pipes to execute, or NULL on EOF
4046 * or if end_trigger character is met.
4047 * On syntax error, exit if shell is not interactive,
4048 * reset parsing machinery and start parsing anew,
4049 * or return ERR_PTR.
4051 static struct pipe *parse_stream(char **pstring,
4052 struct in_str *input,
4055 struct parse_context ctx;
4056 o_string dest = NULL_O_STRING;
4059 /* Single-quote triggers a bypass of the main loop until its mate is
4060 * found. When recursing, quote state is passed in via dest->o_expflags.
4062 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4063 end_trigger ? end_trigger : 'X');
4066 /* If very first arg is "" or '', dest.data may end up NULL.
4067 * Preventing this: */
4068 o_addchr(&dest, '\0');
4071 /* We used to separate words on $IFS here. This was wrong.
4072 * $IFS is used only for word splitting when $var is expanded,
4073 * here we should use blank chars as separators, not $IFS
4076 if (MAYBE_ASSIGNMENT != 0)
4077 dest.o_assignment = MAYBE_ASSIGNMENT;
4078 initialize_context(&ctx);
4081 const char *is_blank;
4082 const char *is_special;
4086 redir_type redir_style;
4088 ch = i_getch(input);
4089 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4090 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4095 syntax_error_unterm_str("here document");
4098 /* end_trigger == '}' case errors out earlier,
4099 * checking only ')' */
4100 if (end_trigger == ')') {
4101 syntax_error_unterm_ch('(');
4105 if (done_word(&dest, &ctx)) {
4109 done_pipe(&ctx, PIPE_SEQ);
4111 /* If we got nothing... */
4112 /* (this makes bare "&" cmd a no-op.
4113 * bash says: "syntax error near unexpected token '&'") */
4114 if (pi->num_cmds == 0
4115 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4121 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4123 *pstring = ctx.as_string.data;
4125 o_free_unsafe(&ctx.as_string);
4128 debug_printf_parse("parse_stream return %p\n", pi);
4131 nommu_addchr(&ctx.as_string, ch);
4135 next = i_peek(input);
4137 is_special = "{}<>;&|()#'" /* special outside of "str" */
4138 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4139 /* Are { and } special here? */
4140 if (ctx.command->argv /* word [word]{... - non-special */
4141 || dest.length /* word{... - non-special */
4142 || dest.has_quoted_part /* ""{... - non-special */
4143 || (next != ';' /* }; - special */
4144 && next != ')' /* }) - special */
4145 && next != '&' /* }& and }&& ... - special */
4146 && next != '|' /* }|| ... - special */
4147 && !strchr(defifs, next) /* {word - non-special */
4150 /* They are not special, skip "{}" */
4153 is_special = strchr(is_special, ch);
4154 is_blank = strchr(defifs, ch);
4156 if (!is_special && !is_blank) { /* ordinary char */
4158 o_addQchr(&dest, ch);
4159 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4160 || dest.o_assignment == WORD_IS_KEYWORD)
4162 && is_well_formed_var_name(dest.data, '=')
4164 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4170 if (done_word(&dest, &ctx)) {
4174 /* Is this a case when newline is simply ignored?
4176 * "cmd | <newline> cmd ..."
4177 * "case ... in <newline> word) ..."
4179 if (IS_NULL_CMD(ctx.command)
4180 && dest.length == 0 && !dest.has_quoted_part
4182 /* This newline can be ignored. But...
4183 * Without check #1, interactive shell
4184 * ignores even bare <newline>,
4185 * and shows the continuation prompt:
4186 * ps1_prompt$ <enter>
4187 * ps2> _ <=== wrong, should be ps1
4188 * Without check #2, "cmd & <newline>"
4189 * is similarly mistreated.
4190 * (BTW, this makes "cmd & cmd"
4191 * and "cmd && cmd" non-orthogonal.
4192 * Really, ask yourself, why
4193 * "cmd && <newline>" doesn't start
4194 * cmd but waits for more input?
4197 struct pipe *pi = ctx.list_head;
4198 if (pi->num_cmds != 0 /* check #1 */
4199 && pi->followup != PIPE_BG /* check #2 */
4204 /* Treat newline as a command separator. */
4205 done_pipe(&ctx, PIPE_SEQ);
4206 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4208 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4213 dest.o_assignment = MAYBE_ASSIGNMENT;
4215 /* note: if (is_blank) continue;
4216 * will still trigger for us */
4220 /* "cmd}" or "cmd }..." without semicolon or &:
4221 * } is an ordinary char in this case, even inside { cmd; }
4222 * Pathological example: { ""}; } should exec "}" cmd
4225 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4226 || dest.length != 0 /* word} */
4227 || dest.has_quoted_part /* ""} */
4231 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4232 goto skip_end_trigger;
4233 /* else: } does terminate a group */
4236 if (end_trigger && end_trigger == ch
4237 && (ch != ';' || heredoc_cnt == 0)
4238 #if ENABLE_HUSH_CASE
4240 || ctx.ctx_res_w != RES_MATCH
4241 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4246 /* This is technically valid:
4247 * { cat <<HERE; }; echo Ok
4251 * but we don't support this.
4252 * We require heredoc to be in enclosing {}/(),
4255 syntax_error_unterm_str("here document");
4258 if (done_word(&dest, &ctx)) {
4261 done_pipe(&ctx, PIPE_SEQ);
4262 dest.o_assignment = MAYBE_ASSIGNMENT;
4263 /* Do we sit outside of any if's, loops or case's? */
4265 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4269 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4271 *pstring = ctx.as_string.data;
4273 o_free_unsafe(&ctx.as_string);
4276 debug_printf_parse("parse_stream return %p: "
4277 "end_trigger char found\n",
4279 return ctx.list_head;
4286 /* Catch <, > before deciding whether this word is
4287 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4290 redir_fd = redirect_opt_num(&dest);
4291 if (done_word(&dest, &ctx)) {
4294 redir_style = REDIRECT_OVERWRITE;
4296 redir_style = REDIRECT_APPEND;
4297 ch = i_getch(input);
4298 nommu_addchr(&ctx.as_string, ch);
4301 else if (next == '(') {
4302 syntax_error(">(process) not supported");
4306 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4308 continue; /* back to top of while (1) */
4310 redir_fd = redirect_opt_num(&dest);
4311 if (done_word(&dest, &ctx)) {
4314 redir_style = REDIRECT_INPUT;
4316 redir_style = REDIRECT_HEREDOC;
4318 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4319 ch = i_getch(input);
4320 nommu_addchr(&ctx.as_string, ch);
4321 } else if (next == '>') {
4322 redir_style = REDIRECT_IO;
4323 ch = i_getch(input);
4324 nommu_addchr(&ctx.as_string, ch);
4327 else if (next == '(') {
4328 syntax_error("<(process) not supported");
4332 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4334 continue; /* back to top of while (1) */
4336 if (dest.length == 0 && !dest.has_quoted_part) {
4337 /* skip "#comment" */
4340 if (ch == EOF || ch == '\n')
4343 /* note: we do not add it to &ctx.as_string */
4345 nommu_addchr(&ctx.as_string, '\n');
4346 continue; /* back to top of while (1) */
4351 /* It's "\<newline>" */
4353 /* Remove trailing '\' from ctx.as_string */
4354 ctx.as_string.data[--ctx.as_string.length] = '\0';
4356 ch = i_getch(input); /* eat it */
4357 continue; /* back to top of while (1) */
4362 if (dest.o_assignment == MAYBE_ASSIGNMENT
4363 /* check that we are not in word in "a=1 2>word b=1": */
4364 && !ctx.pending_redirect
4366 /* ch is a special char and thus this word
4367 * cannot be an assignment */
4368 dest.o_assignment = NOT_ASSIGNMENT;
4371 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4374 case '#': /* non-comment #: "echo a#b" etc */
4375 o_addQchr(&dest, ch);
4379 syntax_error("\\<eof>");
4382 ch = i_getch(input);
4383 /* note: ch != '\n' (that case does not reach this place) */
4384 o_addchr(&dest, '\\');
4385 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4386 o_addchr(&dest, ch);
4387 nommu_addchr(&ctx.as_string, ch);
4388 /* Example: echo Hello \2>file
4389 * we need to know that word 2 is quoted */
4390 dest.has_quoted_part = 1;
4393 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4394 debug_printf_parse("parse_stream parse error: "
4395 "parse_dollar returned 0 (error)\n");
4400 dest.has_quoted_part = 1;
4402 ch = i_getch(input);
4404 syntax_error_unterm_ch('\'');
4407 nommu_addchr(&ctx.as_string, ch);
4410 o_addqchr(&dest, ch);
4414 dest.has_quoted_part = 1;
4415 if (dest.o_assignment == NOT_ASSIGNMENT)
4416 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4417 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4419 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4421 #if ENABLE_HUSH_TICK
4425 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4426 o_addchr(&dest, '`');
4428 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4431 o_addstr(&ctx.as_string, dest.data + pos);
4432 o_addchr(&ctx.as_string, '`');
4434 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4435 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4440 #if ENABLE_HUSH_CASE
4443 if (done_word(&dest, &ctx)) {
4446 done_pipe(&ctx, PIPE_SEQ);
4447 #if ENABLE_HUSH_CASE
4448 /* Eat multiple semicolons, detect
4449 * whether it means something special */
4454 ch = i_getch(input);
4455 nommu_addchr(&ctx.as_string, ch);
4456 if (ctx.ctx_res_w == RES_CASE_BODY) {
4457 ctx.ctx_dsemicolon = 1;
4458 ctx.ctx_res_w = RES_MATCH;
4464 /* We just finished a cmd. New one may start
4465 * with an assignment */
4466 dest.o_assignment = MAYBE_ASSIGNMENT;
4469 if (done_word(&dest, &ctx)) {
4473 ch = i_getch(input);
4474 nommu_addchr(&ctx.as_string, ch);
4475 done_pipe(&ctx, PIPE_AND);
4477 done_pipe(&ctx, PIPE_BG);
4481 if (done_word(&dest, &ctx)) {
4484 #if ENABLE_HUSH_CASE
4485 if (ctx.ctx_res_w == RES_MATCH)
4486 break; /* we are in case's "word | word)" */
4488 if (next == '|') { /* || */
4489 ch = i_getch(input);
4490 nommu_addchr(&ctx.as_string, ch);
4491 done_pipe(&ctx, PIPE_OR);
4493 /* we could pick up a file descriptor choice here
4494 * with redirect_opt_num(), but bash doesn't do it.
4495 * "echo foo 2| cat" yields "foo 2". */
4498 o_reset_to_empty_unquoted(&ctx.as_string);
4503 #if ENABLE_HUSH_CASE
4504 /* "case... in [(]word)..." - skip '(' */
4505 if (ctx.ctx_res_w == RES_MATCH
4506 && ctx.command->argv == NULL /* not (word|(... */
4507 && dest.length == 0 /* not word(... */
4508 && dest.has_quoted_part == 0 /* not ""(... */
4514 if (parse_group(&dest, &ctx, input, ch) != 0) {
4519 #if ENABLE_HUSH_CASE
4520 if (ctx.ctx_res_w == RES_MATCH)
4524 /* proper use of this character is caught by end_trigger:
4525 * if we see {, we call parse_group(..., end_trigger='}')
4526 * and it will match } earlier (not here). */
4527 syntax_error_unexpected_ch(ch);
4531 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4537 struct parse_context *pctx;
4538 IF_HAS_KEYWORDS(struct parse_context *p2;)
4540 /* Clean up allocated tree.
4541 * Sample for finding leaks on syntax error recovery path.
4542 * Run it from interactive shell, watch pmap `pidof hush`.
4543 * while if false; then false; fi; do break; fi
4544 * Samples to catch leaks at execution:
4545 * while if (true | {true;}); then echo ok; fi; do break; done
4546 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4550 /* Update pipe/command counts,
4551 * otherwise freeing may miss some */
4552 done_pipe(pctx, PIPE_SEQ);
4553 debug_printf_clean("freeing list %p from ctx %p\n",
4554 pctx->list_head, pctx);
4555 debug_print_tree(pctx->list_head, 0);
4556 free_pipe_list(pctx->list_head);
4557 debug_printf_clean("freed list %p\n", pctx->list_head);
4559 o_free_unsafe(&pctx->as_string);
4561 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4565 IF_HAS_KEYWORDS(pctx = p2;)
4566 } while (HAS_KEYWORDS && pctx);
4569 G.last_exitcode = 1;
4580 /*** Execution routines ***/
4582 /* Expansion can recurse, need forward decls: */
4583 #if !ENABLE_HUSH_BASH_COMPAT
4584 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4585 #define expand_string_to_string(str, do_unbackslash) \
4586 expand_string_to_string(str)
4588 static char *expand_string_to_string(const char *str, int do_unbackslash);
4589 #if ENABLE_HUSH_TICK
4590 static int process_command_subs(o_string *dest, const char *s);
4593 /* expand_strvec_to_strvec() takes a list of strings, expands
4594 * all variable references within and returns a pointer to
4595 * a list of expanded strings, possibly with larger number
4596 * of strings. (Think VAR="a b"; echo $VAR).
4597 * This new list is allocated as a single malloc block.
4598 * NULL-terminated list of char* pointers is at the beginning of it,
4599 * followed by strings themselves.
4600 * Caller can deallocate entire list by single free(list). */
4602 /* A horde of its helpers come first: */
4604 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4606 while (--len >= 0) {
4609 #if ENABLE_HUSH_BRACE_EXPANSION
4610 if (c == '{' || c == '}') {
4611 /* { -> \{, } -> \} */
4613 /* And now we want to add { or } and continue:
4616 * luckily, just falling throught achieves this.
4622 /* \z -> \\\z; \<eol> -> \\<eol> */
4627 o_addchr(o, *str++);
4633 /* Store given string, finalizing the word and starting new one whenever
4634 * we encounter IFS char(s). This is used for expanding variable values.
4635 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4636 static int expand_on_ifs(o_string *output, int n, const char *str)
4639 int word_len = strcspn(str, G.ifs);
4641 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4642 o_addblock(output, str, word_len);
4644 /* Protect backslashes against globbing up :)
4645 * Example: "v='\*'; echo b$v" prints "b\*"
4646 * (and does not try to glob on "*")
4648 o_addblock_duplicate_backslash(output, str, word_len);
4649 /*/ Why can't we do it easier? */
4650 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4651 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4655 if (!*str) /* EOL - do not finalize word */
4657 o_addchr(output, '\0');
4658 debug_print_list("expand_on_ifs", output, n);
4659 n = o_save_ptr(output, n);
4660 str += strspn(str, G.ifs); /* skip ifs chars */
4662 debug_print_list("expand_on_ifs[1]", output, n);
4666 /* Helper to expand $((...)) and heredoc body. These act as if
4667 * they are in double quotes, with the exception that they are not :).
4668 * Just the rules are similar: "expand only $var and `cmd`"
4670 * Returns malloced string.
4671 * As an optimization, we return NULL if expansion is not needed.
4673 #if !ENABLE_HUSH_BASH_COMPAT
4674 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4675 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4676 encode_then_expand_string(str)
4678 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4681 struct in_str input;
4682 o_string dest = NULL_O_STRING;
4684 if (!strchr(str, '$')
4685 && !strchr(str, '\\')
4686 #if ENABLE_HUSH_TICK
4687 && !strchr(str, '`')
4693 /* We need to expand. Example:
4694 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4696 setup_string_in_str(&input, str);
4697 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4698 //TODO: error check (encode_string returns 0 on error)?
4699 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4700 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4701 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4702 o_free_unsafe(&dest);
4706 #if ENABLE_SH_MATH_SUPPORT
4707 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4709 arith_state_t math_state;
4713 math_state.lookupvar = get_local_var_value;
4714 math_state.setvar = set_local_var_from_halves;
4715 //math_state.endofname = endofname;
4716 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4717 res = arith(&math_state, exp_str ? exp_str : arg);
4720 *errmsg_p = math_state.errmsg;
4721 if (math_state.errmsg)
4722 die_if_script(math_state.errmsg);
4727 #if ENABLE_HUSH_BASH_COMPAT
4728 /* ${var/[/]pattern[/repl]} helpers */
4729 static char *strstr_pattern(char *val, const char *pattern, int *size)
4732 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4733 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4740 /* Optimization: if "*pat" did not match the start of "string",
4741 * we know that "tring", "ring" etc will not match too:
4743 if (pattern[0] == '*')
4748 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4750 char *result = NULL;
4751 unsigned res_len = 0;
4752 unsigned repl_len = strlen(repl);
4756 char *s = strstr_pattern(val, pattern, &size);
4760 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4761 memcpy(result + res_len, val, s - val);
4763 strcpy(result + res_len, repl);
4764 res_len += repl_len;
4765 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4771 if (val[0] && result) {
4772 result = xrealloc(result, res_len + strlen(val) + 1);
4773 strcpy(result + res_len, val);
4774 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4776 debug_printf_varexp("result:'%s'\n", result);
4782 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4784 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4786 const char *val = NULL;
4787 char *to_be_freed = NULL;
4792 char exp_save = exp_save; /* for compiler */
4793 char *exp_saveptr; /* points to expansion operator */
4794 char *exp_word = exp_word; /* for compiler */
4797 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4799 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4801 first_char = arg[0] = arg0 & 0x7f;
4804 if (first_char == '#' /* ${#... */
4805 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4807 /* It must be length operator: ${#var} */
4811 /* Maybe handle parameter expansion */
4812 if (exp_saveptr /* if 2nd char is one of expansion operators */
4813 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4815 /* ${?:0}, ${#[:]%0} etc */
4816 exp_saveptr = var + 1;
4818 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4819 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4821 exp_op = exp_save = *exp_saveptr;
4823 exp_word = exp_saveptr + 1;
4824 if (exp_op == ':') {
4825 exp_op = *exp_word++;
4826 //TODO: try ${var:} and ${var:bogus} in non-bash config
4827 if (ENABLE_HUSH_BASH_COMPAT
4828 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4830 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4835 *exp_saveptr = '\0';
4836 } /* else: it's not an expansion op, but bare ${var} */
4839 /* Look up the variable in question */
4840 if (isdigit(var[0])) {
4841 /* parse_dollar should have vetted var for us */
4842 int n = xatoi_positive(var);
4843 if (n < G.global_argc)
4844 val = G.global_argv[n];
4845 /* else val remains NULL: $N with too big N */
4849 val = utoa(G.root_pid);
4851 case '!': /* bg pid */
4852 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4854 case '?': /* exitcode */
4855 val = utoa(G.last_exitcode);
4857 case '#': /* argc */
4858 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4861 val = get_local_var_value(var);
4865 /* Handle any expansions */
4866 if (exp_op == 'L') {
4867 debug_printf_expand("expand: length(%s)=", val);
4868 val = utoa(val ? strlen(val) : 0);
4869 debug_printf_expand("%s\n", val);
4870 } else if (exp_op) {
4871 if (exp_op == '%' || exp_op == '#') {
4872 /* Standard-mandated substring removal ops:
4873 * ${parameter%word} - remove smallest suffix pattern
4874 * ${parameter%%word} - remove largest suffix pattern
4875 * ${parameter#word} - remove smallest prefix pattern
4876 * ${parameter##word} - remove largest prefix pattern
4878 * Word is expanded to produce a glob pattern.
4879 * Then var's value is matched to it and matching part removed.
4881 if (val && val[0]) {
4885 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4886 if (exp_op == *exp_word) /* ## or %% */
4888 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4890 exp_word = exp_exp_word;
4891 /* HACK ALERT. We depend here on the fact that
4892 * G.global_argv and results of utoa and get_local_var_value
4893 * are actually in writable memory:
4894 * scan_and_match momentarily stores NULs there. */
4896 loc = scan_and_match(t, exp_word, scan_flags);
4897 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4898 // exp_op, t, exp_word, loc);
4900 if (loc) { /* match was found */
4901 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4902 val = loc; /* take right part */
4904 val = to_be_freed = xstrndup(val, loc - val); /* left */
4908 #if ENABLE_HUSH_BASH_COMPAT
4909 else if (exp_op == '/' || exp_op == '\\') {
4910 /* It's ${var/[/]pattern[/repl]} thing.
4911 * Note that in encoded form it has TWO parts:
4912 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4913 * and if // is used, it is encoded as \:
4914 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4916 /* Empty variable always gives nothing: */
4917 // "v=''; echo ${v/*/w}" prints "", not "w"
4918 if (val && val[0]) {
4919 /* pattern uses non-standard expansion.
4920 * repl should be unbackslashed and globbed
4921 * by the usual expansion rules:
4923 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4924 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4925 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4926 * v='a bz'; echo ${v/a*z/\z} prints "z"
4927 * (note that a*z _pattern_ is never globbed!)
4929 char *pattern, *repl, *t;
4930 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4932 pattern = xstrdup(exp_word);
4933 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4934 *p++ = SPECIAL_VAR_SYMBOL;
4936 p = strchr(p, SPECIAL_VAR_SYMBOL);
4938 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4939 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4940 /* HACK ALERT. We depend here on the fact that
4941 * G.global_argv and results of utoa and get_local_var_value
4942 * are actually in writable memory:
4943 * replace_pattern momentarily stores NULs there. */
4945 to_be_freed = replace_pattern(t,
4947 (repl ? repl : exp_word),
4949 if (to_be_freed) /* at least one replace happened */
4956 else if (exp_op == ':') {
4957 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4958 /* It's ${var:N[:M]} bashism.
4959 * Note that in encoded form it has TWO parts:
4960 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4965 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4968 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4969 *p++ = SPECIAL_VAR_SYMBOL;
4971 p = strchr(p, SPECIAL_VAR_SYMBOL);
4973 len = expand_and_evaluate_arith(exp_word, &errmsg);
4976 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4977 if (len >= 0) { /* bash compat: len < 0 is illegal */
4978 if (beg < 0) /* bash compat */
4980 debug_printf_varexp("from val:'%s'\n", val);
4981 if (len == 0 || !val || beg >= strlen(val)) {
4985 /* Paranoia. What if user entered 9999999999999
4986 * which fits in arith_t but not int? */
4989 val = to_be_freed = xstrndup(val + beg, len);
4991 debug_printf_varexp("val:'%s'\n", val);
4995 die_if_script("malformed ${%s:...}", var);
4998 } else { /* one of "-=+?" */
4999 /* Standard-mandated substitution ops:
5000 * ${var?word} - indicate error if unset
5001 * If var is unset, word (or a message indicating it is unset
5002 * if word is null) is written to standard error
5003 * and the shell exits with a non-zero exit status.
5004 * Otherwise, the value of var is substituted.
5005 * ${var-word} - use default value
5006 * If var is unset, word is substituted.
5007 * ${var=word} - assign and use default value
5008 * If var is unset, word is assigned to var.
5009 * In all cases, final value of var is substituted.
5010 * ${var+word} - use alternative value
5011 * If var is unset, null is substituted.
5012 * Otherwise, word is substituted.
5014 * Word is subjected to tilde expansion, parameter expansion,
5015 * command substitution, and arithmetic expansion.
5016 * If word is not needed, it is not expanded.
5018 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5019 * but also treat null var as if it is unset.
5021 int use_word = (!val || ((exp_save == ':') && !val[0]));
5023 use_word = !use_word;
5024 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5025 (exp_save == ':') ? "true" : "false", use_word);
5027 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5029 exp_word = to_be_freed;
5030 if (exp_op == '?') {
5031 /* mimic bash message */
5032 die_if_script("%s: %s",
5034 exp_word[0] ? exp_word : "parameter null or not set"
5036 //TODO: how interactive bash aborts expansion mid-command?
5041 if (exp_op == '=') {
5042 /* ${var=[word]} or ${var:=[word]} */
5043 if (isdigit(var[0]) || var[0] == '#') {
5044 /* mimic bash message */
5045 die_if_script("$%s: cannot assign in this way", var);
5048 char *new_var = xasprintf("%s=%s", var, val);
5049 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5053 } /* one of "-=+?" */
5055 *exp_saveptr = exp_save;
5061 *to_be_freed_pp = to_be_freed;
5065 /* Expand all variable references in given string, adding words to list[]
5066 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5067 * to be filled). This routine is extremely tricky: has to deal with
5068 * variables/parameters with whitespace, $* and $@, and constructs like
5069 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5070 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5072 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5073 * expansion of right-hand side of assignment == 1-element expand.
5075 char cant_be_null = 0; /* only bit 0x80 matters */
5078 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5079 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5080 debug_print_list("expand_vars_to_list", output, n);
5081 n = o_save_ptr(output, n);
5082 debug_print_list("expand_vars_to_list[0]", output, n);
5084 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5086 char *to_be_freed = NULL;
5087 const char *val = NULL;
5088 #if ENABLE_HUSH_TICK
5089 o_string subst_result = NULL_O_STRING;
5091 #if ENABLE_SH_MATH_SUPPORT
5092 char arith_buf[sizeof(arith_t)*3 + 2];
5094 o_addblock(output, arg, p - arg);
5095 debug_print_list("expand_vars_to_list[1]", output, n);
5097 p = strchr(p, SPECIAL_VAR_SYMBOL);
5099 /* Fetch special var name (if it is indeed one of them)
5100 * and quote bit, force the bit on if singleword expansion -
5101 * important for not getting v=$@ expand to many words. */
5102 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5104 /* Is this variable quoted and thus expansion can't be null?
5105 * "$@" is special. Even if quoted, it can still
5106 * expand to nothing (not even an empty string),
5107 * thus it is excluded. */
5108 if ((first_ch & 0x7f) != '@')
5109 cant_be_null |= first_ch;
5111 switch (first_ch & 0x7f) {
5112 /* Highest bit in first_ch indicates that var is double-quoted */
5116 if (!G.global_argv[1])
5119 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5120 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5121 while (G.global_argv[i]) {
5122 n = expand_on_ifs(output, n, G.global_argv[i]);
5123 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5124 if (G.global_argv[i++][0] && G.global_argv[i]) {
5125 /* this argv[] is not empty and not last:
5126 * put terminating NUL, start new word */
5127 o_addchr(output, '\0');
5128 debug_print_list("expand_vars_to_list[2]", output, n);
5129 n = o_save_ptr(output, n);
5130 debug_print_list("expand_vars_to_list[3]", output, n);
5134 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5135 * and in this case should treat it like '$*' - see 'else...' below */
5136 if (first_ch == ('@'|0x80) /* quoted $@ */
5137 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5140 o_addQstr(output, G.global_argv[i]);
5141 if (++i >= G.global_argc)
5143 o_addchr(output, '\0');
5144 debug_print_list("expand_vars_to_list[4]", output, n);
5145 n = o_save_ptr(output, n);
5147 } else { /* quoted $* (or v="$@" case): add as one word */
5149 o_addQstr(output, G.global_argv[i]);
5150 if (!G.global_argv[++i])
5153 o_addchr(output, G.ifs[0]);
5158 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5159 /* "Empty variable", used to make "" etc to not disappear */
5161 cant_be_null = 0x80;
5163 #if ENABLE_HUSH_TICK
5164 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5165 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5167 /* Can't just stuff it into output o_string,
5168 * expanded result may need to be globbed
5169 * and $IFS-splitted */
5170 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5171 G.last_exitcode = process_command_subs(&subst_result, arg);
5172 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5173 val = subst_result.data;
5176 #if ENABLE_SH_MATH_SUPPORT
5177 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5180 arg++; /* skip '+' */
5181 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5182 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5183 res = expand_and_evaluate_arith(arg, NULL);
5184 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5185 sprintf(arith_buf, ARITH_FMT, res);
5191 val = expand_one_var(&to_be_freed, arg, &p);
5192 IF_HUSH_TICK(store_val:)
5193 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5194 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5195 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5196 if (val && val[0]) {
5197 n = expand_on_ifs(output, n, val);
5200 } else { /* quoted $VAR, val will be appended below */
5201 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5202 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5206 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5208 if (val && val[0]) {
5209 o_addQstr(output, val);
5213 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5214 * Do the check to avoid writing to a const string. */
5215 if (*p != SPECIAL_VAR_SYMBOL)
5216 *p = SPECIAL_VAR_SYMBOL;
5218 #if ENABLE_HUSH_TICK
5219 o_free(&subst_result);
5222 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5225 debug_print_list("expand_vars_to_list[a]", output, n);
5226 /* this part is literal, and it was already pre-quoted
5227 * if needed (much earlier), do not use o_addQstr here! */
5228 o_addstr_with_NUL(output, arg);
5229 debug_print_list("expand_vars_to_list[b]", output, n);
5230 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5231 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5234 /* allow to reuse list[n] later without re-growth */
5235 output->has_empty_slot = 1;
5237 o_addchr(output, '\0');
5243 static char **expand_variables(char **argv, unsigned expflags)
5247 o_string output = NULL_O_STRING;
5249 output.o_expflags = expflags;
5253 n = expand_vars_to_list(&output, n, *argv);
5256 debug_print_list("expand_variables", &output, n);
5258 /* output.data (malloced in one block) gets returned in "list" */
5259 list = o_finalize_list(&output, n);
5260 debug_print_strings("expand_variables[1]", list);
5264 static char **expand_strvec_to_strvec(char **argv)
5266 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5269 #if ENABLE_HUSH_BASH_COMPAT
5270 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5272 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5276 /* Used for expansion of right hand of assignments,
5277 * $((...)), heredocs, variable espansion parts.
5279 * NB: should NOT do globbing!
5280 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5282 static char *expand_string_to_string(const char *str, int do_unbackslash)
5284 #if !ENABLE_HUSH_BASH_COMPAT
5285 const int do_unbackslash = 1;
5287 char *argv[2], **list;
5289 debug_printf_expand("string_to_string<='%s'\n", str);
5290 /* This is generally an optimization, but it also
5291 * handles "", which otherwise trips over !list[0] check below.
5292 * (is this ever happens that we actually get str="" here?)
5294 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5295 //TODO: Can use on strings with \ too, just unbackslash() them?
5296 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5297 return xstrdup(str);
5300 argv[0] = (char*)str;
5302 list = expand_variables(argv, do_unbackslash
5303 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5304 : EXP_FLAG_SINGLEWORD
5307 if (!list[0] || list[1])
5308 bb_error_msg_and_die("BUG in varexp2");
5309 /* actually, just move string 2*sizeof(char*) bytes back */
5310 overlapping_strcpy((char*)list, list[0]);
5312 unbackslash((char*)list);
5313 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5317 /* Used for "eval" builtin */
5318 static char* expand_strvec_to_string(char **argv)
5322 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5323 /* Convert all NULs to spaces */
5328 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5329 bb_error_msg_and_die("BUG in varexp3");
5330 /* bash uses ' ' regardless of $IFS contents */
5335 overlapping_strcpy((char*)list, list[0]);
5336 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5340 static char **expand_assignments(char **argv, int count)
5345 G.expanded_assignments = p = NULL;
5346 /* Expand assignments into one string each */
5347 for (i = 0; i < count; i++) {
5348 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5350 G.expanded_assignments = NULL;
5357 void re_execute_shell(char ***to_free, const char *s,
5358 char *g_argv0, char **g_argv,
5359 char **builtin_argv) NORETURN;
5361 static void reset_traps_to_defaults(void)
5363 /* This function is always called in a child shell
5364 * after fork (not vfork, NOMMU doesn't use this function).
5369 /* Child shells are not interactive.
5370 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5371 * Testcase: (while :; do :; done) + ^Z should background.
5372 * Same goes for SIGTERM, SIGHUP, SIGINT.
5374 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5375 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5377 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5378 * Stupid. It can be done with *single* &= op, but we can't use
5379 * the fact that G.blocked_set is implemented as a bitmask
5381 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5385 /* Careful. Only if no trap or trap is not "" */
5386 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5387 sigdelset(&G.blocked_set, sig);
5394 /* Our homegrown sig mask is saner to work with :) */
5395 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5397 /* Resetting all traps to default except empty ones */
5398 mask = G.non_DFL_mask;
5399 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5400 if (!G.traps[sig] || !G.traps[sig][0])
5403 G.traps[sig] = NULL;
5404 /* There is no signal for 0 (EXIT) */
5407 /* There was a trap handler, we just removed it.
5408 * But if sig still has non-DFL handling,
5409 * we should not unblock the sig. */
5412 sigdelset(&G.blocked_set, sig);
5414 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5419 static void re_execute_shell(char ***to_free, const char *s,
5420 char *g_argv0, char **g_argv,
5421 char **builtin_argv) NORETURN;
5422 static void re_execute_shell(char ***to_free, const char *s,
5423 char *g_argv0, char **g_argv,
5424 char **builtin_argv)
5426 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5427 /* delims + 2 * (number of bytes in printed hex numbers) */
5428 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5429 char *heredoc_argv[4];
5430 struct variable *cur;
5431 # if ENABLE_HUSH_FUNCTIONS
5432 struct function *funcp;
5436 unsigned long long empty_trap_mask;
5438 if (!g_argv0) { /* heredoc */
5439 argv = heredoc_argv;
5440 argv[0] = (char *) G.argv0_for_re_execing;
5441 argv[1] = (char *) "-<";
5442 argv[2] = (char *) s;
5444 pp = &argv[3]; /* used as pointer to empty environment */
5450 if (pp) while (*pp++)
5453 empty_trap_mask = 0;
5456 for (sig = 1; sig < NSIG; sig++) {
5457 if (G.traps[sig] && !G.traps[sig][0])
5458 empty_trap_mask |= 1LL << sig;
5462 sprintf(param_buf, NOMMU_HACK_FMT
5463 , (unsigned) G.root_pid
5464 , (unsigned) G.root_ppid
5465 , (unsigned) G.last_bg_pid
5466 , (unsigned) G.last_exitcode
5469 IF_HUSH_LOOPS(, G.depth_of_loop)
5471 # undef NOMMU_HACK_FMT
5472 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5473 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5476 for (cur = G.top_var; cur; cur = cur->next) {
5477 if (!cur->flg_export || cur->flg_read_only)
5480 # if ENABLE_HUSH_FUNCTIONS
5481 for (funcp = G.top_func; funcp; funcp = funcp->next)
5487 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5488 *pp++ = (char *) G.argv0_for_re_execing;
5490 for (cur = G.top_var; cur; cur = cur->next) {
5491 if (strcmp(cur->varstr, hush_version_str) == 0)
5493 if (cur->flg_read_only) {
5494 *pp++ = (char *) "-R";
5495 *pp++ = cur->varstr;
5496 } else if (!cur->flg_export) {
5497 *pp++ = (char *) "-V";
5498 *pp++ = cur->varstr;
5501 # if ENABLE_HUSH_FUNCTIONS
5502 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5503 *pp++ = (char *) "-F";
5504 *pp++ = funcp->name;
5505 *pp++ = funcp->body_as_string;
5508 /* We can pass activated traps here. Say, -Tnn:trap_string
5510 * However, POSIX says that subshells reset signals with traps
5512 * I tested bash-3.2 and it not only does that with true subshells
5513 * of the form ( list ), but with any forked children shells.
5514 * I set trap "echo W" WINCH; and then tried:
5516 * { echo 1; sleep 20; echo 2; } &
5517 * while true; do echo 1; sleep 20; echo 2; break; done &
5518 * true | { echo 1; sleep 20; echo 2; } | cat
5520 * In all these cases sending SIGWINCH to the child shell
5521 * did not run the trap. If I add trap "echo V" WINCH;
5522 * _inside_ group (just before echo 1), it works.
5524 * I conclude it means we don't need to pass active traps here.
5525 * Even if we would use signal handlers instead of signal masking
5526 * in order to implement trap handling,
5527 * exec syscall below resets signals to SIG_DFL for us.
5529 *pp++ = (char *) "-c";
5532 while (*++builtin_argv)
5533 *pp++ = *builtin_argv;
5534 *pp++ = (char *) "";
5539 /* *pp = NULL; - is already there */
5543 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5544 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5545 execve(bb_busybox_exec_path, argv, pp);
5546 /* Fallback. Useful for init=/bin/hush usage etc */
5547 if (argv[0][0] == '/')
5548 execve(argv[0], argv, pp);
5549 xfunc_error_retval = 127;
5550 bb_error_msg_and_die("can't re-execute the shell");
5552 #endif /* !BB_MMU */
5555 static int run_and_free_list(struct pipe *pi);
5557 /* Executing from string: eval, sh -c '...'
5558 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5559 * end_trigger controls how often we stop parsing
5560 * NUL: parse all, execute, return
5561 * ';': parse till ';' or newline, execute, repeat till EOF
5563 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5565 /* Why we need empty flag?
5566 * An obscure corner case "false; ``; echo $?":
5567 * empty command in `` should still set $? to 0.
5568 * But we can't just set $? to 0 at the start,
5569 * this breaks "false; echo `echo $?`" case.
5573 struct pipe *pipe_list;
5575 #if ENABLE_HUSH_INTERACTIVE
5576 if (end_trigger == ';')
5577 inp->promptmode = 0; /* PS1 */
5579 pipe_list = parse_stream(NULL, inp, end_trigger);
5580 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5581 /* If we are in "big" script
5582 * (not in `cmd` or something similar)...
5584 if (pipe_list == ERR_PTR && end_trigger == ';') {
5585 /* Discard cached input (rest of line) */
5586 int ch = inp->last_char;
5587 while (ch != EOF && ch != '\n') {
5588 //bb_error_msg("Discarded:'%c'", ch);
5593 /* This stream isn't empty */
5597 if (!pipe_list && empty)
5598 G.last_exitcode = 0;
5601 debug_print_tree(pipe_list, 0);
5602 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5603 run_and_free_list(pipe_list);
5605 #if ENABLE_HUSH_FUNCTIONS
5606 if (G.flag_return_in_progress == 1)
5612 static void parse_and_run_string(const char *s)
5614 struct in_str input;
5615 setup_string_in_str(&input, s);
5616 parse_and_run_stream(&input, '\0');
5619 static void parse_and_run_file(FILE *f)
5621 struct in_str input;
5622 setup_file_in_str(&input, f);
5623 parse_and_run_stream(&input, ';');
5626 #if ENABLE_HUSH_TICK
5627 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5632 char **to_free = NULL;
5636 pid = BB_MMU ? xfork() : xvfork();
5637 if (pid == 0) { /* child */
5638 disable_restore_tty_pgrp_on_exit();
5639 /* Process substitution is not considered to be usual
5640 * 'command execution'.
5641 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5648 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5649 close(channel[0]); /* NB: close _first_, then move fd! */
5650 xmove_fd(channel[1], 1);
5651 /* Prevent it from trying to handle ctrl-z etc */
5652 IF_HUSH_JOB(G.run_list_level = 1;)
5653 /* Awful hack for `trap` or $(trap).
5655 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5656 * contains an example where "trap" is executed in a subshell:
5658 * save_traps=$(trap)
5660 * eval "$save_traps"
5662 * Standard does not say that "trap" in subshell shall print
5663 * parent shell's traps. It only says that its output
5664 * must have suitable form, but then, in the above example
5665 * (which is not supposed to be normative), it implies that.
5667 * bash (and probably other shell) does implement it
5668 * (traps are reset to defaults, but "trap" still shows them),
5669 * but as a result, "trap" logic is hopelessly messed up:
5672 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5673 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5674 * # true | trap <--- trap is in subshell - no output (ditto)
5675 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5676 * trap -- 'echo Ho' SIGWINCH
5677 * # echo `(trap)` <--- in subshell in subshell - output
5678 * trap -- 'echo Ho' SIGWINCH
5679 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5680 * trap -- 'echo Ho' SIGWINCH
5682 * The rules when to forget and when to not forget traps
5683 * get really complex and nonsensical.
5685 * Our solution: ONLY bare $(trap) or `trap` is special.
5687 s = skip_whitespace(s);
5688 if (strncmp(s, "trap", 4) == 0
5689 && skip_whitespace(s + 4)[0] == '\0'
5691 static const char *const argv[] = { NULL, NULL };
5692 builtin_trap((char**)argv);
5693 exit(0); /* not _exit() - we need to fflush */
5696 reset_traps_to_defaults();
5697 parse_and_run_string(s);
5698 _exit(G.last_exitcode);
5700 /* We re-execute after vfork on NOMMU. This makes this script safe:
5701 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5702 * huge=`cat BIG` # was blocking here forever
5705 re_execute_shell(&to_free,
5715 # if ENABLE_HUSH_FAST
5717 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5718 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5719 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5721 enable_restore_tty_pgrp_on_exit();
5726 close_on_exec_on(channel[0]);
5727 return xfdopen_for_read(channel[0]);
5730 /* Return code is exit status of the process that is run. */
5731 static int process_command_subs(o_string *dest, const char *s)
5734 struct in_str pipe_str;
5736 int status, ch, eol_cnt;
5738 fp = generate_stream_from_string(s, &pid);
5740 /* Now send results of command back into original context */
5741 setup_file_in_str(&pipe_str, fp);
5743 while ((ch = i_getch(&pipe_str)) != EOF) {
5749 o_addchr(dest, '\n');
5752 o_addQchr(dest, ch);
5755 debug_printf("done reading from `cmd` pipe, closing it\n");
5757 /* We need to extract exitcode. Test case
5758 * "true; echo `sleep 1; false` $?"
5760 safe_waitpid(pid, &status, 0);
5761 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5762 return WEXITSTATUS(status);
5764 #endif /* ENABLE_HUSH_TICK */
5767 static void setup_heredoc(struct redir_struct *redir)
5769 struct fd_pair pair;
5772 /* the _body_ of heredoc (misleading field name) */
5773 const char *heredoc = redir->rd_filename;
5780 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5781 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5785 len = strlen(heredoc);
5787 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5789 xmove_fd(pair.rd, redir->rd_fd);
5791 /* Try writing without forking. Newer kernels have
5792 * dynamically growing pipes. Must use non-blocking write! */
5795 written = write(pair.wr, heredoc, len);
5806 ndelay_off(pair.wr);
5808 /* Okay, pipe buffer was not big enough */
5809 /* Note: we must not create a stray child (bastard? :)
5810 * for the unsuspecting parent process. Child creates a grandchild
5811 * and exits before parent execs the process which consumes heredoc
5812 * (that exec happens after we return from this function) */
5819 disable_restore_tty_pgrp_on_exit();
5820 pid = BB_MMU ? xfork() : xvfork();
5824 close(redir->rd_fd); /* read side of the pipe */
5826 full_write(pair.wr, heredoc, len); /* may loop or block */
5829 /* Delegate blocking writes to another process */
5830 xmove_fd(pair.wr, STDOUT_FILENO);
5831 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5835 #if ENABLE_HUSH_FAST
5837 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5839 enable_restore_tty_pgrp_on_exit();
5845 wait(NULL); /* wait till child has died */
5848 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5849 * and stderr if they are redirected. */
5850 static int setup_redirects(struct command *prog, int squirrel[])
5853 struct redir_struct *redir;
5855 for (redir = prog->redirects; redir; redir = redir->next) {
5856 if (redir->rd_type == REDIRECT_HEREDOC2) {
5857 /* rd_fd<<HERE case */
5858 if (squirrel && redir->rd_fd < 3
5859 && squirrel[redir->rd_fd] < 0
5861 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5863 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5865 debug_printf_parse("set heredoc '%s'\n",
5866 redir->rd_filename);
5867 setup_heredoc(redir);
5871 if (redir->rd_dup == REDIRFD_TO_FILE) {
5872 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5874 if (redir->rd_filename == NULL) {
5875 /* Something went wrong in the parse.
5876 * Pretend it didn't happen */
5877 bb_error_msg("bug in redirect parse");
5880 mode = redir_table[redir->rd_type].mode;
5881 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5882 openfd = open_or_warn(p, mode);
5885 /* this could get lost if stderr has been redirected, but
5886 * bash and ash both lose it as well (though zsh doesn't!) */
5887 //what the above comment tries to say?
5891 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5892 openfd = redir->rd_dup;
5895 if (openfd != redir->rd_fd) {
5896 if (squirrel && redir->rd_fd < 3
5897 && squirrel[redir->rd_fd] < 0
5899 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5901 if (openfd == REDIRFD_CLOSE) {
5902 /* "n>-" means "close me" */
5903 close(redir->rd_fd);
5905 xdup2(openfd, redir->rd_fd);
5906 if (redir->rd_dup == REDIRFD_TO_FILE)
5914 static void restore_redirects(int squirrel[])
5917 for (i = 0; i < 3; i++) {
5920 /* We simply die on error */
5926 static char *find_in_path(const char *arg)
5929 const char *PATH = get_local_var_value("PATH");
5935 const char *end = strchrnul(PATH, ':');
5936 int sz = end - PATH; /* must be int! */
5940 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5942 /* We have xxx::yyyy in $PATH,
5943 * it means "use current dir" */
5946 if (access(ret, F_OK) == 0)
5959 static const struct built_in_command *find_builtin_helper(const char *name,
5960 const struct built_in_command *x,
5961 const struct built_in_command *end)
5964 if (strcmp(name, x->b_cmd) != 0) {
5968 debug_printf_exec("found builtin '%s'\n", name);
5973 static const struct built_in_command *find_builtin1(const char *name)
5975 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5977 static const struct built_in_command *find_builtin(const char *name)
5979 const struct built_in_command *x = find_builtin1(name);
5982 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5985 #if ENABLE_HUSH_FUNCTIONS
5986 static struct function **find_function_slot(const char *name)
5988 struct function **funcpp = &G.top_func;
5990 if (strcmp(name, (*funcpp)->name) == 0) {
5993 funcpp = &(*funcpp)->next;
5998 static const struct function *find_function(const char *name)
6000 const struct function *funcp = *find_function_slot(name);
6002 debug_printf_exec("found function '%s'\n", name);
6006 /* Note: takes ownership on name ptr */
6007 static struct function *new_function(char *name)
6009 struct function **funcpp = find_function_slot(name);
6010 struct function *funcp = *funcpp;
6012 if (funcp != NULL) {
6013 struct command *cmd = funcp->parent_cmd;
6014 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6016 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6018 /* Note: if !funcp->body, do not free body_as_string!
6019 * This is a special case of "-F name body" function:
6020 * body_as_string was not malloced! */
6022 free_pipe_list(funcp->body);
6024 free(funcp->body_as_string);
6028 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6029 cmd->argv[0] = funcp->name;
6030 cmd->group = funcp->body;
6032 cmd->group_as_string = funcp->body_as_string;
6036 debug_printf_exec("remembering new function '%s'\n", name);
6037 funcp = *funcpp = xzalloc(sizeof(*funcp));
6038 /*funcp->next = NULL;*/
6045 static void unset_func(const char *name)
6047 struct function **funcpp = find_function_slot(name);
6048 struct function *funcp = *funcpp;
6050 if (funcp != NULL) {
6051 debug_printf_exec("freeing function '%s'\n", funcp->name);
6052 *funcpp = funcp->next;
6053 /* funcp is unlinked now, deleting it.
6054 * Note: if !funcp->body, the function was created by
6055 * "-F name body", do not free ->body_as_string
6056 * and ->name as they were not malloced. */
6058 free_pipe_list(funcp->body);
6061 free(funcp->body_as_string);
6069 #define exec_function(to_free, funcp, argv) \
6070 exec_function(funcp, argv)
6072 static void exec_function(char ***to_free,
6073 const struct function *funcp,
6074 char **argv) NORETURN;
6075 static void exec_function(char ***to_free,
6076 const struct function *funcp,
6082 argv[0] = G.global_argv[0];
6083 G.global_argv = argv;
6087 /* On MMU, funcp->body is always non-NULL */
6088 n = run_list(funcp->body);
6092 re_execute_shell(to_free,
6093 funcp->body_as_string,
6100 static int run_function(const struct function *funcp, char **argv)
6106 save_and_replace_G_args(&sv, argv);
6108 /* "we are in function, ok to use return" */
6109 sv_flg = G.flag_return_in_progress;
6110 G.flag_return_in_progress = -1;
6111 # if ENABLE_HUSH_LOCAL
6112 G.func_nest_level++;
6115 /* On MMU, funcp->body is always non-NULL */
6118 /* Function defined by -F */
6119 parse_and_run_string(funcp->body_as_string);
6120 rc = G.last_exitcode;
6124 rc = run_list(funcp->body);
6127 # if ENABLE_HUSH_LOCAL
6129 struct variable *var;
6130 struct variable **var_pp;
6132 var_pp = &G.top_var;
6133 while ((var = *var_pp) != NULL) {
6134 if (var->func_nest_level < G.func_nest_level) {
6135 var_pp = &var->next;
6139 if (var->flg_export)
6140 bb_unsetenv(var->varstr);
6141 /* Remove from global list */
6142 *var_pp = var->next;
6148 G.func_nest_level--;
6151 G.flag_return_in_progress = sv_flg;
6153 restore_G_args(&sv, argv);
6157 #endif /* ENABLE_HUSH_FUNCTIONS */
6161 #define exec_builtin(to_free, x, argv) \
6162 exec_builtin(x, argv)
6164 #define exec_builtin(to_free, x, argv) \
6165 exec_builtin(to_free, argv)
6167 static void exec_builtin(char ***to_free,
6168 const struct built_in_command *x,
6169 char **argv) NORETURN;
6170 static void exec_builtin(char ***to_free,
6171 const struct built_in_command *x,
6177 rcode = x->b_function(argv);
6182 /* On NOMMU, we must never block!
6183 * Example: { sleep 99 | read line; } & echo Ok
6185 re_execute_shell(to_free,
6194 static void execvp_or_die(char **argv) NORETURN;
6195 static void execvp_or_die(char **argv)
6197 debug_printf_exec("execing '%s'\n", argv[0]);
6198 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6199 execvp(argv[0], argv);
6200 bb_perror_msg("can't execute '%s'", argv[0]);
6201 _exit(127); /* bash compat */
6204 #if ENABLE_HUSH_MODE_X
6205 static void dump_cmd_in_x_mode(char **argv)
6207 if (G_x_mode && argv) {
6208 /* We want to output the line in one write op */
6216 len += strlen(argv[n++]) + 1;
6222 p += sprintf(p, " %s", argv[n++]);
6230 # define dump_cmd_in_x_mode(argv) ((void)0)
6234 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6235 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6236 #define pseudo_exec(nommu_save, command, argv_expanded) \
6237 pseudo_exec(command, argv_expanded)
6240 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6242 * Don't exit() here. If you don't exec, use _exit instead.
6243 * The at_exit handlers apparently confuse the calling process,
6244 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6245 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6246 char **argv, int assignment_cnt,
6247 char **argv_expanded) NORETURN;
6248 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6249 char **argv, int assignment_cnt,
6250 char **argv_expanded)
6254 new_env = expand_assignments(argv, assignment_cnt);
6255 dump_cmd_in_x_mode(new_env);
6257 if (!argv[assignment_cnt]) {
6258 /* Case when we are here: ... | var=val | ...
6259 * (note that we do not exit early, i.e., do not optimize out
6260 * expand_assignments(): think about ... | var=`sleep 1` | ...
6262 free_strings(new_env);
6263 _exit(EXIT_SUCCESS);
6267 set_vars_and_save_old(new_env);
6268 free(new_env); /* optional */
6269 /* we can also destroy set_vars_and_save_old's return value,
6272 nommu_save->new_env = new_env;
6273 nommu_save->old_vars = set_vars_and_save_old(new_env);
6276 if (argv_expanded) {
6277 argv = argv_expanded;
6279 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6281 nommu_save->argv = argv;
6284 dump_cmd_in_x_mode(argv);
6286 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6287 if (strchr(argv[0], '/') != NULL)
6291 /* Check if the command matches any of the builtins.
6292 * Depending on context, this might be redundant. But it's
6293 * easier to waste a few CPU cycles than it is to figure out
6294 * if this is one of those cases.
6297 /* On NOMMU, it is more expensive to re-execute shell
6298 * just in order to run echo or test builtin.
6299 * It's better to skip it here and run corresponding
6300 * non-builtin later. */
6301 const struct built_in_command *x;
6302 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6304 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6307 #if ENABLE_HUSH_FUNCTIONS
6308 /* Check if the command matches any functions */
6310 const struct function *funcp = find_function(argv[0]);
6312 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6317 #if ENABLE_FEATURE_SH_STANDALONE
6318 /* Check if the command matches any busybox applets */
6320 int a = find_applet_by_name(argv[0]);
6322 # if BB_MMU /* see above why on NOMMU it is not allowed */
6323 if (APPLET_IS_NOEXEC(a)) {
6324 debug_printf_exec("running applet '%s'\n", argv[0]);
6325 run_applet_no_and_exit(a, argv);
6328 /* Re-exec ourselves */
6329 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6330 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6331 execv(bb_busybox_exec_path, argv);
6332 /* If they called chroot or otherwise made the binary no longer
6333 * executable, fall through */
6338 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6341 execvp_or_die(argv);
6344 /* Called after [v]fork() in run_pipe
6346 static void pseudo_exec(nommu_save_t *nommu_save,
6347 struct command *command,
6348 char **argv_expanded) NORETURN;
6349 static void pseudo_exec(nommu_save_t *nommu_save,
6350 struct command *command,
6351 char **argv_expanded)
6353 if (command->argv) {
6354 pseudo_exec_argv(nommu_save, command->argv,
6355 command->assignment_cnt, argv_expanded);
6358 if (command->group) {
6359 /* Cases when we are here:
6362 * ... | ( list ) | ...
6363 * ... | { list } | ...
6367 debug_printf_exec("pseudo_exec: run_list\n");
6368 reset_traps_to_defaults();
6369 rcode = run_list(command->group);
6370 /* OK to leak memory by not calling free_pipe_list,
6371 * since this process is about to exit */
6374 re_execute_shell(&nommu_save->argv_from_re_execing,
6375 command->group_as_string,
6382 /* Case when we are here: ... | >file */
6383 debug_printf_exec("pseudo_exec'ed null command\n");
6384 _exit(EXIT_SUCCESS);
6388 static const char *get_cmdtext(struct pipe *pi)
6394 /* This is subtle. ->cmdtext is created only on first backgrounding.
6395 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6396 * On subsequent bg argv is trashed, but we won't use it */
6399 argv = pi->cmds[0].argv;
6400 if (!argv || !argv[0]) {
6401 pi->cmdtext = xzalloc(1);
6407 len += strlen(*argv) + 1;
6411 argv = pi->cmds[0].argv;
6413 len = strlen(*argv);
6414 memcpy(p, *argv, len);
6422 static void insert_bg_job(struct pipe *pi)
6424 struct pipe *job, **jobp;
6427 /* Linear search for the ID of the job to use */
6429 for (job = G.job_list; job; job = job->next)
6430 if (job->jobid >= pi->jobid)
6431 pi->jobid = job->jobid + 1;
6433 /* Add job to the list of running jobs */
6435 while ((job = *jobp) != NULL)
6437 job = *jobp = xmalloc(sizeof(*job));
6439 *job = *pi; /* physical copy */
6441 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6442 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6443 for (i = 0; i < pi->num_cmds; i++) {
6444 job->cmds[i].pid = pi->cmds[i].pid;
6445 /* all other fields are not used and stay zero */
6447 job->cmdtext = xstrdup(get_cmdtext(pi));
6449 if (G_interactive_fd)
6450 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6451 G.last_jobid = job->jobid;
6454 static void remove_bg_job(struct pipe *pi)
6456 struct pipe *prev_pipe;
6458 if (pi == G.job_list) {
6459 G.job_list = pi->next;
6461 prev_pipe = G.job_list;
6462 while (prev_pipe->next != pi)
6463 prev_pipe = prev_pipe->next;
6464 prev_pipe->next = pi->next;
6467 G.last_jobid = G.job_list->jobid;
6472 /* Remove a backgrounded job */
6473 static void delete_finished_bg_job(struct pipe *pi)
6480 /* Check to see if any processes have exited -- if they
6481 * have, figure out why and see if a job has completed */
6482 static int checkjobs(struct pipe *fg_pipe)
6492 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6494 attributes = WUNTRACED;
6495 if (fg_pipe == NULL)
6496 attributes |= WNOHANG;
6499 #if ENABLE_HUSH_FAST
6500 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6501 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6502 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6503 /* There was neither fork nor SIGCHLD since last waitpid */
6504 /* Avoid doing waitpid syscall if possible */
6505 if (!G.we_have_children) {
6509 if (fg_pipe == NULL) { /* is WNOHANG set? */
6510 /* We have children, but they did not exit
6511 * or stop yet (we saw no SIGCHLD) */
6514 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6518 /* Do we do this right?
6519 * bash-3.00# sleep 20 | false
6521 * [3]+ Stopped sleep 20 | false
6522 * bash-3.00# echo $?
6523 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6524 * [hush 1.14.0: yes we do it right]
6531 #if ENABLE_HUSH_FAST
6532 i = G.count_SIGCHLD;
6534 childpid = waitpid(-1, &status, attributes);
6535 if (childpid <= 0) {
6536 if (childpid && errno != ECHILD)
6537 bb_perror_msg("waitpid");
6538 #if ENABLE_HUSH_FAST
6539 else { /* Until next SIGCHLD, waitpid's are useless */
6540 G.we_have_children = (childpid == 0);
6541 G.handled_SIGCHLD = i;
6542 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6547 dead = WIFEXITED(status) || WIFSIGNALED(status);
6550 if (WIFSTOPPED(status))
6551 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6552 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6553 if (WIFSIGNALED(status))
6554 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6555 childpid, WTERMSIG(status), WEXITSTATUS(status));
6556 if (WIFEXITED(status))
6557 debug_printf_jobs("pid %d exited, exitcode %d\n",
6558 childpid, WEXITSTATUS(status));
6560 /* Were we asked to wait for fg pipe? */
6562 i = fg_pipe->num_cmds;
6564 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6565 if (fg_pipe->cmds[i].pid != childpid)
6569 fg_pipe->cmds[i].pid = 0;
6570 fg_pipe->alive_cmds--;
6571 ex = WEXITSTATUS(status);
6572 /* bash prints killer signal's name for *last*
6573 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6574 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6576 if (WIFSIGNALED(status)) {
6577 int sig = WTERMSIG(status);
6578 if (i == fg_pipe->num_cmds-1)
6579 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6580 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6581 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6582 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6583 * Maybe we need to use sig | 128? */
6586 fg_pipe->cmds[i].cmd_exitcode = ex;
6588 fg_pipe->cmds[i].is_stopped = 1;
6589 fg_pipe->stopped_cmds++;
6591 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6592 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6593 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6594 /* All processes in fg pipe have exited or stopped */
6595 i = fg_pipe->num_cmds;
6597 rcode = fg_pipe->cmds[i].cmd_exitcode;
6598 /* usually last process gives overall exitstatus,
6599 * but with "set -o pipefail", last *failed* process does */
6600 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6603 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6604 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6605 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6606 * and "killall -STOP cat" */
6607 if (G_interactive_fd) {
6609 if (fg_pipe->alive_cmds != 0)
6610 insert_bg_job(fg_pipe);
6614 if (fg_pipe->alive_cmds == 0)
6617 /* There are still running processes in the fg pipe */
6618 goto wait_more; /* do waitpid again */
6620 /* it wasnt fg_pipe, look for process in bg pipes */
6624 /* We asked to wait for bg or orphaned children */
6625 /* No need to remember exitcode in this case */
6626 for (pi = G.job_list; pi; pi = pi->next) {
6627 for (i = 0; i < pi->num_cmds; i++) {
6628 if (pi->cmds[i].pid == childpid)
6629 goto found_pi_and_prognum;
6632 /* Happens when shell is used as init process (init=/bin/sh) */
6633 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6634 continue; /* do waitpid again */
6636 found_pi_and_prognum:
6639 pi->cmds[i].pid = 0;
6641 if (!pi->alive_cmds) {
6642 if (G_interactive_fd)
6643 printf(JOB_STATUS_FORMAT, pi->jobid,
6644 "Done", pi->cmdtext);
6645 delete_finished_bg_job(pi);
6649 pi->cmds[i].is_stopped = 1;
6653 } /* while (waitpid succeeds)... */
6659 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6662 int rcode = checkjobs(fg_pipe);
6663 if (G_saved_tty_pgrp) {
6664 /* Job finished, move the shell to the foreground */
6665 p = getpgrp(); /* our process group id */
6666 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6667 tcsetpgrp(G_interactive_fd, p);
6673 /* Start all the jobs, but don't wait for anything to finish.
6676 * Return code is normally -1, when the caller has to wait for children
6677 * to finish to determine the exit status of the pipe. If the pipe
6678 * is a simple builtin command, however, the action is done by the
6679 * time run_pipe returns, and the exit code is provided as the
6682 * Returns -1 only if started some children. IOW: we have to
6683 * mask out retvals of builtins etc with 0xff!
6685 * The only case when we do not need to [v]fork is when the pipe
6686 * is single, non-backgrounded, non-subshell command. Examples:
6687 * cmd ; ... { list } ; ...
6688 * cmd && ... { list } && ...
6689 * cmd || ... { list } || ...
6690 * If it is, then we can run cmd as a builtin, NOFORK,
6691 * or (if SH_STANDALONE) an applet, and we can run the { list }
6692 * with run_list. If it isn't one of these, we fork and exec cmd.
6694 * Cases when we must fork:
6695 * non-single: cmd | cmd
6696 * backgrounded: cmd & { list } &
6697 * subshell: ( list ) [&]
6699 #if !ENABLE_HUSH_MODE_X
6700 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6701 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6703 static int redirect_and_varexp_helper(char ***new_env_p,
6704 struct variable **old_vars_p,
6705 struct command *command,
6707 char **argv_expanded)
6709 /* setup_redirects acts on file descriptors, not FILEs.
6710 * This is perfect for work that comes after exec().
6711 * Is it really safe for inline use? Experimentally,
6712 * things seem to work. */
6713 int rcode = setup_redirects(command, squirrel);
6715 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6716 *new_env_p = new_env;
6717 dump_cmd_in_x_mode(new_env);
6718 dump_cmd_in_x_mode(argv_expanded);
6720 *old_vars_p = set_vars_and_save_old(new_env);
6724 static NOINLINE int run_pipe(struct pipe *pi)
6726 static const char *const null_ptr = NULL;
6730 struct command *command;
6731 char **argv_expanded;
6733 /* it is not always needed, but we aim to smaller code */
6734 int squirrel[] = { -1, -1, -1 };
6737 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6740 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6741 * Result should be 3 lines: q w e, qwe, q w e
6743 G.ifs = get_local_var_value("IFS");
6747 IF_HUSH_JOB(pi->pgrp = -1;)
6748 pi->stopped_cmds = 0;
6749 command = &pi->cmds[0];
6750 argv_expanded = NULL;
6752 if (pi->num_cmds != 1
6753 || pi->followup == PIPE_BG
6754 || command->cmd_type == CMD_SUBSHELL
6761 debug_printf_exec(": group:%p argv:'%s'\n",
6762 command->group, command->argv ? command->argv[0] : "NONE");
6764 if (command->group) {
6765 #if ENABLE_HUSH_FUNCTIONS
6766 if (command->cmd_type == CMD_FUNCDEF) {
6767 /* "executing" func () { list } */
6768 struct function *funcp;
6770 funcp = new_function(command->argv[0]);
6771 /* funcp->name is already set to argv[0] */
6772 funcp->body = command->group;
6774 funcp->body_as_string = command->group_as_string;
6775 command->group_as_string = NULL;
6777 command->group = NULL;
6778 command->argv[0] = NULL;
6779 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6780 funcp->parent_cmd = command;
6781 command->child_func = funcp;
6783 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6785 return EXIT_SUCCESS;
6789 debug_printf("non-subshell group\n");
6790 rcode = 1; /* exitcode if redir failed */
6791 if (setup_redirects(command, squirrel) == 0) {
6792 debug_printf_exec(": run_list\n");
6793 rcode = run_list(command->group) & 0xff;
6795 restore_redirects(squirrel);
6796 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6798 debug_printf_exec("run_pipe: return %d\n", rcode);
6802 argv = command->argv ? command->argv : (char **) &null_ptr;
6804 const struct built_in_command *x;
6805 #if ENABLE_HUSH_FUNCTIONS
6806 const struct function *funcp;
6810 char **new_env = NULL;
6811 struct variable *old_vars = NULL;
6813 if (argv[command->assignment_cnt] == NULL) {
6814 /* Assignments, but no command */
6815 /* Ensure redirects take effect (that is, create files).
6816 * Try "a=t >file" */
6817 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6818 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6819 /* Set shell variables */
6823 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6824 /* Do we need to flag set_local_var() errors?
6825 * "assignment to readonly var" and "putenv error"
6830 /* Redirect error sets $? to 1. Otherwise,
6831 * if evaluating assignment value set $?, retain it.
6832 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6834 rcode = G.last_exitcode;
6835 /* Exit, _skipping_ variable restoring code: */
6836 goto clean_up_and_ret0;
6838 #else /* Older, bigger, but more correct code */
6840 rcode = setup_redirects(command, squirrel);
6841 restore_redirects(squirrel);
6842 /* Set shell variables */
6844 bb_putchar_stderr('+');
6846 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6848 fprintf(stderr, " %s", p);
6849 debug_printf_exec("set shell var:'%s'->'%s'\n",
6851 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6852 /* Do we need to flag set_local_var() errors?
6853 * "assignment to readonly var" and "putenv error"
6858 bb_putchar_stderr('\n');
6859 /* Redirect error sets $? to 1. Otherwise,
6860 * if evaluating assignment value set $?, retain it.
6861 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6863 rcode = G.last_exitcode;
6864 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6866 debug_printf_exec("run_pipe: return %d\n", rcode);
6871 /* Expand the rest into (possibly) many strings each */
6872 #if ENABLE_HUSH_BASH_COMPAT
6873 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6874 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6878 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6881 /* if someone gives us an empty string: `cmd with empty output` */
6882 if (!argv_expanded[0]) {
6883 free(argv_expanded);
6885 return G.last_exitcode;
6888 x = find_builtin(argv_expanded[0]);
6889 #if ENABLE_HUSH_FUNCTIONS
6892 funcp = find_function(argv_expanded[0]);
6896 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6897 debug_printf("exec with redirects only\n");
6898 rcode = setup_redirects(command, NULL);
6899 goto clean_up_and_ret1;
6902 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6905 debug_printf_exec(": builtin '%s' '%s'...\n",
6906 x->b_cmd, argv_expanded[1]);
6908 rcode = x->b_function(argv_expanded) & 0xff;
6911 #if ENABLE_HUSH_FUNCTIONS
6913 # if ENABLE_HUSH_LOCAL
6914 struct variable **sv;
6915 sv = G.shadowed_vars_pp;
6916 G.shadowed_vars_pp = &old_vars;
6918 debug_printf_exec(": function '%s' '%s'...\n",
6919 funcp->name, argv_expanded[1]);
6920 rcode = run_function(funcp, argv_expanded) & 0xff;
6921 # if ENABLE_HUSH_LOCAL
6922 G.shadowed_vars_pp = sv;
6928 unset_vars(new_env);
6930 /* clean_up_and_ret0: */
6931 restore_redirects(squirrel);
6933 free(argv_expanded);
6934 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6936 debug_printf_exec("run_pipe return %d\n", rcode);
6940 if (ENABLE_FEATURE_SH_NOFORK) {
6941 int n = find_applet_by_name(argv_expanded[0]);
6942 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6943 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6945 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6946 argv_expanded[0], argv_expanded[1]);
6947 rcode = run_nofork_applet(n, argv_expanded);
6949 goto clean_up_and_ret;
6952 /* It is neither builtin nor applet. We must fork. */
6956 /* NB: argv_expanded may already be created, and that
6957 * might include `cmd` runs! Do not rerun it! We *must*
6958 * use argv_expanded if it's non-NULL */
6960 /* Going to fork a child per each pipe member */
6965 while (cmd_no < pi->num_cmds) {
6966 struct fd_pair pipefds;
6968 volatile nommu_save_t nommu_save;
6969 nommu_save.new_env = NULL;
6970 nommu_save.old_vars = NULL;
6971 nommu_save.argv = NULL;
6972 nommu_save.argv_from_re_execing = NULL;
6974 command = &pi->cmds[cmd_no];
6976 if (command->argv) {
6977 debug_printf_exec(": pipe member '%s' '%s'...\n",
6978 command->argv[0], command->argv[1]);
6980 debug_printf_exec(": pipe member with no argv\n");
6983 /* pipes are inserted between pairs of commands */
6986 if (cmd_no < pi->num_cmds)
6987 xpiped_pair(pipefds);
6989 command->pid = BB_MMU ? fork() : vfork();
6990 if (!command->pid) { /* child */
6992 disable_restore_tty_pgrp_on_exit();
6993 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6995 /* Every child adds itself to new process group
6996 * with pgid == pid_of_first_child_in_pipe */
6997 if (G.run_list_level == 1 && G_interactive_fd) {
7000 if (pgrp < 0) /* true for 1st process only */
7002 if (setpgid(0, pgrp) == 0
7003 && pi->followup != PIPE_BG
7004 && G_saved_tty_pgrp /* we have ctty */
7006 /* We do it in *every* child, not just first,
7008 tcsetpgrp(G_interactive_fd, pgrp);
7012 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7013 /* 1st cmd in backgrounded pipe
7014 * should have its stdin /dev/null'ed */
7016 if (open(bb_dev_null, O_RDONLY))
7017 xopen("/", O_RDONLY);
7019 xmove_fd(next_infd, 0);
7021 xmove_fd(pipefds.wr, 1);
7024 /* Like bash, explicit redirects override pipes,
7025 * and the pipe fd is available for dup'ing. */
7026 if (setup_redirects(command, NULL))
7029 /* Restore default handlers just prior to exec */
7030 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
7032 /* Stores to nommu_save list of env vars putenv'ed
7033 * (NOMMU, on MMU we don't need that) */
7034 /* cast away volatility... */
7035 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7036 /* pseudo_exec() does not return */
7039 /* parent or error */
7040 #if ENABLE_HUSH_FAST
7042 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7044 enable_restore_tty_pgrp_on_exit();
7046 /* Clean up after vforked child */
7047 free(nommu_save.argv);
7048 free(nommu_save.argv_from_re_execing);
7049 unset_vars(nommu_save.new_env);
7050 add_vars(nommu_save.old_vars);
7052 free(argv_expanded);
7053 argv_expanded = NULL;
7054 if (command->pid < 0) { /* [v]fork failed */
7055 /* Clearly indicate, was it fork or vfork */
7056 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7060 /* Second and next children need to know pid of first one */
7062 pi->pgrp = command->pid;
7068 if (cmd_no < pi->num_cmds)
7070 /* Pass read (output) pipe end to next iteration */
7071 next_infd = pipefds.rd;
7074 if (!pi->alive_cmds) {
7076 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7081 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7085 /* NB: called by pseudo_exec, and therefore must not modify any
7086 * global data until exec/_exit (we can be a child after vfork!) */
7087 static int run_list(struct pipe *pi)
7089 #if ENABLE_HUSH_CASE
7090 char *case_word = NULL;
7092 #if ENABLE_HUSH_LOOPS
7093 struct pipe *loop_top = NULL;
7094 char **for_lcur = NULL;
7095 char **for_list = NULL;
7097 smallint last_followup;
7099 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7100 smalluint cond_code = 0;
7102 enum { cond_code = 0 };
7105 smallint rword; /* RES_foo */
7106 smallint last_rword; /* ditto */
7109 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7112 #if ENABLE_HUSH_LOOPS
7113 /* Check syntax for "for" */
7116 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7117 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7119 /* current word is FOR or IN (BOLD in comments below) */
7120 if (cpipe->next == NULL) {
7121 syntax_error("malformed for");
7123 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7126 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7127 if (cpipe->next->res_word == RES_DO)
7129 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7130 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7131 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7133 syntax_error("malformed for");
7135 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7142 /* Past this point, all code paths should jump to ret: label
7143 * in order to return, no direct "return" statements please.
7144 * This helps to ensure that no memory is leaked. */
7152 last_rword = RES_XXXX;
7154 last_followup = PIPE_SEQ;
7155 rcode = G.last_exitcode;
7157 /* Go through list of pipes, (maybe) executing them. */
7158 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7162 IF_HAS_KEYWORDS(rword = pi->res_word;)
7163 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7164 rword, cond_code, last_rword);
7165 #if ENABLE_HUSH_LOOPS
7166 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7167 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7169 /* start of a loop: remember where loop starts */
7174 /* Still in the same "if...", "then..." or "do..." branch? */
7175 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7176 if ((rcode == 0 && last_followup == PIPE_OR)
7177 || (rcode != 0 && last_followup == PIPE_AND)
7179 /* It is "<true> || CMD" or "<false> && CMD"
7180 * and we should not execute CMD */
7181 debug_printf_exec("skipped cmd because of || or &&\n");
7182 last_followup = pi->followup;
7186 last_followup = pi->followup;
7187 IF_HAS_KEYWORDS(last_rword = rword;)
7190 if (rword == RES_THEN) {
7191 /* if false; then ... fi has exitcode 0! */
7192 G.last_exitcode = rcode = EXIT_SUCCESS;
7193 /* "if <false> THEN cmd": skip cmd */
7197 if (rword == RES_ELSE || rword == RES_ELIF) {
7198 /* "if <true> then ... ELSE/ELIF cmd":
7199 * skip cmd and all following ones */
7204 #if ENABLE_HUSH_LOOPS
7205 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7207 /* first loop through for */
7209 static const char encoded_dollar_at[] ALIGN1 = {
7210 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7211 }; /* encoded representation of "$@" */
7212 static const char *const encoded_dollar_at_argv[] = {
7213 encoded_dollar_at, NULL
7214 }; /* argv list with one element: "$@" */
7217 vals = (char**)encoded_dollar_at_argv;
7218 if (pi->next->res_word == RES_IN) {
7219 /* if no variable values after "in" we skip "for" */
7220 if (!pi->next->cmds[0].argv) {
7221 G.last_exitcode = rcode = EXIT_SUCCESS;
7222 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7225 vals = pi->next->cmds[0].argv;
7226 } /* else: "for var; do..." -> assume "$@" list */
7227 /* create list of variable values */
7228 debug_print_strings("for_list made from", vals);
7229 for_list = expand_strvec_to_strvec(vals);
7230 for_lcur = for_list;
7231 debug_print_strings("for_list", for_list);
7234 /* "for" loop is over, clean up */
7240 /* Insert next value from for_lcur */
7241 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7242 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7245 if (rword == RES_IN) {
7246 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7248 if (rword == RES_DONE) {
7249 continue; /* "done" has no cmds too */
7252 #if ENABLE_HUSH_CASE
7253 if (rword == RES_CASE) {
7254 case_word = expand_strvec_to_string(pi->cmds->argv);
7257 if (rword == RES_MATCH) {
7260 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7262 /* all prev words didn't match, does this one match? */
7263 argv = pi->cmds->argv;
7265 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7266 /* TODO: which FNM_xxx flags to use? */
7267 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7269 if (cond_code == 0) { /* match! we will execute this branch */
7270 free(case_word); /* make future "word)" stop */
7278 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7280 continue; /* not matched yet, skip this pipe */
7283 /* Just pressing <enter> in shell should check for jobs.
7284 * OTOH, in non-interactive shell this is useless
7285 * and only leads to extra job checks */
7286 if (pi->num_cmds == 0) {
7287 if (G_interactive_fd)
7288 goto check_jobs_and_continue;
7292 /* After analyzing all keywords and conditions, we decided
7293 * to execute this pipe. NB: have to do checkjobs(NULL)
7294 * after run_pipe to collect any background children,
7295 * even if list execution is to be stopped. */
7296 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7299 #if ENABLE_HUSH_LOOPS
7300 G.flag_break_continue = 0;
7302 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7304 /* We ran a builtin, function, or group.
7305 * rcode is already known
7306 * and we don't need to wait for anything. */
7307 G.last_exitcode = rcode;
7308 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7309 check_and_run_traps(0);
7310 #if ENABLE_HUSH_LOOPS
7311 /* Was it "break" or "continue"? */
7312 if (G.flag_break_continue) {
7313 smallint fbc = G.flag_break_continue;
7314 /* We might fall into outer *loop*,
7315 * don't want to break it too */
7317 G.depth_break_continue--;
7318 if (G.depth_break_continue == 0)
7319 G.flag_break_continue = 0;
7320 /* else: e.g. "continue 2" should *break* once, *then* continue */
7321 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7322 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7323 goto check_jobs_and_break;
7324 /* "continue": simulate end of loop */
7329 #if ENABLE_HUSH_FUNCTIONS
7330 if (G.flag_return_in_progress == 1) {
7331 /* same as "goto check_jobs_and_break" */
7336 } else if (pi->followup == PIPE_BG) {
7337 /* What does bash do with attempts to background builtins? */
7338 /* even bash 3.2 doesn't do that well with nested bg:
7339 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7340 * I'm NOT treating inner &'s as jobs */
7341 check_and_run_traps(0);
7343 if (G.run_list_level == 1)
7346 /* Last command's pid goes to $! */
7347 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7348 G.last_exitcode = rcode = EXIT_SUCCESS;
7349 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7352 if (G.run_list_level == 1 && G_interactive_fd) {
7353 /* Waits for completion, then fg's main shell */
7354 rcode = checkjobs_and_fg_shell(pi);
7355 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7356 check_and_run_traps(0);
7359 { /* This one just waits for completion */
7360 rcode = checkjobs(pi);
7361 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7362 check_and_run_traps(0);
7364 G.last_exitcode = rcode;
7368 /* Analyze how result affects subsequent commands */
7370 if (rword == RES_IF || rword == RES_ELIF)
7373 #if ENABLE_HUSH_LOOPS
7374 /* Beware of "while false; true; do ..."! */
7375 if (pi->next && pi->next->res_word == RES_DO) {
7376 if (rword == RES_WHILE) {
7378 /* "while false; do...done" - exitcode 0 */
7379 G.last_exitcode = rcode = EXIT_SUCCESS;
7380 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7381 goto check_jobs_and_break;
7384 if (rword == RES_UNTIL) {
7386 debug_printf_exec(": until expr is true: breaking\n");
7387 check_jobs_and_break:
7395 check_jobs_and_continue:
7402 #if ENABLE_HUSH_LOOPS
7407 #if ENABLE_HUSH_CASE
7411 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7415 /* Select which version we will use */
7416 static int run_and_free_list(struct pipe *pi)
7419 debug_printf_exec("run_and_free_list entered\n");
7420 if (!G.o_opt[OPT_O_NOEXEC]) {
7421 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7422 rcode = run_list(pi);
7424 /* free_pipe_list has the side effect of clearing memory.
7425 * In the long run that function can be merged with run_list,
7426 * but doing that now would hobble the debugging effort. */
7428 debug_printf_exec("run_and_free_list return %d\n", rcode);
7433 /* Called a few times only (or even once if "sh -c") */
7434 static void init_sigmasks(void)
7438 sigset_t old_blocked_set;
7440 if (!G.inherited_set_is_saved) {
7441 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7442 G.inherited_set = G.blocked_set;
7444 old_blocked_set = G.blocked_set;
7446 mask = (1 << SIGQUIT);
7447 if (G_interactive_fd) {
7448 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7449 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7450 mask |= SPECIAL_JOB_SIGS;
7452 G.non_DFL_mask = mask;
7457 sigaddset(&G.blocked_set, sig);
7461 sigdelset(&G.blocked_set, SIGCHLD);
7463 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7464 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7466 /* POSIX allows shell to re-enable SIGCHLD
7467 * even if it was SIG_IGN on entry */
7468 #if ENABLE_HUSH_FAST
7469 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7470 if (!G.inherited_set_is_saved)
7471 signal(SIGCHLD, SIGCHLD_handler);
7473 if (!G.inherited_set_is_saved)
7474 signal(SIGCHLD, SIG_DFL);
7477 G.inherited_set_is_saved = 1;
7482 static void maybe_set_to_sigexit(int sig)
7484 void (*handler)(int);
7485 /* non_DFL_mask'ed signals are, well, masked,
7486 * no need to set handler for them.
7488 if (!((G.non_DFL_mask >> sig) & 1)) {
7489 handler = signal(sig, sigexit);
7490 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7491 signal(sig, handler);
7494 /* Set handlers to restore tty pgrp and exit */
7495 static void set_fatal_handlers(void)
7497 /* We _must_ restore tty pgrp on fatal signals */
7499 maybe_set_to_sigexit(SIGILL );
7500 maybe_set_to_sigexit(SIGFPE );
7501 maybe_set_to_sigexit(SIGBUS );
7502 maybe_set_to_sigexit(SIGSEGV);
7503 maybe_set_to_sigexit(SIGTRAP);
7504 } /* else: hush is perfect. what SEGV? */
7505 maybe_set_to_sigexit(SIGABRT);
7506 /* bash 3.2 seems to handle these just like 'fatal' ones */
7507 maybe_set_to_sigexit(SIGPIPE);
7508 maybe_set_to_sigexit(SIGALRM);
7509 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7510 * if we aren't interactive... but in this case
7511 * we never want to restore pgrp on exit, and this fn is not called */
7512 /*maybe_set_to_sigexit(SIGHUP );*/
7513 /*maybe_set_to_sigexit(SIGTERM);*/
7514 /*maybe_set_to_sigexit(SIGINT );*/
7518 static int set_mode(int state, char mode, const char *o_opt)
7523 G.o_opt[OPT_O_NOEXEC] = state;
7526 IF_HUSH_MODE_X(G_x_mode = state;)
7530 /* "set -+o" without parameter.
7531 * in bash, set -o produces this output:
7535 * We always use the second form.
7537 const char *p = o_opt_strings;
7540 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7546 idx = index_in_strings(o_opt_strings, o_opt);
7548 G.o_opt[idx] = state;
7552 return EXIT_FAILURE;
7554 return EXIT_SUCCESS;
7557 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7558 int hush_main(int argc, char **argv)
7561 unsigned builtin_argc;
7563 struct variable *cur_var;
7564 struct variable *shell_ver;
7567 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7568 G.last_exitcode = EXIT_SUCCESS;
7570 G.argv0_for_re_execing = argv[0];
7572 /* Deal with HUSH_VERSION */
7573 shell_ver = xzalloc(sizeof(*shell_ver));
7574 shell_ver->flg_export = 1;
7575 shell_ver->flg_read_only = 1;
7576 /* Code which handles ${var<op>...} needs writable values for all variables,
7577 * therefore we xstrdup: */
7578 shell_ver->varstr = xstrdup(hush_version_str);
7579 /* Create shell local variables from the values
7580 * currently living in the environment */
7581 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7582 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7583 G.top_var = shell_ver;
7584 cur_var = G.top_var;
7587 char *value = strchr(*e, '=');
7588 if (value) { /* paranoia */
7589 cur_var->next = xzalloc(sizeof(*cur_var));
7590 cur_var = cur_var->next;
7591 cur_var->varstr = *e;
7592 cur_var->max_len = strlen(*e);
7593 cur_var->flg_export = 1;
7597 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7598 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7599 putenv(shell_ver->varstr);
7602 set_pwd_var(/*exp:*/ 1);
7603 /* bash also exports SHLVL and _,
7604 * and sets (but doesn't export) the following variables:
7606 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7607 * BASH_VERSION='3.2.0(1)-release'
7609 * MACHTYPE=i386-pc-linux-gnu
7611 * HOSTNAME=<xxxxxxxxxx>
7612 * PPID=<NNNNN> - we also do it elsewhere
7623 * PIPESTATUS=([0]="0")
7624 * HISTFILE=/<xxx>/.bash_history
7628 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7630 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7640 #if ENABLE_FEATURE_EDITING
7641 G.line_input_state = new_line_input_t(FOR_SHELL);
7642 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7644 const char *hp = get_local_var_value("HISTFILE");
7646 hp = get_local_var_value("HOME");
7648 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7649 //set_local_var(xasprintf("HISTFILE=%s", ...));
7652 # if ENABLE_FEATURE_SH_HISTFILESIZE
7653 hp = get_local_var_value("HISTFILESIZE");
7654 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7660 G.global_argc = argc;
7661 G.global_argv = argv;
7662 /* Initialize some more globals to non-zero values */
7663 cmdedit_update_prompt();
7665 if (setjmp(die_jmp)) {
7666 /* xfunc has failed! die die die */
7667 /* no EXIT traps, this is an escape hatch! */
7669 hush_exit(xfunc_error_retval);
7672 /* Shell is non-interactive at first. We need to call
7673 * init_sigmasks() if we are going to execute "sh <script>",
7674 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7675 * If we later decide that we are interactive, we run init_sigmasks()
7676 * in order to intercept (more) signals.
7680 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7683 opt = getopt(argc, argv, "+c:xins"
7686 # if ENABLE_HUSH_FUNCTIONS
7696 * sh ... -c 'script'
7697 * sh ... -c 'script' ARG0 [ARG1...]
7698 * On NOMMU, if builtin_argc != 0,
7699 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7700 * "" needs to be replaced with NULL
7701 * and BARGV vector fed to builtin function.
7702 * Note: the form without ARG0 never happens:
7703 * sh ... -c 'builtin' BARGV... ""
7706 G.root_pid = getpid();
7707 G.root_ppid = getppid();
7709 G.global_argv = argv + optind;
7710 G.global_argc = argc - optind;
7712 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7713 const struct built_in_command *x;
7716 x = find_builtin(optarg);
7717 if (x) { /* paranoia */
7718 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7719 G.global_argv += builtin_argc;
7720 G.global_argv[-1] = NULL; /* replace "" */
7722 G.last_exitcode = x->b_function(argv + optind - 1);
7726 if (!G.global_argv[0]) {
7727 /* -c 'script' (no params): prevent empty $0 */
7728 G.global_argv--; /* points to argv[i] of 'script' */
7729 G.global_argv[0] = argv[0];
7731 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7733 parse_and_run_string(optarg);
7736 /* Well, we cannot just declare interactiveness,
7737 * we have to have some stuff (ctty, etc) */
7738 /* G_interactive_fd++; */
7741 /* "-s" means "read from stdin", but this is how we always
7742 * operate, so simply do nothing here. */
7745 case '<': /* "big heredoc" support */
7746 full_write1_str(optarg);
7749 unsigned long long empty_trap_mask;
7751 G.root_pid = bb_strtou(optarg, &optarg, 16);
7753 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7755 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7757 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7759 builtin_argc = bb_strtou(optarg, &optarg, 16);
7761 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7762 if (empty_trap_mask != 0) {
7765 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7766 for (sig = 1; sig < NSIG; sig++) {
7767 if (empty_trap_mask & (1LL << sig)) {
7768 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7769 sigaddset(&G.blocked_set, sig);
7772 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7774 # if ENABLE_HUSH_LOOPS
7776 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7782 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7784 # if ENABLE_HUSH_FUNCTIONS
7786 struct function *funcp = new_function(optarg);
7787 /* funcp->name is already set to optarg */
7788 /* funcp->body is set to NULL. It's a special case. */
7789 funcp->body_as_string = argv[optind];
7797 if (set_mode(1, opt, NULL) == 0) /* no error */
7801 fprintf(stderr, "Usage: sh [FILE]...\n"
7802 " or: sh -c command [args]...\n\n");
7808 } /* option parsing loop */
7811 G.root_pid = getpid();
7812 G.root_ppid = getppid();
7815 /* If we are login shell... */
7816 if (argv[0] && argv[0][0] == '-') {
7818 debug_printf("sourcing /etc/profile\n");
7819 input = fopen_for_read("/etc/profile");
7820 if (input != NULL) {
7821 close_on_exec_on(fileno(input));
7823 parse_and_run_file(input);
7826 /* bash: after sourcing /etc/profile,
7827 * tries to source (in the given order):
7828 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7829 * stopping on first found. --noprofile turns this off.
7830 * bash also sources ~/.bash_logout on exit.
7831 * If called as sh, skips .bash_XXX files.
7838 * "bash <script>" (which is never interactive (unless -i?))
7839 * sources $BASH_ENV here (without scanning $PATH).
7840 * If called as sh, does the same but with $ENV.
7842 debug_printf("running script '%s'\n", argv[optind]);
7843 G.global_argv = argv + optind;
7844 G.global_argc = argc - optind;
7845 input = xfopen_for_read(argv[optind]);
7846 close_on_exec_on(fileno(input));
7848 parse_and_run_file(input);
7849 #if ENABLE_FEATURE_CLEAN_UP
7855 /* Up to here, shell was non-interactive. Now it may become one.
7856 * NB: don't forget to (re)run init_sigmasks() as needed.
7859 /* A shell is interactive if the '-i' flag was given,
7860 * or if all of the following conditions are met:
7862 * no arguments remaining or the -s flag given
7863 * standard input is a terminal
7864 * standard output is a terminal
7865 * Refer to Posix.2, the description of the 'sh' utility.
7868 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7869 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7870 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7871 if (G_saved_tty_pgrp < 0)
7872 G_saved_tty_pgrp = 0;
7874 /* try to dup stdin to high fd#, >= 255 */
7875 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7876 if (G_interactive_fd < 0) {
7877 /* try to dup to any fd */
7878 G_interactive_fd = dup(STDIN_FILENO);
7879 if (G_interactive_fd < 0) {
7881 G_interactive_fd = 0;
7882 G_saved_tty_pgrp = 0;
7885 // TODO: track & disallow any attempts of user
7886 // to (inadvertently) close/redirect G_interactive_fd
7888 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7889 if (G_interactive_fd) {
7890 close_on_exec_on(G_interactive_fd);
7892 if (G_saved_tty_pgrp) {
7893 /* If we were run as 'hush &', sleep until we are
7894 * in the foreground (tty pgrp == our pgrp).
7895 * If we get started under a job aware app (like bash),
7896 * make sure we are now in charge so we don't fight over
7897 * who gets the foreground */
7899 pid_t shell_pgrp = getpgrp();
7900 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7901 if (G_saved_tty_pgrp == shell_pgrp)
7903 /* send TTIN to ourself (should stop us) */
7904 kill(- shell_pgrp, SIGTTIN);
7908 /* Block some signals */
7911 if (G_saved_tty_pgrp) {
7912 /* Set other signals to restore saved_tty_pgrp */
7913 set_fatal_handlers();
7914 /* Put ourselves in our own process group
7915 * (bash, too, does this only if ctty is available) */
7916 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7917 /* Grab control of the terminal */
7918 tcsetpgrp(G_interactive_fd, getpid());
7920 /* -1 is special - makes xfuncs longjmp, not exit
7921 * (we reset die_sleep = 0 whereever we [v]fork) */
7922 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7926 #elif ENABLE_HUSH_INTERACTIVE
7927 /* No job control compiled in, only prompt/line editing */
7928 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7929 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7930 if (G_interactive_fd < 0) {
7931 /* try to dup to any fd */
7932 G_interactive_fd = dup(STDIN_FILENO);
7933 if (G_interactive_fd < 0)
7935 G_interactive_fd = 0;
7938 if (G_interactive_fd) {
7939 close_on_exec_on(G_interactive_fd);
7943 /* We have interactiveness code disabled */
7947 * if interactive but not a login shell, sources ~/.bashrc
7948 * (--norc turns this off, --rcfile <file> overrides)
7951 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7952 /* note: ash and hush share this string */
7953 printf("\n\n%s %s\n"
7954 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7957 "hush - the humble shell"
7961 parse_and_run_file(stdin);
7964 hush_exit(G.last_exitcode);
7969 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7970 int msh_main(int argc, char **argv)
7972 //bb_error_msg("msh is deprecated, please use hush instead");
7973 return hush_main(argc, argv);
7981 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7986 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7993 return applet_main_func(argc, argv - argc);
7996 static int FAST_FUNC builtin_test(char **argv)
7998 return run_applet_main(argv, test_main);
8001 static int FAST_FUNC builtin_echo(char **argv)
8003 return run_applet_main(argv, echo_main);
8007 static int FAST_FUNC builtin_printf(char **argv)
8009 return run_applet_main(argv, printf_main);
8013 static char **skip_dash_dash(char **argv)
8016 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8021 static int FAST_FUNC builtin_eval(char **argv)
8023 int rcode = EXIT_SUCCESS;
8025 argv = skip_dash_dash(argv);
8027 char *str = expand_strvec_to_string(argv);
8029 * eval "echo Hi; done" ("done" is syntax error):
8030 * "echo Hi" will not execute too.
8032 parse_and_run_string(str);
8034 rcode = G.last_exitcode;
8039 static int FAST_FUNC builtin_cd(char **argv)
8043 argv = skip_dash_dash(argv);
8045 if (newdir == NULL) {
8046 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8047 * bash says "bash: cd: HOME not set" and does nothing
8050 const char *home = get_local_var_value("HOME");
8051 newdir = home ? home : "/";
8053 if (chdir(newdir)) {
8054 /* Mimic bash message exactly */
8055 bb_perror_msg("cd: %s", newdir);
8056 return EXIT_FAILURE;
8058 /* Read current dir (get_cwd(1) is inside) and set PWD.
8059 * Note: do not enforce exporting. If PWD was unset or unexported,
8060 * set it again, but do not export. bash does the same.
8062 set_pwd_var(/*exp:*/ 0);
8063 return EXIT_SUCCESS;
8066 static int FAST_FUNC builtin_exec(char **argv)
8068 argv = skip_dash_dash(argv);
8069 if (argv[0] == NULL)
8070 return EXIT_SUCCESS; /* bash does this */
8072 /* Careful: we can end up here after [v]fork. Do not restore
8073 * tty pgrp then, only top-level shell process does that */
8074 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8075 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8077 /* TODO: if exec fails, bash does NOT exit! We do.
8078 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8079 * and tcsetpgrp, and this is inherently racy.
8081 execvp_or_die(argv);
8084 static int FAST_FUNC builtin_exit(char **argv)
8086 debug_printf_exec("%s()\n", __func__);
8088 /* interactive bash:
8089 * # trap "echo EEE" EXIT
8092 * There are stopped jobs.
8093 * (if there are _stopped_ jobs, running ones don't count)
8096 # EEE (then bash exits)
8098 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8101 /* note: EXIT trap is run by hush_exit */
8102 argv = skip_dash_dash(argv);
8103 if (argv[0] == NULL)
8104 hush_exit(G.last_exitcode);
8105 /* mimic bash: exit 123abc == exit 255 + error msg */
8106 xfunc_error_retval = 255;
8107 /* bash: exit -2 == exit 254, no error msg */
8108 hush_exit(xatoi(argv[0]) & 0xff);
8111 static void print_escaped(const char *s)
8116 const char *p = strchrnul(s, '\'');
8117 /* print 'xxxx', possibly just '' */
8118 printf("'%.*s'", (int)(p - s), s);
8123 /* s points to '; print "'''...'''" */
8125 do putchar('\''); while (*++s == '\'');
8130 #if !ENABLE_HUSH_LOCAL
8131 #define helper_export_local(argv, exp, lvl) \
8132 helper_export_local(argv, exp)
8134 static void helper_export_local(char **argv, int exp, int lvl)
8138 char *name_end = strchrnul(name, '=');
8140 /* So far we do not check that name is valid (TODO?) */
8142 if (*name_end == '\0') {
8143 struct variable *var, **vpp;
8145 vpp = get_ptr_to_local_var(name, name_end - name);
8146 var = vpp ? *vpp : NULL;
8148 if (exp == -1) { /* unexporting? */
8149 /* export -n NAME (without =VALUE) */
8151 var->flg_export = 0;
8152 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8154 } /* else: export -n NOT_EXISTING_VAR: no-op */
8157 if (exp == 1) { /* exporting? */
8158 /* export NAME (without =VALUE) */
8160 var->flg_export = 1;
8161 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8162 putenv(var->varstr);
8166 /* Exporting non-existing variable.
8167 * bash does not put it in environment,
8168 * but remembers that it is exported,
8169 * and does put it in env when it is set later.
8170 * We just set it to "" and export. */
8171 /* Or, it's "local NAME" (without =VALUE).
8172 * bash sets the value to "". */
8173 name = xasprintf("%s=", name);
8175 /* (Un)exporting/making local NAME=VALUE */
8176 name = xstrdup(name);
8178 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8182 static int FAST_FUNC builtin_export(char **argv)
8184 unsigned opt_unexport;
8186 #if ENABLE_HUSH_EXPORT_N
8187 /* "!": do not abort on errors */
8188 opt_unexport = getopt32(argv, "!n");
8189 if (opt_unexport == (uint32_t)-1)
8190 return EXIT_FAILURE;
8197 if (argv[0] == NULL) {
8204 /* ash emits: export VAR='VAL'
8205 * bash: declare -x VAR="VAL"
8206 * we follow ash example */
8207 const char *s = *e++;
8208 const char *p = strchr(s, '=');
8210 if (!p) /* wtf? take next variable */
8213 printf("export %.*s", (int)(p - s) + 1, s);
8214 print_escaped(p + 1);
8218 /*fflush_all(); - done after each builtin anyway */
8220 return EXIT_SUCCESS;
8223 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8225 return EXIT_SUCCESS;
8228 #if ENABLE_HUSH_LOCAL
8229 static int FAST_FUNC builtin_local(char **argv)
8231 if (G.func_nest_level == 0) {
8232 bb_error_msg("%s: not in a function", argv[0]);
8233 return EXIT_FAILURE; /* bash compat */
8235 helper_export_local(argv, 0, G.func_nest_level);
8236 return EXIT_SUCCESS;
8240 static int FAST_FUNC builtin_trap(char **argv)
8246 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8251 /* No args: print all trapped */
8252 for (i = 0; i < NSIG; ++i) {
8255 print_escaped(G.traps[i]);
8256 /* note: bash adds "SIG", but only if invoked
8257 * as "bash". If called as "sh", or if set -o posix,
8258 * then it prints short signal names.
8259 * We are printing short names: */
8260 printf(" %s\n", get_signame(i));
8263 /*fflush_all(); - done after each builtin anyway */
8264 return EXIT_SUCCESS;
8268 /* If first arg is a number: reset all specified signals */
8269 sig = bb_strtou(*argv, NULL, 10);
8275 sig = get_signum(*argv++);
8276 if (sig < 0 || sig >= NSIG) {
8278 /* Mimic bash message exactly */
8279 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8284 G.traps[sig] = xstrdup(new_cmd);
8286 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8287 get_signame(sig), sig, G.traps[sig]);
8289 /* There is no signal for 0 (EXIT) */
8294 sigaddset(&G.blocked_set, sig);
8296 /* There was a trap handler, we are removing it
8297 * (if sig has non-DFL handling,
8298 * we don't need to do anything) */
8299 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8301 sigdelset(&G.blocked_set, sig);
8304 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8308 if (!argv[1]) { /* no second arg */
8309 bb_error_msg("trap: invalid arguments");
8310 return EXIT_FAILURE;
8313 /* First arg is "-": reset all specified to default */
8314 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8315 /* Everything else: set arg as signal handler
8316 * (includes "" case, which ignores signal) */
8317 if (argv[0][0] == '-') {
8318 if (argv[0][1] == '\0') { /* "-" */
8319 /* new_cmd remains NULL: "reset these sigs" */
8322 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8325 /* else: "-something", no special meaning */
8330 goto process_sig_list;
8333 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8334 static int FAST_FUNC builtin_type(char **argv)
8336 int ret = EXIT_SUCCESS;
8342 if (0) {} /* make conditional compile easier below */
8343 /*else if (find_alias(*argv))
8344 type = "an alias";*/
8345 #if ENABLE_HUSH_FUNCTIONS
8346 else if (find_function(*argv))
8347 type = "a function";
8349 else if (find_builtin(*argv))
8350 type = "a shell builtin";
8351 else if ((path = find_in_path(*argv)) != NULL)
8354 bb_error_msg("type: %s: not found", *argv);
8359 printf("%s is %s\n", *argv, type);
8367 /* built-in 'fg' and 'bg' handler */
8368 static int FAST_FUNC builtin_fg_bg(char **argv)
8373 if (!G_interactive_fd)
8374 return EXIT_FAILURE;
8376 /* If they gave us no args, assume they want the last backgrounded task */
8378 for (pi = G.job_list; pi; pi = pi->next) {
8379 if (pi->jobid == G.last_jobid) {
8383 bb_error_msg("%s: no current job", argv[0]);
8384 return EXIT_FAILURE;
8386 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8387 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8388 return EXIT_FAILURE;
8390 for (pi = G.job_list; pi; pi = pi->next) {
8391 if (pi->jobid == jobnum) {
8395 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8396 return EXIT_FAILURE;
8398 /* TODO: bash prints a string representation
8399 * of job being foregrounded (like "sleep 1 | cat") */
8400 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8401 /* Put the job into the foreground. */
8402 tcsetpgrp(G_interactive_fd, pi->pgrp);
8405 /* Restart the processes in the job */
8406 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8407 for (i = 0; i < pi->num_cmds; i++) {
8408 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8409 pi->cmds[i].is_stopped = 0;
8411 pi->stopped_cmds = 0;
8413 i = kill(- pi->pgrp, SIGCONT);
8415 if (errno == ESRCH) {
8416 delete_finished_bg_job(pi);
8417 return EXIT_SUCCESS;
8419 bb_perror_msg("kill (SIGCONT)");
8422 if (argv[0][0] == 'f') {
8424 return checkjobs_and_fg_shell(pi);
8426 return EXIT_SUCCESS;
8430 #if ENABLE_HUSH_HELP
8431 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8433 const struct built_in_command *x;
8436 "Built-in commands:\n"
8437 "------------------\n");
8438 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8440 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8443 return EXIT_SUCCESS;
8448 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8451 const char *status_string;
8453 for (job = G.job_list; job; job = job->next) {
8454 if (job->alive_cmds == job->stopped_cmds)
8455 status_string = "Stopped";
8457 status_string = "Running";
8459 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8461 return EXIT_SUCCESS;
8466 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8471 # ifdef M_TRIM_THRESHOLD
8472 /* Optional. Reduces probability of false positives */
8475 /* Crude attempt to find where "free memory" starts,
8476 * sans fragmentation. */
8478 l = (unsigned long)p;
8481 if (l < (unsigned long)p) l = (unsigned long)p;
8484 if (!G.memleak_value)
8485 G.memleak_value = l;
8487 l -= G.memleak_value;
8494 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8499 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8502 return EXIT_SUCCESS;
8505 /* Interruptibility of read builtin in bash
8506 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8508 * Empty trap makes read ignore corresponding signal, for any signal.
8511 * - terminates non-interactive shell;
8512 * - interrupts read in interactive shell;
8513 * if it has non-empty trap:
8514 * - executes trap and returns to command prompt in interactive shell;
8515 * - executes trap and returns to read in non-interactive shell;
8517 * - is ignored (does not interrupt) read in interactive shell;
8518 * - terminates non-interactive shell;
8519 * if it has non-empty trap:
8520 * - executes trap and returns to read;
8522 * - terminates shell (regardless of interactivity);
8523 * if it has non-empty trap:
8524 * - executes trap and returns to read;
8527 static void record_signal(int sig)
8529 sigaddset(&G.detected_set, sig);
8531 static int FAST_FUNC builtin_read(char **argv)
8540 sigset_t saved_blkd_set;
8542 /* "!": do not abort on errors.
8543 * Option string must start with "sr" to match BUILTIN_READ_xxx
8545 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8546 if (read_flags == (uint32_t)-1)
8547 return EXIT_FAILURE;
8549 ifs = get_local_var_value("IFS"); /* can be NULL */
8552 /* We need to temporarily unblock and record signals around read */
8554 saved_blkd_set = G.blocked_set;
8557 struct sigaction sa, old_sa;
8559 memset(&sa, 0, sizeof(sa));
8560 sigfillset(&sa.sa_mask);
8561 /*sa.sa_flags = 0;*/
8562 sa.sa_handler = record_signal;
8567 if (sigismember(&G.blocked_set, sig)) {
8568 char *sig_trap = (G.traps && G.traps[sig]) ? G.traps[sig] : NULL;
8569 /* If has a nonempty trap... */
8570 if ((sig_trap && sig_trap[0])
8571 /* ...or has no trap and is SIGINT or SIGHUP */
8572 || (!sig_trap && (sig == SIGINT || sig == SIGHUP))
8574 sigaction(sig, &sa, &old_sa);
8575 if (old_sa.sa_handler == SIG_IGN) /* oops... restore back to IGN! */
8576 sigaction_set(sig, &old_sa);
8578 sigdelset(&G.blocked_set, sig);
8581 } while (sig < NSIG-1);
8584 if (memcmp(&saved_blkd_set, &G.blocked_set, sizeof(saved_blkd_set)) != 0)
8585 sigprocmask_set(&G.blocked_set);
8587 r = shell_builtin_read(set_local_var_from_halves,
8597 if (memcmp(&saved_blkd_set, &G.blocked_set, sizeof(saved_blkd_set)) != 0) {
8598 G.blocked_set = saved_blkd_set;
8599 sigprocmask_set(&G.blocked_set);
8602 if ((uintptr_t)r == 1 && errno == EINTR) {
8603 unsigned sig = check_and_run_traps(0);
8604 if (sig && sig != SIGINT)
8608 if ((uintptr_t)r > 1) {
8609 bb_error_msg("%s", r);
8610 r = (char*)(uintptr_t)1;
8613 return (uintptr_t)r;
8616 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8617 * built-in 'set' handler
8619 * set [-abCefhmnuvx] [-o option] [argument...]
8620 * set [+abCefhmnuvx] [+o option] [argument...]
8621 * set -- [argument...]
8624 * Implementations shall support the options in both their hyphen and
8625 * plus-sign forms. These options can also be specified as options to sh.
8627 * Write out all variables and their values: set
8628 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8629 * Turn on the -x and -v options: set -xv
8630 * Unset all positional parameters: set --
8631 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8632 * Set the positional parameters to the expansion of x, even if x expands
8633 * with a leading '-' or '+': set -- $x
8635 * So far, we only support "set -- [argument...]" and some of the short names.
8637 static int FAST_FUNC builtin_set(char **argv)
8640 char **pp, **g_argv;
8641 char *arg = *++argv;
8645 for (e = G.top_var; e; e = e->next)
8647 return EXIT_SUCCESS;
8651 if (strcmp(arg, "--") == 0) {
8655 if (arg[0] != '+' && arg[0] != '-')
8657 for (n = 1; arg[n]; ++n) {
8658 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8660 if (arg[n] == 'o' && argv[1])
8663 } while ((arg = *++argv) != NULL);
8664 /* Now argv[0] is 1st argument */
8667 return EXIT_SUCCESS;
8670 /* NB: G.global_argv[0] ($0) is never freed/changed */
8671 g_argv = G.global_argv;
8672 if (G.global_args_malloced) {
8678 G.global_args_malloced = 1;
8679 pp = xzalloc(sizeof(pp[0]) * 2);
8680 pp[0] = g_argv[0]; /* retain $0 */
8683 /* This realloc's G.global_argv */
8684 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8691 return EXIT_SUCCESS;
8693 /* Nothing known, so abort */
8695 bb_error_msg("set: %s: invalid option", arg);
8696 return EXIT_FAILURE;
8699 static int FAST_FUNC builtin_shift(char **argv)
8702 argv = skip_dash_dash(argv);
8706 if (n >= 0 && n < G.global_argc) {
8707 if (G.global_args_malloced) {
8710 free(G.global_argv[m++]);
8713 memmove(&G.global_argv[1], &G.global_argv[n+1],
8714 G.global_argc * sizeof(G.global_argv[0]));
8715 return EXIT_SUCCESS;
8717 return EXIT_FAILURE;
8720 static int FAST_FUNC builtin_source(char **argv)
8722 char *arg_path, *filename;
8725 #if ENABLE_HUSH_FUNCTIONS
8729 argv = skip_dash_dash(argv);
8732 /* bash says: "bash: .: filename argument required" */
8733 return 2; /* bash compat */
8736 if (!strchr(filename, '/')) {
8737 arg_path = find_in_path(filename);
8739 filename = arg_path;
8741 input = fopen_or_warn(filename, "r");
8744 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8745 return EXIT_FAILURE;
8747 close_on_exec_on(fileno(input));
8749 #if ENABLE_HUSH_FUNCTIONS
8750 sv_flg = G.flag_return_in_progress;
8751 /* "we are inside sourced file, ok to use return" */
8752 G.flag_return_in_progress = -1;
8754 save_and_replace_G_args(&sv, argv);
8756 parse_and_run_file(input);
8759 restore_G_args(&sv, argv);
8760 #if ENABLE_HUSH_FUNCTIONS
8761 G.flag_return_in_progress = sv_flg;
8764 return G.last_exitcode;
8767 static int FAST_FUNC builtin_umask(char **argv)
8773 argv = skip_dash_dash(argv);
8775 mode_t old_mask = mask;
8778 rc = bb_parse_mode(argv[0], &mask);
8783 * bash: umask: 'q': invalid symbolic mode operator
8784 * bash: umask: 999: octal number out of range
8786 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8791 printf("%04o\n", (unsigned) mask);
8792 /* fall through and restore mask which we set to 0 */
8796 return !rc; /* rc != 0 - success */
8799 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8800 static int FAST_FUNC builtin_unset(char **argv)
8805 /* "!": do not abort on errors */
8806 /* "+": stop at 1st non-option */
8807 opts = getopt32(argv, "!+vf");
8808 if (opts == (unsigned)-1)
8809 return EXIT_FAILURE;
8811 bb_error_msg("unset: -v and -f are exclusive");
8812 return EXIT_FAILURE;
8818 if (!(opts & 2)) { /* not -f */
8819 if (unset_local_var(*argv)) {
8820 /* unset <nonexistent_var> doesn't fail.
8821 * Error is when one tries to unset RO var.
8822 * Message was printed by unset_local_var. */
8826 #if ENABLE_HUSH_FUNCTIONS
8836 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8837 static int FAST_FUNC builtin_wait(char **argv)
8839 int ret = EXIT_SUCCESS;
8842 argv = skip_dash_dash(argv);
8843 if (argv[0] == NULL) {
8844 /* Don't care about wait results */
8845 /* Note 1: must wait until there are no more children */
8846 /* Note 2: must be interruptible */
8848 * $ sleep 3 & sleep 6 & wait
8853 * $ sleep 3 & sleep 6 & wait
8857 * ^C <-- after ~4 sec from keyboard
8860 sigaddset(&G.blocked_set, SIGCHLD);
8861 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8864 if (errno == ECHILD)
8866 /* Wait for SIGCHLD or any other signal of interest */
8867 /* sigtimedwait with infinite timeout: */
8868 sig = sigwaitinfo(&G.blocked_set, NULL);
8870 sig = check_and_run_traps(sig);
8871 if (sig && sig != SIGCHLD) { /* see note 2 */
8877 sigdelset(&G.blocked_set, SIGCHLD);
8878 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8882 /* This is probably buggy wrt interruptible-ness */
8884 pid_t pid = bb_strtou(*argv, NULL, 10);
8886 /* mimic bash message */
8887 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8888 return EXIT_FAILURE;
8890 if (waitpid(pid, &status, 0) == pid) {
8891 if (WIFSIGNALED(status))
8892 ret = 128 + WTERMSIG(status);
8893 else if (WIFEXITED(status))
8894 ret = WEXITSTATUS(status);
8898 bb_perror_msg("wait %s", *argv);
8907 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8908 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8911 def = bb_strtou(argv[1], NULL, 10);
8912 if (errno || def < def_min || argv[2]) {
8913 bb_error_msg("%s: bad arguments", argv[0]);
8921 #if ENABLE_HUSH_LOOPS
8922 static int FAST_FUNC builtin_break(char **argv)
8925 if (G.depth_of_loop == 0) {
8926 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8927 return EXIT_SUCCESS; /* bash compat */
8929 G.flag_break_continue++; /* BC_BREAK = 1 */
8931 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8932 if (depth == UINT_MAX)
8933 G.flag_break_continue = BC_BREAK;
8934 if (G.depth_of_loop < depth)
8935 G.depth_break_continue = G.depth_of_loop;
8937 return EXIT_SUCCESS;
8940 static int FAST_FUNC builtin_continue(char **argv)
8942 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8943 return builtin_break(argv);
8947 #if ENABLE_HUSH_FUNCTIONS
8948 static int FAST_FUNC builtin_return(char **argv)
8952 if (G.flag_return_in_progress != -1) {
8953 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8954 return EXIT_FAILURE; /* bash compat */
8957 G.flag_return_in_progress = 1;
8960 * out of range: wraps around at 256, does not error out
8961 * non-numeric param:
8962 * f() { false; return qwe; }; f; echo $?
8963 * bash: return: qwe: numeric argument required <== we do this
8964 * 255 <== we also do this
8966 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);