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 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #include <malloc.h> /* for malloc_trim */
87 /* #include <dmalloc.h> */
92 #include "shell_common.h"
95 #if ENABLE_HUSH_RANDOM_SUPPORT
98 # define CLEAR_RANDOM_T(rnd) ((void)0)
101 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
104 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
107 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
109 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
110 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
113 //config: bool "hush"
116 //config: hush is a small shell (25k). It handles the normal flow control
117 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
118 //config: case/esac. Redirections, here documents, $((arithmetic))
119 //config: and functions are supported.
121 //config: It will compile and work on no-mmu systems.
123 //config: It does not handle select, aliases, tilde expansion,
124 //config: &>file and >&file redirection of stdout+stderr.
126 //config:config HUSH_BASH_COMPAT
127 //config: bool "bash-compatible extensions"
129 //config: depends on HUSH
131 //config: Enable bash-compatible extensions.
133 //config:config HUSH_BRACE_EXPANSION
134 //config: bool "Brace expansion"
136 //config: depends on HUSH_BASH_COMPAT
138 //config: Enable {abc,def} extension.
140 //config:config HUSH_HELP
141 //config: bool "help builtin"
143 //config: depends on HUSH
145 //config: Enable help builtin in hush. Code size + ~1 kbyte.
147 //config:config HUSH_INTERACTIVE
148 //config: bool "Interactive mode"
150 //config: depends on HUSH
152 //config: Enable interactive mode (prompt and command editing).
153 //config: Without this, hush simply reads and executes commands
154 //config: from stdin just like a shell script from a file.
155 //config: No prompt, no PS1/PS2 magic shell variables.
157 //config:config HUSH_SAVEHISTORY
158 //config: bool "Save command history to .hush_history"
160 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162 //config: Enable history saving in hush.
164 //config:config HUSH_JOB
165 //config: bool "Job control"
167 //config: depends on HUSH_INTERACTIVE
169 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
170 //config: command (not entire shell), fg/bg builtins work. Without this option,
171 //config: "cmd &" still works by simply spawning a process and immediately
172 //config: prompting for next command (or executing next command in a script),
173 //config: but no separate process group is formed.
175 //config:config HUSH_TICK
176 //config: bool "Process substitution"
178 //config: depends on HUSH
180 //config: Enable process substitution `command` and $(command) in hush.
182 //config:config HUSH_IF
183 //config: bool "Support if/then/elif/else/fi"
185 //config: depends on HUSH
187 //config: Enable if/then/elif/else/fi in hush.
189 //config:config HUSH_LOOPS
190 //config: bool "Support for, while and until loops"
192 //config: depends on HUSH
194 //config: Enable for, while and until loops in hush.
196 //config:config HUSH_CASE
197 //config: bool "Support case ... esac statement"
199 //config: depends on HUSH
201 //config: Enable case ... esac statement in hush. +400 bytes.
203 //config:config HUSH_FUNCTIONS
204 //config: bool "Support funcname() { commands; } syntax"
206 //config: depends on HUSH
208 //config: Enable support for shell functions in hush. +800 bytes.
210 //config:config HUSH_LOCAL
211 //config: bool "Support local builtin"
213 //config: depends on HUSH_FUNCTIONS
215 //config: Enable support for local variables in functions.
217 //config:config HUSH_RANDOM_SUPPORT
218 //config: bool "Pseudorandom generator and $RANDOM variable"
220 //config: depends on HUSH
222 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
223 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
225 //config:config HUSH_EXPORT_N
226 //config: bool "Support 'export -n' option"
228 //config: depends on HUSH
230 //config: export -n unexports variables. It is a bash extension.
232 //config:config HUSH_MODE_X
233 //config: bool "Support 'hush -x' option and 'set -x' command"
235 //config: depends on HUSH
237 //config: This instructs hush to print commands before execution.
238 //config: Adds ~300 bytes.
241 //config: bool "msh (deprecated: aliased to hush)"
243 //config: select HUSH
245 //config: msh is deprecated and will be removed, please migrate to hush.
248 //usage:#define hush_trivial_usage NOUSAGE_STR
249 //usage:#define hush_full_usage ""
250 //usage:#define msh_trivial_usage NOUSAGE_STR
251 //usage:#define msh_full_usage ""
252 //usage:#define sh_trivial_usage NOUSAGE_STR
253 //usage:#define sh_full_usage ""
254 //usage:#define bash_trivial_usage NOUSAGE_STR
255 //usage:#define bash_full_usage ""
259 #define LEAK_HUNTING 0
260 #define BUILD_AS_NOMMU 0
261 /* Enable/disable sanity checks. Ok to enable in production,
262 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
263 * Keeping 1 for now even in released versions.
266 /* Slightly bigger (+200 bytes), but faster hush.
267 * So far it only enables a trick with counting SIGCHLDs and forks,
268 * which allows us to do fewer waitpid's.
269 * (we can detect a case where neither forks were done nor SIGCHLDs happened
270 * and therefore waitpid will return the same result as last time)
272 #define ENABLE_HUSH_FAST 0
273 /* TODO: implement simplified code for users which do not need ${var%...} ops
274 * So far ${var%...} ops are always enabled:
276 #define ENABLE_HUSH_DOLLAR_OPS 1
281 # undef USE_FOR_NOMMU
284 # define USE_FOR_NOMMU(...) __VA_ARGS__
285 # define USE_FOR_MMU(...)
288 #include "NUM_APPLETS.h"
290 /* STANDALONE does not make sense, and won't compile */
291 # undef CONFIG_FEATURE_SH_STANDALONE
292 # undef ENABLE_FEATURE_SH_STANDALONE
293 # undef IF_FEATURE_SH_STANDALONE
294 # undef IF_NOT_FEATURE_SH_STANDALONE
295 # define ENABLE_FEATURE_SH_STANDALONE 0
296 # define IF_FEATURE_SH_STANDALONE(...)
297 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
300 #if !ENABLE_HUSH_INTERACTIVE
301 # undef ENABLE_FEATURE_EDITING
302 # define ENABLE_FEATURE_EDITING 0
303 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
304 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
307 /* Do we support ANY keywords? */
308 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
309 # define HAS_KEYWORDS 1
310 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
311 # define IF_HAS_NO_KEYWORDS(...)
313 # define HAS_KEYWORDS 0
314 # define IF_HAS_KEYWORDS(...)
315 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
318 /* If you comment out one of these below, it will be #defined later
319 * to perform debug printfs to stderr: */
320 #define debug_printf(...) do {} while (0)
321 /* Finer-grained debug switches */
322 #define debug_printf_parse(...) do {} while (0)
323 #define debug_print_tree(a, b) do {} while (0)
324 #define debug_printf_exec(...) do {} while (0)
325 #define debug_printf_env(...) do {} while (0)
326 #define debug_printf_jobs(...) do {} while (0)
327 #define debug_printf_expand(...) do {} while (0)
328 #define debug_printf_varexp(...) do {} while (0)
329 #define debug_printf_glob(...) do {} while (0)
330 #define debug_printf_list(...) do {} while (0)
331 #define debug_printf_subst(...) do {} while (0)
332 #define debug_printf_clean(...) do {} while (0)
334 #define ERR_PTR ((void*)(long)1)
336 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
338 #define _SPECIAL_VARS_STR "_*@$!?#"
339 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
340 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
341 #if ENABLE_HUSH_BASH_COMPAT
342 /* Support / and // replace ops */
343 /* Note that // is stored as \ in "encoded" string representation */
344 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
345 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
346 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
348 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
349 # define VAR_SUBST_OPS "%#:-=+?"
350 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
353 #define SPECIAL_VAR_SYMBOL 3
357 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
359 /* This supports saving pointers malloced in vfork child,
360 * to be freed in the parent.
363 typedef struct nommu_save_t {
365 struct variable *old_vars;
367 char **argv_from_re_execing;
380 #if ENABLE_HUSH_LOOPS
387 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
392 /* three pseudo-keywords support contrived "case" syntax: */
393 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
394 RES_MATCH , /* "word)" */
395 RES_CASE_BODY, /* "this command is inside CASE" */
402 typedef struct o_string {
404 int length; /* position where data is appended */
407 /* At least some part of the string was inside '' or "",
408 * possibly empty one: word"", wo''rd etc. */
409 smallint has_quoted_part;
410 smallint has_empty_slot;
411 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
414 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
416 /* Protect newly added chars against globbing
417 * by prepending \ to *, ?, [, \ */
418 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
421 MAYBE_ASSIGNMENT = 0,
422 DEFINITELY_ASSIGNMENT = 1,
424 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
427 /* Used for initialization: o_string foo = NULL_O_STRING; */
428 #define NULL_O_STRING { NULL }
430 /* I can almost use ordinary FILE*. Is open_memstream() universally
431 * available? Where is it documented? */
432 typedef struct in_str {
434 /* eof_flag=1: last char in ->p is really an EOF */
435 char eof_flag; /* meaningless if ->p == NULL */
437 #if ENABLE_HUSH_INTERACTIVE
439 smallint promptmode; /* 0: PS1, 1: PS2 */
442 int (*get) (struct in_str *) FAST_FUNC;
443 int (*peek) (struct in_str *) FAST_FUNC;
445 #define i_getch(input) ((input)->get(input))
446 #define i_peek(input) ((input)->peek(input))
448 /* The descrip member of this structure is only used to make
449 * debugging output pretty */
450 static const struct {
452 signed char default_fd;
455 { O_RDONLY, 0, "<" },
456 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
457 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
458 { O_CREAT|O_RDWR, 1, "<>" },
459 { O_RDONLY, 0, "<<" },
460 /* Should not be needed. Bogus default_fd helps in debugging */
461 /* { O_RDONLY, 77, "<<" }, */
464 struct redir_struct {
465 struct redir_struct *next;
466 char *rd_filename; /* filename */
467 int rd_fd; /* fd to redirect */
468 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
470 smallint rd_type; /* (enum redir_type) */
471 /* note: for heredocs, rd_filename contains heredoc delimiter,
472 * and subsequently heredoc itself; and rd_dup is a bitmask:
473 * bit 0: do we need to trim leading tabs?
474 * bit 1: is heredoc quoted (<<'delim' syntax) ?
477 typedef enum redir_type {
479 REDIRECT_OVERWRITE = 1,
482 REDIRECT_HEREDOC = 4,
483 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
486 REDIRFD_SYNTAX_ERR = -2,
487 REDIRFD_TO_FILE = -1,
488 /* otherwise, rd_fd is redirected to rd_dup */
490 HEREDOC_SKIPTABS = 1,
496 pid_t pid; /* 0 if exited */
497 int assignment_cnt; /* how many argv[i] are assignments? */
498 smallint is_stopped; /* is the command currently running? */
499 smallint cmd_type; /* CMD_xxx */
501 #define CMD_SUBSHELL 1
502 #if ENABLE_HUSH_BASH_COMPAT
503 /* used for "[[ EXPR ]]" */
504 # define CMD_SINGLEWORD_NOGLOB 2
506 #if ENABLE_HUSH_FUNCTIONS
507 # define CMD_FUNCDEF 3
510 smalluint cmd_exitcode;
511 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
514 char *group_as_string;
516 #if ENABLE_HUSH_FUNCTIONS
517 struct function *child_func;
518 /* This field is used to prevent a bug here:
519 * while...do f1() {a;}; f1; f1() {b;}; f1; done
520 * When we execute "f1() {a;}" cmd, we create new function and clear
521 * cmd->group, cmd->group_as_string, cmd->argv[0].
522 * When we execute "f1() {b;}", we notice that f1 exists,
523 * and that its "parent cmd" struct is still "alive",
524 * we put those fields back into cmd->xxx
525 * (struct function has ->parent_cmd ptr to facilitate that).
526 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
527 * Without this trick, loop would execute a;b;b;b;...
528 * instead of correct sequence a;b;a;b;...
529 * When command is freed, it severs the link
530 * (sets ->child_func->parent_cmd to NULL).
533 char **argv; /* command name and arguments */
534 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
535 * and on execution these are substituted with their values.
536 * Substitution can make _several_ words out of one argv[n]!
537 * Example: argv[0]=='.^C*^C.' here: echo .$*.
538 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
540 struct redir_struct *redirects; /* I/O redirections */
542 /* Is there anything in this command at all? */
543 #define IS_NULL_CMD(cmd) \
544 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
549 int num_cmds; /* total number of commands in pipe */
550 int alive_cmds; /* number of commands running (not exited) */
551 int stopped_cmds; /* number of commands alive, but stopped */
553 int jobid; /* job number */
554 pid_t pgrp; /* process group ID for the job */
555 char *cmdtext; /* name of job */
557 struct command *cmds; /* array of commands in pipe */
558 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
559 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
560 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
562 typedef enum pipe_style {
568 /* Is there anything in this pipe at all? */
569 #define IS_NULL_PIPE(pi) \
570 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
572 /* This holds pointers to the various results of parsing */
573 struct parse_context {
574 /* linked list of pipes */
575 struct pipe *list_head;
576 /* last pipe (being constructed right now) */
578 /* last command in pipe (being constructed right now) */
579 struct command *command;
580 /* last redirect in command->redirects list */
581 struct redir_struct *pending_redirect;
587 smallint ctx_inverted; /* "! cmd | cmd" */
589 smallint ctx_dsemicolon; /* ";;" seen */
591 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
593 /* group we are enclosed in:
594 * example: "if pipe1; pipe2; then pipe3; fi"
595 * when we see "if" or "then", we malloc and copy current context,
596 * and make ->stack point to it. then we parse pipeN.
597 * when closing "then" / fi" / whatever is found,
598 * we move list_head into ->stack->command->group,
599 * copy ->stack into current context, and delete ->stack.
600 * (parsing of { list } and ( list ) doesn't use this method)
602 struct parse_context *stack;
606 /* On program start, environ points to initial environment.
607 * putenv adds new pointers into it, unsetenv removes them.
608 * Neither of these (de)allocates the strings.
609 * setenv allocates new strings in malloc space and does putenv,
610 * and thus setenv is unusable (leaky) for shell's purposes */
611 #define setenv(...) setenv_is_leaky_dont_use()
613 struct variable *next;
614 char *varstr; /* points to "name=" portion */
615 #if ENABLE_HUSH_LOCAL
616 unsigned func_nest_level;
618 int max_len; /* if > 0, name is part of initial env; else name is malloced */
619 smallint flg_export; /* putenv should be done on this var */
620 smallint flg_read_only;
628 #if ENABLE_HUSH_FUNCTIONS
630 struct function *next;
632 struct command *parent_cmd;
635 char *body_as_string;
641 /* set -/+o OPT support. (TODO: make it optional)
642 * bash supports the following opts:
653 * interactive-comments on
671 static const char o_opt_strings[] ALIGN1 = "pipefail\0";
678 /* "Globals" within this file */
679 /* Sorted roughly by size (smaller offsets == smaller code) */
681 /* interactive_fd != 0 means we are an interactive shell.
682 * If we are, then saved_tty_pgrp can also be != 0, meaning
683 * that controlling tty is available. With saved_tty_pgrp == 0,
684 * job control still works, but terminal signals
685 * (^C, ^Z, ^Y, ^\) won't work at all, and background
686 * process groups can only be created with "cmd &".
687 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
688 * to give tty to the foreground process group,
689 * and will take it back when the group is stopped (^Z)
692 #if ENABLE_HUSH_INTERACTIVE
693 /* 'interactive_fd' is a fd# open to ctty, if we have one
694 * _AND_ if we decided to act interactively */
698 # define G_interactive_fd (G.interactive_fd)
700 # define G_interactive_fd 0
702 #if ENABLE_FEATURE_EDITING
703 line_input_t *line_input_state;
708 #if ENABLE_HUSH_RANDOM_SUPPORT
714 pid_t saved_tty_pgrp;
715 struct pipe *job_list;
716 char o_opt[NUM_OPT_O];
717 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
719 # define G_saved_tty_pgrp 0
721 smallint flag_SIGINT;
722 #if ENABLE_HUSH_LOOPS
723 smallint flag_break_continue;
725 #if ENABLE_HUSH_FUNCTIONS
726 /* 0: outside of a function (or sourced file)
727 * -1: inside of a function, ok to use return builtin
728 * 1: return is invoked, skip all till end of func
730 smallint flag_return_in_progress;
733 #if ENABLE_HUSH_MODE_X
735 # define G_x_mode (G.x_mode)
739 smallint exiting; /* used to prevent EXIT trap recursion */
740 /* These four support $?, $#, and $1 */
741 smalluint last_exitcode;
742 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
743 smalluint global_args_malloced;
744 smalluint inherited_set_is_saved;
745 /* how many non-NULL argv's we have. NB: $# + 1 */
749 char *argv0_for_re_execing;
751 #if ENABLE_HUSH_LOOPS
752 unsigned depth_break_continue;
753 unsigned depth_of_loop;
757 struct variable *top_var;
758 char **expanded_assignments;
759 #if ENABLE_HUSH_FUNCTIONS
760 struct function *top_func;
761 # if ENABLE_HUSH_LOCAL
762 struct variable **shadowed_vars_pp;
763 unsigned func_nest_level;
766 /* Signal and trap handling */
768 unsigned count_SIGCHLD;
769 unsigned handled_SIGCHLD;
770 smallint we_have_children;
772 /* which signals have non-DFL handler (even with no traps set)? */
773 unsigned non_DFL_mask;
774 char **traps; /* char *traps[NSIG] */
775 sigset_t blocked_set;
776 sigset_t inherited_set;
778 unsigned long memleak_value;
781 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
783 #define G (*ptr_to_globals)
784 /* Not #defining name to G.name - this quickly gets unwieldy
785 * (too many defines). Also, I actually prefer to see when a variable
786 * is global, thus "G." prefix is a useful hint */
787 #define INIT_G() do { \
788 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
792 /* Function prototypes for builtins */
793 static int builtin_cd(char **argv) FAST_FUNC;
794 static int builtin_echo(char **argv) FAST_FUNC;
795 static int builtin_eval(char **argv) FAST_FUNC;
796 static int builtin_exec(char **argv) FAST_FUNC;
797 static int builtin_exit(char **argv) FAST_FUNC;
798 static int builtin_export(char **argv) FAST_FUNC;
800 static int builtin_fg_bg(char **argv) FAST_FUNC;
801 static int builtin_jobs(char **argv) FAST_FUNC;
804 static int builtin_help(char **argv) FAST_FUNC;
806 #if ENABLE_HUSH_LOCAL
807 static int builtin_local(char **argv) FAST_FUNC;
810 static int builtin_memleak(char **argv) FAST_FUNC;
813 static int builtin_printf(char **argv) FAST_FUNC;
815 static int builtin_pwd(char **argv) FAST_FUNC;
816 static int builtin_read(char **argv) FAST_FUNC;
817 static int builtin_set(char **argv) FAST_FUNC;
818 static int builtin_shift(char **argv) FAST_FUNC;
819 static int builtin_source(char **argv) FAST_FUNC;
820 static int builtin_test(char **argv) FAST_FUNC;
821 static int builtin_trap(char **argv) FAST_FUNC;
822 static int builtin_type(char **argv) FAST_FUNC;
823 static int builtin_true(char **argv) FAST_FUNC;
824 static int builtin_umask(char **argv) FAST_FUNC;
825 static int builtin_unset(char **argv) FAST_FUNC;
826 static int builtin_wait(char **argv) FAST_FUNC;
827 #if ENABLE_HUSH_LOOPS
828 static int builtin_break(char **argv) FAST_FUNC;
829 static int builtin_continue(char **argv) FAST_FUNC;
831 #if ENABLE_HUSH_FUNCTIONS
832 static int builtin_return(char **argv) FAST_FUNC;
835 /* Table of built-in functions. They can be forked or not, depending on
836 * context: within pipes, they fork. As simple commands, they do not.
837 * When used in non-forking context, they can change global variables
838 * in the parent shell process. If forked, of course they cannot.
839 * For example, 'unset foo | whatever' will parse and run, but foo will
840 * still be set at the end. */
841 struct built_in_command {
843 int (*b_function)(char **argv) FAST_FUNC;
846 # define BLTIN(cmd, func, help) { cmd, func, help }
848 # define BLTIN(cmd, func, help) { cmd, func }
852 static const struct built_in_command bltins1[] = {
853 BLTIN("." , builtin_source , "Run commands in a file"),
854 BLTIN(":" , builtin_true , NULL),
856 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
858 #if ENABLE_HUSH_LOOPS
859 BLTIN("break" , builtin_break , "Exit from a loop"),
861 BLTIN("cd" , builtin_cd , "Change directory"),
862 #if ENABLE_HUSH_LOOPS
863 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
865 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
866 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
867 BLTIN("exit" , builtin_exit , "Exit"),
868 BLTIN("export" , builtin_export , "Set environment variables"),
870 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
873 BLTIN("help" , builtin_help , NULL),
876 BLTIN("jobs" , builtin_jobs , "List jobs"),
878 #if ENABLE_HUSH_LOCAL
879 BLTIN("local" , builtin_local , "Set local variables"),
882 BLTIN("memleak" , builtin_memleak , NULL),
884 BLTIN("read" , builtin_read , "Input into variable"),
885 #if ENABLE_HUSH_FUNCTIONS
886 BLTIN("return" , builtin_return , "Return from a function"),
888 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
889 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
890 #if ENABLE_HUSH_BASH_COMPAT
891 BLTIN("source" , builtin_source , "Run commands in a file"),
893 BLTIN("trap" , builtin_trap , "Trap signals"),
894 BLTIN("type" , builtin_type , "Show command type"),
895 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
896 BLTIN("umask" , builtin_umask , "Set file creation mask"),
897 BLTIN("unset" , builtin_unset , "Unset variables"),
898 BLTIN("wait" , builtin_wait , "Wait for process"),
900 /* For now, echo and test are unconditionally enabled.
901 * Maybe make it configurable? */
902 static const struct built_in_command bltins2[] = {
903 BLTIN("[" , builtin_test , NULL),
904 BLTIN("echo" , builtin_echo , NULL),
906 BLTIN("printf" , builtin_printf , NULL),
908 BLTIN("pwd" , builtin_pwd , NULL),
909 BLTIN("test" , builtin_test , NULL),
916 /* prevent disasters with G.debug_indent < 0 */
917 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
918 # define debug_enter() (G.debug_indent++)
919 # define debug_leave() (G.debug_indent--)
921 # define indent() ((void)0)
922 # define debug_enter() ((void)0)
923 # define debug_leave() ((void)0)
927 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
930 #ifndef debug_printf_parse
931 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
934 #ifndef debug_printf_exec
935 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
938 #ifndef debug_printf_env
939 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
942 #ifndef debug_printf_jobs
943 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
944 # define DEBUG_JOBS 1
946 # define DEBUG_JOBS 0
949 #ifndef debug_printf_expand
950 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
951 # define DEBUG_EXPAND 1
953 # define DEBUG_EXPAND 0
956 #ifndef debug_printf_varexp
957 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
960 #ifndef debug_printf_glob
961 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
962 # define DEBUG_GLOB 1
964 # define DEBUG_GLOB 0
967 #ifndef debug_printf_list
968 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
971 #ifndef debug_printf_subst
972 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
975 #ifndef debug_printf_clean
976 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
977 # define DEBUG_CLEAN 1
979 # define DEBUG_CLEAN 0
983 static void debug_print_strings(const char *prefix, char **vv)
986 fprintf(stderr, "%s:\n", prefix);
988 fprintf(stderr, " '%s'\n", *vv++);
991 # define debug_print_strings(prefix, vv) ((void)0)
995 /* Leak hunting. Use hush_leaktool.sh for post-processing.
998 static void *xxmalloc(int lineno, size_t size)
1000 void *ptr = xmalloc((size + 0xff) & ~0xff);
1001 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1004 static void *xxrealloc(int lineno, void *ptr, size_t size)
1006 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1007 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1010 static char *xxstrdup(int lineno, const char *str)
1012 char *ptr = xstrdup(str);
1013 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1016 static void xxfree(void *ptr)
1018 fdprintf(2, "free %p\n", ptr);
1021 # define xmalloc(s) xxmalloc(__LINE__, s)
1022 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1023 # define xstrdup(s) xxstrdup(__LINE__, s)
1024 # define free(p) xxfree(p)
1028 /* Syntax and runtime errors. They always abort scripts.
1029 * In interactive use they usually discard unparsed and/or unexecuted commands
1030 * and return to the prompt.
1031 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1034 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1035 # define syntax_error(lineno, msg) syntax_error(msg)
1036 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1037 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1038 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1039 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1042 static void die_if_script(unsigned lineno, const char *fmt, ...)
1047 bb_error_msg("hush.c:%u", lineno);
1050 bb_verror_msg(fmt, p, NULL);
1052 if (!G_interactive_fd)
1056 static void syntax_error(unsigned lineno, const char *msg)
1059 die_if_script(lineno, "syntax error: %s", msg);
1061 die_if_script(lineno, "syntax error", NULL);
1064 static void syntax_error_at(unsigned lineno, const char *msg)
1066 die_if_script(lineno, "syntax error at '%s'", msg);
1069 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1071 die_if_script(lineno, "syntax error: unterminated %s", s);
1074 /* It so happens that all such cases are totally fatal
1075 * even if shell is interactive: EOF while looking for closing
1076 * delimiter. There is nowhere to read stuff from after that,
1077 * it's EOF! The only choice is to terminate.
1079 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1080 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1082 char msg[2] = { ch, '\0' };
1083 syntax_error_unterm_str(lineno, msg);
1087 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1092 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1096 # undef die_if_script
1097 # undef syntax_error
1098 # undef syntax_error_at
1099 # undef syntax_error_unterm_ch
1100 # undef syntax_error_unterm_str
1101 # undef syntax_error_unexpected_ch
1103 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1104 # define syntax_error(msg) syntax_error(__LINE__, msg)
1105 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1106 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1107 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1108 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1112 #if ENABLE_HUSH_INTERACTIVE
1113 static void cmdedit_update_prompt(void);
1115 # define cmdedit_update_prompt() ((void)0)
1119 /* Utility functions
1121 /* Replace each \x with x in place, return ptr past NUL. */
1122 static char *unbackslash(char *src)
1124 char *dst = src = strchrnul(src, '\\');
1128 if ((*dst++ = *src++) == '\0')
1134 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1155 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1156 v[count1 + count2] = NULL;
1159 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1163 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1165 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1166 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1169 #define add_strings_to_strings(strings, add, need_to_dup) \
1170 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1173 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1174 static char **add_string_to_strings(char **strings, char *add)
1179 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1182 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1184 char **ptr = add_string_to_strings(strings, add);
1185 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1188 #define add_string_to_strings(strings, add) \
1189 xx_add_string_to_strings(__LINE__, strings, add)
1192 static void free_strings(char **strings)
1207 /* Helpers for setting new $n and restoring them back
1209 typedef struct save_arg_t {
1213 smallint sv_g_malloced;
1216 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1220 sv->sv_argv0 = argv[0];
1221 sv->sv_g_argv = G.global_argv;
1222 sv->sv_g_argc = G.global_argc;
1223 sv->sv_g_malloced = G.global_args_malloced;
1225 argv[0] = G.global_argv[0]; /* retain $0 */
1226 G.global_argv = argv;
1227 G.global_args_malloced = 0;
1235 static void restore_G_args(save_arg_t *sv, char **argv)
1239 if (G.global_args_malloced) {
1240 /* someone ran "set -- arg1 arg2 ...", undo */
1242 while (*++pp) /* note: does not free $0 */
1244 free(G.global_argv);
1246 argv[0] = sv->sv_argv0;
1247 G.global_argv = sv->sv_g_argv;
1248 G.global_argc = sv->sv_g_argc;
1249 G.global_args_malloced = sv->sv_g_malloced;
1253 /* Basic theory of signal handling in shell
1254 * ========================================
1255 * This does not describe what hush does, rather, it is current understanding
1256 * what it _should_ do. If it doesn't, it's a bug.
1257 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1259 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1260 * is finished or backgrounded. It is the same in interactive and
1261 * non-interactive shells, and is the same regardless of whether
1262 * a user trap handler is installed or a shell special one is in effect.
1263 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1264 * backgrounds (i.e. stops) or kills all members of currently running
1267 * Wait builtin in interruptible by signals for which user trap is set
1268 * or by SIGINT in interactive shell.
1270 * Trap handlers will execute even within trap handlers. (right?)
1272 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1273 * except for handlers set to '' (empty string).
1275 * If job control is off, backgrounded commands ("cmd &")
1276 * have SIGINT, SIGQUIT set to SIG_IGN.
1278 * Commands which are run in command substitution ("`cmd`")
1279 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1281 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1282 * by the shell from its parent.
1284 * Signals which differ from SIG_DFL action
1285 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1288 * SIGTERM (interactive): ignore
1289 * SIGHUP (interactive):
1290 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1291 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1292 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1293 * that all pipe members are stopped. Try this in bash:
1294 * while :; do :; done - ^Z does not background it
1295 * (while :; do :; done) - ^Z backgrounds it
1296 * SIGINT (interactive): wait for last pipe, ignore the rest
1297 * of the command line, show prompt. NB: ^C does not send SIGINT
1298 * to interactive shell while shell is waiting for a pipe,
1299 * since shell is bg'ed (is not in foreground process group).
1300 * Example 1: this waits 5 sec, but does not execute ls:
1301 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1302 * Example 2: this does not wait and does not execute ls:
1303 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1304 * Example 3: this does not wait 5 sec, but executes ls:
1305 * "sleep 5; ls -l" + press ^C
1307 * (What happens to signals which are IGN on shell start?)
1308 * (What happens with signal mask on shell start?)
1310 * Implementation in hush
1311 * ======================
1312 * We use in-kernel pending signal mask to determine which signals were sent.
1313 * We block all signals which we don't want to take action immediately,
1314 * i.e. we block all signals which need to have special handling as described
1315 * above, and all signals which have traps set.
1316 * After each pipe execution, we extract any pending signals via sigtimedwait()
1319 * unsigned non_DFL_mask: a mask of such "special" signals
1320 * sigset_t blocked_set: current blocked signal set
1323 * clear bit in blocked_set unless it is also in non_DFL_mask
1324 * "trap 'cmd' SIGxxx":
1325 * set bit in blocked_set (even if 'cmd' is '')
1326 * after [v]fork, if we plan to be a shell:
1327 * unblock signals with special interactive handling
1328 * (child shell is not interactive),
1329 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1330 * after [v]fork, if we plan to exec:
1331 * POSIX says fork clears pending signal mask in child - no need to clear it.
1332 * Restore blocked signal set to one inherited by shell just prior to exec.
1334 * Note: as a result, we do not use signal handlers much. The only uses
1335 * are to count SIGCHLDs
1336 * and to restore tty pgrp on signal-induced exit.
1339 * Standard says "When a subshell is entered, traps that are not being ignored
1340 * are set to the default actions". bash interprets it so that traps which
1341 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1344 SPECIAL_INTERACTIVE_SIGS = 0
1349 SPECIAL_JOB_SIGS = 0
1357 #if ENABLE_HUSH_FAST
1358 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1361 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1367 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1368 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1369 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1370 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1372 /* Restores tty foreground process group, and exits.
1373 * May be called as signal handler for fatal signal
1374 * (will resend signal to itself, producing correct exit state)
1375 * or called directly with -EXITCODE.
1376 * We also call it if xfunc is exiting. */
1377 static void sigexit(int sig) NORETURN;
1378 static void sigexit(int sig)
1380 /* Disable all signals: job control, SIGPIPE, etc. */
1381 sigprocmask_allsigs(SIG_BLOCK);
1383 /* Careful: we can end up here after [v]fork. Do not restore
1384 * tty pgrp then, only top-level shell process does that */
1385 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1386 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1388 /* Not a signal, just exit */
1392 kill_myself_with_sig(sig); /* does not return */
1396 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1397 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1401 /* Restores tty foreground process group, and exits. */
1402 static void hush_exit(int exitcode) NORETURN;
1403 static void hush_exit(int exitcode)
1405 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1406 /* Prevent recursion:
1407 * trap "echo Hi; exit" EXIT; exit
1410 /* argv[0] is unused */
1411 argv[1] = G.traps[0];
1413 G.exiting = 1; /* prevent EXIT trap recursion */
1414 /* Note: G.traps[0] is not cleared!
1415 * "trap" will still show it, if executed
1422 sigexit(- (exitcode & 0xff));
1429 static int check_and_run_traps(int sig)
1431 /* I want it in rodata, not in bss.
1432 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1433 * initializer. But other compilers may still use bss.
1434 * TODO: find more portable solution.
1436 static const struct timespec zero_timespec = { 0, 0 };
1437 smalluint save_rcode;
1443 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1448 if (G.traps && G.traps[sig]) {
1449 if (G.traps[sig][0]) {
1450 /* We have user-defined handler */
1452 /* argv[0] is unused */
1453 argv[1] = G.traps[sig];
1455 save_rcode = G.last_exitcode;
1457 G.last_exitcode = save_rcode;
1458 } /* else: "" trap, ignoring signal */
1461 /* not a trap: special action */
1463 #if ENABLE_HUSH_FAST
1466 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1470 /* Builtin was ^C'ed, make it look prettier: */
1477 /* bash is observed to signal whole process groups,
1478 * not individual processes */
1479 for (job = G.job_list; job; job = job->next) {
1482 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1483 if (kill(- job->pgrp, SIGHUP) == 0)
1484 kill(- job->pgrp, SIGCONT);
1489 default: /* ignored: */
1490 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1498 static const char *get_cwd(int force)
1500 if (force || G.cwd == NULL) {
1501 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1502 * we must not try to free(bb_msg_unknown) */
1503 if (G.cwd == bb_msg_unknown)
1505 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1507 G.cwd = bb_msg_unknown;
1514 * Shell and environment variable support
1516 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1518 struct variable **pp;
1519 struct variable *cur;
1522 while ((cur = *pp) != NULL) {
1523 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1530 static const char* FAST_FUNC get_local_var_value(const char *name)
1532 struct variable **vpp;
1533 unsigned len = strlen(name);
1535 if (G.expanded_assignments) {
1536 char **cpp = G.expanded_assignments;
1539 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1540 return cp + len + 1;
1545 vpp = get_ptr_to_local_var(name, len);
1547 return (*vpp)->varstr + len + 1;
1549 if (strcmp(name, "PPID") == 0)
1550 return utoa(G.root_ppid);
1551 // bash compat: UID? EUID?
1552 #if ENABLE_HUSH_RANDOM_SUPPORT
1553 if (strcmp(name, "RANDOM") == 0)
1554 return utoa(next_random(&G.random_gen));
1559 /* str holds "NAME=VAL" and is expected to be malloced.
1560 * We take ownership of it.
1562 * 0: do not change export flag
1563 * (if creating new variable, flag will be 0)
1564 * 1: set export flag and putenv the variable
1565 * -1: clear export flag and unsetenv the variable
1566 * flg_read_only is set only when we handle -R var=val
1568 #if !BB_MMU && ENABLE_HUSH_LOCAL
1569 /* all params are used */
1570 #elif BB_MMU && ENABLE_HUSH_LOCAL
1571 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1572 set_local_var(str, flg_export, local_lvl)
1573 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1574 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1575 set_local_var(str, flg_export)
1576 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1577 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1578 set_local_var(str, flg_export, flg_read_only)
1580 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1582 struct variable **var_pp;
1583 struct variable *cur;
1587 eq_sign = strchr(str, '=');
1588 if (!eq_sign) { /* not expected to ever happen? */
1593 name_len = eq_sign - str + 1; /* including '=' */
1594 var_pp = &G.top_var;
1595 while ((cur = *var_pp) != NULL) {
1596 if (strncmp(cur->varstr, str, name_len) != 0) {
1597 var_pp = &cur->next;
1600 /* We found an existing var with this name */
1601 if (cur->flg_read_only) {
1605 bb_error_msg("%s: readonly variable", str);
1609 if (flg_export == -1) { // "&& cur->flg_export" ?
1610 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1615 #if ENABLE_HUSH_LOCAL
1616 if (cur->func_nest_level < local_lvl) {
1617 /* New variable is declared as local,
1618 * and existing one is global, or local
1619 * from enclosing function.
1620 * Remove and save old one: */
1621 *var_pp = cur->next;
1622 cur->next = *G.shadowed_vars_pp;
1623 *G.shadowed_vars_pp = cur;
1624 /* bash 3.2.33(1) and exported vars:
1626 * # f() { local z=a; env | grep ^z; }
1632 if (cur->flg_export)
1637 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1642 if (cur->max_len != 0) {
1643 if (cur->max_len >= strlen(str)) {
1644 /* This one is from startup env, reuse space */
1645 strcpy(cur->varstr, str);
1649 /* max_len == 0 signifies "malloced" var, which we can
1650 * (and has to) free */
1654 goto set_str_and_exp;
1657 /* Not found - create new variable struct */
1658 cur = xzalloc(sizeof(*cur));
1659 #if ENABLE_HUSH_LOCAL
1660 cur->func_nest_level = local_lvl;
1662 cur->next = *var_pp;
1668 cur->flg_read_only = flg_read_only;
1671 if (flg_export == 1)
1672 cur->flg_export = 1;
1673 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1674 cmdedit_update_prompt();
1675 if (cur->flg_export) {
1676 if (flg_export == -1) {
1677 cur->flg_export = 0;
1678 /* unsetenv was already done */
1680 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1681 return putenv(cur->varstr);
1687 /* Used at startup and after each cd */
1688 static void set_pwd_var(int exp)
1690 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1691 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1694 static int unset_local_var_len(const char *name, int name_len)
1696 struct variable *cur;
1697 struct variable **var_pp;
1700 return EXIT_SUCCESS;
1701 var_pp = &G.top_var;
1702 while ((cur = *var_pp) != NULL) {
1703 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1704 if (cur->flg_read_only) {
1705 bb_error_msg("%s: readonly variable", name);
1706 return EXIT_FAILURE;
1708 *var_pp = cur->next;
1709 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1710 bb_unsetenv(cur->varstr);
1711 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1712 cmdedit_update_prompt();
1716 return EXIT_SUCCESS;
1718 var_pp = &cur->next;
1720 return EXIT_SUCCESS;
1723 static int unset_local_var(const char *name)
1725 return unset_local_var_len(name, strlen(name));
1728 static void unset_vars(char **strings)
1736 const char *eq = strchrnul(*v, '=');
1737 unset_local_var_len(*v, (int)(eq - *v));
1743 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1745 char *var = xasprintf("%s=%s", name, val);
1746 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1751 * Helpers for "var1=val1 var2=val2 cmd" feature
1753 static void add_vars(struct variable *var)
1755 struct variable *next;
1759 var->next = G.top_var;
1761 if (var->flg_export) {
1762 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1763 putenv(var->varstr);
1765 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1771 static struct variable *set_vars_and_save_old(char **strings)
1774 struct variable *old = NULL;
1780 struct variable *var_p;
1781 struct variable **var_pp;
1784 eq = strchr(*s, '=');
1786 var_pp = get_ptr_to_local_var(*s, eq - *s);
1788 /* Remove variable from global linked list */
1790 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1791 *var_pp = var_p->next;
1792 /* Add it to returned list */
1796 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1807 static int FAST_FUNC static_get(struct in_str *i)
1817 static int FAST_FUNC static_peek(struct in_str *i)
1822 #if ENABLE_HUSH_INTERACTIVE
1824 static void cmdedit_update_prompt(void)
1826 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1827 G.PS1 = get_local_var_value("PS1");
1830 G.PS2 = get_local_var_value("PS2");
1838 static const char *setup_prompt_string(int promptmode)
1840 const char *prompt_str;
1841 debug_printf("setup_prompt_string %d ", promptmode);
1842 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1843 /* Set up the prompt */
1844 if (promptmode == 0) { /* PS1 */
1846 /* bash uses $PWD value, even if it is set by user.
1847 * It uses current dir only if PWD is unset.
1848 * We always use current dir. */
1849 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1854 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1855 debug_printf("result '%s'\n", prompt_str);
1859 static void get_user_input(struct in_str *i)
1862 const char *prompt_str;
1864 prompt_str = setup_prompt_string(i->promptmode);
1865 # if ENABLE_FEATURE_EDITING
1866 /* Enable command line editing only while a command line
1867 * is actually being read */
1870 /* buglet: SIGINT will not make new prompt to appear _at once_,
1871 * only after <Enter>. (^C will work) */
1872 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1873 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1874 check_and_run_traps(0);
1875 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1876 i->eof_flag = (r < 0);
1877 if (i->eof_flag) { /* EOF/error detected */
1878 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1879 G.user_input_buf[1] = '\0';
1884 fputs(prompt_str, stdout);
1886 G.user_input_buf[0] = r = fgetc(i->file);
1887 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1888 //do we need check_and_run_traps(0)? (maybe only if stdin)
1889 } while (G.flag_SIGINT);
1890 i->eof_flag = (r == EOF);
1892 i->p = G.user_input_buf;
1895 #endif /* INTERACTIVE */
1897 /* This is the magic location that prints prompts
1898 * and gets data back from the user */
1899 static int FAST_FUNC file_get(struct in_str *i)
1903 /* If there is data waiting, eat it up */
1904 if (i->p && *i->p) {
1905 #if ENABLE_HUSH_INTERACTIVE
1909 if (i->eof_flag && !*i->p)
1911 /* note: ch is never NUL */
1913 /* need to double check i->file because we might be doing something
1914 * more complicated by now, like sourcing or substituting. */
1915 #if ENABLE_HUSH_INTERACTIVE
1916 if (G_interactive_fd && i->promptme && i->file == stdin) {
1919 } while (!*i->p); /* need non-empty line */
1920 i->promptmode = 1; /* PS2 */
1925 do ch = fgetc(i->file); while (ch == '\0');
1927 debug_printf("file_get: got '%c' %d\n", ch, ch);
1928 #if ENABLE_HUSH_INTERACTIVE
1935 /* All callers guarantee this routine will never
1936 * be used right after a newline, so prompting is not needed.
1938 static int FAST_FUNC file_peek(struct in_str *i)
1941 if (i->p && *i->p) {
1942 if (i->eof_flag && !i->p[1])
1945 /* note: ch is never NUL */
1947 do ch = fgetc(i->file); while (ch == '\0');
1948 i->eof_flag = (ch == EOF);
1949 i->peek_buf[0] = ch;
1950 i->peek_buf[1] = '\0';
1952 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1956 static void setup_file_in_str(struct in_str *i, FILE *f)
1958 i->peek = file_peek;
1960 #if ENABLE_HUSH_INTERACTIVE
1962 i->promptmode = 0; /* PS1 */
1968 static void setup_string_in_str(struct in_str *i, const char *s)
1970 i->peek = static_peek;
1971 i->get = static_get;
1972 #if ENABLE_HUSH_INTERACTIVE
1974 i->promptmode = 0; /* PS1 */
1984 #define B_CHUNK (32 * sizeof(char*))
1986 static void o_reset_to_empty_unquoted(o_string *o)
1989 o->has_quoted_part = 0;
1994 static void o_free(o_string *o)
1997 memset(o, 0, sizeof(*o));
2000 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2005 static void o_grow_by(o_string *o, int len)
2007 if (o->length + len > o->maxlen) {
2008 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2009 o->data = xrealloc(o->data, 1 + o->maxlen);
2013 static void o_addchr(o_string *o, int ch)
2015 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2017 o->data[o->length] = ch;
2019 o->data[o->length] = '\0';
2022 static void o_addblock(o_string *o, const char *str, int len)
2025 memcpy(&o->data[o->length], str, len);
2027 o->data[o->length] = '\0';
2030 static void o_addstr(o_string *o, const char *str)
2032 o_addblock(o, str, strlen(str));
2036 static void nommu_addchr(o_string *o, int ch)
2042 # define nommu_addchr(o, str) ((void)0)
2045 static void o_addstr_with_NUL(o_string *o, const char *str)
2047 o_addblock(o, str, strlen(str) + 1);
2051 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2052 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2053 * Apparently, on unquoted $v bash still does globbing
2054 * ("v='*.txt'; echo $v" prints all .txt files),
2055 * but NOT brace expansion! Thus, there should be TWO independent
2056 * quoting mechanisms on $v expansion side: one protects
2057 * $v from brace expansion, and other additionally protects "$v" against globbing.
2058 * We have only second one.
2061 #if ENABLE_HUSH_BRACE_EXPANSION
2062 # define MAYBE_BRACES "{}"
2064 # define MAYBE_BRACES ""
2067 /* My analysis of quoting semantics tells me that state information
2068 * is associated with a destination, not a source.
2070 static void o_addqchr(o_string *o, int ch)
2073 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2078 o->data[o->length] = '\\';
2081 o->data[o->length] = ch;
2083 o->data[o->length] = '\0';
2086 static void o_addQchr(o_string *o, int ch)
2089 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2090 && strchr("*?[\\" MAYBE_BRACES, ch)
2093 o->data[o->length] = '\\';
2097 o->data[o->length] = ch;
2099 o->data[o->length] = '\0';
2102 static void o_addqblock(o_string *o, const char *str, int len)
2107 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2108 if (ordinary_cnt > len) /* paranoia */
2110 o_addblock(o, str, ordinary_cnt);
2111 if (ordinary_cnt == len)
2113 str += ordinary_cnt;
2114 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2118 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2120 o->data[o->length] = '\\';
2124 o->data[o->length] = ch;
2126 o->data[o->length] = '\0';
2130 static void o_addQblock(o_string *o, const char *str, int len)
2132 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2133 o_addblock(o, str, len);
2136 o_addqblock(o, str, len);
2139 static void o_addQstr(o_string *o, const char *str)
2141 o_addQblock(o, str, strlen(str));
2144 /* A special kind of o_string for $VAR and `cmd` expansion.
2145 * It contains char* list[] at the beginning, which is grown in 16 element
2146 * increments. Actual string data starts at the next multiple of 16 * (char*).
2147 * list[i] contains an INDEX (int!) into this string data.
2148 * It means that if list[] needs to grow, data needs to be moved higher up
2149 * but list[i]'s need not be modified.
2150 * NB: remembering how many list[i]'s you have there is crucial.
2151 * o_finalize_list() operation post-processes this structure - calculates
2152 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2154 #if DEBUG_EXPAND || DEBUG_GLOB
2155 static void debug_print_list(const char *prefix, o_string *o, int n)
2157 char **list = (char**)o->data;
2158 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2162 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2163 prefix, list, n, string_start, o->length, o->maxlen,
2164 !!(o->o_expflags & EXP_FLAG_GLOB),
2166 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2169 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2170 o->data + (int)list[i] + string_start,
2171 o->data + (int)list[i] + string_start);
2175 const char *p = o->data + (int)list[n - 1] + string_start;
2177 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2181 # define debug_print_list(prefix, o, n) ((void)0)
2184 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2185 * in list[n] so that it points past last stored byte so far.
2186 * It returns n+1. */
2187 static int o_save_ptr_helper(o_string *o, int n)
2189 char **list = (char**)o->data;
2193 if (!o->has_empty_slot) {
2194 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2195 string_len = o->length - string_start;
2196 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2197 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2198 /* list[n] points to string_start, make space for 16 more pointers */
2199 o->maxlen += 0x10 * sizeof(list[0]);
2200 o->data = xrealloc(o->data, o->maxlen + 1);
2201 list = (char**)o->data;
2202 memmove(list + n + 0x10, list + n, string_len);
2203 o->length += 0x10 * sizeof(list[0]);
2205 debug_printf_list("list[%d]=%d string_start=%d\n",
2206 n, string_len, string_start);
2209 /* We have empty slot at list[n], reuse without growth */
2210 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2211 string_len = o->length - string_start;
2212 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2213 n, string_len, string_start);
2214 o->has_empty_slot = 0;
2216 list[n] = (char*)(uintptr_t)string_len;
2220 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2221 static int o_get_last_ptr(o_string *o, int n)
2223 char **list = (char**)o->data;
2224 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2226 return ((int)(uintptr_t)list[n-1]) + string_start;
2229 #if ENABLE_HUSH_BRACE_EXPANSION
2230 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2231 * first, it processes even {a} (no commas), second,
2232 * I didn't manage to make it return strings when they don't match
2233 * existing files. Need to re-implement it.
2237 static int glob_needed(const char *s)
2246 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2252 /* Return pointer to next closing brace or to comma */
2253 static const char *next_brace_sub(const char *cp)
2257 while (*cp != '\0') {
2264 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2270 return *cp != '\0' ? cp : NULL;
2272 /* Recursive brace globber. Note: may garble pattern[]. */
2273 static int glob_brace(char *pattern, o_string *o, int n)
2275 char *new_pattern_buf;
2282 debug_printf_glob("glob_brace('%s')\n", pattern);
2288 if (*begin == '{') {
2289 /* Find the first sub-pattern and at the same time
2290 * find the rest after the closing brace */
2291 next = next_brace_sub(begin);
2293 /* An illegal expression */
2297 /* "{abc}" with no commas - illegal
2298 * brace expr, disregard and skip it */
2304 if (*begin == '\\' && begin[1] != '\0')
2308 debug_printf_glob("begin:%s\n", begin);
2309 debug_printf_glob("next:%s\n", next);
2311 /* Now find the end of the whole brace expression */
2313 while (*rest != '}') {
2314 rest = next_brace_sub(rest);
2316 /* An illegal expression */
2319 debug_printf_glob("rest:%s\n", rest);
2321 rest_len = strlen(++rest) + 1;
2323 /* We are sure the brace expression is well-formed */
2325 /* Allocate working buffer large enough for our work */
2326 new_pattern_buf = xmalloc(strlen(pattern));
2328 /* We have a brace expression. BEGIN points to the opening {,
2329 * NEXT points past the terminator of the first element, and REST
2330 * points past the final }. We will accumulate result names from
2331 * recursive runs for each brace alternative in the buffer using
2336 /* Construct the new glob expression */
2339 mempcpy(new_pattern_buf,
2340 /* We know the prefix for all sub-patterns */
2341 pattern, begin - pattern),
2345 /* Note: glob_brace() may garble new_pattern_buf[].
2346 * That's why we re-copy prefix every time (1st memcpy above).
2348 n = glob_brace(new_pattern_buf, o, n);
2350 /* We saw the last entry */
2354 next = next_brace_sub(next);
2356 free(new_pattern_buf);
2364 memset(&globdata, 0, sizeof(globdata));
2365 gr = glob(pattern, 0, NULL, &globdata);
2366 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2368 if (gr == GLOB_NOMATCH) {
2369 globfree(&globdata);
2370 /* NB: garbles parameter */
2371 unbackslash(pattern);
2372 o_addstr_with_NUL(o, pattern);
2373 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2374 return o_save_ptr_helper(o, n);
2376 if (gr == GLOB_NOSPACE)
2377 bb_error_msg_and_die(bb_msg_memory_exhausted);
2378 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2379 * but we didn't specify it. Paranoia again. */
2380 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2382 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2383 char **argv = globdata.gl_pathv;
2385 o_addstr_with_NUL(o, *argv);
2386 n = o_save_ptr_helper(o, n);
2392 globfree(&globdata);
2396 /* Performs globbing on last list[],
2397 * saving each result as a new list[].
2399 static int perform_glob(o_string *o, int n)
2401 char *pattern, *copy;
2403 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2405 return o_save_ptr_helper(o, n);
2406 pattern = o->data + o_get_last_ptr(o, n);
2407 debug_printf_glob("glob pattern '%s'\n", pattern);
2408 if (!glob_needed(pattern)) {
2409 /* unbackslash last string in o in place, fix length */
2410 o->length = unbackslash(pattern) - o->data;
2411 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2412 return o_save_ptr_helper(o, n);
2415 copy = xstrdup(pattern);
2416 /* "forget" pattern in o */
2417 o->length = pattern - o->data;
2418 n = glob_brace(copy, o, n);
2421 debug_print_list("perform_glob returning", o, n);
2425 #else /* !HUSH_BRACE_EXPANSION */
2428 static int glob_needed(const char *s)
2437 if (*s == '*' || *s == '[' || *s == '?')
2443 /* Performs globbing on last list[],
2444 * saving each result as a new list[].
2446 static int perform_glob(o_string *o, int n)
2452 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2454 return o_save_ptr_helper(o, n);
2455 pattern = o->data + o_get_last_ptr(o, n);
2456 debug_printf_glob("glob pattern '%s'\n", pattern);
2457 if (!glob_needed(pattern)) {
2459 /* unbackslash last string in o in place, fix length */
2460 o->length = unbackslash(pattern) - o->data;
2461 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2462 return o_save_ptr_helper(o, n);
2465 memset(&globdata, 0, sizeof(globdata));
2466 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2467 * If we glob "*.\*" and don't find anything, we need
2468 * to fall back to using literal "*.*", but GLOB_NOCHECK
2469 * will return "*.\*"!
2471 gr = glob(pattern, 0, NULL, &globdata);
2472 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2474 if (gr == GLOB_NOMATCH) {
2475 globfree(&globdata);
2478 if (gr == GLOB_NOSPACE)
2479 bb_error_msg_and_die(bb_msg_memory_exhausted);
2480 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2481 * but we didn't specify it. Paranoia again. */
2482 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2484 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2485 char **argv = globdata.gl_pathv;
2486 /* "forget" pattern in o */
2487 o->length = pattern - o->data;
2489 o_addstr_with_NUL(o, *argv);
2490 n = o_save_ptr_helper(o, n);
2496 globfree(&globdata);
2498 debug_print_list("perform_glob returning", o, n);
2502 #endif /* !HUSH_BRACE_EXPANSION */
2504 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2505 * Otherwise, just finish current list[] and start new */
2506 static int o_save_ptr(o_string *o, int n)
2508 if (o->o_expflags & EXP_FLAG_GLOB) {
2509 /* If o->has_empty_slot, list[n] was already globbed
2510 * (if it was requested back then when it was filled)
2511 * so don't do that again! */
2512 if (!o->has_empty_slot)
2513 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2515 return o_save_ptr_helper(o, n);
2518 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2519 static char **o_finalize_list(o_string *o, int n)
2524 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2526 debug_print_list("finalized", o, n);
2527 debug_printf_expand("finalized n:%d\n", n);
2528 list = (char**)o->data;
2529 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2533 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2538 static void free_pipe_list(struct pipe *pi);
2540 /* Returns pi->next - next pipe in the list */
2541 static struct pipe *free_pipe(struct pipe *pi)
2546 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2547 for (i = 0; i < pi->num_cmds; i++) {
2548 struct command *command;
2549 struct redir_struct *r, *rnext;
2551 command = &pi->cmds[i];
2552 debug_printf_clean(" command %d:\n", i);
2553 if (command->argv) {
2557 for (a = 0, p = command->argv; *p; a++, p++) {
2558 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2561 free_strings(command->argv);
2562 //command->argv = NULL;
2564 /* not "else if": on syntax error, we may have both! */
2565 if (command->group) {
2566 debug_printf_clean(" begin group (cmd_type:%d)\n",
2568 free_pipe_list(command->group);
2569 debug_printf_clean(" end group\n");
2570 //command->group = NULL;
2572 /* else is crucial here.
2573 * If group != NULL, child_func is meaningless */
2574 #if ENABLE_HUSH_FUNCTIONS
2575 else if (command->child_func) {
2576 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2577 command->child_func->parent_cmd = NULL;
2581 free(command->group_as_string);
2582 //command->group_as_string = NULL;
2584 for (r = command->redirects; r; r = rnext) {
2585 debug_printf_clean(" redirect %d%s",
2586 r->rd_fd, redir_table[r->rd_type].descrip);
2587 /* guard against the case >$FOO, where foo is unset or blank */
2588 if (r->rd_filename) {
2589 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2590 free(r->rd_filename);
2591 //r->rd_filename = NULL;
2593 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2597 //command->redirects = NULL;
2599 free(pi->cmds); /* children are an array, they get freed all at once */
2603 //pi->cmdtext = NULL;
2611 static void free_pipe_list(struct pipe *pi)
2615 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2617 debug_printf_clean("pipe followup code %d\n", pi->followup);
2623 /*** Parsing routines ***/
2625 static struct pipe *new_pipe(void)
2628 pi = xzalloc(sizeof(struct pipe));
2629 /*pi->followup = 0; - deliberately invalid value */
2630 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2634 /* Command (member of a pipe) is complete, or we start a new pipe
2635 * if ctx->command is NULL.
2636 * No errors possible here.
2638 static int done_command(struct parse_context *ctx)
2640 /* The command is really already in the pipe structure, so
2641 * advance the pipe counter and make a new, null command. */
2642 struct pipe *pi = ctx->pipe;
2643 struct command *command = ctx->command;
2646 if (IS_NULL_CMD(command)) {
2647 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2651 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2652 //debug_print_tree(ctx->list_head, 20);
2654 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2657 /* Only real trickiness here is that the uncommitted
2658 * command structure is not counted in pi->num_cmds. */
2659 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2660 ctx->command = command = &pi->cmds[pi->num_cmds];
2662 memset(command, 0, sizeof(*command));
2663 return pi->num_cmds; /* used only for 0/nonzero check */
2666 static void done_pipe(struct parse_context *ctx, pipe_style type)
2670 debug_printf_parse("done_pipe entered, followup %d\n", type);
2671 /* Close previous command */
2672 not_null = done_command(ctx);
2673 ctx->pipe->followup = type;
2675 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2676 ctx->ctx_inverted = 0;
2677 ctx->pipe->res_word = ctx->ctx_res_w;
2680 /* Without this check, even just <enter> on command line generates
2681 * tree of three NOPs (!). Which is harmless but annoying.
2682 * IOW: it is safe to do it unconditionally. */
2685 || ctx->ctx_res_w == RES_FI
2687 #if ENABLE_HUSH_LOOPS
2688 || ctx->ctx_res_w == RES_DONE
2689 || ctx->ctx_res_w == RES_FOR
2690 || ctx->ctx_res_w == RES_IN
2692 #if ENABLE_HUSH_CASE
2693 || ctx->ctx_res_w == RES_ESAC
2697 debug_printf_parse("done_pipe: adding new pipe: "
2698 "not_null:%d ctx->ctx_res_w:%d\n",
2699 not_null, ctx->ctx_res_w);
2701 ctx->pipe->next = new_p;
2703 /* RES_THEN, RES_DO etc are "sticky" -
2704 * they remain set for pipes inside if/while.
2705 * This is used to control execution.
2706 * RES_FOR and RES_IN are NOT sticky (needed to support
2707 * cases where variable or value happens to match a keyword):
2709 #if ENABLE_HUSH_LOOPS
2710 if (ctx->ctx_res_w == RES_FOR
2711 || ctx->ctx_res_w == RES_IN)
2712 ctx->ctx_res_w = RES_NONE;
2714 #if ENABLE_HUSH_CASE
2715 if (ctx->ctx_res_w == RES_MATCH)
2716 ctx->ctx_res_w = RES_CASE_BODY;
2717 if (ctx->ctx_res_w == RES_CASE)
2718 ctx->ctx_res_w = RES_CASE_IN;
2720 ctx->command = NULL; /* trick done_command below */
2721 /* Create the memory for command, roughly:
2722 * ctx->pipe->cmds = new struct command;
2723 * ctx->command = &ctx->pipe->cmds[0];
2726 //debug_print_tree(ctx->list_head, 10);
2728 debug_printf_parse("done_pipe return\n");
2731 static void initialize_context(struct parse_context *ctx)
2733 memset(ctx, 0, sizeof(*ctx));
2734 ctx->pipe = ctx->list_head = new_pipe();
2735 /* Create the memory for command, roughly:
2736 * ctx->pipe->cmds = new struct command;
2737 * ctx->command = &ctx->pipe->cmds[0];
2742 /* If a reserved word is found and processed, parse context is modified
2743 * and 1 is returned.
2746 struct reserved_combo {
2749 unsigned char assignment_flag;
2753 FLAG_END = (1 << RES_NONE ),
2755 FLAG_IF = (1 << RES_IF ),
2756 FLAG_THEN = (1 << RES_THEN ),
2757 FLAG_ELIF = (1 << RES_ELIF ),
2758 FLAG_ELSE = (1 << RES_ELSE ),
2759 FLAG_FI = (1 << RES_FI ),
2761 # if ENABLE_HUSH_LOOPS
2762 FLAG_FOR = (1 << RES_FOR ),
2763 FLAG_WHILE = (1 << RES_WHILE),
2764 FLAG_UNTIL = (1 << RES_UNTIL),
2765 FLAG_DO = (1 << RES_DO ),
2766 FLAG_DONE = (1 << RES_DONE ),
2767 FLAG_IN = (1 << RES_IN ),
2769 # if ENABLE_HUSH_CASE
2770 FLAG_MATCH = (1 << RES_MATCH),
2771 FLAG_ESAC = (1 << RES_ESAC ),
2773 FLAG_START = (1 << RES_XXXX ),
2776 static const struct reserved_combo* match_reserved_word(o_string *word)
2778 /* Mostly a list of accepted follow-up reserved words.
2779 * FLAG_END means we are done with the sequence, and are ready
2780 * to turn the compound list into a command.
2781 * FLAG_START means the word must start a new compound list.
2783 static const struct reserved_combo reserved_list[] = {
2785 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2786 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2787 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2788 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2789 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2790 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2792 # if ENABLE_HUSH_LOOPS
2793 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2794 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2795 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2796 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2797 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2798 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2800 # if ENABLE_HUSH_CASE
2801 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2802 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2805 const struct reserved_combo *r;
2807 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2808 if (strcmp(word->data, r->literal) == 0)
2813 /* Return 0: not a keyword, 1: keyword
2815 static int reserved_word(o_string *word, struct parse_context *ctx)
2817 # if ENABLE_HUSH_CASE
2818 static const struct reserved_combo reserved_match = {
2819 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2822 const struct reserved_combo *r;
2824 if (word->has_quoted_part)
2826 r = match_reserved_word(word);
2830 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2831 # if ENABLE_HUSH_CASE
2832 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2833 /* "case word IN ..." - IN part starts first MATCH part */
2834 r = &reserved_match;
2837 if (r->flag == 0) { /* '!' */
2838 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2839 syntax_error("! ! command");
2840 ctx->ctx_res_w = RES_SNTX;
2842 ctx->ctx_inverted = 1;
2845 if (r->flag & FLAG_START) {
2846 struct parse_context *old;
2848 old = xmalloc(sizeof(*old));
2849 debug_printf_parse("push stack %p\n", old);
2850 *old = *ctx; /* physical copy */
2851 initialize_context(ctx);
2853 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2854 syntax_error_at(word->data);
2855 ctx->ctx_res_w = RES_SNTX;
2858 /* "{...} fi" is ok. "{...} if" is not
2860 * if { echo foo; } then { echo bar; } fi */
2861 if (ctx->command->group)
2862 done_pipe(ctx, PIPE_SEQ);
2865 ctx->ctx_res_w = r->res;
2866 ctx->old_flag = r->flag;
2867 word->o_assignment = r->assignment_flag;
2869 if (ctx->old_flag & FLAG_END) {
2870 struct parse_context *old;
2872 done_pipe(ctx, PIPE_SEQ);
2873 debug_printf_parse("pop stack %p\n", ctx->stack);
2875 old->command->group = ctx->list_head;
2876 old->command->cmd_type = CMD_NORMAL;
2878 o_addstr(&old->as_string, ctx->as_string.data);
2879 o_free_unsafe(&ctx->as_string);
2880 old->command->group_as_string = xstrdup(old->as_string.data);
2881 debug_printf_parse("pop, remembering as:'%s'\n",
2882 old->command->group_as_string);
2884 *ctx = *old; /* physical copy */
2889 #endif /* HAS_KEYWORDS */
2891 /* Word is complete, look at it and update parsing context.
2892 * Normal return is 0. Syntax errors return 1.
2893 * Note: on return, word is reset, but not o_free'd!
2895 static int done_word(o_string *word, struct parse_context *ctx)
2897 struct command *command = ctx->command;
2899 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2900 if (word->length == 0 && !word->has_quoted_part) {
2901 debug_printf_parse("done_word return 0: true null, ignored\n");
2905 if (ctx->pending_redirect) {
2906 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2907 * only if run as "bash", not "sh" */
2908 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2910 * ...the word that follows the redirection operator
2911 * shall be subjected to tilde expansion, parameter expansion,
2912 * command substitution, arithmetic expansion, and quote
2913 * removal. Pathname expansion shall not be performed
2914 * on the word by a non-interactive shell; an interactive
2915 * shell may perform it, but shall do so only when
2916 * the expansion would result in one word."
2918 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2919 /* Cater for >\file case:
2920 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2921 * Same with heredocs:
2922 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2924 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2925 unbackslash(ctx->pending_redirect->rd_filename);
2926 /* Is it <<"HEREDOC"? */
2927 if (word->has_quoted_part) {
2928 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2931 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2932 ctx->pending_redirect = NULL;
2934 /* If this word wasn't an assignment, next ones definitely
2935 * can't be assignments. Even if they look like ones. */
2936 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2937 && word->o_assignment != WORD_IS_KEYWORD
2939 word->o_assignment = NOT_ASSIGNMENT;
2941 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2942 command->assignment_cnt++;
2943 word->o_assignment = MAYBE_ASSIGNMENT;
2947 # if ENABLE_HUSH_CASE
2948 if (ctx->ctx_dsemicolon
2949 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2951 /* already done when ctx_dsemicolon was set to 1: */
2952 /* ctx->ctx_res_w = RES_MATCH; */
2953 ctx->ctx_dsemicolon = 0;
2956 if (!command->argv /* if it's the first word... */
2957 # if ENABLE_HUSH_LOOPS
2958 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2959 && ctx->ctx_res_w != RES_IN
2961 # if ENABLE_HUSH_CASE
2962 && ctx->ctx_res_w != RES_CASE
2965 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2966 if (reserved_word(word, ctx)) {
2967 o_reset_to_empty_unquoted(word);
2968 debug_printf_parse("done_word return %d\n",
2969 (ctx->ctx_res_w == RES_SNTX));
2970 return (ctx->ctx_res_w == RES_SNTX);
2972 # if ENABLE_HUSH_BASH_COMPAT
2973 if (strcmp(word->data, "[[") == 0) {
2974 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2980 if (command->group) {
2981 /* "{ echo foo; } echo bar" - bad */
2982 syntax_error_at(word->data);
2983 debug_printf_parse("done_word return 1: syntax error, "
2984 "groups and arglists don't mix\n");
2987 if (word->has_quoted_part
2988 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2989 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2990 /* (otherwise it's known to be not empty and is already safe) */
2992 /* exclude "$@" - it can expand to no word despite "" */
2993 char *p = word->data;
2994 while (p[0] == SPECIAL_VAR_SYMBOL
2995 && (p[1] & 0x7f) == '@'
2996 && p[2] == SPECIAL_VAR_SYMBOL
3000 if (p == word->data || p[0] != '\0') {
3001 /* saw no "$@", or not only "$@" but some
3002 * real text is there too */
3003 /* insert "empty variable" reference, this makes
3004 * e.g. "", $empty"" etc to not disappear */
3005 o_addchr(word, SPECIAL_VAR_SYMBOL);
3006 o_addchr(word, SPECIAL_VAR_SYMBOL);
3009 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3010 debug_print_strings("word appended to argv", command->argv);
3013 #if ENABLE_HUSH_LOOPS
3014 if (ctx->ctx_res_w == RES_FOR) {
3015 if (word->has_quoted_part
3016 || !is_well_formed_var_name(command->argv[0], '\0')
3018 /* bash says just "not a valid identifier" */
3019 syntax_error("not a valid identifier in for");
3022 /* Force FOR to have just one word (variable name) */
3023 /* NB: basically, this makes hush see "for v in ..."
3024 * syntax as if it is "for v; in ...". FOR and IN become
3025 * two pipe structs in parse tree. */
3026 done_pipe(ctx, PIPE_SEQ);
3029 #if ENABLE_HUSH_CASE
3030 /* Force CASE to have just one word */
3031 if (ctx->ctx_res_w == RES_CASE) {
3032 done_pipe(ctx, PIPE_SEQ);
3036 o_reset_to_empty_unquoted(word);
3038 debug_printf_parse("done_word return 0\n");
3043 /* Peek ahead in the input to find out if we have a "&n" construct,
3044 * as in "2>&1", that represents duplicating a file descriptor.
3046 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3047 * REDIRFD_SYNTAX_ERR if syntax error,
3048 * REDIRFD_TO_FILE if no & was seen,
3049 * or the number found.
3052 #define parse_redir_right_fd(as_string, input) \
3053 parse_redir_right_fd(input)
3055 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3061 return REDIRFD_TO_FILE;
3063 ch = i_getch(input); /* get the & */
3064 nommu_addchr(as_string, ch);
3067 ch = i_getch(input);
3068 nommu_addchr(as_string, ch);
3069 return REDIRFD_CLOSE;
3073 while (ch != EOF && isdigit(ch)) {
3074 d = d*10 + (ch-'0');
3076 ch = i_getch(input);
3077 nommu_addchr(as_string, ch);
3082 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3084 bb_error_msg("ambiguous redirect");
3085 return REDIRFD_SYNTAX_ERR;
3088 /* Return code is 0 normal, 1 if a syntax error is detected
3090 static int parse_redirect(struct parse_context *ctx,
3093 struct in_str *input)
3095 struct command *command = ctx->command;
3096 struct redir_struct *redir;
3097 struct redir_struct **redirp;
3100 dup_num = REDIRFD_TO_FILE;
3101 if (style != REDIRECT_HEREDOC) {
3102 /* Check for a '>&1' type redirect */
3103 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3104 if (dup_num == REDIRFD_SYNTAX_ERR)
3107 int ch = i_peek(input);
3108 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3109 if (dup_num) { /* <<-... */
3110 ch = i_getch(input);
3111 nommu_addchr(&ctx->as_string, ch);
3116 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3117 int ch = i_peek(input);
3119 /* >|FILE redirect ("clobbering" >).
3120 * Since we do not support "set -o noclobber" yet,
3121 * >| and > are the same for now. Just eat |.
3123 ch = i_getch(input);
3124 nommu_addchr(&ctx->as_string, ch);
3128 /* Create a new redir_struct and append it to the linked list */
3129 redirp = &command->redirects;
3130 while ((redir = *redirp) != NULL) {
3131 redirp = &(redir->next);
3133 *redirp = redir = xzalloc(sizeof(*redir));
3134 /* redir->next = NULL; */
3135 /* redir->rd_filename = NULL; */
3136 redir->rd_type = style;
3137 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3139 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3140 redir_table[style].descrip);
3142 redir->rd_dup = dup_num;
3143 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3144 /* Erik had a check here that the file descriptor in question
3145 * is legit; I postpone that to "run time"
3146 * A "-" representation of "close me" shows up as a -3 here */
3147 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3148 redir->rd_fd, redir->rd_dup);
3150 /* Set ctx->pending_redirect, so we know what to do at the
3151 * end of the next parsed word. */
3152 ctx->pending_redirect = redir;
3157 /* If a redirect is immediately preceded by a number, that number is
3158 * supposed to tell which file descriptor to redirect. This routine
3159 * looks for such preceding numbers. In an ideal world this routine
3160 * needs to handle all the following classes of redirects...
3161 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3162 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3163 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3164 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3166 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3168 * ... If n is quoted, the number shall not be recognized as part of
3169 * the redirection expression. For example:
3171 * writes the character 2 into file a"
3172 * We are getting it right by setting ->has_quoted_part on any \<char>
3174 * A -1 return means no valid number was found,
3175 * the caller should use the appropriate default for this redirection.
3177 static int redirect_opt_num(o_string *o)
3181 if (o->data == NULL)
3183 num = bb_strtou(o->data, NULL, 10);
3184 if (errno || num < 0)
3186 o_reset_to_empty_unquoted(o);
3191 #define fetch_till_str(as_string, input, word, skip_tabs) \
3192 fetch_till_str(input, word, skip_tabs)
3194 static char *fetch_till_str(o_string *as_string,
3195 struct in_str *input,
3199 o_string heredoc = NULL_O_STRING;
3201 int prev = 0; /* not \ */
3206 ch = i_getch(input);
3208 nommu_addchr(as_string, ch);
3209 if ((ch == '\n' || ch == EOF)
3210 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3212 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3213 heredoc.data[past_EOL] = '\0';
3214 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3215 return heredoc.data;
3217 while (ch == '\n') {
3218 o_addchr(&heredoc, ch);
3221 past_EOL = heredoc.length;
3223 ch = i_getch(input);
3225 nommu_addchr(as_string, ch);
3226 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3230 o_free_unsafe(&heredoc);
3233 o_addchr(&heredoc, ch);
3234 nommu_addchr(as_string, ch);
3235 if (prev == '\\' && ch == '\\')
3236 /* Correctly handle foo\\<eol> (not a line cont.) */
3237 prev = 0; /* not \ */
3243 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3244 * and load them all. There should be exactly heredoc_cnt of them.
3246 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3248 struct pipe *pi = ctx->list_head;
3250 while (pi && heredoc_cnt) {
3252 struct command *cmd = pi->cmds;
3254 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3256 cmd->argv ? cmd->argv[0] : "NONE");
3257 for (i = 0; i < pi->num_cmds; i++) {
3258 struct redir_struct *redir = cmd->redirects;
3260 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3261 i, cmd->argv ? cmd->argv[0] : "NONE");
3263 if (redir->rd_type == REDIRECT_HEREDOC) {
3266 redir->rd_type = REDIRECT_HEREDOC2;
3267 /* redir->rd_dup is (ab)used to indicate <<- */
3268 p = fetch_till_str(&ctx->as_string, input,
3269 redir->rd_filename, redir->rd_dup);
3271 syntax_error("unexpected EOF in here document");
3274 free(redir->rd_filename);
3275 redir->rd_filename = p;
3278 redir = redir->next;
3285 /* Should be 0. If it isn't, it's a parse error */
3287 bb_error_msg_and_die("heredoc BUG 2");
3293 static int run_list(struct pipe *pi);
3295 #define parse_stream(pstring, input, end_trigger) \
3296 parse_stream(input, end_trigger)
3298 static struct pipe *parse_stream(char **pstring,
3299 struct in_str *input,
3303 #if !ENABLE_HUSH_FUNCTIONS
3304 #define parse_group(dest, ctx, input, ch) \
3305 parse_group(ctx, input, ch)
3307 static int parse_group(o_string *dest, struct parse_context *ctx,
3308 struct in_str *input, int ch)
3310 /* dest contains characters seen prior to ( or {.
3311 * Typically it's empty, but for function defs,
3312 * it contains function name (without '()'). */
3313 struct pipe *pipe_list;
3315 struct command *command = ctx->command;
3317 debug_printf_parse("parse_group entered\n");
3318 #if ENABLE_HUSH_FUNCTIONS
3319 if (ch == '(' && !dest->has_quoted_part) {
3321 if (done_word(dest, ctx))
3324 goto skip; /* (... */
3325 if (command->argv[1]) { /* word word ... (... */
3326 syntax_error_unexpected_ch('(');
3329 /* it is "word(..." or "word (..." */
3331 ch = i_getch(input);
3332 while (ch == ' ' || ch == '\t');
3334 syntax_error_unexpected_ch(ch);
3337 nommu_addchr(&ctx->as_string, ch);
3339 ch = i_getch(input);
3340 while (ch == ' ' || ch == '\t' || ch == '\n');
3342 syntax_error_unexpected_ch(ch);
3345 nommu_addchr(&ctx->as_string, ch);
3346 command->cmd_type = CMD_FUNCDEF;
3351 #if 0 /* Prevented by caller */
3352 if (command->argv /* word [word]{... */
3353 || dest->length /* word{... */
3354 || dest->has_quoted_part /* ""{... */
3357 debug_printf_parse("parse_group return 1: "
3358 "syntax error, groups and arglists don't mix\n");
3363 #if ENABLE_HUSH_FUNCTIONS
3369 command->cmd_type = CMD_SUBSHELL;
3371 /* bash does not allow "{echo...", requires whitespace */
3372 ch = i_getch(input);
3373 if (ch != ' ' && ch != '\t' && ch != '\n') {
3374 syntax_error_unexpected_ch(ch);
3377 nommu_addchr(&ctx->as_string, ch);
3382 # define as_string NULL
3384 char *as_string = NULL;
3386 pipe_list = parse_stream(&as_string, input, endch);
3389 o_addstr(&ctx->as_string, as_string);
3391 /* empty ()/{} or parse error? */
3392 if (!pipe_list || pipe_list == ERR_PTR) {
3393 /* parse_stream already emitted error msg */
3396 debug_printf_parse("parse_group return 1: "
3397 "parse_stream returned %p\n", pipe_list);
3400 command->group = pipe_list;
3402 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3403 command->group_as_string = as_string;
3404 debug_printf_parse("end of group, remembering as:'%s'\n",
3405 command->group_as_string);
3409 debug_printf_parse("parse_group return 0\n");
3411 /* command remains "open", available for possible redirects */
3414 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3415 /* Subroutines for copying $(...) and `...` things */
3416 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3418 static void add_till_single_quote(o_string *dest, struct in_str *input)
3421 int ch = i_getch(input);
3423 syntax_error_unterm_ch('\'');
3424 /*xfunc_die(); - redundant */
3431 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3432 static void add_till_double_quote(o_string *dest, struct in_str *input)
3435 int ch = i_getch(input);
3437 syntax_error_unterm_ch('"');
3438 /*xfunc_die(); - redundant */
3442 if (ch == '\\') { /* \x. Copy both chars. */
3444 ch = i_getch(input);
3448 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3452 //if (ch == '$') ...
3455 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3457 * "Within the backquoted style of command substitution, backslash
3458 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3459 * The search for the matching backquote shall be satisfied by the first
3460 * backquote found without a preceding backslash; during this search,
3461 * if a non-escaped backquote is encountered within a shell comment,
3462 * a here-document, an embedded command substitution of the $(command)
3463 * form, or a quoted string, undefined results occur. A single-quoted
3464 * or double-quoted string that begins, but does not end, within the
3465 * "`...`" sequence produces undefined results."
3467 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3469 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3472 int ch = i_getch(input);
3476 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3477 ch = i_getch(input);
3481 && (!in_dquote || ch != '"')
3483 o_addchr(dest, '\\');
3487 syntax_error_unterm_ch('`');
3488 /*xfunc_die(); - redundant */
3493 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3494 * quoting and nested ()s.
3495 * "With the $(command) style of command substitution, all characters
3496 * following the open parenthesis to the matching closing parenthesis
3497 * constitute the command. Any valid shell script can be used for command,
3498 * except a script consisting solely of redirections which produces
3499 * unspecified results."
3501 * echo $(echo '(TEST)' BEST) (TEST) BEST
3502 * echo $(echo 'TEST)' BEST) TEST) BEST
3503 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3505 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3506 * can contain arbitrary constructs, just like $(cmd).
3507 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3508 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3510 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3511 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3514 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3515 # if ENABLE_HUSH_BASH_COMPAT
3516 char end_char2 = end_ch >> 8;
3518 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3521 ch = i_getch(input);
3523 syntax_error_unterm_ch(end_ch);
3524 /*xfunc_die(); - redundant */
3526 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3529 /* we look for closing )) of $((EXPR)) */
3530 if (i_peek(input) == end_ch) {
3531 i_getch(input); /* eat second ')' */
3536 if (ch == '(' || ch == '{') {
3537 ch = (ch == '(' ? ')' : '}');
3538 add_till_closing_bracket(dest, input, ch);
3543 add_till_single_quote(dest, input);
3548 add_till_double_quote(dest, input);
3553 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3558 /* \x. Copy verbatim. Important for \(, \) */
3559 ch = i_getch(input);
3561 syntax_error_unterm_ch(')');
3562 /*xfunc_die(); - redundant */
3570 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3572 /* Return code: 0 for OK, 1 for syntax error */
3574 #define parse_dollar(as_string, dest, input, quote_mask) \
3575 parse_dollar(dest, input, quote_mask)
3576 #define as_string NULL
3578 static int parse_dollar(o_string *as_string,
3580 struct in_str *input, unsigned char quote_mask)
3582 int ch = i_peek(input); /* first character after the $ */
3584 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3586 ch = i_getch(input);
3587 nommu_addchr(as_string, ch);
3589 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3591 debug_printf_parse(": '%c'\n", ch);
3592 o_addchr(dest, ch | quote_mask);
3595 if (!isalnum(ch) && ch != '_')
3597 ch = i_getch(input);
3598 nommu_addchr(as_string, ch);
3600 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3601 } else if (isdigit(ch)) {
3603 ch = i_getch(input);
3604 nommu_addchr(as_string, ch);
3605 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3606 debug_printf_parse(": '%c'\n", ch);
3607 o_addchr(dest, ch | quote_mask);
3608 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3609 } else switch (ch) {
3611 case '!': /* last bg pid */
3612 case '?': /* last exit code */
3613 case '#': /* number of args */
3614 case '*': /* args */
3615 case '@': /* args */
3616 goto make_one_char_var;
3618 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3620 ch = i_getch(input); /* eat '{' */
3621 nommu_addchr(as_string, ch);
3623 ch = i_getch(input); /* first char after '{' */
3624 /* It should be ${?}, or ${#var},
3625 * or even ${?+subst} - operator acting on a special variable,
3626 * or the beginning of variable name.
3629 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3632 syntax_error_unterm_str("${name}");
3633 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3636 nommu_addchr(as_string, ch);
3639 /* It's possible to just call add_till_closing_bracket() at this point.
3640 * However, this regresses some of our testsuite cases
3641 * which check invalid constructs like ${%}.
3642 * Oh well... let's check that the var name part is fine... */
3648 debug_printf_parse(": '%c'\n", ch);
3650 ch = i_getch(input);
3651 nommu_addchr(as_string, ch);
3655 if (!isalnum(ch) && ch != '_') {
3657 unsigned char last_ch;
3658 /* handle parameter expansions
3659 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3661 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3662 goto bad_dollar_syntax;
3664 /* Eat everything until closing '}' (or ':') */
3666 if (ENABLE_HUSH_BASH_COMPAT
3668 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3670 /* It's ${var:N[:M]} thing */
3671 end_ch = '}' * 0x100 + ':';
3673 if (ENABLE_HUSH_BASH_COMPAT
3676 /* It's ${var/[/]pattern[/repl]} thing */
3677 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3679 nommu_addchr(as_string, '/');
3682 end_ch = '}' * 0x100 + '/';
3688 #if ENABLE_HUSH_DOLLAR_OPS
3689 last_ch = add_till_closing_bracket(dest, input, end_ch);
3691 #error Simple code to only allow ${var} is not implemented
3694 o_addstr(as_string, dest->data + pos);
3695 o_addchr(as_string, last_ch);
3698 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3699 /* close the first block: */
3700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3701 /* while parsing N from ${var:N[:M]}
3702 * or pattern from ${var/[/]pattern[/repl]} */
3703 if ((end_ch & 0xff) == last_ch) {
3704 /* got ':' or '/'- parse the rest */
3709 if (end_ch == '}' * 0x100 + ':') {
3710 /* it's ${var:N} - emulate :999999999 */
3711 o_addstr(dest, "999999999");
3712 } /* else: it's ${var/[/]pattern} */
3717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3724 ch = i_getch(input);
3725 nommu_addchr(as_string, ch);
3726 # if ENABLE_SH_MATH_SUPPORT
3727 if (i_peek(input) == '(') {
3728 ch = i_getch(input);
3729 nommu_addchr(as_string, ch);
3730 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3731 o_addchr(dest, /*quote_mask |*/ '+');
3734 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3736 o_addstr(as_string, dest->data + pos);
3737 o_addchr(as_string, ')');
3738 o_addchr(as_string, ')');
3740 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3744 # if ENABLE_HUSH_TICK
3745 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3746 o_addchr(dest, quote_mask | '`');
3749 add_till_closing_bracket(dest, input, ')');
3751 o_addstr(as_string, dest->data + pos);
3752 o_addchr(as_string, ')');
3754 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3760 ch = i_getch(input);
3761 nommu_addchr(as_string, ch);
3763 if (isalnum(ch)) { /* it's $_name or $_123 */
3768 /* TODO: $_ and $-: */
3769 /* $_ Shell or shell script name; or last argument of last command
3770 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3771 * but in command's env, set to full pathname used to invoke it */
3772 /* $- Option flags set by set builtin or shell options (-i etc) */
3774 o_addQchr(dest, '$');
3776 debug_printf_parse("parse_dollar return 0\n");
3782 # if ENABLE_HUSH_BASH_COMPAT
3783 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3784 encode_string(dest, input, dquote_end, process_bkslash)
3786 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3787 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3788 encode_string(dest, input, dquote_end)
3790 #define as_string NULL
3794 # if ENABLE_HUSH_BASH_COMPAT
3795 /* all parameters are needed, no macro tricks */
3797 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3798 encode_string(as_string, dest, input, dquote_end)
3801 static int encode_string(o_string *as_string,
3803 struct in_str *input,
3805 int process_bkslash)
3807 #if !ENABLE_HUSH_BASH_COMPAT
3808 const int process_bkslash = 1;
3814 ch = i_getch(input);
3816 nommu_addchr(as_string, ch);
3817 if (ch == dquote_end) { /* may be only '"' or EOF */
3818 debug_printf_parse("encode_string return 0\n");
3821 /* note: can't move it above ch == dquote_end check! */
3823 syntax_error_unterm_ch('"');
3824 /*xfunc_die(); - redundant */
3828 next = i_peek(input);
3830 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3831 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3832 if (process_bkslash && ch == '\\') {
3834 syntax_error("\\<eof>");
3838 * "The backslash retains its special meaning [in "..."]
3839 * only when followed by one of the following characters:
3840 * $, `, ", \, or <newline>. A double quote may be quoted
3841 * within double quotes by preceding it with a backslash."
3842 * NB: in (unquoted) heredoc, above does not apply to ",
3843 * therefore we check for it by "next == dquote_end" cond.
3845 if (next == dquote_end || strchr("$`\\\n", next)) {
3846 ch = i_getch(input); /* eat next */
3848 goto again; /* skip \<newline> */
3849 } /* else: ch remains == '\\', and we double it below: */
3850 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3851 nommu_addchr(as_string, ch);
3855 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3856 debug_printf_parse("encode_string return 1: "
3857 "parse_dollar returned non-0\n");
3862 #if ENABLE_HUSH_TICK
3864 //unsigned pos = dest->length;
3865 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3866 o_addchr(dest, 0x80 | '`');
3867 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3868 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3869 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3873 o_addQchr(dest, ch);
3879 * Scan input until EOF or end_trigger char.
3880 * Return a list of pipes to execute, or NULL on EOF
3881 * or if end_trigger character is met.
3882 * On syntax error, exit is shell is not interactive,
3883 * reset parsing machinery and start parsing anew,
3884 * or return ERR_PTR.
3886 static struct pipe *parse_stream(char **pstring,
3887 struct in_str *input,
3890 struct parse_context ctx;
3891 o_string dest = NULL_O_STRING;
3894 /* Single-quote triggers a bypass of the main loop until its mate is
3895 * found. When recursing, quote state is passed in via dest->o_expflags.
3897 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3898 end_trigger ? end_trigger : 'X');
3901 /* If very first arg is "" or '', dest.data may end up NULL.
3902 * Preventing this: */
3903 o_addchr(&dest, '\0');
3906 /* We used to separate words on $IFS here. This was wrong.
3907 * $IFS is used only for word splitting when $var is expanded,
3908 * here we should use blank chars as separators, not $IFS
3911 reset: /* we come back here only on syntax errors in interactive shell */
3913 #if ENABLE_HUSH_INTERACTIVE
3914 input->promptmode = 0; /* PS1 */
3916 if (MAYBE_ASSIGNMENT != 0)
3917 dest.o_assignment = MAYBE_ASSIGNMENT;
3918 initialize_context(&ctx);
3921 const char *is_blank;
3922 const char *is_special;
3926 redir_type redir_style;
3928 ch = i_getch(input);
3929 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3930 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3935 syntax_error_unterm_str("here document");
3938 /* end_trigger == '}' case errors out earlier,
3939 * checking only ')' */
3940 if (end_trigger == ')') {
3941 syntax_error_unterm_ch('('); /* exits */
3942 /* goto parse_error; */
3945 if (done_word(&dest, &ctx)) {
3949 done_pipe(&ctx, PIPE_SEQ);
3951 /* If we got nothing... */
3952 /* (this makes bare "&" cmd a no-op.
3953 * bash says: "syntax error near unexpected token '&'") */
3954 if (pi->num_cmds == 0
3955 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3961 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3963 *pstring = ctx.as_string.data;
3965 o_free_unsafe(&ctx.as_string);
3968 debug_printf_parse("parse_stream return %p\n", pi);
3971 nommu_addchr(&ctx.as_string, ch);
3975 next = i_peek(input);
3977 is_special = "{}<>;&|()#'" /* special outside of "str" */
3978 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3979 /* Are { and } special here? */
3980 if (ctx.command->argv /* word [word]{... - non-special */
3981 || dest.length /* word{... - non-special */
3982 || dest.has_quoted_part /* ""{... - non-special */
3983 || (next != ';' /* }; - special */
3984 && next != ')' /* }) - special */
3985 && next != '&' /* }& and }&& ... - special */
3986 && next != '|' /* }|| ... - special */
3987 && !strchr(defifs, next) /* {word - non-special */
3990 /* They are not special, skip "{}" */
3993 is_special = strchr(is_special, ch);
3994 is_blank = strchr(defifs, ch);
3996 if (!is_special && !is_blank) { /* ordinary char */
3998 o_addQchr(&dest, ch);
3999 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4000 || dest.o_assignment == WORD_IS_KEYWORD)
4002 && is_well_formed_var_name(dest.data, '=')
4004 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4010 if (done_word(&dest, &ctx)) {
4014 #if ENABLE_HUSH_CASE
4015 /* "case ... in <newline> word) ..." -
4016 * newlines are ignored (but ';' wouldn't be) */
4017 if (ctx.command->argv == NULL
4018 && ctx.ctx_res_w == RES_MATCH
4023 /* Treat newline as a command separator. */
4024 done_pipe(&ctx, PIPE_SEQ);
4025 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4027 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4032 dest.o_assignment = MAYBE_ASSIGNMENT;
4034 /* note: if (is_blank) continue;
4035 * will still trigger for us */
4039 /* "cmd}" or "cmd }..." without semicolon or &:
4040 * } is an ordinary char in this case, even inside { cmd; }
4041 * Pathological example: { ""}; } should exec "}" cmd
4044 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4045 || dest.length != 0 /* word} */
4046 || dest.has_quoted_part /* ""} */
4050 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4051 goto skip_end_trigger;
4052 /* else: } does terminate a group */
4055 if (end_trigger && end_trigger == ch
4056 && (ch != ';' || heredoc_cnt == 0)
4057 #if ENABLE_HUSH_CASE
4059 || ctx.ctx_res_w != RES_MATCH
4060 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4065 /* This is technically valid:
4066 * { cat <<HERE; }; echo Ok
4070 * but we don't support this.
4071 * We require heredoc to be in enclosing {}/(),
4074 syntax_error_unterm_str("here document");
4077 if (done_word(&dest, &ctx)) {
4080 done_pipe(&ctx, PIPE_SEQ);
4081 dest.o_assignment = MAYBE_ASSIGNMENT;
4082 /* Do we sit outside of any if's, loops or case's? */
4084 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4088 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4090 *pstring = ctx.as_string.data;
4092 o_free_unsafe(&ctx.as_string);
4095 debug_printf_parse("parse_stream return %p: "
4096 "end_trigger char found\n",
4098 return ctx.list_head;
4105 /* Catch <, > before deciding whether this word is
4106 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4109 redir_fd = redirect_opt_num(&dest);
4110 if (done_word(&dest, &ctx)) {
4113 redir_style = REDIRECT_OVERWRITE;
4115 redir_style = REDIRECT_APPEND;
4116 ch = i_getch(input);
4117 nommu_addchr(&ctx.as_string, ch);
4120 else if (next == '(') {
4121 syntax_error(">(process) not supported");
4125 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4127 continue; /* back to top of while (1) */
4129 redir_fd = redirect_opt_num(&dest);
4130 if (done_word(&dest, &ctx)) {
4133 redir_style = REDIRECT_INPUT;
4135 redir_style = REDIRECT_HEREDOC;
4137 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4138 ch = i_getch(input);
4139 nommu_addchr(&ctx.as_string, ch);
4140 } else if (next == '>') {
4141 redir_style = REDIRECT_IO;
4142 ch = i_getch(input);
4143 nommu_addchr(&ctx.as_string, ch);
4146 else if (next == '(') {
4147 syntax_error("<(process) not supported");
4151 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4153 continue; /* back to top of while (1) */
4156 if (dest.o_assignment == MAYBE_ASSIGNMENT
4157 /* check that we are not in word in "a=1 2>word b=1": */
4158 && !ctx.pending_redirect
4160 /* ch is a special char and thus this word
4161 * cannot be an assignment */
4162 dest.o_assignment = NOT_ASSIGNMENT;
4165 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4169 if (dest.length == 0) {
4172 if (ch == EOF || ch == '\n')
4175 /* note: we do not add it to &ctx.as_string */
4177 nommu_addchr(&ctx.as_string, '\n');
4179 o_addQchr(&dest, ch);
4184 syntax_error("\\<eof>");
4187 ch = i_getch(input);
4189 o_addchr(&dest, '\\');
4190 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4191 o_addchr(&dest, ch);
4192 nommu_addchr(&ctx.as_string, ch);
4193 /* Example: echo Hello \2>file
4194 * we need to know that word 2 is quoted */
4195 dest.has_quoted_part = 1;
4199 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4200 ctx.as_string.data[--ctx.as_string.length] = '\0';
4205 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4206 debug_printf_parse("parse_stream parse error: "
4207 "parse_dollar returned non-0\n");
4212 dest.has_quoted_part = 1;
4214 ch = i_getch(input);
4216 syntax_error_unterm_ch('\'');
4217 /*xfunc_die(); - redundant */
4219 nommu_addchr(&ctx.as_string, ch);
4222 o_addqchr(&dest, ch);
4226 dest.has_quoted_part = 1;
4227 if (dest.o_assignment == NOT_ASSIGNMENT)
4228 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4229 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4231 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4233 #if ENABLE_HUSH_TICK
4237 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4238 o_addchr(&dest, '`');
4240 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4242 o_addstr(&ctx.as_string, dest.data + pos);
4243 o_addchr(&ctx.as_string, '`');
4245 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4246 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4251 #if ENABLE_HUSH_CASE
4254 if (done_word(&dest, &ctx)) {
4257 done_pipe(&ctx, PIPE_SEQ);
4258 #if ENABLE_HUSH_CASE
4259 /* Eat multiple semicolons, detect
4260 * whether it means something special */
4265 ch = i_getch(input);
4266 nommu_addchr(&ctx.as_string, ch);
4267 if (ctx.ctx_res_w == RES_CASE_BODY) {
4268 ctx.ctx_dsemicolon = 1;
4269 ctx.ctx_res_w = RES_MATCH;
4275 /* We just finished a cmd. New one may start
4276 * with an assignment */
4277 dest.o_assignment = MAYBE_ASSIGNMENT;
4280 if (done_word(&dest, &ctx)) {
4284 ch = i_getch(input);
4285 nommu_addchr(&ctx.as_string, ch);
4286 done_pipe(&ctx, PIPE_AND);
4288 done_pipe(&ctx, PIPE_BG);
4292 if (done_word(&dest, &ctx)) {
4295 #if ENABLE_HUSH_CASE
4296 if (ctx.ctx_res_w == RES_MATCH)
4297 break; /* we are in case's "word | word)" */
4299 if (next == '|') { /* || */
4300 ch = i_getch(input);
4301 nommu_addchr(&ctx.as_string, ch);
4302 done_pipe(&ctx, PIPE_OR);
4304 /* we could pick up a file descriptor choice here
4305 * with redirect_opt_num(), but bash doesn't do it.
4306 * "echo foo 2| cat" yields "foo 2". */
4309 o_reset_to_empty_unquoted(&ctx.as_string);
4314 #if ENABLE_HUSH_CASE
4315 /* "case... in [(]word)..." - skip '(' */
4316 if (ctx.ctx_res_w == RES_MATCH
4317 && ctx.command->argv == NULL /* not (word|(... */
4318 && dest.length == 0 /* not word(... */
4319 && dest.has_quoted_part == 0 /* not ""(... */
4325 if (parse_group(&dest, &ctx, input, ch) != 0) {
4330 #if ENABLE_HUSH_CASE
4331 if (ctx.ctx_res_w == RES_MATCH)
4335 /* proper use of this character is caught by end_trigger:
4336 * if we see {, we call parse_group(..., end_trigger='}')
4337 * and it will match } earlier (not here). */
4338 syntax_error_unexpected_ch(ch);
4342 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4348 struct parse_context *pctx;
4349 IF_HAS_KEYWORDS(struct parse_context *p2;)
4351 /* Clean up allocated tree.
4352 * Sample for finding leaks on syntax error recovery path.
4353 * Run it from interactive shell, watch pmap `pidof hush`.
4354 * while if false; then false; fi; do break; fi
4355 * Samples to catch leaks at execution:
4356 * while if (true | {true;}); then echo ok; fi; do break; done
4357 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4361 /* Update pipe/command counts,
4362 * otherwise freeing may miss some */
4363 done_pipe(pctx, PIPE_SEQ);
4364 debug_printf_clean("freeing list %p from ctx %p\n",
4365 pctx->list_head, pctx);
4366 debug_print_tree(pctx->list_head, 0);
4367 free_pipe_list(pctx->list_head);
4368 debug_printf_clean("freed list %p\n", pctx->list_head);
4370 o_free_unsafe(&pctx->as_string);
4372 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4376 IF_HAS_KEYWORDS(pctx = p2;)
4377 } while (HAS_KEYWORDS && pctx);
4378 /* Free text, clear all dest fields */
4380 /* If we are not in top-level parse, we return,
4381 * our caller will propagate error.
4383 if (end_trigger != ';') {
4391 /* Discard cached input, force prompt */
4393 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4399 /*** Execution routines ***/
4401 /* Expansion can recurse, need forward decls: */
4402 #if !ENABLE_HUSH_BASH_COMPAT
4403 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4404 #define expand_string_to_string(str, do_unbackslash) \
4405 expand_string_to_string(str)
4407 static char *expand_string_to_string(const char *str, int do_unbackslash);
4408 static int process_command_subs(o_string *dest, const char *s);
4410 /* expand_strvec_to_strvec() takes a list of strings, expands
4411 * all variable references within and returns a pointer to
4412 * a list of expanded strings, possibly with larger number
4413 * of strings. (Think VAR="a b"; echo $VAR).
4414 * This new list is allocated as a single malloc block.
4415 * NULL-terminated list of char* pointers is at the beginning of it,
4416 * followed by strings themselves.
4417 * Caller can deallocate entire list by single free(list). */
4419 /* A horde of its helpers come first: */
4421 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4423 while (--len >= 0) {
4426 #if ENABLE_HUSH_BRACE_EXPANSION
4427 if (c == '{' || c == '}') {
4428 /* { -> \{, } -> \} */
4430 /* And now we want to add { or } and continue:
4433 * luckily, just falling throught achieves this.
4439 /* \z -> \\\z; \<eol> -> \\<eol> */
4444 o_addchr(o, *str++);
4450 /* Store given string, finalizing the word and starting new one whenever
4451 * we encounter IFS char(s). This is used for expanding variable values.
4452 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4453 static int expand_on_ifs(o_string *output, int n, const char *str)
4456 int word_len = strcspn(str, G.ifs);
4458 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4459 o_addblock(output, str, word_len);
4461 /* Protect backslashes against globbing up :)
4462 * Example: "v='\*'; echo b$v" prints "b\*"
4463 * (and does not try to glob on "*")
4465 o_addblock_duplicate_backslash(output, str, word_len);
4466 /*/ Why can't we do it easier? */
4467 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4468 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4472 if (!*str) /* EOL - do not finalize word */
4474 o_addchr(output, '\0');
4475 debug_print_list("expand_on_ifs", output, n);
4476 n = o_save_ptr(output, n);
4477 str += strspn(str, G.ifs); /* skip ifs chars */
4479 debug_print_list("expand_on_ifs[1]", output, n);
4483 /* Helper to expand $((...)) and heredoc body. These act as if
4484 * they are in double quotes, with the exception that they are not :).
4485 * Just the rules are similar: "expand only $var and `cmd`"
4487 * Returns malloced string.
4488 * As an optimization, we return NULL if expansion is not needed.
4490 #if !ENABLE_HUSH_BASH_COMPAT
4491 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4492 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4493 encode_then_expand_string(str)
4495 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4498 struct in_str input;
4499 o_string dest = NULL_O_STRING;
4501 if (!strchr(str, '$')
4502 && !strchr(str, '\\')
4503 #if ENABLE_HUSH_TICK
4504 && !strchr(str, '`')
4510 /* We need to expand. Example:
4511 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4513 setup_string_in_str(&input, str);
4514 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4515 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4516 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4517 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4518 o_free_unsafe(&dest);
4522 #if ENABLE_SH_MATH_SUPPORT
4523 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4525 arith_state_t math_state;
4529 math_state.lookupvar = get_local_var_value;
4530 math_state.setvar = set_local_var_from_halves;
4531 //math_state.endofname = endofname;
4532 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4533 res = arith(&math_state, exp_str ? exp_str : arg);
4536 *errmsg_p = math_state.errmsg;
4537 if (math_state.errmsg)
4538 die_if_script(math_state.errmsg);
4543 #if ENABLE_HUSH_BASH_COMPAT
4544 /* ${var/[/]pattern[/repl]} helpers */
4545 static char *strstr_pattern(char *val, const char *pattern, int *size)
4548 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4549 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4556 /* Optimization: if "*pat" did not match the start of "string",
4557 * we know that "tring", "ring" etc will not match too:
4559 if (pattern[0] == '*')
4564 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4566 char *result = NULL;
4567 unsigned res_len = 0;
4568 unsigned repl_len = strlen(repl);
4572 char *s = strstr_pattern(val, pattern, &size);
4576 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4577 memcpy(result + res_len, val, s - val);
4579 strcpy(result + res_len, repl);
4580 res_len += repl_len;
4581 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4587 if (val[0] && result) {
4588 result = xrealloc(result, res_len + strlen(val) + 1);
4589 strcpy(result + res_len, val);
4590 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4592 debug_printf_varexp("result:'%s'\n", result);
4598 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4600 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4602 const char *val = NULL;
4603 char *to_be_freed = NULL;
4608 char exp_save = exp_save; /* for compiler */
4609 char *exp_saveptr; /* points to expansion operator */
4610 char *exp_word = exp_word; /* for compiler */
4613 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4615 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4617 first_char = arg[0] = arg0 & 0x7f;
4620 if (first_char == '#' /* ${#... */
4621 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4623 /* It must be length operator: ${#var} */
4627 /* Maybe handle parameter expansion */
4628 if (exp_saveptr /* if 2nd char is one of expansion operators */
4629 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4631 /* ${?:0}, ${#[:]%0} etc */
4632 exp_saveptr = var + 1;
4634 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4635 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4637 exp_op = exp_save = *exp_saveptr;
4639 exp_word = exp_saveptr + 1;
4640 if (exp_op == ':') {
4641 exp_op = *exp_word++;
4642 //TODO: try ${var:} and ${var:bogus} in non-bash config
4643 if (ENABLE_HUSH_BASH_COMPAT
4644 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4646 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4651 *exp_saveptr = '\0';
4652 } /* else: it's not an expansion op, but bare ${var} */
4655 /* Look up the variable in question */
4656 if (isdigit(var[0])) {
4657 /* parse_dollar should have vetted var for us */
4658 int n = xatoi_positive(var);
4659 if (n < G.global_argc)
4660 val = G.global_argv[n];
4661 /* else val remains NULL: $N with too big N */
4665 val = utoa(G.root_pid);
4667 case '!': /* bg pid */
4668 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4670 case '?': /* exitcode */
4671 val = utoa(G.last_exitcode);
4673 case '#': /* argc */
4674 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4677 val = get_local_var_value(var);
4681 /* Handle any expansions */
4682 if (exp_op == 'L') {
4683 debug_printf_expand("expand: length(%s)=", val);
4684 val = utoa(val ? strlen(val) : 0);
4685 debug_printf_expand("%s\n", val);
4686 } else if (exp_op) {
4687 if (exp_op == '%' || exp_op == '#') {
4688 /* Standard-mandated substring removal ops:
4689 * ${parameter%word} - remove smallest suffix pattern
4690 * ${parameter%%word} - remove largest suffix pattern
4691 * ${parameter#word} - remove smallest prefix pattern
4692 * ${parameter##word} - remove largest prefix pattern
4694 * Word is expanded to produce a glob pattern.
4695 * Then var's value is matched to it and matching part removed.
4697 if (val && val[0]) {
4701 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4702 if (exp_op == *exp_word) /* ## or %% */
4704 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4706 exp_word = exp_exp_word;
4707 /* HACK ALERT. We depend here on the fact that
4708 * G.global_argv and results of utoa and get_local_var_value
4709 * are actually in writable memory:
4710 * scan_and_match momentarily stores NULs there. */
4712 loc = scan_and_match(t, exp_word, scan_flags);
4713 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4714 // exp_op, t, exp_word, loc);
4716 if (loc) { /* match was found */
4717 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4718 val = loc; /* take right part */
4720 val = to_be_freed = xstrndup(val, loc - val); /* left */
4724 #if ENABLE_HUSH_BASH_COMPAT
4725 else if (exp_op == '/' || exp_op == '\\') {
4726 /* It's ${var/[/]pattern[/repl]} thing.
4727 * Note that in encoded form it has TWO parts:
4728 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4729 * and if // is used, it is encoded as \:
4730 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4732 /* Empty variable always gives nothing: */
4733 // "v=''; echo ${v/*/w}" prints "", not "w"
4734 if (val && val[0]) {
4735 /* pattern uses non-standard expansion.
4736 * repl should be unbackslashed and globbed
4737 * by the usual expansion rules:
4739 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4740 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4741 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4742 * v='a bz'; echo ${v/a*z/\z} prints "z"
4743 * (note that a*z _pattern_ is never globbed!)
4745 char *pattern, *repl, *t;
4746 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4748 pattern = xstrdup(exp_word);
4749 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4750 *p++ = SPECIAL_VAR_SYMBOL;
4752 p = strchr(p, SPECIAL_VAR_SYMBOL);
4754 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4755 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4756 /* HACK ALERT. We depend here on the fact that
4757 * G.global_argv and results of utoa and get_local_var_value
4758 * are actually in writable memory:
4759 * replace_pattern momentarily stores NULs there. */
4761 to_be_freed = replace_pattern(t,
4763 (repl ? repl : exp_word),
4765 if (to_be_freed) /* at least one replace happened */
4772 else if (exp_op == ':') {
4773 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4774 /* It's ${var:N[:M]} bashism.
4775 * Note that in encoded form it has TWO parts:
4776 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4781 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4784 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4785 *p++ = SPECIAL_VAR_SYMBOL;
4787 p = strchr(p, SPECIAL_VAR_SYMBOL);
4789 len = expand_and_evaluate_arith(exp_word, &errmsg);
4792 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4793 if (len >= 0) { /* bash compat: len < 0 is illegal */
4794 if (beg < 0) /* bash compat */
4796 debug_printf_varexp("from val:'%s'\n", val);
4797 if (len == 0 || !val || beg >= strlen(val)) {
4801 /* Paranoia. What if user entered 9999999999999
4802 * which fits in arith_t but not int? */
4805 val = to_be_freed = xstrndup(val + beg, len);
4807 debug_printf_varexp("val:'%s'\n", val);
4811 die_if_script("malformed ${%s:...}", var);
4814 } else { /* one of "-=+?" */
4815 /* Standard-mandated substitution ops:
4816 * ${var?word} - indicate error if unset
4817 * If var is unset, word (or a message indicating it is unset
4818 * if word is null) is written to standard error
4819 * and the shell exits with a non-zero exit status.
4820 * Otherwise, the value of var is substituted.
4821 * ${var-word} - use default value
4822 * If var is unset, word is substituted.
4823 * ${var=word} - assign and use default value
4824 * If var is unset, word is assigned to var.
4825 * In all cases, final value of var is substituted.
4826 * ${var+word} - use alternative value
4827 * If var is unset, null is substituted.
4828 * Otherwise, word is substituted.
4830 * Word is subjected to tilde expansion, parameter expansion,
4831 * command substitution, and arithmetic expansion.
4832 * If word is not needed, it is not expanded.
4834 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4835 * but also treat null var as if it is unset.
4837 int use_word = (!val || ((exp_save == ':') && !val[0]));
4839 use_word = !use_word;
4840 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4841 (exp_save == ':') ? "true" : "false", use_word);
4843 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4845 exp_word = to_be_freed;
4846 if (exp_op == '?') {
4847 /* mimic bash message */
4848 die_if_script("%s: %s",
4850 exp_word[0] ? exp_word : "parameter null or not set"
4852 //TODO: how interactive bash aborts expansion mid-command?
4857 if (exp_op == '=') {
4858 /* ${var=[word]} or ${var:=[word]} */
4859 if (isdigit(var[0]) || var[0] == '#') {
4860 /* mimic bash message */
4861 die_if_script("$%s: cannot assign in this way", var);
4864 char *new_var = xasprintf("%s=%s", var, val);
4865 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4869 } /* one of "-=+?" */
4871 *exp_saveptr = exp_save;
4877 *to_be_freed_pp = to_be_freed;
4881 /* Expand all variable references in given string, adding words to list[]
4882 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4883 * to be filled). This routine is extremely tricky: has to deal with
4884 * variables/parameters with whitespace, $* and $@, and constructs like
4885 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4886 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4888 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4889 * expansion of right-hand side of assignment == 1-element expand.
4891 char cant_be_null = 0; /* only bit 0x80 matters */
4894 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4895 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4896 debug_print_list("expand_vars_to_list", output, n);
4897 n = o_save_ptr(output, n);
4898 debug_print_list("expand_vars_to_list[0]", output, n);
4900 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4902 char *to_be_freed = NULL;
4903 const char *val = NULL;
4904 #if ENABLE_HUSH_TICK
4905 o_string subst_result = NULL_O_STRING;
4907 #if ENABLE_SH_MATH_SUPPORT
4908 char arith_buf[sizeof(arith_t)*3 + 2];
4910 o_addblock(output, arg, p - arg);
4911 debug_print_list("expand_vars_to_list[1]", output, n);
4913 p = strchr(p, SPECIAL_VAR_SYMBOL);
4915 /* Fetch special var name (if it is indeed one of them)
4916 * and quote bit, force the bit on if singleword expansion -
4917 * important for not getting v=$@ expand to many words. */
4918 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4920 /* Is this variable quoted and thus expansion can't be null?
4921 * "$@" is special. Even if quoted, it can still
4922 * expand to nothing (not even an empty string),
4923 * thus it is excluded. */
4924 if ((first_ch & 0x7f) != '@')
4925 cant_be_null |= first_ch;
4927 switch (first_ch & 0x7f) {
4928 /* Highest bit in first_ch indicates that var is double-quoted */
4932 if (!G.global_argv[1])
4935 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4936 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4937 while (G.global_argv[i]) {
4938 n = expand_on_ifs(output, n, G.global_argv[i]);
4939 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4940 if (G.global_argv[i++][0] && G.global_argv[i]) {
4941 /* this argv[] is not empty and not last:
4942 * put terminating NUL, start new word */
4943 o_addchr(output, '\0');
4944 debug_print_list("expand_vars_to_list[2]", output, n);
4945 n = o_save_ptr(output, n);
4946 debug_print_list("expand_vars_to_list[3]", output, n);
4950 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4951 * and in this case should treat it like '$*' - see 'else...' below */
4952 if (first_ch == ('@'|0x80) /* quoted $@ */
4953 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4956 o_addQstr(output, G.global_argv[i]);
4957 if (++i >= G.global_argc)
4959 o_addchr(output, '\0');
4960 debug_print_list("expand_vars_to_list[4]", output, n);
4961 n = o_save_ptr(output, n);
4963 } else { /* quoted $* (or v="$@" case): add as one word */
4965 o_addQstr(output, G.global_argv[i]);
4966 if (!G.global_argv[++i])
4969 o_addchr(output, G.ifs[0]);
4974 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4975 /* "Empty variable", used to make "" etc to not disappear */
4977 cant_be_null = 0x80;
4979 #if ENABLE_HUSH_TICK
4980 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4981 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4983 /* Can't just stuff it into output o_string,
4984 * expanded result may need to be globbed
4985 * and $IFS-splitted */
4986 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4987 G.last_exitcode = process_command_subs(&subst_result, arg);
4988 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4989 val = subst_result.data;
4992 #if ENABLE_SH_MATH_SUPPORT
4993 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4996 arg++; /* skip '+' */
4997 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4998 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4999 res = expand_and_evaluate_arith(arg, NULL);
5000 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5001 sprintf(arith_buf, ARITH_FMT, res);
5007 val = expand_one_var(&to_be_freed, arg, &p);
5008 IF_HUSH_TICK(store_val:)
5009 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5010 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5011 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5012 if (val && val[0]) {
5013 n = expand_on_ifs(output, n, val);
5016 } else { /* quoted $VAR, val will be appended below */
5017 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5018 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5022 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5024 if (val && val[0]) {
5025 o_addQstr(output, val);
5029 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5030 * Do the check to avoid writing to a const string. */
5031 if (*p != SPECIAL_VAR_SYMBOL)
5032 *p = SPECIAL_VAR_SYMBOL;
5034 #if ENABLE_HUSH_TICK
5035 o_free(&subst_result);
5038 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5041 debug_print_list("expand_vars_to_list[a]", output, n);
5042 /* this part is literal, and it was already pre-quoted
5043 * if needed (much earlier), do not use o_addQstr here! */
5044 o_addstr_with_NUL(output, arg);
5045 debug_print_list("expand_vars_to_list[b]", output, n);
5046 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5047 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5050 /* allow to reuse list[n] later without re-growth */
5051 output->has_empty_slot = 1;
5053 o_addchr(output, '\0');
5059 static char **expand_variables(char **argv, unsigned expflags)
5063 o_string output = NULL_O_STRING;
5065 output.o_expflags = expflags;
5069 n = expand_vars_to_list(&output, n, *argv);
5072 debug_print_list("expand_variables", &output, n);
5074 /* output.data (malloced in one block) gets returned in "list" */
5075 list = o_finalize_list(&output, n);
5076 debug_print_strings("expand_variables[1]", list);
5080 static char **expand_strvec_to_strvec(char **argv)
5082 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5085 #if ENABLE_HUSH_BASH_COMPAT
5086 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5088 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5092 /* Used for expansion of right hand of assignments,
5093 * $((...)), heredocs, variable espansion parts.
5095 * NB: should NOT do globbing!
5096 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5098 static char *expand_string_to_string(const char *str, int do_unbackslash)
5100 #if !ENABLE_HUSH_BASH_COMPAT
5101 const int do_unbackslash = 1;
5103 char *argv[2], **list;
5105 debug_printf_expand("string_to_string<='%s'\n", str);
5106 /* This is generally an optimization, but it also
5107 * handles "", which otherwise trips over !list[0] check below.
5108 * (is this ever happens that we actually get str="" here?)
5110 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5111 //TODO: Can use on strings with \ too, just unbackslash() them?
5112 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5113 return xstrdup(str);
5116 argv[0] = (char*)str;
5118 list = expand_variables(argv, do_unbackslash
5119 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5120 : EXP_FLAG_SINGLEWORD
5123 if (!list[0] || list[1])
5124 bb_error_msg_and_die("BUG in varexp2");
5125 /* actually, just move string 2*sizeof(char*) bytes back */
5126 overlapping_strcpy((char*)list, list[0]);
5128 unbackslash((char*)list);
5129 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5133 /* Used for "eval" builtin */
5134 static char* expand_strvec_to_string(char **argv)
5138 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5139 /* Convert all NULs to spaces */
5144 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5145 bb_error_msg_and_die("BUG in varexp3");
5146 /* bash uses ' ' regardless of $IFS contents */
5151 overlapping_strcpy((char*)list, list[0]);
5152 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5156 static char **expand_assignments(char **argv, int count)
5161 G.expanded_assignments = p = NULL;
5162 /* Expand assignments into one string each */
5163 for (i = 0; i < count; i++) {
5164 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5166 G.expanded_assignments = NULL;
5173 void re_execute_shell(char ***to_free, const char *s,
5174 char *g_argv0, char **g_argv,
5175 char **builtin_argv) NORETURN;
5177 static void reset_traps_to_defaults(void)
5179 /* This function is always called in a child shell
5180 * after fork (not vfork, NOMMU doesn't use this function).
5185 /* Child shells are not interactive.
5186 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5187 * Testcase: (while :; do :; done) + ^Z should background.
5188 * Same goes for SIGTERM, SIGHUP, SIGINT.
5190 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5191 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5193 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5194 * Stupid. It can be done with *single* &= op, but we can't use
5195 * the fact that G.blocked_set is implemented as a bitmask
5197 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5201 /* Careful. Only if no trap or trap is not "" */
5202 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5203 sigdelset(&G.blocked_set, sig);
5210 /* Our homegrown sig mask is saner to work with :) */
5211 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5213 /* Resetting all traps to default except empty ones */
5214 mask = G.non_DFL_mask;
5215 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5216 if (!G.traps[sig] || !G.traps[sig][0])
5219 G.traps[sig] = NULL;
5220 /* There is no signal for 0 (EXIT) */
5223 /* There was a trap handler, we just removed it.
5224 * But if sig still has non-DFL handling,
5225 * we should not unblock the sig. */
5228 sigdelset(&G.blocked_set, sig);
5230 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5235 static void re_execute_shell(char ***to_free, const char *s,
5236 char *g_argv0, char **g_argv,
5237 char **builtin_argv) NORETURN;
5238 static void re_execute_shell(char ***to_free, const char *s,
5239 char *g_argv0, char **g_argv,
5240 char **builtin_argv)
5242 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5243 /* delims + 2 * (number of bytes in printed hex numbers) */
5244 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5245 char *heredoc_argv[4];
5246 struct variable *cur;
5247 # if ENABLE_HUSH_FUNCTIONS
5248 struct function *funcp;
5252 unsigned long long empty_trap_mask;
5254 if (!g_argv0) { /* heredoc */
5255 argv = heredoc_argv;
5256 argv[0] = (char *) G.argv0_for_re_execing;
5257 argv[1] = (char *) "-<";
5258 argv[2] = (char *) s;
5260 pp = &argv[3]; /* used as pointer to empty environment */
5266 if (pp) while (*pp++)
5269 empty_trap_mask = 0;
5272 for (sig = 1; sig < NSIG; sig++) {
5273 if (G.traps[sig] && !G.traps[sig][0])
5274 empty_trap_mask |= 1LL << sig;
5278 sprintf(param_buf, NOMMU_HACK_FMT
5279 , (unsigned) G.root_pid
5280 , (unsigned) G.root_ppid
5281 , (unsigned) G.last_bg_pid
5282 , (unsigned) G.last_exitcode
5285 IF_HUSH_LOOPS(, G.depth_of_loop)
5287 # undef NOMMU_HACK_FMT
5288 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5289 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5292 for (cur = G.top_var; cur; cur = cur->next) {
5293 if (!cur->flg_export || cur->flg_read_only)
5296 # if ENABLE_HUSH_FUNCTIONS
5297 for (funcp = G.top_func; funcp; funcp = funcp->next)
5303 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5304 *pp++ = (char *) G.argv0_for_re_execing;
5306 for (cur = G.top_var; cur; cur = cur->next) {
5307 if (strcmp(cur->varstr, hush_version_str) == 0)
5309 if (cur->flg_read_only) {
5310 *pp++ = (char *) "-R";
5311 *pp++ = cur->varstr;
5312 } else if (!cur->flg_export) {
5313 *pp++ = (char *) "-V";
5314 *pp++ = cur->varstr;
5317 # if ENABLE_HUSH_FUNCTIONS
5318 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5319 *pp++ = (char *) "-F";
5320 *pp++ = funcp->name;
5321 *pp++ = funcp->body_as_string;
5324 /* We can pass activated traps here. Say, -Tnn:trap_string
5326 * However, POSIX says that subshells reset signals with traps
5328 * I tested bash-3.2 and it not only does that with true subshells
5329 * of the form ( list ), but with any forked children shells.
5330 * I set trap "echo W" WINCH; and then tried:
5332 * { echo 1; sleep 20; echo 2; } &
5333 * while true; do echo 1; sleep 20; echo 2; break; done &
5334 * true | { echo 1; sleep 20; echo 2; } | cat
5336 * In all these cases sending SIGWINCH to the child shell
5337 * did not run the trap. If I add trap "echo V" WINCH;
5338 * _inside_ group (just before echo 1), it works.
5340 * I conclude it means we don't need to pass active traps here.
5341 * Even if we would use signal handlers instead of signal masking
5342 * in order to implement trap handling,
5343 * exec syscall below resets signals to SIG_DFL for us.
5345 *pp++ = (char *) "-c";
5348 while (*++builtin_argv)
5349 *pp++ = *builtin_argv;
5350 *pp++ = (char *) "";
5355 /* *pp = NULL; - is already there */
5359 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5360 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5361 execve(bb_busybox_exec_path, argv, pp);
5362 /* Fallback. Useful for init=/bin/hush usage etc */
5363 if (argv[0][0] == '/')
5364 execve(argv[0], argv, pp);
5365 xfunc_error_retval = 127;
5366 bb_error_msg_and_die("can't re-execute the shell");
5368 #endif /* !BB_MMU */
5371 static int run_and_free_list(struct pipe *pi);
5373 /* Executing from string: eval, sh -c '...'
5374 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5375 * end_trigger controls how often we stop parsing
5376 * NUL: parse all, execute, return
5377 * ';': parse till ';' or newline, execute, repeat till EOF
5379 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5381 /* Why we need empty flag?
5382 * An obscure corner case "false; ``; echo $?":
5383 * empty command in `` should still set $? to 0.
5384 * But we can't just set $? to 0 at the start,
5385 * this breaks "false; echo `echo $?`" case.
5389 struct pipe *pipe_list;
5391 pipe_list = parse_stream(NULL, inp, end_trigger);
5392 if (!pipe_list) { /* EOF */
5394 G.last_exitcode = 0;
5397 debug_print_tree(pipe_list, 0);
5398 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5399 run_and_free_list(pipe_list);
5404 static void parse_and_run_string(const char *s)
5406 struct in_str input;
5407 setup_string_in_str(&input, s);
5408 parse_and_run_stream(&input, '\0');
5411 static void parse_and_run_file(FILE *f)
5413 struct in_str input;
5414 setup_file_in_str(&input, f);
5415 parse_and_run_stream(&input, ';');
5418 #if ENABLE_HUSH_TICK
5419 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5424 char **to_free = NULL;
5428 pid = BB_MMU ? xfork() : xvfork();
5429 if (pid == 0) { /* child */
5430 disable_restore_tty_pgrp_on_exit();
5431 /* Process substitution is not considered to be usual
5432 * 'command execution'.
5433 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5440 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5441 close(channel[0]); /* NB: close _first_, then move fd! */
5442 xmove_fd(channel[1], 1);
5443 /* Prevent it from trying to handle ctrl-z etc */
5444 IF_HUSH_JOB(G.run_list_level = 1;)
5445 /* Awful hack for `trap` or $(trap).
5447 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5448 * contains an example where "trap" is executed in a subshell:
5450 * save_traps=$(trap)
5452 * eval "$save_traps"
5454 * Standard does not say that "trap" in subshell shall print
5455 * parent shell's traps. It only says that its output
5456 * must have suitable form, but then, in the above example
5457 * (which is not supposed to be normative), it implies that.
5459 * bash (and probably other shell) does implement it
5460 * (traps are reset to defaults, but "trap" still shows them),
5461 * but as a result, "trap" logic is hopelessly messed up:
5464 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5465 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5466 * # true | trap <--- trap is in subshell - no output (ditto)
5467 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5468 * trap -- 'echo Ho' SIGWINCH
5469 * # echo `(trap)` <--- in subshell in subshell - output
5470 * trap -- 'echo Ho' SIGWINCH
5471 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5472 * trap -- 'echo Ho' SIGWINCH
5474 * The rules when to forget and when to not forget traps
5475 * get really complex and nonsensical.
5477 * Our solution: ONLY bare $(trap) or `trap` is special.
5479 s = skip_whitespace(s);
5480 if (strncmp(s, "trap", 4) == 0
5481 && skip_whitespace(s + 4)[0] == '\0'
5483 static const char *const argv[] = { NULL, NULL };
5484 builtin_trap((char**)argv);
5485 exit(0); /* not _exit() - we need to fflush */
5488 reset_traps_to_defaults();
5489 parse_and_run_string(s);
5490 _exit(G.last_exitcode);
5492 /* We re-execute after vfork on NOMMU. This makes this script safe:
5493 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5494 * huge=`cat BIG` # was blocking here forever
5497 re_execute_shell(&to_free,
5507 # if ENABLE_HUSH_FAST
5509 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5510 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5511 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5513 enable_restore_tty_pgrp_on_exit();
5518 close_on_exec_on(channel[0]);
5519 return xfdopen_for_read(channel[0]);
5522 /* Return code is exit status of the process that is run. */
5523 static int process_command_subs(o_string *dest, const char *s)
5526 struct in_str pipe_str;
5528 int status, ch, eol_cnt;
5530 fp = generate_stream_from_string(s, &pid);
5532 /* Now send results of command back into original context */
5533 setup_file_in_str(&pipe_str, fp);
5535 while ((ch = i_getch(&pipe_str)) != EOF) {
5541 o_addchr(dest, '\n');
5544 o_addQchr(dest, ch);
5547 debug_printf("done reading from `cmd` pipe, closing it\n");
5549 /* We need to extract exitcode. Test case
5550 * "true; echo `sleep 1; false` $?"
5552 safe_waitpid(pid, &status, 0);
5553 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5554 return WEXITSTATUS(status);
5556 #endif /* ENABLE_HUSH_TICK */
5559 static void setup_heredoc(struct redir_struct *redir)
5561 struct fd_pair pair;
5564 /* the _body_ of heredoc (misleading field name) */
5565 const char *heredoc = redir->rd_filename;
5572 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5573 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5577 len = strlen(heredoc);
5579 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5581 xmove_fd(pair.rd, redir->rd_fd);
5583 /* Try writing without forking. Newer kernels have
5584 * dynamically growing pipes. Must use non-blocking write! */
5587 written = write(pair.wr, heredoc, len);
5598 ndelay_off(pair.wr);
5600 /* Okay, pipe buffer was not big enough */
5601 /* Note: we must not create a stray child (bastard? :)
5602 * for the unsuspecting parent process. Child creates a grandchild
5603 * and exits before parent execs the process which consumes heredoc
5604 * (that exec happens after we return from this function) */
5611 disable_restore_tty_pgrp_on_exit();
5612 pid = BB_MMU ? xfork() : xvfork();
5616 close(redir->rd_fd); /* read side of the pipe */
5618 full_write(pair.wr, heredoc, len); /* may loop or block */
5621 /* Delegate blocking writes to another process */
5622 xmove_fd(pair.wr, STDOUT_FILENO);
5623 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5627 #if ENABLE_HUSH_FAST
5629 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5631 enable_restore_tty_pgrp_on_exit();
5637 wait(NULL); /* wait till child has died */
5640 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5641 * and stderr if they are redirected. */
5642 static int setup_redirects(struct command *prog, int squirrel[])
5645 struct redir_struct *redir;
5647 for (redir = prog->redirects; redir; redir = redir->next) {
5648 if (redir->rd_type == REDIRECT_HEREDOC2) {
5649 /* rd_fd<<HERE case */
5650 if (squirrel && redir->rd_fd < 3
5651 && squirrel[redir->rd_fd] < 0
5653 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5655 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5657 debug_printf_parse("set heredoc '%s'\n",
5658 redir->rd_filename);
5659 setup_heredoc(redir);
5663 if (redir->rd_dup == REDIRFD_TO_FILE) {
5664 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5666 if (redir->rd_filename == NULL) {
5667 /* Something went wrong in the parse.
5668 * Pretend it didn't happen */
5669 bb_error_msg("bug in redirect parse");
5672 mode = redir_table[redir->rd_type].mode;
5673 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5674 openfd = open_or_warn(p, mode);
5677 /* this could get lost if stderr has been redirected, but
5678 * bash and ash both lose it as well (though zsh doesn't!) */
5679 //what the above comment tries to say?
5683 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5684 openfd = redir->rd_dup;
5687 if (openfd != redir->rd_fd) {
5688 if (squirrel && redir->rd_fd < 3
5689 && squirrel[redir->rd_fd] < 0
5691 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5693 if (openfd == REDIRFD_CLOSE) {
5694 /* "n>-" means "close me" */
5695 close(redir->rd_fd);
5697 xdup2(openfd, redir->rd_fd);
5698 if (redir->rd_dup == REDIRFD_TO_FILE)
5706 static void restore_redirects(int squirrel[])
5709 for (i = 0; i < 3; i++) {
5712 /* We simply die on error */
5718 static char *find_in_path(const char *arg)
5721 const char *PATH = get_local_var_value("PATH");
5727 const char *end = strchrnul(PATH, ':');
5728 int sz = end - PATH; /* must be int! */
5732 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5734 /* We have xxx::yyyy in $PATH,
5735 * it means "use current dir" */
5738 if (access(ret, F_OK) == 0)
5751 static const struct built_in_command *find_builtin_helper(const char *name,
5752 const struct built_in_command *x,
5753 const struct built_in_command *end)
5756 if (strcmp(name, x->b_cmd) != 0) {
5760 debug_printf_exec("found builtin '%s'\n", name);
5765 static const struct built_in_command *find_builtin1(const char *name)
5767 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5769 static const struct built_in_command *find_builtin(const char *name)
5771 const struct built_in_command *x = find_builtin1(name);
5774 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5777 #if ENABLE_HUSH_FUNCTIONS
5778 static struct function **find_function_slot(const char *name)
5780 struct function **funcpp = &G.top_func;
5782 if (strcmp(name, (*funcpp)->name) == 0) {
5785 funcpp = &(*funcpp)->next;
5790 static const struct function *find_function(const char *name)
5792 const struct function *funcp = *find_function_slot(name);
5794 debug_printf_exec("found function '%s'\n", name);
5798 /* Note: takes ownership on name ptr */
5799 static struct function *new_function(char *name)
5801 struct function **funcpp = find_function_slot(name);
5802 struct function *funcp = *funcpp;
5804 if (funcp != NULL) {
5805 struct command *cmd = funcp->parent_cmd;
5806 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5808 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5810 /* Note: if !funcp->body, do not free body_as_string!
5811 * This is a special case of "-F name body" function:
5812 * body_as_string was not malloced! */
5814 free_pipe_list(funcp->body);
5816 free(funcp->body_as_string);
5820 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5821 cmd->argv[0] = funcp->name;
5822 cmd->group = funcp->body;
5824 cmd->group_as_string = funcp->body_as_string;
5828 debug_printf_exec("remembering new function '%s'\n", name);
5829 funcp = *funcpp = xzalloc(sizeof(*funcp));
5830 /*funcp->next = NULL;*/
5837 static void unset_func(const char *name)
5839 struct function **funcpp = find_function_slot(name);
5840 struct function *funcp = *funcpp;
5842 if (funcp != NULL) {
5843 debug_printf_exec("freeing function '%s'\n", funcp->name);
5844 *funcpp = funcp->next;
5845 /* funcp is unlinked now, deleting it.
5846 * Note: if !funcp->body, the function was created by
5847 * "-F name body", do not free ->body_as_string
5848 * and ->name as they were not malloced. */
5850 free_pipe_list(funcp->body);
5853 free(funcp->body_as_string);
5861 #define exec_function(to_free, funcp, argv) \
5862 exec_function(funcp, argv)
5864 static void exec_function(char ***to_free,
5865 const struct function *funcp,
5866 char **argv) NORETURN;
5867 static void exec_function(char ***to_free,
5868 const struct function *funcp,
5874 argv[0] = G.global_argv[0];
5875 G.global_argv = argv;
5879 /* On MMU, funcp->body is always non-NULL */
5880 n = run_list(funcp->body);
5884 re_execute_shell(to_free,
5885 funcp->body_as_string,
5892 static int run_function(const struct function *funcp, char **argv)
5898 save_and_replace_G_args(&sv, argv);
5900 /* "we are in function, ok to use return" */
5901 sv_flg = G.flag_return_in_progress;
5902 G.flag_return_in_progress = -1;
5903 # if ENABLE_HUSH_LOCAL
5904 G.func_nest_level++;
5907 /* On MMU, funcp->body is always non-NULL */
5910 /* Function defined by -F */
5911 parse_and_run_string(funcp->body_as_string);
5912 rc = G.last_exitcode;
5916 rc = run_list(funcp->body);
5919 # if ENABLE_HUSH_LOCAL
5921 struct variable *var;
5922 struct variable **var_pp;
5924 var_pp = &G.top_var;
5925 while ((var = *var_pp) != NULL) {
5926 if (var->func_nest_level < G.func_nest_level) {
5927 var_pp = &var->next;
5931 if (var->flg_export)
5932 bb_unsetenv(var->varstr);
5933 /* Remove from global list */
5934 *var_pp = var->next;
5940 G.func_nest_level--;
5943 G.flag_return_in_progress = sv_flg;
5945 restore_G_args(&sv, argv);
5949 #endif /* ENABLE_HUSH_FUNCTIONS */
5953 #define exec_builtin(to_free, x, argv) \
5954 exec_builtin(x, argv)
5956 #define exec_builtin(to_free, x, argv) \
5957 exec_builtin(to_free, argv)
5959 static void exec_builtin(char ***to_free,
5960 const struct built_in_command *x,
5961 char **argv) NORETURN;
5962 static void exec_builtin(char ***to_free,
5963 const struct built_in_command *x,
5967 int rcode = x->b_function(argv);
5971 /* On NOMMU, we must never block!
5972 * Example: { sleep 99 | read line; } & echo Ok
5974 re_execute_shell(to_free,
5983 static void execvp_or_die(char **argv) NORETURN;
5984 static void execvp_or_die(char **argv)
5986 debug_printf_exec("execing '%s'\n", argv[0]);
5987 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5988 execvp(argv[0], argv);
5989 bb_perror_msg("can't execute '%s'", argv[0]);
5990 _exit(127); /* bash compat */
5993 #if ENABLE_HUSH_MODE_X
5994 static void dump_cmd_in_x_mode(char **argv)
5996 if (G_x_mode && argv) {
5997 /* We want to output the line in one write op */
6005 len += strlen(argv[n++]) + 1;
6011 p += sprintf(p, " %s", argv[n++]);
6019 # define dump_cmd_in_x_mode(argv) ((void)0)
6023 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6024 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6025 #define pseudo_exec(nommu_save, command, argv_expanded) \
6026 pseudo_exec(command, argv_expanded)
6029 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6031 * Don't exit() here. If you don't exec, use _exit instead.
6032 * The at_exit handlers apparently confuse the calling process,
6033 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6034 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6035 char **argv, int assignment_cnt,
6036 char **argv_expanded) NORETURN;
6037 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6038 char **argv, int assignment_cnt,
6039 char **argv_expanded)
6043 new_env = expand_assignments(argv, assignment_cnt);
6044 dump_cmd_in_x_mode(new_env);
6046 if (!argv[assignment_cnt]) {
6047 /* Case when we are here: ... | var=val | ...
6048 * (note that we do not exit early, i.e., do not optimize out
6049 * expand_assignments(): think about ... | var=`sleep 1` | ...
6051 free_strings(new_env);
6052 _exit(EXIT_SUCCESS);
6056 set_vars_and_save_old(new_env);
6057 free(new_env); /* optional */
6058 /* we can also destroy set_vars_and_save_old's return value,
6061 nommu_save->new_env = new_env;
6062 nommu_save->old_vars = set_vars_and_save_old(new_env);
6065 if (argv_expanded) {
6066 argv = argv_expanded;
6068 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6070 nommu_save->argv = argv;
6073 dump_cmd_in_x_mode(argv);
6075 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6076 if (strchr(argv[0], '/') != NULL)
6080 /* Check if the command matches any of the builtins.
6081 * Depending on context, this might be redundant. But it's
6082 * easier to waste a few CPU cycles than it is to figure out
6083 * if this is one of those cases.
6086 /* On NOMMU, it is more expensive to re-execute shell
6087 * just in order to run echo or test builtin.
6088 * It's better to skip it here and run corresponding
6089 * non-builtin later. */
6090 const struct built_in_command *x;
6091 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6093 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6096 #if ENABLE_HUSH_FUNCTIONS
6097 /* Check if the command matches any functions */
6099 const struct function *funcp = find_function(argv[0]);
6101 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6106 #if ENABLE_FEATURE_SH_STANDALONE
6107 /* Check if the command matches any busybox applets */
6109 int a = find_applet_by_name(argv[0]);
6111 # if BB_MMU /* see above why on NOMMU it is not allowed */
6112 if (APPLET_IS_NOEXEC(a)) {
6113 debug_printf_exec("running applet '%s'\n", argv[0]);
6114 run_applet_no_and_exit(a, argv);
6117 /* Re-exec ourselves */
6118 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6119 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6120 execv(bb_busybox_exec_path, argv);
6121 /* If they called chroot or otherwise made the binary no longer
6122 * executable, fall through */
6127 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6130 execvp_or_die(argv);
6133 /* Called after [v]fork() in run_pipe
6135 static void pseudo_exec(nommu_save_t *nommu_save,
6136 struct command *command,
6137 char **argv_expanded) NORETURN;
6138 static void pseudo_exec(nommu_save_t *nommu_save,
6139 struct command *command,
6140 char **argv_expanded)
6142 if (command->argv) {
6143 pseudo_exec_argv(nommu_save, command->argv,
6144 command->assignment_cnt, argv_expanded);
6147 if (command->group) {
6148 /* Cases when we are here:
6151 * ... | ( list ) | ...
6152 * ... | { list } | ...
6156 debug_printf_exec("pseudo_exec: run_list\n");
6157 reset_traps_to_defaults();
6158 rcode = run_list(command->group);
6159 /* OK to leak memory by not calling free_pipe_list,
6160 * since this process is about to exit */
6163 re_execute_shell(&nommu_save->argv_from_re_execing,
6164 command->group_as_string,
6171 /* Case when we are here: ... | >file */
6172 debug_printf_exec("pseudo_exec'ed null command\n");
6173 _exit(EXIT_SUCCESS);
6177 static const char *get_cmdtext(struct pipe *pi)
6183 /* This is subtle. ->cmdtext is created only on first backgrounding.
6184 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6185 * On subsequent bg argv is trashed, but we won't use it */
6188 argv = pi->cmds[0].argv;
6189 if (!argv || !argv[0]) {
6190 pi->cmdtext = xzalloc(1);
6196 len += strlen(*argv) + 1;
6200 argv = pi->cmds[0].argv;
6202 len = strlen(*argv);
6203 memcpy(p, *argv, len);
6211 static void insert_bg_job(struct pipe *pi)
6213 struct pipe *job, **jobp;
6216 /* Linear search for the ID of the job to use */
6218 for (job = G.job_list; job; job = job->next)
6219 if (job->jobid >= pi->jobid)
6220 pi->jobid = job->jobid + 1;
6222 /* Add job to the list of running jobs */
6224 while ((job = *jobp) != NULL)
6226 job = *jobp = xmalloc(sizeof(*job));
6228 *job = *pi; /* physical copy */
6230 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6231 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6232 for (i = 0; i < pi->num_cmds; i++) {
6233 job->cmds[i].pid = pi->cmds[i].pid;
6234 /* all other fields are not used and stay zero */
6236 job->cmdtext = xstrdup(get_cmdtext(pi));
6238 if (G_interactive_fd)
6239 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6240 G.last_jobid = job->jobid;
6243 static void remove_bg_job(struct pipe *pi)
6245 struct pipe *prev_pipe;
6247 if (pi == G.job_list) {
6248 G.job_list = pi->next;
6250 prev_pipe = G.job_list;
6251 while (prev_pipe->next != pi)
6252 prev_pipe = prev_pipe->next;
6253 prev_pipe->next = pi->next;
6256 G.last_jobid = G.job_list->jobid;
6261 /* Remove a backgrounded job */
6262 static void delete_finished_bg_job(struct pipe *pi)
6269 /* Check to see if any processes have exited -- if they
6270 * have, figure out why and see if a job has completed */
6271 static int checkjobs(struct pipe *fg_pipe)
6281 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6283 attributes = WUNTRACED;
6284 if (fg_pipe == NULL)
6285 attributes |= WNOHANG;
6288 #if ENABLE_HUSH_FAST
6289 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6290 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6291 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6292 /* There was neither fork nor SIGCHLD since last waitpid */
6293 /* Avoid doing waitpid syscall if possible */
6294 if (!G.we_have_children) {
6298 if (fg_pipe == NULL) { /* is WNOHANG set? */
6299 /* We have children, but they did not exit
6300 * or stop yet (we saw no SIGCHLD) */
6303 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6307 /* Do we do this right?
6308 * bash-3.00# sleep 20 | false
6310 * [3]+ Stopped sleep 20 | false
6311 * bash-3.00# echo $?
6312 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6313 * [hush 1.14.0: yes we do it right]
6320 #if ENABLE_HUSH_FAST
6321 i = G.count_SIGCHLD;
6323 childpid = waitpid(-1, &status, attributes);
6324 if (childpid <= 0) {
6325 if (childpid && errno != ECHILD)
6326 bb_perror_msg("waitpid");
6327 #if ENABLE_HUSH_FAST
6328 else { /* Until next SIGCHLD, waitpid's are useless */
6329 G.we_have_children = (childpid == 0);
6330 G.handled_SIGCHLD = i;
6331 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6336 dead = WIFEXITED(status) || WIFSIGNALED(status);
6339 if (WIFSTOPPED(status))
6340 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6341 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6342 if (WIFSIGNALED(status))
6343 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6344 childpid, WTERMSIG(status), WEXITSTATUS(status));
6345 if (WIFEXITED(status))
6346 debug_printf_jobs("pid %d exited, exitcode %d\n",
6347 childpid, WEXITSTATUS(status));
6349 /* Were we asked to wait for fg pipe? */
6351 i = fg_pipe->num_cmds;
6353 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6354 if (fg_pipe->cmds[i].pid != childpid)
6358 fg_pipe->cmds[i].pid = 0;
6359 fg_pipe->alive_cmds--;
6360 ex = WEXITSTATUS(status);
6361 /* bash prints killer signal's name for *last*
6362 * process in pipe (prints just newline for SIGINT).
6363 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6365 if (WIFSIGNALED(status)) {
6366 int sig = WTERMSIG(status);
6367 if (i == fg_pipe->num_cmds-1)
6368 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6369 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6370 * Maybe we need to use sig | 128? */
6373 fg_pipe->cmds[i].cmd_exitcode = ex;
6375 fg_pipe->cmds[i].is_stopped = 1;
6376 fg_pipe->stopped_cmds++;
6378 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6379 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6380 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6381 /* All processes in fg pipe have exited or stopped */
6382 i = fg_pipe->num_cmds;
6384 rcode = fg_pipe->cmds[i].cmd_exitcode;
6385 /* usually last process gives overall exitstatus,
6386 * but with "set -o pipefail", last *failed* process does */
6387 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6390 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6391 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6392 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6393 * and "killall -STOP cat" */
6394 if (G_interactive_fd) {
6396 if (fg_pipe->alive_cmds != 0)
6397 insert_bg_job(fg_pipe);
6401 if (fg_pipe->alive_cmds == 0)
6404 /* There are still running processes in the fg pipe */
6405 goto wait_more; /* do waitpid again */
6407 /* it wasnt fg_pipe, look for process in bg pipes */
6411 /* We asked to wait for bg or orphaned children */
6412 /* No need to remember exitcode in this case */
6413 for (pi = G.job_list; pi; pi = pi->next) {
6414 for (i = 0; i < pi->num_cmds; i++) {
6415 if (pi->cmds[i].pid == childpid)
6416 goto found_pi_and_prognum;
6419 /* Happens when shell is used as init process (init=/bin/sh) */
6420 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6421 continue; /* do waitpid again */
6423 found_pi_and_prognum:
6426 pi->cmds[i].pid = 0;
6428 if (!pi->alive_cmds) {
6429 if (G_interactive_fd)
6430 printf(JOB_STATUS_FORMAT, pi->jobid,
6431 "Done", pi->cmdtext);
6432 delete_finished_bg_job(pi);
6436 pi->cmds[i].is_stopped = 1;
6440 } /* while (waitpid succeeds)... */
6446 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6449 int rcode = checkjobs(fg_pipe);
6450 if (G_saved_tty_pgrp) {
6451 /* Job finished, move the shell to the foreground */
6452 p = getpgrp(); /* our process group id */
6453 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6454 tcsetpgrp(G_interactive_fd, p);
6460 /* Start all the jobs, but don't wait for anything to finish.
6463 * Return code is normally -1, when the caller has to wait for children
6464 * to finish to determine the exit status of the pipe. If the pipe
6465 * is a simple builtin command, however, the action is done by the
6466 * time run_pipe returns, and the exit code is provided as the
6469 * Returns -1 only if started some children. IOW: we have to
6470 * mask out retvals of builtins etc with 0xff!
6472 * The only case when we do not need to [v]fork is when the pipe
6473 * is single, non-backgrounded, non-subshell command. Examples:
6474 * cmd ; ... { list } ; ...
6475 * cmd && ... { list } && ...
6476 * cmd || ... { list } || ...
6477 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6478 * or (if SH_STANDALONE) an applet, and we can run the { list }
6479 * with run_list. If it isn't one of these, we fork and exec cmd.
6481 * Cases when we must fork:
6482 * non-single: cmd | cmd
6483 * backgrounded: cmd & { list } &
6484 * subshell: ( list ) [&]
6486 #if !ENABLE_HUSH_MODE_X
6487 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6488 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6490 static int redirect_and_varexp_helper(char ***new_env_p,
6491 struct variable **old_vars_p,
6492 struct command *command,
6494 char **argv_expanded)
6496 /* setup_redirects acts on file descriptors, not FILEs.
6497 * This is perfect for work that comes after exec().
6498 * Is it really safe for inline use? Experimentally,
6499 * things seem to work. */
6500 int rcode = setup_redirects(command, squirrel);
6502 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6503 *new_env_p = new_env;
6504 dump_cmd_in_x_mode(new_env);
6505 dump_cmd_in_x_mode(argv_expanded);
6507 *old_vars_p = set_vars_and_save_old(new_env);
6511 static NOINLINE int run_pipe(struct pipe *pi)
6513 static const char *const null_ptr = NULL;
6517 struct command *command;
6518 char **argv_expanded;
6520 /* it is not always needed, but we aim to smaller code */
6521 int squirrel[] = { -1, -1, -1 };
6524 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6527 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6528 * Result should be 3 lines: q w e, qwe, q w e
6530 G.ifs = get_local_var_value("IFS");
6534 IF_HUSH_JOB(pi->pgrp = -1;)
6535 pi->stopped_cmds = 0;
6536 command = &pi->cmds[0];
6537 argv_expanded = NULL;
6539 if (pi->num_cmds != 1
6540 || pi->followup == PIPE_BG
6541 || command->cmd_type == CMD_SUBSHELL
6548 debug_printf_exec(": group:%p argv:'%s'\n",
6549 command->group, command->argv ? command->argv[0] : "NONE");
6551 if (command->group) {
6552 #if ENABLE_HUSH_FUNCTIONS
6553 if (command->cmd_type == CMD_FUNCDEF) {
6554 /* "executing" func () { list } */
6555 struct function *funcp;
6557 funcp = new_function(command->argv[0]);
6558 /* funcp->name is already set to argv[0] */
6559 funcp->body = command->group;
6561 funcp->body_as_string = command->group_as_string;
6562 command->group_as_string = NULL;
6564 command->group = NULL;
6565 command->argv[0] = NULL;
6566 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6567 funcp->parent_cmd = command;
6568 command->child_func = funcp;
6570 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6572 return EXIT_SUCCESS;
6576 debug_printf("non-subshell group\n");
6577 rcode = 1; /* exitcode if redir failed */
6578 if (setup_redirects(command, squirrel) == 0) {
6579 debug_printf_exec(": run_list\n");
6580 rcode = run_list(command->group) & 0xff;
6582 restore_redirects(squirrel);
6583 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6585 debug_printf_exec("run_pipe: return %d\n", rcode);
6589 argv = command->argv ? command->argv : (char **) &null_ptr;
6591 const struct built_in_command *x;
6592 #if ENABLE_HUSH_FUNCTIONS
6593 const struct function *funcp;
6597 char **new_env = NULL;
6598 struct variable *old_vars = NULL;
6600 if (argv[command->assignment_cnt] == NULL) {
6601 /* Assignments, but no command */
6602 /* Ensure redirects take effect (that is, create files).
6603 * Try "a=t >file" */
6604 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6605 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6606 /* Set shell variables */
6610 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6611 /* Do we need to flag set_local_var() errors?
6612 * "assignment to readonly var" and "putenv error"
6617 /* Redirect error sets $? to 1. Otherwise,
6618 * if evaluating assignment value set $?, retain it.
6619 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6621 rcode = G.last_exitcode;
6622 /* Exit, _skipping_ variable restoring code: */
6623 goto clean_up_and_ret0;
6625 #else /* Older, bigger, but more correct code */
6627 rcode = setup_redirects(command, squirrel);
6628 restore_redirects(squirrel);
6629 /* Set shell variables */
6631 bb_putchar_stderr('+');
6633 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6635 fprintf(stderr, " %s", p);
6636 debug_printf_exec("set shell var:'%s'->'%s'\n",
6638 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6639 /* Do we need to flag set_local_var() errors?
6640 * "assignment to readonly var" and "putenv error"
6645 bb_putchar_stderr('\n');
6646 /* Redirect error sets $? to 1. Otherwise,
6647 * if evaluating assignment value set $?, retain it.
6648 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6650 rcode = G.last_exitcode;
6651 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6653 debug_printf_exec("run_pipe: return %d\n", rcode);
6658 /* Expand the rest into (possibly) many strings each */
6660 #if ENABLE_HUSH_BASH_COMPAT
6661 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6662 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6666 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6669 /* if someone gives us an empty string: `cmd with empty output` */
6670 if (!argv_expanded[0]) {
6671 free(argv_expanded);
6673 return G.last_exitcode;
6676 x = find_builtin(argv_expanded[0]);
6677 #if ENABLE_HUSH_FUNCTIONS
6680 funcp = find_function(argv_expanded[0]);
6684 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6685 debug_printf("exec with redirects only\n");
6686 rcode = setup_redirects(command, NULL);
6687 goto clean_up_and_ret1;
6690 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6693 debug_printf_exec(": builtin '%s' '%s'...\n",
6694 x->b_cmd, argv_expanded[1]);
6695 rcode = x->b_function(argv_expanded) & 0xff;
6698 #if ENABLE_HUSH_FUNCTIONS
6700 # if ENABLE_HUSH_LOCAL
6701 struct variable **sv;
6702 sv = G.shadowed_vars_pp;
6703 G.shadowed_vars_pp = &old_vars;
6705 debug_printf_exec(": function '%s' '%s'...\n",
6706 funcp->name, argv_expanded[1]);
6707 rcode = run_function(funcp, argv_expanded) & 0xff;
6708 # if ENABLE_HUSH_LOCAL
6709 G.shadowed_vars_pp = sv;
6715 unset_vars(new_env);
6717 /* clean_up_and_ret0: */
6718 restore_redirects(squirrel);
6720 free(argv_expanded);
6721 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6723 debug_printf_exec("run_pipe return %d\n", rcode);
6727 if (ENABLE_FEATURE_SH_STANDALONE) {
6728 int n = find_applet_by_name(argv_expanded[0]);
6729 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6730 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6732 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6733 argv_expanded[0], argv_expanded[1]);
6734 rcode = run_nofork_applet(n, argv_expanded);
6736 goto clean_up_and_ret;
6739 /* It is neither builtin nor applet. We must fork. */
6743 /* NB: argv_expanded may already be created, and that
6744 * might include `cmd` runs! Do not rerun it! We *must*
6745 * use argv_expanded if it's non-NULL */
6747 /* Going to fork a child per each pipe member */
6752 while (cmd_no < pi->num_cmds) {
6753 struct fd_pair pipefds;
6755 volatile nommu_save_t nommu_save;
6756 nommu_save.new_env = NULL;
6757 nommu_save.old_vars = NULL;
6758 nommu_save.argv = NULL;
6759 nommu_save.argv_from_re_execing = NULL;
6761 command = &pi->cmds[cmd_no];
6763 if (command->argv) {
6764 debug_printf_exec(": pipe member '%s' '%s'...\n",
6765 command->argv[0], command->argv[1]);
6767 debug_printf_exec(": pipe member with no argv\n");
6770 /* pipes are inserted between pairs of commands */
6773 if (cmd_no < pi->num_cmds)
6774 xpiped_pair(pipefds);
6776 command->pid = BB_MMU ? fork() : vfork();
6777 if (!command->pid) { /* child */
6779 disable_restore_tty_pgrp_on_exit();
6780 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6782 /* Every child adds itself to new process group
6783 * with pgid == pid_of_first_child_in_pipe */
6784 if (G.run_list_level == 1 && G_interactive_fd) {
6787 if (pgrp < 0) /* true for 1st process only */
6789 if (setpgid(0, pgrp) == 0
6790 && pi->followup != PIPE_BG
6791 && G_saved_tty_pgrp /* we have ctty */
6793 /* We do it in *every* child, not just first,
6795 tcsetpgrp(G_interactive_fd, pgrp);
6799 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6800 /* 1st cmd in backgrounded pipe
6801 * should have its stdin /dev/null'ed */
6803 if (open(bb_dev_null, O_RDONLY))
6804 xopen("/", O_RDONLY);
6806 xmove_fd(next_infd, 0);
6808 xmove_fd(pipefds.wr, 1);
6811 /* Like bash, explicit redirects override pipes,
6812 * and the pipe fd is available for dup'ing. */
6813 if (setup_redirects(command, NULL))
6816 /* Restore default handlers just prior to exec */
6817 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6819 /* Stores to nommu_save list of env vars putenv'ed
6820 * (NOMMU, on MMU we don't need that) */
6821 /* cast away volatility... */
6822 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6823 /* pseudo_exec() does not return */
6826 /* parent or error */
6827 #if ENABLE_HUSH_FAST
6829 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6831 enable_restore_tty_pgrp_on_exit();
6833 /* Clean up after vforked child */
6834 free(nommu_save.argv);
6835 free(nommu_save.argv_from_re_execing);
6836 unset_vars(nommu_save.new_env);
6837 add_vars(nommu_save.old_vars);
6839 free(argv_expanded);
6840 argv_expanded = NULL;
6841 if (command->pid < 0) { /* [v]fork failed */
6842 /* Clearly indicate, was it fork or vfork */
6843 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6847 /* Second and next children need to know pid of first one */
6849 pi->pgrp = command->pid;
6855 if (cmd_no < pi->num_cmds)
6857 /* Pass read (output) pipe end to next iteration */
6858 next_infd = pipefds.rd;
6861 if (!pi->alive_cmds) {
6863 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6868 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6872 #ifndef debug_print_tree
6873 static void debug_print_tree(struct pipe *pi, int lvl)
6875 static const char *const PIPE[] = {
6881 static const char *RES[] = {
6882 [RES_NONE ] = "NONE" ,
6885 [RES_THEN ] = "THEN" ,
6886 [RES_ELIF ] = "ELIF" ,
6887 [RES_ELSE ] = "ELSE" ,
6890 # if ENABLE_HUSH_LOOPS
6891 [RES_FOR ] = "FOR" ,
6892 [RES_WHILE] = "WHILE",
6893 [RES_UNTIL] = "UNTIL",
6895 [RES_DONE ] = "DONE" ,
6897 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6900 # if ENABLE_HUSH_CASE
6901 [RES_CASE ] = "CASE" ,
6902 [RES_CASE_IN ] = "CASE_IN" ,
6903 [RES_MATCH] = "MATCH",
6904 [RES_CASE_BODY] = "CASE_BODY",
6905 [RES_ESAC ] = "ESAC" ,
6907 [RES_XXXX ] = "XXXX" ,
6908 [RES_SNTX ] = "SNTX" ,
6910 static const char *const CMDTYPE[] = {
6914 # if ENABLE_HUSH_FUNCTIONS
6923 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6924 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6926 while (prn < pi->num_cmds) {
6927 struct command *command = &pi->cmds[prn];
6928 char **argv = command->argv;
6930 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6932 command->assignment_cnt);
6933 if (command->group) {
6934 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6935 CMDTYPE[command->cmd_type],
6938 , " group_as_string:", command->group_as_string
6943 debug_print_tree(command->group, lvl+1);
6947 if (argv) while (*argv) {
6948 fprintf(stderr, " '%s'", *argv);
6951 fprintf(stderr, "\n");
6958 #endif /* debug_print_tree */
6960 /* NB: called by pseudo_exec, and therefore must not modify any
6961 * global data until exec/_exit (we can be a child after vfork!) */
6962 static int run_list(struct pipe *pi)
6964 #if ENABLE_HUSH_CASE
6965 char *case_word = NULL;
6967 #if ENABLE_HUSH_LOOPS
6968 struct pipe *loop_top = NULL;
6969 char **for_lcur = NULL;
6970 char **for_list = NULL;
6972 smallint last_followup;
6974 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6975 smalluint cond_code = 0;
6977 enum { cond_code = 0 };
6980 smallint rword; /* RES_foo */
6981 smallint last_rword; /* ditto */
6984 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6987 #if ENABLE_HUSH_LOOPS
6988 /* Check syntax for "for" */
6989 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6990 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6992 /* current word is FOR or IN (BOLD in comments below) */
6993 if (cpipe->next == NULL) {
6994 syntax_error("malformed for");
6996 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6999 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7000 if (cpipe->next->res_word == RES_DO)
7002 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7003 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7004 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7006 syntax_error("malformed for");
7008 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7014 /* Past this point, all code paths should jump to ret: label
7015 * in order to return, no direct "return" statements please.
7016 * This helps to ensure that no memory is leaked. */
7024 last_rword = RES_XXXX;
7026 last_followup = PIPE_SEQ;
7027 rcode = G.last_exitcode;
7029 /* Go through list of pipes, (maybe) executing them. */
7030 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7034 IF_HAS_KEYWORDS(rword = pi->res_word;)
7035 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7036 rword, cond_code, last_rword);
7037 #if ENABLE_HUSH_LOOPS
7038 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7039 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7041 /* start of a loop: remember where loop starts */
7046 /* Still in the same "if...", "then..." or "do..." branch? */
7047 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7048 if ((rcode == 0 && last_followup == PIPE_OR)
7049 || (rcode != 0 && last_followup == PIPE_AND)
7051 /* It is "<true> || CMD" or "<false> && CMD"
7052 * and we should not execute CMD */
7053 debug_printf_exec("skipped cmd because of || or &&\n");
7054 last_followup = pi->followup;
7058 last_followup = pi->followup;
7059 IF_HAS_KEYWORDS(last_rword = rword;)
7062 if (rword == RES_THEN) {
7063 /* if false; then ... fi has exitcode 0! */
7064 G.last_exitcode = rcode = EXIT_SUCCESS;
7065 /* "if <false> THEN cmd": skip cmd */
7069 if (rword == RES_ELSE || rword == RES_ELIF) {
7070 /* "if <true> then ... ELSE/ELIF cmd":
7071 * skip cmd and all following ones */
7076 #if ENABLE_HUSH_LOOPS
7077 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7079 /* first loop through for */
7081 static const char encoded_dollar_at[] ALIGN1 = {
7082 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7083 }; /* encoded representation of "$@" */
7084 static const char *const encoded_dollar_at_argv[] = {
7085 encoded_dollar_at, NULL
7086 }; /* argv list with one element: "$@" */
7089 vals = (char**)encoded_dollar_at_argv;
7090 if (pi->next->res_word == RES_IN) {
7091 /* if no variable values after "in" we skip "for" */
7092 if (!pi->next->cmds[0].argv) {
7093 G.last_exitcode = rcode = EXIT_SUCCESS;
7094 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7097 vals = pi->next->cmds[0].argv;
7098 } /* else: "for var; do..." -> assume "$@" list */
7099 /* create list of variable values */
7100 debug_print_strings("for_list made from", vals);
7101 for_list = expand_strvec_to_strvec(vals);
7102 for_lcur = for_list;
7103 debug_print_strings("for_list", for_list);
7106 /* "for" loop is over, clean up */
7112 /* Insert next value from for_lcur */
7113 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7114 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7117 if (rword == RES_IN) {
7118 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7120 if (rword == RES_DONE) {
7121 continue; /* "done" has no cmds too */
7124 #if ENABLE_HUSH_CASE
7125 if (rword == RES_CASE) {
7126 case_word = expand_strvec_to_string(pi->cmds->argv);
7129 if (rword == RES_MATCH) {
7132 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7134 /* all prev words didn't match, does this one match? */
7135 argv = pi->cmds->argv;
7137 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7138 /* TODO: which FNM_xxx flags to use? */
7139 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7141 if (cond_code == 0) { /* match! we will execute this branch */
7142 free(case_word); /* make future "word)" stop */
7150 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7152 continue; /* not matched yet, skip this pipe */
7155 /* Just pressing <enter> in shell should check for jobs.
7156 * OTOH, in non-interactive shell this is useless
7157 * and only leads to extra job checks */
7158 if (pi->num_cmds == 0) {
7159 if (G_interactive_fd)
7160 goto check_jobs_and_continue;
7164 /* After analyzing all keywords and conditions, we decided
7165 * to execute this pipe. NB: have to do checkjobs(NULL)
7166 * after run_pipe to collect any background children,
7167 * even if list execution is to be stopped. */
7168 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7171 #if ENABLE_HUSH_LOOPS
7172 G.flag_break_continue = 0;
7174 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7176 /* We ran a builtin, function, or group.
7177 * rcode is already known
7178 * and we don't need to wait for anything. */
7179 G.last_exitcode = rcode;
7180 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7181 check_and_run_traps(0);
7182 #if ENABLE_HUSH_LOOPS
7183 /* Was it "break" or "continue"? */
7184 if (G.flag_break_continue) {
7185 smallint fbc = G.flag_break_continue;
7186 /* We might fall into outer *loop*,
7187 * don't want to break it too */
7189 G.depth_break_continue--;
7190 if (G.depth_break_continue == 0)
7191 G.flag_break_continue = 0;
7192 /* else: e.g. "continue 2" should *break* once, *then* continue */
7193 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7194 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7195 goto check_jobs_and_break;
7196 /* "continue": simulate end of loop */
7201 #if ENABLE_HUSH_FUNCTIONS
7202 if (G.flag_return_in_progress == 1) {
7203 /* same as "goto check_jobs_and_break" */
7208 } else if (pi->followup == PIPE_BG) {
7209 /* What does bash do with attempts to background builtins? */
7210 /* even bash 3.2 doesn't do that well with nested bg:
7211 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7212 * I'm NOT treating inner &'s as jobs */
7213 check_and_run_traps(0);
7215 if (G.run_list_level == 1)
7218 /* Last command's pid goes to $! */
7219 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7220 G.last_exitcode = rcode = EXIT_SUCCESS;
7221 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7224 if (G.run_list_level == 1 && G_interactive_fd) {
7225 /* Waits for completion, then fg's main shell */
7226 rcode = checkjobs_and_fg_shell(pi);
7227 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7228 check_and_run_traps(0);
7231 { /* This one just waits for completion */
7232 rcode = checkjobs(pi);
7233 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7234 check_and_run_traps(0);
7236 G.last_exitcode = rcode;
7240 /* Analyze how result affects subsequent commands */
7242 if (rword == RES_IF || rword == RES_ELIF)
7245 #if ENABLE_HUSH_LOOPS
7246 /* Beware of "while false; true; do ..."! */
7247 if (pi->next && pi->next->res_word == RES_DO) {
7248 if (rword == RES_WHILE) {
7250 /* "while false; do...done" - exitcode 0 */
7251 G.last_exitcode = rcode = EXIT_SUCCESS;
7252 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7253 goto check_jobs_and_break;
7256 if (rword == RES_UNTIL) {
7258 debug_printf_exec(": until expr is true: breaking\n");
7259 check_jobs_and_break:
7267 check_jobs_and_continue:
7274 #if ENABLE_HUSH_LOOPS
7279 #if ENABLE_HUSH_CASE
7283 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7287 /* Select which version we will use */
7288 static int run_and_free_list(struct pipe *pi)
7291 debug_printf_exec("run_and_free_list entered\n");
7293 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7294 rcode = run_list(pi);
7296 /* free_pipe_list has the side effect of clearing memory.
7297 * In the long run that function can be merged with run_list,
7298 * but doing that now would hobble the debugging effort. */
7300 debug_printf_exec("run_and_free_list return %d\n", rcode);
7305 /* Called a few times only (or even once if "sh -c") */
7306 static void init_sigmasks(void)
7310 sigset_t old_blocked_set;
7312 if (!G.inherited_set_is_saved) {
7313 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7314 G.inherited_set = G.blocked_set;
7316 old_blocked_set = G.blocked_set;
7318 mask = (1 << SIGQUIT);
7319 if (G_interactive_fd) {
7320 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7321 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7322 mask |= SPECIAL_JOB_SIGS;
7324 G.non_DFL_mask = mask;
7329 sigaddset(&G.blocked_set, sig);
7333 sigdelset(&G.blocked_set, SIGCHLD);
7335 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7336 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7338 /* POSIX allows shell to re-enable SIGCHLD
7339 * even if it was SIG_IGN on entry */
7340 #if ENABLE_HUSH_FAST
7341 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7342 if (!G.inherited_set_is_saved)
7343 signal(SIGCHLD, SIGCHLD_handler);
7345 if (!G.inherited_set_is_saved)
7346 signal(SIGCHLD, SIG_DFL);
7349 G.inherited_set_is_saved = 1;
7354 static void maybe_set_to_sigexit(int sig)
7356 void (*handler)(int);
7357 /* non_DFL_mask'ed signals are, well, masked,
7358 * no need to set handler for them.
7360 if (!((G.non_DFL_mask >> sig) & 1)) {
7361 handler = signal(sig, sigexit);
7362 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7363 signal(sig, handler);
7366 /* Set handlers to restore tty pgrp and exit */
7367 static void set_fatal_handlers(void)
7369 /* We _must_ restore tty pgrp on fatal signals */
7371 maybe_set_to_sigexit(SIGILL );
7372 maybe_set_to_sigexit(SIGFPE );
7373 maybe_set_to_sigexit(SIGBUS );
7374 maybe_set_to_sigexit(SIGSEGV);
7375 maybe_set_to_sigexit(SIGTRAP);
7376 } /* else: hush is perfect. what SEGV? */
7377 maybe_set_to_sigexit(SIGABRT);
7378 /* bash 3.2 seems to handle these just like 'fatal' ones */
7379 maybe_set_to_sigexit(SIGPIPE);
7380 maybe_set_to_sigexit(SIGALRM);
7381 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7382 * if we aren't interactive... but in this case
7383 * we never want to restore pgrp on exit, and this fn is not called */
7384 /*maybe_set_to_sigexit(SIGHUP );*/
7385 /*maybe_set_to_sigexit(SIGTERM);*/
7386 /*maybe_set_to_sigexit(SIGINT );*/
7390 static int set_mode(int state, char mode, const char *o_opt)
7398 IF_HUSH_MODE_X(G_x_mode = state;)
7402 /* "set -+o" without parameter.
7403 * in bash, set -o produces this output:
7407 * We always use the second form.
7409 const char *p = o_opt_strings;
7412 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7418 idx = index_in_strings(o_opt_strings, o_opt);
7420 G.o_opt[idx] = state;
7424 return EXIT_FAILURE;
7426 return EXIT_SUCCESS;
7429 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7430 int hush_main(int argc, char **argv)
7433 unsigned builtin_argc;
7435 struct variable *cur_var;
7436 struct variable shell_ver;
7439 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7440 G.last_exitcode = EXIT_SUCCESS;
7442 G.argv0_for_re_execing = argv[0];
7444 /* Deal with HUSH_VERSION */
7445 memset(&shell_ver, 0, sizeof(shell_ver));
7446 shell_ver.flg_export = 1;
7447 shell_ver.flg_read_only = 1;
7448 /* Code which handles ${var<op>...} needs writable values for all variables,
7449 * therefore we xstrdup: */
7450 shell_ver.varstr = xstrdup(hush_version_str),
7451 G.top_var = &shell_ver;
7452 /* Create shell local variables from the values
7453 * currently living in the environment */
7454 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7455 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7456 cur_var = G.top_var;
7459 char *value = strchr(*e, '=');
7460 if (value) { /* paranoia */
7461 cur_var->next = xzalloc(sizeof(*cur_var));
7462 cur_var = cur_var->next;
7463 cur_var->varstr = *e;
7464 cur_var->max_len = strlen(*e);
7465 cur_var->flg_export = 1;
7469 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7470 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7471 putenv(shell_ver.varstr);
7474 set_pwd_var(/*exp:*/ 1);
7475 /* bash also exports SHLVL and _,
7476 * and sets (but doesn't export) the following variables:
7478 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7479 * BASH_VERSION='3.2.0(1)-release'
7481 * MACHTYPE=i386-pc-linux-gnu
7483 * HOSTNAME=<xxxxxxxxxx>
7484 * PPID=<NNNNN> - we also do it elsewhere
7495 * PIPESTATUS=([0]="0")
7496 * HISTFILE=/<xxx>/.bash_history
7500 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7502 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7512 #if ENABLE_FEATURE_EDITING
7513 G.line_input_state = new_line_input_t(FOR_SHELL);
7514 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7516 const char *hp = get_local_var_value("HISTFILE");
7518 hp = get_local_var_value("HOME");
7520 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7521 //set_local_var(xasprintf("HISTFILE=%s", ...));
7528 G.global_argc = argc;
7529 G.global_argv = argv;
7530 /* Initialize some more globals to non-zero values */
7531 cmdedit_update_prompt();
7533 if (setjmp(die_jmp)) {
7534 /* xfunc has failed! die die die */
7535 /* no EXIT traps, this is an escape hatch! */
7537 hush_exit(xfunc_error_retval);
7540 /* Shell is non-interactive at first. We need to call
7541 * init_sigmasks() if we are going to execute "sh <script>",
7542 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7543 * If we later decide that we are interactive, we run init_sigmasks()
7544 * in order to intercept (more) signals.
7548 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7551 opt = getopt(argc, argv, "+c:xins"
7554 # if ENABLE_HUSH_FUNCTIONS
7564 * sh ... -c 'script'
7565 * sh ... -c 'script' ARG0 [ARG1...]
7566 * On NOMMU, if builtin_argc != 0,
7567 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7568 * "" needs to be replaced with NULL
7569 * and BARGV vector fed to builtin function.
7570 * Note: the form without ARG0 never happens:
7571 * sh ... -c 'builtin' BARGV... ""
7574 G.root_pid = getpid();
7575 G.root_ppid = getppid();
7577 G.global_argv = argv + optind;
7578 G.global_argc = argc - optind;
7580 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7581 const struct built_in_command *x;
7584 x = find_builtin(optarg);
7585 if (x) { /* paranoia */
7586 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7587 G.global_argv += builtin_argc;
7588 G.global_argv[-1] = NULL; /* replace "" */
7589 G.last_exitcode = x->b_function(argv + optind - 1);
7593 if (!G.global_argv[0]) {
7594 /* -c 'script' (no params): prevent empty $0 */
7595 G.global_argv--; /* points to argv[i] of 'script' */
7596 G.global_argv[0] = argv[0];
7598 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7600 parse_and_run_string(optarg);
7603 /* Well, we cannot just declare interactiveness,
7604 * we have to have some stuff (ctty, etc) */
7605 /* G_interactive_fd++; */
7608 /* "-s" means "read from stdin", but this is how we always
7609 * operate, so simply do nothing here. */
7612 case '<': /* "big heredoc" support */
7613 full_write1_str(optarg);
7616 unsigned long long empty_trap_mask;
7618 G.root_pid = bb_strtou(optarg, &optarg, 16);
7620 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7622 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7624 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7626 builtin_argc = bb_strtou(optarg, &optarg, 16);
7628 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7629 if (empty_trap_mask != 0) {
7632 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7633 for (sig = 1; sig < NSIG; sig++) {
7634 if (empty_trap_mask & (1LL << sig)) {
7635 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7636 sigaddset(&G.blocked_set, sig);
7639 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7641 # if ENABLE_HUSH_LOOPS
7643 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7649 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7651 # if ENABLE_HUSH_FUNCTIONS
7653 struct function *funcp = new_function(optarg);
7654 /* funcp->name is already set to optarg */
7655 /* funcp->body is set to NULL. It's a special case. */
7656 funcp->body_as_string = argv[optind];
7664 if (set_mode(1, opt, NULL) == 0) /* no error */
7668 fprintf(stderr, "Usage: sh [FILE]...\n"
7669 " or: sh -c command [args]...\n\n");
7675 } /* option parsing loop */
7678 G.root_pid = getpid();
7679 G.root_ppid = getppid();
7682 /* If we are login shell... */
7683 if (argv[0] && argv[0][0] == '-') {
7685 debug_printf("sourcing /etc/profile\n");
7686 input = fopen_for_read("/etc/profile");
7687 if (input != NULL) {
7688 close_on_exec_on(fileno(input));
7690 parse_and_run_file(input);
7693 /* bash: after sourcing /etc/profile,
7694 * tries to source (in the given order):
7695 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7696 * stopping on first found. --noprofile turns this off.
7697 * bash also sources ~/.bash_logout on exit.
7698 * If called as sh, skips .bash_XXX files.
7705 * "bash <script>" (which is never interactive (unless -i?))
7706 * sources $BASH_ENV here (without scanning $PATH).
7707 * If called as sh, does the same but with $ENV.
7709 debug_printf("running script '%s'\n", argv[optind]);
7710 G.global_argv = argv + optind;
7711 G.global_argc = argc - optind;
7712 input = xfopen_for_read(argv[optind]);
7713 close_on_exec_on(fileno(input));
7715 parse_and_run_file(input);
7716 #if ENABLE_FEATURE_CLEAN_UP
7722 /* Up to here, shell was non-interactive. Now it may become one.
7723 * NB: don't forget to (re)run init_sigmasks() as needed.
7726 /* A shell is interactive if the '-i' flag was given,
7727 * or if all of the following conditions are met:
7729 * no arguments remaining or the -s flag given
7730 * standard input is a terminal
7731 * standard output is a terminal
7732 * Refer to Posix.2, the description of the 'sh' utility.
7735 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7736 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7737 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7738 if (G_saved_tty_pgrp < 0)
7739 G_saved_tty_pgrp = 0;
7741 /* try to dup stdin to high fd#, >= 255 */
7742 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7743 if (G_interactive_fd < 0) {
7744 /* try to dup to any fd */
7745 G_interactive_fd = dup(STDIN_FILENO);
7746 if (G_interactive_fd < 0) {
7748 G_interactive_fd = 0;
7749 G_saved_tty_pgrp = 0;
7752 // TODO: track & disallow any attempts of user
7753 // to (inadvertently) close/redirect G_interactive_fd
7755 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7756 if (G_interactive_fd) {
7757 close_on_exec_on(G_interactive_fd);
7759 if (G_saved_tty_pgrp) {
7760 /* If we were run as 'hush &', sleep until we are
7761 * in the foreground (tty pgrp == our pgrp).
7762 * If we get started under a job aware app (like bash),
7763 * make sure we are now in charge so we don't fight over
7764 * who gets the foreground */
7766 pid_t shell_pgrp = getpgrp();
7767 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7768 if (G_saved_tty_pgrp == shell_pgrp)
7770 /* send TTIN to ourself (should stop us) */
7771 kill(- shell_pgrp, SIGTTIN);
7775 /* Block some signals */
7778 if (G_saved_tty_pgrp) {
7779 /* Set other signals to restore saved_tty_pgrp */
7780 set_fatal_handlers();
7781 /* Put ourselves in our own process group
7782 * (bash, too, does this only if ctty is available) */
7783 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7784 /* Grab control of the terminal */
7785 tcsetpgrp(G_interactive_fd, getpid());
7787 /* -1 is special - makes xfuncs longjmp, not exit
7788 * (we reset die_sleep = 0 whereever we [v]fork) */
7789 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7793 #elif ENABLE_HUSH_INTERACTIVE
7794 /* No job control compiled in, only prompt/line editing */
7795 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7796 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7797 if (G_interactive_fd < 0) {
7798 /* try to dup to any fd */
7799 G_interactive_fd = dup(STDIN_FILENO);
7800 if (G_interactive_fd < 0)
7802 G_interactive_fd = 0;
7805 if (G_interactive_fd) {
7806 close_on_exec_on(G_interactive_fd);
7810 /* We have interactiveness code disabled */
7814 * if interactive but not a login shell, sources ~/.bashrc
7815 * (--norc turns this off, --rcfile <file> overrides)
7818 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7819 /* note: ash and hush share this string */
7820 printf("\n\n%s %s\n"
7821 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7824 "hush - the humble shell"
7828 parse_and_run_file(stdin);
7831 #if ENABLE_FEATURE_CLEAN_UP
7832 if (G.cwd != bb_msg_unknown)
7834 cur_var = G.top_var->next;
7836 struct variable *tmp = cur_var;
7837 if (!cur_var->max_len)
7838 free(cur_var->varstr);
7839 cur_var = cur_var->next;
7843 hush_exit(G.last_exitcode);
7848 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7849 int msh_main(int argc, char **argv)
7851 //bb_error_msg("msh is deprecated, please use hush instead");
7852 return hush_main(argc, argv);
7860 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7865 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7872 return applet_main_func(argc, argv - argc);
7875 static int FAST_FUNC builtin_test(char **argv)
7877 return run_applet_main(argv, test_main);
7880 static int FAST_FUNC builtin_echo(char **argv)
7882 return run_applet_main(argv, echo_main);
7886 static int FAST_FUNC builtin_printf(char **argv)
7888 return run_applet_main(argv, printf_main);
7892 static char **skip_dash_dash(char **argv)
7895 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7900 static int FAST_FUNC builtin_eval(char **argv)
7902 int rcode = EXIT_SUCCESS;
7904 argv = skip_dash_dash(argv);
7906 char *str = expand_strvec_to_string(argv);
7908 * eval "echo Hi; done" ("done" is syntax error):
7909 * "echo Hi" will not execute too.
7911 parse_and_run_string(str);
7913 rcode = G.last_exitcode;
7918 static int FAST_FUNC builtin_cd(char **argv)
7922 argv = skip_dash_dash(argv);
7924 if (newdir == NULL) {
7925 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7926 * bash says "bash: cd: HOME not set" and does nothing
7929 const char *home = get_local_var_value("HOME");
7930 newdir = home ? home : "/";
7932 if (chdir(newdir)) {
7933 /* Mimic bash message exactly */
7934 bb_perror_msg("cd: %s", newdir);
7935 return EXIT_FAILURE;
7937 /* Read current dir (get_cwd(1) is inside) and set PWD.
7938 * Note: do not enforce exporting. If PWD was unset or unexported,
7939 * set it again, but do not export. bash does the same.
7941 set_pwd_var(/*exp:*/ 0);
7942 return EXIT_SUCCESS;
7945 static int FAST_FUNC builtin_exec(char **argv)
7947 argv = skip_dash_dash(argv);
7948 if (argv[0] == NULL)
7949 return EXIT_SUCCESS; /* bash does this */
7951 /* Careful: we can end up here after [v]fork. Do not restore
7952 * tty pgrp then, only top-level shell process does that */
7953 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7954 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7956 /* TODO: if exec fails, bash does NOT exit! We do.
7957 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7958 * and tcsetpgrp, and this is inherently racy.
7960 execvp_or_die(argv);
7963 static int FAST_FUNC builtin_exit(char **argv)
7965 debug_printf_exec("%s()\n", __func__);
7967 /* interactive bash:
7968 * # trap "echo EEE" EXIT
7971 * There are stopped jobs.
7972 * (if there are _stopped_ jobs, running ones don't count)
7975 # EEE (then bash exits)
7977 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
7980 /* note: EXIT trap is run by hush_exit */
7981 argv = skip_dash_dash(argv);
7982 if (argv[0] == NULL)
7983 hush_exit(G.last_exitcode);
7984 /* mimic bash: exit 123abc == exit 255 + error msg */
7985 xfunc_error_retval = 255;
7986 /* bash: exit -2 == exit 254, no error msg */
7987 hush_exit(xatoi(argv[0]) & 0xff);
7990 static void print_escaped(const char *s)
7995 const char *p = strchrnul(s, '\'');
7996 /* print 'xxxx', possibly just '' */
7997 printf("'%.*s'", (int)(p - s), s);
8002 /* s points to '; print "'''...'''" */
8004 do putchar('\''); while (*++s == '\'');
8009 #if !ENABLE_HUSH_LOCAL
8010 #define helper_export_local(argv, exp, lvl) \
8011 helper_export_local(argv, exp)
8013 static void helper_export_local(char **argv, int exp, int lvl)
8017 char *name_end = strchrnul(name, '=');
8019 /* So far we do not check that name is valid (TODO?) */
8021 if (*name_end == '\0') {
8022 struct variable *var, **vpp;
8024 vpp = get_ptr_to_local_var(name, name_end - name);
8025 var = vpp ? *vpp : NULL;
8027 if (exp == -1) { /* unexporting? */
8028 /* export -n NAME (without =VALUE) */
8030 var->flg_export = 0;
8031 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8033 } /* else: export -n NOT_EXISTING_VAR: no-op */
8036 if (exp == 1) { /* exporting? */
8037 /* export NAME (without =VALUE) */
8039 var->flg_export = 1;
8040 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8041 putenv(var->varstr);
8045 /* Exporting non-existing variable.
8046 * bash does not put it in environment,
8047 * but remembers that it is exported,
8048 * and does put it in env when it is set later.
8049 * We just set it to "" and export. */
8050 /* Or, it's "local NAME" (without =VALUE).
8051 * bash sets the value to "". */
8052 name = xasprintf("%s=", name);
8054 /* (Un)exporting/making local NAME=VALUE */
8055 name = xstrdup(name);
8057 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8061 static int FAST_FUNC builtin_export(char **argv)
8063 unsigned opt_unexport;
8065 #if ENABLE_HUSH_EXPORT_N
8066 /* "!": do not abort on errors */
8067 opt_unexport = getopt32(argv, "!n");
8068 if (opt_unexport == (uint32_t)-1)
8069 return EXIT_FAILURE;
8076 if (argv[0] == NULL) {
8083 /* ash emits: export VAR='VAL'
8084 * bash: declare -x VAR="VAL"
8085 * we follow ash example */
8086 const char *s = *e++;
8087 const char *p = strchr(s, '=');
8089 if (!p) /* wtf? take next variable */
8092 printf("export %.*s", (int)(p - s) + 1, s);
8093 print_escaped(p + 1);
8097 /*fflush_all(); - done after each builtin anyway */
8099 return EXIT_SUCCESS;
8102 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8104 return EXIT_SUCCESS;
8107 #if ENABLE_HUSH_LOCAL
8108 static int FAST_FUNC builtin_local(char **argv)
8110 if (G.func_nest_level == 0) {
8111 bb_error_msg("%s: not in a function", argv[0]);
8112 return EXIT_FAILURE; /* bash compat */
8114 helper_export_local(argv, 0, G.func_nest_level);
8115 return EXIT_SUCCESS;
8119 static int FAST_FUNC builtin_trap(char **argv)
8125 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8130 /* No args: print all trapped */
8131 for (i = 0; i < NSIG; ++i) {
8134 print_escaped(G.traps[i]);
8135 /* note: bash adds "SIG", but only if invoked
8136 * as "bash". If called as "sh", or if set -o posix,
8137 * then it prints short signal names.
8138 * We are printing short names: */
8139 printf(" %s\n", get_signame(i));
8142 /*fflush_all(); - done after each builtin anyway */
8143 return EXIT_SUCCESS;
8147 /* If first arg is a number: reset all specified signals */
8148 sig = bb_strtou(*argv, NULL, 10);
8154 sig = get_signum(*argv++);
8155 if (sig < 0 || sig >= NSIG) {
8157 /* Mimic bash message exactly */
8158 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8163 G.traps[sig] = xstrdup(new_cmd);
8165 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8166 get_signame(sig), sig, G.traps[sig]);
8168 /* There is no signal for 0 (EXIT) */
8173 sigaddset(&G.blocked_set, sig);
8175 /* There was a trap handler, we are removing it
8176 * (if sig has non-DFL handling,
8177 * we don't need to do anything) */
8178 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8180 sigdelset(&G.blocked_set, sig);
8183 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8187 if (!argv[1]) { /* no second arg */
8188 bb_error_msg("trap: invalid arguments");
8189 return EXIT_FAILURE;
8192 /* First arg is "-": reset all specified to default */
8193 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8194 /* Everything else: set arg as signal handler
8195 * (includes "" case, which ignores signal) */
8196 if (argv[0][0] == '-') {
8197 if (argv[0][1] == '\0') { /* "-" */
8198 /* new_cmd remains NULL: "reset these sigs" */
8201 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8204 /* else: "-something", no special meaning */
8209 goto process_sig_list;
8212 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8213 static int FAST_FUNC builtin_type(char **argv)
8215 int ret = EXIT_SUCCESS;
8221 if (0) {} /* make conditional compile easier below */
8222 /*else if (find_alias(*argv))
8223 type = "an alias";*/
8224 #if ENABLE_HUSH_FUNCTIONS
8225 else if (find_function(*argv))
8226 type = "a function";
8228 else if (find_builtin(*argv))
8229 type = "a shell builtin";
8230 else if ((path = find_in_path(*argv)) != NULL)
8233 bb_error_msg("type: %s: not found", *argv);
8238 printf("%s is %s\n", *argv, type);
8246 /* built-in 'fg' and 'bg' handler */
8247 static int FAST_FUNC builtin_fg_bg(char **argv)
8252 if (!G_interactive_fd)
8253 return EXIT_FAILURE;
8255 /* If they gave us no args, assume they want the last backgrounded task */
8257 for (pi = G.job_list; pi; pi = pi->next) {
8258 if (pi->jobid == G.last_jobid) {
8262 bb_error_msg("%s: no current job", argv[0]);
8263 return EXIT_FAILURE;
8265 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8266 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8267 return EXIT_FAILURE;
8269 for (pi = G.job_list; pi; pi = pi->next) {
8270 if (pi->jobid == jobnum) {
8274 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8275 return EXIT_FAILURE;
8277 /* TODO: bash prints a string representation
8278 * of job being foregrounded (like "sleep 1 | cat") */
8279 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8280 /* Put the job into the foreground. */
8281 tcsetpgrp(G_interactive_fd, pi->pgrp);
8284 /* Restart the processes in the job */
8285 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8286 for (i = 0; i < pi->num_cmds; i++) {
8287 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8288 pi->cmds[i].is_stopped = 0;
8290 pi->stopped_cmds = 0;
8292 i = kill(- pi->pgrp, SIGCONT);
8294 if (errno == ESRCH) {
8295 delete_finished_bg_job(pi);
8296 return EXIT_SUCCESS;
8298 bb_perror_msg("kill (SIGCONT)");
8301 if (argv[0][0] == 'f') {
8303 return checkjobs_and_fg_shell(pi);
8305 return EXIT_SUCCESS;
8309 #if ENABLE_HUSH_HELP
8310 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8312 const struct built_in_command *x;
8315 "Built-in commands:\n"
8316 "------------------\n");
8317 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8319 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8322 return EXIT_SUCCESS;
8327 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8330 const char *status_string;
8332 for (job = G.job_list; job; job = job->next) {
8333 if (job->alive_cmds == job->stopped_cmds)
8334 status_string = "Stopped";
8336 status_string = "Running";
8338 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8340 return EXIT_SUCCESS;
8345 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8350 # ifdef M_TRIM_THRESHOLD
8351 /* Optional. Reduces probability of false positives */
8354 /* Crude attempt to find where "free memory" starts,
8355 * sans fragmentation. */
8357 l = (unsigned long)p;
8360 if (l < (unsigned long)p) l = (unsigned long)p;
8363 if (!G.memleak_value)
8364 G.memleak_value = l;
8366 l -= G.memleak_value;
8373 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8378 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8381 return EXIT_SUCCESS;
8384 static int FAST_FUNC builtin_read(char **argv)
8393 /* "!": do not abort on errors.
8394 * Option string must start with "sr" to match BUILTIN_READ_xxx
8396 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8397 if (read_flags == (uint32_t)-1)
8398 return EXIT_FAILURE;
8401 r = shell_builtin_read(set_local_var_from_halves,
8403 get_local_var_value("IFS"), /* can be NULL */
8411 if ((uintptr_t)r > 1) {
8412 bb_error_msg("%s", r);
8413 r = (char*)(uintptr_t)1;
8416 return (uintptr_t)r;
8419 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8420 * built-in 'set' handler
8422 * set [-abCefhmnuvx] [-o option] [argument...]
8423 * set [+abCefhmnuvx] [+o option] [argument...]
8424 * set -- [argument...]
8427 * Implementations shall support the options in both their hyphen and
8428 * plus-sign forms. These options can also be specified as options to sh.
8430 * Write out all variables and their values: set
8431 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8432 * Turn on the -x and -v options: set -xv
8433 * Unset all positional parameters: set --
8434 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8435 * Set the positional parameters to the expansion of x, even if x expands
8436 * with a leading '-' or '+': set -- $x
8438 * So far, we only support "set -- [argument...]" and some of the short names.
8440 static int FAST_FUNC builtin_set(char **argv)
8443 char **pp, **g_argv;
8444 char *arg = *++argv;
8448 for (e = G.top_var; e; e = e->next)
8450 return EXIT_SUCCESS;
8454 if (strcmp(arg, "--") == 0) {
8458 if (arg[0] != '+' && arg[0] != '-')
8460 for (n = 1; arg[n]; ++n) {
8461 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8463 if (arg[n] == 'o' && argv[1])
8466 } while ((arg = *++argv) != NULL);
8467 /* Now argv[0] is 1st argument */
8470 return EXIT_SUCCESS;
8473 /* NB: G.global_argv[0] ($0) is never freed/changed */
8474 g_argv = G.global_argv;
8475 if (G.global_args_malloced) {
8481 G.global_args_malloced = 1;
8482 pp = xzalloc(sizeof(pp[0]) * 2);
8483 pp[0] = g_argv[0]; /* retain $0 */
8486 /* This realloc's G.global_argv */
8487 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8494 return EXIT_SUCCESS;
8496 /* Nothing known, so abort */
8498 bb_error_msg("set: %s: invalid option", arg);
8499 return EXIT_FAILURE;
8502 static int FAST_FUNC builtin_shift(char **argv)
8505 argv = skip_dash_dash(argv);
8509 if (n >= 0 && n < G.global_argc) {
8510 if (G.global_args_malloced) {
8513 free(G.global_argv[m++]);
8516 memmove(&G.global_argv[1], &G.global_argv[n+1],
8517 G.global_argc * sizeof(G.global_argv[0]));
8518 return EXIT_SUCCESS;
8520 return EXIT_FAILURE;
8523 static int FAST_FUNC builtin_source(char **argv)
8525 char *arg_path, *filename;
8528 #if ENABLE_HUSH_FUNCTIONS
8532 argv = skip_dash_dash(argv);
8535 /* bash says: "bash: .: filename argument required" */
8536 return 2; /* bash compat */
8539 if (!strchr(filename, '/')) {
8540 arg_path = find_in_path(filename);
8542 filename = arg_path;
8544 input = fopen_or_warn(filename, "r");
8547 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8548 return EXIT_FAILURE;
8550 close_on_exec_on(fileno(input));
8552 #if ENABLE_HUSH_FUNCTIONS
8553 sv_flg = G.flag_return_in_progress;
8554 /* "we are inside sourced file, ok to use return" */
8555 G.flag_return_in_progress = -1;
8557 save_and_replace_G_args(&sv, argv);
8559 parse_and_run_file(input);
8562 restore_G_args(&sv, argv);
8563 #if ENABLE_HUSH_FUNCTIONS
8564 G.flag_return_in_progress = sv_flg;
8567 return G.last_exitcode;
8570 static int FAST_FUNC builtin_umask(char **argv)
8576 argv = skip_dash_dash(argv);
8578 mode_t old_mask = mask;
8581 rc = bb_parse_mode(argv[0], &mask);
8586 * bash: umask: 'q': invalid symbolic mode operator
8587 * bash: umask: 999: octal number out of range
8589 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8594 printf("%04o\n", (unsigned) mask);
8595 /* fall through and restore mask which we set to 0 */
8599 return !rc; /* rc != 0 - success */
8602 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8603 static int FAST_FUNC builtin_unset(char **argv)
8608 /* "!": do not abort on errors */
8609 /* "+": stop at 1st non-option */
8610 opts = getopt32(argv, "!+vf");
8611 if (opts == (unsigned)-1)
8612 return EXIT_FAILURE;
8614 bb_error_msg("unset: -v and -f are exclusive");
8615 return EXIT_FAILURE;
8621 if (!(opts & 2)) { /* not -f */
8622 if (unset_local_var(*argv)) {
8623 /* unset <nonexistent_var> doesn't fail.
8624 * Error is when one tries to unset RO var.
8625 * Message was printed by unset_local_var. */
8629 #if ENABLE_HUSH_FUNCTIONS
8639 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8640 static int FAST_FUNC builtin_wait(char **argv)
8642 int ret = EXIT_SUCCESS;
8645 argv = skip_dash_dash(argv);
8646 if (argv[0] == NULL) {
8647 /* Don't care about wait results */
8648 /* Note 1: must wait until there are no more children */
8649 /* Note 2: must be interruptible */
8651 * $ sleep 3 & sleep 6 & wait
8656 * $ sleep 3 & sleep 6 & wait
8660 * ^C <-- after ~4 sec from keyboard
8663 sigaddset(&G.blocked_set, SIGCHLD);
8664 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8667 if (errno == ECHILD)
8669 /* Wait for SIGCHLD or any other signal of interest */
8670 /* sigtimedwait with infinite timeout: */
8671 sig = sigwaitinfo(&G.blocked_set, NULL);
8673 sig = check_and_run_traps(sig);
8674 if (sig && sig != SIGCHLD) { /* see note 2 */
8680 sigdelset(&G.blocked_set, SIGCHLD);
8681 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8685 /* This is probably buggy wrt interruptible-ness */
8687 pid_t pid = bb_strtou(*argv, NULL, 10);
8689 /* mimic bash message */
8690 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8691 return EXIT_FAILURE;
8693 if (waitpid(pid, &status, 0) == pid) {
8694 if (WIFSIGNALED(status))
8695 ret = 128 + WTERMSIG(status);
8696 else if (WIFEXITED(status))
8697 ret = WEXITSTATUS(status);
8701 bb_perror_msg("wait %s", *argv);
8710 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8711 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8714 def = bb_strtou(argv[1], NULL, 10);
8715 if (errno || def < def_min || argv[2]) {
8716 bb_error_msg("%s: bad arguments", argv[0]);
8724 #if ENABLE_HUSH_LOOPS
8725 static int FAST_FUNC builtin_break(char **argv)
8728 if (G.depth_of_loop == 0) {
8729 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8730 return EXIT_SUCCESS; /* bash compat */
8732 G.flag_break_continue++; /* BC_BREAK = 1 */
8734 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8735 if (depth == UINT_MAX)
8736 G.flag_break_continue = BC_BREAK;
8737 if (G.depth_of_loop < depth)
8738 G.depth_break_continue = G.depth_of_loop;
8740 return EXIT_SUCCESS;
8743 static int FAST_FUNC builtin_continue(char **argv)
8745 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8746 return builtin_break(argv);
8750 #if ENABLE_HUSH_FUNCTIONS
8751 static int FAST_FUNC builtin_return(char **argv)
8755 if (G.flag_return_in_progress != -1) {
8756 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8757 return EXIT_FAILURE; /* bash compat */
8760 G.flag_return_in_progress = 1;
8763 * out of range: wraps around at 256, does not error out
8764 * non-numeric param:
8765 * f() { false; return qwe; }; f; echo $?
8766 * bash: return: qwe: numeric argument required <== we do this
8767 * 255 <== we also do this
8769 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);