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 /* It so happens that all such cases are totally fatal
1099 * even if shell is interactive: EOF while looking for closing
1100 * delimiter. There is nowhere to read stuff from after that,
1101 * it's EOF! The only choice is to terminate.
1103 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1104 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1106 char msg[2] = { ch, '\0' };
1107 syntax_error_unterm_str(lineno, msg);
1111 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1116 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1120 # undef die_if_script
1121 # undef syntax_error
1122 # undef syntax_error_at
1123 # undef syntax_error_unterm_ch
1124 # undef syntax_error_unterm_str
1125 # undef syntax_error_unexpected_ch
1127 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1128 # define syntax_error(msg) syntax_error(__LINE__, msg)
1129 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1130 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1131 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1132 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1136 #if ENABLE_HUSH_INTERACTIVE
1137 static void cmdedit_update_prompt(void);
1139 # define cmdedit_update_prompt() ((void)0)
1143 /* Utility functions
1145 /* Replace each \x with x in place, return ptr past NUL. */
1146 static char *unbackslash(char *src)
1148 char *dst = src = strchrnul(src, '\\');
1152 if ((*dst++ = *src++) == '\0')
1158 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1179 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1180 v[count1 + count2] = NULL;
1183 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1187 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1189 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1190 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1193 #define add_strings_to_strings(strings, add, need_to_dup) \
1194 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1197 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1198 static char **add_string_to_strings(char **strings, char *add)
1203 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1206 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1208 char **ptr = add_string_to_strings(strings, add);
1209 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1212 #define add_string_to_strings(strings, add) \
1213 xx_add_string_to_strings(__LINE__, strings, add)
1216 static void free_strings(char **strings)
1231 /* Helpers for setting new $n and restoring them back
1233 typedef struct save_arg_t {
1237 smallint sv_g_malloced;
1240 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1244 sv->sv_argv0 = argv[0];
1245 sv->sv_g_argv = G.global_argv;
1246 sv->sv_g_argc = G.global_argc;
1247 sv->sv_g_malloced = G.global_args_malloced;
1249 argv[0] = G.global_argv[0]; /* retain $0 */
1250 G.global_argv = argv;
1251 G.global_args_malloced = 0;
1259 static void restore_G_args(save_arg_t *sv, char **argv)
1263 if (G.global_args_malloced) {
1264 /* someone ran "set -- arg1 arg2 ...", undo */
1266 while (*++pp) /* note: does not free $0 */
1268 free(G.global_argv);
1270 argv[0] = sv->sv_argv0;
1271 G.global_argv = sv->sv_g_argv;
1272 G.global_argc = sv->sv_g_argc;
1273 G.global_args_malloced = sv->sv_g_malloced;
1277 /* Basic theory of signal handling in shell
1278 * ========================================
1279 * This does not describe what hush does, rather, it is current understanding
1280 * what it _should_ do. If it doesn't, it's a bug.
1281 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1283 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1284 * is finished or backgrounded. It is the same in interactive and
1285 * non-interactive shells, and is the same regardless of whether
1286 * a user trap handler is installed or a shell special one is in effect.
1287 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1288 * backgrounds (i.e. stops) or kills all members of currently running
1291 * Wait builtin in interruptible by signals for which user trap is set
1292 * or by SIGINT in interactive shell.
1294 * Trap handlers will execute even within trap handlers. (right?)
1296 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1297 * except for handlers set to '' (empty string).
1299 * If job control is off, backgrounded commands ("cmd &")
1300 * have SIGINT, SIGQUIT set to SIG_IGN.
1302 * Commands which are run in command substitution ("`cmd`")
1303 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1305 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1306 * by the shell from its parent.
1308 * Signals which differ from SIG_DFL action
1309 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1312 * SIGTERM (interactive): ignore
1313 * SIGHUP (interactive):
1314 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1315 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1316 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1317 * that all pipe members are stopped. Try this in bash:
1318 * while :; do :; done - ^Z does not background it
1319 * (while :; do :; done) - ^Z backgrounds it
1320 * SIGINT (interactive): wait for last pipe, ignore the rest
1321 * of the command line, show prompt. NB: ^C does not send SIGINT
1322 * to interactive shell while shell is waiting for a pipe,
1323 * since shell is bg'ed (is not in foreground process group).
1324 * Example 1: this waits 5 sec, but does not execute ls:
1325 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1326 * Example 2: this does not wait and does not execute ls:
1327 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1328 * Example 3: this does not wait 5 sec, but executes ls:
1329 * "sleep 5; ls -l" + press ^C
1331 * (What happens to signals which are IGN on shell start?)
1332 * (What happens with signal mask on shell start?)
1334 * Implementation in hush
1335 * ======================
1336 * We use in-kernel pending signal mask to determine which signals were sent.
1337 * We block all signals which we don't want to take action immediately,
1338 * i.e. we block all signals which need to have special handling as described
1339 * above, and all signals which have traps set.
1340 * After each pipe execution, we extract any pending signals via sigtimedwait()
1343 * unsigned non_DFL_mask: a mask of such "special" signals
1344 * sigset_t blocked_set: current blocked signal set
1347 * clear bit in blocked_set unless it is also in non_DFL_mask
1348 * "trap 'cmd' SIGxxx":
1349 * set bit in blocked_set (even if 'cmd' is '')
1350 * after [v]fork, if we plan to be a shell:
1351 * unblock signals with special interactive handling
1352 * (child shell is not interactive),
1353 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1354 * after [v]fork, if we plan to exec:
1355 * POSIX says fork clears pending signal mask in child - no need to clear it.
1356 * Restore blocked signal set to one inherited by shell just prior to exec.
1358 * Note: as a result, we do not use signal handlers much. The only uses
1359 * are to count SIGCHLDs
1360 * and to restore tty pgrp on signal-induced exit.
1363 * Standard says "When a subshell is entered, traps that are not being ignored
1364 * are set to the default actions". bash interprets it so that traps which
1365 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1368 SPECIAL_INTERACTIVE_SIGS = 0
1373 SPECIAL_JOB_SIGS = 0
1381 #if ENABLE_HUSH_FAST
1382 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1385 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1391 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1392 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1393 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1394 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1396 /* Restores tty foreground process group, and exits.
1397 * May be called as signal handler for fatal signal
1398 * (will resend signal to itself, producing correct exit state)
1399 * or called directly with -EXITCODE.
1400 * We also call it if xfunc is exiting. */
1401 static void sigexit(int sig) NORETURN;
1402 static void sigexit(int sig)
1404 /* Disable all signals: job control, SIGPIPE, etc. */
1405 sigprocmask_allsigs(SIG_BLOCK);
1407 /* Careful: we can end up here after [v]fork. Do not restore
1408 * tty pgrp then, only top-level shell process does that */
1409 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1410 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1412 /* Not a signal, just exit */
1416 kill_myself_with_sig(sig); /* does not return */
1420 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1421 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1425 /* Restores tty foreground process group, and exits. */
1426 static void hush_exit(int exitcode) NORETURN;
1427 static void hush_exit(int exitcode)
1430 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1431 /* Prevent recursion:
1432 * trap "echo Hi; exit" EXIT; exit
1435 /* argv[0] is unused */
1436 argv[1] = G.traps[0];
1438 G.exiting = 1; /* prevent EXIT trap recursion */
1439 /* Note: G.traps[0] is not cleared!
1440 * "trap" will still show it, if executed
1445 #if ENABLE_FEATURE_CLEAN_UP
1447 struct variable *cur_var;
1448 if (G.cwd != bb_msg_unknown)
1450 cur_var = G.top_var;
1452 struct variable *tmp = cur_var;
1453 if (!cur_var->max_len)
1454 free(cur_var->varstr);
1455 cur_var = cur_var->next;
1463 sigexit(- (exitcode & 0xff));
1470 static int check_and_run_traps(int sig)
1472 /* I want it in rodata, not in bss.
1473 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1474 * initializer. But other compilers may still use bss.
1475 * TODO: find more portable solution.
1477 static const struct timespec zero_timespec = { 0, 0 };
1478 smalluint save_rcode;
1484 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1489 if (G.traps && G.traps[sig]) {
1490 if (G.traps[sig][0]) {
1491 /* We have user-defined handler */
1493 /* argv[0] is unused */
1494 argv[1] = G.traps[sig];
1496 save_rcode = G.last_exitcode;
1498 G.last_exitcode = save_rcode;
1499 } /* else: "" trap, ignoring signal */
1502 /* not a trap: special action */
1504 #if ENABLE_HUSH_FAST
1507 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1511 /* Builtin was ^C'ed, make it look prettier: */
1518 /* bash is observed to signal whole process groups,
1519 * not individual processes */
1520 for (job = G.job_list; job; job = job->next) {
1523 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1524 if (kill(- job->pgrp, SIGHUP) == 0)
1525 kill(- job->pgrp, SIGCONT);
1530 default: /* ignored: */
1531 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1539 static const char *get_cwd(int force)
1541 if (force || G.cwd == NULL) {
1542 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1543 * we must not try to free(bb_msg_unknown) */
1544 if (G.cwd == bb_msg_unknown)
1546 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1548 G.cwd = bb_msg_unknown;
1555 * Shell and environment variable support
1557 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1559 struct variable **pp;
1560 struct variable *cur;
1563 while ((cur = *pp) != NULL) {
1564 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1571 static const char* FAST_FUNC get_local_var_value(const char *name)
1573 struct variable **vpp;
1574 unsigned len = strlen(name);
1576 if (G.expanded_assignments) {
1577 char **cpp = G.expanded_assignments;
1580 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1581 return cp + len + 1;
1586 vpp = get_ptr_to_local_var(name, len);
1588 return (*vpp)->varstr + len + 1;
1590 if (strcmp(name, "PPID") == 0)
1591 return utoa(G.root_ppid);
1592 // bash compat: UID? EUID?
1593 #if ENABLE_HUSH_RANDOM_SUPPORT
1594 if (strcmp(name, "RANDOM") == 0)
1595 return utoa(next_random(&G.random_gen));
1600 /* str holds "NAME=VAL" and is expected to be malloced.
1601 * We take ownership of it.
1603 * 0: do not change export flag
1604 * (if creating new variable, flag will be 0)
1605 * 1: set export flag and putenv the variable
1606 * -1: clear export flag and unsetenv the variable
1607 * flg_read_only is set only when we handle -R var=val
1609 #if !BB_MMU && ENABLE_HUSH_LOCAL
1610 /* all params are used */
1611 #elif BB_MMU && ENABLE_HUSH_LOCAL
1612 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1613 set_local_var(str, flg_export, local_lvl)
1614 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1615 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1616 set_local_var(str, flg_export)
1617 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1618 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1619 set_local_var(str, flg_export, flg_read_only)
1621 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1623 struct variable **var_pp;
1624 struct variable *cur;
1628 eq_sign = strchr(str, '=');
1629 if (!eq_sign) { /* not expected to ever happen? */
1634 name_len = eq_sign - str + 1; /* including '=' */
1635 var_pp = &G.top_var;
1636 while ((cur = *var_pp) != NULL) {
1637 if (strncmp(cur->varstr, str, name_len) != 0) {
1638 var_pp = &cur->next;
1641 /* We found an existing var with this name */
1642 if (cur->flg_read_only) {
1646 bb_error_msg("%s: readonly variable", str);
1650 if (flg_export == -1) { // "&& cur->flg_export" ?
1651 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1656 #if ENABLE_HUSH_LOCAL
1657 if (cur->func_nest_level < local_lvl) {
1658 /* New variable is declared as local,
1659 * and existing one is global, or local
1660 * from enclosing function.
1661 * Remove and save old one: */
1662 *var_pp = cur->next;
1663 cur->next = *G.shadowed_vars_pp;
1664 *G.shadowed_vars_pp = cur;
1665 /* bash 3.2.33(1) and exported vars:
1667 * # f() { local z=a; env | grep ^z; }
1673 if (cur->flg_export)
1678 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1683 if (cur->max_len != 0) {
1684 if (cur->max_len >= strlen(str)) {
1685 /* This one is from startup env, reuse space */
1686 strcpy(cur->varstr, str);
1690 /* max_len == 0 signifies "malloced" var, which we can
1691 * (and has to) free */
1695 goto set_str_and_exp;
1698 /* Not found - create new variable struct */
1699 cur = xzalloc(sizeof(*cur));
1700 #if ENABLE_HUSH_LOCAL
1701 cur->func_nest_level = local_lvl;
1703 cur->next = *var_pp;
1709 cur->flg_read_only = flg_read_only;
1712 if (flg_export == 1)
1713 cur->flg_export = 1;
1714 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1715 cmdedit_update_prompt();
1716 if (cur->flg_export) {
1717 if (flg_export == -1) {
1718 cur->flg_export = 0;
1719 /* unsetenv was already done */
1721 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1722 return putenv(cur->varstr);
1728 /* Used at startup and after each cd */
1729 static void set_pwd_var(int exp)
1731 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1732 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1735 static int unset_local_var_len(const char *name, int name_len)
1737 struct variable *cur;
1738 struct variable **var_pp;
1741 return EXIT_SUCCESS;
1742 var_pp = &G.top_var;
1743 while ((cur = *var_pp) != NULL) {
1744 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1745 if (cur->flg_read_only) {
1746 bb_error_msg("%s: readonly variable", name);
1747 return EXIT_FAILURE;
1749 *var_pp = cur->next;
1750 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1751 bb_unsetenv(cur->varstr);
1752 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1753 cmdedit_update_prompt();
1757 return EXIT_SUCCESS;
1759 var_pp = &cur->next;
1761 return EXIT_SUCCESS;
1764 static int unset_local_var(const char *name)
1766 return unset_local_var_len(name, strlen(name));
1769 static void unset_vars(char **strings)
1777 const char *eq = strchrnul(*v, '=');
1778 unset_local_var_len(*v, (int)(eq - *v));
1784 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1786 char *var = xasprintf("%s=%s", name, val);
1787 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1792 * Helpers for "var1=val1 var2=val2 cmd" feature
1794 static void add_vars(struct variable *var)
1796 struct variable *next;
1800 var->next = G.top_var;
1802 if (var->flg_export) {
1803 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1804 putenv(var->varstr);
1806 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1812 static struct variable *set_vars_and_save_old(char **strings)
1815 struct variable *old = NULL;
1821 struct variable *var_p;
1822 struct variable **var_pp;
1825 eq = strchr(*s, '=');
1827 var_pp = get_ptr_to_local_var(*s, eq - *s);
1829 /* Remove variable from global linked list */
1831 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1832 *var_pp = var_p->next;
1833 /* Add it to returned list */
1837 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1848 static int FAST_FUNC static_get(struct in_str *i)
1858 static int FAST_FUNC static_peek(struct in_str *i)
1863 #if ENABLE_HUSH_INTERACTIVE
1865 static void cmdedit_update_prompt(void)
1867 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1868 G.PS1 = get_local_var_value("PS1");
1871 G.PS2 = get_local_var_value("PS2");
1879 static const char *setup_prompt_string(int promptmode)
1881 const char *prompt_str;
1882 debug_printf("setup_prompt_string %d ", promptmode);
1883 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1884 /* Set up the prompt */
1885 if (promptmode == 0) { /* PS1 */
1887 /* bash uses $PWD value, even if it is set by user.
1888 * It uses current dir only if PWD is unset.
1889 * We always use current dir. */
1890 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1895 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1896 debug_printf("result '%s'\n", prompt_str);
1900 static void get_user_input(struct in_str *i)
1903 const char *prompt_str;
1905 prompt_str = setup_prompt_string(i->promptmode);
1906 # if ENABLE_FEATURE_EDITING
1907 /* Enable command line editing only while a command line
1908 * is actually being read */
1910 /* Unicode support should be activated even if LANG is set
1911 * _during_ shell execution, not only if it was set when
1912 * shell was started. Therefore, re-check LANG every time:
1914 reinit_unicode(get_local_var_value("LANG"));
1917 /* buglet: SIGINT will not make new prompt to appear _at once_,
1918 * only after <Enter>. (^C will work) */
1919 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1920 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1921 check_and_run_traps(0);
1922 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1923 i->eof_flag = (r < 0);
1924 if (i->eof_flag) { /* EOF/error detected */
1925 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1926 G.user_input_buf[1] = '\0';
1931 fputs(prompt_str, stdout);
1933 G.user_input_buf[0] = r = fgetc(i->file);
1934 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1935 //do we need check_and_run_traps(0)? (maybe only if stdin)
1936 } while (G.flag_SIGINT);
1937 i->eof_flag = (r == EOF);
1939 i->p = G.user_input_buf;
1942 #endif /* INTERACTIVE */
1944 /* This is the magic location that prints prompts
1945 * and gets data back from the user */
1946 static int FAST_FUNC file_get(struct in_str *i)
1950 /* If there is data waiting, eat it up */
1951 if (i->p && *i->p) {
1952 #if ENABLE_HUSH_INTERACTIVE
1956 if (i->eof_flag && !*i->p)
1958 /* note: ch is never NUL */
1960 /* need to double check i->file because we might be doing something
1961 * more complicated by now, like sourcing or substituting. */
1962 #if ENABLE_HUSH_INTERACTIVE
1963 if (G_interactive_fd && i->file == stdin) {
1966 } while (!*i->p); /* need non-empty line */
1967 i->promptmode = 1; /* PS2 */
1971 do ch = fgetc(i->file); while (ch == '\0');
1973 debug_printf("file_get: got '%c' %d\n", ch, ch);
1977 /* All callers guarantee this routine will never
1978 * be used right after a newline, so prompting is not needed.
1980 static int FAST_FUNC file_peek(struct in_str *i)
1983 if (i->p && *i->p) {
1984 if (i->eof_flag && !i->p[1])
1987 /* note: ch is never NUL */
1989 do ch = fgetc(i->file); while (ch == '\0');
1990 i->eof_flag = (ch == EOF);
1991 i->peek_buf[0] = ch;
1992 i->peek_buf[1] = '\0';
1994 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1998 static void setup_file_in_str(struct in_str *i, FILE *f)
2000 memset(i, 0, sizeof(*i));
2001 i->peek = file_peek;
2003 /* i->promptmode = 0; - PS1 (memset did it) */
2008 static void setup_string_in_str(struct in_str *i, const char *s)
2010 memset(i, 0, sizeof(*i));
2011 i->peek = static_peek;
2012 i->get = static_get;
2013 /* i->promptmode = 0; - PS1 (memset did it) */
2015 /* i->eof_flag = 0; */
2022 #define B_CHUNK (32 * sizeof(char*))
2024 static void o_reset_to_empty_unquoted(o_string *o)
2027 o->has_quoted_part = 0;
2032 static void o_free(o_string *o)
2035 memset(o, 0, sizeof(*o));
2038 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2043 static void o_grow_by(o_string *o, int len)
2045 if (o->length + len > o->maxlen) {
2046 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2047 o->data = xrealloc(o->data, 1 + o->maxlen);
2051 static void o_addchr(o_string *o, int ch)
2053 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2055 o->data[o->length] = ch;
2057 o->data[o->length] = '\0';
2060 static void o_addblock(o_string *o, const char *str, int len)
2063 memcpy(&o->data[o->length], str, len);
2065 o->data[o->length] = '\0';
2068 static void o_addstr(o_string *o, const char *str)
2070 o_addblock(o, str, strlen(str));
2074 static void nommu_addchr(o_string *o, int ch)
2080 # define nommu_addchr(o, str) ((void)0)
2083 static void o_addstr_with_NUL(o_string *o, const char *str)
2085 o_addblock(o, str, strlen(str) + 1);
2089 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2090 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2091 * Apparently, on unquoted $v bash still does globbing
2092 * ("v='*.txt'; echo $v" prints all .txt files),
2093 * but NOT brace expansion! Thus, there should be TWO independent
2094 * quoting mechanisms on $v expansion side: one protects
2095 * $v from brace expansion, and other additionally protects "$v" against globbing.
2096 * We have only second one.
2099 #if ENABLE_HUSH_BRACE_EXPANSION
2100 # define MAYBE_BRACES "{}"
2102 # define MAYBE_BRACES ""
2105 /* My analysis of quoting semantics tells me that state information
2106 * is associated with a destination, not a source.
2108 static void o_addqchr(o_string *o, int ch)
2111 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2116 o->data[o->length] = '\\';
2119 o->data[o->length] = ch;
2121 o->data[o->length] = '\0';
2124 static void o_addQchr(o_string *o, int ch)
2127 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2128 && strchr("*?[\\" MAYBE_BRACES, ch)
2131 o->data[o->length] = '\\';
2135 o->data[o->length] = ch;
2137 o->data[o->length] = '\0';
2140 static void o_addqblock(o_string *o, const char *str, int len)
2145 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2146 if (ordinary_cnt > len) /* paranoia */
2148 o_addblock(o, str, ordinary_cnt);
2149 if (ordinary_cnt == len)
2151 str += ordinary_cnt;
2152 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2156 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2158 o->data[o->length] = '\\';
2162 o->data[o->length] = ch;
2164 o->data[o->length] = '\0';
2168 static void o_addQblock(o_string *o, const char *str, int len)
2170 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2171 o_addblock(o, str, len);
2174 o_addqblock(o, str, len);
2177 static void o_addQstr(o_string *o, const char *str)
2179 o_addQblock(o, str, strlen(str));
2182 /* A special kind of o_string for $VAR and `cmd` expansion.
2183 * It contains char* list[] at the beginning, which is grown in 16 element
2184 * increments. Actual string data starts at the next multiple of 16 * (char*).
2185 * list[i] contains an INDEX (int!) into this string data.
2186 * It means that if list[] needs to grow, data needs to be moved higher up
2187 * but list[i]'s need not be modified.
2188 * NB: remembering how many list[i]'s you have there is crucial.
2189 * o_finalize_list() operation post-processes this structure - calculates
2190 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2192 #if DEBUG_EXPAND || DEBUG_GLOB
2193 static void debug_print_list(const char *prefix, o_string *o, int n)
2195 char **list = (char**)o->data;
2196 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2200 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2201 prefix, list, n, string_start, o->length, o->maxlen,
2202 !!(o->o_expflags & EXP_FLAG_GLOB),
2204 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2207 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2208 o->data + (int)(uintptr_t)list[i] + string_start,
2209 o->data + (int)(uintptr_t)list[i] + string_start);
2213 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2215 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2219 # define debug_print_list(prefix, o, n) ((void)0)
2222 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2223 * in list[n] so that it points past last stored byte so far.
2224 * It returns n+1. */
2225 static int o_save_ptr_helper(o_string *o, int n)
2227 char **list = (char**)o->data;
2231 if (!o->has_empty_slot) {
2232 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2233 string_len = o->length - string_start;
2234 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2235 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2236 /* list[n] points to string_start, make space for 16 more pointers */
2237 o->maxlen += 0x10 * sizeof(list[0]);
2238 o->data = xrealloc(o->data, o->maxlen + 1);
2239 list = (char**)o->data;
2240 memmove(list + n + 0x10, list + n, string_len);
2241 o->length += 0x10 * sizeof(list[0]);
2243 debug_printf_list("list[%d]=%d string_start=%d\n",
2244 n, string_len, string_start);
2247 /* We have empty slot at list[n], reuse without growth */
2248 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2249 string_len = o->length - string_start;
2250 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2251 n, string_len, string_start);
2252 o->has_empty_slot = 0;
2254 list[n] = (char*)(uintptr_t)string_len;
2258 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2259 static int o_get_last_ptr(o_string *o, int n)
2261 char **list = (char**)o->data;
2262 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2264 return ((int)(uintptr_t)list[n-1]) + string_start;
2267 #if ENABLE_HUSH_BRACE_EXPANSION
2268 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2269 * first, it processes even {a} (no commas), second,
2270 * I didn't manage to make it return strings when they don't match
2271 * existing files. Need to re-implement it.
2275 static int glob_needed(const char *s)
2284 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2290 /* Return pointer to next closing brace or to comma */
2291 static const char *next_brace_sub(const char *cp)
2295 while (*cp != '\0') {
2302 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2308 return *cp != '\0' ? cp : NULL;
2310 /* Recursive brace globber. Note: may garble pattern[]. */
2311 static int glob_brace(char *pattern, o_string *o, int n)
2313 char *new_pattern_buf;
2320 debug_printf_glob("glob_brace('%s')\n", pattern);
2326 if (*begin == '{') {
2327 /* Find the first sub-pattern and at the same time
2328 * find the rest after the closing brace */
2329 next = next_brace_sub(begin);
2331 /* An illegal expression */
2335 /* "{abc}" with no commas - illegal
2336 * brace expr, disregard and skip it */
2342 if (*begin == '\\' && begin[1] != '\0')
2346 debug_printf_glob("begin:%s\n", begin);
2347 debug_printf_glob("next:%s\n", next);
2349 /* Now find the end of the whole brace expression */
2351 while (*rest != '}') {
2352 rest = next_brace_sub(rest);
2354 /* An illegal expression */
2357 debug_printf_glob("rest:%s\n", rest);
2359 rest_len = strlen(++rest) + 1;
2361 /* We are sure the brace expression is well-formed */
2363 /* Allocate working buffer large enough for our work */
2364 new_pattern_buf = xmalloc(strlen(pattern));
2366 /* We have a brace expression. BEGIN points to the opening {,
2367 * NEXT points past the terminator of the first element, and REST
2368 * points past the final }. We will accumulate result names from
2369 * recursive runs for each brace alternative in the buffer using
2374 /* Construct the new glob expression */
2377 mempcpy(new_pattern_buf,
2378 /* We know the prefix for all sub-patterns */
2379 pattern, begin - pattern),
2383 /* Note: glob_brace() may garble new_pattern_buf[].
2384 * That's why we re-copy prefix every time (1st memcpy above).
2386 n = glob_brace(new_pattern_buf, o, n);
2388 /* We saw the last entry */
2392 next = next_brace_sub(next);
2394 free(new_pattern_buf);
2402 memset(&globdata, 0, sizeof(globdata));
2403 gr = glob(pattern, 0, NULL, &globdata);
2404 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2406 if (gr == GLOB_NOMATCH) {
2407 globfree(&globdata);
2408 /* NB: garbles parameter */
2409 unbackslash(pattern);
2410 o_addstr_with_NUL(o, pattern);
2411 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2412 return o_save_ptr_helper(o, n);
2414 if (gr == GLOB_NOSPACE)
2415 bb_error_msg_and_die(bb_msg_memory_exhausted);
2416 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2417 * but we didn't specify it. Paranoia again. */
2418 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2420 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2421 char **argv = globdata.gl_pathv;
2423 o_addstr_with_NUL(o, *argv);
2424 n = o_save_ptr_helper(o, n);
2430 globfree(&globdata);
2434 /* Performs globbing on last list[],
2435 * saving each result as a new list[].
2437 static int perform_glob(o_string *o, int n)
2439 char *pattern, *copy;
2441 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2443 return o_save_ptr_helper(o, n);
2444 pattern = o->data + o_get_last_ptr(o, n);
2445 debug_printf_glob("glob pattern '%s'\n", pattern);
2446 if (!glob_needed(pattern)) {
2447 /* unbackslash last string in o in place, fix length */
2448 o->length = unbackslash(pattern) - o->data;
2449 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2450 return o_save_ptr_helper(o, n);
2453 copy = xstrdup(pattern);
2454 /* "forget" pattern in o */
2455 o->length = pattern - o->data;
2456 n = glob_brace(copy, o, n);
2459 debug_print_list("perform_glob returning", o, n);
2463 #else /* !HUSH_BRACE_EXPANSION */
2466 static int glob_needed(const char *s)
2475 if (*s == '*' || *s == '[' || *s == '?')
2481 /* Performs globbing on last list[],
2482 * saving each result as a new list[].
2484 static int perform_glob(o_string *o, int n)
2490 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2492 return o_save_ptr_helper(o, n);
2493 pattern = o->data + o_get_last_ptr(o, n);
2494 debug_printf_glob("glob pattern '%s'\n", pattern);
2495 if (!glob_needed(pattern)) {
2497 /* unbackslash last string in o in place, fix length */
2498 o->length = unbackslash(pattern) - o->data;
2499 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2500 return o_save_ptr_helper(o, n);
2503 memset(&globdata, 0, sizeof(globdata));
2504 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2505 * If we glob "*.\*" and don't find anything, we need
2506 * to fall back to using literal "*.*", but GLOB_NOCHECK
2507 * will return "*.\*"!
2509 gr = glob(pattern, 0, NULL, &globdata);
2510 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2512 if (gr == GLOB_NOMATCH) {
2513 globfree(&globdata);
2516 if (gr == GLOB_NOSPACE)
2517 bb_error_msg_and_die(bb_msg_memory_exhausted);
2518 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2519 * but we didn't specify it. Paranoia again. */
2520 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2522 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2523 char **argv = globdata.gl_pathv;
2524 /* "forget" pattern in o */
2525 o->length = pattern - o->data;
2527 o_addstr_with_NUL(o, *argv);
2528 n = o_save_ptr_helper(o, n);
2534 globfree(&globdata);
2536 debug_print_list("perform_glob returning", o, n);
2540 #endif /* !HUSH_BRACE_EXPANSION */
2542 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2543 * Otherwise, just finish current list[] and start new */
2544 static int o_save_ptr(o_string *o, int n)
2546 if (o->o_expflags & EXP_FLAG_GLOB) {
2547 /* If o->has_empty_slot, list[n] was already globbed
2548 * (if it was requested back then when it was filled)
2549 * so don't do that again! */
2550 if (!o->has_empty_slot)
2551 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2553 return o_save_ptr_helper(o, n);
2556 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2557 static char **o_finalize_list(o_string *o, int n)
2562 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2564 debug_print_list("finalized", o, n);
2565 debug_printf_expand("finalized n:%d\n", n);
2566 list = (char**)o->data;
2567 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2571 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2576 static void free_pipe_list(struct pipe *pi);
2578 /* Returns pi->next - next pipe in the list */
2579 static struct pipe *free_pipe(struct pipe *pi)
2584 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2585 for (i = 0; i < pi->num_cmds; i++) {
2586 struct command *command;
2587 struct redir_struct *r, *rnext;
2589 command = &pi->cmds[i];
2590 debug_printf_clean(" command %d:\n", i);
2591 if (command->argv) {
2595 for (a = 0, p = command->argv; *p; a++, p++) {
2596 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2599 free_strings(command->argv);
2600 //command->argv = NULL;
2602 /* not "else if": on syntax error, we may have both! */
2603 if (command->group) {
2604 debug_printf_clean(" begin group (cmd_type:%d)\n",
2606 free_pipe_list(command->group);
2607 debug_printf_clean(" end group\n");
2608 //command->group = NULL;
2610 /* else is crucial here.
2611 * If group != NULL, child_func is meaningless */
2612 #if ENABLE_HUSH_FUNCTIONS
2613 else if (command->child_func) {
2614 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2615 command->child_func->parent_cmd = NULL;
2619 free(command->group_as_string);
2620 //command->group_as_string = NULL;
2622 for (r = command->redirects; r; r = rnext) {
2623 debug_printf_clean(" redirect %d%s",
2624 r->rd_fd, redir_table[r->rd_type].descrip);
2625 /* guard against the case >$FOO, where foo is unset or blank */
2626 if (r->rd_filename) {
2627 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2628 free(r->rd_filename);
2629 //r->rd_filename = NULL;
2631 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2635 //command->redirects = NULL;
2637 free(pi->cmds); /* children are an array, they get freed all at once */
2641 //pi->cmdtext = NULL;
2649 static void free_pipe_list(struct pipe *pi)
2653 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2655 debug_printf_clean("pipe followup code %d\n", pi->followup);
2661 /*** Parsing routines ***/
2663 #ifndef debug_print_tree
2664 static void debug_print_tree(struct pipe *pi, int lvl)
2666 static const char *const PIPE[] = {
2672 static const char *RES[] = {
2673 [RES_NONE ] = "NONE" ,
2676 [RES_THEN ] = "THEN" ,
2677 [RES_ELIF ] = "ELIF" ,
2678 [RES_ELSE ] = "ELSE" ,
2681 # if ENABLE_HUSH_LOOPS
2682 [RES_FOR ] = "FOR" ,
2683 [RES_WHILE] = "WHILE",
2684 [RES_UNTIL] = "UNTIL",
2686 [RES_DONE ] = "DONE" ,
2688 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2691 # if ENABLE_HUSH_CASE
2692 [RES_CASE ] = "CASE" ,
2693 [RES_CASE_IN ] = "CASE_IN" ,
2694 [RES_MATCH] = "MATCH",
2695 [RES_CASE_BODY] = "CASE_BODY",
2696 [RES_ESAC ] = "ESAC" ,
2698 [RES_XXXX ] = "XXXX" ,
2699 [RES_SNTX ] = "SNTX" ,
2701 static const char *const CMDTYPE[] = {
2705 # if ENABLE_HUSH_FUNCTIONS
2714 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2715 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2717 while (prn < pi->num_cmds) {
2718 struct command *command = &pi->cmds[prn];
2719 char **argv = command->argv;
2721 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2723 command->assignment_cnt);
2724 if (command->group) {
2725 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2726 CMDTYPE[command->cmd_type],
2729 , " group_as_string:", command->group_as_string
2734 debug_print_tree(command->group, lvl+1);
2738 if (argv) while (*argv) {
2739 fdprintf(2, " '%s'", *argv);
2749 #endif /* debug_print_tree */
2751 static struct pipe *new_pipe(void)
2754 pi = xzalloc(sizeof(struct pipe));
2755 /*pi->followup = 0; - deliberately invalid value */
2756 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2760 /* Command (member of a pipe) is complete, or we start a new pipe
2761 * if ctx->command is NULL.
2762 * No errors possible here.
2764 static int done_command(struct parse_context *ctx)
2766 /* The command is really already in the pipe structure, so
2767 * advance the pipe counter and make a new, null command. */
2768 struct pipe *pi = ctx->pipe;
2769 struct command *command = ctx->command;
2772 if (IS_NULL_CMD(command)) {
2773 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2777 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2778 //debug_print_tree(ctx->list_head, 20);
2780 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2783 /* Only real trickiness here is that the uncommitted
2784 * command structure is not counted in pi->num_cmds. */
2785 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2786 ctx->command = command = &pi->cmds[pi->num_cmds];
2788 memset(command, 0, sizeof(*command));
2789 return pi->num_cmds; /* used only for 0/nonzero check */
2792 static void done_pipe(struct parse_context *ctx, pipe_style type)
2796 debug_printf_parse("done_pipe entered, followup %d\n", type);
2797 /* Close previous command */
2798 not_null = done_command(ctx);
2799 ctx->pipe->followup = type;
2801 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2802 ctx->ctx_inverted = 0;
2803 ctx->pipe->res_word = ctx->ctx_res_w;
2806 /* Without this check, even just <enter> on command line generates
2807 * tree of three NOPs (!). Which is harmless but annoying.
2808 * IOW: it is safe to do it unconditionally. */
2811 || ctx->ctx_res_w == RES_FI
2813 #if ENABLE_HUSH_LOOPS
2814 || ctx->ctx_res_w == RES_DONE
2815 || ctx->ctx_res_w == RES_FOR
2816 || ctx->ctx_res_w == RES_IN
2818 #if ENABLE_HUSH_CASE
2819 || ctx->ctx_res_w == RES_ESAC
2823 debug_printf_parse("done_pipe: adding new pipe: "
2824 "not_null:%d ctx->ctx_res_w:%d\n",
2825 not_null, ctx->ctx_res_w);
2827 ctx->pipe->next = new_p;
2829 /* RES_THEN, RES_DO etc are "sticky" -
2830 * they remain set for pipes inside if/while.
2831 * This is used to control execution.
2832 * RES_FOR and RES_IN are NOT sticky (needed to support
2833 * cases where variable or value happens to match a keyword):
2835 #if ENABLE_HUSH_LOOPS
2836 if (ctx->ctx_res_w == RES_FOR
2837 || ctx->ctx_res_w == RES_IN)
2838 ctx->ctx_res_w = RES_NONE;
2840 #if ENABLE_HUSH_CASE
2841 if (ctx->ctx_res_w == RES_MATCH)
2842 ctx->ctx_res_w = RES_CASE_BODY;
2843 if (ctx->ctx_res_w == RES_CASE)
2844 ctx->ctx_res_w = RES_CASE_IN;
2846 ctx->command = NULL; /* trick done_command below */
2847 /* Create the memory for command, roughly:
2848 * ctx->pipe->cmds = new struct command;
2849 * ctx->command = &ctx->pipe->cmds[0];
2852 //debug_print_tree(ctx->list_head, 10);
2854 debug_printf_parse("done_pipe return\n");
2857 static void initialize_context(struct parse_context *ctx)
2859 memset(ctx, 0, sizeof(*ctx));
2860 ctx->pipe = ctx->list_head = new_pipe();
2861 /* Create the memory for command, roughly:
2862 * ctx->pipe->cmds = new struct command;
2863 * ctx->command = &ctx->pipe->cmds[0];
2868 /* If a reserved word is found and processed, parse context is modified
2869 * and 1 is returned.
2872 struct reserved_combo {
2875 unsigned char assignment_flag;
2879 FLAG_END = (1 << RES_NONE ),
2881 FLAG_IF = (1 << RES_IF ),
2882 FLAG_THEN = (1 << RES_THEN ),
2883 FLAG_ELIF = (1 << RES_ELIF ),
2884 FLAG_ELSE = (1 << RES_ELSE ),
2885 FLAG_FI = (1 << RES_FI ),
2887 # if ENABLE_HUSH_LOOPS
2888 FLAG_FOR = (1 << RES_FOR ),
2889 FLAG_WHILE = (1 << RES_WHILE),
2890 FLAG_UNTIL = (1 << RES_UNTIL),
2891 FLAG_DO = (1 << RES_DO ),
2892 FLAG_DONE = (1 << RES_DONE ),
2893 FLAG_IN = (1 << RES_IN ),
2895 # if ENABLE_HUSH_CASE
2896 FLAG_MATCH = (1 << RES_MATCH),
2897 FLAG_ESAC = (1 << RES_ESAC ),
2899 FLAG_START = (1 << RES_XXXX ),
2902 static const struct reserved_combo* match_reserved_word(o_string *word)
2904 /* Mostly a list of accepted follow-up reserved words.
2905 * FLAG_END means we are done with the sequence, and are ready
2906 * to turn the compound list into a command.
2907 * FLAG_START means the word must start a new compound list.
2909 static const struct reserved_combo reserved_list[] = {
2911 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2912 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2913 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2914 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2915 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2916 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2918 # if ENABLE_HUSH_LOOPS
2919 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2920 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2921 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2922 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2923 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2924 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2926 # if ENABLE_HUSH_CASE
2927 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2928 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2931 const struct reserved_combo *r;
2933 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2934 if (strcmp(word->data, r->literal) == 0)
2939 /* Return 0: not a keyword, 1: keyword
2941 static int reserved_word(o_string *word, struct parse_context *ctx)
2943 # if ENABLE_HUSH_CASE
2944 static const struct reserved_combo reserved_match = {
2945 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2948 const struct reserved_combo *r;
2950 if (word->has_quoted_part)
2952 r = match_reserved_word(word);
2956 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2957 # if ENABLE_HUSH_CASE
2958 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2959 /* "case word IN ..." - IN part starts first MATCH part */
2960 r = &reserved_match;
2963 if (r->flag == 0) { /* '!' */
2964 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2965 syntax_error("! ! command");
2966 ctx->ctx_res_w = RES_SNTX;
2968 ctx->ctx_inverted = 1;
2971 if (r->flag & FLAG_START) {
2972 struct parse_context *old;
2974 old = xmalloc(sizeof(*old));
2975 debug_printf_parse("push stack %p\n", old);
2976 *old = *ctx; /* physical copy */
2977 initialize_context(ctx);
2979 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2980 syntax_error_at(word->data);
2981 ctx->ctx_res_w = RES_SNTX;
2984 /* "{...} fi" is ok. "{...} if" is not
2986 * if { echo foo; } then { echo bar; } fi */
2987 if (ctx->command->group)
2988 done_pipe(ctx, PIPE_SEQ);
2991 ctx->ctx_res_w = r->res;
2992 ctx->old_flag = r->flag;
2993 word->o_assignment = r->assignment_flag;
2995 if (ctx->old_flag & FLAG_END) {
2996 struct parse_context *old;
2998 done_pipe(ctx, PIPE_SEQ);
2999 debug_printf_parse("pop stack %p\n", ctx->stack);
3001 old->command->group = ctx->list_head;
3002 old->command->cmd_type = CMD_NORMAL;
3004 o_addstr(&old->as_string, ctx->as_string.data);
3005 o_free_unsafe(&ctx->as_string);
3006 old->command->group_as_string = xstrdup(old->as_string.data);
3007 debug_printf_parse("pop, remembering as:'%s'\n",
3008 old->command->group_as_string);
3010 *ctx = *old; /* physical copy */
3015 #endif /* HAS_KEYWORDS */
3017 /* Word is complete, look at it and update parsing context.
3018 * Normal return is 0. Syntax errors return 1.
3019 * Note: on return, word is reset, but not o_free'd!
3021 static int done_word(o_string *word, struct parse_context *ctx)
3023 struct command *command = ctx->command;
3025 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3026 if (word->length == 0 && !word->has_quoted_part) {
3027 debug_printf_parse("done_word return 0: true null, ignored\n");
3031 if (ctx->pending_redirect) {
3032 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3033 * only if run as "bash", not "sh" */
3034 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3036 * ...the word that follows the redirection operator
3037 * shall be subjected to tilde expansion, parameter expansion,
3038 * command substitution, arithmetic expansion, and quote
3039 * removal. Pathname expansion shall not be performed
3040 * on the word by a non-interactive shell; an interactive
3041 * shell may perform it, but shall do so only when
3042 * the expansion would result in one word."
3044 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3045 /* Cater for >\file case:
3046 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3047 * Same with heredocs:
3048 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3050 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3051 unbackslash(ctx->pending_redirect->rd_filename);
3052 /* Is it <<"HEREDOC"? */
3053 if (word->has_quoted_part) {
3054 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3057 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3058 ctx->pending_redirect = NULL;
3060 /* If this word wasn't an assignment, next ones definitely
3061 * can't be assignments. Even if they look like ones. */
3062 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3063 && word->o_assignment != WORD_IS_KEYWORD
3065 word->o_assignment = NOT_ASSIGNMENT;
3067 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3068 command->assignment_cnt++;
3069 word->o_assignment = MAYBE_ASSIGNMENT;
3073 # if ENABLE_HUSH_CASE
3074 if (ctx->ctx_dsemicolon
3075 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3077 /* already done when ctx_dsemicolon was set to 1: */
3078 /* ctx->ctx_res_w = RES_MATCH; */
3079 ctx->ctx_dsemicolon = 0;
3082 if (!command->argv /* if it's the first word... */
3083 # if ENABLE_HUSH_LOOPS
3084 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3085 && ctx->ctx_res_w != RES_IN
3087 # if ENABLE_HUSH_CASE
3088 && ctx->ctx_res_w != RES_CASE
3091 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3092 if (reserved_word(word, ctx)) {
3093 o_reset_to_empty_unquoted(word);
3094 debug_printf_parse("done_word return %d\n",
3095 (ctx->ctx_res_w == RES_SNTX));
3096 return (ctx->ctx_res_w == RES_SNTX);
3098 # if ENABLE_HUSH_BASH_COMPAT
3099 if (strcmp(word->data, "[[") == 0) {
3100 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3106 if (command->group) {
3107 /* "{ echo foo; } echo bar" - bad */
3108 syntax_error_at(word->data);
3109 debug_printf_parse("done_word return 1: syntax error, "
3110 "groups and arglists don't mix\n");
3113 if (word->has_quoted_part
3114 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3115 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3116 /* (otherwise it's known to be not empty and is already safe) */
3118 /* exclude "$@" - it can expand to no word despite "" */
3119 char *p = word->data;
3120 while (p[0] == SPECIAL_VAR_SYMBOL
3121 && (p[1] & 0x7f) == '@'
3122 && p[2] == SPECIAL_VAR_SYMBOL
3126 if (p == word->data || p[0] != '\0') {
3127 /* saw no "$@", or not only "$@" but some
3128 * real text is there too */
3129 /* insert "empty variable" reference, this makes
3130 * e.g. "", $empty"" etc to not disappear */
3131 o_addchr(word, SPECIAL_VAR_SYMBOL);
3132 o_addchr(word, SPECIAL_VAR_SYMBOL);
3135 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3136 debug_print_strings("word appended to argv", command->argv);
3139 #if ENABLE_HUSH_LOOPS
3140 if (ctx->ctx_res_w == RES_FOR) {
3141 if (word->has_quoted_part
3142 || !is_well_formed_var_name(command->argv[0], '\0')
3144 /* bash says just "not a valid identifier" */
3145 syntax_error("not a valid identifier in for");
3148 /* Force FOR to have just one word (variable name) */
3149 /* NB: basically, this makes hush see "for v in ..."
3150 * syntax as if it is "for v; in ...". FOR and IN become
3151 * two pipe structs in parse tree. */
3152 done_pipe(ctx, PIPE_SEQ);
3155 #if ENABLE_HUSH_CASE
3156 /* Force CASE to have just one word */
3157 if (ctx->ctx_res_w == RES_CASE) {
3158 done_pipe(ctx, PIPE_SEQ);
3162 o_reset_to_empty_unquoted(word);
3164 debug_printf_parse("done_word return 0\n");
3169 /* Peek ahead in the input to find out if we have a "&n" construct,
3170 * as in "2>&1", that represents duplicating a file descriptor.
3172 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3173 * REDIRFD_SYNTAX_ERR if syntax error,
3174 * REDIRFD_TO_FILE if no & was seen,
3175 * or the number found.
3178 #define parse_redir_right_fd(as_string, input) \
3179 parse_redir_right_fd(input)
3181 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3187 return REDIRFD_TO_FILE;
3189 ch = i_getch(input); /* get the & */
3190 nommu_addchr(as_string, ch);
3193 ch = i_getch(input);
3194 nommu_addchr(as_string, ch);
3195 return REDIRFD_CLOSE;
3199 while (ch != EOF && isdigit(ch)) {
3200 d = d*10 + (ch-'0');
3202 ch = i_getch(input);
3203 nommu_addchr(as_string, ch);
3208 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3210 bb_error_msg("ambiguous redirect");
3211 return REDIRFD_SYNTAX_ERR;
3214 /* Return code is 0 normal, 1 if a syntax error is detected
3216 static int parse_redirect(struct parse_context *ctx,
3219 struct in_str *input)
3221 struct command *command = ctx->command;
3222 struct redir_struct *redir;
3223 struct redir_struct **redirp;
3226 dup_num = REDIRFD_TO_FILE;
3227 if (style != REDIRECT_HEREDOC) {
3228 /* Check for a '>&1' type redirect */
3229 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3230 if (dup_num == REDIRFD_SYNTAX_ERR)
3233 int ch = i_peek(input);
3234 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3235 if (dup_num) { /* <<-... */
3236 ch = i_getch(input);
3237 nommu_addchr(&ctx->as_string, ch);
3242 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3243 int ch = i_peek(input);
3245 /* >|FILE redirect ("clobbering" >).
3246 * Since we do not support "set -o noclobber" yet,
3247 * >| and > are the same for now. Just eat |.
3249 ch = i_getch(input);
3250 nommu_addchr(&ctx->as_string, ch);
3254 /* Create a new redir_struct and append it to the linked list */
3255 redirp = &command->redirects;
3256 while ((redir = *redirp) != NULL) {
3257 redirp = &(redir->next);
3259 *redirp = redir = xzalloc(sizeof(*redir));
3260 /* redir->next = NULL; */
3261 /* redir->rd_filename = NULL; */
3262 redir->rd_type = style;
3263 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3265 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3266 redir_table[style].descrip);
3268 redir->rd_dup = dup_num;
3269 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3270 /* Erik had a check here that the file descriptor in question
3271 * is legit; I postpone that to "run time"
3272 * A "-" representation of "close me" shows up as a -3 here */
3273 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3274 redir->rd_fd, redir->rd_dup);
3276 /* Set ctx->pending_redirect, so we know what to do at the
3277 * end of the next parsed word. */
3278 ctx->pending_redirect = redir;
3283 /* If a redirect is immediately preceded by a number, that number is
3284 * supposed to tell which file descriptor to redirect. This routine
3285 * looks for such preceding numbers. In an ideal world this routine
3286 * needs to handle all the following classes of redirects...
3287 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3288 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3289 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3290 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3292 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3294 * ... If n is quoted, the number shall not be recognized as part of
3295 * the redirection expression. For example:
3297 * writes the character 2 into file a"
3298 * We are getting it right by setting ->has_quoted_part on any \<char>
3300 * A -1 return means no valid number was found,
3301 * the caller should use the appropriate default for this redirection.
3303 static int redirect_opt_num(o_string *o)
3307 if (o->data == NULL)
3309 num = bb_strtou(o->data, NULL, 10);
3310 if (errno || num < 0)
3312 o_reset_to_empty_unquoted(o);
3317 #define fetch_till_str(as_string, input, word, skip_tabs) \
3318 fetch_till_str(input, word, skip_tabs)
3320 static char *fetch_till_str(o_string *as_string,
3321 struct in_str *input,
3325 o_string heredoc = NULL_O_STRING;
3327 int prev = 0; /* not \ */
3332 ch = i_getch(input);
3334 nommu_addchr(as_string, ch);
3335 if ((ch == '\n' || ch == EOF)
3336 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3338 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3339 heredoc.data[past_EOL] = '\0';
3340 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3341 return heredoc.data;
3343 while (ch == '\n') {
3344 o_addchr(&heredoc, ch);
3347 past_EOL = heredoc.length;
3349 ch = i_getch(input);
3351 nommu_addchr(as_string, ch);
3352 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3356 o_free_unsafe(&heredoc);
3359 o_addchr(&heredoc, ch);
3360 nommu_addchr(as_string, ch);
3361 if (prev == '\\' && ch == '\\')
3362 /* Correctly handle foo\\<eol> (not a line cont.) */
3363 prev = 0; /* not \ */
3369 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3370 * and load them all. There should be exactly heredoc_cnt of them.
3372 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3374 struct pipe *pi = ctx->list_head;
3376 while (pi && heredoc_cnt) {
3378 struct command *cmd = pi->cmds;
3380 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3382 cmd->argv ? cmd->argv[0] : "NONE");
3383 for (i = 0; i < pi->num_cmds; i++) {
3384 struct redir_struct *redir = cmd->redirects;
3386 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3387 i, cmd->argv ? cmd->argv[0] : "NONE");
3389 if (redir->rd_type == REDIRECT_HEREDOC) {
3392 redir->rd_type = REDIRECT_HEREDOC2;
3393 /* redir->rd_dup is (ab)used to indicate <<- */
3394 p = fetch_till_str(&ctx->as_string, input,
3395 redir->rd_filename, redir->rd_dup);
3397 syntax_error("unexpected EOF in here document");
3400 free(redir->rd_filename);
3401 redir->rd_filename = p;
3404 redir = redir->next;
3411 /* Should be 0. If it isn't, it's a parse error */
3413 bb_error_msg_and_die("heredoc BUG 2");
3419 static int run_list(struct pipe *pi);
3421 #define parse_stream(pstring, input, end_trigger) \
3422 parse_stream(input, end_trigger)
3424 static struct pipe *parse_stream(char **pstring,
3425 struct in_str *input,
3429 #if !ENABLE_HUSH_FUNCTIONS
3430 #define parse_group(dest, ctx, input, ch) \
3431 parse_group(ctx, input, ch)
3433 static int parse_group(o_string *dest, struct parse_context *ctx,
3434 struct in_str *input, int ch)
3436 /* dest contains characters seen prior to ( or {.
3437 * Typically it's empty, but for function defs,
3438 * it contains function name (without '()'). */
3439 struct pipe *pipe_list;
3441 struct command *command = ctx->command;
3443 debug_printf_parse("parse_group entered\n");
3444 #if ENABLE_HUSH_FUNCTIONS
3445 if (ch == '(' && !dest->has_quoted_part) {
3447 if (done_word(dest, ctx))
3450 goto skip; /* (... */
3451 if (command->argv[1]) { /* word word ... (... */
3452 syntax_error_unexpected_ch('(');
3455 /* it is "word(..." or "word (..." */
3457 ch = i_getch(input);
3458 while (ch == ' ' || ch == '\t');
3460 syntax_error_unexpected_ch(ch);
3463 nommu_addchr(&ctx->as_string, ch);
3465 ch = i_getch(input);
3466 while (ch == ' ' || ch == '\t' || ch == '\n');
3468 syntax_error_unexpected_ch(ch);
3471 nommu_addchr(&ctx->as_string, ch);
3472 command->cmd_type = CMD_FUNCDEF;
3477 #if 0 /* Prevented by caller */
3478 if (command->argv /* word [word]{... */
3479 || dest->length /* word{... */
3480 || dest->has_quoted_part /* ""{... */
3483 debug_printf_parse("parse_group return 1: "
3484 "syntax error, groups and arglists don't mix\n");
3489 #if ENABLE_HUSH_FUNCTIONS
3495 command->cmd_type = CMD_SUBSHELL;
3497 /* bash does not allow "{echo...", requires whitespace */
3498 ch = i_getch(input);
3499 if (ch != ' ' && ch != '\t' && ch != '\n') {
3500 syntax_error_unexpected_ch(ch);
3503 nommu_addchr(&ctx->as_string, ch);
3508 # define as_string NULL
3510 char *as_string = NULL;
3512 pipe_list = parse_stream(&as_string, input, endch);
3515 o_addstr(&ctx->as_string, as_string);
3517 /* empty ()/{} or parse error? */
3518 if (!pipe_list || pipe_list == ERR_PTR) {
3519 /* parse_stream already emitted error msg */
3522 debug_printf_parse("parse_group return 1: "
3523 "parse_stream returned %p\n", pipe_list);
3526 command->group = pipe_list;
3528 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3529 command->group_as_string = as_string;
3530 debug_printf_parse("end of group, remembering as:'%s'\n",
3531 command->group_as_string);
3535 debug_printf_parse("parse_group return 0\n");
3537 /* command remains "open", available for possible redirects */
3540 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3541 /* Subroutines for copying $(...) and `...` things */
3542 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3544 static void add_till_single_quote(o_string *dest, struct in_str *input)
3547 int ch = i_getch(input);
3549 syntax_error_unterm_ch('\'');
3550 /*xfunc_die(); - redundant */
3557 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3558 static void add_till_double_quote(o_string *dest, struct in_str *input)
3561 int ch = i_getch(input);
3563 syntax_error_unterm_ch('"');
3564 /*xfunc_die(); - redundant */
3568 if (ch == '\\') { /* \x. Copy both chars. */
3570 ch = i_getch(input);
3574 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3578 //if (ch == '$') ...
3581 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3583 * "Within the backquoted style of command substitution, backslash
3584 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3585 * The search for the matching backquote shall be satisfied by the first
3586 * backquote found without a preceding backslash; during this search,
3587 * if a non-escaped backquote is encountered within a shell comment,
3588 * a here-document, an embedded command substitution of the $(command)
3589 * form, or a quoted string, undefined results occur. A single-quoted
3590 * or double-quoted string that begins, but does not end, within the
3591 * "`...`" sequence produces undefined results."
3593 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3595 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3598 int ch = i_getch(input);
3602 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3603 ch = i_getch(input);
3607 && (!in_dquote || ch != '"')
3609 o_addchr(dest, '\\');
3613 syntax_error_unterm_ch('`');
3614 /*xfunc_die(); - redundant */
3619 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3620 * quoting and nested ()s.
3621 * "With the $(command) style of command substitution, all characters
3622 * following the open parenthesis to the matching closing parenthesis
3623 * constitute the command. Any valid shell script can be used for command,
3624 * except a script consisting solely of redirections which produces
3625 * unspecified results."
3627 * echo $(echo '(TEST)' BEST) (TEST) BEST
3628 * echo $(echo 'TEST)' BEST) TEST) BEST
3629 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3631 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3632 * can contain arbitrary constructs, just like $(cmd).
3633 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3634 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3636 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3637 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3640 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3641 # if ENABLE_HUSH_BASH_COMPAT
3642 char end_char2 = end_ch >> 8;
3644 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3647 ch = i_getch(input);
3649 syntax_error_unterm_ch(end_ch);
3650 /*xfunc_die(); - redundant */
3652 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3655 /* we look for closing )) of $((EXPR)) */
3656 if (i_peek(input) == end_ch) {
3657 i_getch(input); /* eat second ')' */
3662 if (ch == '(' || ch == '{') {
3663 ch = (ch == '(' ? ')' : '}');
3664 add_till_closing_bracket(dest, input, ch);
3669 add_till_single_quote(dest, input);
3674 add_till_double_quote(dest, input);
3679 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3684 /* \x. Copy verbatim. Important for \(, \) */
3685 ch = i_getch(input);
3687 syntax_error_unterm_ch(')');
3688 /*xfunc_die(); - redundant */
3696 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3698 /* Return code: 0 for OK, 1 for syntax error */
3700 #define parse_dollar(as_string, dest, input, quote_mask) \
3701 parse_dollar(dest, input, quote_mask)
3702 #define as_string NULL
3704 static int parse_dollar(o_string *as_string,
3706 struct in_str *input, unsigned char quote_mask)
3708 int ch = i_peek(input); /* first character after the $ */
3710 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3712 ch = i_getch(input);
3713 nommu_addchr(as_string, ch);
3715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3717 debug_printf_parse(": '%c'\n", ch);
3718 o_addchr(dest, ch | quote_mask);
3721 if (!isalnum(ch) && ch != '_')
3723 ch = i_getch(input);
3724 nommu_addchr(as_string, ch);
3726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3727 } else if (isdigit(ch)) {
3729 ch = i_getch(input);
3730 nommu_addchr(as_string, ch);
3731 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3732 debug_printf_parse(": '%c'\n", ch);
3733 o_addchr(dest, ch | quote_mask);
3734 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3735 } else switch (ch) {
3737 case '!': /* last bg pid */
3738 case '?': /* last exit code */
3739 case '#': /* number of args */
3740 case '*': /* args */
3741 case '@': /* args */
3742 goto make_one_char_var;
3744 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3746 ch = i_getch(input); /* eat '{' */
3747 nommu_addchr(as_string, ch);
3749 ch = i_getch(input); /* first char after '{' */
3750 /* It should be ${?}, or ${#var},
3751 * or even ${?+subst} - operator acting on a special variable,
3752 * or the beginning of variable name.
3755 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3758 syntax_error_unterm_str("${name}");
3759 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3762 nommu_addchr(as_string, ch);
3765 /* It's possible to just call add_till_closing_bracket() at this point.
3766 * However, this regresses some of our testsuite cases
3767 * which check invalid constructs like ${%}.
3768 * Oh well... let's check that the var name part is fine... */
3774 debug_printf_parse(": '%c'\n", ch);
3776 ch = i_getch(input);
3777 nommu_addchr(as_string, ch);
3781 if (!isalnum(ch) && ch != '_') {
3783 unsigned char last_ch;
3784 /* handle parameter expansions
3785 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3787 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3788 goto bad_dollar_syntax;
3790 /* Eat everything until closing '}' (or ':') */
3792 if (ENABLE_HUSH_BASH_COMPAT
3794 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3796 /* It's ${var:N[:M]} thing */
3797 end_ch = '}' * 0x100 + ':';
3799 if (ENABLE_HUSH_BASH_COMPAT
3802 /* It's ${var/[/]pattern[/repl]} thing */
3803 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3805 nommu_addchr(as_string, '/');
3808 end_ch = '}' * 0x100 + '/';
3814 #if ENABLE_HUSH_DOLLAR_OPS
3815 last_ch = add_till_closing_bracket(dest, input, end_ch);
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 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3862 o_addstr(as_string, dest->data + pos);
3863 o_addchr(as_string, ')');
3864 o_addchr(as_string, ')');
3866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3870 # if ENABLE_HUSH_TICK
3871 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3872 o_addchr(dest, quote_mask | '`');
3875 add_till_closing_bracket(dest, input, ')');
3877 o_addstr(as_string, dest->data + pos);
3878 o_addchr(as_string, ')');
3880 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3886 ch = i_getch(input);
3887 nommu_addchr(as_string, ch);
3889 if (isalnum(ch)) { /* it's $_name or $_123 */
3894 /* TODO: $_ and $-: */
3895 /* $_ Shell or shell script name; or last argument of last command
3896 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3897 * but in command's env, set to full pathname used to invoke it */
3898 /* $- Option flags set by set builtin or shell options (-i etc) */
3900 o_addQchr(dest, '$');
3902 debug_printf_parse("parse_dollar return 0\n");
3908 # if ENABLE_HUSH_BASH_COMPAT
3909 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3910 encode_string(dest, input, dquote_end, process_bkslash)
3912 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3913 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3914 encode_string(dest, input, dquote_end)
3916 #define as_string NULL
3920 # if ENABLE_HUSH_BASH_COMPAT
3921 /* all parameters are needed, no macro tricks */
3923 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3924 encode_string(as_string, dest, input, dquote_end)
3927 static int encode_string(o_string *as_string,
3929 struct in_str *input,
3931 int process_bkslash)
3933 #if !ENABLE_HUSH_BASH_COMPAT
3934 const int process_bkslash = 1;
3940 ch = i_getch(input);
3942 nommu_addchr(as_string, ch);
3943 if (ch == dquote_end) { /* may be only '"' or EOF */
3944 debug_printf_parse("encode_string return 0\n");
3947 /* note: can't move it above ch == dquote_end check! */
3949 syntax_error_unterm_ch('"');
3950 /*xfunc_die(); - redundant */
3954 next = i_peek(input);
3956 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3957 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3958 if (process_bkslash && ch == '\\') {
3960 syntax_error("\\<eof>");
3964 * "The backslash retains its special meaning [in "..."]
3965 * only when followed by one of the following characters:
3966 * $, `, ", \, or <newline>. A double quote may be quoted
3967 * within double quotes by preceding it with a backslash."
3968 * NB: in (unquoted) heredoc, above does not apply to ",
3969 * therefore we check for it by "next == dquote_end" cond.
3971 if (next == dquote_end || strchr("$`\\\n", next)) {
3972 ch = i_getch(input); /* eat next */
3974 goto again; /* skip \<newline> */
3975 } /* else: ch remains == '\\', and we double it below: */
3976 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3977 nommu_addchr(as_string, ch);
3981 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3982 debug_printf_parse("encode_string return 1: "
3983 "parse_dollar returned non-0\n");
3988 #if ENABLE_HUSH_TICK
3990 //unsigned pos = dest->length;
3991 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3992 o_addchr(dest, 0x80 | '`');
3993 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3995 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3999 o_addQchr(dest, ch);
4005 * Scan input until EOF or end_trigger char.
4006 * Return a list of pipes to execute, or NULL on EOF
4007 * or if end_trigger character is met.
4008 * On syntax error, exit is shell is not interactive,
4009 * reset parsing machinery and start parsing anew,
4010 * or return ERR_PTR.
4012 static struct pipe *parse_stream(char **pstring,
4013 struct in_str *input,
4016 struct parse_context ctx;
4017 o_string dest = NULL_O_STRING;
4020 /* Single-quote triggers a bypass of the main loop until its mate is
4021 * found. When recursing, quote state is passed in via dest->o_expflags.
4023 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4024 end_trigger ? end_trigger : 'X');
4027 /* If very first arg is "" or '', dest.data may end up NULL.
4028 * Preventing this: */
4029 o_addchr(&dest, '\0');
4032 /* We used to separate words on $IFS here. This was wrong.
4033 * $IFS is used only for word splitting when $var is expanded,
4034 * here we should use blank chars as separators, not $IFS
4037 reset: /* we come back here only on syntax errors in interactive shell */
4039 if (MAYBE_ASSIGNMENT != 0)
4040 dest.o_assignment = MAYBE_ASSIGNMENT;
4041 initialize_context(&ctx);
4044 const char *is_blank;
4045 const char *is_special;
4049 redir_type redir_style;
4051 ch = i_getch(input);
4052 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4053 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4058 syntax_error_unterm_str("here document");
4061 /* end_trigger == '}' case errors out earlier,
4062 * checking only ')' */
4063 if (end_trigger == ')') {
4064 syntax_error_unterm_ch('('); /* exits */
4065 /* goto parse_error; */
4068 if (done_word(&dest, &ctx)) {
4072 done_pipe(&ctx, PIPE_SEQ);
4074 /* If we got nothing... */
4075 /* (this makes bare "&" cmd a no-op.
4076 * bash says: "syntax error near unexpected token '&'") */
4077 if (pi->num_cmds == 0
4078 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4084 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4086 *pstring = ctx.as_string.data;
4088 o_free_unsafe(&ctx.as_string);
4091 debug_printf_parse("parse_stream return %p\n", pi);
4094 nommu_addchr(&ctx.as_string, ch);
4098 next = i_peek(input);
4100 is_special = "{}<>;&|()#'" /* special outside of "str" */
4101 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4102 /* Are { and } special here? */
4103 if (ctx.command->argv /* word [word]{... - non-special */
4104 || dest.length /* word{... - non-special */
4105 || dest.has_quoted_part /* ""{... - non-special */
4106 || (next != ';' /* }; - special */
4107 && next != ')' /* }) - special */
4108 && next != '&' /* }& and }&& ... - special */
4109 && next != '|' /* }|| ... - special */
4110 && !strchr(defifs, next) /* {word - non-special */
4113 /* They are not special, skip "{}" */
4116 is_special = strchr(is_special, ch);
4117 is_blank = strchr(defifs, ch);
4119 if (!is_special && !is_blank) { /* ordinary char */
4121 o_addQchr(&dest, ch);
4122 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4123 || dest.o_assignment == WORD_IS_KEYWORD)
4125 && is_well_formed_var_name(dest.data, '=')
4127 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4133 if (done_word(&dest, &ctx)) {
4137 /* Is this a case when newline is simply ignored?
4139 * "cmd | <newline> cmd ..."
4140 * "case ... in <newline> word) ..."
4142 if (IS_NULL_CMD(ctx.command)
4143 && dest.length == 0 && !dest.has_quoted_part
4145 /* This newline can be ignored. But...
4146 * Without check #1, interactive shell
4147 * ignores even bare <newline>,
4148 * and shows the continuation prompt:
4149 * ps1_prompt$ <enter>
4150 * ps2> _ <=== wrong, should be ps1
4151 * Without check #2, "cmd & <newline>"
4152 * is similarly mistreated.
4153 * (BTW, this makes "cmd & cmd"
4154 * and "cmd && cmd" non-orthogonal.
4155 * Really, ask yourself, why
4156 * "cmd && <newline>" doesn't start
4157 * cmd but waits for more input?
4160 struct pipe *pi = ctx.list_head;
4161 if (pi->num_cmds != 0 /* check #1 */
4162 && pi->followup != PIPE_BG /* check #2 */
4167 /* Treat newline as a command separator. */
4168 done_pipe(&ctx, PIPE_SEQ);
4169 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4171 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4176 dest.o_assignment = MAYBE_ASSIGNMENT;
4178 /* note: if (is_blank) continue;
4179 * will still trigger for us */
4183 /* "cmd}" or "cmd }..." without semicolon or &:
4184 * } is an ordinary char in this case, even inside { cmd; }
4185 * Pathological example: { ""}; } should exec "}" cmd
4188 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4189 || dest.length != 0 /* word} */
4190 || dest.has_quoted_part /* ""} */
4194 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4195 goto skip_end_trigger;
4196 /* else: } does terminate a group */
4199 if (end_trigger && end_trigger == ch
4200 && (ch != ';' || heredoc_cnt == 0)
4201 #if ENABLE_HUSH_CASE
4203 || ctx.ctx_res_w != RES_MATCH
4204 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4209 /* This is technically valid:
4210 * { cat <<HERE; }; echo Ok
4214 * but we don't support this.
4215 * We require heredoc to be in enclosing {}/(),
4218 syntax_error_unterm_str("here document");
4221 if (done_word(&dest, &ctx)) {
4224 done_pipe(&ctx, PIPE_SEQ);
4225 dest.o_assignment = MAYBE_ASSIGNMENT;
4226 /* Do we sit outside of any if's, loops or case's? */
4228 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4232 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4234 *pstring = ctx.as_string.data;
4236 o_free_unsafe(&ctx.as_string);
4239 debug_printf_parse("parse_stream return %p: "
4240 "end_trigger char found\n",
4242 return ctx.list_head;
4249 /* Catch <, > before deciding whether this word is
4250 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4253 redir_fd = redirect_opt_num(&dest);
4254 if (done_word(&dest, &ctx)) {
4257 redir_style = REDIRECT_OVERWRITE;
4259 redir_style = REDIRECT_APPEND;
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4264 else if (next == '(') {
4265 syntax_error(">(process) not supported");
4269 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4271 continue; /* back to top of while (1) */
4273 redir_fd = redirect_opt_num(&dest);
4274 if (done_word(&dest, &ctx)) {
4277 redir_style = REDIRECT_INPUT;
4279 redir_style = REDIRECT_HEREDOC;
4281 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4282 ch = i_getch(input);
4283 nommu_addchr(&ctx.as_string, ch);
4284 } else if (next == '>') {
4285 redir_style = REDIRECT_IO;
4286 ch = i_getch(input);
4287 nommu_addchr(&ctx.as_string, ch);
4290 else if (next == '(') {
4291 syntax_error("<(process) not supported");
4295 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4297 continue; /* back to top of while (1) */
4299 if (dest.length == 0 && !dest.has_quoted_part) {
4300 /* skip "#comment" */
4303 if (ch == EOF || ch == '\n')
4306 /* note: we do not add it to &ctx.as_string */
4308 nommu_addchr(&ctx.as_string, '\n');
4309 continue; /* back to top of while (1) */
4314 /* It's "\<newline>" */
4316 /* Remove trailing '\' from ctx.as_string */
4317 ctx.as_string.data[--ctx.as_string.length] = '\0';
4319 ch = i_getch(input); /* eat it */
4320 continue; /* back to top of while (1) */
4325 if (dest.o_assignment == MAYBE_ASSIGNMENT
4326 /* check that we are not in word in "a=1 2>word b=1": */
4327 && !ctx.pending_redirect
4329 /* ch is a special char and thus this word
4330 * cannot be an assignment */
4331 dest.o_assignment = NOT_ASSIGNMENT;
4334 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4337 case '#': /* non-comment #: "echo a#b" etc */
4338 o_addQchr(&dest, ch);
4342 syntax_error("\\<eof>");
4345 ch = i_getch(input);
4346 /* note: ch != '\n' (that case does not reach this place) */
4347 o_addchr(&dest, '\\');
4348 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4349 o_addchr(&dest, ch);
4350 nommu_addchr(&ctx.as_string, ch);
4351 /* Example: echo Hello \2>file
4352 * we need to know that word 2 is quoted */
4353 dest.has_quoted_part = 1;
4356 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4357 debug_printf_parse("parse_stream parse error: "
4358 "parse_dollar returned non-0\n");
4363 dest.has_quoted_part = 1;
4365 ch = i_getch(input);
4367 syntax_error_unterm_ch('\'');
4368 /*xfunc_die(); - redundant */
4370 nommu_addchr(&ctx.as_string, ch);
4373 o_addqchr(&dest, ch);
4377 dest.has_quoted_part = 1;
4378 if (dest.o_assignment == NOT_ASSIGNMENT)
4379 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4380 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4382 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4384 #if ENABLE_HUSH_TICK
4388 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4389 o_addchr(&dest, '`');
4391 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4393 o_addstr(&ctx.as_string, dest.data + pos);
4394 o_addchr(&ctx.as_string, '`');
4396 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4397 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4402 #if ENABLE_HUSH_CASE
4405 if (done_word(&dest, &ctx)) {
4408 done_pipe(&ctx, PIPE_SEQ);
4409 #if ENABLE_HUSH_CASE
4410 /* Eat multiple semicolons, detect
4411 * whether it means something special */
4416 ch = i_getch(input);
4417 nommu_addchr(&ctx.as_string, ch);
4418 if (ctx.ctx_res_w == RES_CASE_BODY) {
4419 ctx.ctx_dsemicolon = 1;
4420 ctx.ctx_res_w = RES_MATCH;
4426 /* We just finished a cmd. New one may start
4427 * with an assignment */
4428 dest.o_assignment = MAYBE_ASSIGNMENT;
4431 if (done_word(&dest, &ctx)) {
4435 ch = i_getch(input);
4436 nommu_addchr(&ctx.as_string, ch);
4437 done_pipe(&ctx, PIPE_AND);
4439 done_pipe(&ctx, PIPE_BG);
4443 if (done_word(&dest, &ctx)) {
4446 #if ENABLE_HUSH_CASE
4447 if (ctx.ctx_res_w == RES_MATCH)
4448 break; /* we are in case's "word | word)" */
4450 if (next == '|') { /* || */
4451 ch = i_getch(input);
4452 nommu_addchr(&ctx.as_string, ch);
4453 done_pipe(&ctx, PIPE_OR);
4455 /* we could pick up a file descriptor choice here
4456 * with redirect_opt_num(), but bash doesn't do it.
4457 * "echo foo 2| cat" yields "foo 2". */
4460 o_reset_to_empty_unquoted(&ctx.as_string);
4465 #if ENABLE_HUSH_CASE
4466 /* "case... in [(]word)..." - skip '(' */
4467 if (ctx.ctx_res_w == RES_MATCH
4468 && ctx.command->argv == NULL /* not (word|(... */
4469 && dest.length == 0 /* not word(... */
4470 && dest.has_quoted_part == 0 /* not ""(... */
4476 if (parse_group(&dest, &ctx, input, ch) != 0) {
4481 #if ENABLE_HUSH_CASE
4482 if (ctx.ctx_res_w == RES_MATCH)
4486 /* proper use of this character is caught by end_trigger:
4487 * if we see {, we call parse_group(..., end_trigger='}')
4488 * and it will match } earlier (not here). */
4489 syntax_error_unexpected_ch(ch);
4493 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4499 struct parse_context *pctx;
4500 IF_HAS_KEYWORDS(struct parse_context *p2;)
4502 /* Clean up allocated tree.
4503 * Sample for finding leaks on syntax error recovery path.
4504 * Run it from interactive shell, watch pmap `pidof hush`.
4505 * while if false; then false; fi; do break; fi
4506 * Samples to catch leaks at execution:
4507 * while if (true | {true;}); then echo ok; fi; do break; done
4508 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4512 /* Update pipe/command counts,
4513 * otherwise freeing may miss some */
4514 done_pipe(pctx, PIPE_SEQ);
4515 debug_printf_clean("freeing list %p from ctx %p\n",
4516 pctx->list_head, pctx);
4517 debug_print_tree(pctx->list_head, 0);
4518 free_pipe_list(pctx->list_head);
4519 debug_printf_clean("freed list %p\n", pctx->list_head);
4521 o_free_unsafe(&pctx->as_string);
4523 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4527 IF_HAS_KEYWORDS(pctx = p2;)
4528 } while (HAS_KEYWORDS && pctx);
4529 /* Free text, clear all dest fields */
4531 /* If we are not in top-level parse, we return,
4532 * our caller will propagate error.
4534 if (end_trigger != ';') {
4542 /* Discard cached input, force prompt */
4549 /*** Execution routines ***/
4551 /* Expansion can recurse, need forward decls: */
4552 #if !ENABLE_HUSH_BASH_COMPAT
4553 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4554 #define expand_string_to_string(str, do_unbackslash) \
4555 expand_string_to_string(str)
4557 static char *expand_string_to_string(const char *str, int do_unbackslash);
4558 #if ENABLE_HUSH_TICK
4559 static int process_command_subs(o_string *dest, const char *s);
4562 /* expand_strvec_to_strvec() takes a list of strings, expands
4563 * all variable references within and returns a pointer to
4564 * a list of expanded strings, possibly with larger number
4565 * of strings. (Think VAR="a b"; echo $VAR).
4566 * This new list is allocated as a single malloc block.
4567 * NULL-terminated list of char* pointers is at the beginning of it,
4568 * followed by strings themselves.
4569 * Caller can deallocate entire list by single free(list). */
4571 /* A horde of its helpers come first: */
4573 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4575 while (--len >= 0) {
4578 #if ENABLE_HUSH_BRACE_EXPANSION
4579 if (c == '{' || c == '}') {
4580 /* { -> \{, } -> \} */
4582 /* And now we want to add { or } and continue:
4585 * luckily, just falling throught achieves this.
4591 /* \z -> \\\z; \<eol> -> \\<eol> */
4596 o_addchr(o, *str++);
4602 /* Store given string, finalizing the word and starting new one whenever
4603 * we encounter IFS char(s). This is used for expanding variable values.
4604 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4605 static int expand_on_ifs(o_string *output, int n, const char *str)
4608 int word_len = strcspn(str, G.ifs);
4610 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4611 o_addblock(output, str, word_len);
4613 /* Protect backslashes against globbing up :)
4614 * Example: "v='\*'; echo b$v" prints "b\*"
4615 * (and does not try to glob on "*")
4617 o_addblock_duplicate_backslash(output, str, word_len);
4618 /*/ Why can't we do it easier? */
4619 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4620 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4624 if (!*str) /* EOL - do not finalize word */
4626 o_addchr(output, '\0');
4627 debug_print_list("expand_on_ifs", output, n);
4628 n = o_save_ptr(output, n);
4629 str += strspn(str, G.ifs); /* skip ifs chars */
4631 debug_print_list("expand_on_ifs[1]", output, n);
4635 /* Helper to expand $((...)) and heredoc body. These act as if
4636 * they are in double quotes, with the exception that they are not :).
4637 * Just the rules are similar: "expand only $var and `cmd`"
4639 * Returns malloced string.
4640 * As an optimization, we return NULL if expansion is not needed.
4642 #if !ENABLE_HUSH_BASH_COMPAT
4643 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4644 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4645 encode_then_expand_string(str)
4647 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4650 struct in_str input;
4651 o_string dest = NULL_O_STRING;
4653 if (!strchr(str, '$')
4654 && !strchr(str, '\\')
4655 #if ENABLE_HUSH_TICK
4656 && !strchr(str, '`')
4662 /* We need to expand. Example:
4663 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4665 setup_string_in_str(&input, str);
4666 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4667 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4668 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4669 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4670 o_free_unsafe(&dest);
4674 #if ENABLE_SH_MATH_SUPPORT
4675 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4677 arith_state_t math_state;
4681 math_state.lookupvar = get_local_var_value;
4682 math_state.setvar = set_local_var_from_halves;
4683 //math_state.endofname = endofname;
4684 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4685 res = arith(&math_state, exp_str ? exp_str : arg);
4688 *errmsg_p = math_state.errmsg;
4689 if (math_state.errmsg)
4690 die_if_script(math_state.errmsg);
4695 #if ENABLE_HUSH_BASH_COMPAT
4696 /* ${var/[/]pattern[/repl]} helpers */
4697 static char *strstr_pattern(char *val, const char *pattern, int *size)
4700 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4701 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4708 /* Optimization: if "*pat" did not match the start of "string",
4709 * we know that "tring", "ring" etc will not match too:
4711 if (pattern[0] == '*')
4716 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4718 char *result = NULL;
4719 unsigned res_len = 0;
4720 unsigned repl_len = strlen(repl);
4724 char *s = strstr_pattern(val, pattern, &size);
4728 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4729 memcpy(result + res_len, val, s - val);
4731 strcpy(result + res_len, repl);
4732 res_len += repl_len;
4733 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4739 if (val[0] && result) {
4740 result = xrealloc(result, res_len + strlen(val) + 1);
4741 strcpy(result + res_len, val);
4742 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4744 debug_printf_varexp("result:'%s'\n", result);
4750 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4752 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4754 const char *val = NULL;
4755 char *to_be_freed = NULL;
4760 char exp_save = exp_save; /* for compiler */
4761 char *exp_saveptr; /* points to expansion operator */
4762 char *exp_word = exp_word; /* for compiler */
4765 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4767 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4769 first_char = arg[0] = arg0 & 0x7f;
4772 if (first_char == '#' /* ${#... */
4773 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4775 /* It must be length operator: ${#var} */
4779 /* Maybe handle parameter expansion */
4780 if (exp_saveptr /* if 2nd char is one of expansion operators */
4781 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4783 /* ${?:0}, ${#[:]%0} etc */
4784 exp_saveptr = var + 1;
4786 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4787 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4789 exp_op = exp_save = *exp_saveptr;
4791 exp_word = exp_saveptr + 1;
4792 if (exp_op == ':') {
4793 exp_op = *exp_word++;
4794 //TODO: try ${var:} and ${var:bogus} in non-bash config
4795 if (ENABLE_HUSH_BASH_COMPAT
4796 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4798 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4803 *exp_saveptr = '\0';
4804 } /* else: it's not an expansion op, but bare ${var} */
4807 /* Look up the variable in question */
4808 if (isdigit(var[0])) {
4809 /* parse_dollar should have vetted var for us */
4810 int n = xatoi_positive(var);
4811 if (n < G.global_argc)
4812 val = G.global_argv[n];
4813 /* else val remains NULL: $N with too big N */
4817 val = utoa(G.root_pid);
4819 case '!': /* bg pid */
4820 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4822 case '?': /* exitcode */
4823 val = utoa(G.last_exitcode);
4825 case '#': /* argc */
4826 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4829 val = get_local_var_value(var);
4833 /* Handle any expansions */
4834 if (exp_op == 'L') {
4835 debug_printf_expand("expand: length(%s)=", val);
4836 val = utoa(val ? strlen(val) : 0);
4837 debug_printf_expand("%s\n", val);
4838 } else if (exp_op) {
4839 if (exp_op == '%' || exp_op == '#') {
4840 /* Standard-mandated substring removal ops:
4841 * ${parameter%word} - remove smallest suffix pattern
4842 * ${parameter%%word} - remove largest suffix pattern
4843 * ${parameter#word} - remove smallest prefix pattern
4844 * ${parameter##word} - remove largest prefix pattern
4846 * Word is expanded to produce a glob pattern.
4847 * Then var's value is matched to it and matching part removed.
4849 if (val && val[0]) {
4853 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4854 if (exp_op == *exp_word) /* ## or %% */
4856 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4858 exp_word = exp_exp_word;
4859 /* HACK ALERT. We depend here on the fact that
4860 * G.global_argv and results of utoa and get_local_var_value
4861 * are actually in writable memory:
4862 * scan_and_match momentarily stores NULs there. */
4864 loc = scan_and_match(t, exp_word, scan_flags);
4865 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4866 // exp_op, t, exp_word, loc);
4868 if (loc) { /* match was found */
4869 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4870 val = loc; /* take right part */
4872 val = to_be_freed = xstrndup(val, loc - val); /* left */
4876 #if ENABLE_HUSH_BASH_COMPAT
4877 else if (exp_op == '/' || exp_op == '\\') {
4878 /* It's ${var/[/]pattern[/repl]} thing.
4879 * Note that in encoded form it has TWO parts:
4880 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4881 * and if // is used, it is encoded as \:
4882 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4884 /* Empty variable always gives nothing: */
4885 // "v=''; echo ${v/*/w}" prints "", not "w"
4886 if (val && val[0]) {
4887 /* pattern uses non-standard expansion.
4888 * repl should be unbackslashed and globbed
4889 * by the usual expansion rules:
4891 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4892 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4893 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4894 * v='a bz'; echo ${v/a*z/\z} prints "z"
4895 * (note that a*z _pattern_ is never globbed!)
4897 char *pattern, *repl, *t;
4898 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4900 pattern = xstrdup(exp_word);
4901 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4902 *p++ = SPECIAL_VAR_SYMBOL;
4904 p = strchr(p, SPECIAL_VAR_SYMBOL);
4906 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4907 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4908 /* HACK ALERT. We depend here on the fact that
4909 * G.global_argv and results of utoa and get_local_var_value
4910 * are actually in writable memory:
4911 * replace_pattern momentarily stores NULs there. */
4913 to_be_freed = replace_pattern(t,
4915 (repl ? repl : exp_word),
4917 if (to_be_freed) /* at least one replace happened */
4924 else if (exp_op == ':') {
4925 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4926 /* It's ${var:N[:M]} bashism.
4927 * Note that in encoded form it has TWO parts:
4928 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4933 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4936 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4937 *p++ = SPECIAL_VAR_SYMBOL;
4939 p = strchr(p, SPECIAL_VAR_SYMBOL);
4941 len = expand_and_evaluate_arith(exp_word, &errmsg);
4944 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4945 if (len >= 0) { /* bash compat: len < 0 is illegal */
4946 if (beg < 0) /* bash compat */
4948 debug_printf_varexp("from val:'%s'\n", val);
4949 if (len == 0 || !val || beg >= strlen(val)) {
4953 /* Paranoia. What if user entered 9999999999999
4954 * which fits in arith_t but not int? */
4957 val = to_be_freed = xstrndup(val + beg, len);
4959 debug_printf_varexp("val:'%s'\n", val);
4963 die_if_script("malformed ${%s:...}", var);
4966 } else { /* one of "-=+?" */
4967 /* Standard-mandated substitution ops:
4968 * ${var?word} - indicate error if unset
4969 * If var is unset, word (or a message indicating it is unset
4970 * if word is null) is written to standard error
4971 * and the shell exits with a non-zero exit status.
4972 * Otherwise, the value of var is substituted.
4973 * ${var-word} - use default value
4974 * If var is unset, word is substituted.
4975 * ${var=word} - assign and use default value
4976 * If var is unset, word is assigned to var.
4977 * In all cases, final value of var is substituted.
4978 * ${var+word} - use alternative value
4979 * If var is unset, null is substituted.
4980 * Otherwise, word is substituted.
4982 * Word is subjected to tilde expansion, parameter expansion,
4983 * command substitution, and arithmetic expansion.
4984 * If word is not needed, it is not expanded.
4986 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4987 * but also treat null var as if it is unset.
4989 int use_word = (!val || ((exp_save == ':') && !val[0]));
4991 use_word = !use_word;
4992 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4993 (exp_save == ':') ? "true" : "false", use_word);
4995 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4997 exp_word = to_be_freed;
4998 if (exp_op == '?') {
4999 /* mimic bash message */
5000 die_if_script("%s: %s",
5002 exp_word[0] ? exp_word : "parameter null or not set"
5004 //TODO: how interactive bash aborts expansion mid-command?
5009 if (exp_op == '=') {
5010 /* ${var=[word]} or ${var:=[word]} */
5011 if (isdigit(var[0]) || var[0] == '#') {
5012 /* mimic bash message */
5013 die_if_script("$%s: cannot assign in this way", var);
5016 char *new_var = xasprintf("%s=%s", var, val);
5017 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5021 } /* one of "-=+?" */
5023 *exp_saveptr = exp_save;
5029 *to_be_freed_pp = to_be_freed;
5033 /* Expand all variable references in given string, adding words to list[]
5034 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5035 * to be filled). This routine is extremely tricky: has to deal with
5036 * variables/parameters with whitespace, $* and $@, and constructs like
5037 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5038 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5040 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5041 * expansion of right-hand side of assignment == 1-element expand.
5043 char cant_be_null = 0; /* only bit 0x80 matters */
5046 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5047 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5048 debug_print_list("expand_vars_to_list", output, n);
5049 n = o_save_ptr(output, n);
5050 debug_print_list("expand_vars_to_list[0]", output, n);
5052 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5054 char *to_be_freed = NULL;
5055 const char *val = NULL;
5056 #if ENABLE_HUSH_TICK
5057 o_string subst_result = NULL_O_STRING;
5059 #if ENABLE_SH_MATH_SUPPORT
5060 char arith_buf[sizeof(arith_t)*3 + 2];
5062 o_addblock(output, arg, p - arg);
5063 debug_print_list("expand_vars_to_list[1]", output, n);
5065 p = strchr(p, SPECIAL_VAR_SYMBOL);
5067 /* Fetch special var name (if it is indeed one of them)
5068 * and quote bit, force the bit on if singleword expansion -
5069 * important for not getting v=$@ expand to many words. */
5070 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5072 /* Is this variable quoted and thus expansion can't be null?
5073 * "$@" is special. Even if quoted, it can still
5074 * expand to nothing (not even an empty string),
5075 * thus it is excluded. */
5076 if ((first_ch & 0x7f) != '@')
5077 cant_be_null |= first_ch;
5079 switch (first_ch & 0x7f) {
5080 /* Highest bit in first_ch indicates that var is double-quoted */
5084 if (!G.global_argv[1])
5087 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5088 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5089 while (G.global_argv[i]) {
5090 n = expand_on_ifs(output, n, G.global_argv[i]);
5091 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5092 if (G.global_argv[i++][0] && G.global_argv[i]) {
5093 /* this argv[] is not empty and not last:
5094 * put terminating NUL, start new word */
5095 o_addchr(output, '\0');
5096 debug_print_list("expand_vars_to_list[2]", output, n);
5097 n = o_save_ptr(output, n);
5098 debug_print_list("expand_vars_to_list[3]", output, n);
5102 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5103 * and in this case should treat it like '$*' - see 'else...' below */
5104 if (first_ch == ('@'|0x80) /* quoted $@ */
5105 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5108 o_addQstr(output, G.global_argv[i]);
5109 if (++i >= G.global_argc)
5111 o_addchr(output, '\0');
5112 debug_print_list("expand_vars_to_list[4]", output, n);
5113 n = o_save_ptr(output, n);
5115 } else { /* quoted $* (or v="$@" case): add as one word */
5117 o_addQstr(output, G.global_argv[i]);
5118 if (!G.global_argv[++i])
5121 o_addchr(output, G.ifs[0]);
5126 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5127 /* "Empty variable", used to make "" etc to not disappear */
5129 cant_be_null = 0x80;
5131 #if ENABLE_HUSH_TICK
5132 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5133 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5135 /* Can't just stuff it into output o_string,
5136 * expanded result may need to be globbed
5137 * and $IFS-splitted */
5138 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5139 G.last_exitcode = process_command_subs(&subst_result, arg);
5140 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5141 val = subst_result.data;
5144 #if ENABLE_SH_MATH_SUPPORT
5145 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5148 arg++; /* skip '+' */
5149 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5150 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5151 res = expand_and_evaluate_arith(arg, NULL);
5152 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5153 sprintf(arith_buf, ARITH_FMT, res);
5159 val = expand_one_var(&to_be_freed, arg, &p);
5160 IF_HUSH_TICK(store_val:)
5161 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5162 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5163 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5164 if (val && val[0]) {
5165 n = expand_on_ifs(output, n, val);
5168 } else { /* quoted $VAR, val will be appended below */
5169 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5170 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5174 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5176 if (val && val[0]) {
5177 o_addQstr(output, val);
5181 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5182 * Do the check to avoid writing to a const string. */
5183 if (*p != SPECIAL_VAR_SYMBOL)
5184 *p = SPECIAL_VAR_SYMBOL;
5186 #if ENABLE_HUSH_TICK
5187 o_free(&subst_result);
5190 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5193 debug_print_list("expand_vars_to_list[a]", output, n);
5194 /* this part is literal, and it was already pre-quoted
5195 * if needed (much earlier), do not use o_addQstr here! */
5196 o_addstr_with_NUL(output, arg);
5197 debug_print_list("expand_vars_to_list[b]", output, n);
5198 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5199 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5202 /* allow to reuse list[n] later without re-growth */
5203 output->has_empty_slot = 1;
5205 o_addchr(output, '\0');
5211 static char **expand_variables(char **argv, unsigned expflags)
5215 o_string output = NULL_O_STRING;
5217 output.o_expflags = expflags;
5221 n = expand_vars_to_list(&output, n, *argv);
5224 debug_print_list("expand_variables", &output, n);
5226 /* output.data (malloced in one block) gets returned in "list" */
5227 list = o_finalize_list(&output, n);
5228 debug_print_strings("expand_variables[1]", list);
5232 static char **expand_strvec_to_strvec(char **argv)
5234 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5237 #if ENABLE_HUSH_BASH_COMPAT
5238 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5240 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5244 /* Used for expansion of right hand of assignments,
5245 * $((...)), heredocs, variable espansion parts.
5247 * NB: should NOT do globbing!
5248 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5250 static char *expand_string_to_string(const char *str, int do_unbackslash)
5252 #if !ENABLE_HUSH_BASH_COMPAT
5253 const int do_unbackslash = 1;
5255 char *argv[2], **list;
5257 debug_printf_expand("string_to_string<='%s'\n", str);
5258 /* This is generally an optimization, but it also
5259 * handles "", which otherwise trips over !list[0] check below.
5260 * (is this ever happens that we actually get str="" here?)
5262 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5263 //TODO: Can use on strings with \ too, just unbackslash() them?
5264 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5265 return xstrdup(str);
5268 argv[0] = (char*)str;
5270 list = expand_variables(argv, do_unbackslash
5271 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5272 : EXP_FLAG_SINGLEWORD
5275 if (!list[0] || list[1])
5276 bb_error_msg_and_die("BUG in varexp2");
5277 /* actually, just move string 2*sizeof(char*) bytes back */
5278 overlapping_strcpy((char*)list, list[0]);
5280 unbackslash((char*)list);
5281 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5285 /* Used for "eval" builtin */
5286 static char* expand_strvec_to_string(char **argv)
5290 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5291 /* Convert all NULs to spaces */
5296 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5297 bb_error_msg_and_die("BUG in varexp3");
5298 /* bash uses ' ' regardless of $IFS contents */
5303 overlapping_strcpy((char*)list, list[0]);
5304 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5308 static char **expand_assignments(char **argv, int count)
5313 G.expanded_assignments = p = NULL;
5314 /* Expand assignments into one string each */
5315 for (i = 0; i < count; i++) {
5316 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5318 G.expanded_assignments = NULL;
5325 void re_execute_shell(char ***to_free, const char *s,
5326 char *g_argv0, char **g_argv,
5327 char **builtin_argv) NORETURN;
5329 static void reset_traps_to_defaults(void)
5331 /* This function is always called in a child shell
5332 * after fork (not vfork, NOMMU doesn't use this function).
5337 /* Child shells are not interactive.
5338 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5339 * Testcase: (while :; do :; done) + ^Z should background.
5340 * Same goes for SIGTERM, SIGHUP, SIGINT.
5342 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5343 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5345 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5346 * Stupid. It can be done with *single* &= op, but we can't use
5347 * the fact that G.blocked_set is implemented as a bitmask
5349 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5353 /* Careful. Only if no trap or trap is not "" */
5354 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5355 sigdelset(&G.blocked_set, sig);
5362 /* Our homegrown sig mask is saner to work with :) */
5363 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5365 /* Resetting all traps to default except empty ones */
5366 mask = G.non_DFL_mask;
5367 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5368 if (!G.traps[sig] || !G.traps[sig][0])
5371 G.traps[sig] = NULL;
5372 /* There is no signal for 0 (EXIT) */
5375 /* There was a trap handler, we just removed it.
5376 * But if sig still has non-DFL handling,
5377 * we should not unblock the sig. */
5380 sigdelset(&G.blocked_set, sig);
5382 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5387 static void re_execute_shell(char ***to_free, const char *s,
5388 char *g_argv0, char **g_argv,
5389 char **builtin_argv) NORETURN;
5390 static void re_execute_shell(char ***to_free, const char *s,
5391 char *g_argv0, char **g_argv,
5392 char **builtin_argv)
5394 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5395 /* delims + 2 * (number of bytes in printed hex numbers) */
5396 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5397 char *heredoc_argv[4];
5398 struct variable *cur;
5399 # if ENABLE_HUSH_FUNCTIONS
5400 struct function *funcp;
5404 unsigned long long empty_trap_mask;
5406 if (!g_argv0) { /* heredoc */
5407 argv = heredoc_argv;
5408 argv[0] = (char *) G.argv0_for_re_execing;
5409 argv[1] = (char *) "-<";
5410 argv[2] = (char *) s;
5412 pp = &argv[3]; /* used as pointer to empty environment */
5418 if (pp) while (*pp++)
5421 empty_trap_mask = 0;
5424 for (sig = 1; sig < NSIG; sig++) {
5425 if (G.traps[sig] && !G.traps[sig][0])
5426 empty_trap_mask |= 1LL << sig;
5430 sprintf(param_buf, NOMMU_HACK_FMT
5431 , (unsigned) G.root_pid
5432 , (unsigned) G.root_ppid
5433 , (unsigned) G.last_bg_pid
5434 , (unsigned) G.last_exitcode
5437 IF_HUSH_LOOPS(, G.depth_of_loop)
5439 # undef NOMMU_HACK_FMT
5440 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5441 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5444 for (cur = G.top_var; cur; cur = cur->next) {
5445 if (!cur->flg_export || cur->flg_read_only)
5448 # if ENABLE_HUSH_FUNCTIONS
5449 for (funcp = G.top_func; funcp; funcp = funcp->next)
5455 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5456 *pp++ = (char *) G.argv0_for_re_execing;
5458 for (cur = G.top_var; cur; cur = cur->next) {
5459 if (strcmp(cur->varstr, hush_version_str) == 0)
5461 if (cur->flg_read_only) {
5462 *pp++ = (char *) "-R";
5463 *pp++ = cur->varstr;
5464 } else if (!cur->flg_export) {
5465 *pp++ = (char *) "-V";
5466 *pp++ = cur->varstr;
5469 # if ENABLE_HUSH_FUNCTIONS
5470 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5471 *pp++ = (char *) "-F";
5472 *pp++ = funcp->name;
5473 *pp++ = funcp->body_as_string;
5476 /* We can pass activated traps here. Say, -Tnn:trap_string
5478 * However, POSIX says that subshells reset signals with traps
5480 * I tested bash-3.2 and it not only does that with true subshells
5481 * of the form ( list ), but with any forked children shells.
5482 * I set trap "echo W" WINCH; and then tried:
5484 * { echo 1; sleep 20; echo 2; } &
5485 * while true; do echo 1; sleep 20; echo 2; break; done &
5486 * true | { echo 1; sleep 20; echo 2; } | cat
5488 * In all these cases sending SIGWINCH to the child shell
5489 * did not run the trap. If I add trap "echo V" WINCH;
5490 * _inside_ group (just before echo 1), it works.
5492 * I conclude it means we don't need to pass active traps here.
5493 * Even if we would use signal handlers instead of signal masking
5494 * in order to implement trap handling,
5495 * exec syscall below resets signals to SIG_DFL for us.
5497 *pp++ = (char *) "-c";
5500 while (*++builtin_argv)
5501 *pp++ = *builtin_argv;
5502 *pp++ = (char *) "";
5507 /* *pp = NULL; - is already there */
5511 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5512 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5513 execve(bb_busybox_exec_path, argv, pp);
5514 /* Fallback. Useful for init=/bin/hush usage etc */
5515 if (argv[0][0] == '/')
5516 execve(argv[0], argv, pp);
5517 xfunc_error_retval = 127;
5518 bb_error_msg_and_die("can't re-execute the shell");
5520 #endif /* !BB_MMU */
5523 static int run_and_free_list(struct pipe *pi);
5525 /* Executing from string: eval, sh -c '...'
5526 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5527 * end_trigger controls how often we stop parsing
5528 * NUL: parse all, execute, return
5529 * ';': parse till ';' or newline, execute, repeat till EOF
5531 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5533 /* Why we need empty flag?
5534 * An obscure corner case "false; ``; echo $?":
5535 * empty command in `` should still set $? to 0.
5536 * But we can't just set $? to 0 at the start,
5537 * this breaks "false; echo `echo $?`" case.
5541 struct pipe *pipe_list;
5543 #if ENABLE_HUSH_INTERACTIVE
5544 if (end_trigger == ';')
5545 inp->promptmode = 0; /* PS1 */
5547 pipe_list = parse_stream(NULL, inp, end_trigger);
5548 if (!pipe_list) { /* EOF */
5550 G.last_exitcode = 0;
5553 debug_print_tree(pipe_list, 0);
5554 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5555 run_and_free_list(pipe_list);
5557 #if ENABLE_HUSH_FUNCTIONS
5558 if (G.flag_return_in_progress == 1)
5564 static void parse_and_run_string(const char *s)
5566 struct in_str input;
5567 setup_string_in_str(&input, s);
5568 parse_and_run_stream(&input, '\0');
5571 static void parse_and_run_file(FILE *f)
5573 struct in_str input;
5574 setup_file_in_str(&input, f);
5575 parse_and_run_stream(&input, ';');
5578 #if ENABLE_HUSH_TICK
5579 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5584 char **to_free = NULL;
5588 pid = BB_MMU ? xfork() : xvfork();
5589 if (pid == 0) { /* child */
5590 disable_restore_tty_pgrp_on_exit();
5591 /* Process substitution is not considered to be usual
5592 * 'command execution'.
5593 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5600 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5601 close(channel[0]); /* NB: close _first_, then move fd! */
5602 xmove_fd(channel[1], 1);
5603 /* Prevent it from trying to handle ctrl-z etc */
5604 IF_HUSH_JOB(G.run_list_level = 1;)
5605 /* Awful hack for `trap` or $(trap).
5607 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5608 * contains an example where "trap" is executed in a subshell:
5610 * save_traps=$(trap)
5612 * eval "$save_traps"
5614 * Standard does not say that "trap" in subshell shall print
5615 * parent shell's traps. It only says that its output
5616 * must have suitable form, but then, in the above example
5617 * (which is not supposed to be normative), it implies that.
5619 * bash (and probably other shell) does implement it
5620 * (traps are reset to defaults, but "trap" still shows them),
5621 * but as a result, "trap" logic is hopelessly messed up:
5624 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5625 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5626 * # true | trap <--- trap is in subshell - no output (ditto)
5627 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5628 * trap -- 'echo Ho' SIGWINCH
5629 * # echo `(trap)` <--- in subshell in subshell - output
5630 * trap -- 'echo Ho' SIGWINCH
5631 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5632 * trap -- 'echo Ho' SIGWINCH
5634 * The rules when to forget and when to not forget traps
5635 * get really complex and nonsensical.
5637 * Our solution: ONLY bare $(trap) or `trap` is special.
5639 s = skip_whitespace(s);
5640 if (strncmp(s, "trap", 4) == 0
5641 && skip_whitespace(s + 4)[0] == '\0'
5643 static const char *const argv[] = { NULL, NULL };
5644 builtin_trap((char**)argv);
5645 exit(0); /* not _exit() - we need to fflush */
5648 reset_traps_to_defaults();
5649 parse_and_run_string(s);
5650 _exit(G.last_exitcode);
5652 /* We re-execute after vfork on NOMMU. This makes this script safe:
5653 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5654 * huge=`cat BIG` # was blocking here forever
5657 re_execute_shell(&to_free,
5667 # if ENABLE_HUSH_FAST
5669 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5670 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5671 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5673 enable_restore_tty_pgrp_on_exit();
5678 close_on_exec_on(channel[0]);
5679 return xfdopen_for_read(channel[0]);
5682 /* Return code is exit status of the process that is run. */
5683 static int process_command_subs(o_string *dest, const char *s)
5686 struct in_str pipe_str;
5688 int status, ch, eol_cnt;
5690 fp = generate_stream_from_string(s, &pid);
5692 /* Now send results of command back into original context */
5693 setup_file_in_str(&pipe_str, fp);
5695 while ((ch = i_getch(&pipe_str)) != EOF) {
5701 o_addchr(dest, '\n');
5704 o_addQchr(dest, ch);
5707 debug_printf("done reading from `cmd` pipe, closing it\n");
5709 /* We need to extract exitcode. Test case
5710 * "true; echo `sleep 1; false` $?"
5712 safe_waitpid(pid, &status, 0);
5713 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5714 return WEXITSTATUS(status);
5716 #endif /* ENABLE_HUSH_TICK */
5719 static void setup_heredoc(struct redir_struct *redir)
5721 struct fd_pair pair;
5724 /* the _body_ of heredoc (misleading field name) */
5725 const char *heredoc = redir->rd_filename;
5732 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5733 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5737 len = strlen(heredoc);
5739 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5741 xmove_fd(pair.rd, redir->rd_fd);
5743 /* Try writing without forking. Newer kernels have
5744 * dynamically growing pipes. Must use non-blocking write! */
5747 written = write(pair.wr, heredoc, len);
5758 ndelay_off(pair.wr);
5760 /* Okay, pipe buffer was not big enough */
5761 /* Note: we must not create a stray child (bastard? :)
5762 * for the unsuspecting parent process. Child creates a grandchild
5763 * and exits before parent execs the process which consumes heredoc
5764 * (that exec happens after we return from this function) */
5771 disable_restore_tty_pgrp_on_exit();
5772 pid = BB_MMU ? xfork() : xvfork();
5776 close(redir->rd_fd); /* read side of the pipe */
5778 full_write(pair.wr, heredoc, len); /* may loop or block */
5781 /* Delegate blocking writes to another process */
5782 xmove_fd(pair.wr, STDOUT_FILENO);
5783 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5787 #if ENABLE_HUSH_FAST
5789 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5791 enable_restore_tty_pgrp_on_exit();
5797 wait(NULL); /* wait till child has died */
5800 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5801 * and stderr if they are redirected. */
5802 static int setup_redirects(struct command *prog, int squirrel[])
5805 struct redir_struct *redir;
5807 for (redir = prog->redirects; redir; redir = redir->next) {
5808 if (redir->rd_type == REDIRECT_HEREDOC2) {
5809 /* rd_fd<<HERE case */
5810 if (squirrel && redir->rd_fd < 3
5811 && squirrel[redir->rd_fd] < 0
5813 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5815 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5817 debug_printf_parse("set heredoc '%s'\n",
5818 redir->rd_filename);
5819 setup_heredoc(redir);
5823 if (redir->rd_dup == REDIRFD_TO_FILE) {
5824 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5826 if (redir->rd_filename == NULL) {
5827 /* Something went wrong in the parse.
5828 * Pretend it didn't happen */
5829 bb_error_msg("bug in redirect parse");
5832 mode = redir_table[redir->rd_type].mode;
5833 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5834 openfd = open_or_warn(p, mode);
5837 /* this could get lost if stderr has been redirected, but
5838 * bash and ash both lose it as well (though zsh doesn't!) */
5839 //what the above comment tries to say?
5843 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5844 openfd = redir->rd_dup;
5847 if (openfd != redir->rd_fd) {
5848 if (squirrel && redir->rd_fd < 3
5849 && squirrel[redir->rd_fd] < 0
5851 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5853 if (openfd == REDIRFD_CLOSE) {
5854 /* "n>-" means "close me" */
5855 close(redir->rd_fd);
5857 xdup2(openfd, redir->rd_fd);
5858 if (redir->rd_dup == REDIRFD_TO_FILE)
5866 static void restore_redirects(int squirrel[])
5869 for (i = 0; i < 3; i++) {
5872 /* We simply die on error */
5878 static char *find_in_path(const char *arg)
5881 const char *PATH = get_local_var_value("PATH");
5887 const char *end = strchrnul(PATH, ':');
5888 int sz = end - PATH; /* must be int! */
5892 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5894 /* We have xxx::yyyy in $PATH,
5895 * it means "use current dir" */
5898 if (access(ret, F_OK) == 0)
5911 static const struct built_in_command *find_builtin_helper(const char *name,
5912 const struct built_in_command *x,
5913 const struct built_in_command *end)
5916 if (strcmp(name, x->b_cmd) != 0) {
5920 debug_printf_exec("found builtin '%s'\n", name);
5925 static const struct built_in_command *find_builtin1(const char *name)
5927 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5929 static const struct built_in_command *find_builtin(const char *name)
5931 const struct built_in_command *x = find_builtin1(name);
5934 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5937 #if ENABLE_HUSH_FUNCTIONS
5938 static struct function **find_function_slot(const char *name)
5940 struct function **funcpp = &G.top_func;
5942 if (strcmp(name, (*funcpp)->name) == 0) {
5945 funcpp = &(*funcpp)->next;
5950 static const struct function *find_function(const char *name)
5952 const struct function *funcp = *find_function_slot(name);
5954 debug_printf_exec("found function '%s'\n", name);
5958 /* Note: takes ownership on name ptr */
5959 static struct function *new_function(char *name)
5961 struct function **funcpp = find_function_slot(name);
5962 struct function *funcp = *funcpp;
5964 if (funcp != NULL) {
5965 struct command *cmd = funcp->parent_cmd;
5966 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5968 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5970 /* Note: if !funcp->body, do not free body_as_string!
5971 * This is a special case of "-F name body" function:
5972 * body_as_string was not malloced! */
5974 free_pipe_list(funcp->body);
5976 free(funcp->body_as_string);
5980 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5981 cmd->argv[0] = funcp->name;
5982 cmd->group = funcp->body;
5984 cmd->group_as_string = funcp->body_as_string;
5988 debug_printf_exec("remembering new function '%s'\n", name);
5989 funcp = *funcpp = xzalloc(sizeof(*funcp));
5990 /*funcp->next = NULL;*/
5997 static void unset_func(const char *name)
5999 struct function **funcpp = find_function_slot(name);
6000 struct function *funcp = *funcpp;
6002 if (funcp != NULL) {
6003 debug_printf_exec("freeing function '%s'\n", funcp->name);
6004 *funcpp = funcp->next;
6005 /* funcp is unlinked now, deleting it.
6006 * Note: if !funcp->body, the function was created by
6007 * "-F name body", do not free ->body_as_string
6008 * and ->name as they were not malloced. */
6010 free_pipe_list(funcp->body);
6013 free(funcp->body_as_string);
6021 #define exec_function(to_free, funcp, argv) \
6022 exec_function(funcp, argv)
6024 static void exec_function(char ***to_free,
6025 const struct function *funcp,
6026 char **argv) NORETURN;
6027 static void exec_function(char ***to_free,
6028 const struct function *funcp,
6034 argv[0] = G.global_argv[0];
6035 G.global_argv = argv;
6039 /* On MMU, funcp->body is always non-NULL */
6040 n = run_list(funcp->body);
6044 re_execute_shell(to_free,
6045 funcp->body_as_string,
6052 static int run_function(const struct function *funcp, char **argv)
6058 save_and_replace_G_args(&sv, argv);
6060 /* "we are in function, ok to use return" */
6061 sv_flg = G.flag_return_in_progress;
6062 G.flag_return_in_progress = -1;
6063 # if ENABLE_HUSH_LOCAL
6064 G.func_nest_level++;
6067 /* On MMU, funcp->body is always non-NULL */
6070 /* Function defined by -F */
6071 parse_and_run_string(funcp->body_as_string);
6072 rc = G.last_exitcode;
6076 rc = run_list(funcp->body);
6079 # if ENABLE_HUSH_LOCAL
6081 struct variable *var;
6082 struct variable **var_pp;
6084 var_pp = &G.top_var;
6085 while ((var = *var_pp) != NULL) {
6086 if (var->func_nest_level < G.func_nest_level) {
6087 var_pp = &var->next;
6091 if (var->flg_export)
6092 bb_unsetenv(var->varstr);
6093 /* Remove from global list */
6094 *var_pp = var->next;
6100 G.func_nest_level--;
6103 G.flag_return_in_progress = sv_flg;
6105 restore_G_args(&sv, argv);
6109 #endif /* ENABLE_HUSH_FUNCTIONS */
6113 #define exec_builtin(to_free, x, argv) \
6114 exec_builtin(x, argv)
6116 #define exec_builtin(to_free, x, argv) \
6117 exec_builtin(to_free, argv)
6119 static void exec_builtin(char ***to_free,
6120 const struct built_in_command *x,
6121 char **argv) NORETURN;
6122 static void exec_builtin(char ***to_free,
6123 const struct built_in_command *x,
6129 rcode = x->b_function(argv);
6134 /* On NOMMU, we must never block!
6135 * Example: { sleep 99 | read line; } & echo Ok
6137 re_execute_shell(to_free,
6146 static void execvp_or_die(char **argv) NORETURN;
6147 static void execvp_or_die(char **argv)
6149 debug_printf_exec("execing '%s'\n", argv[0]);
6150 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6151 execvp(argv[0], argv);
6152 bb_perror_msg("can't execute '%s'", argv[0]);
6153 _exit(127); /* bash compat */
6156 #if ENABLE_HUSH_MODE_X
6157 static void dump_cmd_in_x_mode(char **argv)
6159 if (G_x_mode && argv) {
6160 /* We want to output the line in one write op */
6168 len += strlen(argv[n++]) + 1;
6174 p += sprintf(p, " %s", argv[n++]);
6182 # define dump_cmd_in_x_mode(argv) ((void)0)
6186 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6187 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6188 #define pseudo_exec(nommu_save, command, argv_expanded) \
6189 pseudo_exec(command, argv_expanded)
6192 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6194 * Don't exit() here. If you don't exec, use _exit instead.
6195 * The at_exit handlers apparently confuse the calling process,
6196 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6197 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6198 char **argv, int assignment_cnt,
6199 char **argv_expanded) NORETURN;
6200 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6201 char **argv, int assignment_cnt,
6202 char **argv_expanded)
6206 new_env = expand_assignments(argv, assignment_cnt);
6207 dump_cmd_in_x_mode(new_env);
6209 if (!argv[assignment_cnt]) {
6210 /* Case when we are here: ... | var=val | ...
6211 * (note that we do not exit early, i.e., do not optimize out
6212 * expand_assignments(): think about ... | var=`sleep 1` | ...
6214 free_strings(new_env);
6215 _exit(EXIT_SUCCESS);
6219 set_vars_and_save_old(new_env);
6220 free(new_env); /* optional */
6221 /* we can also destroy set_vars_and_save_old's return value,
6224 nommu_save->new_env = new_env;
6225 nommu_save->old_vars = set_vars_and_save_old(new_env);
6228 if (argv_expanded) {
6229 argv = argv_expanded;
6231 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6233 nommu_save->argv = argv;
6236 dump_cmd_in_x_mode(argv);
6238 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6239 if (strchr(argv[0], '/') != NULL)
6243 /* Check if the command matches any of the builtins.
6244 * Depending on context, this might be redundant. But it's
6245 * easier to waste a few CPU cycles than it is to figure out
6246 * if this is one of those cases.
6249 /* On NOMMU, it is more expensive to re-execute shell
6250 * just in order to run echo or test builtin.
6251 * It's better to skip it here and run corresponding
6252 * non-builtin later. */
6253 const struct built_in_command *x;
6254 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6256 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6259 #if ENABLE_HUSH_FUNCTIONS
6260 /* Check if the command matches any functions */
6262 const struct function *funcp = find_function(argv[0]);
6264 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6269 #if ENABLE_FEATURE_SH_STANDALONE
6270 /* Check if the command matches any busybox applets */
6272 int a = find_applet_by_name(argv[0]);
6274 # if BB_MMU /* see above why on NOMMU it is not allowed */
6275 if (APPLET_IS_NOEXEC(a)) {
6276 debug_printf_exec("running applet '%s'\n", argv[0]);
6277 run_applet_no_and_exit(a, argv);
6280 /* Re-exec ourselves */
6281 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6282 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6283 execv(bb_busybox_exec_path, argv);
6284 /* If they called chroot or otherwise made the binary no longer
6285 * executable, fall through */
6290 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6293 execvp_or_die(argv);
6296 /* Called after [v]fork() in run_pipe
6298 static void pseudo_exec(nommu_save_t *nommu_save,
6299 struct command *command,
6300 char **argv_expanded) NORETURN;
6301 static void pseudo_exec(nommu_save_t *nommu_save,
6302 struct command *command,
6303 char **argv_expanded)
6305 if (command->argv) {
6306 pseudo_exec_argv(nommu_save, command->argv,
6307 command->assignment_cnt, argv_expanded);
6310 if (command->group) {
6311 /* Cases when we are here:
6314 * ... | ( list ) | ...
6315 * ... | { list } | ...
6319 debug_printf_exec("pseudo_exec: run_list\n");
6320 reset_traps_to_defaults();
6321 rcode = run_list(command->group);
6322 /* OK to leak memory by not calling free_pipe_list,
6323 * since this process is about to exit */
6326 re_execute_shell(&nommu_save->argv_from_re_execing,
6327 command->group_as_string,
6334 /* Case when we are here: ... | >file */
6335 debug_printf_exec("pseudo_exec'ed null command\n");
6336 _exit(EXIT_SUCCESS);
6340 static const char *get_cmdtext(struct pipe *pi)
6346 /* This is subtle. ->cmdtext is created only on first backgrounding.
6347 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6348 * On subsequent bg argv is trashed, but we won't use it */
6351 argv = pi->cmds[0].argv;
6352 if (!argv || !argv[0]) {
6353 pi->cmdtext = xzalloc(1);
6359 len += strlen(*argv) + 1;
6363 argv = pi->cmds[0].argv;
6365 len = strlen(*argv);
6366 memcpy(p, *argv, len);
6374 static void insert_bg_job(struct pipe *pi)
6376 struct pipe *job, **jobp;
6379 /* Linear search for the ID of the job to use */
6381 for (job = G.job_list; job; job = job->next)
6382 if (job->jobid >= pi->jobid)
6383 pi->jobid = job->jobid + 1;
6385 /* Add job to the list of running jobs */
6387 while ((job = *jobp) != NULL)
6389 job = *jobp = xmalloc(sizeof(*job));
6391 *job = *pi; /* physical copy */
6393 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6394 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6395 for (i = 0; i < pi->num_cmds; i++) {
6396 job->cmds[i].pid = pi->cmds[i].pid;
6397 /* all other fields are not used and stay zero */
6399 job->cmdtext = xstrdup(get_cmdtext(pi));
6401 if (G_interactive_fd)
6402 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6403 G.last_jobid = job->jobid;
6406 static void remove_bg_job(struct pipe *pi)
6408 struct pipe *prev_pipe;
6410 if (pi == G.job_list) {
6411 G.job_list = pi->next;
6413 prev_pipe = G.job_list;
6414 while (prev_pipe->next != pi)
6415 prev_pipe = prev_pipe->next;
6416 prev_pipe->next = pi->next;
6419 G.last_jobid = G.job_list->jobid;
6424 /* Remove a backgrounded job */
6425 static void delete_finished_bg_job(struct pipe *pi)
6432 /* Check to see if any processes have exited -- if they
6433 * have, figure out why and see if a job has completed */
6434 static int checkjobs(struct pipe *fg_pipe)
6444 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6446 attributes = WUNTRACED;
6447 if (fg_pipe == NULL)
6448 attributes |= WNOHANG;
6451 #if ENABLE_HUSH_FAST
6452 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6453 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6454 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6455 /* There was neither fork nor SIGCHLD since last waitpid */
6456 /* Avoid doing waitpid syscall if possible */
6457 if (!G.we_have_children) {
6461 if (fg_pipe == NULL) { /* is WNOHANG set? */
6462 /* We have children, but they did not exit
6463 * or stop yet (we saw no SIGCHLD) */
6466 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6470 /* Do we do this right?
6471 * bash-3.00# sleep 20 | false
6473 * [3]+ Stopped sleep 20 | false
6474 * bash-3.00# echo $?
6475 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6476 * [hush 1.14.0: yes we do it right]
6483 #if ENABLE_HUSH_FAST
6484 i = G.count_SIGCHLD;
6486 childpid = waitpid(-1, &status, attributes);
6487 if (childpid <= 0) {
6488 if (childpid && errno != ECHILD)
6489 bb_perror_msg("waitpid");
6490 #if ENABLE_HUSH_FAST
6491 else { /* Until next SIGCHLD, waitpid's are useless */
6492 G.we_have_children = (childpid == 0);
6493 G.handled_SIGCHLD = i;
6494 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6499 dead = WIFEXITED(status) || WIFSIGNALED(status);
6502 if (WIFSTOPPED(status))
6503 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6504 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6505 if (WIFSIGNALED(status))
6506 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6507 childpid, WTERMSIG(status), WEXITSTATUS(status));
6508 if (WIFEXITED(status))
6509 debug_printf_jobs("pid %d exited, exitcode %d\n",
6510 childpid, WEXITSTATUS(status));
6512 /* Were we asked to wait for fg pipe? */
6514 i = fg_pipe->num_cmds;
6516 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6517 if (fg_pipe->cmds[i].pid != childpid)
6521 fg_pipe->cmds[i].pid = 0;
6522 fg_pipe->alive_cmds--;
6523 ex = WEXITSTATUS(status);
6524 /* bash prints killer signal's name for *last*
6525 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6526 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6528 if (WIFSIGNALED(status)) {
6529 int sig = WTERMSIG(status);
6530 if (i == fg_pipe->num_cmds-1)
6531 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6532 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6533 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6534 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6535 * Maybe we need to use sig | 128? */
6538 fg_pipe->cmds[i].cmd_exitcode = ex;
6540 fg_pipe->cmds[i].is_stopped = 1;
6541 fg_pipe->stopped_cmds++;
6543 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6544 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6545 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6546 /* All processes in fg pipe have exited or stopped */
6547 i = fg_pipe->num_cmds;
6549 rcode = fg_pipe->cmds[i].cmd_exitcode;
6550 /* usually last process gives overall exitstatus,
6551 * but with "set -o pipefail", last *failed* process does */
6552 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6555 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6556 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6557 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6558 * and "killall -STOP cat" */
6559 if (G_interactive_fd) {
6561 if (fg_pipe->alive_cmds != 0)
6562 insert_bg_job(fg_pipe);
6566 if (fg_pipe->alive_cmds == 0)
6569 /* There are still running processes in the fg pipe */
6570 goto wait_more; /* do waitpid again */
6572 /* it wasnt fg_pipe, look for process in bg pipes */
6576 /* We asked to wait for bg or orphaned children */
6577 /* No need to remember exitcode in this case */
6578 for (pi = G.job_list; pi; pi = pi->next) {
6579 for (i = 0; i < pi->num_cmds; i++) {
6580 if (pi->cmds[i].pid == childpid)
6581 goto found_pi_and_prognum;
6584 /* Happens when shell is used as init process (init=/bin/sh) */
6585 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6586 continue; /* do waitpid again */
6588 found_pi_and_prognum:
6591 pi->cmds[i].pid = 0;
6593 if (!pi->alive_cmds) {
6594 if (G_interactive_fd)
6595 printf(JOB_STATUS_FORMAT, pi->jobid,
6596 "Done", pi->cmdtext);
6597 delete_finished_bg_job(pi);
6601 pi->cmds[i].is_stopped = 1;
6605 } /* while (waitpid succeeds)... */
6611 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6614 int rcode = checkjobs(fg_pipe);
6615 if (G_saved_tty_pgrp) {
6616 /* Job finished, move the shell to the foreground */
6617 p = getpgrp(); /* our process group id */
6618 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6619 tcsetpgrp(G_interactive_fd, p);
6625 /* Start all the jobs, but don't wait for anything to finish.
6628 * Return code is normally -1, when the caller has to wait for children
6629 * to finish to determine the exit status of the pipe. If the pipe
6630 * is a simple builtin command, however, the action is done by the
6631 * time run_pipe returns, and the exit code is provided as the
6634 * Returns -1 only if started some children. IOW: we have to
6635 * mask out retvals of builtins etc with 0xff!
6637 * The only case when we do not need to [v]fork is when the pipe
6638 * is single, non-backgrounded, non-subshell command. Examples:
6639 * cmd ; ... { list } ; ...
6640 * cmd && ... { list } && ...
6641 * cmd || ... { list } || ...
6642 * If it is, then we can run cmd as a builtin, NOFORK,
6643 * or (if SH_STANDALONE) an applet, and we can run the { list }
6644 * with run_list. If it isn't one of these, we fork and exec cmd.
6646 * Cases when we must fork:
6647 * non-single: cmd | cmd
6648 * backgrounded: cmd & { list } &
6649 * subshell: ( list ) [&]
6651 #if !ENABLE_HUSH_MODE_X
6652 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6653 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6655 static int redirect_and_varexp_helper(char ***new_env_p,
6656 struct variable **old_vars_p,
6657 struct command *command,
6659 char **argv_expanded)
6661 /* setup_redirects acts on file descriptors, not FILEs.
6662 * This is perfect for work that comes after exec().
6663 * Is it really safe for inline use? Experimentally,
6664 * things seem to work. */
6665 int rcode = setup_redirects(command, squirrel);
6667 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6668 *new_env_p = new_env;
6669 dump_cmd_in_x_mode(new_env);
6670 dump_cmd_in_x_mode(argv_expanded);
6672 *old_vars_p = set_vars_and_save_old(new_env);
6676 static NOINLINE int run_pipe(struct pipe *pi)
6678 static const char *const null_ptr = NULL;
6682 struct command *command;
6683 char **argv_expanded;
6685 /* it is not always needed, but we aim to smaller code */
6686 int squirrel[] = { -1, -1, -1 };
6689 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6692 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6693 * Result should be 3 lines: q w e, qwe, q w e
6695 G.ifs = get_local_var_value("IFS");
6699 IF_HUSH_JOB(pi->pgrp = -1;)
6700 pi->stopped_cmds = 0;
6701 command = &pi->cmds[0];
6702 argv_expanded = NULL;
6704 if (pi->num_cmds != 1
6705 || pi->followup == PIPE_BG
6706 || command->cmd_type == CMD_SUBSHELL
6713 debug_printf_exec(": group:%p argv:'%s'\n",
6714 command->group, command->argv ? command->argv[0] : "NONE");
6716 if (command->group) {
6717 #if ENABLE_HUSH_FUNCTIONS
6718 if (command->cmd_type == CMD_FUNCDEF) {
6719 /* "executing" func () { list } */
6720 struct function *funcp;
6722 funcp = new_function(command->argv[0]);
6723 /* funcp->name is already set to argv[0] */
6724 funcp->body = command->group;
6726 funcp->body_as_string = command->group_as_string;
6727 command->group_as_string = NULL;
6729 command->group = NULL;
6730 command->argv[0] = NULL;
6731 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6732 funcp->parent_cmd = command;
6733 command->child_func = funcp;
6735 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6737 return EXIT_SUCCESS;
6741 debug_printf("non-subshell group\n");
6742 rcode = 1; /* exitcode if redir failed */
6743 if (setup_redirects(command, squirrel) == 0) {
6744 debug_printf_exec(": run_list\n");
6745 rcode = run_list(command->group) & 0xff;
6747 restore_redirects(squirrel);
6748 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6750 debug_printf_exec("run_pipe: return %d\n", rcode);
6754 argv = command->argv ? command->argv : (char **) &null_ptr;
6756 const struct built_in_command *x;
6757 #if ENABLE_HUSH_FUNCTIONS
6758 const struct function *funcp;
6762 char **new_env = NULL;
6763 struct variable *old_vars = NULL;
6765 if (argv[command->assignment_cnt] == NULL) {
6766 /* Assignments, but no command */
6767 /* Ensure redirects take effect (that is, create files).
6768 * Try "a=t >file" */
6769 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6770 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6771 /* Set shell variables */
6775 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6776 /* Do we need to flag set_local_var() errors?
6777 * "assignment to readonly var" and "putenv error"
6782 /* Redirect error sets $? to 1. Otherwise,
6783 * if evaluating assignment value set $?, retain it.
6784 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6786 rcode = G.last_exitcode;
6787 /* Exit, _skipping_ variable restoring code: */
6788 goto clean_up_and_ret0;
6790 #else /* Older, bigger, but more correct code */
6792 rcode = setup_redirects(command, squirrel);
6793 restore_redirects(squirrel);
6794 /* Set shell variables */
6796 bb_putchar_stderr('+');
6798 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6800 fprintf(stderr, " %s", p);
6801 debug_printf_exec("set shell var:'%s'->'%s'\n",
6803 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6804 /* Do we need to flag set_local_var() errors?
6805 * "assignment to readonly var" and "putenv error"
6810 bb_putchar_stderr('\n');
6811 /* Redirect error sets $? to 1. Otherwise,
6812 * if evaluating assignment value set $?, retain it.
6813 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6815 rcode = G.last_exitcode;
6816 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6818 debug_printf_exec("run_pipe: return %d\n", rcode);
6823 /* Expand the rest into (possibly) many strings each */
6824 #if ENABLE_HUSH_BASH_COMPAT
6825 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6826 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6830 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6833 /* if someone gives us an empty string: `cmd with empty output` */
6834 if (!argv_expanded[0]) {
6835 free(argv_expanded);
6837 return G.last_exitcode;
6840 x = find_builtin(argv_expanded[0]);
6841 #if ENABLE_HUSH_FUNCTIONS
6844 funcp = find_function(argv_expanded[0]);
6848 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6849 debug_printf("exec with redirects only\n");
6850 rcode = setup_redirects(command, NULL);
6851 goto clean_up_and_ret1;
6854 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6857 debug_printf_exec(": builtin '%s' '%s'...\n",
6858 x->b_cmd, argv_expanded[1]);
6860 rcode = x->b_function(argv_expanded) & 0xff;
6863 #if ENABLE_HUSH_FUNCTIONS
6865 # if ENABLE_HUSH_LOCAL
6866 struct variable **sv;
6867 sv = G.shadowed_vars_pp;
6868 G.shadowed_vars_pp = &old_vars;
6870 debug_printf_exec(": function '%s' '%s'...\n",
6871 funcp->name, argv_expanded[1]);
6872 rcode = run_function(funcp, argv_expanded) & 0xff;
6873 # if ENABLE_HUSH_LOCAL
6874 G.shadowed_vars_pp = sv;
6880 unset_vars(new_env);
6882 /* clean_up_and_ret0: */
6883 restore_redirects(squirrel);
6885 free(argv_expanded);
6886 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6888 debug_printf_exec("run_pipe return %d\n", rcode);
6892 if (ENABLE_FEATURE_SH_NOFORK) {
6893 int n = find_applet_by_name(argv_expanded[0]);
6894 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6895 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6897 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6898 argv_expanded[0], argv_expanded[1]);
6899 rcode = run_nofork_applet(n, argv_expanded);
6901 goto clean_up_and_ret;
6904 /* It is neither builtin nor applet. We must fork. */
6908 /* NB: argv_expanded may already be created, and that
6909 * might include `cmd` runs! Do not rerun it! We *must*
6910 * use argv_expanded if it's non-NULL */
6912 /* Going to fork a child per each pipe member */
6917 while (cmd_no < pi->num_cmds) {
6918 struct fd_pair pipefds;
6920 volatile nommu_save_t nommu_save;
6921 nommu_save.new_env = NULL;
6922 nommu_save.old_vars = NULL;
6923 nommu_save.argv = NULL;
6924 nommu_save.argv_from_re_execing = NULL;
6926 command = &pi->cmds[cmd_no];
6928 if (command->argv) {
6929 debug_printf_exec(": pipe member '%s' '%s'...\n",
6930 command->argv[0], command->argv[1]);
6932 debug_printf_exec(": pipe member with no argv\n");
6935 /* pipes are inserted between pairs of commands */
6938 if (cmd_no < pi->num_cmds)
6939 xpiped_pair(pipefds);
6941 command->pid = BB_MMU ? fork() : vfork();
6942 if (!command->pid) { /* child */
6944 disable_restore_tty_pgrp_on_exit();
6945 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6947 /* Every child adds itself to new process group
6948 * with pgid == pid_of_first_child_in_pipe */
6949 if (G.run_list_level == 1 && G_interactive_fd) {
6952 if (pgrp < 0) /* true for 1st process only */
6954 if (setpgid(0, pgrp) == 0
6955 && pi->followup != PIPE_BG
6956 && G_saved_tty_pgrp /* we have ctty */
6958 /* We do it in *every* child, not just first,
6960 tcsetpgrp(G_interactive_fd, pgrp);
6964 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6965 /* 1st cmd in backgrounded pipe
6966 * should have its stdin /dev/null'ed */
6968 if (open(bb_dev_null, O_RDONLY))
6969 xopen("/", O_RDONLY);
6971 xmove_fd(next_infd, 0);
6973 xmove_fd(pipefds.wr, 1);
6976 /* Like bash, explicit redirects override pipes,
6977 * and the pipe fd is available for dup'ing. */
6978 if (setup_redirects(command, NULL))
6981 /* Restore default handlers just prior to exec */
6982 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6984 /* Stores to nommu_save list of env vars putenv'ed
6985 * (NOMMU, on MMU we don't need that) */
6986 /* cast away volatility... */
6987 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6988 /* pseudo_exec() does not return */
6991 /* parent or error */
6992 #if ENABLE_HUSH_FAST
6994 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6996 enable_restore_tty_pgrp_on_exit();
6998 /* Clean up after vforked child */
6999 free(nommu_save.argv);
7000 free(nommu_save.argv_from_re_execing);
7001 unset_vars(nommu_save.new_env);
7002 add_vars(nommu_save.old_vars);
7004 free(argv_expanded);
7005 argv_expanded = NULL;
7006 if (command->pid < 0) { /* [v]fork failed */
7007 /* Clearly indicate, was it fork or vfork */
7008 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7012 /* Second and next children need to know pid of first one */
7014 pi->pgrp = command->pid;
7020 if (cmd_no < pi->num_cmds)
7022 /* Pass read (output) pipe end to next iteration */
7023 next_infd = pipefds.rd;
7026 if (!pi->alive_cmds) {
7028 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7033 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7037 /* NB: called by pseudo_exec, and therefore must not modify any
7038 * global data until exec/_exit (we can be a child after vfork!) */
7039 static int run_list(struct pipe *pi)
7041 #if ENABLE_HUSH_CASE
7042 char *case_word = NULL;
7044 #if ENABLE_HUSH_LOOPS
7045 struct pipe *loop_top = NULL;
7046 char **for_lcur = NULL;
7047 char **for_list = NULL;
7049 smallint last_followup;
7051 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7052 smalluint cond_code = 0;
7054 enum { cond_code = 0 };
7057 smallint rword; /* RES_foo */
7058 smallint last_rword; /* ditto */
7061 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7064 #if ENABLE_HUSH_LOOPS
7065 /* Check syntax for "for" */
7068 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7069 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7071 /* current word is FOR or IN (BOLD in comments below) */
7072 if (cpipe->next == NULL) {
7073 syntax_error("malformed for");
7075 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7078 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7079 if (cpipe->next->res_word == RES_DO)
7081 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7082 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7083 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7085 syntax_error("malformed for");
7087 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7094 /* Past this point, all code paths should jump to ret: label
7095 * in order to return, no direct "return" statements please.
7096 * This helps to ensure that no memory is leaked. */
7104 last_rword = RES_XXXX;
7106 last_followup = PIPE_SEQ;
7107 rcode = G.last_exitcode;
7109 /* Go through list of pipes, (maybe) executing them. */
7110 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7114 IF_HAS_KEYWORDS(rword = pi->res_word;)
7115 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7116 rword, cond_code, last_rword);
7117 #if ENABLE_HUSH_LOOPS
7118 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7119 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7121 /* start of a loop: remember where loop starts */
7126 /* Still in the same "if...", "then..." or "do..." branch? */
7127 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7128 if ((rcode == 0 && last_followup == PIPE_OR)
7129 || (rcode != 0 && last_followup == PIPE_AND)
7131 /* It is "<true> || CMD" or "<false> && CMD"
7132 * and we should not execute CMD */
7133 debug_printf_exec("skipped cmd because of || or &&\n");
7134 last_followup = pi->followup;
7138 last_followup = pi->followup;
7139 IF_HAS_KEYWORDS(last_rword = rword;)
7142 if (rword == RES_THEN) {
7143 /* if false; then ... fi has exitcode 0! */
7144 G.last_exitcode = rcode = EXIT_SUCCESS;
7145 /* "if <false> THEN cmd": skip cmd */
7149 if (rword == RES_ELSE || rword == RES_ELIF) {
7150 /* "if <true> then ... ELSE/ELIF cmd":
7151 * skip cmd and all following ones */
7156 #if ENABLE_HUSH_LOOPS
7157 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7159 /* first loop through for */
7161 static const char encoded_dollar_at[] ALIGN1 = {
7162 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7163 }; /* encoded representation of "$@" */
7164 static const char *const encoded_dollar_at_argv[] = {
7165 encoded_dollar_at, NULL
7166 }; /* argv list with one element: "$@" */
7169 vals = (char**)encoded_dollar_at_argv;
7170 if (pi->next->res_word == RES_IN) {
7171 /* if no variable values after "in" we skip "for" */
7172 if (!pi->next->cmds[0].argv) {
7173 G.last_exitcode = rcode = EXIT_SUCCESS;
7174 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7177 vals = pi->next->cmds[0].argv;
7178 } /* else: "for var; do..." -> assume "$@" list */
7179 /* create list of variable values */
7180 debug_print_strings("for_list made from", vals);
7181 for_list = expand_strvec_to_strvec(vals);
7182 for_lcur = for_list;
7183 debug_print_strings("for_list", for_list);
7186 /* "for" loop is over, clean up */
7192 /* Insert next value from for_lcur */
7193 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7194 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7197 if (rword == RES_IN) {
7198 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7200 if (rword == RES_DONE) {
7201 continue; /* "done" has no cmds too */
7204 #if ENABLE_HUSH_CASE
7205 if (rword == RES_CASE) {
7206 case_word = expand_strvec_to_string(pi->cmds->argv);
7209 if (rword == RES_MATCH) {
7212 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7214 /* all prev words didn't match, does this one match? */
7215 argv = pi->cmds->argv;
7217 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7218 /* TODO: which FNM_xxx flags to use? */
7219 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7221 if (cond_code == 0) { /* match! we will execute this branch */
7222 free(case_word); /* make future "word)" stop */
7230 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7232 continue; /* not matched yet, skip this pipe */
7235 /* Just pressing <enter> in shell should check for jobs.
7236 * OTOH, in non-interactive shell this is useless
7237 * and only leads to extra job checks */
7238 if (pi->num_cmds == 0) {
7239 if (G_interactive_fd)
7240 goto check_jobs_and_continue;
7244 /* After analyzing all keywords and conditions, we decided
7245 * to execute this pipe. NB: have to do checkjobs(NULL)
7246 * after run_pipe to collect any background children,
7247 * even if list execution is to be stopped. */
7248 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7251 #if ENABLE_HUSH_LOOPS
7252 G.flag_break_continue = 0;
7254 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7256 /* We ran a builtin, function, or group.
7257 * rcode is already known
7258 * and we don't need to wait for anything. */
7259 G.last_exitcode = rcode;
7260 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7261 check_and_run_traps(0);
7262 #if ENABLE_HUSH_LOOPS
7263 /* Was it "break" or "continue"? */
7264 if (G.flag_break_continue) {
7265 smallint fbc = G.flag_break_continue;
7266 /* We might fall into outer *loop*,
7267 * don't want to break it too */
7269 G.depth_break_continue--;
7270 if (G.depth_break_continue == 0)
7271 G.flag_break_continue = 0;
7272 /* else: e.g. "continue 2" should *break* once, *then* continue */
7273 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7274 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7275 goto check_jobs_and_break;
7276 /* "continue": simulate end of loop */
7281 #if ENABLE_HUSH_FUNCTIONS
7282 if (G.flag_return_in_progress == 1) {
7283 /* same as "goto check_jobs_and_break" */
7288 } else if (pi->followup == PIPE_BG) {
7289 /* What does bash do with attempts to background builtins? */
7290 /* even bash 3.2 doesn't do that well with nested bg:
7291 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7292 * I'm NOT treating inner &'s as jobs */
7293 check_and_run_traps(0);
7295 if (G.run_list_level == 1)
7298 /* Last command's pid goes to $! */
7299 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7300 G.last_exitcode = rcode = EXIT_SUCCESS;
7301 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7304 if (G.run_list_level == 1 && G_interactive_fd) {
7305 /* Waits for completion, then fg's main shell */
7306 rcode = checkjobs_and_fg_shell(pi);
7307 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7308 check_and_run_traps(0);
7311 { /* This one just waits for completion */
7312 rcode = checkjobs(pi);
7313 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7314 check_and_run_traps(0);
7316 G.last_exitcode = rcode;
7320 /* Analyze how result affects subsequent commands */
7322 if (rword == RES_IF || rword == RES_ELIF)
7325 #if ENABLE_HUSH_LOOPS
7326 /* Beware of "while false; true; do ..."! */
7327 if (pi->next && pi->next->res_word == RES_DO) {
7328 if (rword == RES_WHILE) {
7330 /* "while false; do...done" - exitcode 0 */
7331 G.last_exitcode = rcode = EXIT_SUCCESS;
7332 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7333 goto check_jobs_and_break;
7336 if (rword == RES_UNTIL) {
7338 debug_printf_exec(": until expr is true: breaking\n");
7339 check_jobs_and_break:
7347 check_jobs_and_continue:
7354 #if ENABLE_HUSH_LOOPS
7359 #if ENABLE_HUSH_CASE
7363 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7367 /* Select which version we will use */
7368 static int run_and_free_list(struct pipe *pi)
7371 debug_printf_exec("run_and_free_list entered\n");
7372 if (!G.o_opt[OPT_O_NOEXEC]) {
7373 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7374 rcode = run_list(pi);
7376 /* free_pipe_list has the side effect of clearing memory.
7377 * In the long run that function can be merged with run_list,
7378 * but doing that now would hobble the debugging effort. */
7380 debug_printf_exec("run_and_free_list return %d\n", rcode);
7385 /* Called a few times only (or even once if "sh -c") */
7386 static void init_sigmasks(void)
7390 sigset_t old_blocked_set;
7392 if (!G.inherited_set_is_saved) {
7393 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7394 G.inherited_set = G.blocked_set;
7396 old_blocked_set = G.blocked_set;
7398 mask = (1 << SIGQUIT);
7399 if (G_interactive_fd) {
7400 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7401 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7402 mask |= SPECIAL_JOB_SIGS;
7404 G.non_DFL_mask = mask;
7409 sigaddset(&G.blocked_set, sig);
7413 sigdelset(&G.blocked_set, SIGCHLD);
7415 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7416 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7418 /* POSIX allows shell to re-enable SIGCHLD
7419 * even if it was SIG_IGN on entry */
7420 #if ENABLE_HUSH_FAST
7421 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7422 if (!G.inherited_set_is_saved)
7423 signal(SIGCHLD, SIGCHLD_handler);
7425 if (!G.inherited_set_is_saved)
7426 signal(SIGCHLD, SIG_DFL);
7429 G.inherited_set_is_saved = 1;
7434 static void maybe_set_to_sigexit(int sig)
7436 void (*handler)(int);
7437 /* non_DFL_mask'ed signals are, well, masked,
7438 * no need to set handler for them.
7440 if (!((G.non_DFL_mask >> sig) & 1)) {
7441 handler = signal(sig, sigexit);
7442 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7443 signal(sig, handler);
7446 /* Set handlers to restore tty pgrp and exit */
7447 static void set_fatal_handlers(void)
7449 /* We _must_ restore tty pgrp on fatal signals */
7451 maybe_set_to_sigexit(SIGILL );
7452 maybe_set_to_sigexit(SIGFPE );
7453 maybe_set_to_sigexit(SIGBUS );
7454 maybe_set_to_sigexit(SIGSEGV);
7455 maybe_set_to_sigexit(SIGTRAP);
7456 } /* else: hush is perfect. what SEGV? */
7457 maybe_set_to_sigexit(SIGABRT);
7458 /* bash 3.2 seems to handle these just like 'fatal' ones */
7459 maybe_set_to_sigexit(SIGPIPE);
7460 maybe_set_to_sigexit(SIGALRM);
7461 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7462 * if we aren't interactive... but in this case
7463 * we never want to restore pgrp on exit, and this fn is not called */
7464 /*maybe_set_to_sigexit(SIGHUP );*/
7465 /*maybe_set_to_sigexit(SIGTERM);*/
7466 /*maybe_set_to_sigexit(SIGINT );*/
7470 static int set_mode(int state, char mode, const char *o_opt)
7475 G.o_opt[OPT_O_NOEXEC] = state;
7478 IF_HUSH_MODE_X(G_x_mode = state;)
7482 /* "set -+o" without parameter.
7483 * in bash, set -o produces this output:
7487 * We always use the second form.
7489 const char *p = o_opt_strings;
7492 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7498 idx = index_in_strings(o_opt_strings, o_opt);
7500 G.o_opt[idx] = state;
7504 return EXIT_FAILURE;
7506 return EXIT_SUCCESS;
7509 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7510 int hush_main(int argc, char **argv)
7513 unsigned builtin_argc;
7515 struct variable *cur_var;
7516 struct variable *shell_ver;
7519 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7520 G.last_exitcode = EXIT_SUCCESS;
7522 G.argv0_for_re_execing = argv[0];
7524 /* Deal with HUSH_VERSION */
7525 shell_ver = xzalloc(sizeof(*shell_ver));
7526 shell_ver->flg_export = 1;
7527 shell_ver->flg_read_only = 1;
7528 /* Code which handles ${var<op>...} needs writable values for all variables,
7529 * therefore we xstrdup: */
7530 shell_ver->varstr = xstrdup(hush_version_str);
7531 /* Create shell local variables from the values
7532 * currently living in the environment */
7533 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7534 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7535 G.top_var = shell_ver;
7536 cur_var = G.top_var;
7539 char *value = strchr(*e, '=');
7540 if (value) { /* paranoia */
7541 cur_var->next = xzalloc(sizeof(*cur_var));
7542 cur_var = cur_var->next;
7543 cur_var->varstr = *e;
7544 cur_var->max_len = strlen(*e);
7545 cur_var->flg_export = 1;
7549 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7550 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7551 putenv(shell_ver->varstr);
7554 set_pwd_var(/*exp:*/ 1);
7555 /* bash also exports SHLVL and _,
7556 * and sets (but doesn't export) the following variables:
7558 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7559 * BASH_VERSION='3.2.0(1)-release'
7561 * MACHTYPE=i386-pc-linux-gnu
7563 * HOSTNAME=<xxxxxxxxxx>
7564 * PPID=<NNNNN> - we also do it elsewhere
7575 * PIPESTATUS=([0]="0")
7576 * HISTFILE=/<xxx>/.bash_history
7580 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7582 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7592 #if ENABLE_FEATURE_EDITING
7593 G.line_input_state = new_line_input_t(FOR_SHELL);
7594 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7596 const char *hp = get_local_var_value("HISTFILE");
7598 hp = get_local_var_value("HOME");
7600 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7601 //set_local_var(xasprintf("HISTFILE=%s", ...));
7608 G.global_argc = argc;
7609 G.global_argv = argv;
7610 /* Initialize some more globals to non-zero values */
7611 cmdedit_update_prompt();
7613 if (setjmp(die_jmp)) {
7614 /* xfunc has failed! die die die */
7615 /* no EXIT traps, this is an escape hatch! */
7617 hush_exit(xfunc_error_retval);
7620 /* Shell is non-interactive at first. We need to call
7621 * init_sigmasks() if we are going to execute "sh <script>",
7622 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7623 * If we later decide that we are interactive, we run init_sigmasks()
7624 * in order to intercept (more) signals.
7628 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7631 opt = getopt(argc, argv, "+c:xins"
7634 # if ENABLE_HUSH_FUNCTIONS
7644 * sh ... -c 'script'
7645 * sh ... -c 'script' ARG0 [ARG1...]
7646 * On NOMMU, if builtin_argc != 0,
7647 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7648 * "" needs to be replaced with NULL
7649 * and BARGV vector fed to builtin function.
7650 * Note: the form without ARG0 never happens:
7651 * sh ... -c 'builtin' BARGV... ""
7654 G.root_pid = getpid();
7655 G.root_ppid = getppid();
7657 G.global_argv = argv + optind;
7658 G.global_argc = argc - optind;
7660 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7661 const struct built_in_command *x;
7664 x = find_builtin(optarg);
7665 if (x) { /* paranoia */
7666 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7667 G.global_argv += builtin_argc;
7668 G.global_argv[-1] = NULL; /* replace "" */
7670 G.last_exitcode = x->b_function(argv + optind - 1);
7674 if (!G.global_argv[0]) {
7675 /* -c 'script' (no params): prevent empty $0 */
7676 G.global_argv--; /* points to argv[i] of 'script' */
7677 G.global_argv[0] = argv[0];
7679 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7681 parse_and_run_string(optarg);
7684 /* Well, we cannot just declare interactiveness,
7685 * we have to have some stuff (ctty, etc) */
7686 /* G_interactive_fd++; */
7689 /* "-s" means "read from stdin", but this is how we always
7690 * operate, so simply do nothing here. */
7693 case '<': /* "big heredoc" support */
7694 full_write1_str(optarg);
7697 unsigned long long empty_trap_mask;
7699 G.root_pid = bb_strtou(optarg, &optarg, 16);
7701 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7703 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7705 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7707 builtin_argc = bb_strtou(optarg, &optarg, 16);
7709 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7710 if (empty_trap_mask != 0) {
7713 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7714 for (sig = 1; sig < NSIG; sig++) {
7715 if (empty_trap_mask & (1LL << sig)) {
7716 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7717 sigaddset(&G.blocked_set, sig);
7720 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7722 # if ENABLE_HUSH_LOOPS
7724 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7730 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7732 # if ENABLE_HUSH_FUNCTIONS
7734 struct function *funcp = new_function(optarg);
7735 /* funcp->name is already set to optarg */
7736 /* funcp->body is set to NULL. It's a special case. */
7737 funcp->body_as_string = argv[optind];
7745 if (set_mode(1, opt, NULL) == 0) /* no error */
7749 fprintf(stderr, "Usage: sh [FILE]...\n"
7750 " or: sh -c command [args]...\n\n");
7756 } /* option parsing loop */
7759 G.root_pid = getpid();
7760 G.root_ppid = getppid();
7763 /* If we are login shell... */
7764 if (argv[0] && argv[0][0] == '-') {
7766 debug_printf("sourcing /etc/profile\n");
7767 input = fopen_for_read("/etc/profile");
7768 if (input != NULL) {
7769 close_on_exec_on(fileno(input));
7771 parse_and_run_file(input);
7774 /* bash: after sourcing /etc/profile,
7775 * tries to source (in the given order):
7776 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7777 * stopping on first found. --noprofile turns this off.
7778 * bash also sources ~/.bash_logout on exit.
7779 * If called as sh, skips .bash_XXX files.
7786 * "bash <script>" (which is never interactive (unless -i?))
7787 * sources $BASH_ENV here (without scanning $PATH).
7788 * If called as sh, does the same but with $ENV.
7790 debug_printf("running script '%s'\n", argv[optind]);
7791 G.global_argv = argv + optind;
7792 G.global_argc = argc - optind;
7793 input = xfopen_for_read(argv[optind]);
7794 close_on_exec_on(fileno(input));
7796 parse_and_run_file(input);
7797 #if ENABLE_FEATURE_CLEAN_UP
7803 /* Up to here, shell was non-interactive. Now it may become one.
7804 * NB: don't forget to (re)run init_sigmasks() as needed.
7807 /* A shell is interactive if the '-i' flag was given,
7808 * or if all of the following conditions are met:
7810 * no arguments remaining or the -s flag given
7811 * standard input is a terminal
7812 * standard output is a terminal
7813 * Refer to Posix.2, the description of the 'sh' utility.
7816 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7817 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7818 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7819 if (G_saved_tty_pgrp < 0)
7820 G_saved_tty_pgrp = 0;
7822 /* try to dup stdin to high fd#, >= 255 */
7823 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7824 if (G_interactive_fd < 0) {
7825 /* try to dup to any fd */
7826 G_interactive_fd = dup(STDIN_FILENO);
7827 if (G_interactive_fd < 0) {
7829 G_interactive_fd = 0;
7830 G_saved_tty_pgrp = 0;
7833 // TODO: track & disallow any attempts of user
7834 // to (inadvertently) close/redirect G_interactive_fd
7836 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7837 if (G_interactive_fd) {
7838 close_on_exec_on(G_interactive_fd);
7840 if (G_saved_tty_pgrp) {
7841 /* If we were run as 'hush &', sleep until we are
7842 * in the foreground (tty pgrp == our pgrp).
7843 * If we get started under a job aware app (like bash),
7844 * make sure we are now in charge so we don't fight over
7845 * who gets the foreground */
7847 pid_t shell_pgrp = getpgrp();
7848 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7849 if (G_saved_tty_pgrp == shell_pgrp)
7851 /* send TTIN to ourself (should stop us) */
7852 kill(- shell_pgrp, SIGTTIN);
7856 /* Block some signals */
7859 if (G_saved_tty_pgrp) {
7860 /* Set other signals to restore saved_tty_pgrp */
7861 set_fatal_handlers();
7862 /* Put ourselves in our own process group
7863 * (bash, too, does this only if ctty is available) */
7864 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7865 /* Grab control of the terminal */
7866 tcsetpgrp(G_interactive_fd, getpid());
7868 /* -1 is special - makes xfuncs longjmp, not exit
7869 * (we reset die_sleep = 0 whereever we [v]fork) */
7870 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7874 #elif ENABLE_HUSH_INTERACTIVE
7875 /* No job control compiled in, only prompt/line editing */
7876 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7877 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7878 if (G_interactive_fd < 0) {
7879 /* try to dup to any fd */
7880 G_interactive_fd = dup(STDIN_FILENO);
7881 if (G_interactive_fd < 0)
7883 G_interactive_fd = 0;
7886 if (G_interactive_fd) {
7887 close_on_exec_on(G_interactive_fd);
7891 /* We have interactiveness code disabled */
7895 * if interactive but not a login shell, sources ~/.bashrc
7896 * (--norc turns this off, --rcfile <file> overrides)
7899 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7900 /* note: ash and hush share this string */
7901 printf("\n\n%s %s\n"
7902 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7905 "hush - the humble shell"
7909 parse_and_run_file(stdin);
7912 hush_exit(G.last_exitcode);
7917 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7918 int msh_main(int argc, char **argv)
7920 //bb_error_msg("msh is deprecated, please use hush instead");
7921 return hush_main(argc, argv);
7929 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7934 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7941 return applet_main_func(argc, argv - argc);
7944 static int FAST_FUNC builtin_test(char **argv)
7946 return run_applet_main(argv, test_main);
7949 static int FAST_FUNC builtin_echo(char **argv)
7951 return run_applet_main(argv, echo_main);
7955 static int FAST_FUNC builtin_printf(char **argv)
7957 return run_applet_main(argv, printf_main);
7961 static char **skip_dash_dash(char **argv)
7964 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7969 static int FAST_FUNC builtin_eval(char **argv)
7971 int rcode = EXIT_SUCCESS;
7973 argv = skip_dash_dash(argv);
7975 char *str = expand_strvec_to_string(argv);
7977 * eval "echo Hi; done" ("done" is syntax error):
7978 * "echo Hi" will not execute too.
7980 parse_and_run_string(str);
7982 rcode = G.last_exitcode;
7987 static int FAST_FUNC builtin_cd(char **argv)
7991 argv = skip_dash_dash(argv);
7993 if (newdir == NULL) {
7994 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7995 * bash says "bash: cd: HOME not set" and does nothing
7998 const char *home = get_local_var_value("HOME");
7999 newdir = home ? home : "/";
8001 if (chdir(newdir)) {
8002 /* Mimic bash message exactly */
8003 bb_perror_msg("cd: %s", newdir);
8004 return EXIT_FAILURE;
8006 /* Read current dir (get_cwd(1) is inside) and set PWD.
8007 * Note: do not enforce exporting. If PWD was unset or unexported,
8008 * set it again, but do not export. bash does the same.
8010 set_pwd_var(/*exp:*/ 0);
8011 return EXIT_SUCCESS;
8014 static int FAST_FUNC builtin_exec(char **argv)
8016 argv = skip_dash_dash(argv);
8017 if (argv[0] == NULL)
8018 return EXIT_SUCCESS; /* bash does this */
8020 /* Careful: we can end up here after [v]fork. Do not restore
8021 * tty pgrp then, only top-level shell process does that */
8022 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8023 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8025 /* TODO: if exec fails, bash does NOT exit! We do.
8026 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8027 * and tcsetpgrp, and this is inherently racy.
8029 execvp_or_die(argv);
8032 static int FAST_FUNC builtin_exit(char **argv)
8034 debug_printf_exec("%s()\n", __func__);
8036 /* interactive bash:
8037 * # trap "echo EEE" EXIT
8040 * There are stopped jobs.
8041 * (if there are _stopped_ jobs, running ones don't count)
8044 # EEE (then bash exits)
8046 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8049 /* note: EXIT trap is run by hush_exit */
8050 argv = skip_dash_dash(argv);
8051 if (argv[0] == NULL)
8052 hush_exit(G.last_exitcode);
8053 /* mimic bash: exit 123abc == exit 255 + error msg */
8054 xfunc_error_retval = 255;
8055 /* bash: exit -2 == exit 254, no error msg */
8056 hush_exit(xatoi(argv[0]) & 0xff);
8059 static void print_escaped(const char *s)
8064 const char *p = strchrnul(s, '\'');
8065 /* print 'xxxx', possibly just '' */
8066 printf("'%.*s'", (int)(p - s), s);
8071 /* s points to '; print "'''...'''" */
8073 do putchar('\''); while (*++s == '\'');
8078 #if !ENABLE_HUSH_LOCAL
8079 #define helper_export_local(argv, exp, lvl) \
8080 helper_export_local(argv, exp)
8082 static void helper_export_local(char **argv, int exp, int lvl)
8086 char *name_end = strchrnul(name, '=');
8088 /* So far we do not check that name is valid (TODO?) */
8090 if (*name_end == '\0') {
8091 struct variable *var, **vpp;
8093 vpp = get_ptr_to_local_var(name, name_end - name);
8094 var = vpp ? *vpp : NULL;
8096 if (exp == -1) { /* unexporting? */
8097 /* export -n NAME (without =VALUE) */
8099 var->flg_export = 0;
8100 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8102 } /* else: export -n NOT_EXISTING_VAR: no-op */
8105 if (exp == 1) { /* exporting? */
8106 /* export NAME (without =VALUE) */
8108 var->flg_export = 1;
8109 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8110 putenv(var->varstr);
8114 /* Exporting non-existing variable.
8115 * bash does not put it in environment,
8116 * but remembers that it is exported,
8117 * and does put it in env when it is set later.
8118 * We just set it to "" and export. */
8119 /* Or, it's "local NAME" (without =VALUE).
8120 * bash sets the value to "". */
8121 name = xasprintf("%s=", name);
8123 /* (Un)exporting/making local NAME=VALUE */
8124 name = xstrdup(name);
8126 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8130 static int FAST_FUNC builtin_export(char **argv)
8132 unsigned opt_unexport;
8134 #if ENABLE_HUSH_EXPORT_N
8135 /* "!": do not abort on errors */
8136 opt_unexport = getopt32(argv, "!n");
8137 if (opt_unexport == (uint32_t)-1)
8138 return EXIT_FAILURE;
8145 if (argv[0] == NULL) {
8152 /* ash emits: export VAR='VAL'
8153 * bash: declare -x VAR="VAL"
8154 * we follow ash example */
8155 const char *s = *e++;
8156 const char *p = strchr(s, '=');
8158 if (!p) /* wtf? take next variable */
8161 printf("export %.*s", (int)(p - s) + 1, s);
8162 print_escaped(p + 1);
8166 /*fflush_all(); - done after each builtin anyway */
8168 return EXIT_SUCCESS;
8171 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8173 return EXIT_SUCCESS;
8176 #if ENABLE_HUSH_LOCAL
8177 static int FAST_FUNC builtin_local(char **argv)
8179 if (G.func_nest_level == 0) {
8180 bb_error_msg("%s: not in a function", argv[0]);
8181 return EXIT_FAILURE; /* bash compat */
8183 helper_export_local(argv, 0, G.func_nest_level);
8184 return EXIT_SUCCESS;
8188 static int FAST_FUNC builtin_trap(char **argv)
8194 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8199 /* No args: print all trapped */
8200 for (i = 0; i < NSIG; ++i) {
8203 print_escaped(G.traps[i]);
8204 /* note: bash adds "SIG", but only if invoked
8205 * as "bash". If called as "sh", or if set -o posix,
8206 * then it prints short signal names.
8207 * We are printing short names: */
8208 printf(" %s\n", get_signame(i));
8211 /*fflush_all(); - done after each builtin anyway */
8212 return EXIT_SUCCESS;
8216 /* If first arg is a number: reset all specified signals */
8217 sig = bb_strtou(*argv, NULL, 10);
8223 sig = get_signum(*argv++);
8224 if (sig < 0 || sig >= NSIG) {
8226 /* Mimic bash message exactly */
8227 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8232 G.traps[sig] = xstrdup(new_cmd);
8234 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8235 get_signame(sig), sig, G.traps[sig]);
8237 /* There is no signal for 0 (EXIT) */
8242 sigaddset(&G.blocked_set, sig);
8244 /* There was a trap handler, we are removing it
8245 * (if sig has non-DFL handling,
8246 * we don't need to do anything) */
8247 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8249 sigdelset(&G.blocked_set, sig);
8252 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8256 if (!argv[1]) { /* no second arg */
8257 bb_error_msg("trap: invalid arguments");
8258 return EXIT_FAILURE;
8261 /* First arg is "-": reset all specified to default */
8262 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8263 /* Everything else: set arg as signal handler
8264 * (includes "" case, which ignores signal) */
8265 if (argv[0][0] == '-') {
8266 if (argv[0][1] == '\0') { /* "-" */
8267 /* new_cmd remains NULL: "reset these sigs" */
8270 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8273 /* else: "-something", no special meaning */
8278 goto process_sig_list;
8281 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8282 static int FAST_FUNC builtin_type(char **argv)
8284 int ret = EXIT_SUCCESS;
8290 if (0) {} /* make conditional compile easier below */
8291 /*else if (find_alias(*argv))
8292 type = "an alias";*/
8293 #if ENABLE_HUSH_FUNCTIONS
8294 else if (find_function(*argv))
8295 type = "a function";
8297 else if (find_builtin(*argv))
8298 type = "a shell builtin";
8299 else if ((path = find_in_path(*argv)) != NULL)
8302 bb_error_msg("type: %s: not found", *argv);
8307 printf("%s is %s\n", *argv, type);
8315 /* built-in 'fg' and 'bg' handler */
8316 static int FAST_FUNC builtin_fg_bg(char **argv)
8321 if (!G_interactive_fd)
8322 return EXIT_FAILURE;
8324 /* If they gave us no args, assume they want the last backgrounded task */
8326 for (pi = G.job_list; pi; pi = pi->next) {
8327 if (pi->jobid == G.last_jobid) {
8331 bb_error_msg("%s: no current job", argv[0]);
8332 return EXIT_FAILURE;
8334 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8335 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8336 return EXIT_FAILURE;
8338 for (pi = G.job_list; pi; pi = pi->next) {
8339 if (pi->jobid == jobnum) {
8343 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8344 return EXIT_FAILURE;
8346 /* TODO: bash prints a string representation
8347 * of job being foregrounded (like "sleep 1 | cat") */
8348 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8349 /* Put the job into the foreground. */
8350 tcsetpgrp(G_interactive_fd, pi->pgrp);
8353 /* Restart the processes in the job */
8354 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8355 for (i = 0; i < pi->num_cmds; i++) {
8356 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8357 pi->cmds[i].is_stopped = 0;
8359 pi->stopped_cmds = 0;
8361 i = kill(- pi->pgrp, SIGCONT);
8363 if (errno == ESRCH) {
8364 delete_finished_bg_job(pi);
8365 return EXIT_SUCCESS;
8367 bb_perror_msg("kill (SIGCONT)");
8370 if (argv[0][0] == 'f') {
8372 return checkjobs_and_fg_shell(pi);
8374 return EXIT_SUCCESS;
8378 #if ENABLE_HUSH_HELP
8379 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8381 const struct built_in_command *x;
8384 "Built-in commands:\n"
8385 "------------------\n");
8386 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8388 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8391 return EXIT_SUCCESS;
8396 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8399 const char *status_string;
8401 for (job = G.job_list; job; job = job->next) {
8402 if (job->alive_cmds == job->stopped_cmds)
8403 status_string = "Stopped";
8405 status_string = "Running";
8407 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8409 return EXIT_SUCCESS;
8414 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8419 # ifdef M_TRIM_THRESHOLD
8420 /* Optional. Reduces probability of false positives */
8423 /* Crude attempt to find where "free memory" starts,
8424 * sans fragmentation. */
8426 l = (unsigned long)p;
8429 if (l < (unsigned long)p) l = (unsigned long)p;
8432 if (!G.memleak_value)
8433 G.memleak_value = l;
8435 l -= G.memleak_value;
8442 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8447 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8450 return EXIT_SUCCESS;
8453 static int FAST_FUNC builtin_read(char **argv)
8462 /* "!": do not abort on errors.
8463 * Option string must start with "sr" to match BUILTIN_READ_xxx
8465 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8466 if (read_flags == (uint32_t)-1)
8467 return EXIT_FAILURE;
8470 r = shell_builtin_read(set_local_var_from_halves,
8472 get_local_var_value("IFS"), /* can be NULL */
8480 if ((uintptr_t)r > 1) {
8481 bb_error_msg("%s", r);
8482 r = (char*)(uintptr_t)1;
8485 return (uintptr_t)r;
8488 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8489 * built-in 'set' handler
8491 * set [-abCefhmnuvx] [-o option] [argument...]
8492 * set [+abCefhmnuvx] [+o option] [argument...]
8493 * set -- [argument...]
8496 * Implementations shall support the options in both their hyphen and
8497 * plus-sign forms. These options can also be specified as options to sh.
8499 * Write out all variables and their values: set
8500 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8501 * Turn on the -x and -v options: set -xv
8502 * Unset all positional parameters: set --
8503 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8504 * Set the positional parameters to the expansion of x, even if x expands
8505 * with a leading '-' or '+': set -- $x
8507 * So far, we only support "set -- [argument...]" and some of the short names.
8509 static int FAST_FUNC builtin_set(char **argv)
8512 char **pp, **g_argv;
8513 char *arg = *++argv;
8517 for (e = G.top_var; e; e = e->next)
8519 return EXIT_SUCCESS;
8523 if (strcmp(arg, "--") == 0) {
8527 if (arg[0] != '+' && arg[0] != '-')
8529 for (n = 1; arg[n]; ++n) {
8530 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8532 if (arg[n] == 'o' && argv[1])
8535 } while ((arg = *++argv) != NULL);
8536 /* Now argv[0] is 1st argument */
8539 return EXIT_SUCCESS;
8542 /* NB: G.global_argv[0] ($0) is never freed/changed */
8543 g_argv = G.global_argv;
8544 if (G.global_args_malloced) {
8550 G.global_args_malloced = 1;
8551 pp = xzalloc(sizeof(pp[0]) * 2);
8552 pp[0] = g_argv[0]; /* retain $0 */
8555 /* This realloc's G.global_argv */
8556 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8563 return EXIT_SUCCESS;
8565 /* Nothing known, so abort */
8567 bb_error_msg("set: %s: invalid option", arg);
8568 return EXIT_FAILURE;
8571 static int FAST_FUNC builtin_shift(char **argv)
8574 argv = skip_dash_dash(argv);
8578 if (n >= 0 && n < G.global_argc) {
8579 if (G.global_args_malloced) {
8582 free(G.global_argv[m++]);
8585 memmove(&G.global_argv[1], &G.global_argv[n+1],
8586 G.global_argc * sizeof(G.global_argv[0]));
8587 return EXIT_SUCCESS;
8589 return EXIT_FAILURE;
8592 static int FAST_FUNC builtin_source(char **argv)
8594 char *arg_path, *filename;
8597 #if ENABLE_HUSH_FUNCTIONS
8601 argv = skip_dash_dash(argv);
8604 /* bash says: "bash: .: filename argument required" */
8605 return 2; /* bash compat */
8608 if (!strchr(filename, '/')) {
8609 arg_path = find_in_path(filename);
8611 filename = arg_path;
8613 input = fopen_or_warn(filename, "r");
8616 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8617 return EXIT_FAILURE;
8619 close_on_exec_on(fileno(input));
8621 #if ENABLE_HUSH_FUNCTIONS
8622 sv_flg = G.flag_return_in_progress;
8623 /* "we are inside sourced file, ok to use return" */
8624 G.flag_return_in_progress = -1;
8626 save_and_replace_G_args(&sv, argv);
8628 parse_and_run_file(input);
8631 restore_G_args(&sv, argv);
8632 #if ENABLE_HUSH_FUNCTIONS
8633 G.flag_return_in_progress = sv_flg;
8636 return G.last_exitcode;
8639 static int FAST_FUNC builtin_umask(char **argv)
8645 argv = skip_dash_dash(argv);
8647 mode_t old_mask = mask;
8650 rc = bb_parse_mode(argv[0], &mask);
8655 * bash: umask: 'q': invalid symbolic mode operator
8656 * bash: umask: 999: octal number out of range
8658 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8663 printf("%04o\n", (unsigned) mask);
8664 /* fall through and restore mask which we set to 0 */
8668 return !rc; /* rc != 0 - success */
8671 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8672 static int FAST_FUNC builtin_unset(char **argv)
8677 /* "!": do not abort on errors */
8678 /* "+": stop at 1st non-option */
8679 opts = getopt32(argv, "!+vf");
8680 if (opts == (unsigned)-1)
8681 return EXIT_FAILURE;
8683 bb_error_msg("unset: -v and -f are exclusive");
8684 return EXIT_FAILURE;
8690 if (!(opts & 2)) { /* not -f */
8691 if (unset_local_var(*argv)) {
8692 /* unset <nonexistent_var> doesn't fail.
8693 * Error is when one tries to unset RO var.
8694 * Message was printed by unset_local_var. */
8698 #if ENABLE_HUSH_FUNCTIONS
8708 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8709 static int FAST_FUNC builtin_wait(char **argv)
8711 int ret = EXIT_SUCCESS;
8714 argv = skip_dash_dash(argv);
8715 if (argv[0] == NULL) {
8716 /* Don't care about wait results */
8717 /* Note 1: must wait until there are no more children */
8718 /* Note 2: must be interruptible */
8720 * $ sleep 3 & sleep 6 & wait
8725 * $ sleep 3 & sleep 6 & wait
8729 * ^C <-- after ~4 sec from keyboard
8732 sigaddset(&G.blocked_set, SIGCHLD);
8733 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8736 if (errno == ECHILD)
8738 /* Wait for SIGCHLD or any other signal of interest */
8739 /* sigtimedwait with infinite timeout: */
8740 sig = sigwaitinfo(&G.blocked_set, NULL);
8742 sig = check_and_run_traps(sig);
8743 if (sig && sig != SIGCHLD) { /* see note 2 */
8749 sigdelset(&G.blocked_set, SIGCHLD);
8750 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8754 /* This is probably buggy wrt interruptible-ness */
8756 pid_t pid = bb_strtou(*argv, NULL, 10);
8758 /* mimic bash message */
8759 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8760 return EXIT_FAILURE;
8762 if (waitpid(pid, &status, 0) == pid) {
8763 if (WIFSIGNALED(status))
8764 ret = 128 + WTERMSIG(status);
8765 else if (WIFEXITED(status))
8766 ret = WEXITSTATUS(status);
8770 bb_perror_msg("wait %s", *argv);
8779 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8780 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8783 def = bb_strtou(argv[1], NULL, 10);
8784 if (errno || def < def_min || argv[2]) {
8785 bb_error_msg("%s: bad arguments", argv[0]);
8793 #if ENABLE_HUSH_LOOPS
8794 static int FAST_FUNC builtin_break(char **argv)
8797 if (G.depth_of_loop == 0) {
8798 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8799 return EXIT_SUCCESS; /* bash compat */
8801 G.flag_break_continue++; /* BC_BREAK = 1 */
8803 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8804 if (depth == UINT_MAX)
8805 G.flag_break_continue = BC_BREAK;
8806 if (G.depth_of_loop < depth)
8807 G.depth_break_continue = G.depth_of_loop;
8809 return EXIT_SUCCESS;
8812 static int FAST_FUNC builtin_continue(char **argv)
8814 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8815 return builtin_break(argv);
8819 #if ENABLE_HUSH_FUNCTIONS
8820 static int FAST_FUNC builtin_return(char **argv)
8824 if (G.flag_return_in_progress != -1) {
8825 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8826 return EXIT_FAILURE; /* bash compat */
8829 G.flag_return_in_progress = 1;
8832 * out of range: wraps around at 256, does not error out
8833 * non-numeric param:
8834 * f() { false; return qwe; }; f; echo $?
8835 * bash: return: qwe: numeric argument required <== we do this
8836 * 255 <== we also do this
8838 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);