1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
90 /* #include <dmalloc.h> */
95 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97 #include "shell_common.h"
100 #if ENABLE_HUSH_RANDOM_SUPPORT
103 # define CLEAR_RANDOM_T(rnd) ((void)0)
106 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
110 //config: bool "hush"
113 //config: hush is a small shell (25k). It handles the normal flow control
114 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
115 //config: case/esac. Redirections, here documents, $((arithmetic))
116 //config: and functions are supported.
118 //config: It will compile and work on no-mmu systems.
120 //config: It does not handle select, aliases, tilde expansion,
121 //config: &>file and >&file redirection of stdout+stderr.
123 //config:config HUSH_BASH_COMPAT
124 //config: bool "bash-compatible extensions"
126 //config: depends on HUSH
128 //config: Enable bash-compatible extensions.
130 //config:config HUSH_BRACE_EXPANSION
131 //config: bool "Brace expansion"
133 //config: depends on HUSH_BASH_COMPAT
135 //config: Enable {abc,def} extension.
137 //config:config HUSH_HELP
138 //config: bool "help builtin"
140 //config: depends on HUSH
142 //config: Enable help builtin in hush. Code size + ~1 kbyte.
144 //config:config HUSH_INTERACTIVE
145 //config: bool "Interactive mode"
147 //config: depends on HUSH
149 //config: Enable interactive mode (prompt and command editing).
150 //config: Without this, hush simply reads and executes commands
151 //config: from stdin just like a shell script from a file.
152 //config: No prompt, no PS1/PS2 magic shell variables.
154 //config:config HUSH_SAVEHISTORY
155 //config: bool "Save command history to .hush_history"
157 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
159 //config: Enable history saving in hush.
161 //config:config HUSH_JOB
162 //config: bool "Job control"
164 //config: depends on HUSH_INTERACTIVE
166 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
167 //config: command (not entire shell), fg/bg builtins work. Without this option,
168 //config: "cmd &" still works by simply spawning a process and immediately
169 //config: prompting for next command (or executing next command in a script),
170 //config: but no separate process group is formed.
172 //config:config HUSH_TICK
173 //config: bool "Process substitution"
175 //config: depends on HUSH
177 //config: Enable process substitution `command` and $(command) in hush.
179 //config:config HUSH_IF
180 //config: bool "Support if/then/elif/else/fi"
182 //config: depends on HUSH
184 //config: Enable if/then/elif/else/fi in hush.
186 //config:config HUSH_LOOPS
187 //config: bool "Support for, while and until loops"
189 //config: depends on HUSH
191 //config: Enable for, while and until loops in hush.
193 //config:config HUSH_CASE
194 //config: bool "Support case ... esac statement"
196 //config: depends on HUSH
198 //config: Enable case ... esac statement in hush. +400 bytes.
200 //config:config HUSH_FUNCTIONS
201 //config: bool "Support funcname() { commands; } syntax"
203 //config: depends on HUSH
205 //config: Enable support for shell functions in hush. +800 bytes.
207 //config:config HUSH_LOCAL
208 //config: bool "Support local builtin"
210 //config: depends on HUSH_FUNCTIONS
212 //config: Enable support for local variables in functions.
214 //config:config HUSH_RANDOM_SUPPORT
215 //config: bool "Pseudorandom generator and $RANDOM variable"
217 //config: depends on HUSH
219 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
220 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
222 //config:config HUSH_EXPORT_N
223 //config: bool "Support 'export -n' option"
225 //config: depends on HUSH
227 //config: export -n unexports variables. It is a bash extension.
229 //config:config HUSH_MODE_X
230 //config: bool "Support 'hush -x' option and 'set -x' command"
232 //config: depends on HUSH
234 //config: This instructs hush to print commands before execution.
235 //config: Adds ~300 bytes.
238 //config: bool "msh (deprecated: aliased to hush)"
240 //config: select HUSH
242 //config: msh is deprecated and will be removed, please migrate to hush.
245 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
246 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
247 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
248 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
250 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
251 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
253 /* -i (interactive) and -s (read stdin) are also accepted,
254 * but currently do nothing, therefore aren't shown in help.
255 * NOMMU-specific options are not meant to be used by users,
256 * therefore we don't show them either.
258 //usage:#define hush_trivial_usage
259 //usage: "[-nx] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
260 //usage:#define hush_full_usage "\n\n"
261 //usage: "Unix shell interpreter"
263 //usage:#define msh_trivial_usage hush_trivial_usage
264 //usage:#define msh_full_usage hush_full_usage
266 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
267 //usage:# define sh_trivial_usage hush_trivial_usage
268 //usage:# define sh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
271 //usage:# define bash_trivial_usage hush_trivial_usage
272 //usage:# define bash_full_usage hush_full_usage
277 #define LEAK_HUNTING 0
278 #define BUILD_AS_NOMMU 0
279 /* Enable/disable sanity checks. Ok to enable in production,
280 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
281 * Keeping 1 for now even in released versions.
284 /* Slightly bigger (+200 bytes), but faster hush.
285 * So far it only enables a trick with counting SIGCHLDs and forks,
286 * which allows us to do fewer waitpid's.
287 * (we can detect a case where neither forks were done nor SIGCHLDs happened
288 * and therefore waitpid will return the same result as last time)
290 #define ENABLE_HUSH_FAST 0
291 /* TODO: implement simplified code for users which do not need ${var%...} ops
292 * So far ${var%...} ops are always enabled:
294 #define ENABLE_HUSH_DOLLAR_OPS 1
299 # undef USE_FOR_NOMMU
302 # define USE_FOR_NOMMU(...) __VA_ARGS__
303 # define USE_FOR_MMU(...)
306 #include "NUM_APPLETS.h"
308 /* STANDALONE does not make sense, and won't compile */
309 # undef CONFIG_FEATURE_SH_STANDALONE
310 # undef ENABLE_FEATURE_SH_STANDALONE
311 # undef IF_FEATURE_SH_STANDALONE
312 # undef IF_NOT_FEATURE_SH_STANDALONE
313 # define ENABLE_FEATURE_SH_STANDALONE 0
314 # define IF_FEATURE_SH_STANDALONE(...)
315 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
318 #if !ENABLE_HUSH_INTERACTIVE
319 # undef ENABLE_FEATURE_EDITING
320 # define ENABLE_FEATURE_EDITING 0
321 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
322 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
325 /* Do we support ANY keywords? */
326 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
327 # define HAS_KEYWORDS 1
328 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
329 # define IF_HAS_NO_KEYWORDS(...)
331 # define HAS_KEYWORDS 0
332 # define IF_HAS_KEYWORDS(...)
333 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
336 /* If you comment out one of these below, it will be #defined later
337 * to perform debug printfs to stderr: */
338 #define debug_printf(...) do {} while (0)
339 /* Finer-grained debug switches */
340 #define debug_printf_parse(...) do {} while (0)
341 #define debug_print_tree(a, b) do {} while (0)
342 #define debug_printf_exec(...) do {} while (0)
343 #define debug_printf_env(...) do {} while (0)
344 #define debug_printf_jobs(...) do {} while (0)
345 #define debug_printf_expand(...) do {} while (0)
346 #define debug_printf_varexp(...) do {} while (0)
347 #define debug_printf_glob(...) do {} while (0)
348 #define debug_printf_list(...) do {} while (0)
349 #define debug_printf_subst(...) do {} while (0)
350 #define debug_printf_clean(...) do {} while (0)
352 #define ERR_PTR ((void*)(long)1)
354 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
356 #define _SPECIAL_VARS_STR "_*@$!?#"
357 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
358 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
359 #if ENABLE_HUSH_BASH_COMPAT
360 /* Support / and // replace ops */
361 /* Note that // is stored as \ in "encoded" string representation */
362 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
363 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
364 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
366 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
367 # define VAR_SUBST_OPS "%#:-=+?"
368 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
371 #define SPECIAL_VAR_SYMBOL 3
375 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
377 /* This supports saving pointers malloced in vfork child,
378 * to be freed in the parent.
381 typedef struct nommu_save_t {
383 struct variable *old_vars;
385 char **argv_from_re_execing;
398 #if ENABLE_HUSH_LOOPS
405 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
410 /* three pseudo-keywords support contrived "case" syntax: */
411 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
412 RES_MATCH , /* "word)" */
413 RES_CASE_BODY, /* "this command is inside CASE" */
420 typedef struct o_string {
422 int length; /* position where data is appended */
425 /* At least some part of the string was inside '' or "",
426 * possibly empty one: word"", wo''rd etc. */
427 smallint has_quoted_part;
428 smallint has_empty_slot;
429 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
432 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
434 /* Protect newly added chars against globbing
435 * by prepending \ to *, ?, [, \ */
436 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
439 MAYBE_ASSIGNMENT = 0,
440 DEFINITELY_ASSIGNMENT = 1,
442 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
445 /* Used for initialization: o_string foo = NULL_O_STRING; */
446 #define NULL_O_STRING { NULL }
448 typedef struct in_str {
450 /* eof_flag=1: last char in ->p is really an EOF */
451 char eof_flag; /* meaningless if ->p == NULL */
453 #if ENABLE_HUSH_INTERACTIVE
454 smallint promptmode; /* 0: PS1, 1: PS2 */
458 int (*get) (struct in_str *) FAST_FUNC;
459 int (*peek) (struct in_str *) FAST_FUNC;
461 #define i_getch(input) ((input)->get(input))
462 #define i_peek(input) ((input)->peek(input))
464 /* The descrip member of this structure is only used to make
465 * debugging output pretty */
466 static const struct {
468 signed char default_fd;
471 { O_RDONLY, 0, "<" },
472 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
473 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
474 { O_CREAT|O_RDWR, 1, "<>" },
475 { O_RDONLY, 0, "<<" },
476 /* Should not be needed. Bogus default_fd helps in debugging */
477 /* { O_RDONLY, 77, "<<" }, */
480 struct redir_struct {
481 struct redir_struct *next;
482 char *rd_filename; /* filename */
483 int rd_fd; /* fd to redirect */
484 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
486 smallint rd_type; /* (enum redir_type) */
487 /* note: for heredocs, rd_filename contains heredoc delimiter,
488 * and subsequently heredoc itself; and rd_dup is a bitmask:
489 * bit 0: do we need to trim leading tabs?
490 * bit 1: is heredoc quoted (<<'delim' syntax) ?
493 typedef enum redir_type {
495 REDIRECT_OVERWRITE = 1,
498 REDIRECT_HEREDOC = 4,
499 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
502 REDIRFD_SYNTAX_ERR = -2,
503 REDIRFD_TO_FILE = -1,
504 /* otherwise, rd_fd is redirected to rd_dup */
506 HEREDOC_SKIPTABS = 1,
512 pid_t pid; /* 0 if exited */
513 int assignment_cnt; /* how many argv[i] are assignments? */
514 smallint is_stopped; /* is the command currently running? */
515 smallint cmd_type; /* CMD_xxx */
517 #define CMD_SUBSHELL 1
518 #if ENABLE_HUSH_BASH_COMPAT
519 /* used for "[[ EXPR ]]" */
520 # define CMD_SINGLEWORD_NOGLOB 2
522 #if ENABLE_HUSH_FUNCTIONS
523 # define CMD_FUNCDEF 3
526 smalluint cmd_exitcode;
527 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
530 char *group_as_string;
532 #if ENABLE_HUSH_FUNCTIONS
533 struct function *child_func;
534 /* This field is used to prevent a bug here:
535 * while...do f1() {a;}; f1; f1() {b;}; f1; done
536 * When we execute "f1() {a;}" cmd, we create new function and clear
537 * cmd->group, cmd->group_as_string, cmd->argv[0].
538 * When we execute "f1() {b;}", we notice that f1 exists,
539 * and that its "parent cmd" struct is still "alive",
540 * we put those fields back into cmd->xxx
541 * (struct function has ->parent_cmd ptr to facilitate that).
542 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
543 * Without this trick, loop would execute a;b;b;b;...
544 * instead of correct sequence a;b;a;b;...
545 * When command is freed, it severs the link
546 * (sets ->child_func->parent_cmd to NULL).
549 char **argv; /* command name and arguments */
550 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
551 * and on execution these are substituted with their values.
552 * Substitution can make _several_ words out of one argv[n]!
553 * Example: argv[0]=='.^C*^C.' here: echo .$*.
554 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
556 struct redir_struct *redirects; /* I/O redirections */
558 /* Is there anything in this command at all? */
559 #define IS_NULL_CMD(cmd) \
560 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
564 int num_cmds; /* total number of commands in pipe */
565 int alive_cmds; /* number of commands running (not exited) */
566 int stopped_cmds; /* number of commands alive, but stopped */
568 int jobid; /* job number */
569 pid_t pgrp; /* process group ID for the job */
570 char *cmdtext; /* name of job */
572 struct command *cmds; /* array of commands in pipe */
573 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
574 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
575 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
577 typedef enum pipe_style {
583 /* Is there anything in this pipe at all? */
584 #define IS_NULL_PIPE(pi) \
585 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
587 /* This holds pointers to the various results of parsing */
588 struct parse_context {
589 /* linked list of pipes */
590 struct pipe *list_head;
591 /* last pipe (being constructed right now) */
593 /* last command in pipe (being constructed right now) */
594 struct command *command;
595 /* last redirect in command->redirects list */
596 struct redir_struct *pending_redirect;
602 smallint ctx_inverted; /* "! cmd | cmd" */
604 smallint ctx_dsemicolon; /* ";;" seen */
606 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
608 /* group we are enclosed in:
609 * example: "if pipe1; pipe2; then pipe3; fi"
610 * when we see "if" or "then", we malloc and copy current context,
611 * and make ->stack point to it. then we parse pipeN.
612 * when closing "then" / fi" / whatever is found,
613 * we move list_head into ->stack->command->group,
614 * copy ->stack into current context, and delete ->stack.
615 * (parsing of { list } and ( list ) doesn't use this method)
617 struct parse_context *stack;
621 /* On program start, environ points to initial environment.
622 * putenv adds new pointers into it, unsetenv removes them.
623 * Neither of these (de)allocates the strings.
624 * setenv allocates new strings in malloc space and does putenv,
625 * and thus setenv is unusable (leaky) for shell's purposes */
626 #define setenv(...) setenv_is_leaky_dont_use()
628 struct variable *next;
629 char *varstr; /* points to "name=" portion */
630 #if ENABLE_HUSH_LOCAL
631 unsigned func_nest_level;
633 int max_len; /* if > 0, name is part of initial env; else name is malloced */
634 smallint flg_export; /* putenv should be done on this var */
635 smallint flg_read_only;
643 #if ENABLE_HUSH_FUNCTIONS
645 struct function *next;
647 struct command *parent_cmd;
650 char *body_as_string;
656 /* set -/+o OPT support. (TODO: make it optional)
657 * bash supports the following opts:
668 * interactive-comments on
686 static const char o_opt_strings[] ALIGN1 =
689 #if ENABLE_HUSH_MODE_X
696 #if ENABLE_HUSH_MODE_X
703 /* "Globals" within this file */
704 /* Sorted roughly by size (smaller offsets == smaller code) */
706 /* interactive_fd != 0 means we are an interactive shell.
707 * If we are, then saved_tty_pgrp can also be != 0, meaning
708 * that controlling tty is available. With saved_tty_pgrp == 0,
709 * job control still works, but terminal signals
710 * (^C, ^Z, ^Y, ^\) won't work at all, and background
711 * process groups can only be created with "cmd &".
712 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
713 * to give tty to the foreground process group,
714 * and will take it back when the group is stopped (^Z)
717 #if ENABLE_HUSH_INTERACTIVE
718 /* 'interactive_fd' is a fd# open to ctty, if we have one
719 * _AND_ if we decided to act interactively */
723 # define G_interactive_fd (G.interactive_fd)
725 # define G_interactive_fd 0
727 #if ENABLE_FEATURE_EDITING
728 line_input_t *line_input_state;
733 #if ENABLE_HUSH_RANDOM_SUPPORT
739 pid_t saved_tty_pgrp;
740 struct pipe *job_list;
741 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
743 # define G_saved_tty_pgrp 0
745 char o_opt[NUM_OPT_O];
746 #if ENABLE_HUSH_MODE_X
747 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
751 smallint flag_SIGINT;
752 #if ENABLE_HUSH_LOOPS
753 smallint flag_break_continue;
755 #if ENABLE_HUSH_FUNCTIONS
756 /* 0: outside of a function (or sourced file)
757 * -1: inside of a function, ok to use return builtin
758 * 1: return is invoked, skip all till end of func
760 smallint flag_return_in_progress;
762 smallint exiting; /* used to prevent EXIT trap recursion */
763 /* These four support $?, $#, and $1 */
764 smalluint last_exitcode;
765 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
766 smalluint global_args_malloced;
767 smalluint inherited_set_is_saved;
768 /* how many non-NULL argv's we have. NB: $# + 1 */
772 char *argv0_for_re_execing;
774 #if ENABLE_HUSH_LOOPS
775 unsigned depth_break_continue;
776 unsigned depth_of_loop;
780 struct variable *top_var;
781 char **expanded_assignments;
782 #if ENABLE_HUSH_FUNCTIONS
783 struct function *top_func;
784 # if ENABLE_HUSH_LOCAL
785 struct variable **shadowed_vars_pp;
786 unsigned func_nest_level;
789 /* Signal and trap handling */
791 unsigned count_SIGCHLD;
792 unsigned handled_SIGCHLD;
793 smallint we_have_children;
795 /* which signals have non-DFL handler (even with no traps set)? */
796 unsigned non_DFL_mask;
797 char **traps; /* char *traps[NSIG] */
798 sigset_t blocked_set;
799 sigset_t inherited_set;
801 unsigned long memleak_value;
804 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
806 #define G (*ptr_to_globals)
807 /* Not #defining name to G.name - this quickly gets unwieldy
808 * (too many defines). Also, I actually prefer to see when a variable
809 * is global, thus "G." prefix is a useful hint */
810 #define INIT_G() do { \
811 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
815 /* Function prototypes for builtins */
816 static int builtin_cd(char **argv) FAST_FUNC;
817 static int builtin_echo(char **argv) FAST_FUNC;
818 static int builtin_eval(char **argv) FAST_FUNC;
819 static int builtin_exec(char **argv) FAST_FUNC;
820 static int builtin_exit(char **argv) FAST_FUNC;
821 static int builtin_export(char **argv) FAST_FUNC;
823 static int builtin_fg_bg(char **argv) FAST_FUNC;
824 static int builtin_jobs(char **argv) FAST_FUNC;
827 static int builtin_help(char **argv) FAST_FUNC;
829 #if ENABLE_HUSH_LOCAL
830 static int builtin_local(char **argv) FAST_FUNC;
833 static int builtin_memleak(char **argv) FAST_FUNC;
836 static int builtin_printf(char **argv) FAST_FUNC;
838 static int builtin_pwd(char **argv) FAST_FUNC;
839 static int builtin_read(char **argv) FAST_FUNC;
840 static int builtin_set(char **argv) FAST_FUNC;
841 static int builtin_shift(char **argv) FAST_FUNC;
842 static int builtin_source(char **argv) FAST_FUNC;
843 static int builtin_test(char **argv) FAST_FUNC;
844 static int builtin_trap(char **argv) FAST_FUNC;
845 static int builtin_type(char **argv) FAST_FUNC;
846 static int builtin_true(char **argv) FAST_FUNC;
847 static int builtin_umask(char **argv) FAST_FUNC;
848 static int builtin_unset(char **argv) FAST_FUNC;
849 static int builtin_wait(char **argv) FAST_FUNC;
850 #if ENABLE_HUSH_LOOPS
851 static int builtin_break(char **argv) FAST_FUNC;
852 static int builtin_continue(char **argv) FAST_FUNC;
854 #if ENABLE_HUSH_FUNCTIONS
855 static int builtin_return(char **argv) FAST_FUNC;
858 /* Table of built-in functions. They can be forked or not, depending on
859 * context: within pipes, they fork. As simple commands, they do not.
860 * When used in non-forking context, they can change global variables
861 * in the parent shell process. If forked, of course they cannot.
862 * For example, 'unset foo | whatever' will parse and run, but foo will
863 * still be set at the end. */
864 struct built_in_command {
866 int (*b_function)(char **argv) FAST_FUNC;
869 # define BLTIN(cmd, func, help) { cmd, func, help }
871 # define BLTIN(cmd, func, help) { cmd, func }
875 static const struct built_in_command bltins1[] = {
876 BLTIN("." , builtin_source , "Run commands in a file"),
877 BLTIN(":" , builtin_true , NULL),
879 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
881 #if ENABLE_HUSH_LOOPS
882 BLTIN("break" , builtin_break , "Exit from a loop"),
884 BLTIN("cd" , builtin_cd , "Change directory"),
885 #if ENABLE_HUSH_LOOPS
886 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
888 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
889 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
890 BLTIN("exit" , builtin_exit , "Exit"),
891 BLTIN("export" , builtin_export , "Set environment variables"),
893 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
896 BLTIN("help" , builtin_help , NULL),
899 BLTIN("jobs" , builtin_jobs , "List jobs"),
901 #if ENABLE_HUSH_LOCAL
902 BLTIN("local" , builtin_local , "Set local variables"),
905 BLTIN("memleak" , builtin_memleak , NULL),
907 BLTIN("read" , builtin_read , "Input into variable"),
908 #if ENABLE_HUSH_FUNCTIONS
909 BLTIN("return" , builtin_return , "Return from a function"),
911 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
912 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
913 #if ENABLE_HUSH_BASH_COMPAT
914 BLTIN("source" , builtin_source , "Run commands in a file"),
916 BLTIN("trap" , builtin_trap , "Trap signals"),
917 BLTIN("type" , builtin_type , "Show command type"),
918 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
919 BLTIN("umask" , builtin_umask , "Set file creation mask"),
920 BLTIN("unset" , builtin_unset , "Unset variables"),
921 BLTIN("wait" , builtin_wait , "Wait for process"),
923 /* For now, echo and test are unconditionally enabled.
924 * Maybe make it configurable? */
925 static const struct built_in_command bltins2[] = {
926 BLTIN("[" , builtin_test , NULL),
927 BLTIN("echo" , builtin_echo , NULL),
929 BLTIN("printf" , builtin_printf , NULL),
931 BLTIN("pwd" , builtin_pwd , NULL),
932 BLTIN("test" , builtin_test , NULL),
939 /* prevent disasters with G.debug_indent < 0 */
940 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
941 # define debug_enter() (G.debug_indent++)
942 # define debug_leave() (G.debug_indent--)
944 # define indent() ((void)0)
945 # define debug_enter() ((void)0)
946 # define debug_leave() ((void)0)
950 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
953 #ifndef debug_printf_parse
954 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
957 #ifndef debug_printf_exec
958 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
961 #ifndef debug_printf_env
962 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
965 #ifndef debug_printf_jobs
966 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
967 # define DEBUG_JOBS 1
969 # define DEBUG_JOBS 0
972 #ifndef debug_printf_expand
973 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
974 # define DEBUG_EXPAND 1
976 # define DEBUG_EXPAND 0
979 #ifndef debug_printf_varexp
980 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
983 #ifndef debug_printf_glob
984 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
985 # define DEBUG_GLOB 1
987 # define DEBUG_GLOB 0
990 #ifndef debug_printf_list
991 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
994 #ifndef debug_printf_subst
995 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
998 #ifndef debug_printf_clean
999 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1000 # define DEBUG_CLEAN 1
1002 # define DEBUG_CLEAN 0
1006 static void debug_print_strings(const char *prefix, char **vv)
1009 fdprintf(2, "%s:\n", prefix);
1011 fdprintf(2, " '%s'\n", *vv++);
1014 # define debug_print_strings(prefix, vv) ((void)0)
1018 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1021 static void *xxmalloc(int lineno, size_t size)
1023 void *ptr = xmalloc((size + 0xff) & ~0xff);
1024 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1027 static void *xxrealloc(int lineno, void *ptr, size_t size)
1029 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1030 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1033 static char *xxstrdup(int lineno, const char *str)
1035 char *ptr = xstrdup(str);
1036 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1039 static void xxfree(void *ptr)
1041 fdprintf(2, "free %p\n", ptr);
1044 # define xmalloc(s) xxmalloc(__LINE__, s)
1045 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1046 # define xstrdup(s) xxstrdup(__LINE__, s)
1047 # define free(p) xxfree(p)
1051 /* Syntax and runtime errors. They always abort scripts.
1052 * In interactive use they usually discard unparsed and/or unexecuted commands
1053 * and return to the prompt.
1054 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1057 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1058 # define syntax_error(lineno, msg) syntax_error(msg)
1059 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1060 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1061 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1062 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1065 static void die_if_script(unsigned lineno, const char *fmt, ...)
1070 bb_error_msg("hush.c:%u", lineno);
1073 bb_verror_msg(fmt, p, NULL);
1075 if (!G_interactive_fd)
1079 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1082 bb_error_msg("syntax error: %s", msg);
1084 bb_error_msg("syntax error");
1087 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1089 bb_error_msg("syntax error at '%s'", msg);
1092 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1094 bb_error_msg("syntax error: unterminated %s", s);
1097 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1099 char msg[2] = { ch, '\0' };
1100 syntax_error_unterm_str(lineno, msg);
1103 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1108 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1112 # undef die_if_script
1113 # undef syntax_error
1114 # undef syntax_error_at
1115 # undef syntax_error_unterm_ch
1116 # undef syntax_error_unterm_str
1117 # undef syntax_error_unexpected_ch
1119 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1120 # define syntax_error(msg) syntax_error(__LINE__, msg)
1121 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1122 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1123 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1124 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1128 #if ENABLE_HUSH_INTERACTIVE
1129 static void cmdedit_update_prompt(void);
1131 # define cmdedit_update_prompt() ((void)0)
1135 /* Utility functions
1137 /* Replace each \x with x in place, return ptr past NUL. */
1138 static char *unbackslash(char *src)
1140 char *dst = src = strchrnul(src, '\\');
1144 if ((*dst++ = *src++) == '\0')
1150 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1171 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1172 v[count1 + count2] = NULL;
1175 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1179 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1181 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1182 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1185 #define add_strings_to_strings(strings, add, need_to_dup) \
1186 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1189 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1190 static char **add_string_to_strings(char **strings, char *add)
1195 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1198 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1200 char **ptr = add_string_to_strings(strings, add);
1201 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1204 #define add_string_to_strings(strings, add) \
1205 xx_add_string_to_strings(__LINE__, strings, add)
1208 static void free_strings(char **strings)
1223 /* Helpers for setting new $n and restoring them back
1225 typedef struct save_arg_t {
1229 smallint sv_g_malloced;
1232 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1236 sv->sv_argv0 = argv[0];
1237 sv->sv_g_argv = G.global_argv;
1238 sv->sv_g_argc = G.global_argc;
1239 sv->sv_g_malloced = G.global_args_malloced;
1241 argv[0] = G.global_argv[0]; /* retain $0 */
1242 G.global_argv = argv;
1243 G.global_args_malloced = 0;
1251 static void restore_G_args(save_arg_t *sv, char **argv)
1255 if (G.global_args_malloced) {
1256 /* someone ran "set -- arg1 arg2 ...", undo */
1258 while (*++pp) /* note: does not free $0 */
1260 free(G.global_argv);
1262 argv[0] = sv->sv_argv0;
1263 G.global_argv = sv->sv_g_argv;
1264 G.global_argc = sv->sv_g_argc;
1265 G.global_args_malloced = sv->sv_g_malloced;
1269 /* Basic theory of signal handling in shell
1270 * ========================================
1271 * This does not describe what hush does, rather, it is current understanding
1272 * what it _should_ do. If it doesn't, it's a bug.
1273 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1275 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1276 * is finished or backgrounded. It is the same in interactive and
1277 * non-interactive shells, and is the same regardless of whether
1278 * a user trap handler is installed or a shell special one is in effect.
1279 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1280 * backgrounds (i.e. stops) or kills all members of currently running
1283 * Wait builtin in interruptible by signals for which user trap is set
1284 * or by SIGINT in interactive shell.
1286 * Trap handlers will execute even within trap handlers. (right?)
1288 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1289 * except for handlers set to '' (empty string).
1291 * If job control is off, backgrounded commands ("cmd &")
1292 * have SIGINT, SIGQUIT set to SIG_IGN.
1294 * Commands which are run in command substitution ("`cmd`")
1295 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1297 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1298 * by the shell from its parent.
1300 * Signals which differ from SIG_DFL action
1301 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1304 * SIGTERM (interactive): ignore
1305 * SIGHUP (interactive):
1306 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1307 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1308 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1309 * that all pipe members are stopped. Try this in bash:
1310 * while :; do :; done - ^Z does not background it
1311 * (while :; do :; done) - ^Z backgrounds it
1312 * SIGINT (interactive): wait for last pipe, ignore the rest
1313 * of the command line, show prompt. NB: ^C does not send SIGINT
1314 * to interactive shell while shell is waiting for a pipe,
1315 * since shell is bg'ed (is not in foreground process group).
1316 * Example 1: this waits 5 sec, but does not execute ls:
1317 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1318 * Example 2: this does not wait and does not execute ls:
1319 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1320 * Example 3: this does not wait 5 sec, but executes ls:
1321 * "sleep 5; ls -l" + press ^C
1322 * Example 4: this does not wait and does not execute ls:
1323 * "sleep 5 & wait; ls -l" + press ^C
1325 * (What happens to signals which are IGN on shell start?)
1326 * (What happens with signal mask on shell start?)
1328 * Implementation in hush
1329 * ======================
1330 * We use in-kernel pending signal mask to determine which signals were sent.
1331 * We block all signals which we don't want to take action immediately,
1332 * i.e. we block all signals which need to have special handling as described
1333 * above, and all signals which have traps set.
1334 * After each pipe execution, we extract any pending signals via sigtimedwait()
1337 * unsigned non_DFL_mask: a mask of such "special" signals
1338 * sigset_t blocked_set: current blocked signal set
1341 * clear bit in blocked_set unless it is also in non_DFL_mask
1342 * "trap 'cmd' SIGxxx":
1343 * set bit in blocked_set (even if 'cmd' is '')
1344 * after [v]fork, if we plan to be a shell:
1345 * unblock signals with special interactive handling
1346 * (child shell is not interactive),
1347 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1348 * after [v]fork, if we plan to exec:
1349 * POSIX says fork clears pending signal mask in child - no need to clear it.
1350 * Restore blocked signal set to one inherited by shell just prior to exec.
1352 * Note: as a result, we do not use signal handlers much. The only uses
1353 * are to count SIGCHLDs
1354 * and to restore tty pgrp on signal-induced exit.
1357 * Standard says "When a subshell is entered, traps that are not being ignored
1358 * are set to the default actions". bash interprets it so that traps which
1359 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1362 SPECIAL_INTERACTIVE_SIGS = 0
1367 SPECIAL_JOB_SIGS = 0
1375 #if ENABLE_HUSH_FAST
1376 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1379 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1385 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1386 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1387 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1388 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1390 /* Restores tty foreground process group, and exits.
1391 * May be called as signal handler for fatal signal
1392 * (will resend signal to itself, producing correct exit state)
1393 * or called directly with -EXITCODE.
1394 * We also call it if xfunc is exiting. */
1395 static void sigexit(int sig) NORETURN;
1396 static void sigexit(int sig)
1398 /* Disable all signals: job control, SIGPIPE, etc. */
1399 sigprocmask_allsigs(SIG_BLOCK);
1401 /* Careful: we can end up here after [v]fork. Do not restore
1402 * tty pgrp then, only top-level shell process does that */
1403 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1404 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1406 /* Not a signal, just exit */
1410 kill_myself_with_sig(sig); /* does not return */
1414 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1415 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1419 /* Restores tty foreground process group, and exits. */
1420 static void hush_exit(int exitcode) NORETURN;
1421 static void hush_exit(int exitcode)
1424 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1425 /* Prevent recursion:
1426 * trap "echo Hi; exit" EXIT; exit
1429 /* argv[0] is unused */
1430 argv[1] = G.traps[0];
1432 G.exiting = 1; /* prevent EXIT trap recursion */
1433 /* Note: G.traps[0] is not cleared!
1434 * "trap" will still show it, if executed
1439 #if ENABLE_FEATURE_CLEAN_UP
1441 struct variable *cur_var;
1442 if (G.cwd != bb_msg_unknown)
1444 cur_var = G.top_var;
1446 struct variable *tmp = cur_var;
1447 if (!cur_var->max_len)
1448 free(cur_var->varstr);
1449 cur_var = cur_var->next;
1457 sigexit(- (exitcode & 0xff));
1464 static int check_and_run_traps(int sig)
1466 /* I want it in rodata, not in bss.
1467 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1468 * initializer. But other compilers may still use bss.
1469 * TODO: find more portable solution.
1471 static const struct timespec zero_timespec = { 0, 0 };
1472 smalluint save_rcode;
1479 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1483 if (G.traps && G.traps[sig]) {
1484 if (G.traps[sig][0]) {
1485 /* We have user-defined handler */
1487 /* argv[0] is unused */
1488 argv[1] = G.traps[sig];
1490 save_rcode = G.last_exitcode;
1492 G.last_exitcode = save_rcode;
1494 } /* else: "" trap, ignoring signal */
1497 /* not a trap: special action */
1499 #if ENABLE_HUSH_FAST
1502 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1506 /* Builtin was ^C'ed, make it look prettier: */
1514 /* bash is observed to signal whole process groups,
1515 * not individual processes */
1516 for (job = G.job_list; job; job = job->next) {
1519 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1520 if (kill(- job->pgrp, SIGHUP) == 0)
1521 kill(- job->pgrp, SIGCONT);
1526 default: /* ignored: */
1527 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1529 * we dont do 'last_sig = sig' here -> NOT returning this sig.
1530 * example: wait is not interrupted by TERM
1531 * in interactive shell, because TERM is ignored.
1540 static const char *get_cwd(int force)
1542 if (force || G.cwd == NULL) {
1543 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1544 * we must not try to free(bb_msg_unknown) */
1545 if (G.cwd == bb_msg_unknown)
1547 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1549 G.cwd = bb_msg_unknown;
1556 * Shell and environment variable support
1558 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1560 struct variable **pp;
1561 struct variable *cur;
1564 while ((cur = *pp) != NULL) {
1565 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1572 static const char* FAST_FUNC get_local_var_value(const char *name)
1574 struct variable **vpp;
1575 unsigned len = strlen(name);
1577 if (G.expanded_assignments) {
1578 char **cpp = G.expanded_assignments;
1581 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1582 return cp + len + 1;
1587 vpp = get_ptr_to_local_var(name, len);
1589 return (*vpp)->varstr + len + 1;
1591 if (strcmp(name, "PPID") == 0)
1592 return utoa(G.root_ppid);
1593 // bash compat: UID? EUID?
1594 #if ENABLE_HUSH_RANDOM_SUPPORT
1595 if (strcmp(name, "RANDOM") == 0)
1596 return utoa(next_random(&G.random_gen));
1601 /* str holds "NAME=VAL" and is expected to be malloced.
1602 * We take ownership of it.
1604 * 0: do not change export flag
1605 * (if creating new variable, flag will be 0)
1606 * 1: set export flag and putenv the variable
1607 * -1: clear export flag and unsetenv the variable
1608 * flg_read_only is set only when we handle -R var=val
1610 #if !BB_MMU && ENABLE_HUSH_LOCAL
1611 /* all params are used */
1612 #elif BB_MMU && ENABLE_HUSH_LOCAL
1613 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1614 set_local_var(str, flg_export, local_lvl)
1615 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1616 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1617 set_local_var(str, flg_export)
1618 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1619 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1620 set_local_var(str, flg_export, flg_read_only)
1622 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1624 struct variable **var_pp;
1625 struct variable *cur;
1629 eq_sign = strchr(str, '=');
1630 if (!eq_sign) { /* not expected to ever happen? */
1635 name_len = eq_sign - str + 1; /* including '=' */
1636 var_pp = &G.top_var;
1637 while ((cur = *var_pp) != NULL) {
1638 if (strncmp(cur->varstr, str, name_len) != 0) {
1639 var_pp = &cur->next;
1642 /* We found an existing var with this name */
1643 if (cur->flg_read_only) {
1647 bb_error_msg("%s: readonly variable", str);
1651 if (flg_export == -1) { // "&& cur->flg_export" ?
1652 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1657 #if ENABLE_HUSH_LOCAL
1658 if (cur->func_nest_level < local_lvl) {
1659 /* New variable is declared as local,
1660 * and existing one is global, or local
1661 * from enclosing function.
1662 * Remove and save old one: */
1663 *var_pp = cur->next;
1664 cur->next = *G.shadowed_vars_pp;
1665 *G.shadowed_vars_pp = cur;
1666 /* bash 3.2.33(1) and exported vars:
1668 * # f() { local z=a; env | grep ^z; }
1674 if (cur->flg_export)
1679 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1684 if (cur->max_len != 0) {
1685 if (cur->max_len >= strlen(str)) {
1686 /* This one is from startup env, reuse space */
1687 strcpy(cur->varstr, str);
1691 /* max_len == 0 signifies "malloced" var, which we can
1692 * (and has to) free */
1696 goto set_str_and_exp;
1699 /* Not found - create new variable struct */
1700 cur = xzalloc(sizeof(*cur));
1701 #if ENABLE_HUSH_LOCAL
1702 cur->func_nest_level = local_lvl;
1704 cur->next = *var_pp;
1710 cur->flg_read_only = flg_read_only;
1713 if (flg_export == 1)
1714 cur->flg_export = 1;
1715 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1716 cmdedit_update_prompt();
1717 if (cur->flg_export) {
1718 if (flg_export == -1) {
1719 cur->flg_export = 0;
1720 /* unsetenv was already done */
1722 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1723 return putenv(cur->varstr);
1729 /* Used at startup and after each cd */
1730 static void set_pwd_var(int exp)
1732 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1733 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1736 static int unset_local_var_len(const char *name, int name_len)
1738 struct variable *cur;
1739 struct variable **var_pp;
1742 return EXIT_SUCCESS;
1743 var_pp = &G.top_var;
1744 while ((cur = *var_pp) != NULL) {
1745 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1746 if (cur->flg_read_only) {
1747 bb_error_msg("%s: readonly variable", name);
1748 return EXIT_FAILURE;
1750 *var_pp = cur->next;
1751 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1752 bb_unsetenv(cur->varstr);
1753 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1754 cmdedit_update_prompt();
1758 return EXIT_SUCCESS;
1760 var_pp = &cur->next;
1762 return EXIT_SUCCESS;
1765 static int unset_local_var(const char *name)
1767 return unset_local_var_len(name, strlen(name));
1770 static void unset_vars(char **strings)
1778 const char *eq = strchrnul(*v, '=');
1779 unset_local_var_len(*v, (int)(eq - *v));
1785 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1787 char *var = xasprintf("%s=%s", name, val);
1788 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1793 * Helpers for "var1=val1 var2=val2 cmd" feature
1795 static void add_vars(struct variable *var)
1797 struct variable *next;
1801 var->next = G.top_var;
1803 if (var->flg_export) {
1804 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1805 putenv(var->varstr);
1807 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1813 static struct variable *set_vars_and_save_old(char **strings)
1816 struct variable *old = NULL;
1822 struct variable *var_p;
1823 struct variable **var_pp;
1826 eq = strchr(*s, '=');
1828 var_pp = get_ptr_to_local_var(*s, eq - *s);
1830 /* Remove variable from global linked list */
1832 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1833 *var_pp = var_p->next;
1834 /* Add it to returned list */
1838 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1849 static int FAST_FUNC static_get(struct in_str *i)
1860 static int FAST_FUNC static_peek(struct in_str *i)
1865 #if ENABLE_HUSH_INTERACTIVE
1867 static void cmdedit_update_prompt(void)
1869 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1870 G.PS1 = get_local_var_value("PS1");
1873 G.PS2 = get_local_var_value("PS2");
1881 static const char *setup_prompt_string(int promptmode)
1883 const char *prompt_str;
1884 debug_printf("setup_prompt_string %d ", promptmode);
1885 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1886 /* Set up the prompt */
1887 if (promptmode == 0) { /* PS1 */
1889 /* bash uses $PWD value, even if it is set by user.
1890 * It uses current dir only if PWD is unset.
1891 * We always use current dir. */
1892 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1897 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1898 debug_printf("result '%s'\n", prompt_str);
1902 static void get_user_input(struct in_str *i)
1905 const char *prompt_str;
1907 prompt_str = setup_prompt_string(i->promptmode);
1908 # if ENABLE_FEATURE_EDITING
1909 /* Enable command line editing only while a command line
1910 * is actually being read */
1912 /* Unicode support should be activated even if LANG is set
1913 * _during_ shell execution, not only if it was set when
1914 * shell was started. Therefore, re-check LANG every time:
1916 reinit_unicode(get_local_var_value("LANG"));
1919 /* buglet: SIGINT will not make new prompt to appear _at once_,
1920 * only after <Enter>. (^C will work) */
1921 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1922 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1923 check_and_run_traps(0);
1924 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1925 i->eof_flag = (r < 0);
1926 if (i->eof_flag) { /* EOF/error detected */
1927 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1928 G.user_input_buf[1] = '\0';
1933 if (i->last_char == '\0' || i->last_char == '\n') {
1934 /* Why check_and_run_traps here? Try this interactively:
1935 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
1936 * $ <[enter], repeatedly...>
1937 * Without check_and_run_traps, handler never runs.
1939 check_and_run_traps(0);
1940 fputs(prompt_str, stdout);
1943 G.user_input_buf[0] = r = fgetc(i->file);
1944 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1945 } while (G.flag_SIGINT);
1946 i->eof_flag = (r == EOF);
1948 i->p = G.user_input_buf;
1951 #endif /* INTERACTIVE */
1953 /* This is the magic location that prints prompts
1954 * and gets data back from the user */
1955 static int FAST_FUNC file_get(struct in_str *i)
1959 /* If there is data waiting, eat it up */
1960 if (i->p && *i->p) {
1961 #if ENABLE_HUSH_INTERACTIVE
1965 if (i->eof_flag && !*i->p)
1967 /* note: ch is never NUL */
1969 /* need to double check i->file because we might be doing something
1970 * more complicated by now, like sourcing or substituting. */
1971 #if ENABLE_HUSH_INTERACTIVE
1972 if (G_interactive_fd && i->file == stdin) {
1975 } while (!*i->p); /* need non-empty line */
1976 i->promptmode = 1; /* PS2 */
1980 do ch = fgetc(i->file); while (ch == '\0');
1982 debug_printf("file_get: got '%c' %d\n", ch, ch);
1987 /* All callers guarantee this routine will never
1988 * be used right after a newline, so prompting is not needed.
1990 static int FAST_FUNC file_peek(struct in_str *i)
1993 if (i->p && *i->p) {
1994 if (i->eof_flag && !i->p[1])
1997 /* note: ch is never NUL */
1999 do ch = fgetc(i->file); while (ch == '\0');
2000 i->eof_flag = (ch == EOF);
2001 i->peek_buf[0] = ch;
2002 i->peek_buf[1] = '\0';
2004 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2008 static void setup_file_in_str(struct in_str *i, FILE *f)
2010 memset(i, 0, sizeof(*i));
2011 i->peek = file_peek;
2013 /* i->promptmode = 0; - PS1 (memset did it) */
2018 static void setup_string_in_str(struct in_str *i, const char *s)
2020 memset(i, 0, sizeof(*i));
2021 i->peek = static_peek;
2022 i->get = static_get;
2023 /* i->promptmode = 0; - PS1 (memset did it) */
2025 /* i->eof_flag = 0; */
2032 #define B_CHUNK (32 * sizeof(char*))
2034 static void o_reset_to_empty_unquoted(o_string *o)
2037 o->has_quoted_part = 0;
2042 static void o_free(o_string *o)
2045 memset(o, 0, sizeof(*o));
2048 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2053 static void o_grow_by(o_string *o, int len)
2055 if (o->length + len > o->maxlen) {
2056 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2057 o->data = xrealloc(o->data, 1 + o->maxlen);
2061 static void o_addchr(o_string *o, int ch)
2063 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2065 o->data[o->length] = ch;
2067 o->data[o->length] = '\0';
2070 static void o_addblock(o_string *o, const char *str, int len)
2073 memcpy(&o->data[o->length], str, len);
2075 o->data[o->length] = '\0';
2078 static void o_addstr(o_string *o, const char *str)
2080 o_addblock(o, str, strlen(str));
2084 static void nommu_addchr(o_string *o, int ch)
2090 # define nommu_addchr(o, str) ((void)0)
2093 static void o_addstr_with_NUL(o_string *o, const char *str)
2095 o_addblock(o, str, strlen(str) + 1);
2099 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2100 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2101 * Apparently, on unquoted $v bash still does globbing
2102 * ("v='*.txt'; echo $v" prints all .txt files),
2103 * but NOT brace expansion! Thus, there should be TWO independent
2104 * quoting mechanisms on $v expansion side: one protects
2105 * $v from brace expansion, and other additionally protects "$v" against globbing.
2106 * We have only second one.
2109 #if ENABLE_HUSH_BRACE_EXPANSION
2110 # define MAYBE_BRACES "{}"
2112 # define MAYBE_BRACES ""
2115 /* My analysis of quoting semantics tells me that state information
2116 * is associated with a destination, not a source.
2118 static void o_addqchr(o_string *o, int ch)
2121 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2126 o->data[o->length] = '\\';
2129 o->data[o->length] = ch;
2131 o->data[o->length] = '\0';
2134 static void o_addQchr(o_string *o, int ch)
2137 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2138 && strchr("*?[\\" MAYBE_BRACES, ch)
2141 o->data[o->length] = '\\';
2145 o->data[o->length] = ch;
2147 o->data[o->length] = '\0';
2150 static void o_addqblock(o_string *o, const char *str, int len)
2155 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2156 if (ordinary_cnt > len) /* paranoia */
2158 o_addblock(o, str, ordinary_cnt);
2159 if (ordinary_cnt == len)
2161 str += ordinary_cnt;
2162 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2166 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2168 o->data[o->length] = '\\';
2172 o->data[o->length] = ch;
2174 o->data[o->length] = '\0';
2178 static void o_addQblock(o_string *o, const char *str, int len)
2180 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2181 o_addblock(o, str, len);
2184 o_addqblock(o, str, len);
2187 static void o_addQstr(o_string *o, const char *str)
2189 o_addQblock(o, str, strlen(str));
2192 /* A special kind of o_string for $VAR and `cmd` expansion.
2193 * It contains char* list[] at the beginning, which is grown in 16 element
2194 * increments. Actual string data starts at the next multiple of 16 * (char*).
2195 * list[i] contains an INDEX (int!) into this string data.
2196 * It means that if list[] needs to grow, data needs to be moved higher up
2197 * but list[i]'s need not be modified.
2198 * NB: remembering how many list[i]'s you have there is crucial.
2199 * o_finalize_list() operation post-processes this structure - calculates
2200 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2202 #if DEBUG_EXPAND || DEBUG_GLOB
2203 static void debug_print_list(const char *prefix, o_string *o, int n)
2205 char **list = (char**)o->data;
2206 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2210 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2211 prefix, list, n, string_start, o->length, o->maxlen,
2212 !!(o->o_expflags & EXP_FLAG_GLOB),
2214 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2217 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2218 o->data + (int)(uintptr_t)list[i] + string_start,
2219 o->data + (int)(uintptr_t)list[i] + string_start);
2223 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2225 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2229 # define debug_print_list(prefix, o, n) ((void)0)
2232 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2233 * in list[n] so that it points past last stored byte so far.
2234 * It returns n+1. */
2235 static int o_save_ptr_helper(o_string *o, int n)
2237 char **list = (char**)o->data;
2241 if (!o->has_empty_slot) {
2242 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2243 string_len = o->length - string_start;
2244 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2245 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2246 /* list[n] points to string_start, make space for 16 more pointers */
2247 o->maxlen += 0x10 * sizeof(list[0]);
2248 o->data = xrealloc(o->data, o->maxlen + 1);
2249 list = (char**)o->data;
2250 memmove(list + n + 0x10, list + n, string_len);
2251 o->length += 0x10 * sizeof(list[0]);
2253 debug_printf_list("list[%d]=%d string_start=%d\n",
2254 n, string_len, string_start);
2257 /* We have empty slot at list[n], reuse without growth */
2258 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2259 string_len = o->length - string_start;
2260 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2261 n, string_len, string_start);
2262 o->has_empty_slot = 0;
2264 list[n] = (char*)(uintptr_t)string_len;
2268 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2269 static int o_get_last_ptr(o_string *o, int n)
2271 char **list = (char**)o->data;
2272 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2274 return ((int)(uintptr_t)list[n-1]) + string_start;
2277 #if ENABLE_HUSH_BRACE_EXPANSION
2278 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2279 * first, it processes even {a} (no commas), second,
2280 * I didn't manage to make it return strings when they don't match
2281 * existing files. Need to re-implement it.
2285 static int glob_needed(const char *s)
2294 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2300 /* Return pointer to next closing brace or to comma */
2301 static const char *next_brace_sub(const char *cp)
2305 while (*cp != '\0') {
2312 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2318 return *cp != '\0' ? cp : NULL;
2320 /* Recursive brace globber. Note: may garble pattern[]. */
2321 static int glob_brace(char *pattern, o_string *o, int n)
2323 char *new_pattern_buf;
2330 debug_printf_glob("glob_brace('%s')\n", pattern);
2336 if (*begin == '{') {
2337 /* Find the first sub-pattern and at the same time
2338 * find the rest after the closing brace */
2339 next = next_brace_sub(begin);
2341 /* An illegal expression */
2345 /* "{abc}" with no commas - illegal
2346 * brace expr, disregard and skip it */
2352 if (*begin == '\\' && begin[1] != '\0')
2356 debug_printf_glob("begin:%s\n", begin);
2357 debug_printf_glob("next:%s\n", next);
2359 /* Now find the end of the whole brace expression */
2361 while (*rest != '}') {
2362 rest = next_brace_sub(rest);
2364 /* An illegal expression */
2367 debug_printf_glob("rest:%s\n", rest);
2369 rest_len = strlen(++rest) + 1;
2371 /* We are sure the brace expression is well-formed */
2373 /* Allocate working buffer large enough for our work */
2374 new_pattern_buf = xmalloc(strlen(pattern));
2376 /* We have a brace expression. BEGIN points to the opening {,
2377 * NEXT points past the terminator of the first element, and REST
2378 * points past the final }. We will accumulate result names from
2379 * recursive runs for each brace alternative in the buffer using
2384 /* Construct the new glob expression */
2387 mempcpy(new_pattern_buf,
2388 /* We know the prefix for all sub-patterns */
2389 pattern, begin - pattern),
2393 /* Note: glob_brace() may garble new_pattern_buf[].
2394 * That's why we re-copy prefix every time (1st memcpy above).
2396 n = glob_brace(new_pattern_buf, o, n);
2398 /* We saw the last entry */
2402 next = next_brace_sub(next);
2404 free(new_pattern_buf);
2412 memset(&globdata, 0, sizeof(globdata));
2413 gr = glob(pattern, 0, NULL, &globdata);
2414 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2416 if (gr == GLOB_NOMATCH) {
2417 globfree(&globdata);
2418 /* NB: garbles parameter */
2419 unbackslash(pattern);
2420 o_addstr_with_NUL(o, pattern);
2421 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2422 return o_save_ptr_helper(o, n);
2424 if (gr == GLOB_NOSPACE)
2425 bb_error_msg_and_die(bb_msg_memory_exhausted);
2426 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2427 * but we didn't specify it. Paranoia again. */
2428 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2430 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2431 char **argv = globdata.gl_pathv;
2433 o_addstr_with_NUL(o, *argv);
2434 n = o_save_ptr_helper(o, n);
2440 globfree(&globdata);
2444 /* Performs globbing on last list[],
2445 * saving each result as a new list[].
2447 static int perform_glob(o_string *o, int n)
2449 char *pattern, *copy;
2451 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2453 return o_save_ptr_helper(o, n);
2454 pattern = o->data + o_get_last_ptr(o, n);
2455 debug_printf_glob("glob pattern '%s'\n", pattern);
2456 if (!glob_needed(pattern)) {
2457 /* unbackslash last string in o in place, fix length */
2458 o->length = unbackslash(pattern) - o->data;
2459 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2460 return o_save_ptr_helper(o, n);
2463 copy = xstrdup(pattern);
2464 /* "forget" pattern in o */
2465 o->length = pattern - o->data;
2466 n = glob_brace(copy, o, n);
2469 debug_print_list("perform_glob returning", o, n);
2473 #else /* !HUSH_BRACE_EXPANSION */
2476 static int glob_needed(const char *s)
2485 if (*s == '*' || *s == '[' || *s == '?')
2491 /* Performs globbing on last list[],
2492 * saving each result as a new list[].
2494 static int perform_glob(o_string *o, int n)
2500 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2502 return o_save_ptr_helper(o, n);
2503 pattern = o->data + o_get_last_ptr(o, n);
2504 debug_printf_glob("glob pattern '%s'\n", pattern);
2505 if (!glob_needed(pattern)) {
2507 /* unbackslash last string in o in place, fix length */
2508 o->length = unbackslash(pattern) - o->data;
2509 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2510 return o_save_ptr_helper(o, n);
2513 memset(&globdata, 0, sizeof(globdata));
2514 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2515 * If we glob "*.\*" and don't find anything, we need
2516 * to fall back to using literal "*.*", but GLOB_NOCHECK
2517 * will return "*.\*"!
2519 gr = glob(pattern, 0, NULL, &globdata);
2520 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2522 if (gr == GLOB_NOMATCH) {
2523 globfree(&globdata);
2526 if (gr == GLOB_NOSPACE)
2527 bb_error_msg_and_die(bb_msg_memory_exhausted);
2528 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2529 * but we didn't specify it. Paranoia again. */
2530 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2532 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2533 char **argv = globdata.gl_pathv;
2534 /* "forget" pattern in o */
2535 o->length = pattern - o->data;
2537 o_addstr_with_NUL(o, *argv);
2538 n = o_save_ptr_helper(o, n);
2544 globfree(&globdata);
2546 debug_print_list("perform_glob returning", o, n);
2550 #endif /* !HUSH_BRACE_EXPANSION */
2552 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2553 * Otherwise, just finish current list[] and start new */
2554 static int o_save_ptr(o_string *o, int n)
2556 if (o->o_expflags & EXP_FLAG_GLOB) {
2557 /* If o->has_empty_slot, list[n] was already globbed
2558 * (if it was requested back then when it was filled)
2559 * so don't do that again! */
2560 if (!o->has_empty_slot)
2561 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2563 return o_save_ptr_helper(o, n);
2566 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2567 static char **o_finalize_list(o_string *o, int n)
2572 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2574 debug_print_list("finalized", o, n);
2575 debug_printf_expand("finalized n:%d\n", n);
2576 list = (char**)o->data;
2577 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2581 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2586 static void free_pipe_list(struct pipe *pi);
2588 /* Returns pi->next - next pipe in the list */
2589 static struct pipe *free_pipe(struct pipe *pi)
2594 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2595 for (i = 0; i < pi->num_cmds; i++) {
2596 struct command *command;
2597 struct redir_struct *r, *rnext;
2599 command = &pi->cmds[i];
2600 debug_printf_clean(" command %d:\n", i);
2601 if (command->argv) {
2605 for (a = 0, p = command->argv; *p; a++, p++) {
2606 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2609 free_strings(command->argv);
2610 //command->argv = NULL;
2612 /* not "else if": on syntax error, we may have both! */
2613 if (command->group) {
2614 debug_printf_clean(" begin group (cmd_type:%d)\n",
2616 free_pipe_list(command->group);
2617 debug_printf_clean(" end group\n");
2618 //command->group = NULL;
2620 /* else is crucial here.
2621 * If group != NULL, child_func is meaningless */
2622 #if ENABLE_HUSH_FUNCTIONS
2623 else if (command->child_func) {
2624 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2625 command->child_func->parent_cmd = NULL;
2629 free(command->group_as_string);
2630 //command->group_as_string = NULL;
2632 for (r = command->redirects; r; r = rnext) {
2633 debug_printf_clean(" redirect %d%s",
2634 r->rd_fd, redir_table[r->rd_type].descrip);
2635 /* guard against the case >$FOO, where foo is unset or blank */
2636 if (r->rd_filename) {
2637 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2638 free(r->rd_filename);
2639 //r->rd_filename = NULL;
2641 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2645 //command->redirects = NULL;
2647 free(pi->cmds); /* children are an array, they get freed all at once */
2651 //pi->cmdtext = NULL;
2659 static void free_pipe_list(struct pipe *pi)
2663 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2665 debug_printf_clean("pipe followup code %d\n", pi->followup);
2671 /*** Parsing routines ***/
2673 #ifndef debug_print_tree
2674 static void debug_print_tree(struct pipe *pi, int lvl)
2676 static const char *const PIPE[] = {
2682 static const char *RES[] = {
2683 [RES_NONE ] = "NONE" ,
2686 [RES_THEN ] = "THEN" ,
2687 [RES_ELIF ] = "ELIF" ,
2688 [RES_ELSE ] = "ELSE" ,
2691 # if ENABLE_HUSH_LOOPS
2692 [RES_FOR ] = "FOR" ,
2693 [RES_WHILE] = "WHILE",
2694 [RES_UNTIL] = "UNTIL",
2696 [RES_DONE ] = "DONE" ,
2698 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2701 # if ENABLE_HUSH_CASE
2702 [RES_CASE ] = "CASE" ,
2703 [RES_CASE_IN ] = "CASE_IN" ,
2704 [RES_MATCH] = "MATCH",
2705 [RES_CASE_BODY] = "CASE_BODY",
2706 [RES_ESAC ] = "ESAC" ,
2708 [RES_XXXX ] = "XXXX" ,
2709 [RES_SNTX ] = "SNTX" ,
2711 static const char *const CMDTYPE[] = {
2715 # if ENABLE_HUSH_FUNCTIONS
2724 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2725 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2727 while (prn < pi->num_cmds) {
2728 struct command *command = &pi->cmds[prn];
2729 char **argv = command->argv;
2731 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2733 command->assignment_cnt);
2734 if (command->group) {
2735 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2736 CMDTYPE[command->cmd_type],
2739 , " group_as_string:", command->group_as_string
2744 debug_print_tree(command->group, lvl+1);
2748 if (argv) while (*argv) {
2749 fdprintf(2, " '%s'", *argv);
2759 #endif /* debug_print_tree */
2761 static struct pipe *new_pipe(void)
2764 pi = xzalloc(sizeof(struct pipe));
2765 /*pi->followup = 0; - deliberately invalid value */
2766 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2770 /* Command (member of a pipe) is complete, or we start a new pipe
2771 * if ctx->command is NULL.
2772 * No errors possible here.
2774 static int done_command(struct parse_context *ctx)
2776 /* The command is really already in the pipe structure, so
2777 * advance the pipe counter and make a new, null command. */
2778 struct pipe *pi = ctx->pipe;
2779 struct command *command = ctx->command;
2782 if (IS_NULL_CMD(command)) {
2783 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2787 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2788 //debug_print_tree(ctx->list_head, 20);
2790 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2793 /* Only real trickiness here is that the uncommitted
2794 * command structure is not counted in pi->num_cmds. */
2795 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2796 ctx->command = command = &pi->cmds[pi->num_cmds];
2798 memset(command, 0, sizeof(*command));
2799 return pi->num_cmds; /* used only for 0/nonzero check */
2802 static void done_pipe(struct parse_context *ctx, pipe_style type)
2806 debug_printf_parse("done_pipe entered, followup %d\n", type);
2807 /* Close previous command */
2808 not_null = done_command(ctx);
2809 ctx->pipe->followup = type;
2811 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2812 ctx->ctx_inverted = 0;
2813 ctx->pipe->res_word = ctx->ctx_res_w;
2816 /* Without this check, even just <enter> on command line generates
2817 * tree of three NOPs (!). Which is harmless but annoying.
2818 * IOW: it is safe to do it unconditionally. */
2821 || ctx->ctx_res_w == RES_FI
2823 #if ENABLE_HUSH_LOOPS
2824 || ctx->ctx_res_w == RES_DONE
2825 || ctx->ctx_res_w == RES_FOR
2826 || ctx->ctx_res_w == RES_IN
2828 #if ENABLE_HUSH_CASE
2829 || ctx->ctx_res_w == RES_ESAC
2833 debug_printf_parse("done_pipe: adding new pipe: "
2834 "not_null:%d ctx->ctx_res_w:%d\n",
2835 not_null, ctx->ctx_res_w);
2837 ctx->pipe->next = new_p;
2839 /* RES_THEN, RES_DO etc are "sticky" -
2840 * they remain set for pipes inside if/while.
2841 * This is used to control execution.
2842 * RES_FOR and RES_IN are NOT sticky (needed to support
2843 * cases where variable or value happens to match a keyword):
2845 #if ENABLE_HUSH_LOOPS
2846 if (ctx->ctx_res_w == RES_FOR
2847 || ctx->ctx_res_w == RES_IN)
2848 ctx->ctx_res_w = RES_NONE;
2850 #if ENABLE_HUSH_CASE
2851 if (ctx->ctx_res_w == RES_MATCH)
2852 ctx->ctx_res_w = RES_CASE_BODY;
2853 if (ctx->ctx_res_w == RES_CASE)
2854 ctx->ctx_res_w = RES_CASE_IN;
2856 ctx->command = NULL; /* trick done_command below */
2857 /* Create the memory for command, roughly:
2858 * ctx->pipe->cmds = new struct command;
2859 * ctx->command = &ctx->pipe->cmds[0];
2862 //debug_print_tree(ctx->list_head, 10);
2864 debug_printf_parse("done_pipe return\n");
2867 static void initialize_context(struct parse_context *ctx)
2869 memset(ctx, 0, sizeof(*ctx));
2870 ctx->pipe = ctx->list_head = new_pipe();
2871 /* Create the memory for command, roughly:
2872 * ctx->pipe->cmds = new struct command;
2873 * ctx->command = &ctx->pipe->cmds[0];
2878 /* If a reserved word is found and processed, parse context is modified
2879 * and 1 is returned.
2882 struct reserved_combo {
2885 unsigned char assignment_flag;
2889 FLAG_END = (1 << RES_NONE ),
2891 FLAG_IF = (1 << RES_IF ),
2892 FLAG_THEN = (1 << RES_THEN ),
2893 FLAG_ELIF = (1 << RES_ELIF ),
2894 FLAG_ELSE = (1 << RES_ELSE ),
2895 FLAG_FI = (1 << RES_FI ),
2897 # if ENABLE_HUSH_LOOPS
2898 FLAG_FOR = (1 << RES_FOR ),
2899 FLAG_WHILE = (1 << RES_WHILE),
2900 FLAG_UNTIL = (1 << RES_UNTIL),
2901 FLAG_DO = (1 << RES_DO ),
2902 FLAG_DONE = (1 << RES_DONE ),
2903 FLAG_IN = (1 << RES_IN ),
2905 # if ENABLE_HUSH_CASE
2906 FLAG_MATCH = (1 << RES_MATCH),
2907 FLAG_ESAC = (1 << RES_ESAC ),
2909 FLAG_START = (1 << RES_XXXX ),
2912 static const struct reserved_combo* match_reserved_word(o_string *word)
2914 /* Mostly a list of accepted follow-up reserved words.
2915 * FLAG_END means we are done with the sequence, and are ready
2916 * to turn the compound list into a command.
2917 * FLAG_START means the word must start a new compound list.
2919 static const struct reserved_combo reserved_list[] = {
2921 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2922 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2923 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2924 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2925 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2926 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2928 # if ENABLE_HUSH_LOOPS
2929 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2930 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2931 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2932 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2933 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2934 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2936 # if ENABLE_HUSH_CASE
2937 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2938 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2941 const struct reserved_combo *r;
2943 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2944 if (strcmp(word->data, r->literal) == 0)
2949 /* Return 0: not a keyword, 1: keyword
2951 static int reserved_word(o_string *word, struct parse_context *ctx)
2953 # if ENABLE_HUSH_CASE
2954 static const struct reserved_combo reserved_match = {
2955 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2958 const struct reserved_combo *r;
2960 if (word->has_quoted_part)
2962 r = match_reserved_word(word);
2966 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2967 # if ENABLE_HUSH_CASE
2968 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2969 /* "case word IN ..." - IN part starts first MATCH part */
2970 r = &reserved_match;
2973 if (r->flag == 0) { /* '!' */
2974 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2975 syntax_error("! ! command");
2976 ctx->ctx_res_w = RES_SNTX;
2978 ctx->ctx_inverted = 1;
2981 if (r->flag & FLAG_START) {
2982 struct parse_context *old;
2984 old = xmalloc(sizeof(*old));
2985 debug_printf_parse("push stack %p\n", old);
2986 *old = *ctx; /* physical copy */
2987 initialize_context(ctx);
2989 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2990 syntax_error_at(word->data);
2991 ctx->ctx_res_w = RES_SNTX;
2994 /* "{...} fi" is ok. "{...} if" is not
2996 * if { echo foo; } then { echo bar; } fi */
2997 if (ctx->command->group)
2998 done_pipe(ctx, PIPE_SEQ);
3001 ctx->ctx_res_w = r->res;
3002 ctx->old_flag = r->flag;
3003 word->o_assignment = r->assignment_flag;
3005 if (ctx->old_flag & FLAG_END) {
3006 struct parse_context *old;
3008 done_pipe(ctx, PIPE_SEQ);
3009 debug_printf_parse("pop stack %p\n", ctx->stack);
3011 old->command->group = ctx->list_head;
3012 old->command->cmd_type = CMD_NORMAL;
3014 o_addstr(&old->as_string, ctx->as_string.data);
3015 o_free_unsafe(&ctx->as_string);
3016 old->command->group_as_string = xstrdup(old->as_string.data);
3017 debug_printf_parse("pop, remembering as:'%s'\n",
3018 old->command->group_as_string);
3020 *ctx = *old; /* physical copy */
3025 #endif /* HAS_KEYWORDS */
3027 /* Word is complete, look at it and update parsing context.
3028 * Normal return is 0. Syntax errors return 1.
3029 * Note: on return, word is reset, but not o_free'd!
3031 static int done_word(o_string *word, struct parse_context *ctx)
3033 struct command *command = ctx->command;
3035 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3036 if (word->length == 0 && !word->has_quoted_part) {
3037 debug_printf_parse("done_word return 0: true null, ignored\n");
3041 if (ctx->pending_redirect) {
3042 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3043 * only if run as "bash", not "sh" */
3044 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3046 * ...the word that follows the redirection operator
3047 * shall be subjected to tilde expansion, parameter expansion,
3048 * command substitution, arithmetic expansion, and quote
3049 * removal. Pathname expansion shall not be performed
3050 * on the word by a non-interactive shell; an interactive
3051 * shell may perform it, but shall do so only when
3052 * the expansion would result in one word."
3054 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3055 /* Cater for >\file case:
3056 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3057 * Same with heredocs:
3058 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3060 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3061 unbackslash(ctx->pending_redirect->rd_filename);
3062 /* Is it <<"HEREDOC"? */
3063 if (word->has_quoted_part) {
3064 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3067 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3068 ctx->pending_redirect = NULL;
3070 /* If this word wasn't an assignment, next ones definitely
3071 * can't be assignments. Even if they look like ones. */
3072 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3073 && word->o_assignment != WORD_IS_KEYWORD
3075 word->o_assignment = NOT_ASSIGNMENT;
3077 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3078 command->assignment_cnt++;
3079 word->o_assignment = MAYBE_ASSIGNMENT;
3083 # if ENABLE_HUSH_CASE
3084 if (ctx->ctx_dsemicolon
3085 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3087 /* already done when ctx_dsemicolon was set to 1: */
3088 /* ctx->ctx_res_w = RES_MATCH; */
3089 ctx->ctx_dsemicolon = 0;
3092 if (!command->argv /* if it's the first word... */
3093 # if ENABLE_HUSH_LOOPS
3094 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3095 && ctx->ctx_res_w != RES_IN
3097 # if ENABLE_HUSH_CASE
3098 && ctx->ctx_res_w != RES_CASE
3101 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3102 if (reserved_word(word, ctx)) {
3103 o_reset_to_empty_unquoted(word);
3104 debug_printf_parse("done_word return %d\n",
3105 (ctx->ctx_res_w == RES_SNTX));
3106 return (ctx->ctx_res_w == RES_SNTX);
3108 # if ENABLE_HUSH_BASH_COMPAT
3109 if (strcmp(word->data, "[[") == 0) {
3110 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3116 if (command->group) {
3117 /* "{ echo foo; } echo bar" - bad */
3118 syntax_error_at(word->data);
3119 debug_printf_parse("done_word return 1: syntax error, "
3120 "groups and arglists don't mix\n");
3123 if (word->has_quoted_part
3124 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3125 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3126 /* (otherwise it's known to be not empty and is already safe) */
3128 /* exclude "$@" - it can expand to no word despite "" */
3129 char *p = word->data;
3130 while (p[0] == SPECIAL_VAR_SYMBOL
3131 && (p[1] & 0x7f) == '@'
3132 && p[2] == SPECIAL_VAR_SYMBOL
3136 if (p == word->data || p[0] != '\0') {
3137 /* saw no "$@", or not only "$@" but some
3138 * real text is there too */
3139 /* insert "empty variable" reference, this makes
3140 * e.g. "", $empty"" etc to not disappear */
3141 o_addchr(word, SPECIAL_VAR_SYMBOL);
3142 o_addchr(word, SPECIAL_VAR_SYMBOL);
3145 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3146 debug_print_strings("word appended to argv", command->argv);
3149 #if ENABLE_HUSH_LOOPS
3150 if (ctx->ctx_res_w == RES_FOR) {
3151 if (word->has_quoted_part
3152 || !is_well_formed_var_name(command->argv[0], '\0')
3154 /* bash says just "not a valid identifier" */
3155 syntax_error("not a valid identifier in for");
3158 /* Force FOR to have just one word (variable name) */
3159 /* NB: basically, this makes hush see "for v in ..."
3160 * syntax as if it is "for v; in ...". FOR and IN become
3161 * two pipe structs in parse tree. */
3162 done_pipe(ctx, PIPE_SEQ);
3165 #if ENABLE_HUSH_CASE
3166 /* Force CASE to have just one word */
3167 if (ctx->ctx_res_w == RES_CASE) {
3168 done_pipe(ctx, PIPE_SEQ);
3172 o_reset_to_empty_unquoted(word);
3174 debug_printf_parse("done_word return 0\n");
3179 /* Peek ahead in the input to find out if we have a "&n" construct,
3180 * as in "2>&1", that represents duplicating a file descriptor.
3182 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3183 * REDIRFD_SYNTAX_ERR if syntax error,
3184 * REDIRFD_TO_FILE if no & was seen,
3185 * or the number found.
3188 #define parse_redir_right_fd(as_string, input) \
3189 parse_redir_right_fd(input)
3191 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3197 return REDIRFD_TO_FILE;
3199 ch = i_getch(input); /* get the & */
3200 nommu_addchr(as_string, ch);
3203 ch = i_getch(input);
3204 nommu_addchr(as_string, ch);
3205 return REDIRFD_CLOSE;
3209 while (ch != EOF && isdigit(ch)) {
3210 d = d*10 + (ch-'0');
3212 ch = i_getch(input);
3213 nommu_addchr(as_string, ch);
3218 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3220 bb_error_msg("ambiguous redirect");
3221 return REDIRFD_SYNTAX_ERR;
3224 /* Return code is 0 normal, 1 if a syntax error is detected
3226 static int parse_redirect(struct parse_context *ctx,
3229 struct in_str *input)
3231 struct command *command = ctx->command;
3232 struct redir_struct *redir;
3233 struct redir_struct **redirp;
3236 dup_num = REDIRFD_TO_FILE;
3237 if (style != REDIRECT_HEREDOC) {
3238 /* Check for a '>&1' type redirect */
3239 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3240 if (dup_num == REDIRFD_SYNTAX_ERR)
3243 int ch = i_peek(input);
3244 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3245 if (dup_num) { /* <<-... */
3246 ch = i_getch(input);
3247 nommu_addchr(&ctx->as_string, ch);
3252 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3253 int ch = i_peek(input);
3255 /* >|FILE redirect ("clobbering" >).
3256 * Since we do not support "set -o noclobber" yet,
3257 * >| and > are the same for now. Just eat |.
3259 ch = i_getch(input);
3260 nommu_addchr(&ctx->as_string, ch);
3264 /* Create a new redir_struct and append it to the linked list */
3265 redirp = &command->redirects;
3266 while ((redir = *redirp) != NULL) {
3267 redirp = &(redir->next);
3269 *redirp = redir = xzalloc(sizeof(*redir));
3270 /* redir->next = NULL; */
3271 /* redir->rd_filename = NULL; */
3272 redir->rd_type = style;
3273 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3275 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3276 redir_table[style].descrip);
3278 redir->rd_dup = dup_num;
3279 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3280 /* Erik had a check here that the file descriptor in question
3281 * is legit; I postpone that to "run time"
3282 * A "-" representation of "close me" shows up as a -3 here */
3283 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3284 redir->rd_fd, redir->rd_dup);
3286 /* Set ctx->pending_redirect, so we know what to do at the
3287 * end of the next parsed word. */
3288 ctx->pending_redirect = redir;
3293 /* If a redirect is immediately preceded by a number, that number is
3294 * supposed to tell which file descriptor to redirect. This routine
3295 * looks for such preceding numbers. In an ideal world this routine
3296 * needs to handle all the following classes of redirects...
3297 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3298 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3299 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3300 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3302 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3304 * ... If n is quoted, the number shall not be recognized as part of
3305 * the redirection expression. For example:
3307 * writes the character 2 into file a"
3308 * We are getting it right by setting ->has_quoted_part on any \<char>
3310 * A -1 return means no valid number was found,
3311 * the caller should use the appropriate default for this redirection.
3313 static int redirect_opt_num(o_string *o)
3317 if (o->data == NULL)
3319 num = bb_strtou(o->data, NULL, 10);
3320 if (errno || num < 0)
3322 o_reset_to_empty_unquoted(o);
3327 #define fetch_till_str(as_string, input, word, skip_tabs) \
3328 fetch_till_str(input, word, skip_tabs)
3330 static char *fetch_till_str(o_string *as_string,
3331 struct in_str *input,
3335 o_string heredoc = NULL_O_STRING;
3337 int prev = 0; /* not \ */
3343 ch = i_getch(input);
3345 nommu_addchr(as_string, ch);
3346 if ((ch == '\n' || ch == EOF)
3347 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3349 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3350 heredoc.data[past_EOL] = '\0';
3351 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3352 return heredoc.data;
3354 while (ch == '\n') {
3355 o_addchr(&heredoc, ch);
3358 past_EOL = heredoc.length;
3360 ch = i_getch(input);
3362 nommu_addchr(as_string, ch);
3363 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3367 o_free_unsafe(&heredoc);
3370 o_addchr(&heredoc, ch);
3371 nommu_addchr(as_string, ch);
3372 if (prev == '\\' && ch == '\\')
3373 /* Correctly handle foo\\<eol> (not a line cont.) */
3374 prev = 0; /* not \ */
3380 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3381 * and load them all. There should be exactly heredoc_cnt of them.
3383 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3385 struct pipe *pi = ctx->list_head;
3387 while (pi && heredoc_cnt) {
3389 struct command *cmd = pi->cmds;
3391 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3393 cmd->argv ? cmd->argv[0] : "NONE");
3394 for (i = 0; i < pi->num_cmds; i++) {
3395 struct redir_struct *redir = cmd->redirects;
3397 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3398 i, cmd->argv ? cmd->argv[0] : "NONE");
3400 if (redir->rd_type == REDIRECT_HEREDOC) {
3403 redir->rd_type = REDIRECT_HEREDOC2;
3404 /* redir->rd_dup is (ab)used to indicate <<- */
3405 p = fetch_till_str(&ctx->as_string, input,
3406 redir->rd_filename, redir->rd_dup);
3408 syntax_error("unexpected EOF in here document");
3411 free(redir->rd_filename);
3412 redir->rd_filename = p;
3415 redir = redir->next;
3422 /* Should be 0. If it isn't, it's a parse error */
3424 bb_error_msg_and_die("heredoc BUG 2");
3430 static int run_list(struct pipe *pi);
3432 #define parse_stream(pstring, input, end_trigger) \
3433 parse_stream(input, end_trigger)
3435 static struct pipe *parse_stream(char **pstring,
3436 struct in_str *input,
3440 #if !ENABLE_HUSH_FUNCTIONS
3441 #define parse_group(dest, ctx, input, ch) \
3442 parse_group(ctx, input, ch)
3444 static int parse_group(o_string *dest, struct parse_context *ctx,
3445 struct in_str *input, int ch)
3447 /* dest contains characters seen prior to ( or {.
3448 * Typically it's empty, but for function defs,
3449 * it contains function name (without '()'). */
3450 struct pipe *pipe_list;
3452 struct command *command = ctx->command;
3454 debug_printf_parse("parse_group entered\n");
3455 #if ENABLE_HUSH_FUNCTIONS
3456 if (ch == '(' && !dest->has_quoted_part) {
3458 if (done_word(dest, ctx))
3461 goto skip; /* (... */
3462 if (command->argv[1]) { /* word word ... (... */
3463 syntax_error_unexpected_ch('(');
3466 /* it is "word(..." or "word (..." */
3468 ch = i_getch(input);
3469 while (ch == ' ' || ch == '\t');
3471 syntax_error_unexpected_ch(ch);
3474 nommu_addchr(&ctx->as_string, ch);
3476 ch = i_getch(input);
3477 while (ch == ' ' || ch == '\t' || ch == '\n');
3479 syntax_error_unexpected_ch(ch);
3482 nommu_addchr(&ctx->as_string, ch);
3483 command->cmd_type = CMD_FUNCDEF;
3488 #if 0 /* Prevented by caller */
3489 if (command->argv /* word [word]{... */
3490 || dest->length /* word{... */
3491 || dest->has_quoted_part /* ""{... */
3494 debug_printf_parse("parse_group return 1: "
3495 "syntax error, groups and arglists don't mix\n");
3500 #if ENABLE_HUSH_FUNCTIONS
3506 command->cmd_type = CMD_SUBSHELL;
3508 /* bash does not allow "{echo...", requires whitespace */
3509 ch = i_getch(input);
3510 if (ch != ' ' && ch != '\t' && ch != '\n') {
3511 syntax_error_unexpected_ch(ch);
3514 nommu_addchr(&ctx->as_string, ch);
3519 # define as_string NULL
3521 char *as_string = NULL;
3523 pipe_list = parse_stream(&as_string, input, endch);
3526 o_addstr(&ctx->as_string, as_string);
3528 /* empty ()/{} or parse error? */
3529 if (!pipe_list || pipe_list == ERR_PTR) {
3530 /* parse_stream already emitted error msg */
3533 debug_printf_parse("parse_group return 1: "
3534 "parse_stream returned %p\n", pipe_list);
3537 command->group = pipe_list;
3539 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3540 command->group_as_string = as_string;
3541 debug_printf_parse("end of group, remembering as:'%s'\n",
3542 command->group_as_string);
3546 debug_printf_parse("parse_group return 0\n");
3548 /* command remains "open", available for possible redirects */
3551 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3552 /* Subroutines for copying $(...) and `...` things */
3553 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3555 static int add_till_single_quote(o_string *dest, struct in_str *input)
3558 int ch = i_getch(input);
3560 syntax_error_unterm_ch('\'');
3568 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3569 static int add_till_double_quote(o_string *dest, struct in_str *input)
3572 int ch = i_getch(input);
3574 syntax_error_unterm_ch('"');
3579 if (ch == '\\') { /* \x. Copy both chars. */
3581 ch = i_getch(input);
3585 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3590 //if (ch == '$') ...
3593 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3595 * "Within the backquoted style of command substitution, backslash
3596 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3597 * The search for the matching backquote shall be satisfied by the first
3598 * backquote found without a preceding backslash; during this search,
3599 * if a non-escaped backquote is encountered within a shell comment,
3600 * a here-document, an embedded command substitution of the $(command)
3601 * form, or a quoted string, undefined results occur. A single-quoted
3602 * or double-quoted string that begins, but does not end, within the
3603 * "`...`" sequence produces undefined results."
3605 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3607 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3610 int ch = i_getch(input);
3614 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3615 ch = i_getch(input);
3619 && (!in_dquote || ch != '"')
3621 o_addchr(dest, '\\');
3625 syntax_error_unterm_ch('`');
3631 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3632 * quoting and nested ()s.
3633 * "With the $(command) style of command substitution, all characters
3634 * following the open parenthesis to the matching closing parenthesis
3635 * constitute the command. Any valid shell script can be used for command,
3636 * except a script consisting solely of redirections which produces
3637 * unspecified results."
3639 * echo $(echo '(TEST)' BEST) (TEST) BEST
3640 * echo $(echo 'TEST)' BEST) TEST) BEST
3641 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3643 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3644 * can contain arbitrary constructs, just like $(cmd).
3645 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3646 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3648 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3649 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3652 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3653 # if ENABLE_HUSH_BASH_COMPAT
3654 char end_char2 = end_ch >> 8;
3656 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3659 ch = i_getch(input);
3661 syntax_error_unterm_ch(end_ch);
3664 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3667 /* we look for closing )) of $((EXPR)) */
3668 if (i_peek(input) == end_ch) {
3669 i_getch(input); /* eat second ')' */
3674 if (ch == '(' || ch == '{') {
3675 ch = (ch == '(' ? ')' : '}');
3676 if (!add_till_closing_bracket(dest, input, ch))
3682 if (!add_till_single_quote(dest, input))
3688 if (!add_till_double_quote(dest, input))
3694 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3700 /* \x. Copy verbatim. Important for \(, \) */
3701 ch = i_getch(input);
3703 syntax_error_unterm_ch(')');
3712 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3714 /* Return code: 0 for OK, 1 for syntax error */
3716 #define parse_dollar(as_string, dest, input, quote_mask) \
3717 parse_dollar(dest, input, quote_mask)
3718 #define as_string NULL
3720 static int parse_dollar(o_string *as_string,
3722 struct in_str *input, unsigned char quote_mask)
3724 int ch = i_peek(input); /* first character after the $ */
3726 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3728 ch = i_getch(input);
3729 nommu_addchr(as_string, ch);
3731 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3733 debug_printf_parse(": '%c'\n", ch);
3734 o_addchr(dest, ch | quote_mask);
3737 if (!isalnum(ch) && ch != '_')
3739 ch = i_getch(input);
3740 nommu_addchr(as_string, ch);
3742 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3743 } else if (isdigit(ch)) {
3745 ch = i_getch(input);
3746 nommu_addchr(as_string, ch);
3747 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3748 debug_printf_parse(": '%c'\n", ch);
3749 o_addchr(dest, ch | quote_mask);
3750 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3751 } else switch (ch) {
3753 case '!': /* last bg pid */
3754 case '?': /* last exit code */
3755 case '#': /* number of args */
3756 case '*': /* args */
3757 case '@': /* args */
3758 goto make_one_char_var;
3760 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3762 ch = i_getch(input); /* eat '{' */
3763 nommu_addchr(as_string, ch);
3765 ch = i_getch(input); /* first char after '{' */
3766 /* It should be ${?}, or ${#var},
3767 * or even ${?+subst} - operator acting on a special variable,
3768 * or the beginning of variable name.
3771 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3774 syntax_error_unterm_str("${name}");
3775 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3778 nommu_addchr(as_string, ch);
3781 /* It's possible to just call add_till_closing_bracket() at this point.
3782 * However, this regresses some of our testsuite cases
3783 * which check invalid constructs like ${%}.
3784 * Oh well... let's check that the var name part is fine... */
3790 debug_printf_parse(": '%c'\n", ch);
3792 ch = i_getch(input);
3793 nommu_addchr(as_string, ch);
3797 if (!isalnum(ch) && ch != '_') {
3799 unsigned char last_ch;
3800 /* handle parameter expansions
3801 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3803 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3804 goto bad_dollar_syntax;
3806 /* Eat everything until closing '}' (or ':') */
3808 if (ENABLE_HUSH_BASH_COMPAT
3810 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3812 /* It's ${var:N[:M]} thing */
3813 end_ch = '}' * 0x100 + ':';
3815 if (ENABLE_HUSH_BASH_COMPAT
3818 /* It's ${var/[/]pattern[/repl]} thing */
3819 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3821 nommu_addchr(as_string, '/');
3824 end_ch = '}' * 0x100 + '/';
3830 #if ENABLE_HUSH_DOLLAR_OPS
3831 last_ch = add_till_closing_bracket(dest, input, end_ch);
3832 if (last_ch == 0) /* error? */
3835 #error Simple code to only allow ${var} is not implemented
3838 o_addstr(as_string, dest->data + pos);
3839 o_addchr(as_string, last_ch);
3842 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3843 /* close the first block: */
3844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3845 /* while parsing N from ${var:N[:M]}
3846 * or pattern from ${var/[/]pattern[/repl]} */
3847 if ((end_ch & 0xff) == last_ch) {
3848 /* got ':' or '/'- parse the rest */
3853 if (end_ch == '}' * 0x100 + ':') {
3854 /* it's ${var:N} - emulate :999999999 */
3855 o_addstr(dest, "999999999");
3856 } /* else: it's ${var/[/]pattern} */
3861 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3864 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3868 ch = i_getch(input);
3869 nommu_addchr(as_string, ch);
3870 # if ENABLE_SH_MATH_SUPPORT
3871 if (i_peek(input) == '(') {
3872 ch = i_getch(input);
3873 nommu_addchr(as_string, ch);
3874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3875 o_addchr(dest, /*quote_mask |*/ '+');
3878 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3879 return 0; /* error */
3881 o_addstr(as_string, dest->data + pos);
3882 o_addchr(as_string, ')');
3883 o_addchr(as_string, ')');
3885 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3889 # if ENABLE_HUSH_TICK
3890 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3891 o_addchr(dest, quote_mask | '`');
3894 if (!add_till_closing_bracket(dest, input, ')'))
3895 return 0; /* error */
3897 o_addstr(as_string, dest->data + pos);
3898 o_addchr(as_string, ')');
3900 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3906 ch = i_getch(input);
3907 nommu_addchr(as_string, ch);
3909 if (isalnum(ch)) { /* it's $_name or $_123 */
3914 /* TODO: $_ and $-: */
3915 /* $_ Shell or shell script name; or last argument of last command
3916 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3917 * but in command's env, set to full pathname used to invoke it */
3918 /* $- Option flags set by set builtin or shell options (-i etc) */
3920 o_addQchr(dest, '$');
3922 debug_printf_parse("parse_dollar return 1 (ok)\n");
3928 # if ENABLE_HUSH_BASH_COMPAT
3929 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3930 encode_string(dest, input, dquote_end, process_bkslash)
3932 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3933 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3934 encode_string(dest, input, dquote_end)
3936 #define as_string NULL
3940 # if ENABLE_HUSH_BASH_COMPAT
3941 /* all parameters are needed, no macro tricks */
3943 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3944 encode_string(as_string, dest, input, dquote_end)
3947 static int encode_string(o_string *as_string,
3949 struct in_str *input,
3951 int process_bkslash)
3953 #if !ENABLE_HUSH_BASH_COMPAT
3954 const int process_bkslash = 1;
3960 ch = i_getch(input);
3962 nommu_addchr(as_string, ch);
3963 if (ch == dquote_end) { /* may be only '"' or EOF */
3964 debug_printf_parse("encode_string return 1 (ok)\n");
3967 /* note: can't move it above ch == dquote_end check! */
3969 syntax_error_unterm_ch('"');
3970 return 0; /* error */
3974 next = i_peek(input);
3976 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3977 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3978 if (process_bkslash && ch == '\\') {
3980 syntax_error("\\<eof>");
3984 * "The backslash retains its special meaning [in "..."]
3985 * only when followed by one of the following characters:
3986 * $, `, ", \, or <newline>. A double quote may be quoted
3987 * within double quotes by preceding it with a backslash."
3988 * NB: in (unquoted) heredoc, above does not apply to ",
3989 * therefore we check for it by "next == dquote_end" cond.
3991 if (next == dquote_end || strchr("$`\\\n", next)) {
3992 ch = i_getch(input); /* eat next */
3994 goto again; /* skip \<newline> */
3995 } /* else: ch remains == '\\', and we double it below: */
3996 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3997 nommu_addchr(as_string, ch);
4001 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4002 debug_printf_parse("encode_string return 0: "
4003 "parse_dollar returned 0 (error)\n");
4008 #if ENABLE_HUSH_TICK
4010 //unsigned pos = dest->length;
4011 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4012 o_addchr(dest, 0x80 | '`');
4013 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4014 return 0; /* error */
4015 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4016 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4020 o_addQchr(dest, ch);
4026 * Scan input until EOF or end_trigger char.
4027 * Return a list of pipes to execute, or NULL on EOF
4028 * or if end_trigger character is met.
4029 * On syntax error, exit if shell is not interactive,
4030 * reset parsing machinery and start parsing anew,
4031 * or return ERR_PTR.
4033 static struct pipe *parse_stream(char **pstring,
4034 struct in_str *input,
4037 struct parse_context ctx;
4038 o_string dest = NULL_O_STRING;
4041 /* Single-quote triggers a bypass of the main loop until its mate is
4042 * found. When recursing, quote state is passed in via dest->o_expflags.
4044 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4045 end_trigger ? end_trigger : 'X');
4048 /* If very first arg is "" or '', dest.data may end up NULL.
4049 * Preventing this: */
4050 o_addchr(&dest, '\0');
4053 /* We used to separate words on $IFS here. This was wrong.
4054 * $IFS is used only for word splitting when $var is expanded,
4055 * here we should use blank chars as separators, not $IFS
4058 if (MAYBE_ASSIGNMENT != 0)
4059 dest.o_assignment = MAYBE_ASSIGNMENT;
4060 initialize_context(&ctx);
4063 const char *is_blank;
4064 const char *is_special;
4068 redir_type redir_style;
4070 ch = i_getch(input);
4071 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4072 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4077 syntax_error_unterm_str("here document");
4080 /* end_trigger == '}' case errors out earlier,
4081 * checking only ')' */
4082 if (end_trigger == ')') {
4083 syntax_error_unterm_ch('(');
4087 if (done_word(&dest, &ctx)) {
4091 done_pipe(&ctx, PIPE_SEQ);
4093 /* If we got nothing... */
4094 /* (this makes bare "&" cmd a no-op.
4095 * bash says: "syntax error near unexpected token '&'") */
4096 if (pi->num_cmds == 0
4097 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4103 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4105 *pstring = ctx.as_string.data;
4107 o_free_unsafe(&ctx.as_string);
4110 debug_printf_parse("parse_stream return %p\n", pi);
4113 nommu_addchr(&ctx.as_string, ch);
4117 next = i_peek(input);
4119 is_special = "{}<>;&|()#'" /* special outside of "str" */
4120 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4121 /* Are { and } special here? */
4122 if (ctx.command->argv /* word [word]{... - non-special */
4123 || dest.length /* word{... - non-special */
4124 || dest.has_quoted_part /* ""{... - non-special */
4125 || (next != ';' /* }; - special */
4126 && next != ')' /* }) - special */
4127 && next != '&' /* }& and }&& ... - special */
4128 && next != '|' /* }|| ... - special */
4129 && !strchr(defifs, next) /* {word - non-special */
4132 /* They are not special, skip "{}" */
4135 is_special = strchr(is_special, ch);
4136 is_blank = strchr(defifs, ch);
4138 if (!is_special && !is_blank) { /* ordinary char */
4140 o_addQchr(&dest, ch);
4141 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4142 || dest.o_assignment == WORD_IS_KEYWORD)
4144 && is_well_formed_var_name(dest.data, '=')
4146 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4152 if (done_word(&dest, &ctx)) {
4156 /* Is this a case when newline is simply ignored?
4158 * "cmd | <newline> cmd ..."
4159 * "case ... in <newline> word) ..."
4161 if (IS_NULL_CMD(ctx.command)
4162 && dest.length == 0 && !dest.has_quoted_part
4164 /* This newline can be ignored. But...
4165 * Without check #1, interactive shell
4166 * ignores even bare <newline>,
4167 * and shows the continuation prompt:
4168 * ps1_prompt$ <enter>
4169 * ps2> _ <=== wrong, should be ps1
4170 * Without check #2, "cmd & <newline>"
4171 * is similarly mistreated.
4172 * (BTW, this makes "cmd & cmd"
4173 * and "cmd && cmd" non-orthogonal.
4174 * Really, ask yourself, why
4175 * "cmd && <newline>" doesn't start
4176 * cmd but waits for more input?
4179 struct pipe *pi = ctx.list_head;
4180 if (pi->num_cmds != 0 /* check #1 */
4181 && pi->followup != PIPE_BG /* check #2 */
4186 /* Treat newline as a command separator. */
4187 done_pipe(&ctx, PIPE_SEQ);
4188 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4190 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4195 dest.o_assignment = MAYBE_ASSIGNMENT;
4197 /* note: if (is_blank) continue;
4198 * will still trigger for us */
4202 /* "cmd}" or "cmd }..." without semicolon or &:
4203 * } is an ordinary char in this case, even inside { cmd; }
4204 * Pathological example: { ""}; } should exec "}" cmd
4207 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4208 || dest.length != 0 /* word} */
4209 || dest.has_quoted_part /* ""} */
4213 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4214 goto skip_end_trigger;
4215 /* else: } does terminate a group */
4218 if (end_trigger && end_trigger == ch
4219 && (ch != ';' || heredoc_cnt == 0)
4220 #if ENABLE_HUSH_CASE
4222 || ctx.ctx_res_w != RES_MATCH
4223 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4228 /* This is technically valid:
4229 * { cat <<HERE; }; echo Ok
4233 * but we don't support this.
4234 * We require heredoc to be in enclosing {}/(),
4237 syntax_error_unterm_str("here document");
4240 if (done_word(&dest, &ctx)) {
4243 done_pipe(&ctx, PIPE_SEQ);
4244 dest.o_assignment = MAYBE_ASSIGNMENT;
4245 /* Do we sit outside of any if's, loops or case's? */
4247 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4251 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4253 *pstring = ctx.as_string.data;
4255 o_free_unsafe(&ctx.as_string);
4258 debug_printf_parse("parse_stream return %p: "
4259 "end_trigger char found\n",
4261 return ctx.list_head;
4268 /* Catch <, > before deciding whether this word is
4269 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4272 redir_fd = redirect_opt_num(&dest);
4273 if (done_word(&dest, &ctx)) {
4276 redir_style = REDIRECT_OVERWRITE;
4278 redir_style = REDIRECT_APPEND;
4279 ch = i_getch(input);
4280 nommu_addchr(&ctx.as_string, ch);
4283 else if (next == '(') {
4284 syntax_error(">(process) not supported");
4288 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4290 continue; /* back to top of while (1) */
4292 redir_fd = redirect_opt_num(&dest);
4293 if (done_word(&dest, &ctx)) {
4296 redir_style = REDIRECT_INPUT;
4298 redir_style = REDIRECT_HEREDOC;
4300 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4301 ch = i_getch(input);
4302 nommu_addchr(&ctx.as_string, ch);
4303 } else if (next == '>') {
4304 redir_style = REDIRECT_IO;
4305 ch = i_getch(input);
4306 nommu_addchr(&ctx.as_string, ch);
4309 else if (next == '(') {
4310 syntax_error("<(process) not supported");
4314 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4316 continue; /* back to top of while (1) */
4318 if (dest.length == 0 && !dest.has_quoted_part) {
4319 /* skip "#comment" */
4322 if (ch == EOF || ch == '\n')
4325 /* note: we do not add it to &ctx.as_string */
4327 nommu_addchr(&ctx.as_string, '\n');
4328 continue; /* back to top of while (1) */
4333 /* It's "\<newline>" */
4335 /* Remove trailing '\' from ctx.as_string */
4336 ctx.as_string.data[--ctx.as_string.length] = '\0';
4338 ch = i_getch(input); /* eat it */
4339 continue; /* back to top of while (1) */
4344 if (dest.o_assignment == MAYBE_ASSIGNMENT
4345 /* check that we are not in word in "a=1 2>word b=1": */
4346 && !ctx.pending_redirect
4348 /* ch is a special char and thus this word
4349 * cannot be an assignment */
4350 dest.o_assignment = NOT_ASSIGNMENT;
4353 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4356 case '#': /* non-comment #: "echo a#b" etc */
4357 o_addQchr(&dest, ch);
4361 syntax_error("\\<eof>");
4364 ch = i_getch(input);
4365 /* note: ch != '\n' (that case does not reach this place) */
4366 o_addchr(&dest, '\\');
4367 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4368 o_addchr(&dest, ch);
4369 nommu_addchr(&ctx.as_string, ch);
4370 /* Example: echo Hello \2>file
4371 * we need to know that word 2 is quoted */
4372 dest.has_quoted_part = 1;
4375 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4376 debug_printf_parse("parse_stream parse error: "
4377 "parse_dollar returned 0 (error)\n");
4382 dest.has_quoted_part = 1;
4384 ch = i_getch(input);
4386 syntax_error_unterm_ch('\'');
4389 nommu_addchr(&ctx.as_string, ch);
4392 o_addqchr(&dest, ch);
4396 dest.has_quoted_part = 1;
4397 if (dest.o_assignment == NOT_ASSIGNMENT)
4398 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4399 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4401 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4403 #if ENABLE_HUSH_TICK
4407 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4408 o_addchr(&dest, '`');
4410 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4413 o_addstr(&ctx.as_string, dest.data + pos);
4414 o_addchr(&ctx.as_string, '`');
4416 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4417 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4422 #if ENABLE_HUSH_CASE
4425 if (done_word(&dest, &ctx)) {
4428 done_pipe(&ctx, PIPE_SEQ);
4429 #if ENABLE_HUSH_CASE
4430 /* Eat multiple semicolons, detect
4431 * whether it means something special */
4436 ch = i_getch(input);
4437 nommu_addchr(&ctx.as_string, ch);
4438 if (ctx.ctx_res_w == RES_CASE_BODY) {
4439 ctx.ctx_dsemicolon = 1;
4440 ctx.ctx_res_w = RES_MATCH;
4446 /* We just finished a cmd. New one may start
4447 * with an assignment */
4448 dest.o_assignment = MAYBE_ASSIGNMENT;
4451 if (done_word(&dest, &ctx)) {
4455 ch = i_getch(input);
4456 nommu_addchr(&ctx.as_string, ch);
4457 done_pipe(&ctx, PIPE_AND);
4459 done_pipe(&ctx, PIPE_BG);
4463 if (done_word(&dest, &ctx)) {
4466 #if ENABLE_HUSH_CASE
4467 if (ctx.ctx_res_w == RES_MATCH)
4468 break; /* we are in case's "word | word)" */
4470 if (next == '|') { /* || */
4471 ch = i_getch(input);
4472 nommu_addchr(&ctx.as_string, ch);
4473 done_pipe(&ctx, PIPE_OR);
4475 /* we could pick up a file descriptor choice here
4476 * with redirect_opt_num(), but bash doesn't do it.
4477 * "echo foo 2| cat" yields "foo 2". */
4480 o_reset_to_empty_unquoted(&ctx.as_string);
4485 #if ENABLE_HUSH_CASE
4486 /* "case... in [(]word)..." - skip '(' */
4487 if (ctx.ctx_res_w == RES_MATCH
4488 && ctx.command->argv == NULL /* not (word|(... */
4489 && dest.length == 0 /* not word(... */
4490 && dest.has_quoted_part == 0 /* not ""(... */
4496 if (parse_group(&dest, &ctx, input, ch) != 0) {
4501 #if ENABLE_HUSH_CASE
4502 if (ctx.ctx_res_w == RES_MATCH)
4506 /* proper use of this character is caught by end_trigger:
4507 * if we see {, we call parse_group(..., end_trigger='}')
4508 * and it will match } earlier (not here). */
4509 syntax_error_unexpected_ch(ch);
4513 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4519 struct parse_context *pctx;
4520 IF_HAS_KEYWORDS(struct parse_context *p2;)
4522 /* Clean up allocated tree.
4523 * Sample for finding leaks on syntax error recovery path.
4524 * Run it from interactive shell, watch pmap `pidof hush`.
4525 * while if false; then false; fi; do break; fi
4526 * Samples to catch leaks at execution:
4527 * while if (true | {true;}); then echo ok; fi; do break; done
4528 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4532 /* Update pipe/command counts,
4533 * otherwise freeing may miss some */
4534 done_pipe(pctx, PIPE_SEQ);
4535 debug_printf_clean("freeing list %p from ctx %p\n",
4536 pctx->list_head, pctx);
4537 debug_print_tree(pctx->list_head, 0);
4538 free_pipe_list(pctx->list_head);
4539 debug_printf_clean("freed list %p\n", pctx->list_head);
4541 o_free_unsafe(&pctx->as_string);
4543 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4547 IF_HAS_KEYWORDS(pctx = p2;)
4548 } while (HAS_KEYWORDS && pctx);
4551 G.last_exitcode = 1;
4562 /*** Execution routines ***/
4564 /* Expansion can recurse, need forward decls: */
4565 #if !ENABLE_HUSH_BASH_COMPAT
4566 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4567 #define expand_string_to_string(str, do_unbackslash) \
4568 expand_string_to_string(str)
4570 static char *expand_string_to_string(const char *str, int do_unbackslash);
4571 #if ENABLE_HUSH_TICK
4572 static int process_command_subs(o_string *dest, const char *s);
4575 /* expand_strvec_to_strvec() takes a list of strings, expands
4576 * all variable references within and returns a pointer to
4577 * a list of expanded strings, possibly with larger number
4578 * of strings. (Think VAR="a b"; echo $VAR).
4579 * This new list is allocated as a single malloc block.
4580 * NULL-terminated list of char* pointers is at the beginning of it,
4581 * followed by strings themselves.
4582 * Caller can deallocate entire list by single free(list). */
4584 /* A horde of its helpers come first: */
4586 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4588 while (--len >= 0) {
4591 #if ENABLE_HUSH_BRACE_EXPANSION
4592 if (c == '{' || c == '}') {
4593 /* { -> \{, } -> \} */
4595 /* And now we want to add { or } and continue:
4598 * luckily, just falling throught achieves this.
4604 /* \z -> \\\z; \<eol> -> \\<eol> */
4609 o_addchr(o, *str++);
4615 /* Store given string, finalizing the word and starting new one whenever
4616 * we encounter IFS char(s). This is used for expanding variable values.
4617 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4618 static int expand_on_ifs(o_string *output, int n, const char *str)
4621 int word_len = strcspn(str, G.ifs);
4623 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4624 o_addblock(output, str, word_len);
4626 /* Protect backslashes against globbing up :)
4627 * Example: "v='\*'; echo b$v" prints "b\*"
4628 * (and does not try to glob on "*")
4630 o_addblock_duplicate_backslash(output, str, word_len);
4631 /*/ Why can't we do it easier? */
4632 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4633 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4637 if (!*str) /* EOL - do not finalize word */
4639 o_addchr(output, '\0');
4640 debug_print_list("expand_on_ifs", output, n);
4641 n = o_save_ptr(output, n);
4642 str += strspn(str, G.ifs); /* skip ifs chars */
4644 debug_print_list("expand_on_ifs[1]", output, n);
4648 /* Helper to expand $((...)) and heredoc body. These act as if
4649 * they are in double quotes, with the exception that they are not :).
4650 * Just the rules are similar: "expand only $var and `cmd`"
4652 * Returns malloced string.
4653 * As an optimization, we return NULL if expansion is not needed.
4655 #if !ENABLE_HUSH_BASH_COMPAT
4656 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4657 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4658 encode_then_expand_string(str)
4660 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4663 struct in_str input;
4664 o_string dest = NULL_O_STRING;
4666 if (!strchr(str, '$')
4667 && !strchr(str, '\\')
4668 #if ENABLE_HUSH_TICK
4669 && !strchr(str, '`')
4675 /* We need to expand. Example:
4676 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4678 setup_string_in_str(&input, str);
4679 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4680 //TODO: error check (encode_string returns 0 on error)?
4681 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4682 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4683 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4684 o_free_unsafe(&dest);
4688 #if ENABLE_SH_MATH_SUPPORT
4689 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4691 arith_state_t math_state;
4695 math_state.lookupvar = get_local_var_value;
4696 math_state.setvar = set_local_var_from_halves;
4697 //math_state.endofname = endofname;
4698 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4699 res = arith(&math_state, exp_str ? exp_str : arg);
4702 *errmsg_p = math_state.errmsg;
4703 if (math_state.errmsg)
4704 die_if_script(math_state.errmsg);
4709 #if ENABLE_HUSH_BASH_COMPAT
4710 /* ${var/[/]pattern[/repl]} helpers */
4711 static char *strstr_pattern(char *val, const char *pattern, int *size)
4714 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4715 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4722 /* Optimization: if "*pat" did not match the start of "string",
4723 * we know that "tring", "ring" etc will not match too:
4725 if (pattern[0] == '*')
4730 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4732 char *result = NULL;
4733 unsigned res_len = 0;
4734 unsigned repl_len = strlen(repl);
4738 char *s = strstr_pattern(val, pattern, &size);
4742 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4743 memcpy(result + res_len, val, s - val);
4745 strcpy(result + res_len, repl);
4746 res_len += repl_len;
4747 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4753 if (val[0] && result) {
4754 result = xrealloc(result, res_len + strlen(val) + 1);
4755 strcpy(result + res_len, val);
4756 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4758 debug_printf_varexp("result:'%s'\n", result);
4764 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4766 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4768 const char *val = NULL;
4769 char *to_be_freed = NULL;
4774 char exp_save = exp_save; /* for compiler */
4775 char *exp_saveptr; /* points to expansion operator */
4776 char *exp_word = exp_word; /* for compiler */
4779 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4781 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4783 first_char = arg[0] = arg0 & 0x7f;
4786 if (first_char == '#' /* ${#... */
4787 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4789 /* It must be length operator: ${#var} */
4793 /* Maybe handle parameter expansion */
4794 if (exp_saveptr /* if 2nd char is one of expansion operators */
4795 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4797 /* ${?:0}, ${#[:]%0} etc */
4798 exp_saveptr = var + 1;
4800 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4801 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4803 exp_op = exp_save = *exp_saveptr;
4805 exp_word = exp_saveptr + 1;
4806 if (exp_op == ':') {
4807 exp_op = *exp_word++;
4808 //TODO: try ${var:} and ${var:bogus} in non-bash config
4809 if (ENABLE_HUSH_BASH_COMPAT
4810 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4812 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4817 *exp_saveptr = '\0';
4818 } /* else: it's not an expansion op, but bare ${var} */
4821 /* Look up the variable in question */
4822 if (isdigit(var[0])) {
4823 /* parse_dollar should have vetted var for us */
4824 int n = xatoi_positive(var);
4825 if (n < G.global_argc)
4826 val = G.global_argv[n];
4827 /* else val remains NULL: $N with too big N */
4831 val = utoa(G.root_pid);
4833 case '!': /* bg pid */
4834 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4836 case '?': /* exitcode */
4837 val = utoa(G.last_exitcode);
4839 case '#': /* argc */
4840 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4843 val = get_local_var_value(var);
4847 /* Handle any expansions */
4848 if (exp_op == 'L') {
4849 debug_printf_expand("expand: length(%s)=", val);
4850 val = utoa(val ? strlen(val) : 0);
4851 debug_printf_expand("%s\n", val);
4852 } else if (exp_op) {
4853 if (exp_op == '%' || exp_op == '#') {
4854 /* Standard-mandated substring removal ops:
4855 * ${parameter%word} - remove smallest suffix pattern
4856 * ${parameter%%word} - remove largest suffix pattern
4857 * ${parameter#word} - remove smallest prefix pattern
4858 * ${parameter##word} - remove largest prefix pattern
4860 * Word is expanded to produce a glob pattern.
4861 * Then var's value is matched to it and matching part removed.
4863 if (val && val[0]) {
4867 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4868 if (exp_op == *exp_word) /* ## or %% */
4870 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4872 exp_word = exp_exp_word;
4873 /* HACK ALERT. We depend here on the fact that
4874 * G.global_argv and results of utoa and get_local_var_value
4875 * are actually in writable memory:
4876 * scan_and_match momentarily stores NULs there. */
4878 loc = scan_and_match(t, exp_word, scan_flags);
4879 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4880 // exp_op, t, exp_word, loc);
4882 if (loc) { /* match was found */
4883 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4884 val = loc; /* take right part */
4886 val = to_be_freed = xstrndup(val, loc - val); /* left */
4890 #if ENABLE_HUSH_BASH_COMPAT
4891 else if (exp_op == '/' || exp_op == '\\') {
4892 /* It's ${var/[/]pattern[/repl]} thing.
4893 * Note that in encoded form it has TWO parts:
4894 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4895 * and if // is used, it is encoded as \:
4896 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4898 /* Empty variable always gives nothing: */
4899 // "v=''; echo ${v/*/w}" prints "", not "w"
4900 if (val && val[0]) {
4901 /* pattern uses non-standard expansion.
4902 * repl should be unbackslashed and globbed
4903 * by the usual expansion rules:
4905 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4906 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4907 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4908 * v='a bz'; echo ${v/a*z/\z} prints "z"
4909 * (note that a*z _pattern_ is never globbed!)
4911 char *pattern, *repl, *t;
4912 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4914 pattern = xstrdup(exp_word);
4915 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4916 *p++ = SPECIAL_VAR_SYMBOL;
4918 p = strchr(p, SPECIAL_VAR_SYMBOL);
4920 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4921 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4922 /* HACK ALERT. We depend here on the fact that
4923 * G.global_argv and results of utoa and get_local_var_value
4924 * are actually in writable memory:
4925 * replace_pattern momentarily stores NULs there. */
4927 to_be_freed = replace_pattern(t,
4929 (repl ? repl : exp_word),
4931 if (to_be_freed) /* at least one replace happened */
4938 else if (exp_op == ':') {
4939 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4940 /* It's ${var:N[:M]} bashism.
4941 * Note that in encoded form it has TWO parts:
4942 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4947 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4950 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4951 *p++ = SPECIAL_VAR_SYMBOL;
4953 p = strchr(p, SPECIAL_VAR_SYMBOL);
4955 len = expand_and_evaluate_arith(exp_word, &errmsg);
4958 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4959 if (len >= 0) { /* bash compat: len < 0 is illegal */
4960 if (beg < 0) /* bash compat */
4962 debug_printf_varexp("from val:'%s'\n", val);
4963 if (len == 0 || !val || beg >= strlen(val)) {
4967 /* Paranoia. What if user entered 9999999999999
4968 * which fits in arith_t but not int? */
4971 val = to_be_freed = xstrndup(val + beg, len);
4973 debug_printf_varexp("val:'%s'\n", val);
4977 die_if_script("malformed ${%s:...}", var);
4980 } else { /* one of "-=+?" */
4981 /* Standard-mandated substitution ops:
4982 * ${var?word} - indicate error if unset
4983 * If var is unset, word (or a message indicating it is unset
4984 * if word is null) is written to standard error
4985 * and the shell exits with a non-zero exit status.
4986 * Otherwise, the value of var is substituted.
4987 * ${var-word} - use default value
4988 * If var is unset, word is substituted.
4989 * ${var=word} - assign and use default value
4990 * If var is unset, word is assigned to var.
4991 * In all cases, final value of var is substituted.
4992 * ${var+word} - use alternative value
4993 * If var is unset, null is substituted.
4994 * Otherwise, word is substituted.
4996 * Word is subjected to tilde expansion, parameter expansion,
4997 * command substitution, and arithmetic expansion.
4998 * If word is not needed, it is not expanded.
5000 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5001 * but also treat null var as if it is unset.
5003 int use_word = (!val || ((exp_save == ':') && !val[0]));
5005 use_word = !use_word;
5006 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5007 (exp_save == ':') ? "true" : "false", use_word);
5009 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5011 exp_word = to_be_freed;
5012 if (exp_op == '?') {
5013 /* mimic bash message */
5014 die_if_script("%s: %s",
5016 exp_word[0] ? exp_word : "parameter null or not set"
5018 //TODO: how interactive bash aborts expansion mid-command?
5023 if (exp_op == '=') {
5024 /* ${var=[word]} or ${var:=[word]} */
5025 if (isdigit(var[0]) || var[0] == '#') {
5026 /* mimic bash message */
5027 die_if_script("$%s: cannot assign in this way", var);
5030 char *new_var = xasprintf("%s=%s", var, val);
5031 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5035 } /* one of "-=+?" */
5037 *exp_saveptr = exp_save;
5043 *to_be_freed_pp = to_be_freed;
5047 /* Expand all variable references in given string, adding words to list[]
5048 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5049 * to be filled). This routine is extremely tricky: has to deal with
5050 * variables/parameters with whitespace, $* and $@, and constructs like
5051 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5052 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5054 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5055 * expansion of right-hand side of assignment == 1-element expand.
5057 char cant_be_null = 0; /* only bit 0x80 matters */
5060 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5061 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5062 debug_print_list("expand_vars_to_list", output, n);
5063 n = o_save_ptr(output, n);
5064 debug_print_list("expand_vars_to_list[0]", output, n);
5066 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5068 char *to_be_freed = NULL;
5069 const char *val = NULL;
5070 #if ENABLE_HUSH_TICK
5071 o_string subst_result = NULL_O_STRING;
5073 #if ENABLE_SH_MATH_SUPPORT
5074 char arith_buf[sizeof(arith_t)*3 + 2];
5076 o_addblock(output, arg, p - arg);
5077 debug_print_list("expand_vars_to_list[1]", output, n);
5079 p = strchr(p, SPECIAL_VAR_SYMBOL);
5081 /* Fetch special var name (if it is indeed one of them)
5082 * and quote bit, force the bit on if singleword expansion -
5083 * important for not getting v=$@ expand to many words. */
5084 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5086 /* Is this variable quoted and thus expansion can't be null?
5087 * "$@" is special. Even if quoted, it can still
5088 * expand to nothing (not even an empty string),
5089 * thus it is excluded. */
5090 if ((first_ch & 0x7f) != '@')
5091 cant_be_null |= first_ch;
5093 switch (first_ch & 0x7f) {
5094 /* Highest bit in first_ch indicates that var is double-quoted */
5098 if (!G.global_argv[1])
5101 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5102 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5103 while (G.global_argv[i]) {
5104 n = expand_on_ifs(output, n, G.global_argv[i]);
5105 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5106 if (G.global_argv[i++][0] && G.global_argv[i]) {
5107 /* this argv[] is not empty and not last:
5108 * put terminating NUL, start new word */
5109 o_addchr(output, '\0');
5110 debug_print_list("expand_vars_to_list[2]", output, n);
5111 n = o_save_ptr(output, n);
5112 debug_print_list("expand_vars_to_list[3]", output, n);
5116 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5117 * and in this case should treat it like '$*' - see 'else...' below */
5118 if (first_ch == ('@'|0x80) /* quoted $@ */
5119 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5122 o_addQstr(output, G.global_argv[i]);
5123 if (++i >= G.global_argc)
5125 o_addchr(output, '\0');
5126 debug_print_list("expand_vars_to_list[4]", output, n);
5127 n = o_save_ptr(output, n);
5129 } else { /* quoted $* (or v="$@" case): add as one word */
5131 o_addQstr(output, G.global_argv[i]);
5132 if (!G.global_argv[++i])
5135 o_addchr(output, G.ifs[0]);
5140 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5141 /* "Empty variable", used to make "" etc to not disappear */
5143 cant_be_null = 0x80;
5145 #if ENABLE_HUSH_TICK
5146 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5147 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5149 /* Can't just stuff it into output o_string,
5150 * expanded result may need to be globbed
5151 * and $IFS-splitted */
5152 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5153 G.last_exitcode = process_command_subs(&subst_result, arg);
5154 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5155 val = subst_result.data;
5158 #if ENABLE_SH_MATH_SUPPORT
5159 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5162 arg++; /* skip '+' */
5163 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5164 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5165 res = expand_and_evaluate_arith(arg, NULL);
5166 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5167 sprintf(arith_buf, ARITH_FMT, res);
5173 val = expand_one_var(&to_be_freed, arg, &p);
5174 IF_HUSH_TICK(store_val:)
5175 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5176 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5177 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5178 if (val && val[0]) {
5179 n = expand_on_ifs(output, n, val);
5182 } else { /* quoted $VAR, val will be appended below */
5183 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5184 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5188 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5190 if (val && val[0]) {
5191 o_addQstr(output, val);
5195 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5196 * Do the check to avoid writing to a const string. */
5197 if (*p != SPECIAL_VAR_SYMBOL)
5198 *p = SPECIAL_VAR_SYMBOL;
5200 #if ENABLE_HUSH_TICK
5201 o_free(&subst_result);
5204 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5207 debug_print_list("expand_vars_to_list[a]", output, n);
5208 /* this part is literal, and it was already pre-quoted
5209 * if needed (much earlier), do not use o_addQstr here! */
5210 o_addstr_with_NUL(output, arg);
5211 debug_print_list("expand_vars_to_list[b]", output, n);
5212 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5213 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5216 /* allow to reuse list[n] later without re-growth */
5217 output->has_empty_slot = 1;
5219 o_addchr(output, '\0');
5225 static char **expand_variables(char **argv, unsigned expflags)
5229 o_string output = NULL_O_STRING;
5231 output.o_expflags = expflags;
5235 n = expand_vars_to_list(&output, n, *argv);
5238 debug_print_list("expand_variables", &output, n);
5240 /* output.data (malloced in one block) gets returned in "list" */
5241 list = o_finalize_list(&output, n);
5242 debug_print_strings("expand_variables[1]", list);
5246 static char **expand_strvec_to_strvec(char **argv)
5248 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5251 #if ENABLE_HUSH_BASH_COMPAT
5252 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5254 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5258 /* Used for expansion of right hand of assignments,
5259 * $((...)), heredocs, variable espansion parts.
5261 * NB: should NOT do globbing!
5262 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5264 static char *expand_string_to_string(const char *str, int do_unbackslash)
5266 #if !ENABLE_HUSH_BASH_COMPAT
5267 const int do_unbackslash = 1;
5269 char *argv[2], **list;
5271 debug_printf_expand("string_to_string<='%s'\n", str);
5272 /* This is generally an optimization, but it also
5273 * handles "", which otherwise trips over !list[0] check below.
5274 * (is this ever happens that we actually get str="" here?)
5276 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5277 //TODO: Can use on strings with \ too, just unbackslash() them?
5278 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5279 return xstrdup(str);
5282 argv[0] = (char*)str;
5284 list = expand_variables(argv, do_unbackslash
5285 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5286 : EXP_FLAG_SINGLEWORD
5289 if (!list[0] || list[1])
5290 bb_error_msg_and_die("BUG in varexp2");
5291 /* actually, just move string 2*sizeof(char*) bytes back */
5292 overlapping_strcpy((char*)list, list[0]);
5294 unbackslash((char*)list);
5295 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5299 /* Used for "eval" builtin */
5300 static char* expand_strvec_to_string(char **argv)
5304 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5305 /* Convert all NULs to spaces */
5310 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5311 bb_error_msg_and_die("BUG in varexp3");
5312 /* bash uses ' ' regardless of $IFS contents */
5317 overlapping_strcpy((char*)list, list[0]);
5318 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5322 static char **expand_assignments(char **argv, int count)
5327 G.expanded_assignments = p = NULL;
5328 /* Expand assignments into one string each */
5329 for (i = 0; i < count; i++) {
5330 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5332 G.expanded_assignments = NULL;
5339 void re_execute_shell(char ***to_free, const char *s,
5340 char *g_argv0, char **g_argv,
5341 char **builtin_argv) NORETURN;
5343 static void reset_traps_to_defaults(void)
5345 /* This function is always called in a child shell
5346 * after fork (not vfork, NOMMU doesn't use this function).
5351 /* Child shells are not interactive.
5352 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5353 * Testcase: (while :; do :; done) + ^Z should background.
5354 * Same goes for SIGTERM, SIGHUP, SIGINT.
5356 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5357 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5359 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5360 * Stupid. It can be done with *single* &= op, but we can't use
5361 * the fact that G.blocked_set is implemented as a bitmask
5363 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5367 /* Careful. Only if no trap or trap is not "" */
5368 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5369 sigdelset(&G.blocked_set, sig);
5376 /* Our homegrown sig mask is saner to work with :) */
5377 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5379 /* Resetting all traps to default except empty ones */
5380 mask = G.non_DFL_mask;
5381 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5382 if (!G.traps[sig] || !G.traps[sig][0])
5385 G.traps[sig] = NULL;
5386 /* There is no signal for 0 (EXIT) */
5389 /* There was a trap handler, we just removed it.
5390 * But if sig still has non-DFL handling,
5391 * we should not unblock the sig. */
5394 sigdelset(&G.blocked_set, sig);
5396 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5401 static void re_execute_shell(char ***to_free, const char *s,
5402 char *g_argv0, char **g_argv,
5403 char **builtin_argv) NORETURN;
5404 static void re_execute_shell(char ***to_free, const char *s,
5405 char *g_argv0, char **g_argv,
5406 char **builtin_argv)
5408 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5409 /* delims + 2 * (number of bytes in printed hex numbers) */
5410 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5411 char *heredoc_argv[4];
5412 struct variable *cur;
5413 # if ENABLE_HUSH_FUNCTIONS
5414 struct function *funcp;
5418 unsigned long long empty_trap_mask;
5420 if (!g_argv0) { /* heredoc */
5421 argv = heredoc_argv;
5422 argv[0] = (char *) G.argv0_for_re_execing;
5423 argv[1] = (char *) "-<";
5424 argv[2] = (char *) s;
5426 pp = &argv[3]; /* used as pointer to empty environment */
5432 if (pp) while (*pp++)
5435 empty_trap_mask = 0;
5438 for (sig = 1; sig < NSIG; sig++) {
5439 if (G.traps[sig] && !G.traps[sig][0])
5440 empty_trap_mask |= 1LL << sig;
5444 sprintf(param_buf, NOMMU_HACK_FMT
5445 , (unsigned) G.root_pid
5446 , (unsigned) G.root_ppid
5447 , (unsigned) G.last_bg_pid
5448 , (unsigned) G.last_exitcode
5451 IF_HUSH_LOOPS(, G.depth_of_loop)
5453 # undef NOMMU_HACK_FMT
5454 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5455 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5458 for (cur = G.top_var; cur; cur = cur->next) {
5459 if (!cur->flg_export || cur->flg_read_only)
5462 # if ENABLE_HUSH_FUNCTIONS
5463 for (funcp = G.top_func; funcp; funcp = funcp->next)
5469 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5470 *pp++ = (char *) G.argv0_for_re_execing;
5472 for (cur = G.top_var; cur; cur = cur->next) {
5473 if (strcmp(cur->varstr, hush_version_str) == 0)
5475 if (cur->flg_read_only) {
5476 *pp++ = (char *) "-R";
5477 *pp++ = cur->varstr;
5478 } else if (!cur->flg_export) {
5479 *pp++ = (char *) "-V";
5480 *pp++ = cur->varstr;
5483 # if ENABLE_HUSH_FUNCTIONS
5484 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5485 *pp++ = (char *) "-F";
5486 *pp++ = funcp->name;
5487 *pp++ = funcp->body_as_string;
5490 /* We can pass activated traps here. Say, -Tnn:trap_string
5492 * However, POSIX says that subshells reset signals with traps
5494 * I tested bash-3.2 and it not only does that with true subshells
5495 * of the form ( list ), but with any forked children shells.
5496 * I set trap "echo W" WINCH; and then tried:
5498 * { echo 1; sleep 20; echo 2; } &
5499 * while true; do echo 1; sleep 20; echo 2; break; done &
5500 * true | { echo 1; sleep 20; echo 2; } | cat
5502 * In all these cases sending SIGWINCH to the child shell
5503 * did not run the trap. If I add trap "echo V" WINCH;
5504 * _inside_ group (just before echo 1), it works.
5506 * I conclude it means we don't need to pass active traps here.
5507 * Even if we would use signal handlers instead of signal masking
5508 * in order to implement trap handling,
5509 * exec syscall below resets signals to SIG_DFL for us.
5511 *pp++ = (char *) "-c";
5514 while (*++builtin_argv)
5515 *pp++ = *builtin_argv;
5516 *pp++ = (char *) "";
5521 /* *pp = NULL; - is already there */
5525 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5526 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5527 execve(bb_busybox_exec_path, argv, pp);
5528 /* Fallback. Useful for init=/bin/hush usage etc */
5529 if (argv[0][0] == '/')
5530 execve(argv[0], argv, pp);
5531 xfunc_error_retval = 127;
5532 bb_error_msg_and_die("can't re-execute the shell");
5534 #endif /* !BB_MMU */
5537 static int run_and_free_list(struct pipe *pi);
5539 /* Executing from string: eval, sh -c '...'
5540 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5541 * end_trigger controls how often we stop parsing
5542 * NUL: parse all, execute, return
5543 * ';': parse till ';' or newline, execute, repeat till EOF
5545 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5547 /* Why we need empty flag?
5548 * An obscure corner case "false; ``; echo $?":
5549 * empty command in `` should still set $? to 0.
5550 * But we can't just set $? to 0 at the start,
5551 * this breaks "false; echo `echo $?`" case.
5555 struct pipe *pipe_list;
5557 #if ENABLE_HUSH_INTERACTIVE
5558 if (end_trigger == ';')
5559 inp->promptmode = 0; /* PS1 */
5561 pipe_list = parse_stream(NULL, inp, end_trigger);
5562 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5563 /* If we are in "big" script
5564 * (not in `cmd` or something similar)...
5566 if (pipe_list == ERR_PTR && end_trigger == ';') {
5567 /* Discard cached input (rest of line) */
5568 int ch = inp->last_char;
5569 while (ch != EOF && ch != '\n') {
5570 //bb_error_msg("Discarded:'%c'", ch);
5575 /* This stream isn't empty */
5579 if (!pipe_list && empty)
5580 G.last_exitcode = 0;
5583 debug_print_tree(pipe_list, 0);
5584 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5585 run_and_free_list(pipe_list);
5587 #if ENABLE_HUSH_FUNCTIONS
5588 if (G.flag_return_in_progress == 1)
5594 static void parse_and_run_string(const char *s)
5596 struct in_str input;
5597 setup_string_in_str(&input, s);
5598 parse_and_run_stream(&input, '\0');
5601 static void parse_and_run_file(FILE *f)
5603 struct in_str input;
5604 setup_file_in_str(&input, f);
5605 parse_and_run_stream(&input, ';');
5608 #if ENABLE_HUSH_TICK
5609 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5614 char **to_free = NULL;
5618 pid = BB_MMU ? xfork() : xvfork();
5619 if (pid == 0) { /* child */
5620 disable_restore_tty_pgrp_on_exit();
5621 /* Process substitution is not considered to be usual
5622 * 'command execution'.
5623 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5630 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5631 close(channel[0]); /* NB: close _first_, then move fd! */
5632 xmove_fd(channel[1], 1);
5633 /* Prevent it from trying to handle ctrl-z etc */
5634 IF_HUSH_JOB(G.run_list_level = 1;)
5635 /* Awful hack for `trap` or $(trap).
5637 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5638 * contains an example where "trap" is executed in a subshell:
5640 * save_traps=$(trap)
5642 * eval "$save_traps"
5644 * Standard does not say that "trap" in subshell shall print
5645 * parent shell's traps. It only says that its output
5646 * must have suitable form, but then, in the above example
5647 * (which is not supposed to be normative), it implies that.
5649 * bash (and probably other shell) does implement it
5650 * (traps are reset to defaults, but "trap" still shows them),
5651 * but as a result, "trap" logic is hopelessly messed up:
5654 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5655 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5656 * # true | trap <--- trap is in subshell - no output (ditto)
5657 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5658 * trap -- 'echo Ho' SIGWINCH
5659 * # echo `(trap)` <--- in subshell in subshell - output
5660 * trap -- 'echo Ho' SIGWINCH
5661 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5662 * trap -- 'echo Ho' SIGWINCH
5664 * The rules when to forget and when to not forget traps
5665 * get really complex and nonsensical.
5667 * Our solution: ONLY bare $(trap) or `trap` is special.
5669 s = skip_whitespace(s);
5670 if (strncmp(s, "trap", 4) == 0
5671 && skip_whitespace(s + 4)[0] == '\0'
5673 static const char *const argv[] = { NULL, NULL };
5674 builtin_trap((char**)argv);
5675 exit(0); /* not _exit() - we need to fflush */
5678 reset_traps_to_defaults();
5679 parse_and_run_string(s);
5680 _exit(G.last_exitcode);
5682 /* We re-execute after vfork on NOMMU. This makes this script safe:
5683 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5684 * huge=`cat BIG` # was blocking here forever
5687 re_execute_shell(&to_free,
5697 # if ENABLE_HUSH_FAST
5699 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5700 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5701 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5703 enable_restore_tty_pgrp_on_exit();
5708 close_on_exec_on(channel[0]);
5709 return xfdopen_for_read(channel[0]);
5712 /* Return code is exit status of the process that is run. */
5713 static int process_command_subs(o_string *dest, const char *s)
5716 struct in_str pipe_str;
5718 int status, ch, eol_cnt;
5720 fp = generate_stream_from_string(s, &pid);
5722 /* Now send results of command back into original context */
5723 setup_file_in_str(&pipe_str, fp);
5725 while ((ch = i_getch(&pipe_str)) != EOF) {
5731 o_addchr(dest, '\n');
5734 o_addQchr(dest, ch);
5737 debug_printf("done reading from `cmd` pipe, closing it\n");
5739 /* We need to extract exitcode. Test case
5740 * "true; echo `sleep 1; false` $?"
5742 safe_waitpid(pid, &status, 0);
5743 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5744 return WEXITSTATUS(status);
5746 #endif /* ENABLE_HUSH_TICK */
5749 static void setup_heredoc(struct redir_struct *redir)
5751 struct fd_pair pair;
5754 /* the _body_ of heredoc (misleading field name) */
5755 const char *heredoc = redir->rd_filename;
5762 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5763 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5767 len = strlen(heredoc);
5769 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5771 xmove_fd(pair.rd, redir->rd_fd);
5773 /* Try writing without forking. Newer kernels have
5774 * dynamically growing pipes. Must use non-blocking write! */
5777 written = write(pair.wr, heredoc, len);
5788 ndelay_off(pair.wr);
5790 /* Okay, pipe buffer was not big enough */
5791 /* Note: we must not create a stray child (bastard? :)
5792 * for the unsuspecting parent process. Child creates a grandchild
5793 * and exits before parent execs the process which consumes heredoc
5794 * (that exec happens after we return from this function) */
5801 disable_restore_tty_pgrp_on_exit();
5802 pid = BB_MMU ? xfork() : xvfork();
5806 close(redir->rd_fd); /* read side of the pipe */
5808 full_write(pair.wr, heredoc, len); /* may loop or block */
5811 /* Delegate blocking writes to another process */
5812 xmove_fd(pair.wr, STDOUT_FILENO);
5813 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5817 #if ENABLE_HUSH_FAST
5819 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5821 enable_restore_tty_pgrp_on_exit();
5827 wait(NULL); /* wait till child has died */
5830 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5831 * and stderr if they are redirected. */
5832 static int setup_redirects(struct command *prog, int squirrel[])
5835 struct redir_struct *redir;
5837 for (redir = prog->redirects; redir; redir = redir->next) {
5838 if (redir->rd_type == REDIRECT_HEREDOC2) {
5839 /* rd_fd<<HERE case */
5840 if (squirrel && redir->rd_fd < 3
5841 && squirrel[redir->rd_fd] < 0
5843 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5845 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5847 debug_printf_parse("set heredoc '%s'\n",
5848 redir->rd_filename);
5849 setup_heredoc(redir);
5853 if (redir->rd_dup == REDIRFD_TO_FILE) {
5854 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5856 if (redir->rd_filename == NULL) {
5857 /* Something went wrong in the parse.
5858 * Pretend it didn't happen */
5859 bb_error_msg("bug in redirect parse");
5862 mode = redir_table[redir->rd_type].mode;
5863 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5864 openfd = open_or_warn(p, mode);
5867 /* this could get lost if stderr has been redirected, but
5868 * bash and ash both lose it as well (though zsh doesn't!) */
5869 //what the above comment tries to say?
5873 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5874 openfd = redir->rd_dup;
5877 if (openfd != redir->rd_fd) {
5878 if (squirrel && redir->rd_fd < 3
5879 && squirrel[redir->rd_fd] < 0
5881 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5883 if (openfd == REDIRFD_CLOSE) {
5884 /* "n>-" means "close me" */
5885 close(redir->rd_fd);
5887 xdup2(openfd, redir->rd_fd);
5888 if (redir->rd_dup == REDIRFD_TO_FILE)
5896 static void restore_redirects(int squirrel[])
5899 for (i = 0; i < 3; i++) {
5902 /* We simply die on error */
5908 static char *find_in_path(const char *arg)
5911 const char *PATH = get_local_var_value("PATH");
5917 const char *end = strchrnul(PATH, ':');
5918 int sz = end - PATH; /* must be int! */
5922 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5924 /* We have xxx::yyyy in $PATH,
5925 * it means "use current dir" */
5928 if (access(ret, F_OK) == 0)
5941 static const struct built_in_command *find_builtin_helper(const char *name,
5942 const struct built_in_command *x,
5943 const struct built_in_command *end)
5946 if (strcmp(name, x->b_cmd) != 0) {
5950 debug_printf_exec("found builtin '%s'\n", name);
5955 static const struct built_in_command *find_builtin1(const char *name)
5957 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5959 static const struct built_in_command *find_builtin(const char *name)
5961 const struct built_in_command *x = find_builtin1(name);
5964 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5967 #if ENABLE_HUSH_FUNCTIONS
5968 static struct function **find_function_slot(const char *name)
5970 struct function **funcpp = &G.top_func;
5972 if (strcmp(name, (*funcpp)->name) == 0) {
5975 funcpp = &(*funcpp)->next;
5980 static const struct function *find_function(const char *name)
5982 const struct function *funcp = *find_function_slot(name);
5984 debug_printf_exec("found function '%s'\n", name);
5988 /* Note: takes ownership on name ptr */
5989 static struct function *new_function(char *name)
5991 struct function **funcpp = find_function_slot(name);
5992 struct function *funcp = *funcpp;
5994 if (funcp != NULL) {
5995 struct command *cmd = funcp->parent_cmd;
5996 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5998 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6000 /* Note: if !funcp->body, do not free body_as_string!
6001 * This is a special case of "-F name body" function:
6002 * body_as_string was not malloced! */
6004 free_pipe_list(funcp->body);
6006 free(funcp->body_as_string);
6010 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6011 cmd->argv[0] = funcp->name;
6012 cmd->group = funcp->body;
6014 cmd->group_as_string = funcp->body_as_string;
6018 debug_printf_exec("remembering new function '%s'\n", name);
6019 funcp = *funcpp = xzalloc(sizeof(*funcp));
6020 /*funcp->next = NULL;*/
6027 static void unset_func(const char *name)
6029 struct function **funcpp = find_function_slot(name);
6030 struct function *funcp = *funcpp;
6032 if (funcp != NULL) {
6033 debug_printf_exec("freeing function '%s'\n", funcp->name);
6034 *funcpp = funcp->next;
6035 /* funcp is unlinked now, deleting it.
6036 * Note: if !funcp->body, the function was created by
6037 * "-F name body", do not free ->body_as_string
6038 * and ->name as they were not malloced. */
6040 free_pipe_list(funcp->body);
6043 free(funcp->body_as_string);
6051 #define exec_function(to_free, funcp, argv) \
6052 exec_function(funcp, argv)
6054 static void exec_function(char ***to_free,
6055 const struct function *funcp,
6056 char **argv) NORETURN;
6057 static void exec_function(char ***to_free,
6058 const struct function *funcp,
6064 argv[0] = G.global_argv[0];
6065 G.global_argv = argv;
6069 /* On MMU, funcp->body is always non-NULL */
6070 n = run_list(funcp->body);
6074 re_execute_shell(to_free,
6075 funcp->body_as_string,
6082 static int run_function(const struct function *funcp, char **argv)
6088 save_and_replace_G_args(&sv, argv);
6090 /* "we are in function, ok to use return" */
6091 sv_flg = G.flag_return_in_progress;
6092 G.flag_return_in_progress = -1;
6093 # if ENABLE_HUSH_LOCAL
6094 G.func_nest_level++;
6097 /* On MMU, funcp->body is always non-NULL */
6100 /* Function defined by -F */
6101 parse_and_run_string(funcp->body_as_string);
6102 rc = G.last_exitcode;
6106 rc = run_list(funcp->body);
6109 # if ENABLE_HUSH_LOCAL
6111 struct variable *var;
6112 struct variable **var_pp;
6114 var_pp = &G.top_var;
6115 while ((var = *var_pp) != NULL) {
6116 if (var->func_nest_level < G.func_nest_level) {
6117 var_pp = &var->next;
6121 if (var->flg_export)
6122 bb_unsetenv(var->varstr);
6123 /* Remove from global list */
6124 *var_pp = var->next;
6130 G.func_nest_level--;
6133 G.flag_return_in_progress = sv_flg;
6135 restore_G_args(&sv, argv);
6139 #endif /* ENABLE_HUSH_FUNCTIONS */
6143 #define exec_builtin(to_free, x, argv) \
6144 exec_builtin(x, argv)
6146 #define exec_builtin(to_free, x, argv) \
6147 exec_builtin(to_free, argv)
6149 static void exec_builtin(char ***to_free,
6150 const struct built_in_command *x,
6151 char **argv) NORETURN;
6152 static void exec_builtin(char ***to_free,
6153 const struct built_in_command *x,
6159 rcode = x->b_function(argv);
6164 /* On NOMMU, we must never block!
6165 * Example: { sleep 99 | read line; } & echo Ok
6167 re_execute_shell(to_free,
6176 static void execvp_or_die(char **argv) NORETURN;
6177 static void execvp_or_die(char **argv)
6179 debug_printf_exec("execing '%s'\n", argv[0]);
6180 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6181 execvp(argv[0], argv);
6182 bb_perror_msg("can't execute '%s'", argv[0]);
6183 _exit(127); /* bash compat */
6186 #if ENABLE_HUSH_MODE_X
6187 static void dump_cmd_in_x_mode(char **argv)
6189 if (G_x_mode && argv) {
6190 /* We want to output the line in one write op */
6198 len += strlen(argv[n++]) + 1;
6204 p += sprintf(p, " %s", argv[n++]);
6212 # define dump_cmd_in_x_mode(argv) ((void)0)
6216 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6217 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6218 #define pseudo_exec(nommu_save, command, argv_expanded) \
6219 pseudo_exec(command, argv_expanded)
6222 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6224 * Don't exit() here. If you don't exec, use _exit instead.
6225 * The at_exit handlers apparently confuse the calling process,
6226 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6227 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6228 char **argv, int assignment_cnt,
6229 char **argv_expanded) NORETURN;
6230 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6231 char **argv, int assignment_cnt,
6232 char **argv_expanded)
6236 new_env = expand_assignments(argv, assignment_cnt);
6237 dump_cmd_in_x_mode(new_env);
6239 if (!argv[assignment_cnt]) {
6240 /* Case when we are here: ... | var=val | ...
6241 * (note that we do not exit early, i.e., do not optimize out
6242 * expand_assignments(): think about ... | var=`sleep 1` | ...
6244 free_strings(new_env);
6245 _exit(EXIT_SUCCESS);
6249 set_vars_and_save_old(new_env);
6250 free(new_env); /* optional */
6251 /* we can also destroy set_vars_and_save_old's return value,
6254 nommu_save->new_env = new_env;
6255 nommu_save->old_vars = set_vars_and_save_old(new_env);
6258 if (argv_expanded) {
6259 argv = argv_expanded;
6261 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6263 nommu_save->argv = argv;
6266 dump_cmd_in_x_mode(argv);
6268 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6269 if (strchr(argv[0], '/') != NULL)
6273 /* Check if the command matches any of the builtins.
6274 * Depending on context, this might be redundant. But it's
6275 * easier to waste a few CPU cycles than it is to figure out
6276 * if this is one of those cases.
6279 /* On NOMMU, it is more expensive to re-execute shell
6280 * just in order to run echo or test builtin.
6281 * It's better to skip it here and run corresponding
6282 * non-builtin later. */
6283 const struct built_in_command *x;
6284 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6286 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6289 #if ENABLE_HUSH_FUNCTIONS
6290 /* Check if the command matches any functions */
6292 const struct function *funcp = find_function(argv[0]);
6294 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6299 #if ENABLE_FEATURE_SH_STANDALONE
6300 /* Check if the command matches any busybox applets */
6302 int a = find_applet_by_name(argv[0]);
6304 # if BB_MMU /* see above why on NOMMU it is not allowed */
6305 if (APPLET_IS_NOEXEC(a)) {
6306 debug_printf_exec("running applet '%s'\n", argv[0]);
6307 run_applet_no_and_exit(a, argv);
6310 /* Re-exec ourselves */
6311 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6312 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6313 execv(bb_busybox_exec_path, argv);
6314 /* If they called chroot or otherwise made the binary no longer
6315 * executable, fall through */
6320 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6323 execvp_or_die(argv);
6326 /* Called after [v]fork() in run_pipe
6328 static void pseudo_exec(nommu_save_t *nommu_save,
6329 struct command *command,
6330 char **argv_expanded) NORETURN;
6331 static void pseudo_exec(nommu_save_t *nommu_save,
6332 struct command *command,
6333 char **argv_expanded)
6335 if (command->argv) {
6336 pseudo_exec_argv(nommu_save, command->argv,
6337 command->assignment_cnt, argv_expanded);
6340 if (command->group) {
6341 /* Cases when we are here:
6344 * ... | ( list ) | ...
6345 * ... | { list } | ...
6349 debug_printf_exec("pseudo_exec: run_list\n");
6350 reset_traps_to_defaults();
6351 rcode = run_list(command->group);
6352 /* OK to leak memory by not calling free_pipe_list,
6353 * since this process is about to exit */
6356 re_execute_shell(&nommu_save->argv_from_re_execing,
6357 command->group_as_string,
6364 /* Case when we are here: ... | >file */
6365 debug_printf_exec("pseudo_exec'ed null command\n");
6366 _exit(EXIT_SUCCESS);
6370 static const char *get_cmdtext(struct pipe *pi)
6376 /* This is subtle. ->cmdtext is created only on first backgrounding.
6377 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6378 * On subsequent bg argv is trashed, but we won't use it */
6381 argv = pi->cmds[0].argv;
6382 if (!argv || !argv[0]) {
6383 pi->cmdtext = xzalloc(1);
6389 len += strlen(*argv) + 1;
6393 argv = pi->cmds[0].argv;
6395 len = strlen(*argv);
6396 memcpy(p, *argv, len);
6404 static void insert_bg_job(struct pipe *pi)
6406 struct pipe *job, **jobp;
6409 /* Linear search for the ID of the job to use */
6411 for (job = G.job_list; job; job = job->next)
6412 if (job->jobid >= pi->jobid)
6413 pi->jobid = job->jobid + 1;
6415 /* Add job to the list of running jobs */
6417 while ((job = *jobp) != NULL)
6419 job = *jobp = xmalloc(sizeof(*job));
6421 *job = *pi; /* physical copy */
6423 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6424 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6425 for (i = 0; i < pi->num_cmds; i++) {
6426 job->cmds[i].pid = pi->cmds[i].pid;
6427 /* all other fields are not used and stay zero */
6429 job->cmdtext = xstrdup(get_cmdtext(pi));
6431 if (G_interactive_fd)
6432 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6433 G.last_jobid = job->jobid;
6436 static void remove_bg_job(struct pipe *pi)
6438 struct pipe *prev_pipe;
6440 if (pi == G.job_list) {
6441 G.job_list = pi->next;
6443 prev_pipe = G.job_list;
6444 while (prev_pipe->next != pi)
6445 prev_pipe = prev_pipe->next;
6446 prev_pipe->next = pi->next;
6449 G.last_jobid = G.job_list->jobid;
6454 /* Remove a backgrounded job */
6455 static void delete_finished_bg_job(struct pipe *pi)
6462 /* Check to see if any processes have exited -- if they
6463 * have, figure out why and see if a job has completed */
6464 static int checkjobs(struct pipe *fg_pipe)
6474 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6476 attributes = WUNTRACED;
6477 if (fg_pipe == NULL)
6478 attributes |= WNOHANG;
6481 #if ENABLE_HUSH_FAST
6482 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6483 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6484 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6485 /* There was neither fork nor SIGCHLD since last waitpid */
6486 /* Avoid doing waitpid syscall if possible */
6487 if (!G.we_have_children) {
6491 if (fg_pipe == NULL) { /* is WNOHANG set? */
6492 /* We have children, but they did not exit
6493 * or stop yet (we saw no SIGCHLD) */
6496 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6500 /* Do we do this right?
6501 * bash-3.00# sleep 20 | false
6503 * [3]+ Stopped sleep 20 | false
6504 * bash-3.00# echo $?
6505 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6506 * [hush 1.14.0: yes we do it right]
6513 #if ENABLE_HUSH_FAST
6514 i = G.count_SIGCHLD;
6516 childpid = waitpid(-1, &status, attributes);
6517 if (childpid <= 0) {
6518 if (childpid && errno != ECHILD)
6519 bb_perror_msg("waitpid");
6520 #if ENABLE_HUSH_FAST
6521 else { /* Until next SIGCHLD, waitpid's are useless */
6522 G.we_have_children = (childpid == 0);
6523 G.handled_SIGCHLD = i;
6524 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6529 dead = WIFEXITED(status) || WIFSIGNALED(status);
6532 if (WIFSTOPPED(status))
6533 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6534 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6535 if (WIFSIGNALED(status))
6536 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6537 childpid, WTERMSIG(status), WEXITSTATUS(status));
6538 if (WIFEXITED(status))
6539 debug_printf_jobs("pid %d exited, exitcode %d\n",
6540 childpid, WEXITSTATUS(status));
6542 /* Were we asked to wait for fg pipe? */
6544 i = fg_pipe->num_cmds;
6546 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6547 if (fg_pipe->cmds[i].pid != childpid)
6551 fg_pipe->cmds[i].pid = 0;
6552 fg_pipe->alive_cmds--;
6553 ex = WEXITSTATUS(status);
6554 /* bash prints killer signal's name for *last*
6555 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6556 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6558 if (WIFSIGNALED(status)) {
6559 int sig = WTERMSIG(status);
6560 if (i == fg_pipe->num_cmds-1)
6561 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6562 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6563 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6564 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6565 * Maybe we need to use sig | 128? */
6568 fg_pipe->cmds[i].cmd_exitcode = ex;
6570 fg_pipe->cmds[i].is_stopped = 1;
6571 fg_pipe->stopped_cmds++;
6573 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6574 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6575 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6576 /* All processes in fg pipe have exited or stopped */
6577 i = fg_pipe->num_cmds;
6579 rcode = fg_pipe->cmds[i].cmd_exitcode;
6580 /* usually last process gives overall exitstatus,
6581 * but with "set -o pipefail", last *failed* process does */
6582 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6585 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6586 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6587 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6588 * and "killall -STOP cat" */
6589 if (G_interactive_fd) {
6591 if (fg_pipe->alive_cmds != 0)
6592 insert_bg_job(fg_pipe);
6596 if (fg_pipe->alive_cmds == 0)
6599 /* There are still running processes in the fg pipe */
6600 goto wait_more; /* do waitpid again */
6602 /* it wasnt fg_pipe, look for process in bg pipes */
6606 /* We asked to wait for bg or orphaned children */
6607 /* No need to remember exitcode in this case */
6608 for (pi = G.job_list; pi; pi = pi->next) {
6609 for (i = 0; i < pi->num_cmds; i++) {
6610 if (pi->cmds[i].pid == childpid)
6611 goto found_pi_and_prognum;
6614 /* Happens when shell is used as init process (init=/bin/sh) */
6615 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6616 continue; /* do waitpid again */
6618 found_pi_and_prognum:
6621 pi->cmds[i].pid = 0;
6623 if (!pi->alive_cmds) {
6624 if (G_interactive_fd)
6625 printf(JOB_STATUS_FORMAT, pi->jobid,
6626 "Done", pi->cmdtext);
6627 delete_finished_bg_job(pi);
6631 pi->cmds[i].is_stopped = 1;
6635 } /* while (waitpid succeeds)... */
6641 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6644 int rcode = checkjobs(fg_pipe);
6645 if (G_saved_tty_pgrp) {
6646 /* Job finished, move the shell to the foreground */
6647 p = getpgrp(); /* our process group id */
6648 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6649 tcsetpgrp(G_interactive_fd, p);
6655 /* Start all the jobs, but don't wait for anything to finish.
6658 * Return code is normally -1, when the caller has to wait for children
6659 * to finish to determine the exit status of the pipe. If the pipe
6660 * is a simple builtin command, however, the action is done by the
6661 * time run_pipe returns, and the exit code is provided as the
6664 * Returns -1 only if started some children. IOW: we have to
6665 * mask out retvals of builtins etc with 0xff!
6667 * The only case when we do not need to [v]fork is when the pipe
6668 * is single, non-backgrounded, non-subshell command. Examples:
6669 * cmd ; ... { list } ; ...
6670 * cmd && ... { list } && ...
6671 * cmd || ... { list } || ...
6672 * If it is, then we can run cmd as a builtin, NOFORK,
6673 * or (if SH_STANDALONE) an applet, and we can run the { list }
6674 * with run_list. If it isn't one of these, we fork and exec cmd.
6676 * Cases when we must fork:
6677 * non-single: cmd | cmd
6678 * backgrounded: cmd & { list } &
6679 * subshell: ( list ) [&]
6681 #if !ENABLE_HUSH_MODE_X
6682 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6683 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6685 static int redirect_and_varexp_helper(char ***new_env_p,
6686 struct variable **old_vars_p,
6687 struct command *command,
6689 char **argv_expanded)
6691 /* setup_redirects acts on file descriptors, not FILEs.
6692 * This is perfect for work that comes after exec().
6693 * Is it really safe for inline use? Experimentally,
6694 * things seem to work. */
6695 int rcode = setup_redirects(command, squirrel);
6697 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6698 *new_env_p = new_env;
6699 dump_cmd_in_x_mode(new_env);
6700 dump_cmd_in_x_mode(argv_expanded);
6702 *old_vars_p = set_vars_and_save_old(new_env);
6706 static NOINLINE int run_pipe(struct pipe *pi)
6708 static const char *const null_ptr = NULL;
6712 struct command *command;
6713 char **argv_expanded;
6715 /* it is not always needed, but we aim to smaller code */
6716 int squirrel[] = { -1, -1, -1 };
6719 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6722 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6723 * Result should be 3 lines: q w e, qwe, q w e
6725 G.ifs = get_local_var_value("IFS");
6729 IF_HUSH_JOB(pi->pgrp = -1;)
6730 pi->stopped_cmds = 0;
6731 command = &pi->cmds[0];
6732 argv_expanded = NULL;
6734 if (pi->num_cmds != 1
6735 || pi->followup == PIPE_BG
6736 || command->cmd_type == CMD_SUBSHELL
6743 debug_printf_exec(": group:%p argv:'%s'\n",
6744 command->group, command->argv ? command->argv[0] : "NONE");
6746 if (command->group) {
6747 #if ENABLE_HUSH_FUNCTIONS
6748 if (command->cmd_type == CMD_FUNCDEF) {
6749 /* "executing" func () { list } */
6750 struct function *funcp;
6752 funcp = new_function(command->argv[0]);
6753 /* funcp->name is already set to argv[0] */
6754 funcp->body = command->group;
6756 funcp->body_as_string = command->group_as_string;
6757 command->group_as_string = NULL;
6759 command->group = NULL;
6760 command->argv[0] = NULL;
6761 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6762 funcp->parent_cmd = command;
6763 command->child_func = funcp;
6765 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6767 return EXIT_SUCCESS;
6771 debug_printf("non-subshell group\n");
6772 rcode = 1; /* exitcode if redir failed */
6773 if (setup_redirects(command, squirrel) == 0) {
6774 debug_printf_exec(": run_list\n");
6775 rcode = run_list(command->group) & 0xff;
6777 restore_redirects(squirrel);
6778 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6780 debug_printf_exec("run_pipe: return %d\n", rcode);
6784 argv = command->argv ? command->argv : (char **) &null_ptr;
6786 const struct built_in_command *x;
6787 #if ENABLE_HUSH_FUNCTIONS
6788 const struct function *funcp;
6792 char **new_env = NULL;
6793 struct variable *old_vars = NULL;
6795 if (argv[command->assignment_cnt] == NULL) {
6796 /* Assignments, but no command */
6797 /* Ensure redirects take effect (that is, create files).
6798 * Try "a=t >file" */
6799 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6800 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6801 /* Set shell variables */
6805 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6806 /* Do we need to flag set_local_var() errors?
6807 * "assignment to readonly var" and "putenv error"
6812 /* Redirect error sets $? to 1. Otherwise,
6813 * if evaluating assignment value set $?, retain it.
6814 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6816 rcode = G.last_exitcode;
6817 /* Exit, _skipping_ variable restoring code: */
6818 goto clean_up_and_ret0;
6820 #else /* Older, bigger, but more correct code */
6822 rcode = setup_redirects(command, squirrel);
6823 restore_redirects(squirrel);
6824 /* Set shell variables */
6826 bb_putchar_stderr('+');
6828 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6830 fprintf(stderr, " %s", p);
6831 debug_printf_exec("set shell var:'%s'->'%s'\n",
6833 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6834 /* Do we need to flag set_local_var() errors?
6835 * "assignment to readonly var" and "putenv error"
6840 bb_putchar_stderr('\n');
6841 /* Redirect error sets $? to 1. Otherwise,
6842 * if evaluating assignment value set $?, retain it.
6843 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6845 rcode = G.last_exitcode;
6846 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6848 debug_printf_exec("run_pipe: return %d\n", rcode);
6853 /* Expand the rest into (possibly) many strings each */
6854 #if ENABLE_HUSH_BASH_COMPAT
6855 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6856 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6860 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6863 /* if someone gives us an empty string: `cmd with empty output` */
6864 if (!argv_expanded[0]) {
6865 free(argv_expanded);
6867 return G.last_exitcode;
6870 x = find_builtin(argv_expanded[0]);
6871 #if ENABLE_HUSH_FUNCTIONS
6874 funcp = find_function(argv_expanded[0]);
6878 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6879 debug_printf("exec with redirects only\n");
6880 rcode = setup_redirects(command, NULL);
6881 goto clean_up_and_ret1;
6884 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6887 debug_printf_exec(": builtin '%s' '%s'...\n",
6888 x->b_cmd, argv_expanded[1]);
6890 rcode = x->b_function(argv_expanded) & 0xff;
6893 #if ENABLE_HUSH_FUNCTIONS
6895 # if ENABLE_HUSH_LOCAL
6896 struct variable **sv;
6897 sv = G.shadowed_vars_pp;
6898 G.shadowed_vars_pp = &old_vars;
6900 debug_printf_exec(": function '%s' '%s'...\n",
6901 funcp->name, argv_expanded[1]);
6902 rcode = run_function(funcp, argv_expanded) & 0xff;
6903 # if ENABLE_HUSH_LOCAL
6904 G.shadowed_vars_pp = sv;
6910 unset_vars(new_env);
6912 /* clean_up_and_ret0: */
6913 restore_redirects(squirrel);
6915 free(argv_expanded);
6916 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6918 debug_printf_exec("run_pipe return %d\n", rcode);
6922 if (ENABLE_FEATURE_SH_NOFORK) {
6923 int n = find_applet_by_name(argv_expanded[0]);
6924 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6925 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6927 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6928 argv_expanded[0], argv_expanded[1]);
6929 rcode = run_nofork_applet(n, argv_expanded);
6931 goto clean_up_and_ret;
6934 /* It is neither builtin nor applet. We must fork. */
6938 /* NB: argv_expanded may already be created, and that
6939 * might include `cmd` runs! Do not rerun it! We *must*
6940 * use argv_expanded if it's non-NULL */
6942 /* Going to fork a child per each pipe member */
6947 while (cmd_no < pi->num_cmds) {
6948 struct fd_pair pipefds;
6950 volatile nommu_save_t nommu_save;
6951 nommu_save.new_env = NULL;
6952 nommu_save.old_vars = NULL;
6953 nommu_save.argv = NULL;
6954 nommu_save.argv_from_re_execing = NULL;
6956 command = &pi->cmds[cmd_no];
6958 if (command->argv) {
6959 debug_printf_exec(": pipe member '%s' '%s'...\n",
6960 command->argv[0], command->argv[1]);
6962 debug_printf_exec(": pipe member with no argv\n");
6965 /* pipes are inserted between pairs of commands */
6968 if (cmd_no < pi->num_cmds)
6969 xpiped_pair(pipefds);
6971 command->pid = BB_MMU ? fork() : vfork();
6972 if (!command->pid) { /* child */
6974 disable_restore_tty_pgrp_on_exit();
6975 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6977 /* Every child adds itself to new process group
6978 * with pgid == pid_of_first_child_in_pipe */
6979 if (G.run_list_level == 1 && G_interactive_fd) {
6982 if (pgrp < 0) /* true for 1st process only */
6984 if (setpgid(0, pgrp) == 0
6985 && pi->followup != PIPE_BG
6986 && G_saved_tty_pgrp /* we have ctty */
6988 /* We do it in *every* child, not just first,
6990 tcsetpgrp(G_interactive_fd, pgrp);
6994 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6995 /* 1st cmd in backgrounded pipe
6996 * should have its stdin /dev/null'ed */
6998 if (open(bb_dev_null, O_RDONLY))
6999 xopen("/", O_RDONLY);
7001 xmove_fd(next_infd, 0);
7003 xmove_fd(pipefds.wr, 1);
7006 /* Like bash, explicit redirects override pipes,
7007 * and the pipe fd is available for dup'ing. */
7008 if (setup_redirects(command, NULL))
7011 /* Restore default handlers just prior to exec */
7012 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
7014 /* Stores to nommu_save list of env vars putenv'ed
7015 * (NOMMU, on MMU we don't need that) */
7016 /* cast away volatility... */
7017 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7018 /* pseudo_exec() does not return */
7021 /* parent or error */
7022 #if ENABLE_HUSH_FAST
7024 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7026 enable_restore_tty_pgrp_on_exit();
7028 /* Clean up after vforked child */
7029 free(nommu_save.argv);
7030 free(nommu_save.argv_from_re_execing);
7031 unset_vars(nommu_save.new_env);
7032 add_vars(nommu_save.old_vars);
7034 free(argv_expanded);
7035 argv_expanded = NULL;
7036 if (command->pid < 0) { /* [v]fork failed */
7037 /* Clearly indicate, was it fork or vfork */
7038 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7042 /* Second and next children need to know pid of first one */
7044 pi->pgrp = command->pid;
7050 if (cmd_no < pi->num_cmds)
7052 /* Pass read (output) pipe end to next iteration */
7053 next_infd = pipefds.rd;
7056 if (!pi->alive_cmds) {
7058 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7063 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7067 /* NB: called by pseudo_exec, and therefore must not modify any
7068 * global data until exec/_exit (we can be a child after vfork!) */
7069 static int run_list(struct pipe *pi)
7071 #if ENABLE_HUSH_CASE
7072 char *case_word = NULL;
7074 #if ENABLE_HUSH_LOOPS
7075 struct pipe *loop_top = NULL;
7076 char **for_lcur = NULL;
7077 char **for_list = NULL;
7079 smallint last_followup;
7081 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7082 smalluint cond_code = 0;
7084 enum { cond_code = 0 };
7087 smallint rword; /* RES_foo */
7088 smallint last_rword; /* ditto */
7091 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7094 #if ENABLE_HUSH_LOOPS
7095 /* Check syntax for "for" */
7098 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7099 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7101 /* current word is FOR or IN (BOLD in comments below) */
7102 if (cpipe->next == NULL) {
7103 syntax_error("malformed for");
7105 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7108 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7109 if (cpipe->next->res_word == RES_DO)
7111 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7112 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7113 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7115 syntax_error("malformed for");
7117 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7124 /* Past this point, all code paths should jump to ret: label
7125 * in order to return, no direct "return" statements please.
7126 * This helps to ensure that no memory is leaked. */
7134 last_rword = RES_XXXX;
7136 last_followup = PIPE_SEQ;
7137 rcode = G.last_exitcode;
7139 /* Go through list of pipes, (maybe) executing them. */
7140 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7144 IF_HAS_KEYWORDS(rword = pi->res_word;)
7145 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7146 rword, cond_code, last_rword);
7147 #if ENABLE_HUSH_LOOPS
7148 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7149 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7151 /* start of a loop: remember where loop starts */
7156 /* Still in the same "if...", "then..." or "do..." branch? */
7157 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7158 if ((rcode == 0 && last_followup == PIPE_OR)
7159 || (rcode != 0 && last_followup == PIPE_AND)
7161 /* It is "<true> || CMD" or "<false> && CMD"
7162 * and we should not execute CMD */
7163 debug_printf_exec("skipped cmd because of || or &&\n");
7164 last_followup = pi->followup;
7168 last_followup = pi->followup;
7169 IF_HAS_KEYWORDS(last_rword = rword;)
7172 if (rword == RES_THEN) {
7173 /* if false; then ... fi has exitcode 0! */
7174 G.last_exitcode = rcode = EXIT_SUCCESS;
7175 /* "if <false> THEN cmd": skip cmd */
7179 if (rword == RES_ELSE || rword == RES_ELIF) {
7180 /* "if <true> then ... ELSE/ELIF cmd":
7181 * skip cmd and all following ones */
7186 #if ENABLE_HUSH_LOOPS
7187 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7189 /* first loop through for */
7191 static const char encoded_dollar_at[] ALIGN1 = {
7192 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7193 }; /* encoded representation of "$@" */
7194 static const char *const encoded_dollar_at_argv[] = {
7195 encoded_dollar_at, NULL
7196 }; /* argv list with one element: "$@" */
7199 vals = (char**)encoded_dollar_at_argv;
7200 if (pi->next->res_word == RES_IN) {
7201 /* if no variable values after "in" we skip "for" */
7202 if (!pi->next->cmds[0].argv) {
7203 G.last_exitcode = rcode = EXIT_SUCCESS;
7204 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7207 vals = pi->next->cmds[0].argv;
7208 } /* else: "for var; do..." -> assume "$@" list */
7209 /* create list of variable values */
7210 debug_print_strings("for_list made from", vals);
7211 for_list = expand_strvec_to_strvec(vals);
7212 for_lcur = for_list;
7213 debug_print_strings("for_list", for_list);
7216 /* "for" loop is over, clean up */
7222 /* Insert next value from for_lcur */
7223 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7224 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7227 if (rword == RES_IN) {
7228 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7230 if (rword == RES_DONE) {
7231 continue; /* "done" has no cmds too */
7234 #if ENABLE_HUSH_CASE
7235 if (rword == RES_CASE) {
7236 case_word = expand_strvec_to_string(pi->cmds->argv);
7239 if (rword == RES_MATCH) {
7242 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7244 /* all prev words didn't match, does this one match? */
7245 argv = pi->cmds->argv;
7247 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7248 /* TODO: which FNM_xxx flags to use? */
7249 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7251 if (cond_code == 0) { /* match! we will execute this branch */
7252 free(case_word); /* make future "word)" stop */
7260 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7262 continue; /* not matched yet, skip this pipe */
7265 /* Just pressing <enter> in shell should check for jobs.
7266 * OTOH, in non-interactive shell this is useless
7267 * and only leads to extra job checks */
7268 if (pi->num_cmds == 0) {
7269 if (G_interactive_fd)
7270 goto check_jobs_and_continue;
7274 /* After analyzing all keywords and conditions, we decided
7275 * to execute this pipe. NB: have to do checkjobs(NULL)
7276 * after run_pipe to collect any background children,
7277 * even if list execution is to be stopped. */
7278 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7281 #if ENABLE_HUSH_LOOPS
7282 G.flag_break_continue = 0;
7284 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7286 /* We ran a builtin, function, or group.
7287 * rcode is already known
7288 * and we don't need to wait for anything. */
7289 G.last_exitcode = rcode;
7290 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7291 check_and_run_traps(0);
7292 #if ENABLE_HUSH_LOOPS
7293 /* Was it "break" or "continue"? */
7294 if (G.flag_break_continue) {
7295 smallint fbc = G.flag_break_continue;
7296 /* We might fall into outer *loop*,
7297 * don't want to break it too */
7299 G.depth_break_continue--;
7300 if (G.depth_break_continue == 0)
7301 G.flag_break_continue = 0;
7302 /* else: e.g. "continue 2" should *break* once, *then* continue */
7303 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7304 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7305 goto check_jobs_and_break;
7306 /* "continue": simulate end of loop */
7311 #if ENABLE_HUSH_FUNCTIONS
7312 if (G.flag_return_in_progress == 1) {
7313 /* same as "goto check_jobs_and_break" */
7318 } else if (pi->followup == PIPE_BG) {
7319 /* What does bash do with attempts to background builtins? */
7320 /* even bash 3.2 doesn't do that well with nested bg:
7321 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7322 * I'm NOT treating inner &'s as jobs */
7323 check_and_run_traps(0);
7325 if (G.run_list_level == 1)
7328 /* Last command's pid goes to $! */
7329 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7330 G.last_exitcode = rcode = EXIT_SUCCESS;
7331 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7334 if (G.run_list_level == 1 && G_interactive_fd) {
7335 /* Waits for completion, then fg's main shell */
7336 rcode = checkjobs_and_fg_shell(pi);
7337 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7338 check_and_run_traps(0);
7341 { /* This one just waits for completion */
7342 rcode = checkjobs(pi);
7343 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7344 check_and_run_traps(0);
7346 G.last_exitcode = rcode;
7350 /* Analyze how result affects subsequent commands */
7352 if (rword == RES_IF || rword == RES_ELIF)
7355 #if ENABLE_HUSH_LOOPS
7356 /* Beware of "while false; true; do ..."! */
7357 if (pi->next && pi->next->res_word == RES_DO) {
7358 if (rword == RES_WHILE) {
7360 /* "while false; do...done" - exitcode 0 */
7361 G.last_exitcode = rcode = EXIT_SUCCESS;
7362 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7363 goto check_jobs_and_break;
7366 if (rword == RES_UNTIL) {
7368 debug_printf_exec(": until expr is true: breaking\n");
7369 check_jobs_and_break:
7377 check_jobs_and_continue:
7384 #if ENABLE_HUSH_LOOPS
7389 #if ENABLE_HUSH_CASE
7393 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7397 /* Select which version we will use */
7398 static int run_and_free_list(struct pipe *pi)
7401 debug_printf_exec("run_and_free_list entered\n");
7402 if (!G.o_opt[OPT_O_NOEXEC]) {
7403 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7404 rcode = run_list(pi);
7406 /* free_pipe_list has the side effect of clearing memory.
7407 * In the long run that function can be merged with run_list,
7408 * but doing that now would hobble the debugging effort. */
7410 debug_printf_exec("run_and_free_list return %d\n", rcode);
7415 /* Called a few times only (or even once if "sh -c") */
7416 static void init_sigmasks(void)
7420 sigset_t old_blocked_set;
7422 if (!G.inherited_set_is_saved) {
7423 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7424 G.inherited_set = G.blocked_set;
7426 old_blocked_set = G.blocked_set;
7428 mask = (1 << SIGQUIT);
7429 if (G_interactive_fd) {
7430 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7431 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7432 mask |= SPECIAL_JOB_SIGS;
7434 G.non_DFL_mask = mask;
7439 sigaddset(&G.blocked_set, sig);
7443 sigdelset(&G.blocked_set, SIGCHLD);
7445 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7446 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7448 /* POSIX allows shell to re-enable SIGCHLD
7449 * even if it was SIG_IGN on entry */
7450 #if ENABLE_HUSH_FAST
7451 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7452 if (!G.inherited_set_is_saved)
7453 signal(SIGCHLD, SIGCHLD_handler);
7455 if (!G.inherited_set_is_saved)
7456 signal(SIGCHLD, SIG_DFL);
7459 G.inherited_set_is_saved = 1;
7464 static void maybe_set_to_sigexit(int sig)
7466 void (*handler)(int);
7467 /* non_DFL_mask'ed signals are, well, masked,
7468 * no need to set handler for them.
7470 if (!((G.non_DFL_mask >> sig) & 1)) {
7471 handler = signal(sig, sigexit);
7472 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7473 signal(sig, handler);
7476 /* Set handlers to restore tty pgrp and exit */
7477 static void set_fatal_handlers(void)
7479 /* We _must_ restore tty pgrp on fatal signals */
7481 maybe_set_to_sigexit(SIGILL );
7482 maybe_set_to_sigexit(SIGFPE );
7483 maybe_set_to_sigexit(SIGBUS );
7484 maybe_set_to_sigexit(SIGSEGV);
7485 maybe_set_to_sigexit(SIGTRAP);
7486 } /* else: hush is perfect. what SEGV? */
7487 maybe_set_to_sigexit(SIGABRT);
7488 /* bash 3.2 seems to handle these just like 'fatal' ones */
7489 maybe_set_to_sigexit(SIGPIPE);
7490 maybe_set_to_sigexit(SIGALRM);
7491 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7492 * if we aren't interactive... but in this case
7493 * we never want to restore pgrp on exit, and this fn is not called */
7494 /*maybe_set_to_sigexit(SIGHUP );*/
7495 /*maybe_set_to_sigexit(SIGTERM);*/
7496 /*maybe_set_to_sigexit(SIGINT );*/
7500 static int set_mode(int state, char mode, const char *o_opt)
7505 G.o_opt[OPT_O_NOEXEC] = state;
7508 IF_HUSH_MODE_X(G_x_mode = state;)
7512 /* "set -+o" without parameter.
7513 * in bash, set -o produces this output:
7517 * We always use the second form.
7519 const char *p = o_opt_strings;
7522 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7528 idx = index_in_strings(o_opt_strings, o_opt);
7530 G.o_opt[idx] = state;
7534 return EXIT_FAILURE;
7536 return EXIT_SUCCESS;
7539 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7540 int hush_main(int argc, char **argv)
7543 unsigned builtin_argc;
7545 struct variable *cur_var;
7546 struct variable *shell_ver;
7549 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7550 G.last_exitcode = EXIT_SUCCESS;
7552 G.argv0_for_re_execing = argv[0];
7554 /* Deal with HUSH_VERSION */
7555 shell_ver = xzalloc(sizeof(*shell_ver));
7556 shell_ver->flg_export = 1;
7557 shell_ver->flg_read_only = 1;
7558 /* Code which handles ${var<op>...} needs writable values for all variables,
7559 * therefore we xstrdup: */
7560 shell_ver->varstr = xstrdup(hush_version_str);
7561 /* Create shell local variables from the values
7562 * currently living in the environment */
7563 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7564 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7565 G.top_var = shell_ver;
7566 cur_var = G.top_var;
7569 char *value = strchr(*e, '=');
7570 if (value) { /* paranoia */
7571 cur_var->next = xzalloc(sizeof(*cur_var));
7572 cur_var = cur_var->next;
7573 cur_var->varstr = *e;
7574 cur_var->max_len = strlen(*e);
7575 cur_var->flg_export = 1;
7579 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7580 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7581 putenv(shell_ver->varstr);
7584 set_pwd_var(/*exp:*/ 1);
7585 /* bash also exports SHLVL and _,
7586 * and sets (but doesn't export) the following variables:
7588 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7589 * BASH_VERSION='3.2.0(1)-release'
7591 * MACHTYPE=i386-pc-linux-gnu
7593 * HOSTNAME=<xxxxxxxxxx>
7594 * PPID=<NNNNN> - we also do it elsewhere
7605 * PIPESTATUS=([0]="0")
7606 * HISTFILE=/<xxx>/.bash_history
7610 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7612 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7622 #if ENABLE_FEATURE_EDITING
7623 G.line_input_state = new_line_input_t(FOR_SHELL);
7624 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7626 const char *hp = get_local_var_value("HISTFILE");
7628 hp = get_local_var_value("HOME");
7630 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7631 //set_local_var(xasprintf("HISTFILE=%s", ...));
7634 # if ENABLE_FEATURE_SH_HISTFILESIZE
7635 hp = get_local_var_value("HISTFILESIZE");
7636 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7642 G.global_argc = argc;
7643 G.global_argv = argv;
7644 /* Initialize some more globals to non-zero values */
7645 cmdedit_update_prompt();
7647 if (setjmp(die_jmp)) {
7648 /* xfunc has failed! die die die */
7649 /* no EXIT traps, this is an escape hatch! */
7651 hush_exit(xfunc_error_retval);
7654 /* Shell is non-interactive at first. We need to call
7655 * init_sigmasks() if we are going to execute "sh <script>",
7656 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7657 * If we later decide that we are interactive, we run init_sigmasks()
7658 * in order to intercept (more) signals.
7662 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7665 opt = getopt(argc, argv, "+c:xins"
7668 # if ENABLE_HUSH_FUNCTIONS
7678 * sh ... -c 'script'
7679 * sh ... -c 'script' ARG0 [ARG1...]
7680 * On NOMMU, if builtin_argc != 0,
7681 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7682 * "" needs to be replaced with NULL
7683 * and BARGV vector fed to builtin function.
7684 * Note: the form without ARG0 never happens:
7685 * sh ... -c 'builtin' BARGV... ""
7688 G.root_pid = getpid();
7689 G.root_ppid = getppid();
7691 G.global_argv = argv + optind;
7692 G.global_argc = argc - optind;
7694 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7695 const struct built_in_command *x;
7698 x = find_builtin(optarg);
7699 if (x) { /* paranoia */
7700 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7701 G.global_argv += builtin_argc;
7702 G.global_argv[-1] = NULL; /* replace "" */
7704 G.last_exitcode = x->b_function(argv + optind - 1);
7708 if (!G.global_argv[0]) {
7709 /* -c 'script' (no params): prevent empty $0 */
7710 G.global_argv--; /* points to argv[i] of 'script' */
7711 G.global_argv[0] = argv[0];
7713 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7715 parse_and_run_string(optarg);
7718 /* Well, we cannot just declare interactiveness,
7719 * we have to have some stuff (ctty, etc) */
7720 /* G_interactive_fd++; */
7723 /* "-s" means "read from stdin", but this is how we always
7724 * operate, so simply do nothing here. */
7727 case '<': /* "big heredoc" support */
7728 full_write1_str(optarg);
7731 unsigned long long empty_trap_mask;
7733 G.root_pid = bb_strtou(optarg, &optarg, 16);
7735 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7737 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7739 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7741 builtin_argc = bb_strtou(optarg, &optarg, 16);
7743 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7744 if (empty_trap_mask != 0) {
7747 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7748 for (sig = 1; sig < NSIG; sig++) {
7749 if (empty_trap_mask & (1LL << sig)) {
7750 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7751 sigaddset(&G.blocked_set, sig);
7754 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7756 # if ENABLE_HUSH_LOOPS
7758 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7764 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7766 # if ENABLE_HUSH_FUNCTIONS
7768 struct function *funcp = new_function(optarg);
7769 /* funcp->name is already set to optarg */
7770 /* funcp->body is set to NULL. It's a special case. */
7771 funcp->body_as_string = argv[optind];
7779 if (set_mode(1, opt, NULL) == 0) /* no error */
7783 fprintf(stderr, "Usage: sh [FILE]...\n"
7784 " or: sh -c command [args]...\n\n");
7790 } /* option parsing loop */
7793 G.root_pid = getpid();
7794 G.root_ppid = getppid();
7797 /* If we are login shell... */
7798 if (argv[0] && argv[0][0] == '-') {
7800 debug_printf("sourcing /etc/profile\n");
7801 input = fopen_for_read("/etc/profile");
7802 if (input != NULL) {
7803 close_on_exec_on(fileno(input));
7805 parse_and_run_file(input);
7808 /* bash: after sourcing /etc/profile,
7809 * tries to source (in the given order):
7810 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7811 * stopping on first found. --noprofile turns this off.
7812 * bash also sources ~/.bash_logout on exit.
7813 * If called as sh, skips .bash_XXX files.
7820 * "bash <script>" (which is never interactive (unless -i?))
7821 * sources $BASH_ENV here (without scanning $PATH).
7822 * If called as sh, does the same but with $ENV.
7824 debug_printf("running script '%s'\n", argv[optind]);
7825 G.global_argv = argv + optind;
7826 G.global_argc = argc - optind;
7827 input = xfopen_for_read(argv[optind]);
7828 close_on_exec_on(fileno(input));
7830 parse_and_run_file(input);
7831 #if ENABLE_FEATURE_CLEAN_UP
7837 /* Up to here, shell was non-interactive. Now it may become one.
7838 * NB: don't forget to (re)run init_sigmasks() as needed.
7841 /* A shell is interactive if the '-i' flag was given,
7842 * or if all of the following conditions are met:
7844 * no arguments remaining or the -s flag given
7845 * standard input is a terminal
7846 * standard output is a terminal
7847 * Refer to Posix.2, the description of the 'sh' utility.
7850 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7851 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7852 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7853 if (G_saved_tty_pgrp < 0)
7854 G_saved_tty_pgrp = 0;
7856 /* try to dup stdin to high fd#, >= 255 */
7857 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7858 if (G_interactive_fd < 0) {
7859 /* try to dup to any fd */
7860 G_interactive_fd = dup(STDIN_FILENO);
7861 if (G_interactive_fd < 0) {
7863 G_interactive_fd = 0;
7864 G_saved_tty_pgrp = 0;
7867 // TODO: track & disallow any attempts of user
7868 // to (inadvertently) close/redirect G_interactive_fd
7870 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7871 if (G_interactive_fd) {
7872 close_on_exec_on(G_interactive_fd);
7874 if (G_saved_tty_pgrp) {
7875 /* If we were run as 'hush &', sleep until we are
7876 * in the foreground (tty pgrp == our pgrp).
7877 * If we get started under a job aware app (like bash),
7878 * make sure we are now in charge so we don't fight over
7879 * who gets the foreground */
7881 pid_t shell_pgrp = getpgrp();
7882 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7883 if (G_saved_tty_pgrp == shell_pgrp)
7885 /* send TTIN to ourself (should stop us) */
7886 kill(- shell_pgrp, SIGTTIN);
7890 /* Block some signals */
7893 if (G_saved_tty_pgrp) {
7894 /* Set other signals to restore saved_tty_pgrp */
7895 set_fatal_handlers();
7896 /* Put ourselves in our own process group
7897 * (bash, too, does this only if ctty is available) */
7898 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7899 /* Grab control of the terminal */
7900 tcsetpgrp(G_interactive_fd, getpid());
7902 /* -1 is special - makes xfuncs longjmp, not exit
7903 * (we reset die_sleep = 0 whereever we [v]fork) */
7904 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7908 #elif ENABLE_HUSH_INTERACTIVE
7909 /* No job control compiled in, only prompt/line editing */
7910 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7911 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7912 if (G_interactive_fd < 0) {
7913 /* try to dup to any fd */
7914 G_interactive_fd = dup(STDIN_FILENO);
7915 if (G_interactive_fd < 0)
7917 G_interactive_fd = 0;
7920 if (G_interactive_fd) {
7921 close_on_exec_on(G_interactive_fd);
7925 /* We have interactiveness code disabled */
7929 * if interactive but not a login shell, sources ~/.bashrc
7930 * (--norc turns this off, --rcfile <file> overrides)
7933 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7934 /* note: ash and hush share this string */
7935 printf("\n\n%s %s\n"
7936 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7939 "hush - the humble shell"
7943 parse_and_run_file(stdin);
7946 hush_exit(G.last_exitcode);
7951 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7952 int msh_main(int argc, char **argv)
7954 //bb_error_msg("msh is deprecated, please use hush instead");
7955 return hush_main(argc, argv);
7963 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7968 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7975 return applet_main_func(argc, argv - argc);
7978 static int FAST_FUNC builtin_test(char **argv)
7980 return run_applet_main(argv, test_main);
7983 static int FAST_FUNC builtin_echo(char **argv)
7985 return run_applet_main(argv, echo_main);
7989 static int FAST_FUNC builtin_printf(char **argv)
7991 return run_applet_main(argv, printf_main);
7995 static char **skip_dash_dash(char **argv)
7998 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8003 static int FAST_FUNC builtin_eval(char **argv)
8005 int rcode = EXIT_SUCCESS;
8007 argv = skip_dash_dash(argv);
8009 char *str = expand_strvec_to_string(argv);
8011 * eval "echo Hi; done" ("done" is syntax error):
8012 * "echo Hi" will not execute too.
8014 parse_and_run_string(str);
8016 rcode = G.last_exitcode;
8021 static int FAST_FUNC builtin_cd(char **argv)
8025 argv = skip_dash_dash(argv);
8027 if (newdir == NULL) {
8028 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8029 * bash says "bash: cd: HOME not set" and does nothing
8032 const char *home = get_local_var_value("HOME");
8033 newdir = home ? home : "/";
8035 if (chdir(newdir)) {
8036 /* Mimic bash message exactly */
8037 bb_perror_msg("cd: %s", newdir);
8038 return EXIT_FAILURE;
8040 /* Read current dir (get_cwd(1) is inside) and set PWD.
8041 * Note: do not enforce exporting. If PWD was unset or unexported,
8042 * set it again, but do not export. bash does the same.
8044 set_pwd_var(/*exp:*/ 0);
8045 return EXIT_SUCCESS;
8048 static int FAST_FUNC builtin_exec(char **argv)
8050 argv = skip_dash_dash(argv);
8051 if (argv[0] == NULL)
8052 return EXIT_SUCCESS; /* bash does this */
8054 /* Careful: we can end up here after [v]fork. Do not restore
8055 * tty pgrp then, only top-level shell process does that */
8056 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8057 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8059 /* TODO: if exec fails, bash does NOT exit! We do.
8060 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8061 * and tcsetpgrp, and this is inherently racy.
8063 execvp_or_die(argv);
8066 static int FAST_FUNC builtin_exit(char **argv)
8068 debug_printf_exec("%s()\n", __func__);
8070 /* interactive bash:
8071 * # trap "echo EEE" EXIT
8074 * There are stopped jobs.
8075 * (if there are _stopped_ jobs, running ones don't count)
8078 # EEE (then bash exits)
8080 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8083 /* note: EXIT trap is run by hush_exit */
8084 argv = skip_dash_dash(argv);
8085 if (argv[0] == NULL)
8086 hush_exit(G.last_exitcode);
8087 /* mimic bash: exit 123abc == exit 255 + error msg */
8088 xfunc_error_retval = 255;
8089 /* bash: exit -2 == exit 254, no error msg */
8090 hush_exit(xatoi(argv[0]) & 0xff);
8093 static void print_escaped(const char *s)
8098 const char *p = strchrnul(s, '\'');
8099 /* print 'xxxx', possibly just '' */
8100 printf("'%.*s'", (int)(p - s), s);
8105 /* s points to '; print "'''...'''" */
8107 do putchar('\''); while (*++s == '\'');
8112 #if !ENABLE_HUSH_LOCAL
8113 #define helper_export_local(argv, exp, lvl) \
8114 helper_export_local(argv, exp)
8116 static void helper_export_local(char **argv, int exp, int lvl)
8120 char *name_end = strchrnul(name, '=');
8122 /* So far we do not check that name is valid (TODO?) */
8124 if (*name_end == '\0') {
8125 struct variable *var, **vpp;
8127 vpp = get_ptr_to_local_var(name, name_end - name);
8128 var = vpp ? *vpp : NULL;
8130 if (exp == -1) { /* unexporting? */
8131 /* export -n NAME (without =VALUE) */
8133 var->flg_export = 0;
8134 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8136 } /* else: export -n NOT_EXISTING_VAR: no-op */
8139 if (exp == 1) { /* exporting? */
8140 /* export NAME (without =VALUE) */
8142 var->flg_export = 1;
8143 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8144 putenv(var->varstr);
8148 /* Exporting non-existing variable.
8149 * bash does not put it in environment,
8150 * but remembers that it is exported,
8151 * and does put it in env when it is set later.
8152 * We just set it to "" and export. */
8153 /* Or, it's "local NAME" (without =VALUE).
8154 * bash sets the value to "". */
8155 name = xasprintf("%s=", name);
8157 /* (Un)exporting/making local NAME=VALUE */
8158 name = xstrdup(name);
8160 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8164 static int FAST_FUNC builtin_export(char **argv)
8166 unsigned opt_unexport;
8168 #if ENABLE_HUSH_EXPORT_N
8169 /* "!": do not abort on errors */
8170 opt_unexport = getopt32(argv, "!n");
8171 if (opt_unexport == (uint32_t)-1)
8172 return EXIT_FAILURE;
8179 if (argv[0] == NULL) {
8186 /* ash emits: export VAR='VAL'
8187 * bash: declare -x VAR="VAL"
8188 * we follow ash example */
8189 const char *s = *e++;
8190 const char *p = strchr(s, '=');
8192 if (!p) /* wtf? take next variable */
8195 printf("export %.*s", (int)(p - s) + 1, s);
8196 print_escaped(p + 1);
8200 /*fflush_all(); - done after each builtin anyway */
8202 return EXIT_SUCCESS;
8205 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8207 return EXIT_SUCCESS;
8210 #if ENABLE_HUSH_LOCAL
8211 static int FAST_FUNC builtin_local(char **argv)
8213 if (G.func_nest_level == 0) {
8214 bb_error_msg("%s: not in a function", argv[0]);
8215 return EXIT_FAILURE; /* bash compat */
8217 helper_export_local(argv, 0, G.func_nest_level);
8218 return EXIT_SUCCESS;
8222 static int FAST_FUNC builtin_trap(char **argv)
8228 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8233 /* No args: print all trapped */
8234 for (i = 0; i < NSIG; ++i) {
8237 print_escaped(G.traps[i]);
8238 /* note: bash adds "SIG", but only if invoked
8239 * as "bash". If called as "sh", or if set -o posix,
8240 * then it prints short signal names.
8241 * We are printing short names: */
8242 printf(" %s\n", get_signame(i));
8245 /*fflush_all(); - done after each builtin anyway */
8246 return EXIT_SUCCESS;
8250 /* If first arg is a number: reset all specified signals */
8251 sig = bb_strtou(*argv, NULL, 10);
8257 sig = get_signum(*argv++);
8258 if (sig < 0 || sig >= NSIG) {
8260 /* Mimic bash message exactly */
8261 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8266 G.traps[sig] = xstrdup(new_cmd);
8268 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8269 get_signame(sig), sig, G.traps[sig]);
8271 /* There is no signal for 0 (EXIT) */
8276 sigaddset(&G.blocked_set, sig);
8278 /* There was a trap handler, we are removing it
8279 * (if sig has non-DFL handling,
8280 * we don't need to do anything) */
8281 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8283 sigdelset(&G.blocked_set, sig);
8286 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8290 if (!argv[1]) { /* no second arg */
8291 bb_error_msg("trap: invalid arguments");
8292 return EXIT_FAILURE;
8295 /* First arg is "-": reset all specified to default */
8296 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8297 /* Everything else: set arg as signal handler
8298 * (includes "" case, which ignores signal) */
8299 if (argv[0][0] == '-') {
8300 if (argv[0][1] == '\0') { /* "-" */
8301 /* new_cmd remains NULL: "reset these sigs" */
8304 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8307 /* else: "-something", no special meaning */
8312 goto process_sig_list;
8315 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8316 static int FAST_FUNC builtin_type(char **argv)
8318 int ret = EXIT_SUCCESS;
8324 if (0) {} /* make conditional compile easier below */
8325 /*else if (find_alias(*argv))
8326 type = "an alias";*/
8327 #if ENABLE_HUSH_FUNCTIONS
8328 else if (find_function(*argv))
8329 type = "a function";
8331 else if (find_builtin(*argv))
8332 type = "a shell builtin";
8333 else if ((path = find_in_path(*argv)) != NULL)
8336 bb_error_msg("type: %s: not found", *argv);
8341 printf("%s is %s\n", *argv, type);
8349 /* built-in 'fg' and 'bg' handler */
8350 static int FAST_FUNC builtin_fg_bg(char **argv)
8355 if (!G_interactive_fd)
8356 return EXIT_FAILURE;
8358 /* If they gave us no args, assume they want the last backgrounded task */
8360 for (pi = G.job_list; pi; pi = pi->next) {
8361 if (pi->jobid == G.last_jobid) {
8365 bb_error_msg("%s: no current job", argv[0]);
8366 return EXIT_FAILURE;
8368 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8369 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8370 return EXIT_FAILURE;
8372 for (pi = G.job_list; pi; pi = pi->next) {
8373 if (pi->jobid == jobnum) {
8377 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8378 return EXIT_FAILURE;
8380 /* TODO: bash prints a string representation
8381 * of job being foregrounded (like "sleep 1 | cat") */
8382 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8383 /* Put the job into the foreground. */
8384 tcsetpgrp(G_interactive_fd, pi->pgrp);
8387 /* Restart the processes in the job */
8388 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8389 for (i = 0; i < pi->num_cmds; i++) {
8390 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8391 pi->cmds[i].is_stopped = 0;
8393 pi->stopped_cmds = 0;
8395 i = kill(- pi->pgrp, SIGCONT);
8397 if (errno == ESRCH) {
8398 delete_finished_bg_job(pi);
8399 return EXIT_SUCCESS;
8401 bb_perror_msg("kill (SIGCONT)");
8404 if (argv[0][0] == 'f') {
8406 return checkjobs_and_fg_shell(pi);
8408 return EXIT_SUCCESS;
8412 #if ENABLE_HUSH_HELP
8413 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8415 const struct built_in_command *x;
8418 "Built-in commands:\n"
8419 "------------------\n");
8420 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8422 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8425 return EXIT_SUCCESS;
8430 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8433 const char *status_string;
8435 for (job = G.job_list; job; job = job->next) {
8436 if (job->alive_cmds == job->stopped_cmds)
8437 status_string = "Stopped";
8439 status_string = "Running";
8441 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8443 return EXIT_SUCCESS;
8448 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8453 # ifdef M_TRIM_THRESHOLD
8454 /* Optional. Reduces probability of false positives */
8457 /* Crude attempt to find where "free memory" starts,
8458 * sans fragmentation. */
8460 l = (unsigned long)p;
8463 if (l < (unsigned long)p) l = (unsigned long)p;
8466 if (!G.memleak_value)
8467 G.memleak_value = l;
8469 l -= G.memleak_value;
8476 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8481 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8484 return EXIT_SUCCESS;
8487 static int FAST_FUNC builtin_read(char **argv)
8496 /* "!": do not abort on errors.
8497 * Option string must start with "sr" to match BUILTIN_READ_xxx
8499 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8500 if (read_flags == (uint32_t)-1)
8501 return EXIT_FAILURE;
8504 r = shell_builtin_read(set_local_var_from_halves,
8506 get_local_var_value("IFS"), /* can be NULL */
8514 if ((uintptr_t)r > 1) {
8515 bb_error_msg("%s", r);
8516 r = (char*)(uintptr_t)1;
8519 return (uintptr_t)r;
8522 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8523 * built-in 'set' handler
8525 * set [-abCefhmnuvx] [-o option] [argument...]
8526 * set [+abCefhmnuvx] [+o option] [argument...]
8527 * set -- [argument...]
8530 * Implementations shall support the options in both their hyphen and
8531 * plus-sign forms. These options can also be specified as options to sh.
8533 * Write out all variables and their values: set
8534 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8535 * Turn on the -x and -v options: set -xv
8536 * Unset all positional parameters: set --
8537 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8538 * Set the positional parameters to the expansion of x, even if x expands
8539 * with a leading '-' or '+': set -- $x
8541 * So far, we only support "set -- [argument...]" and some of the short names.
8543 static int FAST_FUNC builtin_set(char **argv)
8546 char **pp, **g_argv;
8547 char *arg = *++argv;
8551 for (e = G.top_var; e; e = e->next)
8553 return EXIT_SUCCESS;
8557 if (strcmp(arg, "--") == 0) {
8561 if (arg[0] != '+' && arg[0] != '-')
8563 for (n = 1; arg[n]; ++n) {
8564 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8566 if (arg[n] == 'o' && argv[1])
8569 } while ((arg = *++argv) != NULL);
8570 /* Now argv[0] is 1st argument */
8573 return EXIT_SUCCESS;
8576 /* NB: G.global_argv[0] ($0) is never freed/changed */
8577 g_argv = G.global_argv;
8578 if (G.global_args_malloced) {
8584 G.global_args_malloced = 1;
8585 pp = xzalloc(sizeof(pp[0]) * 2);
8586 pp[0] = g_argv[0]; /* retain $0 */
8589 /* This realloc's G.global_argv */
8590 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8597 return EXIT_SUCCESS;
8599 /* Nothing known, so abort */
8601 bb_error_msg("set: %s: invalid option", arg);
8602 return EXIT_FAILURE;
8605 static int FAST_FUNC builtin_shift(char **argv)
8608 argv = skip_dash_dash(argv);
8612 if (n >= 0 && n < G.global_argc) {
8613 if (G.global_args_malloced) {
8616 free(G.global_argv[m++]);
8619 memmove(&G.global_argv[1], &G.global_argv[n+1],
8620 G.global_argc * sizeof(G.global_argv[0]));
8621 return EXIT_SUCCESS;
8623 return EXIT_FAILURE;
8626 static int FAST_FUNC builtin_source(char **argv)
8628 char *arg_path, *filename;
8631 #if ENABLE_HUSH_FUNCTIONS
8635 argv = skip_dash_dash(argv);
8638 /* bash says: "bash: .: filename argument required" */
8639 return 2; /* bash compat */
8642 if (!strchr(filename, '/')) {
8643 arg_path = find_in_path(filename);
8645 filename = arg_path;
8647 input = fopen_or_warn(filename, "r");
8650 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8651 return EXIT_FAILURE;
8653 close_on_exec_on(fileno(input));
8655 #if ENABLE_HUSH_FUNCTIONS
8656 sv_flg = G.flag_return_in_progress;
8657 /* "we are inside sourced file, ok to use return" */
8658 G.flag_return_in_progress = -1;
8660 save_and_replace_G_args(&sv, argv);
8662 parse_and_run_file(input);
8665 restore_G_args(&sv, argv);
8666 #if ENABLE_HUSH_FUNCTIONS
8667 G.flag_return_in_progress = sv_flg;
8670 return G.last_exitcode;
8673 static int FAST_FUNC builtin_umask(char **argv)
8679 argv = skip_dash_dash(argv);
8681 mode_t old_mask = mask;
8684 rc = bb_parse_mode(argv[0], &mask);
8689 * bash: umask: 'q': invalid symbolic mode operator
8690 * bash: umask: 999: octal number out of range
8692 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8697 printf("%04o\n", (unsigned) mask);
8698 /* fall through and restore mask which we set to 0 */
8702 return !rc; /* rc != 0 - success */
8705 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8706 static int FAST_FUNC builtin_unset(char **argv)
8711 /* "!": do not abort on errors */
8712 /* "+": stop at 1st non-option */
8713 opts = getopt32(argv, "!+vf");
8714 if (opts == (unsigned)-1)
8715 return EXIT_FAILURE;
8717 bb_error_msg("unset: -v and -f are exclusive");
8718 return EXIT_FAILURE;
8724 if (!(opts & 2)) { /* not -f */
8725 if (unset_local_var(*argv)) {
8726 /* unset <nonexistent_var> doesn't fail.
8727 * Error is when one tries to unset RO var.
8728 * Message was printed by unset_local_var. */
8732 #if ENABLE_HUSH_FUNCTIONS
8742 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8743 static int FAST_FUNC builtin_wait(char **argv)
8745 int ret = EXIT_SUCCESS;
8748 argv = skip_dash_dash(argv);
8749 if (argv[0] == NULL) {
8750 /* Don't care about wait results */
8751 /* Note 1: must wait until there are no more children */
8752 /* Note 2: must be interruptible */
8754 * $ sleep 3 & sleep 6 & wait
8759 * $ sleep 3 & sleep 6 & wait
8763 * ^C <-- after ~4 sec from keyboard
8766 sigaddset(&G.blocked_set, SIGCHLD);
8767 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8770 if (errno == ECHILD)
8772 /* Wait for SIGCHLD or any other signal of interest */
8773 /* sigtimedwait with infinite timeout: */
8774 sig = sigwaitinfo(&G.blocked_set, NULL);
8776 sig = check_and_run_traps(sig);
8777 if (sig && sig != SIGCHLD) { /* see note 2 */
8783 sigdelset(&G.blocked_set, SIGCHLD);
8784 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8788 /* This is probably buggy wrt interruptible-ness */
8790 pid_t pid = bb_strtou(*argv, NULL, 10);
8792 /* mimic bash message */
8793 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8794 return EXIT_FAILURE;
8796 if (waitpid(pid, &status, 0) == pid) {
8797 if (WIFSIGNALED(status))
8798 ret = 128 + WTERMSIG(status);
8799 else if (WIFEXITED(status))
8800 ret = WEXITSTATUS(status);
8804 bb_perror_msg("wait %s", *argv);
8813 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8814 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8817 def = bb_strtou(argv[1], NULL, 10);
8818 if (errno || def < def_min || argv[2]) {
8819 bb_error_msg("%s: bad arguments", argv[0]);
8827 #if ENABLE_HUSH_LOOPS
8828 static int FAST_FUNC builtin_break(char **argv)
8831 if (G.depth_of_loop == 0) {
8832 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8833 return EXIT_SUCCESS; /* bash compat */
8835 G.flag_break_continue++; /* BC_BREAK = 1 */
8837 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8838 if (depth == UINT_MAX)
8839 G.flag_break_continue = BC_BREAK;
8840 if (G.depth_of_loop < depth)
8841 G.depth_break_continue = G.depth_of_loop;
8843 return EXIT_SUCCESS;
8846 static int FAST_FUNC builtin_continue(char **argv)
8848 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8849 return builtin_break(argv);
8853 #if ENABLE_HUSH_FUNCTIONS
8854 static int FAST_FUNC builtin_return(char **argv)
8858 if (G.flag_return_in_progress != -1) {
8859 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8860 return EXIT_FAILURE; /* bash compat */
8863 G.flag_return_in_progress = 1;
8866 * out of range: wraps around at 256, does not error out
8867 * non-numeric param:
8868 * f() { false; return qwe; }; f; echo $?
8869 * bash: return: qwe: numeric argument required <== we do this
8870 * 255 <== we also do this
8872 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);