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 /* I can almost use ordinary FILE*. Is open_memstream() universally
449 * available? Where is it documented? */
450 typedef struct in_str {
452 /* eof_flag=1: last char in ->p is really an EOF */
453 char eof_flag; /* meaningless if ->p == NULL */
455 #if ENABLE_HUSH_INTERACTIVE
456 smallint promptmode; /* 0: PS1, 1: PS2 */
459 int (*get) (struct in_str *) FAST_FUNC;
460 int (*peek) (struct in_str *) FAST_FUNC;
462 #define i_getch(input) ((input)->get(input))
463 #define i_peek(input) ((input)->peek(input))
465 /* The descrip member of this structure is only used to make
466 * debugging output pretty */
467 static const struct {
469 signed char default_fd;
472 { O_RDONLY, 0, "<" },
473 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
474 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
475 { O_CREAT|O_RDWR, 1, "<>" },
476 { O_RDONLY, 0, "<<" },
477 /* Should not be needed. Bogus default_fd helps in debugging */
478 /* { O_RDONLY, 77, "<<" }, */
481 struct redir_struct {
482 struct redir_struct *next;
483 char *rd_filename; /* filename */
484 int rd_fd; /* fd to redirect */
485 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
487 smallint rd_type; /* (enum redir_type) */
488 /* note: for heredocs, rd_filename contains heredoc delimiter,
489 * and subsequently heredoc itself; and rd_dup is a bitmask:
490 * bit 0: do we need to trim leading tabs?
491 * bit 1: is heredoc quoted (<<'delim' syntax) ?
494 typedef enum redir_type {
496 REDIRECT_OVERWRITE = 1,
499 REDIRECT_HEREDOC = 4,
500 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
503 REDIRFD_SYNTAX_ERR = -2,
504 REDIRFD_TO_FILE = -1,
505 /* otherwise, rd_fd is redirected to rd_dup */
507 HEREDOC_SKIPTABS = 1,
513 pid_t pid; /* 0 if exited */
514 int assignment_cnt; /* how many argv[i] are assignments? */
515 smallint is_stopped; /* is the command currently running? */
516 smallint cmd_type; /* CMD_xxx */
518 #define CMD_SUBSHELL 1
519 #if ENABLE_HUSH_BASH_COMPAT
520 /* used for "[[ EXPR ]]" */
521 # define CMD_SINGLEWORD_NOGLOB 2
523 #if ENABLE_HUSH_FUNCTIONS
524 # define CMD_FUNCDEF 3
527 smalluint cmd_exitcode;
528 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
531 char *group_as_string;
533 #if ENABLE_HUSH_FUNCTIONS
534 struct function *child_func;
535 /* This field is used to prevent a bug here:
536 * while...do f1() {a;}; f1; f1() {b;}; f1; done
537 * When we execute "f1() {a;}" cmd, we create new function and clear
538 * cmd->group, cmd->group_as_string, cmd->argv[0].
539 * When we execute "f1() {b;}", we notice that f1 exists,
540 * and that its "parent cmd" struct is still "alive",
541 * we put those fields back into cmd->xxx
542 * (struct function has ->parent_cmd ptr to facilitate that).
543 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
544 * Without this trick, loop would execute a;b;b;b;...
545 * instead of correct sequence a;b;a;b;...
546 * When command is freed, it severs the link
547 * (sets ->child_func->parent_cmd to NULL).
550 char **argv; /* command name and arguments */
551 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
552 * and on execution these are substituted with their values.
553 * Substitution can make _several_ words out of one argv[n]!
554 * Example: argv[0]=='.^C*^C.' here: echo .$*.
555 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
557 struct redir_struct *redirects; /* I/O redirections */
559 /* Is there anything in this command at all? */
560 #define IS_NULL_CMD(cmd) \
561 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
565 int num_cmds; /* total number of commands in pipe */
566 int alive_cmds; /* number of commands running (not exited) */
567 int stopped_cmds; /* number of commands alive, but stopped */
569 int jobid; /* job number */
570 pid_t pgrp; /* process group ID for the job */
571 char *cmdtext; /* name of job */
573 struct command *cmds; /* array of commands in pipe */
574 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
575 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
576 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
578 typedef enum pipe_style {
584 /* Is there anything in this pipe at all? */
585 #define IS_NULL_PIPE(pi) \
586 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
588 /* This holds pointers to the various results of parsing */
589 struct parse_context {
590 /* linked list of pipes */
591 struct pipe *list_head;
592 /* last pipe (being constructed right now) */
594 /* last command in pipe (being constructed right now) */
595 struct command *command;
596 /* last redirect in command->redirects list */
597 struct redir_struct *pending_redirect;
603 smallint ctx_inverted; /* "! cmd | cmd" */
605 smallint ctx_dsemicolon; /* ";;" seen */
607 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
609 /* group we are enclosed in:
610 * example: "if pipe1; pipe2; then pipe3; fi"
611 * when we see "if" or "then", we malloc and copy current context,
612 * and make ->stack point to it. then we parse pipeN.
613 * when closing "then" / fi" / whatever is found,
614 * we move list_head into ->stack->command->group,
615 * copy ->stack into current context, and delete ->stack.
616 * (parsing of { list } and ( list ) doesn't use this method)
618 struct parse_context *stack;
622 /* On program start, environ points to initial environment.
623 * putenv adds new pointers into it, unsetenv removes them.
624 * Neither of these (de)allocates the strings.
625 * setenv allocates new strings in malloc space and does putenv,
626 * and thus setenv is unusable (leaky) for shell's purposes */
627 #define setenv(...) setenv_is_leaky_dont_use()
629 struct variable *next;
630 char *varstr; /* points to "name=" portion */
631 #if ENABLE_HUSH_LOCAL
632 unsigned func_nest_level;
634 int max_len; /* if > 0, name is part of initial env; else name is malloced */
635 smallint flg_export; /* putenv should be done on this var */
636 smallint flg_read_only;
644 #if ENABLE_HUSH_FUNCTIONS
646 struct function *next;
648 struct command *parent_cmd;
651 char *body_as_string;
657 /* set -/+o OPT support. (TODO: make it optional)
658 * bash supports the following opts:
669 * interactive-comments on
687 static const char o_opt_strings[] ALIGN1 =
690 #if ENABLE_HUSH_MODE_X
697 #if ENABLE_HUSH_MODE_X
704 /* "Globals" within this file */
705 /* Sorted roughly by size (smaller offsets == smaller code) */
707 /* interactive_fd != 0 means we are an interactive shell.
708 * If we are, then saved_tty_pgrp can also be != 0, meaning
709 * that controlling tty is available. With saved_tty_pgrp == 0,
710 * job control still works, but terminal signals
711 * (^C, ^Z, ^Y, ^\) won't work at all, and background
712 * process groups can only be created with "cmd &".
713 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
714 * to give tty to the foreground process group,
715 * and will take it back when the group is stopped (^Z)
718 #if ENABLE_HUSH_INTERACTIVE
719 /* 'interactive_fd' is a fd# open to ctty, if we have one
720 * _AND_ if we decided to act interactively */
724 # define G_interactive_fd (G.interactive_fd)
726 # define G_interactive_fd 0
728 #if ENABLE_FEATURE_EDITING
729 line_input_t *line_input_state;
734 #if ENABLE_HUSH_RANDOM_SUPPORT
740 pid_t saved_tty_pgrp;
741 struct pipe *job_list;
742 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
744 # define G_saved_tty_pgrp 0
746 char o_opt[NUM_OPT_O];
747 #if ENABLE_HUSH_MODE_X
748 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
752 smallint flag_SIGINT;
753 #if ENABLE_HUSH_LOOPS
754 smallint flag_break_continue;
756 #if ENABLE_HUSH_FUNCTIONS
757 /* 0: outside of a function (or sourced file)
758 * -1: inside of a function, ok to use return builtin
759 * 1: return is invoked, skip all till end of func
761 smallint flag_return_in_progress;
763 smallint exiting; /* used to prevent EXIT trap recursion */
764 /* These four support $?, $#, and $1 */
765 smalluint last_exitcode;
766 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
767 smalluint global_args_malloced;
768 smalluint inherited_set_is_saved;
769 /* how many non-NULL argv's we have. NB: $# + 1 */
773 char *argv0_for_re_execing;
775 #if ENABLE_HUSH_LOOPS
776 unsigned depth_break_continue;
777 unsigned depth_of_loop;
781 struct variable *top_var;
782 char **expanded_assignments;
783 #if ENABLE_HUSH_FUNCTIONS
784 struct function *top_func;
785 # if ENABLE_HUSH_LOCAL
786 struct variable **shadowed_vars_pp;
787 unsigned func_nest_level;
790 /* Signal and trap handling */
792 unsigned count_SIGCHLD;
793 unsigned handled_SIGCHLD;
794 smallint we_have_children;
796 /* which signals have non-DFL handler (even with no traps set)? */
797 unsigned non_DFL_mask;
798 char **traps; /* char *traps[NSIG] */
799 sigset_t blocked_set;
800 sigset_t inherited_set;
802 unsigned long memleak_value;
805 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
807 #define G (*ptr_to_globals)
808 /* Not #defining name to G.name - this quickly gets unwieldy
809 * (too many defines). Also, I actually prefer to see when a variable
810 * is global, thus "G." prefix is a useful hint */
811 #define INIT_G() do { \
812 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
816 /* Function prototypes for builtins */
817 static int builtin_cd(char **argv) FAST_FUNC;
818 static int builtin_echo(char **argv) FAST_FUNC;
819 static int builtin_eval(char **argv) FAST_FUNC;
820 static int builtin_exec(char **argv) FAST_FUNC;
821 static int builtin_exit(char **argv) FAST_FUNC;
822 static int builtin_export(char **argv) FAST_FUNC;
824 static int builtin_fg_bg(char **argv) FAST_FUNC;
825 static int builtin_jobs(char **argv) FAST_FUNC;
828 static int builtin_help(char **argv) FAST_FUNC;
830 #if ENABLE_HUSH_LOCAL
831 static int builtin_local(char **argv) FAST_FUNC;
834 static int builtin_memleak(char **argv) FAST_FUNC;
837 static int builtin_printf(char **argv) FAST_FUNC;
839 static int builtin_pwd(char **argv) FAST_FUNC;
840 static int builtin_read(char **argv) FAST_FUNC;
841 static int builtin_set(char **argv) FAST_FUNC;
842 static int builtin_shift(char **argv) FAST_FUNC;
843 static int builtin_source(char **argv) FAST_FUNC;
844 static int builtin_test(char **argv) FAST_FUNC;
845 static int builtin_trap(char **argv) FAST_FUNC;
846 static int builtin_type(char **argv) FAST_FUNC;
847 static int builtin_true(char **argv) FAST_FUNC;
848 static int builtin_umask(char **argv) FAST_FUNC;
849 static int builtin_unset(char **argv) FAST_FUNC;
850 static int builtin_wait(char **argv) FAST_FUNC;
851 #if ENABLE_HUSH_LOOPS
852 static int builtin_break(char **argv) FAST_FUNC;
853 static int builtin_continue(char **argv) FAST_FUNC;
855 #if ENABLE_HUSH_FUNCTIONS
856 static int builtin_return(char **argv) FAST_FUNC;
859 /* Table of built-in functions. They can be forked or not, depending on
860 * context: within pipes, they fork. As simple commands, they do not.
861 * When used in non-forking context, they can change global variables
862 * in the parent shell process. If forked, of course they cannot.
863 * For example, 'unset foo | whatever' will parse and run, but foo will
864 * still be set at the end. */
865 struct built_in_command {
867 int (*b_function)(char **argv) FAST_FUNC;
870 # define BLTIN(cmd, func, help) { cmd, func, help }
872 # define BLTIN(cmd, func, help) { cmd, func }
876 static const struct built_in_command bltins1[] = {
877 BLTIN("." , builtin_source , "Run commands in a file"),
878 BLTIN(":" , builtin_true , NULL),
880 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
882 #if ENABLE_HUSH_LOOPS
883 BLTIN("break" , builtin_break , "Exit from a loop"),
885 BLTIN("cd" , builtin_cd , "Change directory"),
886 #if ENABLE_HUSH_LOOPS
887 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
889 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
890 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
891 BLTIN("exit" , builtin_exit , "Exit"),
892 BLTIN("export" , builtin_export , "Set environment variables"),
894 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
897 BLTIN("help" , builtin_help , NULL),
900 BLTIN("jobs" , builtin_jobs , "List jobs"),
902 #if ENABLE_HUSH_LOCAL
903 BLTIN("local" , builtin_local , "Set local variables"),
906 BLTIN("memleak" , builtin_memleak , NULL),
908 BLTIN("read" , builtin_read , "Input into variable"),
909 #if ENABLE_HUSH_FUNCTIONS
910 BLTIN("return" , builtin_return , "Return from a function"),
912 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
913 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
914 #if ENABLE_HUSH_BASH_COMPAT
915 BLTIN("source" , builtin_source , "Run commands in a file"),
917 BLTIN("trap" , builtin_trap , "Trap signals"),
918 BLTIN("type" , builtin_type , "Show command type"),
919 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
920 BLTIN("umask" , builtin_umask , "Set file creation mask"),
921 BLTIN("unset" , builtin_unset , "Unset variables"),
922 BLTIN("wait" , builtin_wait , "Wait for process"),
924 /* For now, echo and test are unconditionally enabled.
925 * Maybe make it configurable? */
926 static const struct built_in_command bltins2[] = {
927 BLTIN("[" , builtin_test , NULL),
928 BLTIN("echo" , builtin_echo , NULL),
930 BLTIN("printf" , builtin_printf , NULL),
932 BLTIN("pwd" , builtin_pwd , NULL),
933 BLTIN("test" , builtin_test , NULL),
940 /* prevent disasters with G.debug_indent < 0 */
941 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
942 # define debug_enter() (G.debug_indent++)
943 # define debug_leave() (G.debug_indent--)
945 # define indent() ((void)0)
946 # define debug_enter() ((void)0)
947 # define debug_leave() ((void)0)
951 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
954 #ifndef debug_printf_parse
955 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
958 #ifndef debug_printf_exec
959 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
962 #ifndef debug_printf_env
963 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
966 #ifndef debug_printf_jobs
967 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
968 # define DEBUG_JOBS 1
970 # define DEBUG_JOBS 0
973 #ifndef debug_printf_expand
974 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
975 # define DEBUG_EXPAND 1
977 # define DEBUG_EXPAND 0
980 #ifndef debug_printf_varexp
981 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
984 #ifndef debug_printf_glob
985 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
986 # define DEBUG_GLOB 1
988 # define DEBUG_GLOB 0
991 #ifndef debug_printf_list
992 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
995 #ifndef debug_printf_subst
996 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
999 #ifndef debug_printf_clean
1000 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1001 # define DEBUG_CLEAN 1
1003 # define DEBUG_CLEAN 0
1007 static void debug_print_strings(const char *prefix, char **vv)
1010 fdprintf(2, "%s:\n", prefix);
1012 fdprintf(2, " '%s'\n", *vv++);
1015 # define debug_print_strings(prefix, vv) ((void)0)
1019 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1022 static void *xxmalloc(int lineno, size_t size)
1024 void *ptr = xmalloc((size + 0xff) & ~0xff);
1025 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1028 static void *xxrealloc(int lineno, void *ptr, size_t size)
1030 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1031 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1034 static char *xxstrdup(int lineno, const char *str)
1036 char *ptr = xstrdup(str);
1037 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1040 static void xxfree(void *ptr)
1042 fdprintf(2, "free %p\n", ptr);
1045 # define xmalloc(s) xxmalloc(__LINE__, s)
1046 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1047 # define xstrdup(s) xxstrdup(__LINE__, s)
1048 # define free(p) xxfree(p)
1052 /* Syntax and runtime errors. They always abort scripts.
1053 * In interactive use they usually discard unparsed and/or unexecuted commands
1054 * and return to the prompt.
1055 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1058 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1059 # define syntax_error(lineno, msg) syntax_error(msg)
1060 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1061 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1062 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1063 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1066 static void die_if_script(unsigned lineno, const char *fmt, ...)
1071 bb_error_msg("hush.c:%u", lineno);
1074 bb_verror_msg(fmt, p, NULL);
1076 if (!G_interactive_fd)
1080 static void syntax_error(unsigned lineno, const char *msg)
1083 die_if_script(lineno, "syntax error: %s", msg);
1085 die_if_script(lineno, "syntax error", NULL);
1088 static void syntax_error_at(unsigned lineno, const char *msg)
1090 die_if_script(lineno, "syntax error at '%s'", msg);
1093 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1095 die_if_script(lineno, "syntax error: unterminated %s", s);
1098 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1100 char msg[2] = { ch, '\0' };
1101 syntax_error_unterm_str(lineno, msg);
1104 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1109 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1113 # undef die_if_script
1114 # undef syntax_error
1115 # undef syntax_error_at
1116 # undef syntax_error_unterm_ch
1117 # undef syntax_error_unterm_str
1118 # undef syntax_error_unexpected_ch
1120 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1121 # define syntax_error(msg) syntax_error(__LINE__, msg)
1122 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1123 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1124 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1125 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1129 #if ENABLE_HUSH_INTERACTIVE
1130 static void cmdedit_update_prompt(void);
1132 # define cmdedit_update_prompt() ((void)0)
1136 /* Utility functions
1138 /* Replace each \x with x in place, return ptr past NUL. */
1139 static char *unbackslash(char *src)
1141 char *dst = src = strchrnul(src, '\\');
1145 if ((*dst++ = *src++) == '\0')
1151 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1172 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1173 v[count1 + count2] = NULL;
1176 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1180 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1182 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1183 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1186 #define add_strings_to_strings(strings, add, need_to_dup) \
1187 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1190 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1191 static char **add_string_to_strings(char **strings, char *add)
1196 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1199 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1201 char **ptr = add_string_to_strings(strings, add);
1202 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1205 #define add_string_to_strings(strings, add) \
1206 xx_add_string_to_strings(__LINE__, strings, add)
1209 static void free_strings(char **strings)
1224 /* Helpers for setting new $n and restoring them back
1226 typedef struct save_arg_t {
1230 smallint sv_g_malloced;
1233 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1237 sv->sv_argv0 = argv[0];
1238 sv->sv_g_argv = G.global_argv;
1239 sv->sv_g_argc = G.global_argc;
1240 sv->sv_g_malloced = G.global_args_malloced;
1242 argv[0] = G.global_argv[0]; /* retain $0 */
1243 G.global_argv = argv;
1244 G.global_args_malloced = 0;
1252 static void restore_G_args(save_arg_t *sv, char **argv)
1256 if (G.global_args_malloced) {
1257 /* someone ran "set -- arg1 arg2 ...", undo */
1259 while (*++pp) /* note: does not free $0 */
1261 free(G.global_argv);
1263 argv[0] = sv->sv_argv0;
1264 G.global_argv = sv->sv_g_argv;
1265 G.global_argc = sv->sv_g_argc;
1266 G.global_args_malloced = sv->sv_g_malloced;
1270 /* Basic theory of signal handling in shell
1271 * ========================================
1272 * This does not describe what hush does, rather, it is current understanding
1273 * what it _should_ do. If it doesn't, it's a bug.
1274 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1276 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1277 * is finished or backgrounded. It is the same in interactive and
1278 * non-interactive shells, and is the same regardless of whether
1279 * a user trap handler is installed or a shell special one is in effect.
1280 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1281 * backgrounds (i.e. stops) or kills all members of currently running
1284 * Wait builtin in interruptible by signals for which user trap is set
1285 * or by SIGINT in interactive shell.
1287 * Trap handlers will execute even within trap handlers. (right?)
1289 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1290 * except for handlers set to '' (empty string).
1292 * If job control is off, backgrounded commands ("cmd &")
1293 * have SIGINT, SIGQUIT set to SIG_IGN.
1295 * Commands which are run in command substitution ("`cmd`")
1296 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1298 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1299 * by the shell from its parent.
1301 * Signals which differ from SIG_DFL action
1302 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1305 * SIGTERM (interactive): ignore
1306 * SIGHUP (interactive):
1307 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1308 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1309 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1310 * that all pipe members are stopped. Try this in bash:
1311 * while :; do :; done - ^Z does not background it
1312 * (while :; do :; done) - ^Z backgrounds it
1313 * SIGINT (interactive): wait for last pipe, ignore the rest
1314 * of the command line, show prompt. NB: ^C does not send SIGINT
1315 * to interactive shell while shell is waiting for a pipe,
1316 * since shell is bg'ed (is not in foreground process group).
1317 * Example 1: this waits 5 sec, but does not execute ls:
1318 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1319 * Example 2: this does not wait and does not execute ls:
1320 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1321 * Example 3: this does not wait 5 sec, but executes ls:
1322 * "sleep 5; ls -l" + press ^C
1324 * (What happens to signals which are IGN on shell start?)
1325 * (What happens with signal mask on shell start?)
1327 * Implementation in hush
1328 * ======================
1329 * We use in-kernel pending signal mask to determine which signals were sent.
1330 * We block all signals which we don't want to take action immediately,
1331 * i.e. we block all signals which need to have special handling as described
1332 * above, and all signals which have traps set.
1333 * After each pipe execution, we extract any pending signals via sigtimedwait()
1336 * unsigned non_DFL_mask: a mask of such "special" signals
1337 * sigset_t blocked_set: current blocked signal set
1340 * clear bit in blocked_set unless it is also in non_DFL_mask
1341 * "trap 'cmd' SIGxxx":
1342 * set bit in blocked_set (even if 'cmd' is '')
1343 * after [v]fork, if we plan to be a shell:
1344 * unblock signals with special interactive handling
1345 * (child shell is not interactive),
1346 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1347 * after [v]fork, if we plan to exec:
1348 * POSIX says fork clears pending signal mask in child - no need to clear it.
1349 * Restore blocked signal set to one inherited by shell just prior to exec.
1351 * Note: as a result, we do not use signal handlers much. The only uses
1352 * are to count SIGCHLDs
1353 * and to restore tty pgrp on signal-induced exit.
1356 * Standard says "When a subshell is entered, traps that are not being ignored
1357 * are set to the default actions". bash interprets it so that traps which
1358 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1361 SPECIAL_INTERACTIVE_SIGS = 0
1366 SPECIAL_JOB_SIGS = 0
1374 #if ENABLE_HUSH_FAST
1375 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1378 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1384 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1385 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1386 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1387 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1389 /* Restores tty foreground process group, and exits.
1390 * May be called as signal handler for fatal signal
1391 * (will resend signal to itself, producing correct exit state)
1392 * or called directly with -EXITCODE.
1393 * We also call it if xfunc is exiting. */
1394 static void sigexit(int sig) NORETURN;
1395 static void sigexit(int sig)
1397 /* Disable all signals: job control, SIGPIPE, etc. */
1398 sigprocmask_allsigs(SIG_BLOCK);
1400 /* Careful: we can end up here after [v]fork. Do not restore
1401 * tty pgrp then, only top-level shell process does that */
1402 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1403 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1405 /* Not a signal, just exit */
1409 kill_myself_with_sig(sig); /* does not return */
1413 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1414 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1418 /* Restores tty foreground process group, and exits. */
1419 static void hush_exit(int exitcode) NORETURN;
1420 static void hush_exit(int exitcode)
1423 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1424 /* Prevent recursion:
1425 * trap "echo Hi; exit" EXIT; exit
1428 /* argv[0] is unused */
1429 argv[1] = G.traps[0];
1431 G.exiting = 1; /* prevent EXIT trap recursion */
1432 /* Note: G.traps[0] is not cleared!
1433 * "trap" will still show it, if executed
1438 #if ENABLE_FEATURE_CLEAN_UP
1440 struct variable *cur_var;
1441 if (G.cwd != bb_msg_unknown)
1443 cur_var = G.top_var;
1445 struct variable *tmp = cur_var;
1446 if (!cur_var->max_len)
1447 free(cur_var->varstr);
1448 cur_var = cur_var->next;
1456 sigexit(- (exitcode & 0xff));
1463 static int check_and_run_traps(int sig)
1465 /* I want it in rodata, not in bss.
1466 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1467 * initializer. But other compilers may still use bss.
1468 * TODO: find more portable solution.
1470 static const struct timespec zero_timespec = { 0, 0 };
1471 smalluint save_rcode;
1477 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1482 if (G.traps && G.traps[sig]) {
1483 if (G.traps[sig][0]) {
1484 /* We have user-defined handler */
1486 /* argv[0] is unused */
1487 argv[1] = G.traps[sig];
1489 save_rcode = G.last_exitcode;
1491 G.last_exitcode = save_rcode;
1492 } /* else: "" trap, ignoring signal */
1495 /* not a trap: special action */
1497 #if ENABLE_HUSH_FAST
1500 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1504 /* Builtin was ^C'ed, make it look prettier: */
1511 /* bash is observed to signal whole process groups,
1512 * not individual processes */
1513 for (job = G.job_list; job; job = job->next) {
1516 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1517 if (kill(- job->pgrp, SIGHUP) == 0)
1518 kill(- job->pgrp, SIGCONT);
1523 default: /* ignored: */
1524 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1532 static const char *get_cwd(int force)
1534 if (force || G.cwd == NULL) {
1535 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1536 * we must not try to free(bb_msg_unknown) */
1537 if (G.cwd == bb_msg_unknown)
1539 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1541 G.cwd = bb_msg_unknown;
1548 * Shell and environment variable support
1550 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1552 struct variable **pp;
1553 struct variable *cur;
1556 while ((cur = *pp) != NULL) {
1557 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1564 static const char* FAST_FUNC get_local_var_value(const char *name)
1566 struct variable **vpp;
1567 unsigned len = strlen(name);
1569 if (G.expanded_assignments) {
1570 char **cpp = G.expanded_assignments;
1573 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1574 return cp + len + 1;
1579 vpp = get_ptr_to_local_var(name, len);
1581 return (*vpp)->varstr + len + 1;
1583 if (strcmp(name, "PPID") == 0)
1584 return utoa(G.root_ppid);
1585 // bash compat: UID? EUID?
1586 #if ENABLE_HUSH_RANDOM_SUPPORT
1587 if (strcmp(name, "RANDOM") == 0)
1588 return utoa(next_random(&G.random_gen));
1593 /* str holds "NAME=VAL" and is expected to be malloced.
1594 * We take ownership of it.
1596 * 0: do not change export flag
1597 * (if creating new variable, flag will be 0)
1598 * 1: set export flag and putenv the variable
1599 * -1: clear export flag and unsetenv the variable
1600 * flg_read_only is set only when we handle -R var=val
1602 #if !BB_MMU && ENABLE_HUSH_LOCAL
1603 /* all params are used */
1604 #elif BB_MMU && ENABLE_HUSH_LOCAL
1605 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1606 set_local_var(str, flg_export, local_lvl)
1607 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1608 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1609 set_local_var(str, flg_export)
1610 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1611 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1612 set_local_var(str, flg_export, flg_read_only)
1614 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1616 struct variable **var_pp;
1617 struct variable *cur;
1621 eq_sign = strchr(str, '=');
1622 if (!eq_sign) { /* not expected to ever happen? */
1627 name_len = eq_sign - str + 1; /* including '=' */
1628 var_pp = &G.top_var;
1629 while ((cur = *var_pp) != NULL) {
1630 if (strncmp(cur->varstr, str, name_len) != 0) {
1631 var_pp = &cur->next;
1634 /* We found an existing var with this name */
1635 if (cur->flg_read_only) {
1639 bb_error_msg("%s: readonly variable", str);
1643 if (flg_export == -1) { // "&& cur->flg_export" ?
1644 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1649 #if ENABLE_HUSH_LOCAL
1650 if (cur->func_nest_level < local_lvl) {
1651 /* New variable is declared as local,
1652 * and existing one is global, or local
1653 * from enclosing function.
1654 * Remove and save old one: */
1655 *var_pp = cur->next;
1656 cur->next = *G.shadowed_vars_pp;
1657 *G.shadowed_vars_pp = cur;
1658 /* bash 3.2.33(1) and exported vars:
1660 * # f() { local z=a; env | grep ^z; }
1666 if (cur->flg_export)
1671 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1676 if (cur->max_len != 0) {
1677 if (cur->max_len >= strlen(str)) {
1678 /* This one is from startup env, reuse space */
1679 strcpy(cur->varstr, str);
1683 /* max_len == 0 signifies "malloced" var, which we can
1684 * (and has to) free */
1688 goto set_str_and_exp;
1691 /* Not found - create new variable struct */
1692 cur = xzalloc(sizeof(*cur));
1693 #if ENABLE_HUSH_LOCAL
1694 cur->func_nest_level = local_lvl;
1696 cur->next = *var_pp;
1702 cur->flg_read_only = flg_read_only;
1705 if (flg_export == 1)
1706 cur->flg_export = 1;
1707 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1708 cmdedit_update_prompt();
1709 if (cur->flg_export) {
1710 if (flg_export == -1) {
1711 cur->flg_export = 0;
1712 /* unsetenv was already done */
1714 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1715 return putenv(cur->varstr);
1721 /* Used at startup and after each cd */
1722 static void set_pwd_var(int exp)
1724 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1725 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1728 static int unset_local_var_len(const char *name, int name_len)
1730 struct variable *cur;
1731 struct variable **var_pp;
1734 return EXIT_SUCCESS;
1735 var_pp = &G.top_var;
1736 while ((cur = *var_pp) != NULL) {
1737 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1738 if (cur->flg_read_only) {
1739 bb_error_msg("%s: readonly variable", name);
1740 return EXIT_FAILURE;
1742 *var_pp = cur->next;
1743 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1744 bb_unsetenv(cur->varstr);
1745 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1746 cmdedit_update_prompt();
1750 return EXIT_SUCCESS;
1752 var_pp = &cur->next;
1754 return EXIT_SUCCESS;
1757 static int unset_local_var(const char *name)
1759 return unset_local_var_len(name, strlen(name));
1762 static void unset_vars(char **strings)
1770 const char *eq = strchrnul(*v, '=');
1771 unset_local_var_len(*v, (int)(eq - *v));
1777 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1779 char *var = xasprintf("%s=%s", name, val);
1780 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1785 * Helpers for "var1=val1 var2=val2 cmd" feature
1787 static void add_vars(struct variable *var)
1789 struct variable *next;
1793 var->next = G.top_var;
1795 if (var->flg_export) {
1796 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1797 putenv(var->varstr);
1799 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1805 static struct variable *set_vars_and_save_old(char **strings)
1808 struct variable *old = NULL;
1814 struct variable *var_p;
1815 struct variable **var_pp;
1818 eq = strchr(*s, '=');
1820 var_pp = get_ptr_to_local_var(*s, eq - *s);
1822 /* Remove variable from global linked list */
1824 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1825 *var_pp = var_p->next;
1826 /* Add it to returned list */
1830 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1841 static int FAST_FUNC static_get(struct in_str *i)
1851 static int FAST_FUNC static_peek(struct in_str *i)
1856 #if ENABLE_HUSH_INTERACTIVE
1858 static void cmdedit_update_prompt(void)
1860 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1861 G.PS1 = get_local_var_value("PS1");
1864 G.PS2 = get_local_var_value("PS2");
1872 static const char *setup_prompt_string(int promptmode)
1874 const char *prompt_str;
1875 debug_printf("setup_prompt_string %d ", promptmode);
1876 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1877 /* Set up the prompt */
1878 if (promptmode == 0) { /* PS1 */
1880 /* bash uses $PWD value, even if it is set by user.
1881 * It uses current dir only if PWD is unset.
1882 * We always use current dir. */
1883 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1888 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1889 debug_printf("result '%s'\n", prompt_str);
1893 static void get_user_input(struct in_str *i)
1896 const char *prompt_str;
1898 prompt_str = setup_prompt_string(i->promptmode);
1899 # if ENABLE_FEATURE_EDITING
1900 /* Enable command line editing only while a command line
1901 * is actually being read */
1903 /* Unicode support should be activated even if LANG is set
1904 * _during_ shell execution, not only if it was set when
1905 * shell was started. Therefore, re-check LANG every time:
1907 reinit_unicode(get_local_var_value("LANG"));
1910 /* buglet: SIGINT will not make new prompt to appear _at once_,
1911 * only after <Enter>. (^C will work) */
1912 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1913 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1914 check_and_run_traps(0);
1915 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1916 i->eof_flag = (r < 0);
1917 if (i->eof_flag) { /* EOF/error detected */
1918 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1919 G.user_input_buf[1] = '\0';
1924 fputs(prompt_str, stdout);
1926 G.user_input_buf[0] = r = fgetc(i->file);
1927 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1928 //do we need check_and_run_traps(0)? (maybe only if stdin)
1929 } while (G.flag_SIGINT);
1930 i->eof_flag = (r == EOF);
1932 i->p = G.user_input_buf;
1935 #endif /* INTERACTIVE */
1937 /* This is the magic location that prints prompts
1938 * and gets data back from the user */
1939 static int FAST_FUNC file_get(struct in_str *i)
1943 /* If there is data waiting, eat it up */
1944 if (i->p && *i->p) {
1945 #if ENABLE_HUSH_INTERACTIVE
1949 if (i->eof_flag && !*i->p)
1951 /* note: ch is never NUL */
1953 /* need to double check i->file because we might be doing something
1954 * more complicated by now, like sourcing or substituting. */
1955 #if ENABLE_HUSH_INTERACTIVE
1956 if (G_interactive_fd && i->file == stdin) {
1959 } while (!*i->p); /* need non-empty line */
1960 i->promptmode = 1; /* PS2 */
1964 do ch = fgetc(i->file); while (ch == '\0');
1966 debug_printf("file_get: got '%c' %d\n", ch, ch);
1970 /* All callers guarantee this routine will never
1971 * be used right after a newline, so prompting is not needed.
1973 static int FAST_FUNC file_peek(struct in_str *i)
1976 if (i->p && *i->p) {
1977 if (i->eof_flag && !i->p[1])
1980 /* note: ch is never NUL */
1982 do ch = fgetc(i->file); while (ch == '\0');
1983 i->eof_flag = (ch == EOF);
1984 i->peek_buf[0] = ch;
1985 i->peek_buf[1] = '\0';
1987 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1991 static void setup_file_in_str(struct in_str *i, FILE *f)
1993 memset(i, 0, sizeof(*i));
1994 i->peek = file_peek;
1996 /* i->promptmode = 0; - PS1 (memset did it) */
2001 static void setup_string_in_str(struct in_str *i, const char *s)
2003 memset(i, 0, sizeof(*i));
2004 i->peek = static_peek;
2005 i->get = static_get;
2006 /* i->promptmode = 0; - PS1 (memset did it) */
2008 /* i->eof_flag = 0; */
2015 #define B_CHUNK (32 * sizeof(char*))
2017 static void o_reset_to_empty_unquoted(o_string *o)
2020 o->has_quoted_part = 0;
2025 static void o_free(o_string *o)
2028 memset(o, 0, sizeof(*o));
2031 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2036 static void o_grow_by(o_string *o, int len)
2038 if (o->length + len > o->maxlen) {
2039 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2040 o->data = xrealloc(o->data, 1 + o->maxlen);
2044 static void o_addchr(o_string *o, int ch)
2046 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2048 o->data[o->length] = ch;
2050 o->data[o->length] = '\0';
2053 static void o_addblock(o_string *o, const char *str, int len)
2056 memcpy(&o->data[o->length], str, len);
2058 o->data[o->length] = '\0';
2061 static void o_addstr(o_string *o, const char *str)
2063 o_addblock(o, str, strlen(str));
2067 static void nommu_addchr(o_string *o, int ch)
2073 # define nommu_addchr(o, str) ((void)0)
2076 static void o_addstr_with_NUL(o_string *o, const char *str)
2078 o_addblock(o, str, strlen(str) + 1);
2082 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2083 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2084 * Apparently, on unquoted $v bash still does globbing
2085 * ("v='*.txt'; echo $v" prints all .txt files),
2086 * but NOT brace expansion! Thus, there should be TWO independent
2087 * quoting mechanisms on $v expansion side: one protects
2088 * $v from brace expansion, and other additionally protects "$v" against globbing.
2089 * We have only second one.
2092 #if ENABLE_HUSH_BRACE_EXPANSION
2093 # define MAYBE_BRACES "{}"
2095 # define MAYBE_BRACES ""
2098 /* My analysis of quoting semantics tells me that state information
2099 * is associated with a destination, not a source.
2101 static void o_addqchr(o_string *o, int ch)
2104 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2109 o->data[o->length] = '\\';
2112 o->data[o->length] = ch;
2114 o->data[o->length] = '\0';
2117 static void o_addQchr(o_string *o, int ch)
2120 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2121 && strchr("*?[\\" MAYBE_BRACES, ch)
2124 o->data[o->length] = '\\';
2128 o->data[o->length] = ch;
2130 o->data[o->length] = '\0';
2133 static void o_addqblock(o_string *o, const char *str, int len)
2138 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2139 if (ordinary_cnt > len) /* paranoia */
2141 o_addblock(o, str, ordinary_cnt);
2142 if (ordinary_cnt == len)
2144 str += ordinary_cnt;
2145 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2149 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2151 o->data[o->length] = '\\';
2155 o->data[o->length] = ch;
2157 o->data[o->length] = '\0';
2161 static void o_addQblock(o_string *o, const char *str, int len)
2163 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2164 o_addblock(o, str, len);
2167 o_addqblock(o, str, len);
2170 static void o_addQstr(o_string *o, const char *str)
2172 o_addQblock(o, str, strlen(str));
2175 /* A special kind of o_string for $VAR and `cmd` expansion.
2176 * It contains char* list[] at the beginning, which is grown in 16 element
2177 * increments. Actual string data starts at the next multiple of 16 * (char*).
2178 * list[i] contains an INDEX (int!) into this string data.
2179 * It means that if list[] needs to grow, data needs to be moved higher up
2180 * but list[i]'s need not be modified.
2181 * NB: remembering how many list[i]'s you have there is crucial.
2182 * o_finalize_list() operation post-processes this structure - calculates
2183 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2185 #if DEBUG_EXPAND || DEBUG_GLOB
2186 static void debug_print_list(const char *prefix, o_string *o, int n)
2188 char **list = (char**)o->data;
2189 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2193 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2194 prefix, list, n, string_start, o->length, o->maxlen,
2195 !!(o->o_expflags & EXP_FLAG_GLOB),
2197 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2200 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2201 o->data + (int)(uintptr_t)list[i] + string_start,
2202 o->data + (int)(uintptr_t)list[i] + string_start);
2206 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2208 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2212 # define debug_print_list(prefix, o, n) ((void)0)
2215 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2216 * in list[n] so that it points past last stored byte so far.
2217 * It returns n+1. */
2218 static int o_save_ptr_helper(o_string *o, int n)
2220 char **list = (char**)o->data;
2224 if (!o->has_empty_slot) {
2225 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2226 string_len = o->length - string_start;
2227 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2228 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2229 /* list[n] points to string_start, make space for 16 more pointers */
2230 o->maxlen += 0x10 * sizeof(list[0]);
2231 o->data = xrealloc(o->data, o->maxlen + 1);
2232 list = (char**)o->data;
2233 memmove(list + n + 0x10, list + n, string_len);
2234 o->length += 0x10 * sizeof(list[0]);
2236 debug_printf_list("list[%d]=%d string_start=%d\n",
2237 n, string_len, string_start);
2240 /* We have empty slot at list[n], reuse without growth */
2241 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2242 string_len = o->length - string_start;
2243 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2244 n, string_len, string_start);
2245 o->has_empty_slot = 0;
2247 list[n] = (char*)(uintptr_t)string_len;
2251 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2252 static int o_get_last_ptr(o_string *o, int n)
2254 char **list = (char**)o->data;
2255 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2257 return ((int)(uintptr_t)list[n-1]) + string_start;
2260 #if ENABLE_HUSH_BRACE_EXPANSION
2261 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2262 * first, it processes even {a} (no commas), second,
2263 * I didn't manage to make it return strings when they don't match
2264 * existing files. Need to re-implement it.
2268 static int glob_needed(const char *s)
2277 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2283 /* Return pointer to next closing brace or to comma */
2284 static const char *next_brace_sub(const char *cp)
2288 while (*cp != '\0') {
2295 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2301 return *cp != '\0' ? cp : NULL;
2303 /* Recursive brace globber. Note: may garble pattern[]. */
2304 static int glob_brace(char *pattern, o_string *o, int n)
2306 char *new_pattern_buf;
2313 debug_printf_glob("glob_brace('%s')\n", pattern);
2319 if (*begin == '{') {
2320 /* Find the first sub-pattern and at the same time
2321 * find the rest after the closing brace */
2322 next = next_brace_sub(begin);
2324 /* An illegal expression */
2328 /* "{abc}" with no commas - illegal
2329 * brace expr, disregard and skip it */
2335 if (*begin == '\\' && begin[1] != '\0')
2339 debug_printf_glob("begin:%s\n", begin);
2340 debug_printf_glob("next:%s\n", next);
2342 /* Now find the end of the whole brace expression */
2344 while (*rest != '}') {
2345 rest = next_brace_sub(rest);
2347 /* An illegal expression */
2350 debug_printf_glob("rest:%s\n", rest);
2352 rest_len = strlen(++rest) + 1;
2354 /* We are sure the brace expression is well-formed */
2356 /* Allocate working buffer large enough for our work */
2357 new_pattern_buf = xmalloc(strlen(pattern));
2359 /* We have a brace expression. BEGIN points to the opening {,
2360 * NEXT points past the terminator of the first element, and REST
2361 * points past the final }. We will accumulate result names from
2362 * recursive runs for each brace alternative in the buffer using
2367 /* Construct the new glob expression */
2370 mempcpy(new_pattern_buf,
2371 /* We know the prefix for all sub-patterns */
2372 pattern, begin - pattern),
2376 /* Note: glob_brace() may garble new_pattern_buf[].
2377 * That's why we re-copy prefix every time (1st memcpy above).
2379 n = glob_brace(new_pattern_buf, o, n);
2381 /* We saw the last entry */
2385 next = next_brace_sub(next);
2387 free(new_pattern_buf);
2395 memset(&globdata, 0, sizeof(globdata));
2396 gr = glob(pattern, 0, NULL, &globdata);
2397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2399 if (gr == GLOB_NOMATCH) {
2400 globfree(&globdata);
2401 /* NB: garbles parameter */
2402 unbackslash(pattern);
2403 o_addstr_with_NUL(o, pattern);
2404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2405 return o_save_ptr_helper(o, n);
2407 if (gr == GLOB_NOSPACE)
2408 bb_error_msg_and_die(bb_msg_memory_exhausted);
2409 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2410 * but we didn't specify it. Paranoia again. */
2411 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2413 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2414 char **argv = globdata.gl_pathv;
2416 o_addstr_with_NUL(o, *argv);
2417 n = o_save_ptr_helper(o, n);
2423 globfree(&globdata);
2427 /* Performs globbing on last list[],
2428 * saving each result as a new list[].
2430 static int perform_glob(o_string *o, int n)
2432 char *pattern, *copy;
2434 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2436 return o_save_ptr_helper(o, n);
2437 pattern = o->data + o_get_last_ptr(o, n);
2438 debug_printf_glob("glob pattern '%s'\n", pattern);
2439 if (!glob_needed(pattern)) {
2440 /* unbackslash last string in o in place, fix length */
2441 o->length = unbackslash(pattern) - o->data;
2442 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2443 return o_save_ptr_helper(o, n);
2446 copy = xstrdup(pattern);
2447 /* "forget" pattern in o */
2448 o->length = pattern - o->data;
2449 n = glob_brace(copy, o, n);
2452 debug_print_list("perform_glob returning", o, n);
2456 #else /* !HUSH_BRACE_EXPANSION */
2459 static int glob_needed(const char *s)
2468 if (*s == '*' || *s == '[' || *s == '?')
2474 /* Performs globbing on last list[],
2475 * saving each result as a new list[].
2477 static int perform_glob(o_string *o, int n)
2483 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2485 return o_save_ptr_helper(o, n);
2486 pattern = o->data + o_get_last_ptr(o, n);
2487 debug_printf_glob("glob pattern '%s'\n", pattern);
2488 if (!glob_needed(pattern)) {
2490 /* unbackslash last string in o in place, fix length */
2491 o->length = unbackslash(pattern) - o->data;
2492 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2493 return o_save_ptr_helper(o, n);
2496 memset(&globdata, 0, sizeof(globdata));
2497 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2498 * If we glob "*.\*" and don't find anything, we need
2499 * to fall back to using literal "*.*", but GLOB_NOCHECK
2500 * will return "*.\*"!
2502 gr = glob(pattern, 0, NULL, &globdata);
2503 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2505 if (gr == GLOB_NOMATCH) {
2506 globfree(&globdata);
2509 if (gr == GLOB_NOSPACE)
2510 bb_error_msg_and_die(bb_msg_memory_exhausted);
2511 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2512 * but we didn't specify it. Paranoia again. */
2513 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2515 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2516 char **argv = globdata.gl_pathv;
2517 /* "forget" pattern in o */
2518 o->length = pattern - o->data;
2520 o_addstr_with_NUL(o, *argv);
2521 n = o_save_ptr_helper(o, n);
2527 globfree(&globdata);
2529 debug_print_list("perform_glob returning", o, n);
2533 #endif /* !HUSH_BRACE_EXPANSION */
2535 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2536 * Otherwise, just finish current list[] and start new */
2537 static int o_save_ptr(o_string *o, int n)
2539 if (o->o_expflags & EXP_FLAG_GLOB) {
2540 /* If o->has_empty_slot, list[n] was already globbed
2541 * (if it was requested back then when it was filled)
2542 * so don't do that again! */
2543 if (!o->has_empty_slot)
2544 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2546 return o_save_ptr_helper(o, n);
2549 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2550 static char **o_finalize_list(o_string *o, int n)
2555 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2557 debug_print_list("finalized", o, n);
2558 debug_printf_expand("finalized n:%d\n", n);
2559 list = (char**)o->data;
2560 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2564 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2569 static void free_pipe_list(struct pipe *pi);
2571 /* Returns pi->next - next pipe in the list */
2572 static struct pipe *free_pipe(struct pipe *pi)
2577 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2578 for (i = 0; i < pi->num_cmds; i++) {
2579 struct command *command;
2580 struct redir_struct *r, *rnext;
2582 command = &pi->cmds[i];
2583 debug_printf_clean(" command %d:\n", i);
2584 if (command->argv) {
2588 for (a = 0, p = command->argv; *p; a++, p++) {
2589 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2592 free_strings(command->argv);
2593 //command->argv = NULL;
2595 /* not "else if": on syntax error, we may have both! */
2596 if (command->group) {
2597 debug_printf_clean(" begin group (cmd_type:%d)\n",
2599 free_pipe_list(command->group);
2600 debug_printf_clean(" end group\n");
2601 //command->group = NULL;
2603 /* else is crucial here.
2604 * If group != NULL, child_func is meaningless */
2605 #if ENABLE_HUSH_FUNCTIONS
2606 else if (command->child_func) {
2607 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2608 command->child_func->parent_cmd = NULL;
2612 free(command->group_as_string);
2613 //command->group_as_string = NULL;
2615 for (r = command->redirects; r; r = rnext) {
2616 debug_printf_clean(" redirect %d%s",
2617 r->rd_fd, redir_table[r->rd_type].descrip);
2618 /* guard against the case >$FOO, where foo is unset or blank */
2619 if (r->rd_filename) {
2620 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2621 free(r->rd_filename);
2622 //r->rd_filename = NULL;
2624 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2628 //command->redirects = NULL;
2630 free(pi->cmds); /* children are an array, they get freed all at once */
2634 //pi->cmdtext = NULL;
2642 static void free_pipe_list(struct pipe *pi)
2646 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2648 debug_printf_clean("pipe followup code %d\n", pi->followup);
2654 /*** Parsing routines ***/
2656 #ifndef debug_print_tree
2657 static void debug_print_tree(struct pipe *pi, int lvl)
2659 static const char *const PIPE[] = {
2665 static const char *RES[] = {
2666 [RES_NONE ] = "NONE" ,
2669 [RES_THEN ] = "THEN" ,
2670 [RES_ELIF ] = "ELIF" ,
2671 [RES_ELSE ] = "ELSE" ,
2674 # if ENABLE_HUSH_LOOPS
2675 [RES_FOR ] = "FOR" ,
2676 [RES_WHILE] = "WHILE",
2677 [RES_UNTIL] = "UNTIL",
2679 [RES_DONE ] = "DONE" ,
2681 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2684 # if ENABLE_HUSH_CASE
2685 [RES_CASE ] = "CASE" ,
2686 [RES_CASE_IN ] = "CASE_IN" ,
2687 [RES_MATCH] = "MATCH",
2688 [RES_CASE_BODY] = "CASE_BODY",
2689 [RES_ESAC ] = "ESAC" ,
2691 [RES_XXXX ] = "XXXX" ,
2692 [RES_SNTX ] = "SNTX" ,
2694 static const char *const CMDTYPE[] = {
2698 # if ENABLE_HUSH_FUNCTIONS
2707 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2708 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2710 while (prn < pi->num_cmds) {
2711 struct command *command = &pi->cmds[prn];
2712 char **argv = command->argv;
2714 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2716 command->assignment_cnt);
2717 if (command->group) {
2718 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2719 CMDTYPE[command->cmd_type],
2722 , " group_as_string:", command->group_as_string
2727 debug_print_tree(command->group, lvl+1);
2731 if (argv) while (*argv) {
2732 fdprintf(2, " '%s'", *argv);
2742 #endif /* debug_print_tree */
2744 static struct pipe *new_pipe(void)
2747 pi = xzalloc(sizeof(struct pipe));
2748 /*pi->followup = 0; - deliberately invalid value */
2749 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2753 /* Command (member of a pipe) is complete, or we start a new pipe
2754 * if ctx->command is NULL.
2755 * No errors possible here.
2757 static int done_command(struct parse_context *ctx)
2759 /* The command is really already in the pipe structure, so
2760 * advance the pipe counter and make a new, null command. */
2761 struct pipe *pi = ctx->pipe;
2762 struct command *command = ctx->command;
2765 if (IS_NULL_CMD(command)) {
2766 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2770 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2771 //debug_print_tree(ctx->list_head, 20);
2773 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2776 /* Only real trickiness here is that the uncommitted
2777 * command structure is not counted in pi->num_cmds. */
2778 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2779 ctx->command = command = &pi->cmds[pi->num_cmds];
2781 memset(command, 0, sizeof(*command));
2782 return pi->num_cmds; /* used only for 0/nonzero check */
2785 static void done_pipe(struct parse_context *ctx, pipe_style type)
2789 debug_printf_parse("done_pipe entered, followup %d\n", type);
2790 /* Close previous command */
2791 not_null = done_command(ctx);
2792 ctx->pipe->followup = type;
2794 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2795 ctx->ctx_inverted = 0;
2796 ctx->pipe->res_word = ctx->ctx_res_w;
2799 /* Without this check, even just <enter> on command line generates
2800 * tree of three NOPs (!). Which is harmless but annoying.
2801 * IOW: it is safe to do it unconditionally. */
2804 || ctx->ctx_res_w == RES_FI
2806 #if ENABLE_HUSH_LOOPS
2807 || ctx->ctx_res_w == RES_DONE
2808 || ctx->ctx_res_w == RES_FOR
2809 || ctx->ctx_res_w == RES_IN
2811 #if ENABLE_HUSH_CASE
2812 || ctx->ctx_res_w == RES_ESAC
2816 debug_printf_parse("done_pipe: adding new pipe: "
2817 "not_null:%d ctx->ctx_res_w:%d\n",
2818 not_null, ctx->ctx_res_w);
2820 ctx->pipe->next = new_p;
2822 /* RES_THEN, RES_DO etc are "sticky" -
2823 * they remain set for pipes inside if/while.
2824 * This is used to control execution.
2825 * RES_FOR and RES_IN are NOT sticky (needed to support
2826 * cases where variable or value happens to match a keyword):
2828 #if ENABLE_HUSH_LOOPS
2829 if (ctx->ctx_res_w == RES_FOR
2830 || ctx->ctx_res_w == RES_IN)
2831 ctx->ctx_res_w = RES_NONE;
2833 #if ENABLE_HUSH_CASE
2834 if (ctx->ctx_res_w == RES_MATCH)
2835 ctx->ctx_res_w = RES_CASE_BODY;
2836 if (ctx->ctx_res_w == RES_CASE)
2837 ctx->ctx_res_w = RES_CASE_IN;
2839 ctx->command = NULL; /* trick done_command below */
2840 /* Create the memory for command, roughly:
2841 * ctx->pipe->cmds = new struct command;
2842 * ctx->command = &ctx->pipe->cmds[0];
2845 //debug_print_tree(ctx->list_head, 10);
2847 debug_printf_parse("done_pipe return\n");
2850 static void initialize_context(struct parse_context *ctx)
2852 memset(ctx, 0, sizeof(*ctx));
2853 ctx->pipe = ctx->list_head = new_pipe();
2854 /* Create the memory for command, roughly:
2855 * ctx->pipe->cmds = new struct command;
2856 * ctx->command = &ctx->pipe->cmds[0];
2861 /* If a reserved word is found and processed, parse context is modified
2862 * and 1 is returned.
2865 struct reserved_combo {
2868 unsigned char assignment_flag;
2872 FLAG_END = (1 << RES_NONE ),
2874 FLAG_IF = (1 << RES_IF ),
2875 FLAG_THEN = (1 << RES_THEN ),
2876 FLAG_ELIF = (1 << RES_ELIF ),
2877 FLAG_ELSE = (1 << RES_ELSE ),
2878 FLAG_FI = (1 << RES_FI ),
2880 # if ENABLE_HUSH_LOOPS
2881 FLAG_FOR = (1 << RES_FOR ),
2882 FLAG_WHILE = (1 << RES_WHILE),
2883 FLAG_UNTIL = (1 << RES_UNTIL),
2884 FLAG_DO = (1 << RES_DO ),
2885 FLAG_DONE = (1 << RES_DONE ),
2886 FLAG_IN = (1 << RES_IN ),
2888 # if ENABLE_HUSH_CASE
2889 FLAG_MATCH = (1 << RES_MATCH),
2890 FLAG_ESAC = (1 << RES_ESAC ),
2892 FLAG_START = (1 << RES_XXXX ),
2895 static const struct reserved_combo* match_reserved_word(o_string *word)
2897 /* Mostly a list of accepted follow-up reserved words.
2898 * FLAG_END means we are done with the sequence, and are ready
2899 * to turn the compound list into a command.
2900 * FLAG_START means the word must start a new compound list.
2902 static const struct reserved_combo reserved_list[] = {
2904 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2905 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2906 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2907 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2908 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2909 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2911 # if ENABLE_HUSH_LOOPS
2912 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2913 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2914 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2915 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2916 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2917 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2919 # if ENABLE_HUSH_CASE
2920 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2921 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2924 const struct reserved_combo *r;
2926 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2927 if (strcmp(word->data, r->literal) == 0)
2932 /* Return 0: not a keyword, 1: keyword
2934 static int reserved_word(o_string *word, struct parse_context *ctx)
2936 # if ENABLE_HUSH_CASE
2937 static const struct reserved_combo reserved_match = {
2938 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2941 const struct reserved_combo *r;
2943 if (word->has_quoted_part)
2945 r = match_reserved_word(word);
2949 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2950 # if ENABLE_HUSH_CASE
2951 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2952 /* "case word IN ..." - IN part starts first MATCH part */
2953 r = &reserved_match;
2956 if (r->flag == 0) { /* '!' */
2957 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2958 syntax_error("! ! command");
2959 ctx->ctx_res_w = RES_SNTX;
2961 ctx->ctx_inverted = 1;
2964 if (r->flag & FLAG_START) {
2965 struct parse_context *old;
2967 old = xmalloc(sizeof(*old));
2968 debug_printf_parse("push stack %p\n", old);
2969 *old = *ctx; /* physical copy */
2970 initialize_context(ctx);
2972 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2973 syntax_error_at(word->data);
2974 ctx->ctx_res_w = RES_SNTX;
2977 /* "{...} fi" is ok. "{...} if" is not
2979 * if { echo foo; } then { echo bar; } fi */
2980 if (ctx->command->group)
2981 done_pipe(ctx, PIPE_SEQ);
2984 ctx->ctx_res_w = r->res;
2985 ctx->old_flag = r->flag;
2986 word->o_assignment = r->assignment_flag;
2988 if (ctx->old_flag & FLAG_END) {
2989 struct parse_context *old;
2991 done_pipe(ctx, PIPE_SEQ);
2992 debug_printf_parse("pop stack %p\n", ctx->stack);
2994 old->command->group = ctx->list_head;
2995 old->command->cmd_type = CMD_NORMAL;
2997 o_addstr(&old->as_string, ctx->as_string.data);
2998 o_free_unsafe(&ctx->as_string);
2999 old->command->group_as_string = xstrdup(old->as_string.data);
3000 debug_printf_parse("pop, remembering as:'%s'\n",
3001 old->command->group_as_string);
3003 *ctx = *old; /* physical copy */
3008 #endif /* HAS_KEYWORDS */
3010 /* Word is complete, look at it and update parsing context.
3011 * Normal return is 0. Syntax errors return 1.
3012 * Note: on return, word is reset, but not o_free'd!
3014 static int done_word(o_string *word, struct parse_context *ctx)
3016 struct command *command = ctx->command;
3018 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3019 if (word->length == 0 && !word->has_quoted_part) {
3020 debug_printf_parse("done_word return 0: true null, ignored\n");
3024 if (ctx->pending_redirect) {
3025 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3026 * only if run as "bash", not "sh" */
3027 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3029 * ...the word that follows the redirection operator
3030 * shall be subjected to tilde expansion, parameter expansion,
3031 * command substitution, arithmetic expansion, and quote
3032 * removal. Pathname expansion shall not be performed
3033 * on the word by a non-interactive shell; an interactive
3034 * shell may perform it, but shall do so only when
3035 * the expansion would result in one word."
3037 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3038 /* Cater for >\file case:
3039 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3040 * Same with heredocs:
3041 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3043 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3044 unbackslash(ctx->pending_redirect->rd_filename);
3045 /* Is it <<"HEREDOC"? */
3046 if (word->has_quoted_part) {
3047 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3050 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3051 ctx->pending_redirect = NULL;
3053 /* If this word wasn't an assignment, next ones definitely
3054 * can't be assignments. Even if they look like ones. */
3055 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3056 && word->o_assignment != WORD_IS_KEYWORD
3058 word->o_assignment = NOT_ASSIGNMENT;
3060 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3061 command->assignment_cnt++;
3062 word->o_assignment = MAYBE_ASSIGNMENT;
3066 # if ENABLE_HUSH_CASE
3067 if (ctx->ctx_dsemicolon
3068 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3070 /* already done when ctx_dsemicolon was set to 1: */
3071 /* ctx->ctx_res_w = RES_MATCH; */
3072 ctx->ctx_dsemicolon = 0;
3075 if (!command->argv /* if it's the first word... */
3076 # if ENABLE_HUSH_LOOPS
3077 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3078 && ctx->ctx_res_w != RES_IN
3080 # if ENABLE_HUSH_CASE
3081 && ctx->ctx_res_w != RES_CASE
3084 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3085 if (reserved_word(word, ctx)) {
3086 o_reset_to_empty_unquoted(word);
3087 debug_printf_parse("done_word return %d\n",
3088 (ctx->ctx_res_w == RES_SNTX));
3089 return (ctx->ctx_res_w == RES_SNTX);
3091 # if ENABLE_HUSH_BASH_COMPAT
3092 if (strcmp(word->data, "[[") == 0) {
3093 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3099 if (command->group) {
3100 /* "{ echo foo; } echo bar" - bad */
3101 syntax_error_at(word->data);
3102 debug_printf_parse("done_word return 1: syntax error, "
3103 "groups and arglists don't mix\n");
3106 if (word->has_quoted_part
3107 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3108 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3109 /* (otherwise it's known to be not empty and is already safe) */
3111 /* exclude "$@" - it can expand to no word despite "" */
3112 char *p = word->data;
3113 while (p[0] == SPECIAL_VAR_SYMBOL
3114 && (p[1] & 0x7f) == '@'
3115 && p[2] == SPECIAL_VAR_SYMBOL
3119 if (p == word->data || p[0] != '\0') {
3120 /* saw no "$@", or not only "$@" but some
3121 * real text is there too */
3122 /* insert "empty variable" reference, this makes
3123 * e.g. "", $empty"" etc to not disappear */
3124 o_addchr(word, SPECIAL_VAR_SYMBOL);
3125 o_addchr(word, SPECIAL_VAR_SYMBOL);
3128 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3129 debug_print_strings("word appended to argv", command->argv);
3132 #if ENABLE_HUSH_LOOPS
3133 if (ctx->ctx_res_w == RES_FOR) {
3134 if (word->has_quoted_part
3135 || !is_well_formed_var_name(command->argv[0], '\0')
3137 /* bash says just "not a valid identifier" */
3138 syntax_error("not a valid identifier in for");
3141 /* Force FOR to have just one word (variable name) */
3142 /* NB: basically, this makes hush see "for v in ..."
3143 * syntax as if it is "for v; in ...". FOR and IN become
3144 * two pipe structs in parse tree. */
3145 done_pipe(ctx, PIPE_SEQ);
3148 #if ENABLE_HUSH_CASE
3149 /* Force CASE to have just one word */
3150 if (ctx->ctx_res_w == RES_CASE) {
3151 done_pipe(ctx, PIPE_SEQ);
3155 o_reset_to_empty_unquoted(word);
3157 debug_printf_parse("done_word return 0\n");
3162 /* Peek ahead in the input to find out if we have a "&n" construct,
3163 * as in "2>&1", that represents duplicating a file descriptor.
3165 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3166 * REDIRFD_SYNTAX_ERR if syntax error,
3167 * REDIRFD_TO_FILE if no & was seen,
3168 * or the number found.
3171 #define parse_redir_right_fd(as_string, input) \
3172 parse_redir_right_fd(input)
3174 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3180 return REDIRFD_TO_FILE;
3182 ch = i_getch(input); /* get the & */
3183 nommu_addchr(as_string, ch);
3186 ch = i_getch(input);
3187 nommu_addchr(as_string, ch);
3188 return REDIRFD_CLOSE;
3192 while (ch != EOF && isdigit(ch)) {
3193 d = d*10 + (ch-'0');
3195 ch = i_getch(input);
3196 nommu_addchr(as_string, ch);
3201 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3203 bb_error_msg("ambiguous redirect");
3204 return REDIRFD_SYNTAX_ERR;
3207 /* Return code is 0 normal, 1 if a syntax error is detected
3209 static int parse_redirect(struct parse_context *ctx,
3212 struct in_str *input)
3214 struct command *command = ctx->command;
3215 struct redir_struct *redir;
3216 struct redir_struct **redirp;
3219 dup_num = REDIRFD_TO_FILE;
3220 if (style != REDIRECT_HEREDOC) {
3221 /* Check for a '>&1' type redirect */
3222 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3223 if (dup_num == REDIRFD_SYNTAX_ERR)
3226 int ch = i_peek(input);
3227 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3228 if (dup_num) { /* <<-... */
3229 ch = i_getch(input);
3230 nommu_addchr(&ctx->as_string, ch);
3235 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3236 int ch = i_peek(input);
3238 /* >|FILE redirect ("clobbering" >).
3239 * Since we do not support "set -o noclobber" yet,
3240 * >| and > are the same for now. Just eat |.
3242 ch = i_getch(input);
3243 nommu_addchr(&ctx->as_string, ch);
3247 /* Create a new redir_struct and append it to the linked list */
3248 redirp = &command->redirects;
3249 while ((redir = *redirp) != NULL) {
3250 redirp = &(redir->next);
3252 *redirp = redir = xzalloc(sizeof(*redir));
3253 /* redir->next = NULL; */
3254 /* redir->rd_filename = NULL; */
3255 redir->rd_type = style;
3256 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3258 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3259 redir_table[style].descrip);
3261 redir->rd_dup = dup_num;
3262 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3263 /* Erik had a check here that the file descriptor in question
3264 * is legit; I postpone that to "run time"
3265 * A "-" representation of "close me" shows up as a -3 here */
3266 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3267 redir->rd_fd, redir->rd_dup);
3269 /* Set ctx->pending_redirect, so we know what to do at the
3270 * end of the next parsed word. */
3271 ctx->pending_redirect = redir;
3276 /* If a redirect is immediately preceded by a number, that number is
3277 * supposed to tell which file descriptor to redirect. This routine
3278 * looks for such preceding numbers. In an ideal world this routine
3279 * needs to handle all the following classes of redirects...
3280 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3281 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3282 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3283 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3285 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3287 * ... If n is quoted, the number shall not be recognized as part of
3288 * the redirection expression. For example:
3290 * writes the character 2 into file a"
3291 * We are getting it right by setting ->has_quoted_part on any \<char>
3293 * A -1 return means no valid number was found,
3294 * the caller should use the appropriate default for this redirection.
3296 static int redirect_opt_num(o_string *o)
3300 if (o->data == NULL)
3302 num = bb_strtou(o->data, NULL, 10);
3303 if (errno || num < 0)
3305 o_reset_to_empty_unquoted(o);
3310 #define fetch_till_str(as_string, input, word, skip_tabs) \
3311 fetch_till_str(input, word, skip_tabs)
3313 static char *fetch_till_str(o_string *as_string,
3314 struct in_str *input,
3318 o_string heredoc = NULL_O_STRING;
3320 int prev = 0; /* not \ */
3325 ch = i_getch(input);
3327 nommu_addchr(as_string, ch);
3328 if ((ch == '\n' || ch == EOF)
3329 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3331 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3332 heredoc.data[past_EOL] = '\0';
3333 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3334 return heredoc.data;
3336 while (ch == '\n') {
3337 o_addchr(&heredoc, ch);
3340 past_EOL = heredoc.length;
3342 ch = i_getch(input);
3344 nommu_addchr(as_string, ch);
3345 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3349 o_free_unsafe(&heredoc);
3352 o_addchr(&heredoc, ch);
3353 nommu_addchr(as_string, ch);
3354 if (prev == '\\' && ch == '\\')
3355 /* Correctly handle foo\\<eol> (not a line cont.) */
3356 prev = 0; /* not \ */
3362 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3363 * and load them all. There should be exactly heredoc_cnt of them.
3365 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3367 struct pipe *pi = ctx->list_head;
3369 while (pi && heredoc_cnt) {
3371 struct command *cmd = pi->cmds;
3373 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3375 cmd->argv ? cmd->argv[0] : "NONE");
3376 for (i = 0; i < pi->num_cmds; i++) {
3377 struct redir_struct *redir = cmd->redirects;
3379 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3380 i, cmd->argv ? cmd->argv[0] : "NONE");
3382 if (redir->rd_type == REDIRECT_HEREDOC) {
3385 redir->rd_type = REDIRECT_HEREDOC2;
3386 /* redir->rd_dup is (ab)used to indicate <<- */
3387 p = fetch_till_str(&ctx->as_string, input,
3388 redir->rd_filename, redir->rd_dup);
3390 syntax_error("unexpected EOF in here document");
3393 free(redir->rd_filename);
3394 redir->rd_filename = p;
3397 redir = redir->next;
3404 /* Should be 0. If it isn't, it's a parse error */
3406 bb_error_msg_and_die("heredoc BUG 2");
3412 static int run_list(struct pipe *pi);
3414 #define parse_stream(pstring, input, end_trigger) \
3415 parse_stream(input, end_trigger)
3417 static struct pipe *parse_stream(char **pstring,
3418 struct in_str *input,
3422 #if !ENABLE_HUSH_FUNCTIONS
3423 #define parse_group(dest, ctx, input, ch) \
3424 parse_group(ctx, input, ch)
3426 static int parse_group(o_string *dest, struct parse_context *ctx,
3427 struct in_str *input, int ch)
3429 /* dest contains characters seen prior to ( or {.
3430 * Typically it's empty, but for function defs,
3431 * it contains function name (without '()'). */
3432 struct pipe *pipe_list;
3434 struct command *command = ctx->command;
3436 debug_printf_parse("parse_group entered\n");
3437 #if ENABLE_HUSH_FUNCTIONS
3438 if (ch == '(' && !dest->has_quoted_part) {
3440 if (done_word(dest, ctx))
3443 goto skip; /* (... */
3444 if (command->argv[1]) { /* word word ... (... */
3445 syntax_error_unexpected_ch('(');
3448 /* it is "word(..." or "word (..." */
3450 ch = i_getch(input);
3451 while (ch == ' ' || ch == '\t');
3453 syntax_error_unexpected_ch(ch);
3456 nommu_addchr(&ctx->as_string, ch);
3458 ch = i_getch(input);
3459 while (ch == ' ' || ch == '\t' || ch == '\n');
3461 syntax_error_unexpected_ch(ch);
3464 nommu_addchr(&ctx->as_string, ch);
3465 command->cmd_type = CMD_FUNCDEF;
3470 #if 0 /* Prevented by caller */
3471 if (command->argv /* word [word]{... */
3472 || dest->length /* word{... */
3473 || dest->has_quoted_part /* ""{... */
3476 debug_printf_parse("parse_group return 1: "
3477 "syntax error, groups and arglists don't mix\n");
3482 #if ENABLE_HUSH_FUNCTIONS
3488 command->cmd_type = CMD_SUBSHELL;
3490 /* bash does not allow "{echo...", requires whitespace */
3491 ch = i_getch(input);
3492 if (ch != ' ' && ch != '\t' && ch != '\n') {
3493 syntax_error_unexpected_ch(ch);
3496 nommu_addchr(&ctx->as_string, ch);
3501 # define as_string NULL
3503 char *as_string = NULL;
3505 pipe_list = parse_stream(&as_string, input, endch);
3508 o_addstr(&ctx->as_string, as_string);
3510 /* empty ()/{} or parse error? */
3511 if (!pipe_list || pipe_list == ERR_PTR) {
3512 /* parse_stream already emitted error msg */
3515 debug_printf_parse("parse_group return 1: "
3516 "parse_stream returned %p\n", pipe_list);
3519 command->group = pipe_list;
3521 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3522 command->group_as_string = as_string;
3523 debug_printf_parse("end of group, remembering as:'%s'\n",
3524 command->group_as_string);
3528 debug_printf_parse("parse_group return 0\n");
3530 /* command remains "open", available for possible redirects */
3533 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3534 /* Subroutines for copying $(...) and `...` things */
3535 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3537 static int add_till_single_quote(o_string *dest, struct in_str *input)
3540 int ch = i_getch(input);
3542 syntax_error_unterm_ch('\'');
3550 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3551 static int add_till_double_quote(o_string *dest, struct in_str *input)
3554 int ch = i_getch(input);
3556 syntax_error_unterm_ch('"');
3561 if (ch == '\\') { /* \x. Copy both chars. */
3563 ch = i_getch(input);
3567 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3572 //if (ch == '$') ...
3575 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3577 * "Within the backquoted style of command substitution, backslash
3578 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3579 * The search for the matching backquote shall be satisfied by the first
3580 * backquote found without a preceding backslash; during this search,
3581 * if a non-escaped backquote is encountered within a shell comment,
3582 * a here-document, an embedded command substitution of the $(command)
3583 * form, or a quoted string, undefined results occur. A single-quoted
3584 * or double-quoted string that begins, but does not end, within the
3585 * "`...`" sequence produces undefined results."
3587 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3589 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3592 int ch = i_getch(input);
3596 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3597 ch = i_getch(input);
3601 && (!in_dquote || ch != '"')
3603 o_addchr(dest, '\\');
3607 syntax_error_unterm_ch('`');
3613 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3614 * quoting and nested ()s.
3615 * "With the $(command) style of command substitution, all characters
3616 * following the open parenthesis to the matching closing parenthesis
3617 * constitute the command. Any valid shell script can be used for command,
3618 * except a script consisting solely of redirections which produces
3619 * unspecified results."
3621 * echo $(echo '(TEST)' BEST) (TEST) BEST
3622 * echo $(echo 'TEST)' BEST) TEST) BEST
3623 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3625 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3626 * can contain arbitrary constructs, just like $(cmd).
3627 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3628 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3630 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3631 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3634 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3635 # if ENABLE_HUSH_BASH_COMPAT
3636 char end_char2 = end_ch >> 8;
3638 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3641 ch = i_getch(input);
3643 syntax_error_unterm_ch(end_ch);
3646 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3649 /* we look for closing )) of $((EXPR)) */
3650 if (i_peek(input) == end_ch) {
3651 i_getch(input); /* eat second ')' */
3656 if (ch == '(' || ch == '{') {
3657 ch = (ch == '(' ? ')' : '}');
3658 if (!add_till_closing_bracket(dest, input, ch))
3664 if (!add_till_single_quote(dest, input))
3670 if (!add_till_double_quote(dest, input))
3676 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3682 /* \x. Copy verbatim. Important for \(, \) */
3683 ch = i_getch(input);
3685 syntax_error_unterm_ch(')');
3694 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3696 /* Return code: 0 for OK, 1 for syntax error */
3698 #define parse_dollar(as_string, dest, input, quote_mask) \
3699 parse_dollar(dest, input, quote_mask)
3700 #define as_string NULL
3702 static int parse_dollar(o_string *as_string,
3704 struct in_str *input, unsigned char quote_mask)
3706 int ch = i_peek(input); /* first character after the $ */
3708 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3710 ch = i_getch(input);
3711 nommu_addchr(as_string, ch);
3713 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3715 debug_printf_parse(": '%c'\n", ch);
3716 o_addchr(dest, ch | quote_mask);
3719 if (!isalnum(ch) && ch != '_')
3721 ch = i_getch(input);
3722 nommu_addchr(as_string, ch);
3724 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3725 } else if (isdigit(ch)) {
3727 ch = i_getch(input);
3728 nommu_addchr(as_string, ch);
3729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3730 debug_printf_parse(": '%c'\n", ch);
3731 o_addchr(dest, ch | quote_mask);
3732 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3733 } else switch (ch) {
3735 case '!': /* last bg pid */
3736 case '?': /* last exit code */
3737 case '#': /* number of args */
3738 case '*': /* args */
3739 case '@': /* args */
3740 goto make_one_char_var;
3742 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3744 ch = i_getch(input); /* eat '{' */
3745 nommu_addchr(as_string, ch);
3747 ch = i_getch(input); /* first char after '{' */
3748 /* It should be ${?}, or ${#var},
3749 * or even ${?+subst} - operator acting on a special variable,
3750 * or the beginning of variable name.
3753 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3756 syntax_error_unterm_str("${name}");
3757 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3760 nommu_addchr(as_string, ch);
3763 /* It's possible to just call add_till_closing_bracket() at this point.
3764 * However, this regresses some of our testsuite cases
3765 * which check invalid constructs like ${%}.
3766 * Oh well... let's check that the var name part is fine... */
3772 debug_printf_parse(": '%c'\n", ch);
3774 ch = i_getch(input);
3775 nommu_addchr(as_string, ch);
3779 if (!isalnum(ch) && ch != '_') {
3781 unsigned char last_ch;
3782 /* handle parameter expansions
3783 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3785 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3786 goto bad_dollar_syntax;
3788 /* Eat everything until closing '}' (or ':') */
3790 if (ENABLE_HUSH_BASH_COMPAT
3792 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3794 /* It's ${var:N[:M]} thing */
3795 end_ch = '}' * 0x100 + ':';
3797 if (ENABLE_HUSH_BASH_COMPAT
3800 /* It's ${var/[/]pattern[/repl]} thing */
3801 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3803 nommu_addchr(as_string, '/');
3806 end_ch = '}' * 0x100 + '/';
3812 #if ENABLE_HUSH_DOLLAR_OPS
3813 last_ch = add_till_closing_bracket(dest, input, end_ch);
3814 if (last_ch == 0) /* error? */
3817 #error Simple code to only allow ${var} is not implemented
3820 o_addstr(as_string, dest->data + pos);
3821 o_addchr(as_string, last_ch);
3824 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3825 /* close the first block: */
3826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3827 /* while parsing N from ${var:N[:M]}
3828 * or pattern from ${var/[/]pattern[/repl]} */
3829 if ((end_ch & 0xff) == last_ch) {
3830 /* got ':' or '/'- parse the rest */
3835 if (end_ch == '}' * 0x100 + ':') {
3836 /* it's ${var:N} - emulate :999999999 */
3837 o_addstr(dest, "999999999");
3838 } /* else: it's ${var/[/]pattern} */
3843 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3846 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3850 ch = i_getch(input);
3851 nommu_addchr(as_string, ch);
3852 # if ENABLE_SH_MATH_SUPPORT
3853 if (i_peek(input) == '(') {
3854 ch = i_getch(input);
3855 nommu_addchr(as_string, ch);
3856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3857 o_addchr(dest, /*quote_mask |*/ '+');
3860 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3861 return 0; /* error */
3863 o_addstr(as_string, dest->data + pos);
3864 o_addchr(as_string, ')');
3865 o_addchr(as_string, ')');
3867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3871 # if ENABLE_HUSH_TICK
3872 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3873 o_addchr(dest, quote_mask | '`');
3876 if (!add_till_closing_bracket(dest, input, ')'))
3877 return 0; /* error */
3879 o_addstr(as_string, dest->data + pos);
3880 o_addchr(as_string, ')');
3882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3888 ch = i_getch(input);
3889 nommu_addchr(as_string, ch);
3891 if (isalnum(ch)) { /* it's $_name or $_123 */
3896 /* TODO: $_ and $-: */
3897 /* $_ Shell or shell script name; or last argument of last command
3898 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3899 * but in command's env, set to full pathname used to invoke it */
3900 /* $- Option flags set by set builtin or shell options (-i etc) */
3902 o_addQchr(dest, '$');
3904 debug_printf_parse("parse_dollar return 1 (ok)\n");
3910 # if ENABLE_HUSH_BASH_COMPAT
3911 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3912 encode_string(dest, input, dquote_end, process_bkslash)
3914 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3915 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3916 encode_string(dest, input, dquote_end)
3918 #define as_string NULL
3922 # if ENABLE_HUSH_BASH_COMPAT
3923 /* all parameters are needed, no macro tricks */
3925 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3926 encode_string(as_string, dest, input, dquote_end)
3929 static int encode_string(o_string *as_string,
3931 struct in_str *input,
3933 int process_bkslash)
3935 #if !ENABLE_HUSH_BASH_COMPAT
3936 const int process_bkslash = 1;
3942 ch = i_getch(input);
3944 nommu_addchr(as_string, ch);
3945 if (ch == dquote_end) { /* may be only '"' or EOF */
3946 debug_printf_parse("encode_string return 1 (ok)\n");
3949 /* note: can't move it above ch == dquote_end check! */
3951 syntax_error_unterm_ch('"');
3952 return 0; /* error */
3956 next = i_peek(input);
3958 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3959 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3960 if (process_bkslash && ch == '\\') {
3962 syntax_error("\\<eof>");
3966 * "The backslash retains its special meaning [in "..."]
3967 * only when followed by one of the following characters:
3968 * $, `, ", \, or <newline>. A double quote may be quoted
3969 * within double quotes by preceding it with a backslash."
3970 * NB: in (unquoted) heredoc, above does not apply to ",
3971 * therefore we check for it by "next == dquote_end" cond.
3973 if (next == dquote_end || strchr("$`\\\n", next)) {
3974 ch = i_getch(input); /* eat next */
3976 goto again; /* skip \<newline> */
3977 } /* else: ch remains == '\\', and we double it below: */
3978 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3979 nommu_addchr(as_string, ch);
3983 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
3984 debug_printf_parse("encode_string return 0: "
3985 "parse_dollar returned 0 (error)\n");
3990 #if ENABLE_HUSH_TICK
3992 //unsigned pos = dest->length;
3993 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3994 o_addchr(dest, 0x80 | '`');
3995 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
3996 return 0; /* error */
3997 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3998 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4002 o_addQchr(dest, ch);
4008 * Scan input until EOF or end_trigger char.
4009 * Return a list of pipes to execute, or NULL on EOF
4010 * or if end_trigger character is met.
4011 * On syntax error, exit is shell is not interactive,
4012 * reset parsing machinery and start parsing anew,
4013 * or return ERR_PTR.
4015 static struct pipe *parse_stream(char **pstring,
4016 struct in_str *input,
4019 struct parse_context ctx;
4020 o_string dest = NULL_O_STRING;
4023 /* Single-quote triggers a bypass of the main loop until its mate is
4024 * found. When recursing, quote state is passed in via dest->o_expflags.
4026 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4027 end_trigger ? end_trigger : 'X');
4030 /* If very first arg is "" or '', dest.data may end up NULL.
4031 * Preventing this: */
4032 o_addchr(&dest, '\0');
4035 /* We used to separate words on $IFS here. This was wrong.
4036 * $IFS is used only for word splitting when $var is expanded,
4037 * here we should use blank chars as separators, not $IFS
4040 reset: /* we come back here only on syntax errors in interactive shell */
4042 if (MAYBE_ASSIGNMENT != 0)
4043 dest.o_assignment = MAYBE_ASSIGNMENT;
4044 initialize_context(&ctx);
4047 const char *is_blank;
4048 const char *is_special;
4052 redir_type redir_style;
4054 ch = i_getch(input);
4055 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4056 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4061 syntax_error_unterm_str("here document");
4064 /* end_trigger == '}' case errors out earlier,
4065 * checking only ')' */
4066 if (end_trigger == ')') {
4067 syntax_error_unterm_ch('(');
4071 if (done_word(&dest, &ctx)) {
4075 done_pipe(&ctx, PIPE_SEQ);
4077 /* If we got nothing... */
4078 /* (this makes bare "&" cmd a no-op.
4079 * bash says: "syntax error near unexpected token '&'") */
4080 if (pi->num_cmds == 0
4081 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4087 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4089 *pstring = ctx.as_string.data;
4091 o_free_unsafe(&ctx.as_string);
4094 debug_printf_parse("parse_stream return %p\n", pi);
4097 nommu_addchr(&ctx.as_string, ch);
4101 next = i_peek(input);
4103 is_special = "{}<>;&|()#'" /* special outside of "str" */
4104 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4105 /* Are { and } special here? */
4106 if (ctx.command->argv /* word [word]{... - non-special */
4107 || dest.length /* word{... - non-special */
4108 || dest.has_quoted_part /* ""{... - non-special */
4109 || (next != ';' /* }; - special */
4110 && next != ')' /* }) - special */
4111 && next != '&' /* }& and }&& ... - special */
4112 && next != '|' /* }|| ... - special */
4113 && !strchr(defifs, next) /* {word - non-special */
4116 /* They are not special, skip "{}" */
4119 is_special = strchr(is_special, ch);
4120 is_blank = strchr(defifs, ch);
4122 if (!is_special && !is_blank) { /* ordinary char */
4124 o_addQchr(&dest, ch);
4125 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4126 || dest.o_assignment == WORD_IS_KEYWORD)
4128 && is_well_formed_var_name(dest.data, '=')
4130 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4136 if (done_word(&dest, &ctx)) {
4140 /* Is this a case when newline is simply ignored?
4142 * "cmd | <newline> cmd ..."
4143 * "case ... in <newline> word) ..."
4145 if (IS_NULL_CMD(ctx.command)
4146 && dest.length == 0 && !dest.has_quoted_part
4148 /* This newline can be ignored. But...
4149 * Without check #1, interactive shell
4150 * ignores even bare <newline>,
4151 * and shows the continuation prompt:
4152 * ps1_prompt$ <enter>
4153 * ps2> _ <=== wrong, should be ps1
4154 * Without check #2, "cmd & <newline>"
4155 * is similarly mistreated.
4156 * (BTW, this makes "cmd & cmd"
4157 * and "cmd && cmd" non-orthogonal.
4158 * Really, ask yourself, why
4159 * "cmd && <newline>" doesn't start
4160 * cmd but waits for more input?
4163 struct pipe *pi = ctx.list_head;
4164 if (pi->num_cmds != 0 /* check #1 */
4165 && pi->followup != PIPE_BG /* check #2 */
4170 /* Treat newline as a command separator. */
4171 done_pipe(&ctx, PIPE_SEQ);
4172 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4174 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4179 dest.o_assignment = MAYBE_ASSIGNMENT;
4181 /* note: if (is_blank) continue;
4182 * will still trigger for us */
4186 /* "cmd}" or "cmd }..." without semicolon or &:
4187 * } is an ordinary char in this case, even inside { cmd; }
4188 * Pathological example: { ""}; } should exec "}" cmd
4191 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4192 || dest.length != 0 /* word} */
4193 || dest.has_quoted_part /* ""} */
4197 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4198 goto skip_end_trigger;
4199 /* else: } does terminate a group */
4202 if (end_trigger && end_trigger == ch
4203 && (ch != ';' || heredoc_cnt == 0)
4204 #if ENABLE_HUSH_CASE
4206 || ctx.ctx_res_w != RES_MATCH
4207 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4212 /* This is technically valid:
4213 * { cat <<HERE; }; echo Ok
4217 * but we don't support this.
4218 * We require heredoc to be in enclosing {}/(),
4221 syntax_error_unterm_str("here document");
4224 if (done_word(&dest, &ctx)) {
4227 done_pipe(&ctx, PIPE_SEQ);
4228 dest.o_assignment = MAYBE_ASSIGNMENT;
4229 /* Do we sit outside of any if's, loops or case's? */
4231 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4235 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4237 *pstring = ctx.as_string.data;
4239 o_free_unsafe(&ctx.as_string);
4242 debug_printf_parse("parse_stream return %p: "
4243 "end_trigger char found\n",
4245 return ctx.list_head;
4252 /* Catch <, > before deciding whether this word is
4253 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4256 redir_fd = redirect_opt_num(&dest);
4257 if (done_word(&dest, &ctx)) {
4260 redir_style = REDIRECT_OVERWRITE;
4262 redir_style = REDIRECT_APPEND;
4263 ch = i_getch(input);
4264 nommu_addchr(&ctx.as_string, ch);
4267 else if (next == '(') {
4268 syntax_error(">(process) not supported");
4272 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4274 continue; /* back to top of while (1) */
4276 redir_fd = redirect_opt_num(&dest);
4277 if (done_word(&dest, &ctx)) {
4280 redir_style = REDIRECT_INPUT;
4282 redir_style = REDIRECT_HEREDOC;
4284 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4285 ch = i_getch(input);
4286 nommu_addchr(&ctx.as_string, ch);
4287 } else if (next == '>') {
4288 redir_style = REDIRECT_IO;
4289 ch = i_getch(input);
4290 nommu_addchr(&ctx.as_string, ch);
4293 else if (next == '(') {
4294 syntax_error("<(process) not supported");
4298 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4300 continue; /* back to top of while (1) */
4302 if (dest.length == 0 && !dest.has_quoted_part) {
4303 /* skip "#comment" */
4306 if (ch == EOF || ch == '\n')
4309 /* note: we do not add it to &ctx.as_string */
4311 nommu_addchr(&ctx.as_string, '\n');
4312 continue; /* back to top of while (1) */
4317 /* It's "\<newline>" */
4319 /* Remove trailing '\' from ctx.as_string */
4320 ctx.as_string.data[--ctx.as_string.length] = '\0';
4322 ch = i_getch(input); /* eat it */
4323 continue; /* back to top of while (1) */
4328 if (dest.o_assignment == MAYBE_ASSIGNMENT
4329 /* check that we are not in word in "a=1 2>word b=1": */
4330 && !ctx.pending_redirect
4332 /* ch is a special char and thus this word
4333 * cannot be an assignment */
4334 dest.o_assignment = NOT_ASSIGNMENT;
4337 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4340 case '#': /* non-comment #: "echo a#b" etc */
4341 o_addQchr(&dest, ch);
4345 syntax_error("\\<eof>");
4348 ch = i_getch(input);
4349 /* note: ch != '\n' (that case does not reach this place) */
4350 o_addchr(&dest, '\\');
4351 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4352 o_addchr(&dest, ch);
4353 nommu_addchr(&ctx.as_string, ch);
4354 /* Example: echo Hello \2>file
4355 * we need to know that word 2 is quoted */
4356 dest.has_quoted_part = 1;
4359 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4360 debug_printf_parse("parse_stream parse error: "
4361 "parse_dollar returned 0 (error)\n");
4366 dest.has_quoted_part = 1;
4368 ch = i_getch(input);
4370 syntax_error_unterm_ch('\'');
4373 nommu_addchr(&ctx.as_string, ch);
4376 o_addqchr(&dest, ch);
4380 dest.has_quoted_part = 1;
4381 if (dest.o_assignment == NOT_ASSIGNMENT)
4382 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4383 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4385 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4387 #if ENABLE_HUSH_TICK
4391 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4392 o_addchr(&dest, '`');
4394 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4397 o_addstr(&ctx.as_string, dest.data + pos);
4398 o_addchr(&ctx.as_string, '`');
4400 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4401 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4406 #if ENABLE_HUSH_CASE
4409 if (done_word(&dest, &ctx)) {
4412 done_pipe(&ctx, PIPE_SEQ);
4413 #if ENABLE_HUSH_CASE
4414 /* Eat multiple semicolons, detect
4415 * whether it means something special */
4420 ch = i_getch(input);
4421 nommu_addchr(&ctx.as_string, ch);
4422 if (ctx.ctx_res_w == RES_CASE_BODY) {
4423 ctx.ctx_dsemicolon = 1;
4424 ctx.ctx_res_w = RES_MATCH;
4430 /* We just finished a cmd. New one may start
4431 * with an assignment */
4432 dest.o_assignment = MAYBE_ASSIGNMENT;
4435 if (done_word(&dest, &ctx)) {
4439 ch = i_getch(input);
4440 nommu_addchr(&ctx.as_string, ch);
4441 done_pipe(&ctx, PIPE_AND);
4443 done_pipe(&ctx, PIPE_BG);
4447 if (done_word(&dest, &ctx)) {
4450 #if ENABLE_HUSH_CASE
4451 if (ctx.ctx_res_w == RES_MATCH)
4452 break; /* we are in case's "word | word)" */
4454 if (next == '|') { /* || */
4455 ch = i_getch(input);
4456 nommu_addchr(&ctx.as_string, ch);
4457 done_pipe(&ctx, PIPE_OR);
4459 /* we could pick up a file descriptor choice here
4460 * with redirect_opt_num(), but bash doesn't do it.
4461 * "echo foo 2| cat" yields "foo 2". */
4464 o_reset_to_empty_unquoted(&ctx.as_string);
4469 #if ENABLE_HUSH_CASE
4470 /* "case... in [(]word)..." - skip '(' */
4471 if (ctx.ctx_res_w == RES_MATCH
4472 && ctx.command->argv == NULL /* not (word|(... */
4473 && dest.length == 0 /* not word(... */
4474 && dest.has_quoted_part == 0 /* not ""(... */
4480 if (parse_group(&dest, &ctx, input, ch) != 0) {
4485 #if ENABLE_HUSH_CASE
4486 if (ctx.ctx_res_w == RES_MATCH)
4490 /* proper use of this character is caught by end_trigger:
4491 * if we see {, we call parse_group(..., end_trigger='}')
4492 * and it will match } earlier (not here). */
4493 syntax_error_unexpected_ch(ch);
4497 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4503 struct parse_context *pctx;
4504 IF_HAS_KEYWORDS(struct parse_context *p2;)
4506 /* Clean up allocated tree.
4507 * Sample for finding leaks on syntax error recovery path.
4508 * Run it from interactive shell, watch pmap `pidof hush`.
4509 * while if false; then false; fi; do break; fi
4510 * Samples to catch leaks at execution:
4511 * while if (true | {true;}); then echo ok; fi; do break; done
4512 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4516 /* Update pipe/command counts,
4517 * otherwise freeing may miss some */
4518 done_pipe(pctx, PIPE_SEQ);
4519 debug_printf_clean("freeing list %p from ctx %p\n",
4520 pctx->list_head, pctx);
4521 debug_print_tree(pctx->list_head, 0);
4522 free_pipe_list(pctx->list_head);
4523 debug_printf_clean("freed list %p\n", pctx->list_head);
4525 o_free_unsafe(&pctx->as_string);
4527 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4531 IF_HAS_KEYWORDS(pctx = p2;)
4532 } while (HAS_KEYWORDS && pctx);
4533 /* Free text, clear all dest fields */
4535 /* If we are not in top-level parse, we return,
4536 * our caller will propagate error.
4538 if (end_trigger != ';') {
4546 /* Discard cached input, force prompt */
4553 /*** Execution routines ***/
4555 /* Expansion can recurse, need forward decls: */
4556 #if !ENABLE_HUSH_BASH_COMPAT
4557 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4558 #define expand_string_to_string(str, do_unbackslash) \
4559 expand_string_to_string(str)
4561 static char *expand_string_to_string(const char *str, int do_unbackslash);
4562 #if ENABLE_HUSH_TICK
4563 static int process_command_subs(o_string *dest, const char *s);
4566 /* expand_strvec_to_strvec() takes a list of strings, expands
4567 * all variable references within and returns a pointer to
4568 * a list of expanded strings, possibly with larger number
4569 * of strings. (Think VAR="a b"; echo $VAR).
4570 * This new list is allocated as a single malloc block.
4571 * NULL-terminated list of char* pointers is at the beginning of it,
4572 * followed by strings themselves.
4573 * Caller can deallocate entire list by single free(list). */
4575 /* A horde of its helpers come first: */
4577 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4579 while (--len >= 0) {
4582 #if ENABLE_HUSH_BRACE_EXPANSION
4583 if (c == '{' || c == '}') {
4584 /* { -> \{, } -> \} */
4586 /* And now we want to add { or } and continue:
4589 * luckily, just falling throught achieves this.
4595 /* \z -> \\\z; \<eol> -> \\<eol> */
4600 o_addchr(o, *str++);
4606 /* Store given string, finalizing the word and starting new one whenever
4607 * we encounter IFS char(s). This is used for expanding variable values.
4608 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4609 static int expand_on_ifs(o_string *output, int n, const char *str)
4612 int word_len = strcspn(str, G.ifs);
4614 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4615 o_addblock(output, str, word_len);
4617 /* Protect backslashes against globbing up :)
4618 * Example: "v='\*'; echo b$v" prints "b\*"
4619 * (and does not try to glob on "*")
4621 o_addblock_duplicate_backslash(output, str, word_len);
4622 /*/ Why can't we do it easier? */
4623 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4624 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4628 if (!*str) /* EOL - do not finalize word */
4630 o_addchr(output, '\0');
4631 debug_print_list("expand_on_ifs", output, n);
4632 n = o_save_ptr(output, n);
4633 str += strspn(str, G.ifs); /* skip ifs chars */
4635 debug_print_list("expand_on_ifs[1]", output, n);
4639 /* Helper to expand $((...)) and heredoc body. These act as if
4640 * they are in double quotes, with the exception that they are not :).
4641 * Just the rules are similar: "expand only $var and `cmd`"
4643 * Returns malloced string.
4644 * As an optimization, we return NULL if expansion is not needed.
4646 #if !ENABLE_HUSH_BASH_COMPAT
4647 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4648 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4649 encode_then_expand_string(str)
4651 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4654 struct in_str input;
4655 o_string dest = NULL_O_STRING;
4657 if (!strchr(str, '$')
4658 && !strchr(str, '\\')
4659 #if ENABLE_HUSH_TICK
4660 && !strchr(str, '`')
4666 /* We need to expand. Example:
4667 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4669 setup_string_in_str(&input, str);
4670 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4671 //TODO: error check (encode_string returns 0 on error)?
4672 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4673 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4674 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4675 o_free_unsafe(&dest);
4679 #if ENABLE_SH_MATH_SUPPORT
4680 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4682 arith_state_t math_state;
4686 math_state.lookupvar = get_local_var_value;
4687 math_state.setvar = set_local_var_from_halves;
4688 //math_state.endofname = endofname;
4689 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4690 res = arith(&math_state, exp_str ? exp_str : arg);
4693 *errmsg_p = math_state.errmsg;
4694 if (math_state.errmsg)
4695 die_if_script(math_state.errmsg);
4700 #if ENABLE_HUSH_BASH_COMPAT
4701 /* ${var/[/]pattern[/repl]} helpers */
4702 static char *strstr_pattern(char *val, const char *pattern, int *size)
4705 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4706 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4713 /* Optimization: if "*pat" did not match the start of "string",
4714 * we know that "tring", "ring" etc will not match too:
4716 if (pattern[0] == '*')
4721 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4723 char *result = NULL;
4724 unsigned res_len = 0;
4725 unsigned repl_len = strlen(repl);
4729 char *s = strstr_pattern(val, pattern, &size);
4733 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4734 memcpy(result + res_len, val, s - val);
4736 strcpy(result + res_len, repl);
4737 res_len += repl_len;
4738 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4744 if (val[0] && result) {
4745 result = xrealloc(result, res_len + strlen(val) + 1);
4746 strcpy(result + res_len, val);
4747 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4749 debug_printf_varexp("result:'%s'\n", result);
4755 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4757 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4759 const char *val = NULL;
4760 char *to_be_freed = NULL;
4765 char exp_save = exp_save; /* for compiler */
4766 char *exp_saveptr; /* points to expansion operator */
4767 char *exp_word = exp_word; /* for compiler */
4770 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4772 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4774 first_char = arg[0] = arg0 & 0x7f;
4777 if (first_char == '#' /* ${#... */
4778 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4780 /* It must be length operator: ${#var} */
4784 /* Maybe handle parameter expansion */
4785 if (exp_saveptr /* if 2nd char is one of expansion operators */
4786 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4788 /* ${?:0}, ${#[:]%0} etc */
4789 exp_saveptr = var + 1;
4791 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4792 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4794 exp_op = exp_save = *exp_saveptr;
4796 exp_word = exp_saveptr + 1;
4797 if (exp_op == ':') {
4798 exp_op = *exp_word++;
4799 //TODO: try ${var:} and ${var:bogus} in non-bash config
4800 if (ENABLE_HUSH_BASH_COMPAT
4801 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4803 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4808 *exp_saveptr = '\0';
4809 } /* else: it's not an expansion op, but bare ${var} */
4812 /* Look up the variable in question */
4813 if (isdigit(var[0])) {
4814 /* parse_dollar should have vetted var for us */
4815 int n = xatoi_positive(var);
4816 if (n < G.global_argc)
4817 val = G.global_argv[n];
4818 /* else val remains NULL: $N with too big N */
4822 val = utoa(G.root_pid);
4824 case '!': /* bg pid */
4825 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4827 case '?': /* exitcode */
4828 val = utoa(G.last_exitcode);
4830 case '#': /* argc */
4831 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4834 val = get_local_var_value(var);
4838 /* Handle any expansions */
4839 if (exp_op == 'L') {
4840 debug_printf_expand("expand: length(%s)=", val);
4841 val = utoa(val ? strlen(val) : 0);
4842 debug_printf_expand("%s\n", val);
4843 } else if (exp_op) {
4844 if (exp_op == '%' || exp_op == '#') {
4845 /* Standard-mandated substring removal ops:
4846 * ${parameter%word} - remove smallest suffix pattern
4847 * ${parameter%%word} - remove largest suffix pattern
4848 * ${parameter#word} - remove smallest prefix pattern
4849 * ${parameter##word} - remove largest prefix pattern
4851 * Word is expanded to produce a glob pattern.
4852 * Then var's value is matched to it and matching part removed.
4854 if (val && val[0]) {
4858 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4859 if (exp_op == *exp_word) /* ## or %% */
4861 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4863 exp_word = exp_exp_word;
4864 /* HACK ALERT. We depend here on the fact that
4865 * G.global_argv and results of utoa and get_local_var_value
4866 * are actually in writable memory:
4867 * scan_and_match momentarily stores NULs there. */
4869 loc = scan_and_match(t, exp_word, scan_flags);
4870 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4871 // exp_op, t, exp_word, loc);
4873 if (loc) { /* match was found */
4874 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4875 val = loc; /* take right part */
4877 val = to_be_freed = xstrndup(val, loc - val); /* left */
4881 #if ENABLE_HUSH_BASH_COMPAT
4882 else if (exp_op == '/' || exp_op == '\\') {
4883 /* It's ${var/[/]pattern[/repl]} thing.
4884 * Note that in encoded form it has TWO parts:
4885 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4886 * and if // is used, it is encoded as \:
4887 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4889 /* Empty variable always gives nothing: */
4890 // "v=''; echo ${v/*/w}" prints "", not "w"
4891 if (val && val[0]) {
4892 /* pattern uses non-standard expansion.
4893 * repl should be unbackslashed and globbed
4894 * by the usual expansion rules:
4896 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4897 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4898 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4899 * v='a bz'; echo ${v/a*z/\z} prints "z"
4900 * (note that a*z _pattern_ is never globbed!)
4902 char *pattern, *repl, *t;
4903 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4905 pattern = xstrdup(exp_word);
4906 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4907 *p++ = SPECIAL_VAR_SYMBOL;
4909 p = strchr(p, SPECIAL_VAR_SYMBOL);
4911 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4912 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4913 /* HACK ALERT. We depend here on the fact that
4914 * G.global_argv and results of utoa and get_local_var_value
4915 * are actually in writable memory:
4916 * replace_pattern momentarily stores NULs there. */
4918 to_be_freed = replace_pattern(t,
4920 (repl ? repl : exp_word),
4922 if (to_be_freed) /* at least one replace happened */
4929 else if (exp_op == ':') {
4930 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4931 /* It's ${var:N[:M]} bashism.
4932 * Note that in encoded form it has TWO parts:
4933 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4938 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4941 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4942 *p++ = SPECIAL_VAR_SYMBOL;
4944 p = strchr(p, SPECIAL_VAR_SYMBOL);
4946 len = expand_and_evaluate_arith(exp_word, &errmsg);
4949 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4950 if (len >= 0) { /* bash compat: len < 0 is illegal */
4951 if (beg < 0) /* bash compat */
4953 debug_printf_varexp("from val:'%s'\n", val);
4954 if (len == 0 || !val || beg >= strlen(val)) {
4958 /* Paranoia. What if user entered 9999999999999
4959 * which fits in arith_t but not int? */
4962 val = to_be_freed = xstrndup(val + beg, len);
4964 debug_printf_varexp("val:'%s'\n", val);
4968 die_if_script("malformed ${%s:...}", var);
4971 } else { /* one of "-=+?" */
4972 /* Standard-mandated substitution ops:
4973 * ${var?word} - indicate error if unset
4974 * If var is unset, word (or a message indicating it is unset
4975 * if word is null) is written to standard error
4976 * and the shell exits with a non-zero exit status.
4977 * Otherwise, the value of var is substituted.
4978 * ${var-word} - use default value
4979 * If var is unset, word is substituted.
4980 * ${var=word} - assign and use default value
4981 * If var is unset, word is assigned to var.
4982 * In all cases, final value of var is substituted.
4983 * ${var+word} - use alternative value
4984 * If var is unset, null is substituted.
4985 * Otherwise, word is substituted.
4987 * Word is subjected to tilde expansion, parameter expansion,
4988 * command substitution, and arithmetic expansion.
4989 * If word is not needed, it is not expanded.
4991 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4992 * but also treat null var as if it is unset.
4994 int use_word = (!val || ((exp_save == ':') && !val[0]));
4996 use_word = !use_word;
4997 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4998 (exp_save == ':') ? "true" : "false", use_word);
5000 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5002 exp_word = to_be_freed;
5003 if (exp_op == '?') {
5004 /* mimic bash message */
5005 die_if_script("%s: %s",
5007 exp_word[0] ? exp_word : "parameter null or not set"
5009 //TODO: how interactive bash aborts expansion mid-command?
5014 if (exp_op == '=') {
5015 /* ${var=[word]} or ${var:=[word]} */
5016 if (isdigit(var[0]) || var[0] == '#') {
5017 /* mimic bash message */
5018 die_if_script("$%s: cannot assign in this way", var);
5021 char *new_var = xasprintf("%s=%s", var, val);
5022 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5026 } /* one of "-=+?" */
5028 *exp_saveptr = exp_save;
5034 *to_be_freed_pp = to_be_freed;
5038 /* Expand all variable references in given string, adding words to list[]
5039 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5040 * to be filled). This routine is extremely tricky: has to deal with
5041 * variables/parameters with whitespace, $* and $@, and constructs like
5042 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5043 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5045 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5046 * expansion of right-hand side of assignment == 1-element expand.
5048 char cant_be_null = 0; /* only bit 0x80 matters */
5051 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5052 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5053 debug_print_list("expand_vars_to_list", output, n);
5054 n = o_save_ptr(output, n);
5055 debug_print_list("expand_vars_to_list[0]", output, n);
5057 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5059 char *to_be_freed = NULL;
5060 const char *val = NULL;
5061 #if ENABLE_HUSH_TICK
5062 o_string subst_result = NULL_O_STRING;
5064 #if ENABLE_SH_MATH_SUPPORT
5065 char arith_buf[sizeof(arith_t)*3 + 2];
5067 o_addblock(output, arg, p - arg);
5068 debug_print_list("expand_vars_to_list[1]", output, n);
5070 p = strchr(p, SPECIAL_VAR_SYMBOL);
5072 /* Fetch special var name (if it is indeed one of them)
5073 * and quote bit, force the bit on if singleword expansion -
5074 * important for not getting v=$@ expand to many words. */
5075 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5077 /* Is this variable quoted and thus expansion can't be null?
5078 * "$@" is special. Even if quoted, it can still
5079 * expand to nothing (not even an empty string),
5080 * thus it is excluded. */
5081 if ((first_ch & 0x7f) != '@')
5082 cant_be_null |= first_ch;
5084 switch (first_ch & 0x7f) {
5085 /* Highest bit in first_ch indicates that var is double-quoted */
5089 if (!G.global_argv[1])
5092 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5093 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5094 while (G.global_argv[i]) {
5095 n = expand_on_ifs(output, n, G.global_argv[i]);
5096 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5097 if (G.global_argv[i++][0] && G.global_argv[i]) {
5098 /* this argv[] is not empty and not last:
5099 * put terminating NUL, start new word */
5100 o_addchr(output, '\0');
5101 debug_print_list("expand_vars_to_list[2]", output, n);
5102 n = o_save_ptr(output, n);
5103 debug_print_list("expand_vars_to_list[3]", output, n);
5107 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5108 * and in this case should treat it like '$*' - see 'else...' below */
5109 if (first_ch == ('@'|0x80) /* quoted $@ */
5110 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5113 o_addQstr(output, G.global_argv[i]);
5114 if (++i >= G.global_argc)
5116 o_addchr(output, '\0');
5117 debug_print_list("expand_vars_to_list[4]", output, n);
5118 n = o_save_ptr(output, n);
5120 } else { /* quoted $* (or v="$@" case): add as one word */
5122 o_addQstr(output, G.global_argv[i]);
5123 if (!G.global_argv[++i])
5126 o_addchr(output, G.ifs[0]);
5131 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5132 /* "Empty variable", used to make "" etc to not disappear */
5134 cant_be_null = 0x80;
5136 #if ENABLE_HUSH_TICK
5137 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5138 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5140 /* Can't just stuff it into output o_string,
5141 * expanded result may need to be globbed
5142 * and $IFS-splitted */
5143 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5144 G.last_exitcode = process_command_subs(&subst_result, arg);
5145 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5146 val = subst_result.data;
5149 #if ENABLE_SH_MATH_SUPPORT
5150 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5153 arg++; /* skip '+' */
5154 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5155 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5156 res = expand_and_evaluate_arith(arg, NULL);
5157 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5158 sprintf(arith_buf, ARITH_FMT, res);
5164 val = expand_one_var(&to_be_freed, arg, &p);
5165 IF_HUSH_TICK(store_val:)
5166 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5167 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5168 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5169 if (val && val[0]) {
5170 n = expand_on_ifs(output, n, val);
5173 } else { /* quoted $VAR, val will be appended below */
5174 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5175 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5179 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5181 if (val && val[0]) {
5182 o_addQstr(output, val);
5186 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5187 * Do the check to avoid writing to a const string. */
5188 if (*p != SPECIAL_VAR_SYMBOL)
5189 *p = SPECIAL_VAR_SYMBOL;
5191 #if ENABLE_HUSH_TICK
5192 o_free(&subst_result);
5195 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5198 debug_print_list("expand_vars_to_list[a]", output, n);
5199 /* this part is literal, and it was already pre-quoted
5200 * if needed (much earlier), do not use o_addQstr here! */
5201 o_addstr_with_NUL(output, arg);
5202 debug_print_list("expand_vars_to_list[b]", output, n);
5203 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5204 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5207 /* allow to reuse list[n] later without re-growth */
5208 output->has_empty_slot = 1;
5210 o_addchr(output, '\0');
5216 static char **expand_variables(char **argv, unsigned expflags)
5220 o_string output = NULL_O_STRING;
5222 output.o_expflags = expflags;
5226 n = expand_vars_to_list(&output, n, *argv);
5229 debug_print_list("expand_variables", &output, n);
5231 /* output.data (malloced in one block) gets returned in "list" */
5232 list = o_finalize_list(&output, n);
5233 debug_print_strings("expand_variables[1]", list);
5237 static char **expand_strvec_to_strvec(char **argv)
5239 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5242 #if ENABLE_HUSH_BASH_COMPAT
5243 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5245 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5249 /* Used for expansion of right hand of assignments,
5250 * $((...)), heredocs, variable espansion parts.
5252 * NB: should NOT do globbing!
5253 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5255 static char *expand_string_to_string(const char *str, int do_unbackslash)
5257 #if !ENABLE_HUSH_BASH_COMPAT
5258 const int do_unbackslash = 1;
5260 char *argv[2], **list;
5262 debug_printf_expand("string_to_string<='%s'\n", str);
5263 /* This is generally an optimization, but it also
5264 * handles "", which otherwise trips over !list[0] check below.
5265 * (is this ever happens that we actually get str="" here?)
5267 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5268 //TODO: Can use on strings with \ too, just unbackslash() them?
5269 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5270 return xstrdup(str);
5273 argv[0] = (char*)str;
5275 list = expand_variables(argv, do_unbackslash
5276 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5277 : EXP_FLAG_SINGLEWORD
5280 if (!list[0] || list[1])
5281 bb_error_msg_and_die("BUG in varexp2");
5282 /* actually, just move string 2*sizeof(char*) bytes back */
5283 overlapping_strcpy((char*)list, list[0]);
5285 unbackslash((char*)list);
5286 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5290 /* Used for "eval" builtin */
5291 static char* expand_strvec_to_string(char **argv)
5295 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5296 /* Convert all NULs to spaces */
5301 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5302 bb_error_msg_and_die("BUG in varexp3");
5303 /* bash uses ' ' regardless of $IFS contents */
5308 overlapping_strcpy((char*)list, list[0]);
5309 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5313 static char **expand_assignments(char **argv, int count)
5318 G.expanded_assignments = p = NULL;
5319 /* Expand assignments into one string each */
5320 for (i = 0; i < count; i++) {
5321 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5323 G.expanded_assignments = NULL;
5330 void re_execute_shell(char ***to_free, const char *s,
5331 char *g_argv0, char **g_argv,
5332 char **builtin_argv) NORETURN;
5334 static void reset_traps_to_defaults(void)
5336 /* This function is always called in a child shell
5337 * after fork (not vfork, NOMMU doesn't use this function).
5342 /* Child shells are not interactive.
5343 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5344 * Testcase: (while :; do :; done) + ^Z should background.
5345 * Same goes for SIGTERM, SIGHUP, SIGINT.
5347 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5348 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5350 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5351 * Stupid. It can be done with *single* &= op, but we can't use
5352 * the fact that G.blocked_set is implemented as a bitmask
5354 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5358 /* Careful. Only if no trap or trap is not "" */
5359 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5360 sigdelset(&G.blocked_set, sig);
5367 /* Our homegrown sig mask is saner to work with :) */
5368 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5370 /* Resetting all traps to default except empty ones */
5371 mask = G.non_DFL_mask;
5372 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5373 if (!G.traps[sig] || !G.traps[sig][0])
5376 G.traps[sig] = NULL;
5377 /* There is no signal for 0 (EXIT) */
5380 /* There was a trap handler, we just removed it.
5381 * But if sig still has non-DFL handling,
5382 * we should not unblock the sig. */
5385 sigdelset(&G.blocked_set, sig);
5387 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5392 static void re_execute_shell(char ***to_free, const char *s,
5393 char *g_argv0, char **g_argv,
5394 char **builtin_argv) NORETURN;
5395 static void re_execute_shell(char ***to_free, const char *s,
5396 char *g_argv0, char **g_argv,
5397 char **builtin_argv)
5399 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5400 /* delims + 2 * (number of bytes in printed hex numbers) */
5401 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5402 char *heredoc_argv[4];
5403 struct variable *cur;
5404 # if ENABLE_HUSH_FUNCTIONS
5405 struct function *funcp;
5409 unsigned long long empty_trap_mask;
5411 if (!g_argv0) { /* heredoc */
5412 argv = heredoc_argv;
5413 argv[0] = (char *) G.argv0_for_re_execing;
5414 argv[1] = (char *) "-<";
5415 argv[2] = (char *) s;
5417 pp = &argv[3]; /* used as pointer to empty environment */
5423 if (pp) while (*pp++)
5426 empty_trap_mask = 0;
5429 for (sig = 1; sig < NSIG; sig++) {
5430 if (G.traps[sig] && !G.traps[sig][0])
5431 empty_trap_mask |= 1LL << sig;
5435 sprintf(param_buf, NOMMU_HACK_FMT
5436 , (unsigned) G.root_pid
5437 , (unsigned) G.root_ppid
5438 , (unsigned) G.last_bg_pid
5439 , (unsigned) G.last_exitcode
5442 IF_HUSH_LOOPS(, G.depth_of_loop)
5444 # undef NOMMU_HACK_FMT
5445 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5446 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5449 for (cur = G.top_var; cur; cur = cur->next) {
5450 if (!cur->flg_export || cur->flg_read_only)
5453 # if ENABLE_HUSH_FUNCTIONS
5454 for (funcp = G.top_func; funcp; funcp = funcp->next)
5460 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5461 *pp++ = (char *) G.argv0_for_re_execing;
5463 for (cur = G.top_var; cur; cur = cur->next) {
5464 if (strcmp(cur->varstr, hush_version_str) == 0)
5466 if (cur->flg_read_only) {
5467 *pp++ = (char *) "-R";
5468 *pp++ = cur->varstr;
5469 } else if (!cur->flg_export) {
5470 *pp++ = (char *) "-V";
5471 *pp++ = cur->varstr;
5474 # if ENABLE_HUSH_FUNCTIONS
5475 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5476 *pp++ = (char *) "-F";
5477 *pp++ = funcp->name;
5478 *pp++ = funcp->body_as_string;
5481 /* We can pass activated traps here. Say, -Tnn:trap_string
5483 * However, POSIX says that subshells reset signals with traps
5485 * I tested bash-3.2 and it not only does that with true subshells
5486 * of the form ( list ), but with any forked children shells.
5487 * I set trap "echo W" WINCH; and then tried:
5489 * { echo 1; sleep 20; echo 2; } &
5490 * while true; do echo 1; sleep 20; echo 2; break; done &
5491 * true | { echo 1; sleep 20; echo 2; } | cat
5493 * In all these cases sending SIGWINCH to the child shell
5494 * did not run the trap. If I add trap "echo V" WINCH;
5495 * _inside_ group (just before echo 1), it works.
5497 * I conclude it means we don't need to pass active traps here.
5498 * Even if we would use signal handlers instead of signal masking
5499 * in order to implement trap handling,
5500 * exec syscall below resets signals to SIG_DFL for us.
5502 *pp++ = (char *) "-c";
5505 while (*++builtin_argv)
5506 *pp++ = *builtin_argv;
5507 *pp++ = (char *) "";
5512 /* *pp = NULL; - is already there */
5516 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5517 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5518 execve(bb_busybox_exec_path, argv, pp);
5519 /* Fallback. Useful for init=/bin/hush usage etc */
5520 if (argv[0][0] == '/')
5521 execve(argv[0], argv, pp);
5522 xfunc_error_retval = 127;
5523 bb_error_msg_and_die("can't re-execute the shell");
5525 #endif /* !BB_MMU */
5528 static int run_and_free_list(struct pipe *pi);
5530 /* Executing from string: eval, sh -c '...'
5531 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5532 * end_trigger controls how often we stop parsing
5533 * NUL: parse all, execute, return
5534 * ';': parse till ';' or newline, execute, repeat till EOF
5536 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5538 /* Why we need empty flag?
5539 * An obscure corner case "false; ``; echo $?":
5540 * empty command in `` should still set $? to 0.
5541 * But we can't just set $? to 0 at the start,
5542 * this breaks "false; echo `echo $?`" case.
5546 struct pipe *pipe_list;
5548 #if ENABLE_HUSH_INTERACTIVE
5549 if (end_trigger == ';')
5550 inp->promptmode = 0; /* PS1 */
5552 pipe_list = parse_stream(NULL, inp, end_trigger);
5553 if (!pipe_list) { /* EOF */
5555 G.last_exitcode = 0;
5558 debug_print_tree(pipe_list, 0);
5559 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5560 run_and_free_list(pipe_list);
5562 #if ENABLE_HUSH_FUNCTIONS
5563 if (G.flag_return_in_progress == 1)
5569 static void parse_and_run_string(const char *s)
5571 struct in_str input;
5572 setup_string_in_str(&input, s);
5573 parse_and_run_stream(&input, '\0');
5576 static void parse_and_run_file(FILE *f)
5578 struct in_str input;
5579 setup_file_in_str(&input, f);
5580 parse_and_run_stream(&input, ';');
5583 #if ENABLE_HUSH_TICK
5584 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5589 char **to_free = NULL;
5593 pid = BB_MMU ? xfork() : xvfork();
5594 if (pid == 0) { /* child */
5595 disable_restore_tty_pgrp_on_exit();
5596 /* Process substitution is not considered to be usual
5597 * 'command execution'.
5598 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5605 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5606 close(channel[0]); /* NB: close _first_, then move fd! */
5607 xmove_fd(channel[1], 1);
5608 /* Prevent it from trying to handle ctrl-z etc */
5609 IF_HUSH_JOB(G.run_list_level = 1;)
5610 /* Awful hack for `trap` or $(trap).
5612 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5613 * contains an example where "trap" is executed in a subshell:
5615 * save_traps=$(trap)
5617 * eval "$save_traps"
5619 * Standard does not say that "trap" in subshell shall print
5620 * parent shell's traps. It only says that its output
5621 * must have suitable form, but then, in the above example
5622 * (which is not supposed to be normative), it implies that.
5624 * bash (and probably other shell) does implement it
5625 * (traps are reset to defaults, but "trap" still shows them),
5626 * but as a result, "trap" logic is hopelessly messed up:
5629 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5630 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5631 * # true | trap <--- trap is in subshell - no output (ditto)
5632 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5633 * trap -- 'echo Ho' SIGWINCH
5634 * # echo `(trap)` <--- in subshell in subshell - output
5635 * trap -- 'echo Ho' SIGWINCH
5636 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5637 * trap -- 'echo Ho' SIGWINCH
5639 * The rules when to forget and when to not forget traps
5640 * get really complex and nonsensical.
5642 * Our solution: ONLY bare $(trap) or `trap` is special.
5644 s = skip_whitespace(s);
5645 if (strncmp(s, "trap", 4) == 0
5646 && skip_whitespace(s + 4)[0] == '\0'
5648 static const char *const argv[] = { NULL, NULL };
5649 builtin_trap((char**)argv);
5650 exit(0); /* not _exit() - we need to fflush */
5653 reset_traps_to_defaults();
5654 parse_and_run_string(s);
5655 _exit(G.last_exitcode);
5657 /* We re-execute after vfork on NOMMU. This makes this script safe:
5658 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5659 * huge=`cat BIG` # was blocking here forever
5662 re_execute_shell(&to_free,
5672 # if ENABLE_HUSH_FAST
5674 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5675 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5676 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5678 enable_restore_tty_pgrp_on_exit();
5683 close_on_exec_on(channel[0]);
5684 return xfdopen_for_read(channel[0]);
5687 /* Return code is exit status of the process that is run. */
5688 static int process_command_subs(o_string *dest, const char *s)
5691 struct in_str pipe_str;
5693 int status, ch, eol_cnt;
5695 fp = generate_stream_from_string(s, &pid);
5697 /* Now send results of command back into original context */
5698 setup_file_in_str(&pipe_str, fp);
5700 while ((ch = i_getch(&pipe_str)) != EOF) {
5706 o_addchr(dest, '\n');
5709 o_addQchr(dest, ch);
5712 debug_printf("done reading from `cmd` pipe, closing it\n");
5714 /* We need to extract exitcode. Test case
5715 * "true; echo `sleep 1; false` $?"
5717 safe_waitpid(pid, &status, 0);
5718 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5719 return WEXITSTATUS(status);
5721 #endif /* ENABLE_HUSH_TICK */
5724 static void setup_heredoc(struct redir_struct *redir)
5726 struct fd_pair pair;
5729 /* the _body_ of heredoc (misleading field name) */
5730 const char *heredoc = redir->rd_filename;
5737 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5738 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5742 len = strlen(heredoc);
5744 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5746 xmove_fd(pair.rd, redir->rd_fd);
5748 /* Try writing without forking. Newer kernels have
5749 * dynamically growing pipes. Must use non-blocking write! */
5752 written = write(pair.wr, heredoc, len);
5763 ndelay_off(pair.wr);
5765 /* Okay, pipe buffer was not big enough */
5766 /* Note: we must not create a stray child (bastard? :)
5767 * for the unsuspecting parent process. Child creates a grandchild
5768 * and exits before parent execs the process which consumes heredoc
5769 * (that exec happens after we return from this function) */
5776 disable_restore_tty_pgrp_on_exit();
5777 pid = BB_MMU ? xfork() : xvfork();
5781 close(redir->rd_fd); /* read side of the pipe */
5783 full_write(pair.wr, heredoc, len); /* may loop or block */
5786 /* Delegate blocking writes to another process */
5787 xmove_fd(pair.wr, STDOUT_FILENO);
5788 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5792 #if ENABLE_HUSH_FAST
5794 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5796 enable_restore_tty_pgrp_on_exit();
5802 wait(NULL); /* wait till child has died */
5805 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5806 * and stderr if they are redirected. */
5807 static int setup_redirects(struct command *prog, int squirrel[])
5810 struct redir_struct *redir;
5812 for (redir = prog->redirects; redir; redir = redir->next) {
5813 if (redir->rd_type == REDIRECT_HEREDOC2) {
5814 /* rd_fd<<HERE case */
5815 if (squirrel && redir->rd_fd < 3
5816 && squirrel[redir->rd_fd] < 0
5818 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5820 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5822 debug_printf_parse("set heredoc '%s'\n",
5823 redir->rd_filename);
5824 setup_heredoc(redir);
5828 if (redir->rd_dup == REDIRFD_TO_FILE) {
5829 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5831 if (redir->rd_filename == NULL) {
5832 /* Something went wrong in the parse.
5833 * Pretend it didn't happen */
5834 bb_error_msg("bug in redirect parse");
5837 mode = redir_table[redir->rd_type].mode;
5838 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5839 openfd = open_or_warn(p, mode);
5842 /* this could get lost if stderr has been redirected, but
5843 * bash and ash both lose it as well (though zsh doesn't!) */
5844 //what the above comment tries to say?
5848 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5849 openfd = redir->rd_dup;
5852 if (openfd != redir->rd_fd) {
5853 if (squirrel && redir->rd_fd < 3
5854 && squirrel[redir->rd_fd] < 0
5856 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5858 if (openfd == REDIRFD_CLOSE) {
5859 /* "n>-" means "close me" */
5860 close(redir->rd_fd);
5862 xdup2(openfd, redir->rd_fd);
5863 if (redir->rd_dup == REDIRFD_TO_FILE)
5871 static void restore_redirects(int squirrel[])
5874 for (i = 0; i < 3; i++) {
5877 /* We simply die on error */
5883 static char *find_in_path(const char *arg)
5886 const char *PATH = get_local_var_value("PATH");
5892 const char *end = strchrnul(PATH, ':');
5893 int sz = end - PATH; /* must be int! */
5897 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5899 /* We have xxx::yyyy in $PATH,
5900 * it means "use current dir" */
5903 if (access(ret, F_OK) == 0)
5916 static const struct built_in_command *find_builtin_helper(const char *name,
5917 const struct built_in_command *x,
5918 const struct built_in_command *end)
5921 if (strcmp(name, x->b_cmd) != 0) {
5925 debug_printf_exec("found builtin '%s'\n", name);
5930 static const struct built_in_command *find_builtin1(const char *name)
5932 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5934 static const struct built_in_command *find_builtin(const char *name)
5936 const struct built_in_command *x = find_builtin1(name);
5939 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5942 #if ENABLE_HUSH_FUNCTIONS
5943 static struct function **find_function_slot(const char *name)
5945 struct function **funcpp = &G.top_func;
5947 if (strcmp(name, (*funcpp)->name) == 0) {
5950 funcpp = &(*funcpp)->next;
5955 static const struct function *find_function(const char *name)
5957 const struct function *funcp = *find_function_slot(name);
5959 debug_printf_exec("found function '%s'\n", name);
5963 /* Note: takes ownership on name ptr */
5964 static struct function *new_function(char *name)
5966 struct function **funcpp = find_function_slot(name);
5967 struct function *funcp = *funcpp;
5969 if (funcp != NULL) {
5970 struct command *cmd = funcp->parent_cmd;
5971 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5973 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5975 /* Note: if !funcp->body, do not free body_as_string!
5976 * This is a special case of "-F name body" function:
5977 * body_as_string was not malloced! */
5979 free_pipe_list(funcp->body);
5981 free(funcp->body_as_string);
5985 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5986 cmd->argv[0] = funcp->name;
5987 cmd->group = funcp->body;
5989 cmd->group_as_string = funcp->body_as_string;
5993 debug_printf_exec("remembering new function '%s'\n", name);
5994 funcp = *funcpp = xzalloc(sizeof(*funcp));
5995 /*funcp->next = NULL;*/
6002 static void unset_func(const char *name)
6004 struct function **funcpp = find_function_slot(name);
6005 struct function *funcp = *funcpp;
6007 if (funcp != NULL) {
6008 debug_printf_exec("freeing function '%s'\n", funcp->name);
6009 *funcpp = funcp->next;
6010 /* funcp is unlinked now, deleting it.
6011 * Note: if !funcp->body, the function was created by
6012 * "-F name body", do not free ->body_as_string
6013 * and ->name as they were not malloced. */
6015 free_pipe_list(funcp->body);
6018 free(funcp->body_as_string);
6026 #define exec_function(to_free, funcp, argv) \
6027 exec_function(funcp, argv)
6029 static void exec_function(char ***to_free,
6030 const struct function *funcp,
6031 char **argv) NORETURN;
6032 static void exec_function(char ***to_free,
6033 const struct function *funcp,
6039 argv[0] = G.global_argv[0];
6040 G.global_argv = argv;
6044 /* On MMU, funcp->body is always non-NULL */
6045 n = run_list(funcp->body);
6049 re_execute_shell(to_free,
6050 funcp->body_as_string,
6057 static int run_function(const struct function *funcp, char **argv)
6063 save_and_replace_G_args(&sv, argv);
6065 /* "we are in function, ok to use return" */
6066 sv_flg = G.flag_return_in_progress;
6067 G.flag_return_in_progress = -1;
6068 # if ENABLE_HUSH_LOCAL
6069 G.func_nest_level++;
6072 /* On MMU, funcp->body is always non-NULL */
6075 /* Function defined by -F */
6076 parse_and_run_string(funcp->body_as_string);
6077 rc = G.last_exitcode;
6081 rc = run_list(funcp->body);
6084 # if ENABLE_HUSH_LOCAL
6086 struct variable *var;
6087 struct variable **var_pp;
6089 var_pp = &G.top_var;
6090 while ((var = *var_pp) != NULL) {
6091 if (var->func_nest_level < G.func_nest_level) {
6092 var_pp = &var->next;
6096 if (var->flg_export)
6097 bb_unsetenv(var->varstr);
6098 /* Remove from global list */
6099 *var_pp = var->next;
6105 G.func_nest_level--;
6108 G.flag_return_in_progress = sv_flg;
6110 restore_G_args(&sv, argv);
6114 #endif /* ENABLE_HUSH_FUNCTIONS */
6118 #define exec_builtin(to_free, x, argv) \
6119 exec_builtin(x, argv)
6121 #define exec_builtin(to_free, x, argv) \
6122 exec_builtin(to_free, argv)
6124 static void exec_builtin(char ***to_free,
6125 const struct built_in_command *x,
6126 char **argv) NORETURN;
6127 static void exec_builtin(char ***to_free,
6128 const struct built_in_command *x,
6134 rcode = x->b_function(argv);
6139 /* On NOMMU, we must never block!
6140 * Example: { sleep 99 | read line; } & echo Ok
6142 re_execute_shell(to_free,
6151 static void execvp_or_die(char **argv) NORETURN;
6152 static void execvp_or_die(char **argv)
6154 debug_printf_exec("execing '%s'\n", argv[0]);
6155 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6156 execvp(argv[0], argv);
6157 bb_perror_msg("can't execute '%s'", argv[0]);
6158 _exit(127); /* bash compat */
6161 #if ENABLE_HUSH_MODE_X
6162 static void dump_cmd_in_x_mode(char **argv)
6164 if (G_x_mode && argv) {
6165 /* We want to output the line in one write op */
6173 len += strlen(argv[n++]) + 1;
6179 p += sprintf(p, " %s", argv[n++]);
6187 # define dump_cmd_in_x_mode(argv) ((void)0)
6191 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6192 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6193 #define pseudo_exec(nommu_save, command, argv_expanded) \
6194 pseudo_exec(command, argv_expanded)
6197 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6199 * Don't exit() here. If you don't exec, use _exit instead.
6200 * The at_exit handlers apparently confuse the calling process,
6201 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6202 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6203 char **argv, int assignment_cnt,
6204 char **argv_expanded) NORETURN;
6205 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6206 char **argv, int assignment_cnt,
6207 char **argv_expanded)
6211 new_env = expand_assignments(argv, assignment_cnt);
6212 dump_cmd_in_x_mode(new_env);
6214 if (!argv[assignment_cnt]) {
6215 /* Case when we are here: ... | var=val | ...
6216 * (note that we do not exit early, i.e., do not optimize out
6217 * expand_assignments(): think about ... | var=`sleep 1` | ...
6219 free_strings(new_env);
6220 _exit(EXIT_SUCCESS);
6224 set_vars_and_save_old(new_env);
6225 free(new_env); /* optional */
6226 /* we can also destroy set_vars_and_save_old's return value,
6229 nommu_save->new_env = new_env;
6230 nommu_save->old_vars = set_vars_and_save_old(new_env);
6233 if (argv_expanded) {
6234 argv = argv_expanded;
6236 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6238 nommu_save->argv = argv;
6241 dump_cmd_in_x_mode(argv);
6243 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6244 if (strchr(argv[0], '/') != NULL)
6248 /* Check if the command matches any of the builtins.
6249 * Depending on context, this might be redundant. But it's
6250 * easier to waste a few CPU cycles than it is to figure out
6251 * if this is one of those cases.
6254 /* On NOMMU, it is more expensive to re-execute shell
6255 * just in order to run echo or test builtin.
6256 * It's better to skip it here and run corresponding
6257 * non-builtin later. */
6258 const struct built_in_command *x;
6259 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6261 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6264 #if ENABLE_HUSH_FUNCTIONS
6265 /* Check if the command matches any functions */
6267 const struct function *funcp = find_function(argv[0]);
6269 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6274 #if ENABLE_FEATURE_SH_STANDALONE
6275 /* Check if the command matches any busybox applets */
6277 int a = find_applet_by_name(argv[0]);
6279 # if BB_MMU /* see above why on NOMMU it is not allowed */
6280 if (APPLET_IS_NOEXEC(a)) {
6281 debug_printf_exec("running applet '%s'\n", argv[0]);
6282 run_applet_no_and_exit(a, argv);
6285 /* Re-exec ourselves */
6286 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6287 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6288 execv(bb_busybox_exec_path, argv);
6289 /* If they called chroot or otherwise made the binary no longer
6290 * executable, fall through */
6295 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6298 execvp_or_die(argv);
6301 /* Called after [v]fork() in run_pipe
6303 static void pseudo_exec(nommu_save_t *nommu_save,
6304 struct command *command,
6305 char **argv_expanded) NORETURN;
6306 static void pseudo_exec(nommu_save_t *nommu_save,
6307 struct command *command,
6308 char **argv_expanded)
6310 if (command->argv) {
6311 pseudo_exec_argv(nommu_save, command->argv,
6312 command->assignment_cnt, argv_expanded);
6315 if (command->group) {
6316 /* Cases when we are here:
6319 * ... | ( list ) | ...
6320 * ... | { list } | ...
6324 debug_printf_exec("pseudo_exec: run_list\n");
6325 reset_traps_to_defaults();
6326 rcode = run_list(command->group);
6327 /* OK to leak memory by not calling free_pipe_list,
6328 * since this process is about to exit */
6331 re_execute_shell(&nommu_save->argv_from_re_execing,
6332 command->group_as_string,
6339 /* Case when we are here: ... | >file */
6340 debug_printf_exec("pseudo_exec'ed null command\n");
6341 _exit(EXIT_SUCCESS);
6345 static const char *get_cmdtext(struct pipe *pi)
6351 /* This is subtle. ->cmdtext is created only on first backgrounding.
6352 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6353 * On subsequent bg argv is trashed, but we won't use it */
6356 argv = pi->cmds[0].argv;
6357 if (!argv || !argv[0]) {
6358 pi->cmdtext = xzalloc(1);
6364 len += strlen(*argv) + 1;
6368 argv = pi->cmds[0].argv;
6370 len = strlen(*argv);
6371 memcpy(p, *argv, len);
6379 static void insert_bg_job(struct pipe *pi)
6381 struct pipe *job, **jobp;
6384 /* Linear search for the ID of the job to use */
6386 for (job = G.job_list; job; job = job->next)
6387 if (job->jobid >= pi->jobid)
6388 pi->jobid = job->jobid + 1;
6390 /* Add job to the list of running jobs */
6392 while ((job = *jobp) != NULL)
6394 job = *jobp = xmalloc(sizeof(*job));
6396 *job = *pi; /* physical copy */
6398 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6399 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6400 for (i = 0; i < pi->num_cmds; i++) {
6401 job->cmds[i].pid = pi->cmds[i].pid;
6402 /* all other fields are not used and stay zero */
6404 job->cmdtext = xstrdup(get_cmdtext(pi));
6406 if (G_interactive_fd)
6407 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6408 G.last_jobid = job->jobid;
6411 static void remove_bg_job(struct pipe *pi)
6413 struct pipe *prev_pipe;
6415 if (pi == G.job_list) {
6416 G.job_list = pi->next;
6418 prev_pipe = G.job_list;
6419 while (prev_pipe->next != pi)
6420 prev_pipe = prev_pipe->next;
6421 prev_pipe->next = pi->next;
6424 G.last_jobid = G.job_list->jobid;
6429 /* Remove a backgrounded job */
6430 static void delete_finished_bg_job(struct pipe *pi)
6437 /* Check to see if any processes have exited -- if they
6438 * have, figure out why and see if a job has completed */
6439 static int checkjobs(struct pipe *fg_pipe)
6449 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6451 attributes = WUNTRACED;
6452 if (fg_pipe == NULL)
6453 attributes |= WNOHANG;
6456 #if ENABLE_HUSH_FAST
6457 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6458 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6459 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6460 /* There was neither fork nor SIGCHLD since last waitpid */
6461 /* Avoid doing waitpid syscall if possible */
6462 if (!G.we_have_children) {
6466 if (fg_pipe == NULL) { /* is WNOHANG set? */
6467 /* We have children, but they did not exit
6468 * or stop yet (we saw no SIGCHLD) */
6471 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6475 /* Do we do this right?
6476 * bash-3.00# sleep 20 | false
6478 * [3]+ Stopped sleep 20 | false
6479 * bash-3.00# echo $?
6480 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6481 * [hush 1.14.0: yes we do it right]
6488 #if ENABLE_HUSH_FAST
6489 i = G.count_SIGCHLD;
6491 childpid = waitpid(-1, &status, attributes);
6492 if (childpid <= 0) {
6493 if (childpid && errno != ECHILD)
6494 bb_perror_msg("waitpid");
6495 #if ENABLE_HUSH_FAST
6496 else { /* Until next SIGCHLD, waitpid's are useless */
6497 G.we_have_children = (childpid == 0);
6498 G.handled_SIGCHLD = i;
6499 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6504 dead = WIFEXITED(status) || WIFSIGNALED(status);
6507 if (WIFSTOPPED(status))
6508 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6509 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6510 if (WIFSIGNALED(status))
6511 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6512 childpid, WTERMSIG(status), WEXITSTATUS(status));
6513 if (WIFEXITED(status))
6514 debug_printf_jobs("pid %d exited, exitcode %d\n",
6515 childpid, WEXITSTATUS(status));
6517 /* Were we asked to wait for fg pipe? */
6519 i = fg_pipe->num_cmds;
6521 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6522 if (fg_pipe->cmds[i].pid != childpid)
6526 fg_pipe->cmds[i].pid = 0;
6527 fg_pipe->alive_cmds--;
6528 ex = WEXITSTATUS(status);
6529 /* bash prints killer signal's name for *last*
6530 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6531 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6533 if (WIFSIGNALED(status)) {
6534 int sig = WTERMSIG(status);
6535 if (i == fg_pipe->num_cmds-1)
6536 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6537 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6538 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6539 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6540 * Maybe we need to use sig | 128? */
6543 fg_pipe->cmds[i].cmd_exitcode = ex;
6545 fg_pipe->cmds[i].is_stopped = 1;
6546 fg_pipe->stopped_cmds++;
6548 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6549 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6550 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6551 /* All processes in fg pipe have exited or stopped */
6552 i = fg_pipe->num_cmds;
6554 rcode = fg_pipe->cmds[i].cmd_exitcode;
6555 /* usually last process gives overall exitstatus,
6556 * but with "set -o pipefail", last *failed* process does */
6557 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6560 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6561 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6562 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6563 * and "killall -STOP cat" */
6564 if (G_interactive_fd) {
6566 if (fg_pipe->alive_cmds != 0)
6567 insert_bg_job(fg_pipe);
6571 if (fg_pipe->alive_cmds == 0)
6574 /* There are still running processes in the fg pipe */
6575 goto wait_more; /* do waitpid again */
6577 /* it wasnt fg_pipe, look for process in bg pipes */
6581 /* We asked to wait for bg or orphaned children */
6582 /* No need to remember exitcode in this case */
6583 for (pi = G.job_list; pi; pi = pi->next) {
6584 for (i = 0; i < pi->num_cmds; i++) {
6585 if (pi->cmds[i].pid == childpid)
6586 goto found_pi_and_prognum;
6589 /* Happens when shell is used as init process (init=/bin/sh) */
6590 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6591 continue; /* do waitpid again */
6593 found_pi_and_prognum:
6596 pi->cmds[i].pid = 0;
6598 if (!pi->alive_cmds) {
6599 if (G_interactive_fd)
6600 printf(JOB_STATUS_FORMAT, pi->jobid,
6601 "Done", pi->cmdtext);
6602 delete_finished_bg_job(pi);
6606 pi->cmds[i].is_stopped = 1;
6610 } /* while (waitpid succeeds)... */
6616 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6619 int rcode = checkjobs(fg_pipe);
6620 if (G_saved_tty_pgrp) {
6621 /* Job finished, move the shell to the foreground */
6622 p = getpgrp(); /* our process group id */
6623 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6624 tcsetpgrp(G_interactive_fd, p);
6630 /* Start all the jobs, but don't wait for anything to finish.
6633 * Return code is normally -1, when the caller has to wait for children
6634 * to finish to determine the exit status of the pipe. If the pipe
6635 * is a simple builtin command, however, the action is done by the
6636 * time run_pipe returns, and the exit code is provided as the
6639 * Returns -1 only if started some children. IOW: we have to
6640 * mask out retvals of builtins etc with 0xff!
6642 * The only case when we do not need to [v]fork is when the pipe
6643 * is single, non-backgrounded, non-subshell command. Examples:
6644 * cmd ; ... { list } ; ...
6645 * cmd && ... { list } && ...
6646 * cmd || ... { list } || ...
6647 * If it is, then we can run cmd as a builtin, NOFORK,
6648 * or (if SH_STANDALONE) an applet, and we can run the { list }
6649 * with run_list. If it isn't one of these, we fork and exec cmd.
6651 * Cases when we must fork:
6652 * non-single: cmd | cmd
6653 * backgrounded: cmd & { list } &
6654 * subshell: ( list ) [&]
6656 #if !ENABLE_HUSH_MODE_X
6657 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6658 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6660 static int redirect_and_varexp_helper(char ***new_env_p,
6661 struct variable **old_vars_p,
6662 struct command *command,
6664 char **argv_expanded)
6666 /* setup_redirects acts on file descriptors, not FILEs.
6667 * This is perfect for work that comes after exec().
6668 * Is it really safe for inline use? Experimentally,
6669 * things seem to work. */
6670 int rcode = setup_redirects(command, squirrel);
6672 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6673 *new_env_p = new_env;
6674 dump_cmd_in_x_mode(new_env);
6675 dump_cmd_in_x_mode(argv_expanded);
6677 *old_vars_p = set_vars_and_save_old(new_env);
6681 static NOINLINE int run_pipe(struct pipe *pi)
6683 static const char *const null_ptr = NULL;
6687 struct command *command;
6688 char **argv_expanded;
6690 /* it is not always needed, but we aim to smaller code */
6691 int squirrel[] = { -1, -1, -1 };
6694 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6697 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6698 * Result should be 3 lines: q w e, qwe, q w e
6700 G.ifs = get_local_var_value("IFS");
6704 IF_HUSH_JOB(pi->pgrp = -1;)
6705 pi->stopped_cmds = 0;
6706 command = &pi->cmds[0];
6707 argv_expanded = NULL;
6709 if (pi->num_cmds != 1
6710 || pi->followup == PIPE_BG
6711 || command->cmd_type == CMD_SUBSHELL
6718 debug_printf_exec(": group:%p argv:'%s'\n",
6719 command->group, command->argv ? command->argv[0] : "NONE");
6721 if (command->group) {
6722 #if ENABLE_HUSH_FUNCTIONS
6723 if (command->cmd_type == CMD_FUNCDEF) {
6724 /* "executing" func () { list } */
6725 struct function *funcp;
6727 funcp = new_function(command->argv[0]);
6728 /* funcp->name is already set to argv[0] */
6729 funcp->body = command->group;
6731 funcp->body_as_string = command->group_as_string;
6732 command->group_as_string = NULL;
6734 command->group = NULL;
6735 command->argv[0] = NULL;
6736 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6737 funcp->parent_cmd = command;
6738 command->child_func = funcp;
6740 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6742 return EXIT_SUCCESS;
6746 debug_printf("non-subshell group\n");
6747 rcode = 1; /* exitcode if redir failed */
6748 if (setup_redirects(command, squirrel) == 0) {
6749 debug_printf_exec(": run_list\n");
6750 rcode = run_list(command->group) & 0xff;
6752 restore_redirects(squirrel);
6753 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6755 debug_printf_exec("run_pipe: return %d\n", rcode);
6759 argv = command->argv ? command->argv : (char **) &null_ptr;
6761 const struct built_in_command *x;
6762 #if ENABLE_HUSH_FUNCTIONS
6763 const struct function *funcp;
6767 char **new_env = NULL;
6768 struct variable *old_vars = NULL;
6770 if (argv[command->assignment_cnt] == NULL) {
6771 /* Assignments, but no command */
6772 /* Ensure redirects take effect (that is, create files).
6773 * Try "a=t >file" */
6774 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6775 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6776 /* Set shell variables */
6780 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6781 /* Do we need to flag set_local_var() errors?
6782 * "assignment to readonly var" and "putenv error"
6787 /* Redirect error sets $? to 1. Otherwise,
6788 * if evaluating assignment value set $?, retain it.
6789 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6791 rcode = G.last_exitcode;
6792 /* Exit, _skipping_ variable restoring code: */
6793 goto clean_up_and_ret0;
6795 #else /* Older, bigger, but more correct code */
6797 rcode = setup_redirects(command, squirrel);
6798 restore_redirects(squirrel);
6799 /* Set shell variables */
6801 bb_putchar_stderr('+');
6803 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6805 fprintf(stderr, " %s", p);
6806 debug_printf_exec("set shell var:'%s'->'%s'\n",
6808 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6809 /* Do we need to flag set_local_var() errors?
6810 * "assignment to readonly var" and "putenv error"
6815 bb_putchar_stderr('\n');
6816 /* Redirect error sets $? to 1. Otherwise,
6817 * if evaluating assignment value set $?, retain it.
6818 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6820 rcode = G.last_exitcode;
6821 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6823 debug_printf_exec("run_pipe: return %d\n", rcode);
6828 /* Expand the rest into (possibly) many strings each */
6829 #if ENABLE_HUSH_BASH_COMPAT
6830 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6831 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6835 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6838 /* if someone gives us an empty string: `cmd with empty output` */
6839 if (!argv_expanded[0]) {
6840 free(argv_expanded);
6842 return G.last_exitcode;
6845 x = find_builtin(argv_expanded[0]);
6846 #if ENABLE_HUSH_FUNCTIONS
6849 funcp = find_function(argv_expanded[0]);
6853 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6854 debug_printf("exec with redirects only\n");
6855 rcode = setup_redirects(command, NULL);
6856 goto clean_up_and_ret1;
6859 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6862 debug_printf_exec(": builtin '%s' '%s'...\n",
6863 x->b_cmd, argv_expanded[1]);
6865 rcode = x->b_function(argv_expanded) & 0xff;
6868 #if ENABLE_HUSH_FUNCTIONS
6870 # if ENABLE_HUSH_LOCAL
6871 struct variable **sv;
6872 sv = G.shadowed_vars_pp;
6873 G.shadowed_vars_pp = &old_vars;
6875 debug_printf_exec(": function '%s' '%s'...\n",
6876 funcp->name, argv_expanded[1]);
6877 rcode = run_function(funcp, argv_expanded) & 0xff;
6878 # if ENABLE_HUSH_LOCAL
6879 G.shadowed_vars_pp = sv;
6885 unset_vars(new_env);
6887 /* clean_up_and_ret0: */
6888 restore_redirects(squirrel);
6890 free(argv_expanded);
6891 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6893 debug_printf_exec("run_pipe return %d\n", rcode);
6897 if (ENABLE_FEATURE_SH_NOFORK) {
6898 int n = find_applet_by_name(argv_expanded[0]);
6899 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6900 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6902 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6903 argv_expanded[0], argv_expanded[1]);
6904 rcode = run_nofork_applet(n, argv_expanded);
6906 goto clean_up_and_ret;
6909 /* It is neither builtin nor applet. We must fork. */
6913 /* NB: argv_expanded may already be created, and that
6914 * might include `cmd` runs! Do not rerun it! We *must*
6915 * use argv_expanded if it's non-NULL */
6917 /* Going to fork a child per each pipe member */
6922 while (cmd_no < pi->num_cmds) {
6923 struct fd_pair pipefds;
6925 volatile nommu_save_t nommu_save;
6926 nommu_save.new_env = NULL;
6927 nommu_save.old_vars = NULL;
6928 nommu_save.argv = NULL;
6929 nommu_save.argv_from_re_execing = NULL;
6931 command = &pi->cmds[cmd_no];
6933 if (command->argv) {
6934 debug_printf_exec(": pipe member '%s' '%s'...\n",
6935 command->argv[0], command->argv[1]);
6937 debug_printf_exec(": pipe member with no argv\n");
6940 /* pipes are inserted between pairs of commands */
6943 if (cmd_no < pi->num_cmds)
6944 xpiped_pair(pipefds);
6946 command->pid = BB_MMU ? fork() : vfork();
6947 if (!command->pid) { /* child */
6949 disable_restore_tty_pgrp_on_exit();
6950 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6952 /* Every child adds itself to new process group
6953 * with pgid == pid_of_first_child_in_pipe */
6954 if (G.run_list_level == 1 && G_interactive_fd) {
6957 if (pgrp < 0) /* true for 1st process only */
6959 if (setpgid(0, pgrp) == 0
6960 && pi->followup != PIPE_BG
6961 && G_saved_tty_pgrp /* we have ctty */
6963 /* We do it in *every* child, not just first,
6965 tcsetpgrp(G_interactive_fd, pgrp);
6969 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6970 /* 1st cmd in backgrounded pipe
6971 * should have its stdin /dev/null'ed */
6973 if (open(bb_dev_null, O_RDONLY))
6974 xopen("/", O_RDONLY);
6976 xmove_fd(next_infd, 0);
6978 xmove_fd(pipefds.wr, 1);
6981 /* Like bash, explicit redirects override pipes,
6982 * and the pipe fd is available for dup'ing. */
6983 if (setup_redirects(command, NULL))
6986 /* Restore default handlers just prior to exec */
6987 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6989 /* Stores to nommu_save list of env vars putenv'ed
6990 * (NOMMU, on MMU we don't need that) */
6991 /* cast away volatility... */
6992 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6993 /* pseudo_exec() does not return */
6996 /* parent or error */
6997 #if ENABLE_HUSH_FAST
6999 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7001 enable_restore_tty_pgrp_on_exit();
7003 /* Clean up after vforked child */
7004 free(nommu_save.argv);
7005 free(nommu_save.argv_from_re_execing);
7006 unset_vars(nommu_save.new_env);
7007 add_vars(nommu_save.old_vars);
7009 free(argv_expanded);
7010 argv_expanded = NULL;
7011 if (command->pid < 0) { /* [v]fork failed */
7012 /* Clearly indicate, was it fork or vfork */
7013 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7017 /* Second and next children need to know pid of first one */
7019 pi->pgrp = command->pid;
7025 if (cmd_no < pi->num_cmds)
7027 /* Pass read (output) pipe end to next iteration */
7028 next_infd = pipefds.rd;
7031 if (!pi->alive_cmds) {
7033 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7038 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7042 /* NB: called by pseudo_exec, and therefore must not modify any
7043 * global data until exec/_exit (we can be a child after vfork!) */
7044 static int run_list(struct pipe *pi)
7046 #if ENABLE_HUSH_CASE
7047 char *case_word = NULL;
7049 #if ENABLE_HUSH_LOOPS
7050 struct pipe *loop_top = NULL;
7051 char **for_lcur = NULL;
7052 char **for_list = NULL;
7054 smallint last_followup;
7056 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7057 smalluint cond_code = 0;
7059 enum { cond_code = 0 };
7062 smallint rword; /* RES_foo */
7063 smallint last_rword; /* ditto */
7066 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7069 #if ENABLE_HUSH_LOOPS
7070 /* Check syntax for "for" */
7073 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7074 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7076 /* current word is FOR or IN (BOLD in comments below) */
7077 if (cpipe->next == NULL) {
7078 syntax_error("malformed for");
7080 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7083 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7084 if (cpipe->next->res_word == RES_DO)
7086 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7087 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7088 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7090 syntax_error("malformed for");
7092 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7099 /* Past this point, all code paths should jump to ret: label
7100 * in order to return, no direct "return" statements please.
7101 * This helps to ensure that no memory is leaked. */
7109 last_rword = RES_XXXX;
7111 last_followup = PIPE_SEQ;
7112 rcode = G.last_exitcode;
7114 /* Go through list of pipes, (maybe) executing them. */
7115 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7119 IF_HAS_KEYWORDS(rword = pi->res_word;)
7120 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7121 rword, cond_code, last_rword);
7122 #if ENABLE_HUSH_LOOPS
7123 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7124 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7126 /* start of a loop: remember where loop starts */
7131 /* Still in the same "if...", "then..." or "do..." branch? */
7132 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7133 if ((rcode == 0 && last_followup == PIPE_OR)
7134 || (rcode != 0 && last_followup == PIPE_AND)
7136 /* It is "<true> || CMD" or "<false> && CMD"
7137 * and we should not execute CMD */
7138 debug_printf_exec("skipped cmd because of || or &&\n");
7139 last_followup = pi->followup;
7143 last_followup = pi->followup;
7144 IF_HAS_KEYWORDS(last_rword = rword;)
7147 if (rword == RES_THEN) {
7148 /* if false; then ... fi has exitcode 0! */
7149 G.last_exitcode = rcode = EXIT_SUCCESS;
7150 /* "if <false> THEN cmd": skip cmd */
7154 if (rword == RES_ELSE || rword == RES_ELIF) {
7155 /* "if <true> then ... ELSE/ELIF cmd":
7156 * skip cmd and all following ones */
7161 #if ENABLE_HUSH_LOOPS
7162 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7164 /* first loop through for */
7166 static const char encoded_dollar_at[] ALIGN1 = {
7167 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7168 }; /* encoded representation of "$@" */
7169 static const char *const encoded_dollar_at_argv[] = {
7170 encoded_dollar_at, NULL
7171 }; /* argv list with one element: "$@" */
7174 vals = (char**)encoded_dollar_at_argv;
7175 if (pi->next->res_word == RES_IN) {
7176 /* if no variable values after "in" we skip "for" */
7177 if (!pi->next->cmds[0].argv) {
7178 G.last_exitcode = rcode = EXIT_SUCCESS;
7179 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7182 vals = pi->next->cmds[0].argv;
7183 } /* else: "for var; do..." -> assume "$@" list */
7184 /* create list of variable values */
7185 debug_print_strings("for_list made from", vals);
7186 for_list = expand_strvec_to_strvec(vals);
7187 for_lcur = for_list;
7188 debug_print_strings("for_list", for_list);
7191 /* "for" loop is over, clean up */
7197 /* Insert next value from for_lcur */
7198 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7199 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7202 if (rword == RES_IN) {
7203 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7205 if (rword == RES_DONE) {
7206 continue; /* "done" has no cmds too */
7209 #if ENABLE_HUSH_CASE
7210 if (rword == RES_CASE) {
7211 case_word = expand_strvec_to_string(pi->cmds->argv);
7214 if (rword == RES_MATCH) {
7217 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7219 /* all prev words didn't match, does this one match? */
7220 argv = pi->cmds->argv;
7222 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7223 /* TODO: which FNM_xxx flags to use? */
7224 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7226 if (cond_code == 0) { /* match! we will execute this branch */
7227 free(case_word); /* make future "word)" stop */
7235 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7237 continue; /* not matched yet, skip this pipe */
7240 /* Just pressing <enter> in shell should check for jobs.
7241 * OTOH, in non-interactive shell this is useless
7242 * and only leads to extra job checks */
7243 if (pi->num_cmds == 0) {
7244 if (G_interactive_fd)
7245 goto check_jobs_and_continue;
7249 /* After analyzing all keywords and conditions, we decided
7250 * to execute this pipe. NB: have to do checkjobs(NULL)
7251 * after run_pipe to collect any background children,
7252 * even if list execution is to be stopped. */
7253 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7256 #if ENABLE_HUSH_LOOPS
7257 G.flag_break_continue = 0;
7259 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7261 /* We ran a builtin, function, or group.
7262 * rcode is already known
7263 * and we don't need to wait for anything. */
7264 G.last_exitcode = rcode;
7265 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7266 check_and_run_traps(0);
7267 #if ENABLE_HUSH_LOOPS
7268 /* Was it "break" or "continue"? */
7269 if (G.flag_break_continue) {
7270 smallint fbc = G.flag_break_continue;
7271 /* We might fall into outer *loop*,
7272 * don't want to break it too */
7274 G.depth_break_continue--;
7275 if (G.depth_break_continue == 0)
7276 G.flag_break_continue = 0;
7277 /* else: e.g. "continue 2" should *break* once, *then* continue */
7278 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7279 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7280 goto check_jobs_and_break;
7281 /* "continue": simulate end of loop */
7286 #if ENABLE_HUSH_FUNCTIONS
7287 if (G.flag_return_in_progress == 1) {
7288 /* same as "goto check_jobs_and_break" */
7293 } else if (pi->followup == PIPE_BG) {
7294 /* What does bash do with attempts to background builtins? */
7295 /* even bash 3.2 doesn't do that well with nested bg:
7296 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7297 * I'm NOT treating inner &'s as jobs */
7298 check_and_run_traps(0);
7300 if (G.run_list_level == 1)
7303 /* Last command's pid goes to $! */
7304 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7305 G.last_exitcode = rcode = EXIT_SUCCESS;
7306 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7309 if (G.run_list_level == 1 && G_interactive_fd) {
7310 /* Waits for completion, then fg's main shell */
7311 rcode = checkjobs_and_fg_shell(pi);
7312 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7313 check_and_run_traps(0);
7316 { /* This one just waits for completion */
7317 rcode = checkjobs(pi);
7318 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7319 check_and_run_traps(0);
7321 G.last_exitcode = rcode;
7325 /* Analyze how result affects subsequent commands */
7327 if (rword == RES_IF || rword == RES_ELIF)
7330 #if ENABLE_HUSH_LOOPS
7331 /* Beware of "while false; true; do ..."! */
7332 if (pi->next && pi->next->res_word == RES_DO) {
7333 if (rword == RES_WHILE) {
7335 /* "while false; do...done" - exitcode 0 */
7336 G.last_exitcode = rcode = EXIT_SUCCESS;
7337 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7338 goto check_jobs_and_break;
7341 if (rword == RES_UNTIL) {
7343 debug_printf_exec(": until expr is true: breaking\n");
7344 check_jobs_and_break:
7352 check_jobs_and_continue:
7359 #if ENABLE_HUSH_LOOPS
7364 #if ENABLE_HUSH_CASE
7368 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7372 /* Select which version we will use */
7373 static int run_and_free_list(struct pipe *pi)
7376 debug_printf_exec("run_and_free_list entered\n");
7377 if (!G.o_opt[OPT_O_NOEXEC]) {
7378 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7379 rcode = run_list(pi);
7381 /* free_pipe_list has the side effect of clearing memory.
7382 * In the long run that function can be merged with run_list,
7383 * but doing that now would hobble the debugging effort. */
7385 debug_printf_exec("run_and_free_list return %d\n", rcode);
7390 /* Called a few times only (or even once if "sh -c") */
7391 static void init_sigmasks(void)
7395 sigset_t old_blocked_set;
7397 if (!G.inherited_set_is_saved) {
7398 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7399 G.inherited_set = G.blocked_set;
7401 old_blocked_set = G.blocked_set;
7403 mask = (1 << SIGQUIT);
7404 if (G_interactive_fd) {
7405 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7406 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7407 mask |= SPECIAL_JOB_SIGS;
7409 G.non_DFL_mask = mask;
7414 sigaddset(&G.blocked_set, sig);
7418 sigdelset(&G.blocked_set, SIGCHLD);
7420 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7421 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7423 /* POSIX allows shell to re-enable SIGCHLD
7424 * even if it was SIG_IGN on entry */
7425 #if ENABLE_HUSH_FAST
7426 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7427 if (!G.inherited_set_is_saved)
7428 signal(SIGCHLD, SIGCHLD_handler);
7430 if (!G.inherited_set_is_saved)
7431 signal(SIGCHLD, SIG_DFL);
7434 G.inherited_set_is_saved = 1;
7439 static void maybe_set_to_sigexit(int sig)
7441 void (*handler)(int);
7442 /* non_DFL_mask'ed signals are, well, masked,
7443 * no need to set handler for them.
7445 if (!((G.non_DFL_mask >> sig) & 1)) {
7446 handler = signal(sig, sigexit);
7447 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7448 signal(sig, handler);
7451 /* Set handlers to restore tty pgrp and exit */
7452 static void set_fatal_handlers(void)
7454 /* We _must_ restore tty pgrp on fatal signals */
7456 maybe_set_to_sigexit(SIGILL );
7457 maybe_set_to_sigexit(SIGFPE );
7458 maybe_set_to_sigexit(SIGBUS );
7459 maybe_set_to_sigexit(SIGSEGV);
7460 maybe_set_to_sigexit(SIGTRAP);
7461 } /* else: hush is perfect. what SEGV? */
7462 maybe_set_to_sigexit(SIGABRT);
7463 /* bash 3.2 seems to handle these just like 'fatal' ones */
7464 maybe_set_to_sigexit(SIGPIPE);
7465 maybe_set_to_sigexit(SIGALRM);
7466 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7467 * if we aren't interactive... but in this case
7468 * we never want to restore pgrp on exit, and this fn is not called */
7469 /*maybe_set_to_sigexit(SIGHUP );*/
7470 /*maybe_set_to_sigexit(SIGTERM);*/
7471 /*maybe_set_to_sigexit(SIGINT );*/
7475 static int set_mode(int state, char mode, const char *o_opt)
7480 G.o_opt[OPT_O_NOEXEC] = state;
7483 IF_HUSH_MODE_X(G_x_mode = state;)
7487 /* "set -+o" without parameter.
7488 * in bash, set -o produces this output:
7492 * We always use the second form.
7494 const char *p = o_opt_strings;
7497 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7503 idx = index_in_strings(o_opt_strings, o_opt);
7505 G.o_opt[idx] = state;
7509 return EXIT_FAILURE;
7511 return EXIT_SUCCESS;
7514 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7515 int hush_main(int argc, char **argv)
7518 unsigned builtin_argc;
7520 struct variable *cur_var;
7521 struct variable *shell_ver;
7524 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7525 G.last_exitcode = EXIT_SUCCESS;
7527 G.argv0_for_re_execing = argv[0];
7529 /* Deal with HUSH_VERSION */
7530 shell_ver = xzalloc(sizeof(*shell_ver));
7531 shell_ver->flg_export = 1;
7532 shell_ver->flg_read_only = 1;
7533 /* Code which handles ${var<op>...} needs writable values for all variables,
7534 * therefore we xstrdup: */
7535 shell_ver->varstr = xstrdup(hush_version_str);
7536 /* Create shell local variables from the values
7537 * currently living in the environment */
7538 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7539 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7540 G.top_var = shell_ver;
7541 cur_var = G.top_var;
7544 char *value = strchr(*e, '=');
7545 if (value) { /* paranoia */
7546 cur_var->next = xzalloc(sizeof(*cur_var));
7547 cur_var = cur_var->next;
7548 cur_var->varstr = *e;
7549 cur_var->max_len = strlen(*e);
7550 cur_var->flg_export = 1;
7554 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7555 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7556 putenv(shell_ver->varstr);
7559 set_pwd_var(/*exp:*/ 1);
7560 /* bash also exports SHLVL and _,
7561 * and sets (but doesn't export) the following variables:
7563 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7564 * BASH_VERSION='3.2.0(1)-release'
7566 * MACHTYPE=i386-pc-linux-gnu
7568 * HOSTNAME=<xxxxxxxxxx>
7569 * PPID=<NNNNN> - we also do it elsewhere
7580 * PIPESTATUS=([0]="0")
7581 * HISTFILE=/<xxx>/.bash_history
7585 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7587 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7597 #if ENABLE_FEATURE_EDITING
7598 G.line_input_state = new_line_input_t(FOR_SHELL);
7599 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7601 const char *hp = get_local_var_value("HISTFILE");
7603 hp = get_local_var_value("HOME");
7605 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7606 //set_local_var(xasprintf("HISTFILE=%s", ...));
7613 G.global_argc = argc;
7614 G.global_argv = argv;
7615 /* Initialize some more globals to non-zero values */
7616 cmdedit_update_prompt();
7618 if (setjmp(die_jmp)) {
7619 /* xfunc has failed! die die die */
7620 /* no EXIT traps, this is an escape hatch! */
7622 hush_exit(xfunc_error_retval);
7625 /* Shell is non-interactive at first. We need to call
7626 * init_sigmasks() if we are going to execute "sh <script>",
7627 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7628 * If we later decide that we are interactive, we run init_sigmasks()
7629 * in order to intercept (more) signals.
7633 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7636 opt = getopt(argc, argv, "+c:xins"
7639 # if ENABLE_HUSH_FUNCTIONS
7649 * sh ... -c 'script'
7650 * sh ... -c 'script' ARG0 [ARG1...]
7651 * On NOMMU, if builtin_argc != 0,
7652 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7653 * "" needs to be replaced with NULL
7654 * and BARGV vector fed to builtin function.
7655 * Note: the form without ARG0 never happens:
7656 * sh ... -c 'builtin' BARGV... ""
7659 G.root_pid = getpid();
7660 G.root_ppid = getppid();
7662 G.global_argv = argv + optind;
7663 G.global_argc = argc - optind;
7665 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7666 const struct built_in_command *x;
7669 x = find_builtin(optarg);
7670 if (x) { /* paranoia */
7671 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7672 G.global_argv += builtin_argc;
7673 G.global_argv[-1] = NULL; /* replace "" */
7675 G.last_exitcode = x->b_function(argv + optind - 1);
7679 if (!G.global_argv[0]) {
7680 /* -c 'script' (no params): prevent empty $0 */
7681 G.global_argv--; /* points to argv[i] of 'script' */
7682 G.global_argv[0] = argv[0];
7684 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7686 parse_and_run_string(optarg);
7689 /* Well, we cannot just declare interactiveness,
7690 * we have to have some stuff (ctty, etc) */
7691 /* G_interactive_fd++; */
7694 /* "-s" means "read from stdin", but this is how we always
7695 * operate, so simply do nothing here. */
7698 case '<': /* "big heredoc" support */
7699 full_write1_str(optarg);
7702 unsigned long long empty_trap_mask;
7704 G.root_pid = bb_strtou(optarg, &optarg, 16);
7706 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7708 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7710 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7712 builtin_argc = bb_strtou(optarg, &optarg, 16);
7714 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7715 if (empty_trap_mask != 0) {
7718 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7719 for (sig = 1; sig < NSIG; sig++) {
7720 if (empty_trap_mask & (1LL << sig)) {
7721 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7722 sigaddset(&G.blocked_set, sig);
7725 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7727 # if ENABLE_HUSH_LOOPS
7729 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7735 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7737 # if ENABLE_HUSH_FUNCTIONS
7739 struct function *funcp = new_function(optarg);
7740 /* funcp->name is already set to optarg */
7741 /* funcp->body is set to NULL. It's a special case. */
7742 funcp->body_as_string = argv[optind];
7750 if (set_mode(1, opt, NULL) == 0) /* no error */
7754 fprintf(stderr, "Usage: sh [FILE]...\n"
7755 " or: sh -c command [args]...\n\n");
7761 } /* option parsing loop */
7764 G.root_pid = getpid();
7765 G.root_ppid = getppid();
7768 /* If we are login shell... */
7769 if (argv[0] && argv[0][0] == '-') {
7771 debug_printf("sourcing /etc/profile\n");
7772 input = fopen_for_read("/etc/profile");
7773 if (input != NULL) {
7774 close_on_exec_on(fileno(input));
7776 parse_and_run_file(input);
7779 /* bash: after sourcing /etc/profile,
7780 * tries to source (in the given order):
7781 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7782 * stopping on first found. --noprofile turns this off.
7783 * bash also sources ~/.bash_logout on exit.
7784 * If called as sh, skips .bash_XXX files.
7791 * "bash <script>" (which is never interactive (unless -i?))
7792 * sources $BASH_ENV here (without scanning $PATH).
7793 * If called as sh, does the same but with $ENV.
7795 debug_printf("running script '%s'\n", argv[optind]);
7796 G.global_argv = argv + optind;
7797 G.global_argc = argc - optind;
7798 input = xfopen_for_read(argv[optind]);
7799 close_on_exec_on(fileno(input));
7801 parse_and_run_file(input);
7802 #if ENABLE_FEATURE_CLEAN_UP
7808 /* Up to here, shell was non-interactive. Now it may become one.
7809 * NB: don't forget to (re)run init_sigmasks() as needed.
7812 /* A shell is interactive if the '-i' flag was given,
7813 * or if all of the following conditions are met:
7815 * no arguments remaining or the -s flag given
7816 * standard input is a terminal
7817 * standard output is a terminal
7818 * Refer to Posix.2, the description of the 'sh' utility.
7821 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7822 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7823 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7824 if (G_saved_tty_pgrp < 0)
7825 G_saved_tty_pgrp = 0;
7827 /* try to dup stdin to high fd#, >= 255 */
7828 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7829 if (G_interactive_fd < 0) {
7830 /* try to dup to any fd */
7831 G_interactive_fd = dup(STDIN_FILENO);
7832 if (G_interactive_fd < 0) {
7834 G_interactive_fd = 0;
7835 G_saved_tty_pgrp = 0;
7838 // TODO: track & disallow any attempts of user
7839 // to (inadvertently) close/redirect G_interactive_fd
7841 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7842 if (G_interactive_fd) {
7843 close_on_exec_on(G_interactive_fd);
7845 if (G_saved_tty_pgrp) {
7846 /* If we were run as 'hush &', sleep until we are
7847 * in the foreground (tty pgrp == our pgrp).
7848 * If we get started under a job aware app (like bash),
7849 * make sure we are now in charge so we don't fight over
7850 * who gets the foreground */
7852 pid_t shell_pgrp = getpgrp();
7853 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7854 if (G_saved_tty_pgrp == shell_pgrp)
7856 /* send TTIN to ourself (should stop us) */
7857 kill(- shell_pgrp, SIGTTIN);
7861 /* Block some signals */
7864 if (G_saved_tty_pgrp) {
7865 /* Set other signals to restore saved_tty_pgrp */
7866 set_fatal_handlers();
7867 /* Put ourselves in our own process group
7868 * (bash, too, does this only if ctty is available) */
7869 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7870 /* Grab control of the terminal */
7871 tcsetpgrp(G_interactive_fd, getpid());
7873 /* -1 is special - makes xfuncs longjmp, not exit
7874 * (we reset die_sleep = 0 whereever we [v]fork) */
7875 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7879 #elif ENABLE_HUSH_INTERACTIVE
7880 /* No job control compiled in, only prompt/line editing */
7881 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7882 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7883 if (G_interactive_fd < 0) {
7884 /* try to dup to any fd */
7885 G_interactive_fd = dup(STDIN_FILENO);
7886 if (G_interactive_fd < 0)
7888 G_interactive_fd = 0;
7891 if (G_interactive_fd) {
7892 close_on_exec_on(G_interactive_fd);
7896 /* We have interactiveness code disabled */
7900 * if interactive but not a login shell, sources ~/.bashrc
7901 * (--norc turns this off, --rcfile <file> overrides)
7904 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7905 /* note: ash and hush share this string */
7906 printf("\n\n%s %s\n"
7907 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7910 "hush - the humble shell"
7914 parse_and_run_file(stdin);
7917 hush_exit(G.last_exitcode);
7922 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7923 int msh_main(int argc, char **argv)
7925 //bb_error_msg("msh is deprecated, please use hush instead");
7926 return hush_main(argc, argv);
7934 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7939 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7946 return applet_main_func(argc, argv - argc);
7949 static int FAST_FUNC builtin_test(char **argv)
7951 return run_applet_main(argv, test_main);
7954 static int FAST_FUNC builtin_echo(char **argv)
7956 return run_applet_main(argv, echo_main);
7960 static int FAST_FUNC builtin_printf(char **argv)
7962 return run_applet_main(argv, printf_main);
7966 static char **skip_dash_dash(char **argv)
7969 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7974 static int FAST_FUNC builtin_eval(char **argv)
7976 int rcode = EXIT_SUCCESS;
7978 argv = skip_dash_dash(argv);
7980 char *str = expand_strvec_to_string(argv);
7982 * eval "echo Hi; done" ("done" is syntax error):
7983 * "echo Hi" will not execute too.
7985 parse_and_run_string(str);
7987 rcode = G.last_exitcode;
7992 static int FAST_FUNC builtin_cd(char **argv)
7996 argv = skip_dash_dash(argv);
7998 if (newdir == NULL) {
7999 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8000 * bash says "bash: cd: HOME not set" and does nothing
8003 const char *home = get_local_var_value("HOME");
8004 newdir = home ? home : "/";
8006 if (chdir(newdir)) {
8007 /* Mimic bash message exactly */
8008 bb_perror_msg("cd: %s", newdir);
8009 return EXIT_FAILURE;
8011 /* Read current dir (get_cwd(1) is inside) and set PWD.
8012 * Note: do not enforce exporting. If PWD was unset or unexported,
8013 * set it again, but do not export. bash does the same.
8015 set_pwd_var(/*exp:*/ 0);
8016 return EXIT_SUCCESS;
8019 static int FAST_FUNC builtin_exec(char **argv)
8021 argv = skip_dash_dash(argv);
8022 if (argv[0] == NULL)
8023 return EXIT_SUCCESS; /* bash does this */
8025 /* Careful: we can end up here after [v]fork. Do not restore
8026 * tty pgrp then, only top-level shell process does that */
8027 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8028 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8030 /* TODO: if exec fails, bash does NOT exit! We do.
8031 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8032 * and tcsetpgrp, and this is inherently racy.
8034 execvp_or_die(argv);
8037 static int FAST_FUNC builtin_exit(char **argv)
8039 debug_printf_exec("%s()\n", __func__);
8041 /* interactive bash:
8042 * # trap "echo EEE" EXIT
8045 * There are stopped jobs.
8046 * (if there are _stopped_ jobs, running ones don't count)
8049 # EEE (then bash exits)
8051 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8054 /* note: EXIT trap is run by hush_exit */
8055 argv = skip_dash_dash(argv);
8056 if (argv[0] == NULL)
8057 hush_exit(G.last_exitcode);
8058 /* mimic bash: exit 123abc == exit 255 + error msg */
8059 xfunc_error_retval = 255;
8060 /* bash: exit -2 == exit 254, no error msg */
8061 hush_exit(xatoi(argv[0]) & 0xff);
8064 static void print_escaped(const char *s)
8069 const char *p = strchrnul(s, '\'');
8070 /* print 'xxxx', possibly just '' */
8071 printf("'%.*s'", (int)(p - s), s);
8076 /* s points to '; print "'''...'''" */
8078 do putchar('\''); while (*++s == '\'');
8083 #if !ENABLE_HUSH_LOCAL
8084 #define helper_export_local(argv, exp, lvl) \
8085 helper_export_local(argv, exp)
8087 static void helper_export_local(char **argv, int exp, int lvl)
8091 char *name_end = strchrnul(name, '=');
8093 /* So far we do not check that name is valid (TODO?) */
8095 if (*name_end == '\0') {
8096 struct variable *var, **vpp;
8098 vpp = get_ptr_to_local_var(name, name_end - name);
8099 var = vpp ? *vpp : NULL;
8101 if (exp == -1) { /* unexporting? */
8102 /* export -n NAME (without =VALUE) */
8104 var->flg_export = 0;
8105 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8107 } /* else: export -n NOT_EXISTING_VAR: no-op */
8110 if (exp == 1) { /* exporting? */
8111 /* export NAME (without =VALUE) */
8113 var->flg_export = 1;
8114 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8115 putenv(var->varstr);
8119 /* Exporting non-existing variable.
8120 * bash does not put it in environment,
8121 * but remembers that it is exported,
8122 * and does put it in env when it is set later.
8123 * We just set it to "" and export. */
8124 /* Or, it's "local NAME" (without =VALUE).
8125 * bash sets the value to "". */
8126 name = xasprintf("%s=", name);
8128 /* (Un)exporting/making local NAME=VALUE */
8129 name = xstrdup(name);
8131 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8135 static int FAST_FUNC builtin_export(char **argv)
8137 unsigned opt_unexport;
8139 #if ENABLE_HUSH_EXPORT_N
8140 /* "!": do not abort on errors */
8141 opt_unexport = getopt32(argv, "!n");
8142 if (opt_unexport == (uint32_t)-1)
8143 return EXIT_FAILURE;
8150 if (argv[0] == NULL) {
8157 /* ash emits: export VAR='VAL'
8158 * bash: declare -x VAR="VAL"
8159 * we follow ash example */
8160 const char *s = *e++;
8161 const char *p = strchr(s, '=');
8163 if (!p) /* wtf? take next variable */
8166 printf("export %.*s", (int)(p - s) + 1, s);
8167 print_escaped(p + 1);
8171 /*fflush_all(); - done after each builtin anyway */
8173 return EXIT_SUCCESS;
8176 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8178 return EXIT_SUCCESS;
8181 #if ENABLE_HUSH_LOCAL
8182 static int FAST_FUNC builtin_local(char **argv)
8184 if (G.func_nest_level == 0) {
8185 bb_error_msg("%s: not in a function", argv[0]);
8186 return EXIT_FAILURE; /* bash compat */
8188 helper_export_local(argv, 0, G.func_nest_level);
8189 return EXIT_SUCCESS;
8193 static int FAST_FUNC builtin_trap(char **argv)
8199 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8204 /* No args: print all trapped */
8205 for (i = 0; i < NSIG; ++i) {
8208 print_escaped(G.traps[i]);
8209 /* note: bash adds "SIG", but only if invoked
8210 * as "bash". If called as "sh", or if set -o posix,
8211 * then it prints short signal names.
8212 * We are printing short names: */
8213 printf(" %s\n", get_signame(i));
8216 /*fflush_all(); - done after each builtin anyway */
8217 return EXIT_SUCCESS;
8221 /* If first arg is a number: reset all specified signals */
8222 sig = bb_strtou(*argv, NULL, 10);
8228 sig = get_signum(*argv++);
8229 if (sig < 0 || sig >= NSIG) {
8231 /* Mimic bash message exactly */
8232 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8237 G.traps[sig] = xstrdup(new_cmd);
8239 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8240 get_signame(sig), sig, G.traps[sig]);
8242 /* There is no signal for 0 (EXIT) */
8247 sigaddset(&G.blocked_set, sig);
8249 /* There was a trap handler, we are removing it
8250 * (if sig has non-DFL handling,
8251 * we don't need to do anything) */
8252 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8254 sigdelset(&G.blocked_set, sig);
8257 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8261 if (!argv[1]) { /* no second arg */
8262 bb_error_msg("trap: invalid arguments");
8263 return EXIT_FAILURE;
8266 /* First arg is "-": reset all specified to default */
8267 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8268 /* Everything else: set arg as signal handler
8269 * (includes "" case, which ignores signal) */
8270 if (argv[0][0] == '-') {
8271 if (argv[0][1] == '\0') { /* "-" */
8272 /* new_cmd remains NULL: "reset these sigs" */
8275 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8278 /* else: "-something", no special meaning */
8283 goto process_sig_list;
8286 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8287 static int FAST_FUNC builtin_type(char **argv)
8289 int ret = EXIT_SUCCESS;
8295 if (0) {} /* make conditional compile easier below */
8296 /*else if (find_alias(*argv))
8297 type = "an alias";*/
8298 #if ENABLE_HUSH_FUNCTIONS
8299 else if (find_function(*argv))
8300 type = "a function";
8302 else if (find_builtin(*argv))
8303 type = "a shell builtin";
8304 else if ((path = find_in_path(*argv)) != NULL)
8307 bb_error_msg("type: %s: not found", *argv);
8312 printf("%s is %s\n", *argv, type);
8320 /* built-in 'fg' and 'bg' handler */
8321 static int FAST_FUNC builtin_fg_bg(char **argv)
8326 if (!G_interactive_fd)
8327 return EXIT_FAILURE;
8329 /* If they gave us no args, assume they want the last backgrounded task */
8331 for (pi = G.job_list; pi; pi = pi->next) {
8332 if (pi->jobid == G.last_jobid) {
8336 bb_error_msg("%s: no current job", argv[0]);
8337 return EXIT_FAILURE;
8339 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8340 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8341 return EXIT_FAILURE;
8343 for (pi = G.job_list; pi; pi = pi->next) {
8344 if (pi->jobid == jobnum) {
8348 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8349 return EXIT_FAILURE;
8351 /* TODO: bash prints a string representation
8352 * of job being foregrounded (like "sleep 1 | cat") */
8353 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8354 /* Put the job into the foreground. */
8355 tcsetpgrp(G_interactive_fd, pi->pgrp);
8358 /* Restart the processes in the job */
8359 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8360 for (i = 0; i < pi->num_cmds; i++) {
8361 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8362 pi->cmds[i].is_stopped = 0;
8364 pi->stopped_cmds = 0;
8366 i = kill(- pi->pgrp, SIGCONT);
8368 if (errno == ESRCH) {
8369 delete_finished_bg_job(pi);
8370 return EXIT_SUCCESS;
8372 bb_perror_msg("kill (SIGCONT)");
8375 if (argv[0][0] == 'f') {
8377 return checkjobs_and_fg_shell(pi);
8379 return EXIT_SUCCESS;
8383 #if ENABLE_HUSH_HELP
8384 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8386 const struct built_in_command *x;
8389 "Built-in commands:\n"
8390 "------------------\n");
8391 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8393 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8396 return EXIT_SUCCESS;
8401 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8404 const char *status_string;
8406 for (job = G.job_list; job; job = job->next) {
8407 if (job->alive_cmds == job->stopped_cmds)
8408 status_string = "Stopped";
8410 status_string = "Running";
8412 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8414 return EXIT_SUCCESS;
8419 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8424 # ifdef M_TRIM_THRESHOLD
8425 /* Optional. Reduces probability of false positives */
8428 /* Crude attempt to find where "free memory" starts,
8429 * sans fragmentation. */
8431 l = (unsigned long)p;
8434 if (l < (unsigned long)p) l = (unsigned long)p;
8437 if (!G.memleak_value)
8438 G.memleak_value = l;
8440 l -= G.memleak_value;
8447 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8452 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8455 return EXIT_SUCCESS;
8458 static int FAST_FUNC builtin_read(char **argv)
8467 /* "!": do not abort on errors.
8468 * Option string must start with "sr" to match BUILTIN_READ_xxx
8470 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8471 if (read_flags == (uint32_t)-1)
8472 return EXIT_FAILURE;
8475 r = shell_builtin_read(set_local_var_from_halves,
8477 get_local_var_value("IFS"), /* can be NULL */
8485 if ((uintptr_t)r > 1) {
8486 bb_error_msg("%s", r);
8487 r = (char*)(uintptr_t)1;
8490 return (uintptr_t)r;
8493 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8494 * built-in 'set' handler
8496 * set [-abCefhmnuvx] [-o option] [argument...]
8497 * set [+abCefhmnuvx] [+o option] [argument...]
8498 * set -- [argument...]
8501 * Implementations shall support the options in both their hyphen and
8502 * plus-sign forms. These options can also be specified as options to sh.
8504 * Write out all variables and their values: set
8505 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8506 * Turn on the -x and -v options: set -xv
8507 * Unset all positional parameters: set --
8508 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8509 * Set the positional parameters to the expansion of x, even if x expands
8510 * with a leading '-' or '+': set -- $x
8512 * So far, we only support "set -- [argument...]" and some of the short names.
8514 static int FAST_FUNC builtin_set(char **argv)
8517 char **pp, **g_argv;
8518 char *arg = *++argv;
8522 for (e = G.top_var; e; e = e->next)
8524 return EXIT_SUCCESS;
8528 if (strcmp(arg, "--") == 0) {
8532 if (arg[0] != '+' && arg[0] != '-')
8534 for (n = 1; arg[n]; ++n) {
8535 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8537 if (arg[n] == 'o' && argv[1])
8540 } while ((arg = *++argv) != NULL);
8541 /* Now argv[0] is 1st argument */
8544 return EXIT_SUCCESS;
8547 /* NB: G.global_argv[0] ($0) is never freed/changed */
8548 g_argv = G.global_argv;
8549 if (G.global_args_malloced) {
8555 G.global_args_malloced = 1;
8556 pp = xzalloc(sizeof(pp[0]) * 2);
8557 pp[0] = g_argv[0]; /* retain $0 */
8560 /* This realloc's G.global_argv */
8561 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8568 return EXIT_SUCCESS;
8570 /* Nothing known, so abort */
8572 bb_error_msg("set: %s: invalid option", arg);
8573 return EXIT_FAILURE;
8576 static int FAST_FUNC builtin_shift(char **argv)
8579 argv = skip_dash_dash(argv);
8583 if (n >= 0 && n < G.global_argc) {
8584 if (G.global_args_malloced) {
8587 free(G.global_argv[m++]);
8590 memmove(&G.global_argv[1], &G.global_argv[n+1],
8591 G.global_argc * sizeof(G.global_argv[0]));
8592 return EXIT_SUCCESS;
8594 return EXIT_FAILURE;
8597 static int FAST_FUNC builtin_source(char **argv)
8599 char *arg_path, *filename;
8602 #if ENABLE_HUSH_FUNCTIONS
8606 argv = skip_dash_dash(argv);
8609 /* bash says: "bash: .: filename argument required" */
8610 return 2; /* bash compat */
8613 if (!strchr(filename, '/')) {
8614 arg_path = find_in_path(filename);
8616 filename = arg_path;
8618 input = fopen_or_warn(filename, "r");
8621 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8622 return EXIT_FAILURE;
8624 close_on_exec_on(fileno(input));
8626 #if ENABLE_HUSH_FUNCTIONS
8627 sv_flg = G.flag_return_in_progress;
8628 /* "we are inside sourced file, ok to use return" */
8629 G.flag_return_in_progress = -1;
8631 save_and_replace_G_args(&sv, argv);
8633 //TODO: syntax errors in sourced file should never abort the "calling" script.
8634 //Try: bash -c '. ./bad_file; echo YES'
8635 parse_and_run_file(input);
8638 restore_G_args(&sv, argv);
8639 #if ENABLE_HUSH_FUNCTIONS
8640 G.flag_return_in_progress = sv_flg;
8643 return G.last_exitcode;
8646 static int FAST_FUNC builtin_umask(char **argv)
8652 argv = skip_dash_dash(argv);
8654 mode_t old_mask = mask;
8657 rc = bb_parse_mode(argv[0], &mask);
8662 * bash: umask: 'q': invalid symbolic mode operator
8663 * bash: umask: 999: octal number out of range
8665 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8670 printf("%04o\n", (unsigned) mask);
8671 /* fall through and restore mask which we set to 0 */
8675 return !rc; /* rc != 0 - success */
8678 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8679 static int FAST_FUNC builtin_unset(char **argv)
8684 /* "!": do not abort on errors */
8685 /* "+": stop at 1st non-option */
8686 opts = getopt32(argv, "!+vf");
8687 if (opts == (unsigned)-1)
8688 return EXIT_FAILURE;
8690 bb_error_msg("unset: -v and -f are exclusive");
8691 return EXIT_FAILURE;
8697 if (!(opts & 2)) { /* not -f */
8698 if (unset_local_var(*argv)) {
8699 /* unset <nonexistent_var> doesn't fail.
8700 * Error is when one tries to unset RO var.
8701 * Message was printed by unset_local_var. */
8705 #if ENABLE_HUSH_FUNCTIONS
8715 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8716 static int FAST_FUNC builtin_wait(char **argv)
8718 int ret = EXIT_SUCCESS;
8721 argv = skip_dash_dash(argv);
8722 if (argv[0] == NULL) {
8723 /* Don't care about wait results */
8724 /* Note 1: must wait until there are no more children */
8725 /* Note 2: must be interruptible */
8727 * $ sleep 3 & sleep 6 & wait
8732 * $ sleep 3 & sleep 6 & wait
8736 * ^C <-- after ~4 sec from keyboard
8739 sigaddset(&G.blocked_set, SIGCHLD);
8740 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8743 if (errno == ECHILD)
8745 /* Wait for SIGCHLD or any other signal of interest */
8746 /* sigtimedwait with infinite timeout: */
8747 sig = sigwaitinfo(&G.blocked_set, NULL);
8749 sig = check_and_run_traps(sig);
8750 if (sig && sig != SIGCHLD) { /* see note 2 */
8756 sigdelset(&G.blocked_set, SIGCHLD);
8757 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8761 /* This is probably buggy wrt interruptible-ness */
8763 pid_t pid = bb_strtou(*argv, NULL, 10);
8765 /* mimic bash message */
8766 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8767 return EXIT_FAILURE;
8769 if (waitpid(pid, &status, 0) == pid) {
8770 if (WIFSIGNALED(status))
8771 ret = 128 + WTERMSIG(status);
8772 else if (WIFEXITED(status))
8773 ret = WEXITSTATUS(status);
8777 bb_perror_msg("wait %s", *argv);
8786 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8787 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8790 def = bb_strtou(argv[1], NULL, 10);
8791 if (errno || def < def_min || argv[2]) {
8792 bb_error_msg("%s: bad arguments", argv[0]);
8800 #if ENABLE_HUSH_LOOPS
8801 static int FAST_FUNC builtin_break(char **argv)
8804 if (G.depth_of_loop == 0) {
8805 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8806 return EXIT_SUCCESS; /* bash compat */
8808 G.flag_break_continue++; /* BC_BREAK = 1 */
8810 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8811 if (depth == UINT_MAX)
8812 G.flag_break_continue = BC_BREAK;
8813 if (G.depth_of_loop < depth)
8814 G.depth_break_continue = G.depth_of_loop;
8816 return EXIT_SUCCESS;
8819 static int FAST_FUNC builtin_continue(char **argv)
8821 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8822 return builtin_break(argv);
8826 #if ENABLE_HUSH_FUNCTIONS
8827 static int FAST_FUNC builtin_return(char **argv)
8831 if (G.flag_return_in_progress != -1) {
8832 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8833 return EXIT_FAILURE; /* bash compat */
8836 G.flag_return_in_progress = 1;
8839 * out of range: wraps around at 256, does not error out
8840 * non-numeric param:
8841 * f() { false; return qwe; }; f; echo $?
8842 * bash: return: qwe: numeric argument required <== we do this
8843 * 255 <== we also do this
8845 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);