1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
86 || defined(__APPLE__) \
88 # include <malloc.h> /* for malloc_trim */
91 /* #include <dmalloc.h> */
96 #include "shell_common.h"
99 #if ENABLE_HUSH_RANDOM_SUPPORT
102 # define CLEAR_RANDOM_T(rnd) ((void)0)
105 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
108 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
109 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
110 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
111 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
113 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
114 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
117 //config: bool "hush"
120 //config: hush is a small shell (25k). It handles the normal flow control
121 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
122 //config: case/esac. Redirections, here documents, $((arithmetic))
123 //config: and functions are supported.
125 //config: It will compile and work on no-mmu systems.
127 //config: It does not handle select, aliases, tilde expansion,
128 //config: &>file and >&file redirection of stdout+stderr.
130 //config:config HUSH_BASH_COMPAT
131 //config: bool "bash-compatible extensions"
133 //config: depends on HUSH
135 //config: Enable bash-compatible extensions.
137 //config:config HUSH_BRACE_EXPANSION
138 //config: bool "Brace expansion"
140 //config: depends on HUSH_BASH_COMPAT
142 //config: Enable {abc,def} extension.
144 //config:config HUSH_HELP
145 //config: bool "help builtin"
147 //config: depends on HUSH
149 //config: Enable help builtin in hush. Code size + ~1 kbyte.
151 //config:config HUSH_INTERACTIVE
152 //config: bool "Interactive mode"
154 //config: depends on HUSH
156 //config: Enable interactive mode (prompt and command editing).
157 //config: Without this, hush simply reads and executes commands
158 //config: from stdin just like a shell script from a file.
159 //config: No prompt, no PS1/PS2 magic shell variables.
161 //config:config HUSH_SAVEHISTORY
162 //config: bool "Save command history to .hush_history"
164 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
166 //config: Enable history saving in hush.
168 //config:config HUSH_JOB
169 //config: bool "Job control"
171 //config: depends on HUSH_INTERACTIVE
173 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
174 //config: command (not entire shell), fg/bg builtins work. Without this option,
175 //config: "cmd &" still works by simply spawning a process and immediately
176 //config: prompting for next command (or executing next command in a script),
177 //config: but no separate process group is formed.
179 //config:config HUSH_TICK
180 //config: bool "Process substitution"
182 //config: depends on HUSH
184 //config: Enable process substitution `command` and $(command) in hush.
186 //config:config HUSH_IF
187 //config: bool "Support if/then/elif/else/fi"
189 //config: depends on HUSH
191 //config: Enable if/then/elif/else/fi in hush.
193 //config:config HUSH_LOOPS
194 //config: bool "Support for, while and until loops"
196 //config: depends on HUSH
198 //config: Enable for, while and until loops in hush.
200 //config:config HUSH_CASE
201 //config: bool "Support case ... esac statement"
203 //config: depends on HUSH
205 //config: Enable case ... esac statement in hush. +400 bytes.
207 //config:config HUSH_FUNCTIONS
208 //config: bool "Support funcname() { commands; } syntax"
210 //config: depends on HUSH
212 //config: Enable support for shell functions in hush. +800 bytes.
214 //config:config HUSH_LOCAL
215 //config: bool "Support local builtin"
217 //config: depends on HUSH_FUNCTIONS
219 //config: Enable support for local variables in functions.
221 //config:config HUSH_RANDOM_SUPPORT
222 //config: bool "Pseudorandom generator and $RANDOM variable"
224 //config: depends on HUSH
226 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
227 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
229 //config:config HUSH_EXPORT_N
230 //config: bool "Support 'export -n' option"
232 //config: depends on HUSH
234 //config: export -n unexports variables. It is a bash extension.
236 //config:config HUSH_MODE_X
237 //config: bool "Support 'hush -x' option and 'set -x' command"
239 //config: depends on HUSH
241 //config: This instructs hush to print commands before execution.
242 //config: Adds ~300 bytes.
245 //config: bool "msh (deprecated: aliased to hush)"
247 //config: select HUSH
249 //config: msh is deprecated and will be removed, please migrate to hush.
252 /* -i (interactive) and -s (read stdin) are also accepted,
253 * but currently do nothing, therefore aren't shown in help.
254 * NOMMU-specific options are not meant to be used by users,
255 * therefore we don't show them either.
257 //usage:#define hush_trivial_usage
258 //usage: "[-nx] [-c SCRIPT]"
259 //usage:#define hush_full_usage ""
260 //usage:#define msh_trivial_usage hush_trivial_usage
261 //usage:#define msh_full_usage ""
262 //usage:#define sh_trivial_usage NOUSAGE_STR
263 //usage:#define sh_full_usage ""
264 //usage:#define bash_trivial_usage NOUSAGE_STR
265 //usage:#define bash_full_usage ""
269 #define LEAK_HUNTING 0
270 #define BUILD_AS_NOMMU 0
271 /* Enable/disable sanity checks. Ok to enable in production,
272 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
273 * Keeping 1 for now even in released versions.
276 /* Slightly bigger (+200 bytes), but faster hush.
277 * So far it only enables a trick with counting SIGCHLDs and forks,
278 * which allows us to do fewer waitpid's.
279 * (we can detect a case where neither forks were done nor SIGCHLDs happened
280 * and therefore waitpid will return the same result as last time)
282 #define ENABLE_HUSH_FAST 0
283 /* TODO: implement simplified code for users which do not need ${var%...} ops
284 * So far ${var%...} ops are always enabled:
286 #define ENABLE_HUSH_DOLLAR_OPS 1
291 # undef USE_FOR_NOMMU
294 # define USE_FOR_NOMMU(...) __VA_ARGS__
295 # define USE_FOR_MMU(...)
298 #include "NUM_APPLETS.h"
300 /* STANDALONE does not make sense, and won't compile */
301 # undef CONFIG_FEATURE_SH_STANDALONE
302 # undef ENABLE_FEATURE_SH_STANDALONE
303 # undef IF_FEATURE_SH_STANDALONE
304 # undef IF_NOT_FEATURE_SH_STANDALONE
305 # define ENABLE_FEATURE_SH_STANDALONE 0
306 # define IF_FEATURE_SH_STANDALONE(...)
307 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
310 #if !ENABLE_HUSH_INTERACTIVE
311 # undef ENABLE_FEATURE_EDITING
312 # define ENABLE_FEATURE_EDITING 0
313 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
314 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
317 /* Do we support ANY keywords? */
318 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
319 # define HAS_KEYWORDS 1
320 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
321 # define IF_HAS_NO_KEYWORDS(...)
323 # define HAS_KEYWORDS 0
324 # define IF_HAS_KEYWORDS(...)
325 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
328 /* If you comment out one of these below, it will be #defined later
329 * to perform debug printfs to stderr: */
330 #define debug_printf(...) do {} while (0)
331 /* Finer-grained debug switches */
332 #define debug_printf_parse(...) do {} while (0)
333 #define debug_print_tree(a, b) do {} while (0)
334 #define debug_printf_exec(...) do {} while (0)
335 #define debug_printf_env(...) do {} while (0)
336 #define debug_printf_jobs(...) do {} while (0)
337 #define debug_printf_expand(...) do {} while (0)
338 #define debug_printf_varexp(...) do {} while (0)
339 #define debug_printf_glob(...) do {} while (0)
340 #define debug_printf_list(...) do {} while (0)
341 #define debug_printf_subst(...) do {} while (0)
342 #define debug_printf_clean(...) do {} while (0)
344 #define ERR_PTR ((void*)(long)1)
346 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
348 #define _SPECIAL_VARS_STR "_*@$!?#"
349 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
350 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
351 #if ENABLE_HUSH_BASH_COMPAT
352 /* Support / and // replace ops */
353 /* Note that // is stored as \ in "encoded" string representation */
354 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
355 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
356 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
358 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
359 # define VAR_SUBST_OPS "%#:-=+?"
360 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
363 #define SPECIAL_VAR_SYMBOL 3
367 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
369 /* This supports saving pointers malloced in vfork child,
370 * to be freed in the parent.
373 typedef struct nommu_save_t {
375 struct variable *old_vars;
377 char **argv_from_re_execing;
390 #if ENABLE_HUSH_LOOPS
397 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
402 /* three pseudo-keywords support contrived "case" syntax: */
403 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
404 RES_MATCH , /* "word)" */
405 RES_CASE_BODY, /* "this command is inside CASE" */
412 typedef struct o_string {
414 int length; /* position where data is appended */
417 /* At least some part of the string was inside '' or "",
418 * possibly empty one: word"", wo''rd etc. */
419 smallint has_quoted_part;
420 smallint has_empty_slot;
421 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
424 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
426 /* Protect newly added chars against globbing
427 * by prepending \ to *, ?, [, \ */
428 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
431 MAYBE_ASSIGNMENT = 0,
432 DEFINITELY_ASSIGNMENT = 1,
434 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
437 /* Used for initialization: o_string foo = NULL_O_STRING; */
438 #define NULL_O_STRING { NULL }
440 /* I can almost use ordinary FILE*. Is open_memstream() universally
441 * available? Where is it documented? */
442 typedef struct in_str {
444 /* eof_flag=1: last char in ->p is really an EOF */
445 char eof_flag; /* meaningless if ->p == NULL */
447 #if ENABLE_HUSH_INTERACTIVE
449 smallint promptmode; /* 0: PS1, 1: PS2 */
452 int (*get) (struct in_str *) FAST_FUNC;
453 int (*peek) (struct in_str *) FAST_FUNC;
455 #define i_getch(input) ((input)->get(input))
456 #define i_peek(input) ((input)->peek(input))
458 /* The descrip member of this structure is only used to make
459 * debugging output pretty */
460 static const struct {
462 signed char default_fd;
465 { O_RDONLY, 0, "<" },
466 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
467 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
468 { O_CREAT|O_RDWR, 1, "<>" },
469 { O_RDONLY, 0, "<<" },
470 /* Should not be needed. Bogus default_fd helps in debugging */
471 /* { O_RDONLY, 77, "<<" }, */
474 struct redir_struct {
475 struct redir_struct *next;
476 char *rd_filename; /* filename */
477 int rd_fd; /* fd to redirect */
478 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
480 smallint rd_type; /* (enum redir_type) */
481 /* note: for heredocs, rd_filename contains heredoc delimiter,
482 * and subsequently heredoc itself; and rd_dup is a bitmask:
483 * bit 0: do we need to trim leading tabs?
484 * bit 1: is heredoc quoted (<<'delim' syntax) ?
487 typedef enum redir_type {
489 REDIRECT_OVERWRITE = 1,
492 REDIRECT_HEREDOC = 4,
493 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
496 REDIRFD_SYNTAX_ERR = -2,
497 REDIRFD_TO_FILE = -1,
498 /* otherwise, rd_fd is redirected to rd_dup */
500 HEREDOC_SKIPTABS = 1,
506 pid_t pid; /* 0 if exited */
507 int assignment_cnt; /* how many argv[i] are assignments? */
508 smallint is_stopped; /* is the command currently running? */
509 smallint cmd_type; /* CMD_xxx */
511 #define CMD_SUBSHELL 1
512 #if ENABLE_HUSH_BASH_COMPAT
513 /* used for "[[ EXPR ]]" */
514 # define CMD_SINGLEWORD_NOGLOB 2
516 #if ENABLE_HUSH_FUNCTIONS
517 # define CMD_FUNCDEF 3
520 smalluint cmd_exitcode;
521 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
524 char *group_as_string;
526 #if ENABLE_HUSH_FUNCTIONS
527 struct function *child_func;
528 /* This field is used to prevent a bug here:
529 * while...do f1() {a;}; f1; f1() {b;}; f1; done
530 * When we execute "f1() {a;}" cmd, we create new function and clear
531 * cmd->group, cmd->group_as_string, cmd->argv[0].
532 * When we execute "f1() {b;}", we notice that f1 exists,
533 * and that its "parent cmd" struct is still "alive",
534 * we put those fields back into cmd->xxx
535 * (struct function has ->parent_cmd ptr to facilitate that).
536 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
537 * Without this trick, loop would execute a;b;b;b;...
538 * instead of correct sequence a;b;a;b;...
539 * When command is freed, it severs the link
540 * (sets ->child_func->parent_cmd to NULL).
543 char **argv; /* command name and arguments */
544 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
545 * and on execution these are substituted with their values.
546 * Substitution can make _several_ words out of one argv[n]!
547 * Example: argv[0]=='.^C*^C.' here: echo .$*.
548 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
550 struct redir_struct *redirects; /* I/O redirections */
552 /* Is there anything in this command at all? */
553 #define IS_NULL_CMD(cmd) \
554 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
558 int num_cmds; /* total number of commands in pipe */
559 int alive_cmds; /* number of commands running (not exited) */
560 int stopped_cmds; /* number of commands alive, but stopped */
562 int jobid; /* job number */
563 pid_t pgrp; /* process group ID for the job */
564 char *cmdtext; /* name of job */
566 struct command *cmds; /* array of commands in pipe */
567 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
568 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
569 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
571 typedef enum pipe_style {
577 /* Is there anything in this pipe at all? */
578 #define IS_NULL_PIPE(pi) \
579 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
581 /* This holds pointers to the various results of parsing */
582 struct parse_context {
583 /* linked list of pipes */
584 struct pipe *list_head;
585 /* last pipe (being constructed right now) */
587 /* last command in pipe (being constructed right now) */
588 struct command *command;
589 /* last redirect in command->redirects list */
590 struct redir_struct *pending_redirect;
596 smallint ctx_inverted; /* "! cmd | cmd" */
598 smallint ctx_dsemicolon; /* ";;" seen */
600 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
602 /* group we are enclosed in:
603 * example: "if pipe1; pipe2; then pipe3; fi"
604 * when we see "if" or "then", we malloc and copy current context,
605 * and make ->stack point to it. then we parse pipeN.
606 * when closing "then" / fi" / whatever is found,
607 * we move list_head into ->stack->command->group,
608 * copy ->stack into current context, and delete ->stack.
609 * (parsing of { list } and ( list ) doesn't use this method)
611 struct parse_context *stack;
615 /* On program start, environ points to initial environment.
616 * putenv adds new pointers into it, unsetenv removes them.
617 * Neither of these (de)allocates the strings.
618 * setenv allocates new strings in malloc space and does putenv,
619 * and thus setenv is unusable (leaky) for shell's purposes */
620 #define setenv(...) setenv_is_leaky_dont_use()
622 struct variable *next;
623 char *varstr; /* points to "name=" portion */
624 #if ENABLE_HUSH_LOCAL
625 unsigned func_nest_level;
627 int max_len; /* if > 0, name is part of initial env; else name is malloced */
628 smallint flg_export; /* putenv should be done on this var */
629 smallint flg_read_only;
637 #if ENABLE_HUSH_FUNCTIONS
639 struct function *next;
641 struct command *parent_cmd;
644 char *body_as_string;
650 /* set -/+o OPT support. (TODO: make it optional)
651 * bash supports the following opts:
662 * interactive-comments on
680 static const char o_opt_strings[] ALIGN1 =
683 #if ENABLE_HUSH_MODE_X
690 #if ENABLE_HUSH_MODE_X
697 /* "Globals" within this file */
698 /* Sorted roughly by size (smaller offsets == smaller code) */
700 /* interactive_fd != 0 means we are an interactive shell.
701 * If we are, then saved_tty_pgrp can also be != 0, meaning
702 * that controlling tty is available. With saved_tty_pgrp == 0,
703 * job control still works, but terminal signals
704 * (^C, ^Z, ^Y, ^\) won't work at all, and background
705 * process groups can only be created with "cmd &".
706 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
707 * to give tty to the foreground process group,
708 * and will take it back when the group is stopped (^Z)
711 #if ENABLE_HUSH_INTERACTIVE
712 /* 'interactive_fd' is a fd# open to ctty, if we have one
713 * _AND_ if we decided to act interactively */
717 # define G_interactive_fd (G.interactive_fd)
719 # define G_interactive_fd 0
721 #if ENABLE_FEATURE_EDITING
722 line_input_t *line_input_state;
727 #if ENABLE_HUSH_RANDOM_SUPPORT
733 pid_t saved_tty_pgrp;
734 struct pipe *job_list;
735 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
737 # define G_saved_tty_pgrp 0
739 char o_opt[NUM_OPT_O];
740 #if ENABLE_HUSH_MODE_X
741 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
745 smallint flag_SIGINT;
746 #if ENABLE_HUSH_LOOPS
747 smallint flag_break_continue;
749 #if ENABLE_HUSH_FUNCTIONS
750 /* 0: outside of a function (or sourced file)
751 * -1: inside of a function, ok to use return builtin
752 * 1: return is invoked, skip all till end of func
754 smallint flag_return_in_progress;
756 smallint exiting; /* used to prevent EXIT trap recursion */
757 /* These four support $?, $#, and $1 */
758 smalluint last_exitcode;
759 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
760 smalluint global_args_malloced;
761 smalluint inherited_set_is_saved;
762 /* how many non-NULL argv's we have. NB: $# + 1 */
766 char *argv0_for_re_execing;
768 #if ENABLE_HUSH_LOOPS
769 unsigned depth_break_continue;
770 unsigned depth_of_loop;
774 struct variable *top_var;
775 char **expanded_assignments;
776 #if ENABLE_HUSH_FUNCTIONS
777 struct function *top_func;
778 # if ENABLE_HUSH_LOCAL
779 struct variable **shadowed_vars_pp;
780 unsigned func_nest_level;
783 /* Signal and trap handling */
785 unsigned count_SIGCHLD;
786 unsigned handled_SIGCHLD;
787 smallint we_have_children;
789 /* which signals have non-DFL handler (even with no traps set)? */
790 unsigned non_DFL_mask;
791 char **traps; /* char *traps[NSIG] */
792 sigset_t blocked_set;
793 sigset_t inherited_set;
795 unsigned long memleak_value;
798 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
800 #define G (*ptr_to_globals)
801 /* Not #defining name to G.name - this quickly gets unwieldy
802 * (too many defines). Also, I actually prefer to see when a variable
803 * is global, thus "G." prefix is a useful hint */
804 #define INIT_G() do { \
805 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
809 /* Function prototypes for builtins */
810 static int builtin_cd(char **argv) FAST_FUNC;
811 static int builtin_echo(char **argv) FAST_FUNC;
812 static int builtin_eval(char **argv) FAST_FUNC;
813 static int builtin_exec(char **argv) FAST_FUNC;
814 static int builtin_exit(char **argv) FAST_FUNC;
815 static int builtin_export(char **argv) FAST_FUNC;
817 static int builtin_fg_bg(char **argv) FAST_FUNC;
818 static int builtin_jobs(char **argv) FAST_FUNC;
821 static int builtin_help(char **argv) FAST_FUNC;
823 #if ENABLE_HUSH_LOCAL
824 static int builtin_local(char **argv) FAST_FUNC;
827 static int builtin_memleak(char **argv) FAST_FUNC;
830 static int builtin_printf(char **argv) FAST_FUNC;
832 static int builtin_pwd(char **argv) FAST_FUNC;
833 static int builtin_read(char **argv) FAST_FUNC;
834 static int builtin_set(char **argv) FAST_FUNC;
835 static int builtin_shift(char **argv) FAST_FUNC;
836 static int builtin_source(char **argv) FAST_FUNC;
837 static int builtin_test(char **argv) FAST_FUNC;
838 static int builtin_trap(char **argv) FAST_FUNC;
839 static int builtin_type(char **argv) FAST_FUNC;
840 static int builtin_true(char **argv) FAST_FUNC;
841 static int builtin_umask(char **argv) FAST_FUNC;
842 static int builtin_unset(char **argv) FAST_FUNC;
843 static int builtin_wait(char **argv) FAST_FUNC;
844 #if ENABLE_HUSH_LOOPS
845 static int builtin_break(char **argv) FAST_FUNC;
846 static int builtin_continue(char **argv) FAST_FUNC;
848 #if ENABLE_HUSH_FUNCTIONS
849 static int builtin_return(char **argv) FAST_FUNC;
852 /* Table of built-in functions. They can be forked or not, depending on
853 * context: within pipes, they fork. As simple commands, they do not.
854 * When used in non-forking context, they can change global variables
855 * in the parent shell process. If forked, of course they cannot.
856 * For example, 'unset foo | whatever' will parse and run, but foo will
857 * still be set at the end. */
858 struct built_in_command {
860 int (*b_function)(char **argv) FAST_FUNC;
863 # define BLTIN(cmd, func, help) { cmd, func, help }
865 # define BLTIN(cmd, func, help) { cmd, func }
869 static const struct built_in_command bltins1[] = {
870 BLTIN("." , builtin_source , "Run commands in a file"),
871 BLTIN(":" , builtin_true , NULL),
873 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
875 #if ENABLE_HUSH_LOOPS
876 BLTIN("break" , builtin_break , "Exit from a loop"),
878 BLTIN("cd" , builtin_cd , "Change directory"),
879 #if ENABLE_HUSH_LOOPS
880 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
882 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
883 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
884 BLTIN("exit" , builtin_exit , "Exit"),
885 BLTIN("export" , builtin_export , "Set environment variables"),
887 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
890 BLTIN("help" , builtin_help , NULL),
893 BLTIN("jobs" , builtin_jobs , "List jobs"),
895 #if ENABLE_HUSH_LOCAL
896 BLTIN("local" , builtin_local , "Set local variables"),
899 BLTIN("memleak" , builtin_memleak , NULL),
901 BLTIN("read" , builtin_read , "Input into variable"),
902 #if ENABLE_HUSH_FUNCTIONS
903 BLTIN("return" , builtin_return , "Return from a function"),
905 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
906 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
907 #if ENABLE_HUSH_BASH_COMPAT
908 BLTIN("source" , builtin_source , "Run commands in a file"),
910 BLTIN("trap" , builtin_trap , "Trap signals"),
911 BLTIN("type" , builtin_type , "Show command type"),
912 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
913 BLTIN("umask" , builtin_umask , "Set file creation mask"),
914 BLTIN("unset" , builtin_unset , "Unset variables"),
915 BLTIN("wait" , builtin_wait , "Wait for process"),
917 /* For now, echo and test are unconditionally enabled.
918 * Maybe make it configurable? */
919 static const struct built_in_command bltins2[] = {
920 BLTIN("[" , builtin_test , NULL),
921 BLTIN("echo" , builtin_echo , NULL),
923 BLTIN("printf" , builtin_printf , NULL),
925 BLTIN("pwd" , builtin_pwd , NULL),
926 BLTIN("test" , builtin_test , NULL),
933 /* prevent disasters with G.debug_indent < 0 */
934 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
935 # define debug_enter() (G.debug_indent++)
936 # define debug_leave() (G.debug_indent--)
938 # define indent() ((void)0)
939 # define debug_enter() ((void)0)
940 # define debug_leave() ((void)0)
944 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
947 #ifndef debug_printf_parse
948 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
951 #ifndef debug_printf_exec
952 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
955 #ifndef debug_printf_env
956 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
959 #ifndef debug_printf_jobs
960 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
961 # define DEBUG_JOBS 1
963 # define DEBUG_JOBS 0
966 #ifndef debug_printf_expand
967 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
968 # define DEBUG_EXPAND 1
970 # define DEBUG_EXPAND 0
973 #ifndef debug_printf_varexp
974 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
977 #ifndef debug_printf_glob
978 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
979 # define DEBUG_GLOB 1
981 # define DEBUG_GLOB 0
984 #ifndef debug_printf_list
985 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
988 #ifndef debug_printf_subst
989 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
992 #ifndef debug_printf_clean
993 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
994 # define DEBUG_CLEAN 1
996 # define DEBUG_CLEAN 0
1000 static void debug_print_strings(const char *prefix, char **vv)
1003 fdprintf(2, "%s:\n", prefix);
1005 fdprintf(2, " '%s'\n", *vv++);
1008 # define debug_print_strings(prefix, vv) ((void)0)
1012 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1015 static void *xxmalloc(int lineno, size_t size)
1017 void *ptr = xmalloc((size + 0xff) & ~0xff);
1018 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1021 static void *xxrealloc(int lineno, void *ptr, size_t size)
1023 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1024 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1027 static char *xxstrdup(int lineno, const char *str)
1029 char *ptr = xstrdup(str);
1030 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1033 static void xxfree(void *ptr)
1035 fdprintf(2, "free %p\n", ptr);
1038 # define xmalloc(s) xxmalloc(__LINE__, s)
1039 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1040 # define xstrdup(s) xxstrdup(__LINE__, s)
1041 # define free(p) xxfree(p)
1045 /* Syntax and runtime errors. They always abort scripts.
1046 * In interactive use they usually discard unparsed and/or unexecuted commands
1047 * and return to the prompt.
1048 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1051 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1052 # define syntax_error(lineno, msg) syntax_error(msg)
1053 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1054 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1055 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1056 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1059 static void die_if_script(unsigned lineno, const char *fmt, ...)
1064 bb_error_msg("hush.c:%u", lineno);
1067 bb_verror_msg(fmt, p, NULL);
1069 if (!G_interactive_fd)
1073 static void syntax_error(unsigned lineno, const char *msg)
1076 die_if_script(lineno, "syntax error: %s", msg);
1078 die_if_script(lineno, "syntax error", NULL);
1081 static void syntax_error_at(unsigned lineno, const char *msg)
1083 die_if_script(lineno, "syntax error at '%s'", msg);
1086 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1088 die_if_script(lineno, "syntax error: unterminated %s", s);
1091 /* It so happens that all such cases are totally fatal
1092 * even if shell is interactive: EOF while looking for closing
1093 * delimiter. There is nowhere to read stuff from after that,
1094 * it's EOF! The only choice is to terminate.
1096 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1097 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1099 char msg[2] = { ch, '\0' };
1100 syntax_error_unterm_str(lineno, msg);
1104 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1109 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1113 # undef die_if_script
1114 # undef syntax_error
1115 # undef syntax_error_at
1116 # undef syntax_error_unterm_ch
1117 # undef syntax_error_unterm_str
1118 # undef syntax_error_unexpected_ch
1120 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1121 # define syntax_error(msg) syntax_error(__LINE__, msg)
1122 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1123 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1124 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1125 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1129 #if ENABLE_HUSH_INTERACTIVE
1130 static void cmdedit_update_prompt(void);
1132 # define cmdedit_update_prompt() ((void)0)
1136 /* Utility functions
1138 /* Replace each \x with x in place, return ptr past NUL. */
1139 static char *unbackslash(char *src)
1141 char *dst = src = strchrnul(src, '\\');
1145 if ((*dst++ = *src++) == '\0')
1151 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1172 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1173 v[count1 + count2] = NULL;
1176 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1180 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1182 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1183 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1186 #define add_strings_to_strings(strings, add, need_to_dup) \
1187 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1190 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1191 static char **add_string_to_strings(char **strings, char *add)
1196 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1199 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1201 char **ptr = add_string_to_strings(strings, add);
1202 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1205 #define add_string_to_strings(strings, add) \
1206 xx_add_string_to_strings(__LINE__, strings, add)
1209 static void free_strings(char **strings)
1224 /* Helpers for setting new $n and restoring them back
1226 typedef struct save_arg_t {
1230 smallint sv_g_malloced;
1233 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1237 sv->sv_argv0 = argv[0];
1238 sv->sv_g_argv = G.global_argv;
1239 sv->sv_g_argc = G.global_argc;
1240 sv->sv_g_malloced = G.global_args_malloced;
1242 argv[0] = G.global_argv[0]; /* retain $0 */
1243 G.global_argv = argv;
1244 G.global_args_malloced = 0;
1252 static void restore_G_args(save_arg_t *sv, char **argv)
1256 if (G.global_args_malloced) {
1257 /* someone ran "set -- arg1 arg2 ...", undo */
1259 while (*++pp) /* note: does not free $0 */
1261 free(G.global_argv);
1263 argv[0] = sv->sv_argv0;
1264 G.global_argv = sv->sv_g_argv;
1265 G.global_argc = sv->sv_g_argc;
1266 G.global_args_malloced = sv->sv_g_malloced;
1270 /* Basic theory of signal handling in shell
1271 * ========================================
1272 * This does not describe what hush does, rather, it is current understanding
1273 * what it _should_ do. If it doesn't, it's a bug.
1274 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1276 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1277 * is finished or backgrounded. It is the same in interactive and
1278 * non-interactive shells, and is the same regardless of whether
1279 * a user trap handler is installed or a shell special one is in effect.
1280 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1281 * backgrounds (i.e. stops) or kills all members of currently running
1284 * Wait builtin in interruptible by signals for which user trap is set
1285 * or by SIGINT in interactive shell.
1287 * Trap handlers will execute even within trap handlers. (right?)
1289 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1290 * except for handlers set to '' (empty string).
1292 * If job control is off, backgrounded commands ("cmd &")
1293 * have SIGINT, SIGQUIT set to SIG_IGN.
1295 * Commands which are run in command substitution ("`cmd`")
1296 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1298 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1299 * by the shell from its parent.
1301 * Signals which differ from SIG_DFL action
1302 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1305 * SIGTERM (interactive): ignore
1306 * SIGHUP (interactive):
1307 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1308 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1309 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1310 * that all pipe members are stopped. Try this in bash:
1311 * while :; do :; done - ^Z does not background it
1312 * (while :; do :; done) - ^Z backgrounds it
1313 * SIGINT (interactive): wait for last pipe, ignore the rest
1314 * of the command line, show prompt. NB: ^C does not send SIGINT
1315 * to interactive shell while shell is waiting for a pipe,
1316 * since shell is bg'ed (is not in foreground process group).
1317 * Example 1: this waits 5 sec, but does not execute ls:
1318 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1319 * Example 2: this does not wait and does not execute ls:
1320 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1321 * Example 3: this does not wait 5 sec, but executes ls:
1322 * "sleep 5; ls -l" + press ^C
1324 * (What happens to signals which are IGN on shell start?)
1325 * (What happens with signal mask on shell start?)
1327 * Implementation in hush
1328 * ======================
1329 * We use in-kernel pending signal mask to determine which signals were sent.
1330 * We block all signals which we don't want to take action immediately,
1331 * i.e. we block all signals which need to have special handling as described
1332 * above, and all signals which have traps set.
1333 * After each pipe execution, we extract any pending signals via sigtimedwait()
1336 * unsigned non_DFL_mask: a mask of such "special" signals
1337 * sigset_t blocked_set: current blocked signal set
1340 * clear bit in blocked_set unless it is also in non_DFL_mask
1341 * "trap 'cmd' SIGxxx":
1342 * set bit in blocked_set (even if 'cmd' is '')
1343 * after [v]fork, if we plan to be a shell:
1344 * unblock signals with special interactive handling
1345 * (child shell is not interactive),
1346 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1347 * after [v]fork, if we plan to exec:
1348 * POSIX says fork clears pending signal mask in child - no need to clear it.
1349 * Restore blocked signal set to one inherited by shell just prior to exec.
1351 * Note: as a result, we do not use signal handlers much. The only uses
1352 * are to count SIGCHLDs
1353 * and to restore tty pgrp on signal-induced exit.
1356 * Standard says "When a subshell is entered, traps that are not being ignored
1357 * are set to the default actions". bash interprets it so that traps which
1358 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1361 SPECIAL_INTERACTIVE_SIGS = 0
1366 SPECIAL_JOB_SIGS = 0
1374 #if ENABLE_HUSH_FAST
1375 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1378 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1384 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1385 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1386 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1387 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1389 /* Restores tty foreground process group, and exits.
1390 * May be called as signal handler for fatal signal
1391 * (will resend signal to itself, producing correct exit state)
1392 * or called directly with -EXITCODE.
1393 * We also call it if xfunc is exiting. */
1394 static void sigexit(int sig) NORETURN;
1395 static void sigexit(int sig)
1397 /* Disable all signals: job control, SIGPIPE, etc. */
1398 sigprocmask_allsigs(SIG_BLOCK);
1400 /* Careful: we can end up here after [v]fork. Do not restore
1401 * tty pgrp then, only top-level shell process does that */
1402 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1403 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1405 /* Not a signal, just exit */
1409 kill_myself_with_sig(sig); /* does not return */
1413 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1414 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1418 /* Restores tty foreground process group, and exits. */
1419 static void hush_exit(int exitcode) NORETURN;
1420 static void hush_exit(int exitcode)
1422 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1423 /* Prevent recursion:
1424 * trap "echo Hi; exit" EXIT; exit
1427 /* argv[0] is unused */
1428 argv[1] = G.traps[0];
1430 G.exiting = 1; /* prevent EXIT trap recursion */
1431 /* Note: G.traps[0] is not cleared!
1432 * "trap" will still show it, if executed
1437 #if ENABLE_FEATURE_CLEAN_UP
1439 struct variable *cur_var;
1440 if (G.cwd != bb_msg_unknown)
1442 cur_var = G.top_var;
1444 struct variable *tmp = cur_var;
1445 if (!cur_var->max_len)
1446 free(cur_var->varstr);
1447 cur_var = cur_var->next;
1455 sigexit(- (exitcode & 0xff));
1462 static int check_and_run_traps(int sig)
1464 /* I want it in rodata, not in bss.
1465 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1466 * initializer. But other compilers may still use bss.
1467 * TODO: find more portable solution.
1469 static const struct timespec zero_timespec = { 0, 0 };
1470 smalluint save_rcode;
1476 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1481 if (G.traps && G.traps[sig]) {
1482 if (G.traps[sig][0]) {
1483 /* We have user-defined handler */
1485 /* argv[0] is unused */
1486 argv[1] = G.traps[sig];
1488 save_rcode = G.last_exitcode;
1490 G.last_exitcode = save_rcode;
1491 } /* else: "" trap, ignoring signal */
1494 /* not a trap: special action */
1496 #if ENABLE_HUSH_FAST
1499 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1503 /* Builtin was ^C'ed, make it look prettier: */
1510 /* bash is observed to signal whole process groups,
1511 * not individual processes */
1512 for (job = G.job_list; job; job = job->next) {
1515 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1516 if (kill(- job->pgrp, SIGHUP) == 0)
1517 kill(- job->pgrp, SIGCONT);
1522 default: /* ignored: */
1523 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1531 static const char *get_cwd(int force)
1533 if (force || G.cwd == NULL) {
1534 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1535 * we must not try to free(bb_msg_unknown) */
1536 if (G.cwd == bb_msg_unknown)
1538 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1540 G.cwd = bb_msg_unknown;
1547 * Shell and environment variable support
1549 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1551 struct variable **pp;
1552 struct variable *cur;
1555 while ((cur = *pp) != NULL) {
1556 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1563 static const char* FAST_FUNC get_local_var_value(const char *name)
1565 struct variable **vpp;
1566 unsigned len = strlen(name);
1568 if (G.expanded_assignments) {
1569 char **cpp = G.expanded_assignments;
1572 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1573 return cp + len + 1;
1578 vpp = get_ptr_to_local_var(name, len);
1580 return (*vpp)->varstr + len + 1;
1582 if (strcmp(name, "PPID") == 0)
1583 return utoa(G.root_ppid);
1584 // bash compat: UID? EUID?
1585 #if ENABLE_HUSH_RANDOM_SUPPORT
1586 if (strcmp(name, "RANDOM") == 0)
1587 return utoa(next_random(&G.random_gen));
1592 /* str holds "NAME=VAL" and is expected to be malloced.
1593 * We take ownership of it.
1595 * 0: do not change export flag
1596 * (if creating new variable, flag will be 0)
1597 * 1: set export flag and putenv the variable
1598 * -1: clear export flag and unsetenv the variable
1599 * flg_read_only is set only when we handle -R var=val
1601 #if !BB_MMU && ENABLE_HUSH_LOCAL
1602 /* all params are used */
1603 #elif BB_MMU && ENABLE_HUSH_LOCAL
1604 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1605 set_local_var(str, flg_export, local_lvl)
1606 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1607 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1608 set_local_var(str, flg_export)
1609 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1610 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1611 set_local_var(str, flg_export, flg_read_only)
1613 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1615 struct variable **var_pp;
1616 struct variable *cur;
1620 eq_sign = strchr(str, '=');
1621 if (!eq_sign) { /* not expected to ever happen? */
1626 name_len = eq_sign - str + 1; /* including '=' */
1627 var_pp = &G.top_var;
1628 while ((cur = *var_pp) != NULL) {
1629 if (strncmp(cur->varstr, str, name_len) != 0) {
1630 var_pp = &cur->next;
1633 /* We found an existing var with this name */
1634 if (cur->flg_read_only) {
1638 bb_error_msg("%s: readonly variable", str);
1642 if (flg_export == -1) { // "&& cur->flg_export" ?
1643 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1648 #if ENABLE_HUSH_LOCAL
1649 if (cur->func_nest_level < local_lvl) {
1650 /* New variable is declared as local,
1651 * and existing one is global, or local
1652 * from enclosing function.
1653 * Remove and save old one: */
1654 *var_pp = cur->next;
1655 cur->next = *G.shadowed_vars_pp;
1656 *G.shadowed_vars_pp = cur;
1657 /* bash 3.2.33(1) and exported vars:
1659 * # f() { local z=a; env | grep ^z; }
1665 if (cur->flg_export)
1670 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1675 if (cur->max_len != 0) {
1676 if (cur->max_len >= strlen(str)) {
1677 /* This one is from startup env, reuse space */
1678 strcpy(cur->varstr, str);
1682 /* max_len == 0 signifies "malloced" var, which we can
1683 * (and has to) free */
1687 goto set_str_and_exp;
1690 /* Not found - create new variable struct */
1691 cur = xzalloc(sizeof(*cur));
1692 #if ENABLE_HUSH_LOCAL
1693 cur->func_nest_level = local_lvl;
1695 cur->next = *var_pp;
1701 cur->flg_read_only = flg_read_only;
1704 if (flg_export == 1)
1705 cur->flg_export = 1;
1706 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1707 cmdedit_update_prompt();
1708 if (cur->flg_export) {
1709 if (flg_export == -1) {
1710 cur->flg_export = 0;
1711 /* unsetenv was already done */
1713 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1714 return putenv(cur->varstr);
1720 /* Used at startup and after each cd */
1721 static void set_pwd_var(int exp)
1723 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1724 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1727 static int unset_local_var_len(const char *name, int name_len)
1729 struct variable *cur;
1730 struct variable **var_pp;
1733 return EXIT_SUCCESS;
1734 var_pp = &G.top_var;
1735 while ((cur = *var_pp) != NULL) {
1736 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1737 if (cur->flg_read_only) {
1738 bb_error_msg("%s: readonly variable", name);
1739 return EXIT_FAILURE;
1741 *var_pp = cur->next;
1742 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1743 bb_unsetenv(cur->varstr);
1744 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1745 cmdedit_update_prompt();
1749 return EXIT_SUCCESS;
1751 var_pp = &cur->next;
1753 return EXIT_SUCCESS;
1756 static int unset_local_var(const char *name)
1758 return unset_local_var_len(name, strlen(name));
1761 static void unset_vars(char **strings)
1769 const char *eq = strchrnul(*v, '=');
1770 unset_local_var_len(*v, (int)(eq - *v));
1776 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1778 char *var = xasprintf("%s=%s", name, val);
1779 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1784 * Helpers for "var1=val1 var2=val2 cmd" feature
1786 static void add_vars(struct variable *var)
1788 struct variable *next;
1792 var->next = G.top_var;
1794 if (var->flg_export) {
1795 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1796 putenv(var->varstr);
1798 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1804 static struct variable *set_vars_and_save_old(char **strings)
1807 struct variable *old = NULL;
1813 struct variable *var_p;
1814 struct variable **var_pp;
1817 eq = strchr(*s, '=');
1819 var_pp = get_ptr_to_local_var(*s, eq - *s);
1821 /* Remove variable from global linked list */
1823 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1824 *var_pp = var_p->next;
1825 /* Add it to returned list */
1829 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1840 static int FAST_FUNC static_get(struct in_str *i)
1850 static int FAST_FUNC static_peek(struct in_str *i)
1855 #if ENABLE_HUSH_INTERACTIVE
1857 static void cmdedit_update_prompt(void)
1859 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1860 G.PS1 = get_local_var_value("PS1");
1863 G.PS2 = get_local_var_value("PS2");
1871 static const char *setup_prompt_string(int promptmode)
1873 const char *prompt_str;
1874 debug_printf("setup_prompt_string %d ", promptmode);
1875 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1876 /* Set up the prompt */
1877 if (promptmode == 0) { /* PS1 */
1879 /* bash uses $PWD value, even if it is set by user.
1880 * It uses current dir only if PWD is unset.
1881 * We always use current dir. */
1882 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1887 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1888 debug_printf("result '%s'\n", prompt_str);
1892 static void get_user_input(struct in_str *i)
1895 const char *prompt_str;
1897 prompt_str = setup_prompt_string(i->promptmode);
1898 # if ENABLE_FEATURE_EDITING
1899 /* Enable command line editing only while a command line
1900 * is actually being read */
1903 /* buglet: SIGINT will not make new prompt to appear _at once_,
1904 * only after <Enter>. (^C will work) */
1905 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1906 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1907 check_and_run_traps(0);
1908 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1909 i->eof_flag = (r < 0);
1910 if (i->eof_flag) { /* EOF/error detected */
1911 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1912 G.user_input_buf[1] = '\0';
1917 fputs(prompt_str, stdout);
1919 G.user_input_buf[0] = r = fgetc(i->file);
1920 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1921 //do we need check_and_run_traps(0)? (maybe only if stdin)
1922 } while (G.flag_SIGINT);
1923 i->eof_flag = (r == EOF);
1925 i->p = G.user_input_buf;
1928 #endif /* INTERACTIVE */
1930 /* This is the magic location that prints prompts
1931 * and gets data back from the user */
1932 static int FAST_FUNC file_get(struct in_str *i)
1936 /* If there is data waiting, eat it up */
1937 if (i->p && *i->p) {
1938 #if ENABLE_HUSH_INTERACTIVE
1942 if (i->eof_flag && !*i->p)
1944 /* note: ch is never NUL */
1946 /* need to double check i->file because we might be doing something
1947 * more complicated by now, like sourcing or substituting. */
1948 #if ENABLE_HUSH_INTERACTIVE
1949 if (G_interactive_fd && i->promptme && i->file == stdin) {
1952 } while (!*i->p); /* need non-empty line */
1953 i->promptmode = 1; /* PS2 */
1958 do ch = fgetc(i->file); while (ch == '\0');
1960 debug_printf("file_get: got '%c' %d\n", ch, ch);
1961 #if ENABLE_HUSH_INTERACTIVE
1968 /* All callers guarantee this routine will never
1969 * be used right after a newline, so prompting is not needed.
1971 static int FAST_FUNC file_peek(struct in_str *i)
1974 if (i->p && *i->p) {
1975 if (i->eof_flag && !i->p[1])
1978 /* note: ch is never NUL */
1980 do ch = fgetc(i->file); while (ch == '\0');
1981 i->eof_flag = (ch == EOF);
1982 i->peek_buf[0] = ch;
1983 i->peek_buf[1] = '\0';
1985 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1989 static void setup_file_in_str(struct in_str *i, FILE *f)
1991 i->peek = file_peek;
1993 #if ENABLE_HUSH_INTERACTIVE
1995 i->promptmode = 0; /* PS1 */
2001 static void setup_string_in_str(struct in_str *i, const char *s)
2003 i->peek = static_peek;
2004 i->get = static_get;
2005 #if ENABLE_HUSH_INTERACTIVE
2007 i->promptmode = 0; /* PS1 */
2017 #define B_CHUNK (32 * sizeof(char*))
2019 static void o_reset_to_empty_unquoted(o_string *o)
2022 o->has_quoted_part = 0;
2027 static void o_free(o_string *o)
2030 memset(o, 0, sizeof(*o));
2033 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2038 static void o_grow_by(o_string *o, int len)
2040 if (o->length + len > o->maxlen) {
2041 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2042 o->data = xrealloc(o->data, 1 + o->maxlen);
2046 static void o_addchr(o_string *o, int ch)
2048 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2050 o->data[o->length] = ch;
2052 o->data[o->length] = '\0';
2055 static void o_addblock(o_string *o, const char *str, int len)
2058 memcpy(&o->data[o->length], str, len);
2060 o->data[o->length] = '\0';
2063 static void o_addstr(o_string *o, const char *str)
2065 o_addblock(o, str, strlen(str));
2069 static void nommu_addchr(o_string *o, int ch)
2075 # define nommu_addchr(o, str) ((void)0)
2078 static void o_addstr_with_NUL(o_string *o, const char *str)
2080 o_addblock(o, str, strlen(str) + 1);
2084 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2085 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2086 * Apparently, on unquoted $v bash still does globbing
2087 * ("v='*.txt'; echo $v" prints all .txt files),
2088 * but NOT brace expansion! Thus, there should be TWO independent
2089 * quoting mechanisms on $v expansion side: one protects
2090 * $v from brace expansion, and other additionally protects "$v" against globbing.
2091 * We have only second one.
2094 #if ENABLE_HUSH_BRACE_EXPANSION
2095 # define MAYBE_BRACES "{}"
2097 # define MAYBE_BRACES ""
2100 /* My analysis of quoting semantics tells me that state information
2101 * is associated with a destination, not a source.
2103 static void o_addqchr(o_string *o, int ch)
2106 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2111 o->data[o->length] = '\\';
2114 o->data[o->length] = ch;
2116 o->data[o->length] = '\0';
2119 static void o_addQchr(o_string *o, int ch)
2122 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2123 && strchr("*?[\\" MAYBE_BRACES, ch)
2126 o->data[o->length] = '\\';
2130 o->data[o->length] = ch;
2132 o->data[o->length] = '\0';
2135 static void o_addqblock(o_string *o, const char *str, int len)
2140 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2141 if (ordinary_cnt > len) /* paranoia */
2143 o_addblock(o, str, ordinary_cnt);
2144 if (ordinary_cnt == len)
2146 str += ordinary_cnt;
2147 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2151 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2153 o->data[o->length] = '\\';
2157 o->data[o->length] = ch;
2159 o->data[o->length] = '\0';
2163 static void o_addQblock(o_string *o, const char *str, int len)
2165 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2166 o_addblock(o, str, len);
2169 o_addqblock(o, str, len);
2172 static void o_addQstr(o_string *o, const char *str)
2174 o_addQblock(o, str, strlen(str));
2177 /* A special kind of o_string for $VAR and `cmd` expansion.
2178 * It contains char* list[] at the beginning, which is grown in 16 element
2179 * increments. Actual string data starts at the next multiple of 16 * (char*).
2180 * list[i] contains an INDEX (int!) into this string data.
2181 * It means that if list[] needs to grow, data needs to be moved higher up
2182 * but list[i]'s need not be modified.
2183 * NB: remembering how many list[i]'s you have there is crucial.
2184 * o_finalize_list() operation post-processes this structure - calculates
2185 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2187 #if DEBUG_EXPAND || DEBUG_GLOB
2188 static void debug_print_list(const char *prefix, o_string *o, int n)
2190 char **list = (char**)o->data;
2191 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2195 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2196 prefix, list, n, string_start, o->length, o->maxlen,
2197 !!(o->o_expflags & EXP_FLAG_GLOB),
2199 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2202 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2203 o->data + (int)(uintptr_t)list[i] + string_start,
2204 o->data + (int)(uintptr_t)list[i] + string_start);
2208 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2210 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2214 # define debug_print_list(prefix, o, n) ((void)0)
2217 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2218 * in list[n] so that it points past last stored byte so far.
2219 * It returns n+1. */
2220 static int o_save_ptr_helper(o_string *o, int n)
2222 char **list = (char**)o->data;
2226 if (!o->has_empty_slot) {
2227 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2228 string_len = o->length - string_start;
2229 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2230 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2231 /* list[n] points to string_start, make space for 16 more pointers */
2232 o->maxlen += 0x10 * sizeof(list[0]);
2233 o->data = xrealloc(o->data, o->maxlen + 1);
2234 list = (char**)o->data;
2235 memmove(list + n + 0x10, list + n, string_len);
2236 o->length += 0x10 * sizeof(list[0]);
2238 debug_printf_list("list[%d]=%d string_start=%d\n",
2239 n, string_len, string_start);
2242 /* We have empty slot at list[n], reuse without growth */
2243 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2244 string_len = o->length - string_start;
2245 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2246 n, string_len, string_start);
2247 o->has_empty_slot = 0;
2249 list[n] = (char*)(uintptr_t)string_len;
2253 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2254 static int o_get_last_ptr(o_string *o, int n)
2256 char **list = (char**)o->data;
2257 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2259 return ((int)(uintptr_t)list[n-1]) + string_start;
2262 #if ENABLE_HUSH_BRACE_EXPANSION
2263 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2264 * first, it processes even {a} (no commas), second,
2265 * I didn't manage to make it return strings when they don't match
2266 * existing files. Need to re-implement it.
2270 static int glob_needed(const char *s)
2279 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2285 /* Return pointer to next closing brace or to comma */
2286 static const char *next_brace_sub(const char *cp)
2290 while (*cp != '\0') {
2297 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2303 return *cp != '\0' ? cp : NULL;
2305 /* Recursive brace globber. Note: may garble pattern[]. */
2306 static int glob_brace(char *pattern, o_string *o, int n)
2308 char *new_pattern_buf;
2315 debug_printf_glob("glob_brace('%s')\n", pattern);
2321 if (*begin == '{') {
2322 /* Find the first sub-pattern and at the same time
2323 * find the rest after the closing brace */
2324 next = next_brace_sub(begin);
2326 /* An illegal expression */
2330 /* "{abc}" with no commas - illegal
2331 * brace expr, disregard and skip it */
2337 if (*begin == '\\' && begin[1] != '\0')
2341 debug_printf_glob("begin:%s\n", begin);
2342 debug_printf_glob("next:%s\n", next);
2344 /* Now find the end of the whole brace expression */
2346 while (*rest != '}') {
2347 rest = next_brace_sub(rest);
2349 /* An illegal expression */
2352 debug_printf_glob("rest:%s\n", rest);
2354 rest_len = strlen(++rest) + 1;
2356 /* We are sure the brace expression is well-formed */
2358 /* Allocate working buffer large enough for our work */
2359 new_pattern_buf = xmalloc(strlen(pattern));
2361 /* We have a brace expression. BEGIN points to the opening {,
2362 * NEXT points past the terminator of the first element, and REST
2363 * points past the final }. We will accumulate result names from
2364 * recursive runs for each brace alternative in the buffer using
2369 /* Construct the new glob expression */
2372 mempcpy(new_pattern_buf,
2373 /* We know the prefix for all sub-patterns */
2374 pattern, begin - pattern),
2378 /* Note: glob_brace() may garble new_pattern_buf[].
2379 * That's why we re-copy prefix every time (1st memcpy above).
2381 n = glob_brace(new_pattern_buf, o, n);
2383 /* We saw the last entry */
2387 next = next_brace_sub(next);
2389 free(new_pattern_buf);
2397 memset(&globdata, 0, sizeof(globdata));
2398 gr = glob(pattern, 0, NULL, &globdata);
2399 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2401 if (gr == GLOB_NOMATCH) {
2402 globfree(&globdata);
2403 /* NB: garbles parameter */
2404 unbackslash(pattern);
2405 o_addstr_with_NUL(o, pattern);
2406 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2407 return o_save_ptr_helper(o, n);
2409 if (gr == GLOB_NOSPACE)
2410 bb_error_msg_and_die(bb_msg_memory_exhausted);
2411 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2412 * but we didn't specify it. Paranoia again. */
2413 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2415 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2416 char **argv = globdata.gl_pathv;
2418 o_addstr_with_NUL(o, *argv);
2419 n = o_save_ptr_helper(o, n);
2425 globfree(&globdata);
2429 /* Performs globbing on last list[],
2430 * saving each result as a new list[].
2432 static int perform_glob(o_string *o, int n)
2434 char *pattern, *copy;
2436 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2438 return o_save_ptr_helper(o, n);
2439 pattern = o->data + o_get_last_ptr(o, n);
2440 debug_printf_glob("glob pattern '%s'\n", pattern);
2441 if (!glob_needed(pattern)) {
2442 /* unbackslash last string in o in place, fix length */
2443 o->length = unbackslash(pattern) - o->data;
2444 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2445 return o_save_ptr_helper(o, n);
2448 copy = xstrdup(pattern);
2449 /* "forget" pattern in o */
2450 o->length = pattern - o->data;
2451 n = glob_brace(copy, o, n);
2454 debug_print_list("perform_glob returning", o, n);
2458 #else /* !HUSH_BRACE_EXPANSION */
2461 static int glob_needed(const char *s)
2470 if (*s == '*' || *s == '[' || *s == '?')
2476 /* Performs globbing on last list[],
2477 * saving each result as a new list[].
2479 static int perform_glob(o_string *o, int n)
2485 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2487 return o_save_ptr_helper(o, n);
2488 pattern = o->data + o_get_last_ptr(o, n);
2489 debug_printf_glob("glob pattern '%s'\n", pattern);
2490 if (!glob_needed(pattern)) {
2492 /* unbackslash last string in o in place, fix length */
2493 o->length = unbackslash(pattern) - o->data;
2494 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2495 return o_save_ptr_helper(o, n);
2498 memset(&globdata, 0, sizeof(globdata));
2499 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2500 * If we glob "*.\*" and don't find anything, we need
2501 * to fall back to using literal "*.*", but GLOB_NOCHECK
2502 * will return "*.\*"!
2504 gr = glob(pattern, 0, NULL, &globdata);
2505 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2507 if (gr == GLOB_NOMATCH) {
2508 globfree(&globdata);
2511 if (gr == GLOB_NOSPACE)
2512 bb_error_msg_and_die(bb_msg_memory_exhausted);
2513 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2514 * but we didn't specify it. Paranoia again. */
2515 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2517 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2518 char **argv = globdata.gl_pathv;
2519 /* "forget" pattern in o */
2520 o->length = pattern - o->data;
2522 o_addstr_with_NUL(o, *argv);
2523 n = o_save_ptr_helper(o, n);
2529 globfree(&globdata);
2531 debug_print_list("perform_glob returning", o, n);
2535 #endif /* !HUSH_BRACE_EXPANSION */
2537 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2538 * Otherwise, just finish current list[] and start new */
2539 static int o_save_ptr(o_string *o, int n)
2541 if (o->o_expflags & EXP_FLAG_GLOB) {
2542 /* If o->has_empty_slot, list[n] was already globbed
2543 * (if it was requested back then when it was filled)
2544 * so don't do that again! */
2545 if (!o->has_empty_slot)
2546 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2548 return o_save_ptr_helper(o, n);
2551 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2552 static char **o_finalize_list(o_string *o, int n)
2557 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2559 debug_print_list("finalized", o, n);
2560 debug_printf_expand("finalized n:%d\n", n);
2561 list = (char**)o->data;
2562 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2566 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2571 static void free_pipe_list(struct pipe *pi);
2573 /* Returns pi->next - next pipe in the list */
2574 static struct pipe *free_pipe(struct pipe *pi)
2579 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2580 for (i = 0; i < pi->num_cmds; i++) {
2581 struct command *command;
2582 struct redir_struct *r, *rnext;
2584 command = &pi->cmds[i];
2585 debug_printf_clean(" command %d:\n", i);
2586 if (command->argv) {
2590 for (a = 0, p = command->argv; *p; a++, p++) {
2591 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2594 free_strings(command->argv);
2595 //command->argv = NULL;
2597 /* not "else if": on syntax error, we may have both! */
2598 if (command->group) {
2599 debug_printf_clean(" begin group (cmd_type:%d)\n",
2601 free_pipe_list(command->group);
2602 debug_printf_clean(" end group\n");
2603 //command->group = NULL;
2605 /* else is crucial here.
2606 * If group != NULL, child_func is meaningless */
2607 #if ENABLE_HUSH_FUNCTIONS
2608 else if (command->child_func) {
2609 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2610 command->child_func->parent_cmd = NULL;
2614 free(command->group_as_string);
2615 //command->group_as_string = NULL;
2617 for (r = command->redirects; r; r = rnext) {
2618 debug_printf_clean(" redirect %d%s",
2619 r->rd_fd, redir_table[r->rd_type].descrip);
2620 /* guard against the case >$FOO, where foo is unset or blank */
2621 if (r->rd_filename) {
2622 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2623 free(r->rd_filename);
2624 //r->rd_filename = NULL;
2626 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2630 //command->redirects = NULL;
2632 free(pi->cmds); /* children are an array, they get freed all at once */
2636 //pi->cmdtext = NULL;
2644 static void free_pipe_list(struct pipe *pi)
2648 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2650 debug_printf_clean("pipe followup code %d\n", pi->followup);
2656 /*** Parsing routines ***/
2658 #ifndef debug_print_tree
2659 static void debug_print_tree(struct pipe *pi, int lvl)
2661 static const char *const PIPE[] = {
2667 static const char *RES[] = {
2668 [RES_NONE ] = "NONE" ,
2671 [RES_THEN ] = "THEN" ,
2672 [RES_ELIF ] = "ELIF" ,
2673 [RES_ELSE ] = "ELSE" ,
2676 # if ENABLE_HUSH_LOOPS
2677 [RES_FOR ] = "FOR" ,
2678 [RES_WHILE] = "WHILE",
2679 [RES_UNTIL] = "UNTIL",
2681 [RES_DONE ] = "DONE" ,
2683 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2686 # if ENABLE_HUSH_CASE
2687 [RES_CASE ] = "CASE" ,
2688 [RES_CASE_IN ] = "CASE_IN" ,
2689 [RES_MATCH] = "MATCH",
2690 [RES_CASE_BODY] = "CASE_BODY",
2691 [RES_ESAC ] = "ESAC" ,
2693 [RES_XXXX ] = "XXXX" ,
2694 [RES_SNTX ] = "SNTX" ,
2696 static const char *const CMDTYPE[] = {
2700 # if ENABLE_HUSH_FUNCTIONS
2709 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2710 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2712 while (prn < pi->num_cmds) {
2713 struct command *command = &pi->cmds[prn];
2714 char **argv = command->argv;
2716 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2718 command->assignment_cnt);
2719 if (command->group) {
2720 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2721 CMDTYPE[command->cmd_type],
2724 , " group_as_string:", command->group_as_string
2729 debug_print_tree(command->group, lvl+1);
2733 if (argv) while (*argv) {
2734 fdprintf(2, " '%s'", *argv);
2744 #endif /* debug_print_tree */
2746 static struct pipe *new_pipe(void)
2749 pi = xzalloc(sizeof(struct pipe));
2750 /*pi->followup = 0; - deliberately invalid value */
2751 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2755 /* Command (member of a pipe) is complete, or we start a new pipe
2756 * if ctx->command is NULL.
2757 * No errors possible here.
2759 static int done_command(struct parse_context *ctx)
2761 /* The command is really already in the pipe structure, so
2762 * advance the pipe counter and make a new, null command. */
2763 struct pipe *pi = ctx->pipe;
2764 struct command *command = ctx->command;
2767 if (IS_NULL_CMD(command)) {
2768 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2772 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2773 //debug_print_tree(ctx->list_head, 20);
2775 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2778 /* Only real trickiness here is that the uncommitted
2779 * command structure is not counted in pi->num_cmds. */
2780 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2781 ctx->command = command = &pi->cmds[pi->num_cmds];
2783 memset(command, 0, sizeof(*command));
2784 return pi->num_cmds; /* used only for 0/nonzero check */
2787 static void done_pipe(struct parse_context *ctx, pipe_style type)
2791 debug_printf_parse("done_pipe entered, followup %d\n", type);
2792 /* Close previous command */
2793 not_null = done_command(ctx);
2794 ctx->pipe->followup = type;
2796 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2797 ctx->ctx_inverted = 0;
2798 ctx->pipe->res_word = ctx->ctx_res_w;
2801 /* Without this check, even just <enter> on command line generates
2802 * tree of three NOPs (!). Which is harmless but annoying.
2803 * IOW: it is safe to do it unconditionally. */
2806 || ctx->ctx_res_w == RES_FI
2808 #if ENABLE_HUSH_LOOPS
2809 || ctx->ctx_res_w == RES_DONE
2810 || ctx->ctx_res_w == RES_FOR
2811 || ctx->ctx_res_w == RES_IN
2813 #if ENABLE_HUSH_CASE
2814 || ctx->ctx_res_w == RES_ESAC
2818 debug_printf_parse("done_pipe: adding new pipe: "
2819 "not_null:%d ctx->ctx_res_w:%d\n",
2820 not_null, ctx->ctx_res_w);
2822 ctx->pipe->next = new_p;
2824 /* RES_THEN, RES_DO etc are "sticky" -
2825 * they remain set for pipes inside if/while.
2826 * This is used to control execution.
2827 * RES_FOR and RES_IN are NOT sticky (needed to support
2828 * cases where variable or value happens to match a keyword):
2830 #if ENABLE_HUSH_LOOPS
2831 if (ctx->ctx_res_w == RES_FOR
2832 || ctx->ctx_res_w == RES_IN)
2833 ctx->ctx_res_w = RES_NONE;
2835 #if ENABLE_HUSH_CASE
2836 if (ctx->ctx_res_w == RES_MATCH)
2837 ctx->ctx_res_w = RES_CASE_BODY;
2838 if (ctx->ctx_res_w == RES_CASE)
2839 ctx->ctx_res_w = RES_CASE_IN;
2841 ctx->command = NULL; /* trick done_command below */
2842 /* Create the memory for command, roughly:
2843 * ctx->pipe->cmds = new struct command;
2844 * ctx->command = &ctx->pipe->cmds[0];
2847 //debug_print_tree(ctx->list_head, 10);
2849 debug_printf_parse("done_pipe return\n");
2852 static void initialize_context(struct parse_context *ctx)
2854 memset(ctx, 0, sizeof(*ctx));
2855 ctx->pipe = ctx->list_head = new_pipe();
2856 /* Create the memory for command, roughly:
2857 * ctx->pipe->cmds = new struct command;
2858 * ctx->command = &ctx->pipe->cmds[0];
2863 /* If a reserved word is found and processed, parse context is modified
2864 * and 1 is returned.
2867 struct reserved_combo {
2870 unsigned char assignment_flag;
2874 FLAG_END = (1 << RES_NONE ),
2876 FLAG_IF = (1 << RES_IF ),
2877 FLAG_THEN = (1 << RES_THEN ),
2878 FLAG_ELIF = (1 << RES_ELIF ),
2879 FLAG_ELSE = (1 << RES_ELSE ),
2880 FLAG_FI = (1 << RES_FI ),
2882 # if ENABLE_HUSH_LOOPS
2883 FLAG_FOR = (1 << RES_FOR ),
2884 FLAG_WHILE = (1 << RES_WHILE),
2885 FLAG_UNTIL = (1 << RES_UNTIL),
2886 FLAG_DO = (1 << RES_DO ),
2887 FLAG_DONE = (1 << RES_DONE ),
2888 FLAG_IN = (1 << RES_IN ),
2890 # if ENABLE_HUSH_CASE
2891 FLAG_MATCH = (1 << RES_MATCH),
2892 FLAG_ESAC = (1 << RES_ESAC ),
2894 FLAG_START = (1 << RES_XXXX ),
2897 static const struct reserved_combo* match_reserved_word(o_string *word)
2899 /* Mostly a list of accepted follow-up reserved words.
2900 * FLAG_END means we are done with the sequence, and are ready
2901 * to turn the compound list into a command.
2902 * FLAG_START means the word must start a new compound list.
2904 static const struct reserved_combo reserved_list[] = {
2906 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2907 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2908 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2909 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2910 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2911 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2913 # if ENABLE_HUSH_LOOPS
2914 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2915 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2916 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2917 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2918 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2919 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2921 # if ENABLE_HUSH_CASE
2922 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2923 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2926 const struct reserved_combo *r;
2928 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2929 if (strcmp(word->data, r->literal) == 0)
2934 /* Return 0: not a keyword, 1: keyword
2936 static int reserved_word(o_string *word, struct parse_context *ctx)
2938 # if ENABLE_HUSH_CASE
2939 static const struct reserved_combo reserved_match = {
2940 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2943 const struct reserved_combo *r;
2945 if (word->has_quoted_part)
2947 r = match_reserved_word(word);
2951 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2952 # if ENABLE_HUSH_CASE
2953 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2954 /* "case word IN ..." - IN part starts first MATCH part */
2955 r = &reserved_match;
2958 if (r->flag == 0) { /* '!' */
2959 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2960 syntax_error("! ! command");
2961 ctx->ctx_res_w = RES_SNTX;
2963 ctx->ctx_inverted = 1;
2966 if (r->flag & FLAG_START) {
2967 struct parse_context *old;
2969 old = xmalloc(sizeof(*old));
2970 debug_printf_parse("push stack %p\n", old);
2971 *old = *ctx; /* physical copy */
2972 initialize_context(ctx);
2974 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2975 syntax_error_at(word->data);
2976 ctx->ctx_res_w = RES_SNTX;
2979 /* "{...} fi" is ok. "{...} if" is not
2981 * if { echo foo; } then { echo bar; } fi */
2982 if (ctx->command->group)
2983 done_pipe(ctx, PIPE_SEQ);
2986 ctx->ctx_res_w = r->res;
2987 ctx->old_flag = r->flag;
2988 word->o_assignment = r->assignment_flag;
2990 if (ctx->old_flag & FLAG_END) {
2991 struct parse_context *old;
2993 done_pipe(ctx, PIPE_SEQ);
2994 debug_printf_parse("pop stack %p\n", ctx->stack);
2996 old->command->group = ctx->list_head;
2997 old->command->cmd_type = CMD_NORMAL;
2999 o_addstr(&old->as_string, ctx->as_string.data);
3000 o_free_unsafe(&ctx->as_string);
3001 old->command->group_as_string = xstrdup(old->as_string.data);
3002 debug_printf_parse("pop, remembering as:'%s'\n",
3003 old->command->group_as_string);
3005 *ctx = *old; /* physical copy */
3010 #endif /* HAS_KEYWORDS */
3012 /* Word is complete, look at it and update parsing context.
3013 * Normal return is 0. Syntax errors return 1.
3014 * Note: on return, word is reset, but not o_free'd!
3016 static int done_word(o_string *word, struct parse_context *ctx)
3018 struct command *command = ctx->command;
3020 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3021 if (word->length == 0 && !word->has_quoted_part) {
3022 debug_printf_parse("done_word return 0: true null, ignored\n");
3026 if (ctx->pending_redirect) {
3027 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3028 * only if run as "bash", not "sh" */
3029 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3031 * ...the word that follows the redirection operator
3032 * shall be subjected to tilde expansion, parameter expansion,
3033 * command substitution, arithmetic expansion, and quote
3034 * removal. Pathname expansion shall not be performed
3035 * on the word by a non-interactive shell; an interactive
3036 * shell may perform it, but shall do so only when
3037 * the expansion would result in one word."
3039 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3040 /* Cater for >\file case:
3041 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3042 * Same with heredocs:
3043 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3045 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3046 unbackslash(ctx->pending_redirect->rd_filename);
3047 /* Is it <<"HEREDOC"? */
3048 if (word->has_quoted_part) {
3049 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3052 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3053 ctx->pending_redirect = NULL;
3055 /* If this word wasn't an assignment, next ones definitely
3056 * can't be assignments. Even if they look like ones. */
3057 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3058 && word->o_assignment != WORD_IS_KEYWORD
3060 word->o_assignment = NOT_ASSIGNMENT;
3062 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3063 command->assignment_cnt++;
3064 word->o_assignment = MAYBE_ASSIGNMENT;
3068 # if ENABLE_HUSH_CASE
3069 if (ctx->ctx_dsemicolon
3070 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3072 /* already done when ctx_dsemicolon was set to 1: */
3073 /* ctx->ctx_res_w = RES_MATCH; */
3074 ctx->ctx_dsemicolon = 0;
3077 if (!command->argv /* if it's the first word... */
3078 # if ENABLE_HUSH_LOOPS
3079 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3080 && ctx->ctx_res_w != RES_IN
3082 # if ENABLE_HUSH_CASE
3083 && ctx->ctx_res_w != RES_CASE
3086 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3087 if (reserved_word(word, ctx)) {
3088 o_reset_to_empty_unquoted(word);
3089 debug_printf_parse("done_word return %d\n",
3090 (ctx->ctx_res_w == RES_SNTX));
3091 return (ctx->ctx_res_w == RES_SNTX);
3093 # if ENABLE_HUSH_BASH_COMPAT
3094 if (strcmp(word->data, "[[") == 0) {
3095 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3101 if (command->group) {
3102 /* "{ echo foo; } echo bar" - bad */
3103 syntax_error_at(word->data);
3104 debug_printf_parse("done_word return 1: syntax error, "
3105 "groups and arglists don't mix\n");
3108 if (word->has_quoted_part
3109 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3110 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3111 /* (otherwise it's known to be not empty and is already safe) */
3113 /* exclude "$@" - it can expand to no word despite "" */
3114 char *p = word->data;
3115 while (p[0] == SPECIAL_VAR_SYMBOL
3116 && (p[1] & 0x7f) == '@'
3117 && p[2] == SPECIAL_VAR_SYMBOL
3121 if (p == word->data || p[0] != '\0') {
3122 /* saw no "$@", or not only "$@" but some
3123 * real text is there too */
3124 /* insert "empty variable" reference, this makes
3125 * e.g. "", $empty"" etc to not disappear */
3126 o_addchr(word, SPECIAL_VAR_SYMBOL);
3127 o_addchr(word, SPECIAL_VAR_SYMBOL);
3130 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3131 debug_print_strings("word appended to argv", command->argv);
3134 #if ENABLE_HUSH_LOOPS
3135 if (ctx->ctx_res_w == RES_FOR) {
3136 if (word->has_quoted_part
3137 || !is_well_formed_var_name(command->argv[0], '\0')
3139 /* bash says just "not a valid identifier" */
3140 syntax_error("not a valid identifier in for");
3143 /* Force FOR to have just one word (variable name) */
3144 /* NB: basically, this makes hush see "for v in ..."
3145 * syntax as if it is "for v; in ...". FOR and IN become
3146 * two pipe structs in parse tree. */
3147 done_pipe(ctx, PIPE_SEQ);
3150 #if ENABLE_HUSH_CASE
3151 /* Force CASE to have just one word */
3152 if (ctx->ctx_res_w == RES_CASE) {
3153 done_pipe(ctx, PIPE_SEQ);
3157 o_reset_to_empty_unquoted(word);
3159 debug_printf_parse("done_word return 0\n");
3164 /* Peek ahead in the input to find out if we have a "&n" construct,
3165 * as in "2>&1", that represents duplicating a file descriptor.
3167 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3168 * REDIRFD_SYNTAX_ERR if syntax error,
3169 * REDIRFD_TO_FILE if no & was seen,
3170 * or the number found.
3173 #define parse_redir_right_fd(as_string, input) \
3174 parse_redir_right_fd(input)
3176 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3182 return REDIRFD_TO_FILE;
3184 ch = i_getch(input); /* get the & */
3185 nommu_addchr(as_string, ch);
3188 ch = i_getch(input);
3189 nommu_addchr(as_string, ch);
3190 return REDIRFD_CLOSE;
3194 while (ch != EOF && isdigit(ch)) {
3195 d = d*10 + (ch-'0');
3197 ch = i_getch(input);
3198 nommu_addchr(as_string, ch);
3203 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3205 bb_error_msg("ambiguous redirect");
3206 return REDIRFD_SYNTAX_ERR;
3209 /* Return code is 0 normal, 1 if a syntax error is detected
3211 static int parse_redirect(struct parse_context *ctx,
3214 struct in_str *input)
3216 struct command *command = ctx->command;
3217 struct redir_struct *redir;
3218 struct redir_struct **redirp;
3221 dup_num = REDIRFD_TO_FILE;
3222 if (style != REDIRECT_HEREDOC) {
3223 /* Check for a '>&1' type redirect */
3224 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3225 if (dup_num == REDIRFD_SYNTAX_ERR)
3228 int ch = i_peek(input);
3229 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3230 if (dup_num) { /* <<-... */
3231 ch = i_getch(input);
3232 nommu_addchr(&ctx->as_string, ch);
3237 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3238 int ch = i_peek(input);
3240 /* >|FILE redirect ("clobbering" >).
3241 * Since we do not support "set -o noclobber" yet,
3242 * >| and > are the same for now. Just eat |.
3244 ch = i_getch(input);
3245 nommu_addchr(&ctx->as_string, ch);
3249 /* Create a new redir_struct and append it to the linked list */
3250 redirp = &command->redirects;
3251 while ((redir = *redirp) != NULL) {
3252 redirp = &(redir->next);
3254 *redirp = redir = xzalloc(sizeof(*redir));
3255 /* redir->next = NULL; */
3256 /* redir->rd_filename = NULL; */
3257 redir->rd_type = style;
3258 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3260 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3261 redir_table[style].descrip);
3263 redir->rd_dup = dup_num;
3264 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3265 /* Erik had a check here that the file descriptor in question
3266 * is legit; I postpone that to "run time"
3267 * A "-" representation of "close me" shows up as a -3 here */
3268 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3269 redir->rd_fd, redir->rd_dup);
3271 /* Set ctx->pending_redirect, so we know what to do at the
3272 * end of the next parsed word. */
3273 ctx->pending_redirect = redir;
3278 /* If a redirect is immediately preceded by a number, that number is
3279 * supposed to tell which file descriptor to redirect. This routine
3280 * looks for such preceding numbers. In an ideal world this routine
3281 * needs to handle all the following classes of redirects...
3282 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3283 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3284 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3285 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3287 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3289 * ... If n is quoted, the number shall not be recognized as part of
3290 * the redirection expression. For example:
3292 * writes the character 2 into file a"
3293 * We are getting it right by setting ->has_quoted_part on any \<char>
3295 * A -1 return means no valid number was found,
3296 * the caller should use the appropriate default for this redirection.
3298 static int redirect_opt_num(o_string *o)
3302 if (o->data == NULL)
3304 num = bb_strtou(o->data, NULL, 10);
3305 if (errno || num < 0)
3307 o_reset_to_empty_unquoted(o);
3312 #define fetch_till_str(as_string, input, word, skip_tabs) \
3313 fetch_till_str(input, word, skip_tabs)
3315 static char *fetch_till_str(o_string *as_string,
3316 struct in_str *input,
3320 o_string heredoc = NULL_O_STRING;
3322 int prev = 0; /* not \ */
3327 ch = i_getch(input);
3329 nommu_addchr(as_string, ch);
3330 if ((ch == '\n' || ch == EOF)
3331 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3333 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3334 heredoc.data[past_EOL] = '\0';
3335 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3336 return heredoc.data;
3338 while (ch == '\n') {
3339 o_addchr(&heredoc, ch);
3342 past_EOL = heredoc.length;
3344 ch = i_getch(input);
3346 nommu_addchr(as_string, ch);
3347 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3351 o_free_unsafe(&heredoc);
3354 o_addchr(&heredoc, ch);
3355 nommu_addchr(as_string, ch);
3356 if (prev == '\\' && ch == '\\')
3357 /* Correctly handle foo\\<eol> (not a line cont.) */
3358 prev = 0; /* not \ */
3364 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3365 * and load them all. There should be exactly heredoc_cnt of them.
3367 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3369 struct pipe *pi = ctx->list_head;
3371 while (pi && heredoc_cnt) {
3373 struct command *cmd = pi->cmds;
3375 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3377 cmd->argv ? cmd->argv[0] : "NONE");
3378 for (i = 0; i < pi->num_cmds; i++) {
3379 struct redir_struct *redir = cmd->redirects;
3381 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3382 i, cmd->argv ? cmd->argv[0] : "NONE");
3384 if (redir->rd_type == REDIRECT_HEREDOC) {
3387 redir->rd_type = REDIRECT_HEREDOC2;
3388 /* redir->rd_dup is (ab)used to indicate <<- */
3389 p = fetch_till_str(&ctx->as_string, input,
3390 redir->rd_filename, redir->rd_dup);
3392 syntax_error("unexpected EOF in here document");
3395 free(redir->rd_filename);
3396 redir->rd_filename = p;
3399 redir = redir->next;
3406 /* Should be 0. If it isn't, it's a parse error */
3408 bb_error_msg_and_die("heredoc BUG 2");
3414 static int run_list(struct pipe *pi);
3416 #define parse_stream(pstring, input, end_trigger) \
3417 parse_stream(input, end_trigger)
3419 static struct pipe *parse_stream(char **pstring,
3420 struct in_str *input,
3424 #if !ENABLE_HUSH_FUNCTIONS
3425 #define parse_group(dest, ctx, input, ch) \
3426 parse_group(ctx, input, ch)
3428 static int parse_group(o_string *dest, struct parse_context *ctx,
3429 struct in_str *input, int ch)
3431 /* dest contains characters seen prior to ( or {.
3432 * Typically it's empty, but for function defs,
3433 * it contains function name (without '()'). */
3434 struct pipe *pipe_list;
3436 struct command *command = ctx->command;
3438 debug_printf_parse("parse_group entered\n");
3439 #if ENABLE_HUSH_FUNCTIONS
3440 if (ch == '(' && !dest->has_quoted_part) {
3442 if (done_word(dest, ctx))
3445 goto skip; /* (... */
3446 if (command->argv[1]) { /* word word ... (... */
3447 syntax_error_unexpected_ch('(');
3450 /* it is "word(..." or "word (..." */
3452 ch = i_getch(input);
3453 while (ch == ' ' || ch == '\t');
3455 syntax_error_unexpected_ch(ch);
3458 nommu_addchr(&ctx->as_string, ch);
3460 ch = i_getch(input);
3461 while (ch == ' ' || ch == '\t' || ch == '\n');
3463 syntax_error_unexpected_ch(ch);
3466 nommu_addchr(&ctx->as_string, ch);
3467 command->cmd_type = CMD_FUNCDEF;
3472 #if 0 /* Prevented by caller */
3473 if (command->argv /* word [word]{... */
3474 || dest->length /* word{... */
3475 || dest->has_quoted_part /* ""{... */
3478 debug_printf_parse("parse_group return 1: "
3479 "syntax error, groups and arglists don't mix\n");
3484 #if ENABLE_HUSH_FUNCTIONS
3490 command->cmd_type = CMD_SUBSHELL;
3492 /* bash does not allow "{echo...", requires whitespace */
3493 ch = i_getch(input);
3494 if (ch != ' ' && ch != '\t' && ch != '\n') {
3495 syntax_error_unexpected_ch(ch);
3498 nommu_addchr(&ctx->as_string, ch);
3503 # define as_string NULL
3505 char *as_string = NULL;
3507 pipe_list = parse_stream(&as_string, input, endch);
3510 o_addstr(&ctx->as_string, as_string);
3512 /* empty ()/{} or parse error? */
3513 if (!pipe_list || pipe_list == ERR_PTR) {
3514 /* parse_stream already emitted error msg */
3517 debug_printf_parse("parse_group return 1: "
3518 "parse_stream returned %p\n", pipe_list);
3521 command->group = pipe_list;
3523 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3524 command->group_as_string = as_string;
3525 debug_printf_parse("end of group, remembering as:'%s'\n",
3526 command->group_as_string);
3530 debug_printf_parse("parse_group return 0\n");
3532 /* command remains "open", available for possible redirects */
3535 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3536 /* Subroutines for copying $(...) and `...` things */
3537 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3539 static void add_till_single_quote(o_string *dest, struct in_str *input)
3542 int ch = i_getch(input);
3544 syntax_error_unterm_ch('\'');
3545 /*xfunc_die(); - redundant */
3552 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3553 static void add_till_double_quote(o_string *dest, struct in_str *input)
3556 int ch = i_getch(input);
3558 syntax_error_unterm_ch('"');
3559 /*xfunc_die(); - redundant */
3563 if (ch == '\\') { /* \x. Copy both chars. */
3565 ch = i_getch(input);
3569 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3573 //if (ch == '$') ...
3576 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3578 * "Within the backquoted style of command substitution, backslash
3579 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3580 * The search for the matching backquote shall be satisfied by the first
3581 * backquote found without a preceding backslash; during this search,
3582 * if a non-escaped backquote is encountered within a shell comment,
3583 * a here-document, an embedded command substitution of the $(command)
3584 * form, or a quoted string, undefined results occur. A single-quoted
3585 * or double-quoted string that begins, but does not end, within the
3586 * "`...`" sequence produces undefined results."
3588 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3590 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3593 int ch = i_getch(input);
3597 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3598 ch = i_getch(input);
3602 && (!in_dquote || ch != '"')
3604 o_addchr(dest, '\\');
3608 syntax_error_unterm_ch('`');
3609 /*xfunc_die(); - redundant */
3614 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3615 * quoting and nested ()s.
3616 * "With the $(command) style of command substitution, all characters
3617 * following the open parenthesis to the matching closing parenthesis
3618 * constitute the command. Any valid shell script can be used for command,
3619 * except a script consisting solely of redirections which produces
3620 * unspecified results."
3622 * echo $(echo '(TEST)' BEST) (TEST) BEST
3623 * echo $(echo 'TEST)' BEST) TEST) BEST
3624 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3626 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3627 * can contain arbitrary constructs, just like $(cmd).
3628 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3629 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3631 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3632 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3635 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3636 # if ENABLE_HUSH_BASH_COMPAT
3637 char end_char2 = end_ch >> 8;
3639 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3642 ch = i_getch(input);
3644 syntax_error_unterm_ch(end_ch);
3645 /*xfunc_die(); - redundant */
3647 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3650 /* we look for closing )) of $((EXPR)) */
3651 if (i_peek(input) == end_ch) {
3652 i_getch(input); /* eat second ')' */
3657 if (ch == '(' || ch == '{') {
3658 ch = (ch == '(' ? ')' : '}');
3659 add_till_closing_bracket(dest, input, ch);
3664 add_till_single_quote(dest, input);
3669 add_till_double_quote(dest, input);
3674 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3679 /* \x. Copy verbatim. Important for \(, \) */
3680 ch = i_getch(input);
3682 syntax_error_unterm_ch(')');
3683 /*xfunc_die(); - redundant */
3691 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3693 /* Return code: 0 for OK, 1 for syntax error */
3695 #define parse_dollar(as_string, dest, input, quote_mask) \
3696 parse_dollar(dest, input, quote_mask)
3697 #define as_string NULL
3699 static int parse_dollar(o_string *as_string,
3701 struct in_str *input, unsigned char quote_mask)
3703 int ch = i_peek(input); /* first character after the $ */
3705 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3707 ch = i_getch(input);
3708 nommu_addchr(as_string, ch);
3710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3712 debug_printf_parse(": '%c'\n", ch);
3713 o_addchr(dest, ch | quote_mask);
3716 if (!isalnum(ch) && ch != '_')
3718 ch = i_getch(input);
3719 nommu_addchr(as_string, ch);
3721 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3722 } else if (isdigit(ch)) {
3724 ch = i_getch(input);
3725 nommu_addchr(as_string, ch);
3726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3727 debug_printf_parse(": '%c'\n", ch);
3728 o_addchr(dest, ch | quote_mask);
3729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3730 } else switch (ch) {
3732 case '!': /* last bg pid */
3733 case '?': /* last exit code */
3734 case '#': /* number of args */
3735 case '*': /* args */
3736 case '@': /* args */
3737 goto make_one_char_var;
3739 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3741 ch = i_getch(input); /* eat '{' */
3742 nommu_addchr(as_string, ch);
3744 ch = i_getch(input); /* first char after '{' */
3745 /* It should be ${?}, or ${#var},
3746 * or even ${?+subst} - operator acting on a special variable,
3747 * or the beginning of variable name.
3750 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3753 syntax_error_unterm_str("${name}");
3754 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3757 nommu_addchr(as_string, ch);
3760 /* It's possible to just call add_till_closing_bracket() at this point.
3761 * However, this regresses some of our testsuite cases
3762 * which check invalid constructs like ${%}.
3763 * Oh well... let's check that the var name part is fine... */
3769 debug_printf_parse(": '%c'\n", ch);
3771 ch = i_getch(input);
3772 nommu_addchr(as_string, ch);
3776 if (!isalnum(ch) && ch != '_') {
3778 unsigned char last_ch;
3779 /* handle parameter expansions
3780 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3782 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3783 goto bad_dollar_syntax;
3785 /* Eat everything until closing '}' (or ':') */
3787 if (ENABLE_HUSH_BASH_COMPAT
3789 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3791 /* It's ${var:N[:M]} thing */
3792 end_ch = '}' * 0x100 + ':';
3794 if (ENABLE_HUSH_BASH_COMPAT
3797 /* It's ${var/[/]pattern[/repl]} thing */
3798 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3800 nommu_addchr(as_string, '/');
3803 end_ch = '}' * 0x100 + '/';
3809 #if ENABLE_HUSH_DOLLAR_OPS
3810 last_ch = add_till_closing_bracket(dest, input, end_ch);
3812 #error Simple code to only allow ${var} is not implemented
3815 o_addstr(as_string, dest->data + pos);
3816 o_addchr(as_string, last_ch);
3819 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3820 /* close the first block: */
3821 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3822 /* while parsing N from ${var:N[:M]}
3823 * or pattern from ${var/[/]pattern[/repl]} */
3824 if ((end_ch & 0xff) == last_ch) {
3825 /* got ':' or '/'- parse the rest */
3830 if (end_ch == '}' * 0x100 + ':') {
3831 /* it's ${var:N} - emulate :999999999 */
3832 o_addstr(dest, "999999999");
3833 } /* else: it's ${var/[/]pattern} */
3838 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3841 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3845 ch = i_getch(input);
3846 nommu_addchr(as_string, ch);
3847 # if ENABLE_SH_MATH_SUPPORT
3848 if (i_peek(input) == '(') {
3849 ch = i_getch(input);
3850 nommu_addchr(as_string, ch);
3851 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3852 o_addchr(dest, /*quote_mask |*/ '+');
3855 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3857 o_addstr(as_string, dest->data + pos);
3858 o_addchr(as_string, ')');
3859 o_addchr(as_string, ')');
3861 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3865 # if ENABLE_HUSH_TICK
3866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3867 o_addchr(dest, quote_mask | '`');
3870 add_till_closing_bracket(dest, input, ')');
3872 o_addstr(as_string, dest->data + pos);
3873 o_addchr(as_string, ')');
3875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3881 ch = i_getch(input);
3882 nommu_addchr(as_string, ch);
3884 if (isalnum(ch)) { /* it's $_name or $_123 */
3889 /* TODO: $_ and $-: */
3890 /* $_ Shell or shell script name; or last argument of last command
3891 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3892 * but in command's env, set to full pathname used to invoke it */
3893 /* $- Option flags set by set builtin or shell options (-i etc) */
3895 o_addQchr(dest, '$');
3897 debug_printf_parse("parse_dollar return 0\n");
3903 # if ENABLE_HUSH_BASH_COMPAT
3904 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3905 encode_string(dest, input, dquote_end, process_bkslash)
3907 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3908 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3909 encode_string(dest, input, dquote_end)
3911 #define as_string NULL
3915 # if ENABLE_HUSH_BASH_COMPAT
3916 /* all parameters are needed, no macro tricks */
3918 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3919 encode_string(as_string, dest, input, dquote_end)
3922 static int encode_string(o_string *as_string,
3924 struct in_str *input,
3926 int process_bkslash)
3928 #if !ENABLE_HUSH_BASH_COMPAT
3929 const int process_bkslash = 1;
3935 ch = i_getch(input);
3937 nommu_addchr(as_string, ch);
3938 if (ch == dquote_end) { /* may be only '"' or EOF */
3939 debug_printf_parse("encode_string return 0\n");
3942 /* note: can't move it above ch == dquote_end check! */
3944 syntax_error_unterm_ch('"');
3945 /*xfunc_die(); - redundant */
3949 next = i_peek(input);
3951 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3952 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3953 if (process_bkslash && ch == '\\') {
3955 syntax_error("\\<eof>");
3959 * "The backslash retains its special meaning [in "..."]
3960 * only when followed by one of the following characters:
3961 * $, `, ", \, or <newline>. A double quote may be quoted
3962 * within double quotes by preceding it with a backslash."
3963 * NB: in (unquoted) heredoc, above does not apply to ",
3964 * therefore we check for it by "next == dquote_end" cond.
3966 if (next == dquote_end || strchr("$`\\\n", next)) {
3967 ch = i_getch(input); /* eat next */
3969 goto again; /* skip \<newline> */
3970 } /* else: ch remains == '\\', and we double it below: */
3971 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3972 nommu_addchr(as_string, ch);
3976 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3977 debug_printf_parse("encode_string return 1: "
3978 "parse_dollar returned non-0\n");
3983 #if ENABLE_HUSH_TICK
3985 //unsigned pos = dest->length;
3986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3987 o_addchr(dest, 0x80 | '`');
3988 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3990 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3994 o_addQchr(dest, ch);
4000 * Scan input until EOF or end_trigger char.
4001 * Return a list of pipes to execute, or NULL on EOF
4002 * or if end_trigger character is met.
4003 * On syntax error, exit is shell is not interactive,
4004 * reset parsing machinery and start parsing anew,
4005 * or return ERR_PTR.
4007 static struct pipe *parse_stream(char **pstring,
4008 struct in_str *input,
4011 struct parse_context ctx;
4012 o_string dest = NULL_O_STRING;
4015 /* Single-quote triggers a bypass of the main loop until its mate is
4016 * found. When recursing, quote state is passed in via dest->o_expflags.
4018 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4019 end_trigger ? end_trigger : 'X');
4022 /* If very first arg is "" or '', dest.data may end up NULL.
4023 * Preventing this: */
4024 o_addchr(&dest, '\0');
4027 /* We used to separate words on $IFS here. This was wrong.
4028 * $IFS is used only for word splitting when $var is expanded,
4029 * here we should use blank chars as separators, not $IFS
4032 reset: /* we come back here only on syntax errors in interactive shell */
4034 #if ENABLE_HUSH_INTERACTIVE
4035 input->promptmode = 0; /* PS1 */
4037 if (MAYBE_ASSIGNMENT != 0)
4038 dest.o_assignment = MAYBE_ASSIGNMENT;
4039 initialize_context(&ctx);
4042 const char *is_blank;
4043 const char *is_special;
4047 redir_type redir_style;
4049 ch = i_getch(input);
4050 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4051 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4056 syntax_error_unterm_str("here document");
4059 /* end_trigger == '}' case errors out earlier,
4060 * checking only ')' */
4061 if (end_trigger == ')') {
4062 syntax_error_unterm_ch('('); /* exits */
4063 /* goto parse_error; */
4066 if (done_word(&dest, &ctx)) {
4070 done_pipe(&ctx, PIPE_SEQ);
4072 /* If we got nothing... */
4073 /* (this makes bare "&" cmd a no-op.
4074 * bash says: "syntax error near unexpected token '&'") */
4075 if (pi->num_cmds == 0
4076 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4082 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4084 *pstring = ctx.as_string.data;
4086 o_free_unsafe(&ctx.as_string);
4089 debug_printf_parse("parse_stream return %p\n", pi);
4092 nommu_addchr(&ctx.as_string, ch);
4096 next = i_peek(input);
4098 is_special = "{}<>;&|()#'" /* special outside of "str" */
4099 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4100 /* Are { and } special here? */
4101 if (ctx.command->argv /* word [word]{... - non-special */
4102 || dest.length /* word{... - non-special */
4103 || dest.has_quoted_part /* ""{... - non-special */
4104 || (next != ';' /* }; - special */
4105 && next != ')' /* }) - special */
4106 && next != '&' /* }& and }&& ... - special */
4107 && next != '|' /* }|| ... - special */
4108 && !strchr(defifs, next) /* {word - non-special */
4111 /* They are not special, skip "{}" */
4114 is_special = strchr(is_special, ch);
4115 is_blank = strchr(defifs, ch);
4117 if (!is_special && !is_blank) { /* ordinary char */
4119 o_addQchr(&dest, ch);
4120 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4121 || dest.o_assignment == WORD_IS_KEYWORD)
4123 && is_well_formed_var_name(dest.data, '=')
4125 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4131 if (done_word(&dest, &ctx)) {
4135 /* Is this a case when newline is simply ignored?
4137 * "cmd | <newline> cmd ..."
4138 * "case ... in <newline> word) ..."
4140 if (IS_NULL_CMD(ctx.command)
4141 && dest.length == 0 && !dest.has_quoted_part
4145 /* Treat newline as a command separator. */
4146 done_pipe(&ctx, PIPE_SEQ);
4147 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4149 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4154 dest.o_assignment = MAYBE_ASSIGNMENT;
4156 /* note: if (is_blank) continue;
4157 * will still trigger for us */
4161 /* "cmd}" or "cmd }..." without semicolon or &:
4162 * } is an ordinary char in this case, even inside { cmd; }
4163 * Pathological example: { ""}; } should exec "}" cmd
4166 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4167 || dest.length != 0 /* word} */
4168 || dest.has_quoted_part /* ""} */
4172 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4173 goto skip_end_trigger;
4174 /* else: } does terminate a group */
4177 if (end_trigger && end_trigger == ch
4178 && (ch != ';' || heredoc_cnt == 0)
4179 #if ENABLE_HUSH_CASE
4181 || ctx.ctx_res_w != RES_MATCH
4182 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4187 /* This is technically valid:
4188 * { cat <<HERE; }; echo Ok
4192 * but we don't support this.
4193 * We require heredoc to be in enclosing {}/(),
4196 syntax_error_unterm_str("here document");
4199 if (done_word(&dest, &ctx)) {
4202 done_pipe(&ctx, PIPE_SEQ);
4203 dest.o_assignment = MAYBE_ASSIGNMENT;
4204 /* Do we sit outside of any if's, loops or case's? */
4206 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4210 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4212 *pstring = ctx.as_string.data;
4214 o_free_unsafe(&ctx.as_string);
4217 debug_printf_parse("parse_stream return %p: "
4218 "end_trigger char found\n",
4220 return ctx.list_head;
4227 /* Catch <, > before deciding whether this word is
4228 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4231 redir_fd = redirect_opt_num(&dest);
4232 if (done_word(&dest, &ctx)) {
4235 redir_style = REDIRECT_OVERWRITE;
4237 redir_style = REDIRECT_APPEND;
4238 ch = i_getch(input);
4239 nommu_addchr(&ctx.as_string, ch);
4242 else if (next == '(') {
4243 syntax_error(">(process) not supported");
4247 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4249 continue; /* back to top of while (1) */
4251 redir_fd = redirect_opt_num(&dest);
4252 if (done_word(&dest, &ctx)) {
4255 redir_style = REDIRECT_INPUT;
4257 redir_style = REDIRECT_HEREDOC;
4259 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4262 } else if (next == '>') {
4263 redir_style = REDIRECT_IO;
4264 ch = i_getch(input);
4265 nommu_addchr(&ctx.as_string, ch);
4268 else if (next == '(') {
4269 syntax_error("<(process) not supported");
4273 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4275 continue; /* back to top of while (1) */
4277 if (dest.length == 0 && !dest.has_quoted_part) {
4278 /* skip "#comment" */
4281 if (ch == EOF || ch == '\n')
4284 /* note: we do not add it to &ctx.as_string */
4286 nommu_addchr(&ctx.as_string, '\n');
4287 continue; /* back to top of while (1) */
4292 /* It's "\<newline>" */
4294 /* Remove trailing '\' from ctx.as_string */
4295 ctx.as_string.data[--ctx.as_string.length] = '\0';
4297 ch = i_getch(input); /* eat it */
4298 continue; /* back to top of while (1) */
4303 if (dest.o_assignment == MAYBE_ASSIGNMENT
4304 /* check that we are not in word in "a=1 2>word b=1": */
4305 && !ctx.pending_redirect
4307 /* ch is a special char and thus this word
4308 * cannot be an assignment */
4309 dest.o_assignment = NOT_ASSIGNMENT;
4312 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4315 case '#': /* non-comment #: "echo a#b" etc */
4316 o_addQchr(&dest, ch);
4320 syntax_error("\\<eof>");
4323 ch = i_getch(input);
4324 /* note: ch != '\n' (that case does not reach this place) */
4325 o_addchr(&dest, '\\');
4326 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4327 o_addchr(&dest, ch);
4328 nommu_addchr(&ctx.as_string, ch);
4329 /* Example: echo Hello \2>file
4330 * we need to know that word 2 is quoted */
4331 dest.has_quoted_part = 1;
4334 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4335 debug_printf_parse("parse_stream parse error: "
4336 "parse_dollar returned non-0\n");
4341 dest.has_quoted_part = 1;
4343 ch = i_getch(input);
4345 syntax_error_unterm_ch('\'');
4346 /*xfunc_die(); - redundant */
4348 nommu_addchr(&ctx.as_string, ch);
4351 o_addqchr(&dest, ch);
4355 dest.has_quoted_part = 1;
4356 if (dest.o_assignment == NOT_ASSIGNMENT)
4357 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4358 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4360 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4362 #if ENABLE_HUSH_TICK
4366 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4367 o_addchr(&dest, '`');
4369 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4371 o_addstr(&ctx.as_string, dest.data + pos);
4372 o_addchr(&ctx.as_string, '`');
4374 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4375 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4380 #if ENABLE_HUSH_CASE
4383 if (done_word(&dest, &ctx)) {
4386 done_pipe(&ctx, PIPE_SEQ);
4387 #if ENABLE_HUSH_CASE
4388 /* Eat multiple semicolons, detect
4389 * whether it means something special */
4394 ch = i_getch(input);
4395 nommu_addchr(&ctx.as_string, ch);
4396 if (ctx.ctx_res_w == RES_CASE_BODY) {
4397 ctx.ctx_dsemicolon = 1;
4398 ctx.ctx_res_w = RES_MATCH;
4404 /* We just finished a cmd. New one may start
4405 * with an assignment */
4406 dest.o_assignment = MAYBE_ASSIGNMENT;
4409 if (done_word(&dest, &ctx)) {
4413 ch = i_getch(input);
4414 nommu_addchr(&ctx.as_string, ch);
4415 done_pipe(&ctx, PIPE_AND);
4417 done_pipe(&ctx, PIPE_BG);
4421 if (done_word(&dest, &ctx)) {
4424 #if ENABLE_HUSH_CASE
4425 if (ctx.ctx_res_w == RES_MATCH)
4426 break; /* we are in case's "word | word)" */
4428 if (next == '|') { /* || */
4429 ch = i_getch(input);
4430 nommu_addchr(&ctx.as_string, ch);
4431 done_pipe(&ctx, PIPE_OR);
4433 /* we could pick up a file descriptor choice here
4434 * with redirect_opt_num(), but bash doesn't do it.
4435 * "echo foo 2| cat" yields "foo 2". */
4438 o_reset_to_empty_unquoted(&ctx.as_string);
4443 #if ENABLE_HUSH_CASE
4444 /* "case... in [(]word)..." - skip '(' */
4445 if (ctx.ctx_res_w == RES_MATCH
4446 && ctx.command->argv == NULL /* not (word|(... */
4447 && dest.length == 0 /* not word(... */
4448 && dest.has_quoted_part == 0 /* not ""(... */
4454 if (parse_group(&dest, &ctx, input, ch) != 0) {
4459 #if ENABLE_HUSH_CASE
4460 if (ctx.ctx_res_w == RES_MATCH)
4464 /* proper use of this character is caught by end_trigger:
4465 * if we see {, we call parse_group(..., end_trigger='}')
4466 * and it will match } earlier (not here). */
4467 syntax_error_unexpected_ch(ch);
4471 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4477 struct parse_context *pctx;
4478 IF_HAS_KEYWORDS(struct parse_context *p2;)
4480 /* Clean up allocated tree.
4481 * Sample for finding leaks on syntax error recovery path.
4482 * Run it from interactive shell, watch pmap `pidof hush`.
4483 * while if false; then false; fi; do break; fi
4484 * Samples to catch leaks at execution:
4485 * while if (true | {true;}); then echo ok; fi; do break; done
4486 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4490 /* Update pipe/command counts,
4491 * otherwise freeing may miss some */
4492 done_pipe(pctx, PIPE_SEQ);
4493 debug_printf_clean("freeing list %p from ctx %p\n",
4494 pctx->list_head, pctx);
4495 debug_print_tree(pctx->list_head, 0);
4496 free_pipe_list(pctx->list_head);
4497 debug_printf_clean("freed list %p\n", pctx->list_head);
4499 o_free_unsafe(&pctx->as_string);
4501 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4505 IF_HAS_KEYWORDS(pctx = p2;)
4506 } while (HAS_KEYWORDS && pctx);
4507 /* Free text, clear all dest fields */
4509 /* If we are not in top-level parse, we return,
4510 * our caller will propagate error.
4512 if (end_trigger != ';') {
4520 /* Discard cached input, force prompt */
4522 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4528 /*** Execution routines ***/
4530 /* Expansion can recurse, need forward decls: */
4531 #if !ENABLE_HUSH_BASH_COMPAT
4532 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4533 #define expand_string_to_string(str, do_unbackslash) \
4534 expand_string_to_string(str)
4536 static char *expand_string_to_string(const char *str, int do_unbackslash);
4537 #if ENABLE_HUSH_TICK
4538 static int process_command_subs(o_string *dest, const char *s);
4541 /* expand_strvec_to_strvec() takes a list of strings, expands
4542 * all variable references within and returns a pointer to
4543 * a list of expanded strings, possibly with larger number
4544 * of strings. (Think VAR="a b"; echo $VAR).
4545 * This new list is allocated as a single malloc block.
4546 * NULL-terminated list of char* pointers is at the beginning of it,
4547 * followed by strings themselves.
4548 * Caller can deallocate entire list by single free(list). */
4550 /* A horde of its helpers come first: */
4552 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4554 while (--len >= 0) {
4557 #if ENABLE_HUSH_BRACE_EXPANSION
4558 if (c == '{' || c == '}') {
4559 /* { -> \{, } -> \} */
4561 /* And now we want to add { or } and continue:
4564 * luckily, just falling throught achieves this.
4570 /* \z -> \\\z; \<eol> -> \\<eol> */
4575 o_addchr(o, *str++);
4581 /* Store given string, finalizing the word and starting new one whenever
4582 * we encounter IFS char(s). This is used for expanding variable values.
4583 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4584 static int expand_on_ifs(o_string *output, int n, const char *str)
4587 int word_len = strcspn(str, G.ifs);
4589 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4590 o_addblock(output, str, word_len);
4592 /* Protect backslashes against globbing up :)
4593 * Example: "v='\*'; echo b$v" prints "b\*"
4594 * (and does not try to glob on "*")
4596 o_addblock_duplicate_backslash(output, str, word_len);
4597 /*/ Why can't we do it easier? */
4598 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4599 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4603 if (!*str) /* EOL - do not finalize word */
4605 o_addchr(output, '\0');
4606 debug_print_list("expand_on_ifs", output, n);
4607 n = o_save_ptr(output, n);
4608 str += strspn(str, G.ifs); /* skip ifs chars */
4610 debug_print_list("expand_on_ifs[1]", output, n);
4614 /* Helper to expand $((...)) and heredoc body. These act as if
4615 * they are in double quotes, with the exception that they are not :).
4616 * Just the rules are similar: "expand only $var and `cmd`"
4618 * Returns malloced string.
4619 * As an optimization, we return NULL if expansion is not needed.
4621 #if !ENABLE_HUSH_BASH_COMPAT
4622 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4623 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4624 encode_then_expand_string(str)
4626 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4629 struct in_str input;
4630 o_string dest = NULL_O_STRING;
4632 if (!strchr(str, '$')
4633 && !strchr(str, '\\')
4634 #if ENABLE_HUSH_TICK
4635 && !strchr(str, '`')
4641 /* We need to expand. Example:
4642 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4644 setup_string_in_str(&input, str);
4645 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4646 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4647 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4648 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4649 o_free_unsafe(&dest);
4653 #if ENABLE_SH_MATH_SUPPORT
4654 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4656 arith_state_t math_state;
4660 math_state.lookupvar = get_local_var_value;
4661 math_state.setvar = set_local_var_from_halves;
4662 //math_state.endofname = endofname;
4663 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4664 res = arith(&math_state, exp_str ? exp_str : arg);
4667 *errmsg_p = math_state.errmsg;
4668 if (math_state.errmsg)
4669 die_if_script(math_state.errmsg);
4674 #if ENABLE_HUSH_BASH_COMPAT
4675 /* ${var/[/]pattern[/repl]} helpers */
4676 static char *strstr_pattern(char *val, const char *pattern, int *size)
4679 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4680 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4687 /* Optimization: if "*pat" did not match the start of "string",
4688 * we know that "tring", "ring" etc will not match too:
4690 if (pattern[0] == '*')
4695 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4697 char *result = NULL;
4698 unsigned res_len = 0;
4699 unsigned repl_len = strlen(repl);
4703 char *s = strstr_pattern(val, pattern, &size);
4707 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4708 memcpy(result + res_len, val, s - val);
4710 strcpy(result + res_len, repl);
4711 res_len += repl_len;
4712 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4718 if (val[0] && result) {
4719 result = xrealloc(result, res_len + strlen(val) + 1);
4720 strcpy(result + res_len, val);
4721 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4723 debug_printf_varexp("result:'%s'\n", result);
4729 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4731 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4733 const char *val = NULL;
4734 char *to_be_freed = NULL;
4739 char exp_save = exp_save; /* for compiler */
4740 char *exp_saveptr; /* points to expansion operator */
4741 char *exp_word = exp_word; /* for compiler */
4744 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4746 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4748 first_char = arg[0] = arg0 & 0x7f;
4751 if (first_char == '#' /* ${#... */
4752 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4754 /* It must be length operator: ${#var} */
4758 /* Maybe handle parameter expansion */
4759 if (exp_saveptr /* if 2nd char is one of expansion operators */
4760 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4762 /* ${?:0}, ${#[:]%0} etc */
4763 exp_saveptr = var + 1;
4765 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4766 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4768 exp_op = exp_save = *exp_saveptr;
4770 exp_word = exp_saveptr + 1;
4771 if (exp_op == ':') {
4772 exp_op = *exp_word++;
4773 //TODO: try ${var:} and ${var:bogus} in non-bash config
4774 if (ENABLE_HUSH_BASH_COMPAT
4775 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4777 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4782 *exp_saveptr = '\0';
4783 } /* else: it's not an expansion op, but bare ${var} */
4786 /* Look up the variable in question */
4787 if (isdigit(var[0])) {
4788 /* parse_dollar should have vetted var for us */
4789 int n = xatoi_positive(var);
4790 if (n < G.global_argc)
4791 val = G.global_argv[n];
4792 /* else val remains NULL: $N with too big N */
4796 val = utoa(G.root_pid);
4798 case '!': /* bg pid */
4799 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4801 case '?': /* exitcode */
4802 val = utoa(G.last_exitcode);
4804 case '#': /* argc */
4805 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4808 val = get_local_var_value(var);
4812 /* Handle any expansions */
4813 if (exp_op == 'L') {
4814 debug_printf_expand("expand: length(%s)=", val);
4815 val = utoa(val ? strlen(val) : 0);
4816 debug_printf_expand("%s\n", val);
4817 } else if (exp_op) {
4818 if (exp_op == '%' || exp_op == '#') {
4819 /* Standard-mandated substring removal ops:
4820 * ${parameter%word} - remove smallest suffix pattern
4821 * ${parameter%%word} - remove largest suffix pattern
4822 * ${parameter#word} - remove smallest prefix pattern
4823 * ${parameter##word} - remove largest prefix pattern
4825 * Word is expanded to produce a glob pattern.
4826 * Then var's value is matched to it and matching part removed.
4828 if (val && val[0]) {
4832 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4833 if (exp_op == *exp_word) /* ## or %% */
4835 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4837 exp_word = exp_exp_word;
4838 /* HACK ALERT. We depend here on the fact that
4839 * G.global_argv and results of utoa and get_local_var_value
4840 * are actually in writable memory:
4841 * scan_and_match momentarily stores NULs there. */
4843 loc = scan_and_match(t, exp_word, scan_flags);
4844 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4845 // exp_op, t, exp_word, loc);
4847 if (loc) { /* match was found */
4848 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4849 val = loc; /* take right part */
4851 val = to_be_freed = xstrndup(val, loc - val); /* left */
4855 #if ENABLE_HUSH_BASH_COMPAT
4856 else if (exp_op == '/' || exp_op == '\\') {
4857 /* It's ${var/[/]pattern[/repl]} thing.
4858 * Note that in encoded form it has TWO parts:
4859 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4860 * and if // is used, it is encoded as \:
4861 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4863 /* Empty variable always gives nothing: */
4864 // "v=''; echo ${v/*/w}" prints "", not "w"
4865 if (val && val[0]) {
4866 /* pattern uses non-standard expansion.
4867 * repl should be unbackslashed and globbed
4868 * by the usual expansion rules:
4870 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4871 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4872 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4873 * v='a bz'; echo ${v/a*z/\z} prints "z"
4874 * (note that a*z _pattern_ is never globbed!)
4876 char *pattern, *repl, *t;
4877 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4879 pattern = xstrdup(exp_word);
4880 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4881 *p++ = SPECIAL_VAR_SYMBOL;
4883 p = strchr(p, SPECIAL_VAR_SYMBOL);
4885 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4886 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4887 /* HACK ALERT. We depend here on the fact that
4888 * G.global_argv and results of utoa and get_local_var_value
4889 * are actually in writable memory:
4890 * replace_pattern momentarily stores NULs there. */
4892 to_be_freed = replace_pattern(t,
4894 (repl ? repl : exp_word),
4896 if (to_be_freed) /* at least one replace happened */
4903 else if (exp_op == ':') {
4904 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4905 /* It's ${var:N[:M]} bashism.
4906 * Note that in encoded form it has TWO parts:
4907 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4912 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4915 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4916 *p++ = SPECIAL_VAR_SYMBOL;
4918 p = strchr(p, SPECIAL_VAR_SYMBOL);
4920 len = expand_and_evaluate_arith(exp_word, &errmsg);
4923 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4924 if (len >= 0) { /* bash compat: len < 0 is illegal */
4925 if (beg < 0) /* bash compat */
4927 debug_printf_varexp("from val:'%s'\n", val);
4928 if (len == 0 || !val || beg >= strlen(val)) {
4932 /* Paranoia. What if user entered 9999999999999
4933 * which fits in arith_t but not int? */
4936 val = to_be_freed = xstrndup(val + beg, len);
4938 debug_printf_varexp("val:'%s'\n", val);
4942 die_if_script("malformed ${%s:...}", var);
4945 } else { /* one of "-=+?" */
4946 /* Standard-mandated substitution ops:
4947 * ${var?word} - indicate error if unset
4948 * If var is unset, word (or a message indicating it is unset
4949 * if word is null) is written to standard error
4950 * and the shell exits with a non-zero exit status.
4951 * Otherwise, the value of var is substituted.
4952 * ${var-word} - use default value
4953 * If var is unset, word is substituted.
4954 * ${var=word} - assign and use default value
4955 * If var is unset, word is assigned to var.
4956 * In all cases, final value of var is substituted.
4957 * ${var+word} - use alternative value
4958 * If var is unset, null is substituted.
4959 * Otherwise, word is substituted.
4961 * Word is subjected to tilde expansion, parameter expansion,
4962 * command substitution, and arithmetic expansion.
4963 * If word is not needed, it is not expanded.
4965 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4966 * but also treat null var as if it is unset.
4968 int use_word = (!val || ((exp_save == ':') && !val[0]));
4970 use_word = !use_word;
4971 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4972 (exp_save == ':') ? "true" : "false", use_word);
4974 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4976 exp_word = to_be_freed;
4977 if (exp_op == '?') {
4978 /* mimic bash message */
4979 die_if_script("%s: %s",
4981 exp_word[0] ? exp_word : "parameter null or not set"
4983 //TODO: how interactive bash aborts expansion mid-command?
4988 if (exp_op == '=') {
4989 /* ${var=[word]} or ${var:=[word]} */
4990 if (isdigit(var[0]) || var[0] == '#') {
4991 /* mimic bash message */
4992 die_if_script("$%s: cannot assign in this way", var);
4995 char *new_var = xasprintf("%s=%s", var, val);
4996 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5000 } /* one of "-=+?" */
5002 *exp_saveptr = exp_save;
5008 *to_be_freed_pp = to_be_freed;
5012 /* Expand all variable references in given string, adding words to list[]
5013 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5014 * to be filled). This routine is extremely tricky: has to deal with
5015 * variables/parameters with whitespace, $* and $@, and constructs like
5016 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5017 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5019 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5020 * expansion of right-hand side of assignment == 1-element expand.
5022 char cant_be_null = 0; /* only bit 0x80 matters */
5025 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5026 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5027 debug_print_list("expand_vars_to_list", output, n);
5028 n = o_save_ptr(output, n);
5029 debug_print_list("expand_vars_to_list[0]", output, n);
5031 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5033 char *to_be_freed = NULL;
5034 const char *val = NULL;
5035 #if ENABLE_HUSH_TICK
5036 o_string subst_result = NULL_O_STRING;
5038 #if ENABLE_SH_MATH_SUPPORT
5039 char arith_buf[sizeof(arith_t)*3 + 2];
5041 o_addblock(output, arg, p - arg);
5042 debug_print_list("expand_vars_to_list[1]", output, n);
5044 p = strchr(p, SPECIAL_VAR_SYMBOL);
5046 /* Fetch special var name (if it is indeed one of them)
5047 * and quote bit, force the bit on if singleword expansion -
5048 * important for not getting v=$@ expand to many words. */
5049 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5051 /* Is this variable quoted and thus expansion can't be null?
5052 * "$@" is special. Even if quoted, it can still
5053 * expand to nothing (not even an empty string),
5054 * thus it is excluded. */
5055 if ((first_ch & 0x7f) != '@')
5056 cant_be_null |= first_ch;
5058 switch (first_ch & 0x7f) {
5059 /* Highest bit in first_ch indicates that var is double-quoted */
5063 if (!G.global_argv[1])
5066 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5067 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5068 while (G.global_argv[i]) {
5069 n = expand_on_ifs(output, n, G.global_argv[i]);
5070 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5071 if (G.global_argv[i++][0] && G.global_argv[i]) {
5072 /* this argv[] is not empty and not last:
5073 * put terminating NUL, start new word */
5074 o_addchr(output, '\0');
5075 debug_print_list("expand_vars_to_list[2]", output, n);
5076 n = o_save_ptr(output, n);
5077 debug_print_list("expand_vars_to_list[3]", output, n);
5081 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5082 * and in this case should treat it like '$*' - see 'else...' below */
5083 if (first_ch == ('@'|0x80) /* quoted $@ */
5084 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5087 o_addQstr(output, G.global_argv[i]);
5088 if (++i >= G.global_argc)
5090 o_addchr(output, '\0');
5091 debug_print_list("expand_vars_to_list[4]", output, n);
5092 n = o_save_ptr(output, n);
5094 } else { /* quoted $* (or v="$@" case): add as one word */
5096 o_addQstr(output, G.global_argv[i]);
5097 if (!G.global_argv[++i])
5100 o_addchr(output, G.ifs[0]);
5105 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5106 /* "Empty variable", used to make "" etc to not disappear */
5108 cant_be_null = 0x80;
5110 #if ENABLE_HUSH_TICK
5111 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5112 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5114 /* Can't just stuff it into output o_string,
5115 * expanded result may need to be globbed
5116 * and $IFS-splitted */
5117 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5118 G.last_exitcode = process_command_subs(&subst_result, arg);
5119 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5120 val = subst_result.data;
5123 #if ENABLE_SH_MATH_SUPPORT
5124 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5127 arg++; /* skip '+' */
5128 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5129 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5130 res = expand_and_evaluate_arith(arg, NULL);
5131 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5132 sprintf(arith_buf, ARITH_FMT, res);
5138 val = expand_one_var(&to_be_freed, arg, &p);
5139 IF_HUSH_TICK(store_val:)
5140 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5141 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5142 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5143 if (val && val[0]) {
5144 n = expand_on_ifs(output, n, val);
5147 } else { /* quoted $VAR, val will be appended below */
5148 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5149 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5153 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5155 if (val && val[0]) {
5156 o_addQstr(output, val);
5160 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5161 * Do the check to avoid writing to a const string. */
5162 if (*p != SPECIAL_VAR_SYMBOL)
5163 *p = SPECIAL_VAR_SYMBOL;
5165 #if ENABLE_HUSH_TICK
5166 o_free(&subst_result);
5169 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5172 debug_print_list("expand_vars_to_list[a]", output, n);
5173 /* this part is literal, and it was already pre-quoted
5174 * if needed (much earlier), do not use o_addQstr here! */
5175 o_addstr_with_NUL(output, arg);
5176 debug_print_list("expand_vars_to_list[b]", output, n);
5177 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5178 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5181 /* allow to reuse list[n] later without re-growth */
5182 output->has_empty_slot = 1;
5184 o_addchr(output, '\0');
5190 static char **expand_variables(char **argv, unsigned expflags)
5194 o_string output = NULL_O_STRING;
5196 output.o_expflags = expflags;
5200 n = expand_vars_to_list(&output, n, *argv);
5203 debug_print_list("expand_variables", &output, n);
5205 /* output.data (malloced in one block) gets returned in "list" */
5206 list = o_finalize_list(&output, n);
5207 debug_print_strings("expand_variables[1]", list);
5211 static char **expand_strvec_to_strvec(char **argv)
5213 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5216 #if ENABLE_HUSH_BASH_COMPAT
5217 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5219 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5223 /* Used for expansion of right hand of assignments,
5224 * $((...)), heredocs, variable espansion parts.
5226 * NB: should NOT do globbing!
5227 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5229 static char *expand_string_to_string(const char *str, int do_unbackslash)
5231 #if !ENABLE_HUSH_BASH_COMPAT
5232 const int do_unbackslash = 1;
5234 char *argv[2], **list;
5236 debug_printf_expand("string_to_string<='%s'\n", str);
5237 /* This is generally an optimization, but it also
5238 * handles "", which otherwise trips over !list[0] check below.
5239 * (is this ever happens that we actually get str="" here?)
5241 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5242 //TODO: Can use on strings with \ too, just unbackslash() them?
5243 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5244 return xstrdup(str);
5247 argv[0] = (char*)str;
5249 list = expand_variables(argv, do_unbackslash
5250 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5251 : EXP_FLAG_SINGLEWORD
5254 if (!list[0] || list[1])
5255 bb_error_msg_and_die("BUG in varexp2");
5256 /* actually, just move string 2*sizeof(char*) bytes back */
5257 overlapping_strcpy((char*)list, list[0]);
5259 unbackslash((char*)list);
5260 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5264 /* Used for "eval" builtin */
5265 static char* expand_strvec_to_string(char **argv)
5269 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5270 /* Convert all NULs to spaces */
5275 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5276 bb_error_msg_and_die("BUG in varexp3");
5277 /* bash uses ' ' regardless of $IFS contents */
5282 overlapping_strcpy((char*)list, list[0]);
5283 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5287 static char **expand_assignments(char **argv, int count)
5292 G.expanded_assignments = p = NULL;
5293 /* Expand assignments into one string each */
5294 for (i = 0; i < count; i++) {
5295 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5297 G.expanded_assignments = NULL;
5304 void re_execute_shell(char ***to_free, const char *s,
5305 char *g_argv0, char **g_argv,
5306 char **builtin_argv) NORETURN;
5308 static void reset_traps_to_defaults(void)
5310 /* This function is always called in a child shell
5311 * after fork (not vfork, NOMMU doesn't use this function).
5316 /* Child shells are not interactive.
5317 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5318 * Testcase: (while :; do :; done) + ^Z should background.
5319 * Same goes for SIGTERM, SIGHUP, SIGINT.
5321 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5322 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5324 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5325 * Stupid. It can be done with *single* &= op, but we can't use
5326 * the fact that G.blocked_set is implemented as a bitmask
5328 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5332 /* Careful. Only if no trap or trap is not "" */
5333 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5334 sigdelset(&G.blocked_set, sig);
5341 /* Our homegrown sig mask is saner to work with :) */
5342 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5344 /* Resetting all traps to default except empty ones */
5345 mask = G.non_DFL_mask;
5346 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5347 if (!G.traps[sig] || !G.traps[sig][0])
5350 G.traps[sig] = NULL;
5351 /* There is no signal for 0 (EXIT) */
5354 /* There was a trap handler, we just removed it.
5355 * But if sig still has non-DFL handling,
5356 * we should not unblock the sig. */
5359 sigdelset(&G.blocked_set, sig);
5361 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5366 static void re_execute_shell(char ***to_free, const char *s,
5367 char *g_argv0, char **g_argv,
5368 char **builtin_argv) NORETURN;
5369 static void re_execute_shell(char ***to_free, const char *s,
5370 char *g_argv0, char **g_argv,
5371 char **builtin_argv)
5373 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5374 /* delims + 2 * (number of bytes in printed hex numbers) */
5375 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5376 char *heredoc_argv[4];
5377 struct variable *cur;
5378 # if ENABLE_HUSH_FUNCTIONS
5379 struct function *funcp;
5383 unsigned long long empty_trap_mask;
5385 if (!g_argv0) { /* heredoc */
5386 argv = heredoc_argv;
5387 argv[0] = (char *) G.argv0_for_re_execing;
5388 argv[1] = (char *) "-<";
5389 argv[2] = (char *) s;
5391 pp = &argv[3]; /* used as pointer to empty environment */
5397 if (pp) while (*pp++)
5400 empty_trap_mask = 0;
5403 for (sig = 1; sig < NSIG; sig++) {
5404 if (G.traps[sig] && !G.traps[sig][0])
5405 empty_trap_mask |= 1LL << sig;
5409 sprintf(param_buf, NOMMU_HACK_FMT
5410 , (unsigned) G.root_pid
5411 , (unsigned) G.root_ppid
5412 , (unsigned) G.last_bg_pid
5413 , (unsigned) G.last_exitcode
5416 IF_HUSH_LOOPS(, G.depth_of_loop)
5418 # undef NOMMU_HACK_FMT
5419 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5420 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5423 for (cur = G.top_var; cur; cur = cur->next) {
5424 if (!cur->flg_export || cur->flg_read_only)
5427 # if ENABLE_HUSH_FUNCTIONS
5428 for (funcp = G.top_func; funcp; funcp = funcp->next)
5434 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5435 *pp++ = (char *) G.argv0_for_re_execing;
5437 for (cur = G.top_var; cur; cur = cur->next) {
5438 if (strcmp(cur->varstr, hush_version_str) == 0)
5440 if (cur->flg_read_only) {
5441 *pp++ = (char *) "-R";
5442 *pp++ = cur->varstr;
5443 } else if (!cur->flg_export) {
5444 *pp++ = (char *) "-V";
5445 *pp++ = cur->varstr;
5448 # if ENABLE_HUSH_FUNCTIONS
5449 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5450 *pp++ = (char *) "-F";
5451 *pp++ = funcp->name;
5452 *pp++ = funcp->body_as_string;
5455 /* We can pass activated traps here. Say, -Tnn:trap_string
5457 * However, POSIX says that subshells reset signals with traps
5459 * I tested bash-3.2 and it not only does that with true subshells
5460 * of the form ( list ), but with any forked children shells.
5461 * I set trap "echo W" WINCH; and then tried:
5463 * { echo 1; sleep 20; echo 2; } &
5464 * while true; do echo 1; sleep 20; echo 2; break; done &
5465 * true | { echo 1; sleep 20; echo 2; } | cat
5467 * In all these cases sending SIGWINCH to the child shell
5468 * did not run the trap. If I add trap "echo V" WINCH;
5469 * _inside_ group (just before echo 1), it works.
5471 * I conclude it means we don't need to pass active traps here.
5472 * Even if we would use signal handlers instead of signal masking
5473 * in order to implement trap handling,
5474 * exec syscall below resets signals to SIG_DFL for us.
5476 *pp++ = (char *) "-c";
5479 while (*++builtin_argv)
5480 *pp++ = *builtin_argv;
5481 *pp++ = (char *) "";
5486 /* *pp = NULL; - is already there */
5490 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5491 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5492 execve(bb_busybox_exec_path, argv, pp);
5493 /* Fallback. Useful for init=/bin/hush usage etc */
5494 if (argv[0][0] == '/')
5495 execve(argv[0], argv, pp);
5496 xfunc_error_retval = 127;
5497 bb_error_msg_and_die("can't re-execute the shell");
5499 #endif /* !BB_MMU */
5502 static int run_and_free_list(struct pipe *pi);
5504 /* Executing from string: eval, sh -c '...'
5505 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5506 * end_trigger controls how often we stop parsing
5507 * NUL: parse all, execute, return
5508 * ';': parse till ';' or newline, execute, repeat till EOF
5510 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5512 /* Why we need empty flag?
5513 * An obscure corner case "false; ``; echo $?":
5514 * empty command in `` should still set $? to 0.
5515 * But we can't just set $? to 0 at the start,
5516 * this breaks "false; echo `echo $?`" case.
5520 struct pipe *pipe_list;
5522 pipe_list = parse_stream(NULL, inp, end_trigger);
5523 if (!pipe_list) { /* EOF */
5525 G.last_exitcode = 0;
5528 debug_print_tree(pipe_list, 0);
5529 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5530 run_and_free_list(pipe_list);
5535 static void parse_and_run_string(const char *s)
5537 struct in_str input;
5538 setup_string_in_str(&input, s);
5539 parse_and_run_stream(&input, '\0');
5542 static void parse_and_run_file(FILE *f)
5544 struct in_str input;
5545 setup_file_in_str(&input, f);
5546 parse_and_run_stream(&input, ';');
5549 #if ENABLE_HUSH_TICK
5550 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5555 char **to_free = NULL;
5559 pid = BB_MMU ? xfork() : xvfork();
5560 if (pid == 0) { /* child */
5561 disable_restore_tty_pgrp_on_exit();
5562 /* Process substitution is not considered to be usual
5563 * 'command execution'.
5564 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5571 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5572 close(channel[0]); /* NB: close _first_, then move fd! */
5573 xmove_fd(channel[1], 1);
5574 /* Prevent it from trying to handle ctrl-z etc */
5575 IF_HUSH_JOB(G.run_list_level = 1;)
5576 /* Awful hack for `trap` or $(trap).
5578 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5579 * contains an example where "trap" is executed in a subshell:
5581 * save_traps=$(trap)
5583 * eval "$save_traps"
5585 * Standard does not say that "trap" in subshell shall print
5586 * parent shell's traps. It only says that its output
5587 * must have suitable form, but then, in the above example
5588 * (which is not supposed to be normative), it implies that.
5590 * bash (and probably other shell) does implement it
5591 * (traps are reset to defaults, but "trap" still shows them),
5592 * but as a result, "trap" logic is hopelessly messed up:
5595 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5596 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5597 * # true | trap <--- trap is in subshell - no output (ditto)
5598 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5599 * trap -- 'echo Ho' SIGWINCH
5600 * # echo `(trap)` <--- in subshell in subshell - output
5601 * trap -- 'echo Ho' SIGWINCH
5602 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5603 * trap -- 'echo Ho' SIGWINCH
5605 * The rules when to forget and when to not forget traps
5606 * get really complex and nonsensical.
5608 * Our solution: ONLY bare $(trap) or `trap` is special.
5610 s = skip_whitespace(s);
5611 if (strncmp(s, "trap", 4) == 0
5612 && skip_whitespace(s + 4)[0] == '\0'
5614 static const char *const argv[] = { NULL, NULL };
5615 builtin_trap((char**)argv);
5616 exit(0); /* not _exit() - we need to fflush */
5619 reset_traps_to_defaults();
5620 parse_and_run_string(s);
5621 _exit(G.last_exitcode);
5623 /* We re-execute after vfork on NOMMU. This makes this script safe:
5624 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5625 * huge=`cat BIG` # was blocking here forever
5628 re_execute_shell(&to_free,
5638 # if ENABLE_HUSH_FAST
5640 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5641 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5642 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5644 enable_restore_tty_pgrp_on_exit();
5649 close_on_exec_on(channel[0]);
5650 return xfdopen_for_read(channel[0]);
5653 /* Return code is exit status of the process that is run. */
5654 static int process_command_subs(o_string *dest, const char *s)
5657 struct in_str pipe_str;
5659 int status, ch, eol_cnt;
5661 fp = generate_stream_from_string(s, &pid);
5663 /* Now send results of command back into original context */
5664 setup_file_in_str(&pipe_str, fp);
5666 while ((ch = i_getch(&pipe_str)) != EOF) {
5672 o_addchr(dest, '\n');
5675 o_addQchr(dest, ch);
5678 debug_printf("done reading from `cmd` pipe, closing it\n");
5680 /* We need to extract exitcode. Test case
5681 * "true; echo `sleep 1; false` $?"
5683 safe_waitpid(pid, &status, 0);
5684 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5685 return WEXITSTATUS(status);
5687 #endif /* ENABLE_HUSH_TICK */
5690 static void setup_heredoc(struct redir_struct *redir)
5692 struct fd_pair pair;
5695 /* the _body_ of heredoc (misleading field name) */
5696 const char *heredoc = redir->rd_filename;
5703 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5704 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5708 len = strlen(heredoc);
5710 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5712 xmove_fd(pair.rd, redir->rd_fd);
5714 /* Try writing without forking. Newer kernels have
5715 * dynamically growing pipes. Must use non-blocking write! */
5718 written = write(pair.wr, heredoc, len);
5729 ndelay_off(pair.wr);
5731 /* Okay, pipe buffer was not big enough */
5732 /* Note: we must not create a stray child (bastard? :)
5733 * for the unsuspecting parent process. Child creates a grandchild
5734 * and exits before parent execs the process which consumes heredoc
5735 * (that exec happens after we return from this function) */
5742 disable_restore_tty_pgrp_on_exit();
5743 pid = BB_MMU ? xfork() : xvfork();
5747 close(redir->rd_fd); /* read side of the pipe */
5749 full_write(pair.wr, heredoc, len); /* may loop or block */
5752 /* Delegate blocking writes to another process */
5753 xmove_fd(pair.wr, STDOUT_FILENO);
5754 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5758 #if ENABLE_HUSH_FAST
5760 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5762 enable_restore_tty_pgrp_on_exit();
5768 wait(NULL); /* wait till child has died */
5771 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5772 * and stderr if they are redirected. */
5773 static int setup_redirects(struct command *prog, int squirrel[])
5776 struct redir_struct *redir;
5778 for (redir = prog->redirects; redir; redir = redir->next) {
5779 if (redir->rd_type == REDIRECT_HEREDOC2) {
5780 /* rd_fd<<HERE case */
5781 if (squirrel && redir->rd_fd < 3
5782 && squirrel[redir->rd_fd] < 0
5784 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5786 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5788 debug_printf_parse("set heredoc '%s'\n",
5789 redir->rd_filename);
5790 setup_heredoc(redir);
5794 if (redir->rd_dup == REDIRFD_TO_FILE) {
5795 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5797 if (redir->rd_filename == NULL) {
5798 /* Something went wrong in the parse.
5799 * Pretend it didn't happen */
5800 bb_error_msg("bug in redirect parse");
5803 mode = redir_table[redir->rd_type].mode;
5804 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5805 openfd = open_or_warn(p, mode);
5808 /* this could get lost if stderr has been redirected, but
5809 * bash and ash both lose it as well (though zsh doesn't!) */
5810 //what the above comment tries to say?
5814 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5815 openfd = redir->rd_dup;
5818 if (openfd != redir->rd_fd) {
5819 if (squirrel && redir->rd_fd < 3
5820 && squirrel[redir->rd_fd] < 0
5822 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5824 if (openfd == REDIRFD_CLOSE) {
5825 /* "n>-" means "close me" */
5826 close(redir->rd_fd);
5828 xdup2(openfd, redir->rd_fd);
5829 if (redir->rd_dup == REDIRFD_TO_FILE)
5837 static void restore_redirects(int squirrel[])
5840 for (i = 0; i < 3; i++) {
5843 /* We simply die on error */
5849 static char *find_in_path(const char *arg)
5852 const char *PATH = get_local_var_value("PATH");
5858 const char *end = strchrnul(PATH, ':');
5859 int sz = end - PATH; /* must be int! */
5863 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5865 /* We have xxx::yyyy in $PATH,
5866 * it means "use current dir" */
5869 if (access(ret, F_OK) == 0)
5882 static const struct built_in_command *find_builtin_helper(const char *name,
5883 const struct built_in_command *x,
5884 const struct built_in_command *end)
5887 if (strcmp(name, x->b_cmd) != 0) {
5891 debug_printf_exec("found builtin '%s'\n", name);
5896 static const struct built_in_command *find_builtin1(const char *name)
5898 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5900 static const struct built_in_command *find_builtin(const char *name)
5902 const struct built_in_command *x = find_builtin1(name);
5905 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5908 #if ENABLE_HUSH_FUNCTIONS
5909 static struct function **find_function_slot(const char *name)
5911 struct function **funcpp = &G.top_func;
5913 if (strcmp(name, (*funcpp)->name) == 0) {
5916 funcpp = &(*funcpp)->next;
5921 static const struct function *find_function(const char *name)
5923 const struct function *funcp = *find_function_slot(name);
5925 debug_printf_exec("found function '%s'\n", name);
5929 /* Note: takes ownership on name ptr */
5930 static struct function *new_function(char *name)
5932 struct function **funcpp = find_function_slot(name);
5933 struct function *funcp = *funcpp;
5935 if (funcp != NULL) {
5936 struct command *cmd = funcp->parent_cmd;
5937 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5939 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5941 /* Note: if !funcp->body, do not free body_as_string!
5942 * This is a special case of "-F name body" function:
5943 * body_as_string was not malloced! */
5945 free_pipe_list(funcp->body);
5947 free(funcp->body_as_string);
5951 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5952 cmd->argv[0] = funcp->name;
5953 cmd->group = funcp->body;
5955 cmd->group_as_string = funcp->body_as_string;
5959 debug_printf_exec("remembering new function '%s'\n", name);
5960 funcp = *funcpp = xzalloc(sizeof(*funcp));
5961 /*funcp->next = NULL;*/
5968 static void unset_func(const char *name)
5970 struct function **funcpp = find_function_slot(name);
5971 struct function *funcp = *funcpp;
5973 if (funcp != NULL) {
5974 debug_printf_exec("freeing function '%s'\n", funcp->name);
5975 *funcpp = funcp->next;
5976 /* funcp is unlinked now, deleting it.
5977 * Note: if !funcp->body, the function was created by
5978 * "-F name body", do not free ->body_as_string
5979 * and ->name as they were not malloced. */
5981 free_pipe_list(funcp->body);
5984 free(funcp->body_as_string);
5992 #define exec_function(to_free, funcp, argv) \
5993 exec_function(funcp, argv)
5995 static void exec_function(char ***to_free,
5996 const struct function *funcp,
5997 char **argv) NORETURN;
5998 static void exec_function(char ***to_free,
5999 const struct function *funcp,
6005 argv[0] = G.global_argv[0];
6006 G.global_argv = argv;
6010 /* On MMU, funcp->body is always non-NULL */
6011 n = run_list(funcp->body);
6015 re_execute_shell(to_free,
6016 funcp->body_as_string,
6023 static int run_function(const struct function *funcp, char **argv)
6029 save_and_replace_G_args(&sv, argv);
6031 /* "we are in function, ok to use return" */
6032 sv_flg = G.flag_return_in_progress;
6033 G.flag_return_in_progress = -1;
6034 # if ENABLE_HUSH_LOCAL
6035 G.func_nest_level++;
6038 /* On MMU, funcp->body is always non-NULL */
6041 /* Function defined by -F */
6042 parse_and_run_string(funcp->body_as_string);
6043 rc = G.last_exitcode;
6047 rc = run_list(funcp->body);
6050 # if ENABLE_HUSH_LOCAL
6052 struct variable *var;
6053 struct variable **var_pp;
6055 var_pp = &G.top_var;
6056 while ((var = *var_pp) != NULL) {
6057 if (var->func_nest_level < G.func_nest_level) {
6058 var_pp = &var->next;
6062 if (var->flg_export)
6063 bb_unsetenv(var->varstr);
6064 /* Remove from global list */
6065 *var_pp = var->next;
6071 G.func_nest_level--;
6074 G.flag_return_in_progress = sv_flg;
6076 restore_G_args(&sv, argv);
6080 #endif /* ENABLE_HUSH_FUNCTIONS */
6084 #define exec_builtin(to_free, x, argv) \
6085 exec_builtin(x, argv)
6087 #define exec_builtin(to_free, x, argv) \
6088 exec_builtin(to_free, argv)
6090 static void exec_builtin(char ***to_free,
6091 const struct built_in_command *x,
6092 char **argv) NORETURN;
6093 static void exec_builtin(char ***to_free,
6094 const struct built_in_command *x,
6098 int rcode = x->b_function(argv);
6102 /* On NOMMU, we must never block!
6103 * Example: { sleep 99 | read line; } & echo Ok
6105 re_execute_shell(to_free,
6114 static void execvp_or_die(char **argv) NORETURN;
6115 static void execvp_or_die(char **argv)
6117 debug_printf_exec("execing '%s'\n", argv[0]);
6118 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6119 execvp(argv[0], argv);
6120 bb_perror_msg("can't execute '%s'", argv[0]);
6121 _exit(127); /* bash compat */
6124 #if ENABLE_HUSH_MODE_X
6125 static void dump_cmd_in_x_mode(char **argv)
6127 if (G_x_mode && argv) {
6128 /* We want to output the line in one write op */
6136 len += strlen(argv[n++]) + 1;
6142 p += sprintf(p, " %s", argv[n++]);
6150 # define dump_cmd_in_x_mode(argv) ((void)0)
6154 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6155 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6156 #define pseudo_exec(nommu_save, command, argv_expanded) \
6157 pseudo_exec(command, argv_expanded)
6160 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6162 * Don't exit() here. If you don't exec, use _exit instead.
6163 * The at_exit handlers apparently confuse the calling process,
6164 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6165 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6166 char **argv, int assignment_cnt,
6167 char **argv_expanded) NORETURN;
6168 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6169 char **argv, int assignment_cnt,
6170 char **argv_expanded)
6174 new_env = expand_assignments(argv, assignment_cnt);
6175 dump_cmd_in_x_mode(new_env);
6177 if (!argv[assignment_cnt]) {
6178 /* Case when we are here: ... | var=val | ...
6179 * (note that we do not exit early, i.e., do not optimize out
6180 * expand_assignments(): think about ... | var=`sleep 1` | ...
6182 free_strings(new_env);
6183 _exit(EXIT_SUCCESS);
6187 set_vars_and_save_old(new_env);
6188 free(new_env); /* optional */
6189 /* we can also destroy set_vars_and_save_old's return value,
6192 nommu_save->new_env = new_env;
6193 nommu_save->old_vars = set_vars_and_save_old(new_env);
6196 if (argv_expanded) {
6197 argv = argv_expanded;
6199 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6201 nommu_save->argv = argv;
6204 dump_cmd_in_x_mode(argv);
6206 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6207 if (strchr(argv[0], '/') != NULL)
6211 /* Check if the command matches any of the builtins.
6212 * Depending on context, this might be redundant. But it's
6213 * easier to waste a few CPU cycles than it is to figure out
6214 * if this is one of those cases.
6217 /* On NOMMU, it is more expensive to re-execute shell
6218 * just in order to run echo or test builtin.
6219 * It's better to skip it here and run corresponding
6220 * non-builtin later. */
6221 const struct built_in_command *x;
6222 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6224 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6227 #if ENABLE_HUSH_FUNCTIONS
6228 /* Check if the command matches any functions */
6230 const struct function *funcp = find_function(argv[0]);
6232 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6237 #if ENABLE_FEATURE_SH_STANDALONE
6238 /* Check if the command matches any busybox applets */
6240 int a = find_applet_by_name(argv[0]);
6242 # if BB_MMU /* see above why on NOMMU it is not allowed */
6243 if (APPLET_IS_NOEXEC(a)) {
6244 debug_printf_exec("running applet '%s'\n", argv[0]);
6245 run_applet_no_and_exit(a, argv);
6248 /* Re-exec ourselves */
6249 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6250 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6251 execv(bb_busybox_exec_path, argv);
6252 /* If they called chroot or otherwise made the binary no longer
6253 * executable, fall through */
6258 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6261 execvp_or_die(argv);
6264 /* Called after [v]fork() in run_pipe
6266 static void pseudo_exec(nommu_save_t *nommu_save,
6267 struct command *command,
6268 char **argv_expanded) NORETURN;
6269 static void pseudo_exec(nommu_save_t *nommu_save,
6270 struct command *command,
6271 char **argv_expanded)
6273 if (command->argv) {
6274 pseudo_exec_argv(nommu_save, command->argv,
6275 command->assignment_cnt, argv_expanded);
6278 if (command->group) {
6279 /* Cases when we are here:
6282 * ... | ( list ) | ...
6283 * ... | { list } | ...
6287 debug_printf_exec("pseudo_exec: run_list\n");
6288 reset_traps_to_defaults();
6289 rcode = run_list(command->group);
6290 /* OK to leak memory by not calling free_pipe_list,
6291 * since this process is about to exit */
6294 re_execute_shell(&nommu_save->argv_from_re_execing,
6295 command->group_as_string,
6302 /* Case when we are here: ... | >file */
6303 debug_printf_exec("pseudo_exec'ed null command\n");
6304 _exit(EXIT_SUCCESS);
6308 static const char *get_cmdtext(struct pipe *pi)
6314 /* This is subtle. ->cmdtext is created only on first backgrounding.
6315 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6316 * On subsequent bg argv is trashed, but we won't use it */
6319 argv = pi->cmds[0].argv;
6320 if (!argv || !argv[0]) {
6321 pi->cmdtext = xzalloc(1);
6327 len += strlen(*argv) + 1;
6331 argv = pi->cmds[0].argv;
6333 len = strlen(*argv);
6334 memcpy(p, *argv, len);
6342 static void insert_bg_job(struct pipe *pi)
6344 struct pipe *job, **jobp;
6347 /* Linear search for the ID of the job to use */
6349 for (job = G.job_list; job; job = job->next)
6350 if (job->jobid >= pi->jobid)
6351 pi->jobid = job->jobid + 1;
6353 /* Add job to the list of running jobs */
6355 while ((job = *jobp) != NULL)
6357 job = *jobp = xmalloc(sizeof(*job));
6359 *job = *pi; /* physical copy */
6361 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6362 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6363 for (i = 0; i < pi->num_cmds; i++) {
6364 job->cmds[i].pid = pi->cmds[i].pid;
6365 /* all other fields are not used and stay zero */
6367 job->cmdtext = xstrdup(get_cmdtext(pi));
6369 if (G_interactive_fd)
6370 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6371 G.last_jobid = job->jobid;
6374 static void remove_bg_job(struct pipe *pi)
6376 struct pipe *prev_pipe;
6378 if (pi == G.job_list) {
6379 G.job_list = pi->next;
6381 prev_pipe = G.job_list;
6382 while (prev_pipe->next != pi)
6383 prev_pipe = prev_pipe->next;
6384 prev_pipe->next = pi->next;
6387 G.last_jobid = G.job_list->jobid;
6392 /* Remove a backgrounded job */
6393 static void delete_finished_bg_job(struct pipe *pi)
6400 /* Check to see if any processes have exited -- if they
6401 * have, figure out why and see if a job has completed */
6402 static int checkjobs(struct pipe *fg_pipe)
6412 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6414 attributes = WUNTRACED;
6415 if (fg_pipe == NULL)
6416 attributes |= WNOHANG;
6419 #if ENABLE_HUSH_FAST
6420 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6421 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6422 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6423 /* There was neither fork nor SIGCHLD since last waitpid */
6424 /* Avoid doing waitpid syscall if possible */
6425 if (!G.we_have_children) {
6429 if (fg_pipe == NULL) { /* is WNOHANG set? */
6430 /* We have children, but they did not exit
6431 * or stop yet (we saw no SIGCHLD) */
6434 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6438 /* Do we do this right?
6439 * bash-3.00# sleep 20 | false
6441 * [3]+ Stopped sleep 20 | false
6442 * bash-3.00# echo $?
6443 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6444 * [hush 1.14.0: yes we do it right]
6451 #if ENABLE_HUSH_FAST
6452 i = G.count_SIGCHLD;
6454 childpid = waitpid(-1, &status, attributes);
6455 if (childpid <= 0) {
6456 if (childpid && errno != ECHILD)
6457 bb_perror_msg("waitpid");
6458 #if ENABLE_HUSH_FAST
6459 else { /* Until next SIGCHLD, waitpid's are useless */
6460 G.we_have_children = (childpid == 0);
6461 G.handled_SIGCHLD = i;
6462 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6467 dead = WIFEXITED(status) || WIFSIGNALED(status);
6470 if (WIFSTOPPED(status))
6471 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6472 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6473 if (WIFSIGNALED(status))
6474 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6475 childpid, WTERMSIG(status), WEXITSTATUS(status));
6476 if (WIFEXITED(status))
6477 debug_printf_jobs("pid %d exited, exitcode %d\n",
6478 childpid, WEXITSTATUS(status));
6480 /* Were we asked to wait for fg pipe? */
6482 i = fg_pipe->num_cmds;
6484 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6485 if (fg_pipe->cmds[i].pid != childpid)
6489 fg_pipe->cmds[i].pid = 0;
6490 fg_pipe->alive_cmds--;
6491 ex = WEXITSTATUS(status);
6492 /* bash prints killer signal's name for *last*
6493 * process in pipe (prints just newline for SIGINT).
6494 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6496 if (WIFSIGNALED(status)) {
6497 int sig = WTERMSIG(status);
6498 if (i == fg_pipe->num_cmds-1)
6499 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6500 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6501 * Maybe we need to use sig | 128? */
6504 fg_pipe->cmds[i].cmd_exitcode = ex;
6506 fg_pipe->cmds[i].is_stopped = 1;
6507 fg_pipe->stopped_cmds++;
6509 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6510 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6511 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6512 /* All processes in fg pipe have exited or stopped */
6513 i = fg_pipe->num_cmds;
6515 rcode = fg_pipe->cmds[i].cmd_exitcode;
6516 /* usually last process gives overall exitstatus,
6517 * but with "set -o pipefail", last *failed* process does */
6518 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6521 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6522 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6523 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6524 * and "killall -STOP cat" */
6525 if (G_interactive_fd) {
6527 if (fg_pipe->alive_cmds != 0)
6528 insert_bg_job(fg_pipe);
6532 if (fg_pipe->alive_cmds == 0)
6535 /* There are still running processes in the fg pipe */
6536 goto wait_more; /* do waitpid again */
6538 /* it wasnt fg_pipe, look for process in bg pipes */
6542 /* We asked to wait for bg or orphaned children */
6543 /* No need to remember exitcode in this case */
6544 for (pi = G.job_list; pi; pi = pi->next) {
6545 for (i = 0; i < pi->num_cmds; i++) {
6546 if (pi->cmds[i].pid == childpid)
6547 goto found_pi_and_prognum;
6550 /* Happens when shell is used as init process (init=/bin/sh) */
6551 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6552 continue; /* do waitpid again */
6554 found_pi_and_prognum:
6557 pi->cmds[i].pid = 0;
6559 if (!pi->alive_cmds) {
6560 if (G_interactive_fd)
6561 printf(JOB_STATUS_FORMAT, pi->jobid,
6562 "Done", pi->cmdtext);
6563 delete_finished_bg_job(pi);
6567 pi->cmds[i].is_stopped = 1;
6571 } /* while (waitpid succeeds)... */
6577 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6580 int rcode = checkjobs(fg_pipe);
6581 if (G_saved_tty_pgrp) {
6582 /* Job finished, move the shell to the foreground */
6583 p = getpgrp(); /* our process group id */
6584 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6585 tcsetpgrp(G_interactive_fd, p);
6591 /* Start all the jobs, but don't wait for anything to finish.
6594 * Return code is normally -1, when the caller has to wait for children
6595 * to finish to determine the exit status of the pipe. If the pipe
6596 * is a simple builtin command, however, the action is done by the
6597 * time run_pipe returns, and the exit code is provided as the
6600 * Returns -1 only if started some children. IOW: we have to
6601 * mask out retvals of builtins etc with 0xff!
6603 * The only case when we do not need to [v]fork is when the pipe
6604 * is single, non-backgrounded, non-subshell command. Examples:
6605 * cmd ; ... { list } ; ...
6606 * cmd && ... { list } && ...
6607 * cmd || ... { list } || ...
6608 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6609 * or (if SH_STANDALONE) an applet, and we can run the { list }
6610 * with run_list. If it isn't one of these, we fork and exec cmd.
6612 * Cases when we must fork:
6613 * non-single: cmd | cmd
6614 * backgrounded: cmd & { list } &
6615 * subshell: ( list ) [&]
6617 #if !ENABLE_HUSH_MODE_X
6618 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6619 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6621 static int redirect_and_varexp_helper(char ***new_env_p,
6622 struct variable **old_vars_p,
6623 struct command *command,
6625 char **argv_expanded)
6627 /* setup_redirects acts on file descriptors, not FILEs.
6628 * This is perfect for work that comes after exec().
6629 * Is it really safe for inline use? Experimentally,
6630 * things seem to work. */
6631 int rcode = setup_redirects(command, squirrel);
6633 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6634 *new_env_p = new_env;
6635 dump_cmd_in_x_mode(new_env);
6636 dump_cmd_in_x_mode(argv_expanded);
6638 *old_vars_p = set_vars_and_save_old(new_env);
6642 static NOINLINE int run_pipe(struct pipe *pi)
6644 static const char *const null_ptr = NULL;
6648 struct command *command;
6649 char **argv_expanded;
6651 /* it is not always needed, but we aim to smaller code */
6652 int squirrel[] = { -1, -1, -1 };
6655 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6658 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6659 * Result should be 3 lines: q w e, qwe, q w e
6661 G.ifs = get_local_var_value("IFS");
6665 IF_HUSH_JOB(pi->pgrp = -1;)
6666 pi->stopped_cmds = 0;
6667 command = &pi->cmds[0];
6668 argv_expanded = NULL;
6670 if (pi->num_cmds != 1
6671 || pi->followup == PIPE_BG
6672 || command->cmd_type == CMD_SUBSHELL
6679 debug_printf_exec(": group:%p argv:'%s'\n",
6680 command->group, command->argv ? command->argv[0] : "NONE");
6682 if (command->group) {
6683 #if ENABLE_HUSH_FUNCTIONS
6684 if (command->cmd_type == CMD_FUNCDEF) {
6685 /* "executing" func () { list } */
6686 struct function *funcp;
6688 funcp = new_function(command->argv[0]);
6689 /* funcp->name is already set to argv[0] */
6690 funcp->body = command->group;
6692 funcp->body_as_string = command->group_as_string;
6693 command->group_as_string = NULL;
6695 command->group = NULL;
6696 command->argv[0] = NULL;
6697 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6698 funcp->parent_cmd = command;
6699 command->child_func = funcp;
6701 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6703 return EXIT_SUCCESS;
6707 debug_printf("non-subshell group\n");
6708 rcode = 1; /* exitcode if redir failed */
6709 if (setup_redirects(command, squirrel) == 0) {
6710 debug_printf_exec(": run_list\n");
6711 rcode = run_list(command->group) & 0xff;
6713 restore_redirects(squirrel);
6714 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6716 debug_printf_exec("run_pipe: return %d\n", rcode);
6720 argv = command->argv ? command->argv : (char **) &null_ptr;
6722 const struct built_in_command *x;
6723 #if ENABLE_HUSH_FUNCTIONS
6724 const struct function *funcp;
6728 char **new_env = NULL;
6729 struct variable *old_vars = NULL;
6731 if (argv[command->assignment_cnt] == NULL) {
6732 /* Assignments, but no command */
6733 /* Ensure redirects take effect (that is, create files).
6734 * Try "a=t >file" */
6735 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6736 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6737 /* Set shell variables */
6741 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6742 /* Do we need to flag set_local_var() errors?
6743 * "assignment to readonly var" and "putenv error"
6748 /* Redirect error sets $? to 1. Otherwise,
6749 * if evaluating assignment value set $?, retain it.
6750 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6752 rcode = G.last_exitcode;
6753 /* Exit, _skipping_ variable restoring code: */
6754 goto clean_up_and_ret0;
6756 #else /* Older, bigger, but more correct code */
6758 rcode = setup_redirects(command, squirrel);
6759 restore_redirects(squirrel);
6760 /* Set shell variables */
6762 bb_putchar_stderr('+');
6764 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6766 fprintf(stderr, " %s", p);
6767 debug_printf_exec("set shell var:'%s'->'%s'\n",
6769 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6770 /* Do we need to flag set_local_var() errors?
6771 * "assignment to readonly var" and "putenv error"
6776 bb_putchar_stderr('\n');
6777 /* Redirect error sets $? to 1. Otherwise,
6778 * if evaluating assignment value set $?, retain it.
6779 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6781 rcode = G.last_exitcode;
6782 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6784 debug_printf_exec("run_pipe: return %d\n", rcode);
6789 /* Expand the rest into (possibly) many strings each */
6791 #if ENABLE_HUSH_BASH_COMPAT
6792 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6793 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6797 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6800 /* if someone gives us an empty string: `cmd with empty output` */
6801 if (!argv_expanded[0]) {
6802 free(argv_expanded);
6804 return G.last_exitcode;
6807 x = find_builtin(argv_expanded[0]);
6808 #if ENABLE_HUSH_FUNCTIONS
6811 funcp = find_function(argv_expanded[0]);
6815 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6816 debug_printf("exec with redirects only\n");
6817 rcode = setup_redirects(command, NULL);
6818 goto clean_up_and_ret1;
6821 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6824 debug_printf_exec(": builtin '%s' '%s'...\n",
6825 x->b_cmd, argv_expanded[1]);
6826 rcode = x->b_function(argv_expanded) & 0xff;
6829 #if ENABLE_HUSH_FUNCTIONS
6831 # if ENABLE_HUSH_LOCAL
6832 struct variable **sv;
6833 sv = G.shadowed_vars_pp;
6834 G.shadowed_vars_pp = &old_vars;
6836 debug_printf_exec(": function '%s' '%s'...\n",
6837 funcp->name, argv_expanded[1]);
6838 rcode = run_function(funcp, argv_expanded) & 0xff;
6839 # if ENABLE_HUSH_LOCAL
6840 G.shadowed_vars_pp = sv;
6846 unset_vars(new_env);
6848 /* clean_up_and_ret0: */
6849 restore_redirects(squirrel);
6851 free(argv_expanded);
6852 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6854 debug_printf_exec("run_pipe return %d\n", rcode);
6858 if (ENABLE_FEATURE_SH_STANDALONE) {
6859 int n = find_applet_by_name(argv_expanded[0]);
6860 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6861 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6863 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6864 argv_expanded[0], argv_expanded[1]);
6865 rcode = run_nofork_applet(n, argv_expanded);
6867 goto clean_up_and_ret;
6870 /* It is neither builtin nor applet. We must fork. */
6874 /* NB: argv_expanded may already be created, and that
6875 * might include `cmd` runs! Do not rerun it! We *must*
6876 * use argv_expanded if it's non-NULL */
6878 /* Going to fork a child per each pipe member */
6883 while (cmd_no < pi->num_cmds) {
6884 struct fd_pair pipefds;
6886 volatile nommu_save_t nommu_save;
6887 nommu_save.new_env = NULL;
6888 nommu_save.old_vars = NULL;
6889 nommu_save.argv = NULL;
6890 nommu_save.argv_from_re_execing = NULL;
6892 command = &pi->cmds[cmd_no];
6894 if (command->argv) {
6895 debug_printf_exec(": pipe member '%s' '%s'...\n",
6896 command->argv[0], command->argv[1]);
6898 debug_printf_exec(": pipe member with no argv\n");
6901 /* pipes are inserted between pairs of commands */
6904 if (cmd_no < pi->num_cmds)
6905 xpiped_pair(pipefds);
6907 command->pid = BB_MMU ? fork() : vfork();
6908 if (!command->pid) { /* child */
6910 disable_restore_tty_pgrp_on_exit();
6911 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6913 /* Every child adds itself to new process group
6914 * with pgid == pid_of_first_child_in_pipe */
6915 if (G.run_list_level == 1 && G_interactive_fd) {
6918 if (pgrp < 0) /* true for 1st process only */
6920 if (setpgid(0, pgrp) == 0
6921 && pi->followup != PIPE_BG
6922 && G_saved_tty_pgrp /* we have ctty */
6924 /* We do it in *every* child, not just first,
6926 tcsetpgrp(G_interactive_fd, pgrp);
6930 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6931 /* 1st cmd in backgrounded pipe
6932 * should have its stdin /dev/null'ed */
6934 if (open(bb_dev_null, O_RDONLY))
6935 xopen("/", O_RDONLY);
6937 xmove_fd(next_infd, 0);
6939 xmove_fd(pipefds.wr, 1);
6942 /* Like bash, explicit redirects override pipes,
6943 * and the pipe fd is available for dup'ing. */
6944 if (setup_redirects(command, NULL))
6947 /* Restore default handlers just prior to exec */
6948 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6950 /* Stores to nommu_save list of env vars putenv'ed
6951 * (NOMMU, on MMU we don't need that) */
6952 /* cast away volatility... */
6953 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6954 /* pseudo_exec() does not return */
6957 /* parent or error */
6958 #if ENABLE_HUSH_FAST
6960 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6962 enable_restore_tty_pgrp_on_exit();
6964 /* Clean up after vforked child */
6965 free(nommu_save.argv);
6966 free(nommu_save.argv_from_re_execing);
6967 unset_vars(nommu_save.new_env);
6968 add_vars(nommu_save.old_vars);
6970 free(argv_expanded);
6971 argv_expanded = NULL;
6972 if (command->pid < 0) { /* [v]fork failed */
6973 /* Clearly indicate, was it fork or vfork */
6974 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6978 /* Second and next children need to know pid of first one */
6980 pi->pgrp = command->pid;
6986 if (cmd_no < pi->num_cmds)
6988 /* Pass read (output) pipe end to next iteration */
6989 next_infd = pipefds.rd;
6992 if (!pi->alive_cmds) {
6994 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6999 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7003 /* NB: called by pseudo_exec, and therefore must not modify any
7004 * global data until exec/_exit (we can be a child after vfork!) */
7005 static int run_list(struct pipe *pi)
7007 #if ENABLE_HUSH_CASE
7008 char *case_word = NULL;
7010 #if ENABLE_HUSH_LOOPS
7011 struct pipe *loop_top = NULL;
7012 char **for_lcur = NULL;
7013 char **for_list = NULL;
7015 smallint last_followup;
7017 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7018 smalluint cond_code = 0;
7020 enum { cond_code = 0 };
7023 smallint rword; /* RES_foo */
7024 smallint last_rword; /* ditto */
7027 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7030 #if ENABLE_HUSH_LOOPS
7031 /* Check syntax for "for" */
7034 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7035 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7037 /* current word is FOR or IN (BOLD in comments below) */
7038 if (cpipe->next == NULL) {
7039 syntax_error("malformed for");
7041 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7044 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7045 if (cpipe->next->res_word == RES_DO)
7047 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7048 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7049 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7051 syntax_error("malformed for");
7053 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7060 /* Past this point, all code paths should jump to ret: label
7061 * in order to return, no direct "return" statements please.
7062 * This helps to ensure that no memory is leaked. */
7070 last_rword = RES_XXXX;
7072 last_followup = PIPE_SEQ;
7073 rcode = G.last_exitcode;
7075 /* Go through list of pipes, (maybe) executing them. */
7076 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7080 IF_HAS_KEYWORDS(rword = pi->res_word;)
7081 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7082 rword, cond_code, last_rword);
7083 #if ENABLE_HUSH_LOOPS
7084 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7085 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7087 /* start of a loop: remember where loop starts */
7092 /* Still in the same "if...", "then..." or "do..." branch? */
7093 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7094 if ((rcode == 0 && last_followup == PIPE_OR)
7095 || (rcode != 0 && last_followup == PIPE_AND)
7097 /* It is "<true> || CMD" or "<false> && CMD"
7098 * and we should not execute CMD */
7099 debug_printf_exec("skipped cmd because of || or &&\n");
7100 last_followup = pi->followup;
7104 last_followup = pi->followup;
7105 IF_HAS_KEYWORDS(last_rword = rword;)
7108 if (rword == RES_THEN) {
7109 /* if false; then ... fi has exitcode 0! */
7110 G.last_exitcode = rcode = EXIT_SUCCESS;
7111 /* "if <false> THEN cmd": skip cmd */
7115 if (rword == RES_ELSE || rword == RES_ELIF) {
7116 /* "if <true> then ... ELSE/ELIF cmd":
7117 * skip cmd and all following ones */
7122 #if ENABLE_HUSH_LOOPS
7123 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7125 /* first loop through for */
7127 static const char encoded_dollar_at[] ALIGN1 = {
7128 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7129 }; /* encoded representation of "$@" */
7130 static const char *const encoded_dollar_at_argv[] = {
7131 encoded_dollar_at, NULL
7132 }; /* argv list with one element: "$@" */
7135 vals = (char**)encoded_dollar_at_argv;
7136 if (pi->next->res_word == RES_IN) {
7137 /* if no variable values after "in" we skip "for" */
7138 if (!pi->next->cmds[0].argv) {
7139 G.last_exitcode = rcode = EXIT_SUCCESS;
7140 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7143 vals = pi->next->cmds[0].argv;
7144 } /* else: "for var; do..." -> assume "$@" list */
7145 /* create list of variable values */
7146 debug_print_strings("for_list made from", vals);
7147 for_list = expand_strvec_to_strvec(vals);
7148 for_lcur = for_list;
7149 debug_print_strings("for_list", for_list);
7152 /* "for" loop is over, clean up */
7158 /* Insert next value from for_lcur */
7159 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7160 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7163 if (rword == RES_IN) {
7164 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7166 if (rword == RES_DONE) {
7167 continue; /* "done" has no cmds too */
7170 #if ENABLE_HUSH_CASE
7171 if (rword == RES_CASE) {
7172 case_word = expand_strvec_to_string(pi->cmds->argv);
7175 if (rword == RES_MATCH) {
7178 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7180 /* all prev words didn't match, does this one match? */
7181 argv = pi->cmds->argv;
7183 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7184 /* TODO: which FNM_xxx flags to use? */
7185 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7187 if (cond_code == 0) { /* match! we will execute this branch */
7188 free(case_word); /* make future "word)" stop */
7196 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7198 continue; /* not matched yet, skip this pipe */
7201 /* Just pressing <enter> in shell should check for jobs.
7202 * OTOH, in non-interactive shell this is useless
7203 * and only leads to extra job checks */
7204 if (pi->num_cmds == 0) {
7205 if (G_interactive_fd)
7206 goto check_jobs_and_continue;
7210 /* After analyzing all keywords and conditions, we decided
7211 * to execute this pipe. NB: have to do checkjobs(NULL)
7212 * after run_pipe to collect any background children,
7213 * even if list execution is to be stopped. */
7214 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7217 #if ENABLE_HUSH_LOOPS
7218 G.flag_break_continue = 0;
7220 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7222 /* We ran a builtin, function, or group.
7223 * rcode is already known
7224 * and we don't need to wait for anything. */
7225 G.last_exitcode = rcode;
7226 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7227 check_and_run_traps(0);
7228 #if ENABLE_HUSH_LOOPS
7229 /* Was it "break" or "continue"? */
7230 if (G.flag_break_continue) {
7231 smallint fbc = G.flag_break_continue;
7232 /* We might fall into outer *loop*,
7233 * don't want to break it too */
7235 G.depth_break_continue--;
7236 if (G.depth_break_continue == 0)
7237 G.flag_break_continue = 0;
7238 /* else: e.g. "continue 2" should *break* once, *then* continue */
7239 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7240 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7241 goto check_jobs_and_break;
7242 /* "continue": simulate end of loop */
7247 #if ENABLE_HUSH_FUNCTIONS
7248 if (G.flag_return_in_progress == 1) {
7249 /* same as "goto check_jobs_and_break" */
7254 } else if (pi->followup == PIPE_BG) {
7255 /* What does bash do with attempts to background builtins? */
7256 /* even bash 3.2 doesn't do that well with nested bg:
7257 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7258 * I'm NOT treating inner &'s as jobs */
7259 check_and_run_traps(0);
7261 if (G.run_list_level == 1)
7264 /* Last command's pid goes to $! */
7265 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7266 G.last_exitcode = rcode = EXIT_SUCCESS;
7267 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7270 if (G.run_list_level == 1 && G_interactive_fd) {
7271 /* Waits for completion, then fg's main shell */
7272 rcode = checkjobs_and_fg_shell(pi);
7273 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7274 check_and_run_traps(0);
7277 { /* This one just waits for completion */
7278 rcode = checkjobs(pi);
7279 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7280 check_and_run_traps(0);
7282 G.last_exitcode = rcode;
7286 /* Analyze how result affects subsequent commands */
7288 if (rword == RES_IF || rword == RES_ELIF)
7291 #if ENABLE_HUSH_LOOPS
7292 /* Beware of "while false; true; do ..."! */
7293 if (pi->next && pi->next->res_word == RES_DO) {
7294 if (rword == RES_WHILE) {
7296 /* "while false; do...done" - exitcode 0 */
7297 G.last_exitcode = rcode = EXIT_SUCCESS;
7298 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7299 goto check_jobs_and_break;
7302 if (rword == RES_UNTIL) {
7304 debug_printf_exec(": until expr is true: breaking\n");
7305 check_jobs_and_break:
7313 check_jobs_and_continue:
7320 #if ENABLE_HUSH_LOOPS
7325 #if ENABLE_HUSH_CASE
7329 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7333 /* Select which version we will use */
7334 static int run_and_free_list(struct pipe *pi)
7337 debug_printf_exec("run_and_free_list entered\n");
7338 if (!G.o_opt[OPT_O_NOEXEC]) {
7339 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7340 rcode = run_list(pi);
7342 /* free_pipe_list has the side effect of clearing memory.
7343 * In the long run that function can be merged with run_list,
7344 * but doing that now would hobble the debugging effort. */
7346 debug_printf_exec("run_and_free_list return %d\n", rcode);
7351 /* Called a few times only (or even once if "sh -c") */
7352 static void init_sigmasks(void)
7356 sigset_t old_blocked_set;
7358 if (!G.inherited_set_is_saved) {
7359 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7360 G.inherited_set = G.blocked_set;
7362 old_blocked_set = G.blocked_set;
7364 mask = (1 << SIGQUIT);
7365 if (G_interactive_fd) {
7366 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7367 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7368 mask |= SPECIAL_JOB_SIGS;
7370 G.non_DFL_mask = mask;
7375 sigaddset(&G.blocked_set, sig);
7379 sigdelset(&G.blocked_set, SIGCHLD);
7381 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7382 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7384 /* POSIX allows shell to re-enable SIGCHLD
7385 * even if it was SIG_IGN on entry */
7386 #if ENABLE_HUSH_FAST
7387 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7388 if (!G.inherited_set_is_saved)
7389 signal(SIGCHLD, SIGCHLD_handler);
7391 if (!G.inherited_set_is_saved)
7392 signal(SIGCHLD, SIG_DFL);
7395 G.inherited_set_is_saved = 1;
7400 static void maybe_set_to_sigexit(int sig)
7402 void (*handler)(int);
7403 /* non_DFL_mask'ed signals are, well, masked,
7404 * no need to set handler for them.
7406 if (!((G.non_DFL_mask >> sig) & 1)) {
7407 handler = signal(sig, sigexit);
7408 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7409 signal(sig, handler);
7412 /* Set handlers to restore tty pgrp and exit */
7413 static void set_fatal_handlers(void)
7415 /* We _must_ restore tty pgrp on fatal signals */
7417 maybe_set_to_sigexit(SIGILL );
7418 maybe_set_to_sigexit(SIGFPE );
7419 maybe_set_to_sigexit(SIGBUS );
7420 maybe_set_to_sigexit(SIGSEGV);
7421 maybe_set_to_sigexit(SIGTRAP);
7422 } /* else: hush is perfect. what SEGV? */
7423 maybe_set_to_sigexit(SIGABRT);
7424 /* bash 3.2 seems to handle these just like 'fatal' ones */
7425 maybe_set_to_sigexit(SIGPIPE);
7426 maybe_set_to_sigexit(SIGALRM);
7427 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7428 * if we aren't interactive... but in this case
7429 * we never want to restore pgrp on exit, and this fn is not called */
7430 /*maybe_set_to_sigexit(SIGHUP );*/
7431 /*maybe_set_to_sigexit(SIGTERM);*/
7432 /*maybe_set_to_sigexit(SIGINT );*/
7436 static int set_mode(int state, char mode, const char *o_opt)
7441 G.o_opt[OPT_O_NOEXEC] = state;
7444 IF_HUSH_MODE_X(G_x_mode = state;)
7448 /* "set -+o" without parameter.
7449 * in bash, set -o produces this output:
7453 * We always use the second form.
7455 const char *p = o_opt_strings;
7458 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7464 idx = index_in_strings(o_opt_strings, o_opt);
7466 G.o_opt[idx] = state;
7470 return EXIT_FAILURE;
7472 return EXIT_SUCCESS;
7475 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7476 int hush_main(int argc, char **argv)
7479 unsigned builtin_argc;
7481 struct variable *cur_var;
7482 struct variable *shell_ver;
7485 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7486 G.last_exitcode = EXIT_SUCCESS;
7488 G.argv0_for_re_execing = argv[0];
7490 /* Deal with HUSH_VERSION */
7491 shell_ver = xzalloc(sizeof(*shell_ver));
7492 shell_ver->flg_export = 1;
7493 shell_ver->flg_read_only = 1;
7494 /* Code which handles ${var<op>...} needs writable values for all variables,
7495 * therefore we xstrdup: */
7496 shell_ver->varstr = xstrdup(hush_version_str);
7497 /* Create shell local variables from the values
7498 * currently living in the environment */
7499 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7500 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7501 G.top_var = shell_ver;
7502 cur_var = G.top_var;
7505 char *value = strchr(*e, '=');
7506 if (value) { /* paranoia */
7507 cur_var->next = xzalloc(sizeof(*cur_var));
7508 cur_var = cur_var->next;
7509 cur_var->varstr = *e;
7510 cur_var->max_len = strlen(*e);
7511 cur_var->flg_export = 1;
7515 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7516 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7517 putenv(shell_ver->varstr);
7520 set_pwd_var(/*exp:*/ 1);
7521 /* bash also exports SHLVL and _,
7522 * and sets (but doesn't export) the following variables:
7524 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7525 * BASH_VERSION='3.2.0(1)-release'
7527 * MACHTYPE=i386-pc-linux-gnu
7529 * HOSTNAME=<xxxxxxxxxx>
7530 * PPID=<NNNNN> - we also do it elsewhere
7541 * PIPESTATUS=([0]="0")
7542 * HISTFILE=/<xxx>/.bash_history
7546 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7548 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7558 #if ENABLE_FEATURE_EDITING
7559 G.line_input_state = new_line_input_t(FOR_SHELL);
7560 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7562 const char *hp = get_local_var_value("HISTFILE");
7564 hp = get_local_var_value("HOME");
7566 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7567 //set_local_var(xasprintf("HISTFILE=%s", ...));
7574 G.global_argc = argc;
7575 G.global_argv = argv;
7576 /* Initialize some more globals to non-zero values */
7577 cmdedit_update_prompt();
7579 if (setjmp(die_jmp)) {
7580 /* xfunc has failed! die die die */
7581 /* no EXIT traps, this is an escape hatch! */
7583 hush_exit(xfunc_error_retval);
7586 /* Shell is non-interactive at first. We need to call
7587 * init_sigmasks() if we are going to execute "sh <script>",
7588 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7589 * If we later decide that we are interactive, we run init_sigmasks()
7590 * in order to intercept (more) signals.
7594 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7597 opt = getopt(argc, argv, "+c:xins"
7600 # if ENABLE_HUSH_FUNCTIONS
7610 * sh ... -c 'script'
7611 * sh ... -c 'script' ARG0 [ARG1...]
7612 * On NOMMU, if builtin_argc != 0,
7613 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7614 * "" needs to be replaced with NULL
7615 * and BARGV vector fed to builtin function.
7616 * Note: the form without ARG0 never happens:
7617 * sh ... -c 'builtin' BARGV... ""
7620 G.root_pid = getpid();
7621 G.root_ppid = getppid();
7623 G.global_argv = argv + optind;
7624 G.global_argc = argc - optind;
7626 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7627 const struct built_in_command *x;
7630 x = find_builtin(optarg);
7631 if (x) { /* paranoia */
7632 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7633 G.global_argv += builtin_argc;
7634 G.global_argv[-1] = NULL; /* replace "" */
7635 G.last_exitcode = x->b_function(argv + optind - 1);
7639 if (!G.global_argv[0]) {
7640 /* -c 'script' (no params): prevent empty $0 */
7641 G.global_argv--; /* points to argv[i] of 'script' */
7642 G.global_argv[0] = argv[0];
7644 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7646 parse_and_run_string(optarg);
7649 /* Well, we cannot just declare interactiveness,
7650 * we have to have some stuff (ctty, etc) */
7651 /* G_interactive_fd++; */
7654 /* "-s" means "read from stdin", but this is how we always
7655 * operate, so simply do nothing here. */
7658 case '<': /* "big heredoc" support */
7659 full_write1_str(optarg);
7662 unsigned long long empty_trap_mask;
7664 G.root_pid = bb_strtou(optarg, &optarg, 16);
7666 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7668 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7670 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7672 builtin_argc = bb_strtou(optarg, &optarg, 16);
7674 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7675 if (empty_trap_mask != 0) {
7678 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7679 for (sig = 1; sig < NSIG; sig++) {
7680 if (empty_trap_mask & (1LL << sig)) {
7681 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7682 sigaddset(&G.blocked_set, sig);
7685 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7687 # if ENABLE_HUSH_LOOPS
7689 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7695 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7697 # if ENABLE_HUSH_FUNCTIONS
7699 struct function *funcp = new_function(optarg);
7700 /* funcp->name is already set to optarg */
7701 /* funcp->body is set to NULL. It's a special case. */
7702 funcp->body_as_string = argv[optind];
7710 if (set_mode(1, opt, NULL) == 0) /* no error */
7714 fprintf(stderr, "Usage: sh [FILE]...\n"
7715 " or: sh -c command [args]...\n\n");
7721 } /* option parsing loop */
7724 G.root_pid = getpid();
7725 G.root_ppid = getppid();
7728 /* If we are login shell... */
7729 if (argv[0] && argv[0][0] == '-') {
7731 debug_printf("sourcing /etc/profile\n");
7732 input = fopen_for_read("/etc/profile");
7733 if (input != NULL) {
7734 close_on_exec_on(fileno(input));
7736 parse_and_run_file(input);
7739 /* bash: after sourcing /etc/profile,
7740 * tries to source (in the given order):
7741 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7742 * stopping on first found. --noprofile turns this off.
7743 * bash also sources ~/.bash_logout on exit.
7744 * If called as sh, skips .bash_XXX files.
7751 * "bash <script>" (which is never interactive (unless -i?))
7752 * sources $BASH_ENV here (without scanning $PATH).
7753 * If called as sh, does the same but with $ENV.
7755 debug_printf("running script '%s'\n", argv[optind]);
7756 G.global_argv = argv + optind;
7757 G.global_argc = argc - optind;
7758 input = xfopen_for_read(argv[optind]);
7759 close_on_exec_on(fileno(input));
7761 parse_and_run_file(input);
7762 #if ENABLE_FEATURE_CLEAN_UP
7768 /* Up to here, shell was non-interactive. Now it may become one.
7769 * NB: don't forget to (re)run init_sigmasks() as needed.
7772 /* A shell is interactive if the '-i' flag was given,
7773 * or if all of the following conditions are met:
7775 * no arguments remaining or the -s flag given
7776 * standard input is a terminal
7777 * standard output is a terminal
7778 * Refer to Posix.2, the description of the 'sh' utility.
7781 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7782 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7783 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7784 if (G_saved_tty_pgrp < 0)
7785 G_saved_tty_pgrp = 0;
7787 /* try to dup stdin to high fd#, >= 255 */
7788 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7789 if (G_interactive_fd < 0) {
7790 /* try to dup to any fd */
7791 G_interactive_fd = dup(STDIN_FILENO);
7792 if (G_interactive_fd < 0) {
7794 G_interactive_fd = 0;
7795 G_saved_tty_pgrp = 0;
7798 // TODO: track & disallow any attempts of user
7799 // to (inadvertently) close/redirect G_interactive_fd
7801 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7802 if (G_interactive_fd) {
7803 close_on_exec_on(G_interactive_fd);
7805 if (G_saved_tty_pgrp) {
7806 /* If we were run as 'hush &', sleep until we are
7807 * in the foreground (tty pgrp == our pgrp).
7808 * If we get started under a job aware app (like bash),
7809 * make sure we are now in charge so we don't fight over
7810 * who gets the foreground */
7812 pid_t shell_pgrp = getpgrp();
7813 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7814 if (G_saved_tty_pgrp == shell_pgrp)
7816 /* send TTIN to ourself (should stop us) */
7817 kill(- shell_pgrp, SIGTTIN);
7821 /* Block some signals */
7824 if (G_saved_tty_pgrp) {
7825 /* Set other signals to restore saved_tty_pgrp */
7826 set_fatal_handlers();
7827 /* Put ourselves in our own process group
7828 * (bash, too, does this only if ctty is available) */
7829 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7830 /* Grab control of the terminal */
7831 tcsetpgrp(G_interactive_fd, getpid());
7833 /* -1 is special - makes xfuncs longjmp, not exit
7834 * (we reset die_sleep = 0 whereever we [v]fork) */
7835 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7839 #elif ENABLE_HUSH_INTERACTIVE
7840 /* No job control compiled in, only prompt/line editing */
7841 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7842 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7843 if (G_interactive_fd < 0) {
7844 /* try to dup to any fd */
7845 G_interactive_fd = dup(STDIN_FILENO);
7846 if (G_interactive_fd < 0)
7848 G_interactive_fd = 0;
7851 if (G_interactive_fd) {
7852 close_on_exec_on(G_interactive_fd);
7856 /* We have interactiveness code disabled */
7860 * if interactive but not a login shell, sources ~/.bashrc
7861 * (--norc turns this off, --rcfile <file> overrides)
7864 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7865 /* note: ash and hush share this string */
7866 printf("\n\n%s %s\n"
7867 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7870 "hush - the humble shell"
7874 parse_and_run_file(stdin);
7877 hush_exit(G.last_exitcode);
7882 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7883 int msh_main(int argc, char **argv)
7885 //bb_error_msg("msh is deprecated, please use hush instead");
7886 return hush_main(argc, argv);
7894 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7899 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7906 return applet_main_func(argc, argv - argc);
7909 static int FAST_FUNC builtin_test(char **argv)
7911 return run_applet_main(argv, test_main);
7914 static int FAST_FUNC builtin_echo(char **argv)
7916 return run_applet_main(argv, echo_main);
7920 static int FAST_FUNC builtin_printf(char **argv)
7922 return run_applet_main(argv, printf_main);
7926 static char **skip_dash_dash(char **argv)
7929 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7934 static int FAST_FUNC builtin_eval(char **argv)
7936 int rcode = EXIT_SUCCESS;
7938 argv = skip_dash_dash(argv);
7940 char *str = expand_strvec_to_string(argv);
7942 * eval "echo Hi; done" ("done" is syntax error):
7943 * "echo Hi" will not execute too.
7945 parse_and_run_string(str);
7947 rcode = G.last_exitcode;
7952 static int FAST_FUNC builtin_cd(char **argv)
7956 argv = skip_dash_dash(argv);
7958 if (newdir == NULL) {
7959 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7960 * bash says "bash: cd: HOME not set" and does nothing
7963 const char *home = get_local_var_value("HOME");
7964 newdir = home ? home : "/";
7966 if (chdir(newdir)) {
7967 /* Mimic bash message exactly */
7968 bb_perror_msg("cd: %s", newdir);
7969 return EXIT_FAILURE;
7971 /* Read current dir (get_cwd(1) is inside) and set PWD.
7972 * Note: do not enforce exporting. If PWD was unset or unexported,
7973 * set it again, but do not export. bash does the same.
7975 set_pwd_var(/*exp:*/ 0);
7976 return EXIT_SUCCESS;
7979 static int FAST_FUNC builtin_exec(char **argv)
7981 argv = skip_dash_dash(argv);
7982 if (argv[0] == NULL)
7983 return EXIT_SUCCESS; /* bash does this */
7985 /* Careful: we can end up here after [v]fork. Do not restore
7986 * tty pgrp then, only top-level shell process does that */
7987 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7988 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7990 /* TODO: if exec fails, bash does NOT exit! We do.
7991 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7992 * and tcsetpgrp, and this is inherently racy.
7994 execvp_or_die(argv);
7997 static int FAST_FUNC builtin_exit(char **argv)
7999 debug_printf_exec("%s()\n", __func__);
8001 /* interactive bash:
8002 * # trap "echo EEE" EXIT
8005 * There are stopped jobs.
8006 * (if there are _stopped_ jobs, running ones don't count)
8009 # EEE (then bash exits)
8011 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8014 /* note: EXIT trap is run by hush_exit */
8015 argv = skip_dash_dash(argv);
8016 if (argv[0] == NULL)
8017 hush_exit(G.last_exitcode);
8018 /* mimic bash: exit 123abc == exit 255 + error msg */
8019 xfunc_error_retval = 255;
8020 /* bash: exit -2 == exit 254, no error msg */
8021 hush_exit(xatoi(argv[0]) & 0xff);
8024 static void print_escaped(const char *s)
8029 const char *p = strchrnul(s, '\'');
8030 /* print 'xxxx', possibly just '' */
8031 printf("'%.*s'", (int)(p - s), s);
8036 /* s points to '; print "'''...'''" */
8038 do putchar('\''); while (*++s == '\'');
8043 #if !ENABLE_HUSH_LOCAL
8044 #define helper_export_local(argv, exp, lvl) \
8045 helper_export_local(argv, exp)
8047 static void helper_export_local(char **argv, int exp, int lvl)
8051 char *name_end = strchrnul(name, '=');
8053 /* So far we do not check that name is valid (TODO?) */
8055 if (*name_end == '\0') {
8056 struct variable *var, **vpp;
8058 vpp = get_ptr_to_local_var(name, name_end - name);
8059 var = vpp ? *vpp : NULL;
8061 if (exp == -1) { /* unexporting? */
8062 /* export -n NAME (without =VALUE) */
8064 var->flg_export = 0;
8065 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8067 } /* else: export -n NOT_EXISTING_VAR: no-op */
8070 if (exp == 1) { /* exporting? */
8071 /* export NAME (without =VALUE) */
8073 var->flg_export = 1;
8074 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8075 putenv(var->varstr);
8079 /* Exporting non-existing variable.
8080 * bash does not put it in environment,
8081 * but remembers that it is exported,
8082 * and does put it in env when it is set later.
8083 * We just set it to "" and export. */
8084 /* Or, it's "local NAME" (without =VALUE).
8085 * bash sets the value to "". */
8086 name = xasprintf("%s=", name);
8088 /* (Un)exporting/making local NAME=VALUE */
8089 name = xstrdup(name);
8091 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8095 static int FAST_FUNC builtin_export(char **argv)
8097 unsigned opt_unexport;
8099 #if ENABLE_HUSH_EXPORT_N
8100 /* "!": do not abort on errors */
8101 opt_unexport = getopt32(argv, "!n");
8102 if (opt_unexport == (uint32_t)-1)
8103 return EXIT_FAILURE;
8110 if (argv[0] == NULL) {
8117 /* ash emits: export VAR='VAL'
8118 * bash: declare -x VAR="VAL"
8119 * we follow ash example */
8120 const char *s = *e++;
8121 const char *p = strchr(s, '=');
8123 if (!p) /* wtf? take next variable */
8126 printf("export %.*s", (int)(p - s) + 1, s);
8127 print_escaped(p + 1);
8131 /*fflush_all(); - done after each builtin anyway */
8133 return EXIT_SUCCESS;
8136 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8138 return EXIT_SUCCESS;
8141 #if ENABLE_HUSH_LOCAL
8142 static int FAST_FUNC builtin_local(char **argv)
8144 if (G.func_nest_level == 0) {
8145 bb_error_msg("%s: not in a function", argv[0]);
8146 return EXIT_FAILURE; /* bash compat */
8148 helper_export_local(argv, 0, G.func_nest_level);
8149 return EXIT_SUCCESS;
8153 static int FAST_FUNC builtin_trap(char **argv)
8159 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8164 /* No args: print all trapped */
8165 for (i = 0; i < NSIG; ++i) {
8168 print_escaped(G.traps[i]);
8169 /* note: bash adds "SIG", but only if invoked
8170 * as "bash". If called as "sh", or if set -o posix,
8171 * then it prints short signal names.
8172 * We are printing short names: */
8173 printf(" %s\n", get_signame(i));
8176 /*fflush_all(); - done after each builtin anyway */
8177 return EXIT_SUCCESS;
8181 /* If first arg is a number: reset all specified signals */
8182 sig = bb_strtou(*argv, NULL, 10);
8188 sig = get_signum(*argv++);
8189 if (sig < 0 || sig >= NSIG) {
8191 /* Mimic bash message exactly */
8192 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8197 G.traps[sig] = xstrdup(new_cmd);
8199 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8200 get_signame(sig), sig, G.traps[sig]);
8202 /* There is no signal for 0 (EXIT) */
8207 sigaddset(&G.blocked_set, sig);
8209 /* There was a trap handler, we are removing it
8210 * (if sig has non-DFL handling,
8211 * we don't need to do anything) */
8212 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8214 sigdelset(&G.blocked_set, sig);
8217 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8221 if (!argv[1]) { /* no second arg */
8222 bb_error_msg("trap: invalid arguments");
8223 return EXIT_FAILURE;
8226 /* First arg is "-": reset all specified to default */
8227 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8228 /* Everything else: set arg as signal handler
8229 * (includes "" case, which ignores signal) */
8230 if (argv[0][0] == '-') {
8231 if (argv[0][1] == '\0') { /* "-" */
8232 /* new_cmd remains NULL: "reset these sigs" */
8235 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8238 /* else: "-something", no special meaning */
8243 goto process_sig_list;
8246 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8247 static int FAST_FUNC builtin_type(char **argv)
8249 int ret = EXIT_SUCCESS;
8255 if (0) {} /* make conditional compile easier below */
8256 /*else if (find_alias(*argv))
8257 type = "an alias";*/
8258 #if ENABLE_HUSH_FUNCTIONS
8259 else if (find_function(*argv))
8260 type = "a function";
8262 else if (find_builtin(*argv))
8263 type = "a shell builtin";
8264 else if ((path = find_in_path(*argv)) != NULL)
8267 bb_error_msg("type: %s: not found", *argv);
8272 printf("%s is %s\n", *argv, type);
8280 /* built-in 'fg' and 'bg' handler */
8281 static int FAST_FUNC builtin_fg_bg(char **argv)
8286 if (!G_interactive_fd)
8287 return EXIT_FAILURE;
8289 /* If they gave us no args, assume they want the last backgrounded task */
8291 for (pi = G.job_list; pi; pi = pi->next) {
8292 if (pi->jobid == G.last_jobid) {
8296 bb_error_msg("%s: no current job", argv[0]);
8297 return EXIT_FAILURE;
8299 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8300 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8301 return EXIT_FAILURE;
8303 for (pi = G.job_list; pi; pi = pi->next) {
8304 if (pi->jobid == jobnum) {
8308 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8309 return EXIT_FAILURE;
8311 /* TODO: bash prints a string representation
8312 * of job being foregrounded (like "sleep 1 | cat") */
8313 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8314 /* Put the job into the foreground. */
8315 tcsetpgrp(G_interactive_fd, pi->pgrp);
8318 /* Restart the processes in the job */
8319 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8320 for (i = 0; i < pi->num_cmds; i++) {
8321 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8322 pi->cmds[i].is_stopped = 0;
8324 pi->stopped_cmds = 0;
8326 i = kill(- pi->pgrp, SIGCONT);
8328 if (errno == ESRCH) {
8329 delete_finished_bg_job(pi);
8330 return EXIT_SUCCESS;
8332 bb_perror_msg("kill (SIGCONT)");
8335 if (argv[0][0] == 'f') {
8337 return checkjobs_and_fg_shell(pi);
8339 return EXIT_SUCCESS;
8343 #if ENABLE_HUSH_HELP
8344 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8346 const struct built_in_command *x;
8349 "Built-in commands:\n"
8350 "------------------\n");
8351 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8353 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8356 return EXIT_SUCCESS;
8361 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8364 const char *status_string;
8366 for (job = G.job_list; job; job = job->next) {
8367 if (job->alive_cmds == job->stopped_cmds)
8368 status_string = "Stopped";
8370 status_string = "Running";
8372 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8374 return EXIT_SUCCESS;
8379 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8384 # ifdef M_TRIM_THRESHOLD
8385 /* Optional. Reduces probability of false positives */
8388 /* Crude attempt to find where "free memory" starts,
8389 * sans fragmentation. */
8391 l = (unsigned long)p;
8394 if (l < (unsigned long)p) l = (unsigned long)p;
8397 if (!G.memleak_value)
8398 G.memleak_value = l;
8400 l -= G.memleak_value;
8407 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8412 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8415 return EXIT_SUCCESS;
8418 static int FAST_FUNC builtin_read(char **argv)
8427 /* "!": do not abort on errors.
8428 * Option string must start with "sr" to match BUILTIN_READ_xxx
8430 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8431 if (read_flags == (uint32_t)-1)
8432 return EXIT_FAILURE;
8435 r = shell_builtin_read(set_local_var_from_halves,
8437 get_local_var_value("IFS"), /* can be NULL */
8445 if ((uintptr_t)r > 1) {
8446 bb_error_msg("%s", r);
8447 r = (char*)(uintptr_t)1;
8450 return (uintptr_t)r;
8453 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8454 * built-in 'set' handler
8456 * set [-abCefhmnuvx] [-o option] [argument...]
8457 * set [+abCefhmnuvx] [+o option] [argument...]
8458 * set -- [argument...]
8461 * Implementations shall support the options in both their hyphen and
8462 * plus-sign forms. These options can also be specified as options to sh.
8464 * Write out all variables and their values: set
8465 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8466 * Turn on the -x and -v options: set -xv
8467 * Unset all positional parameters: set --
8468 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8469 * Set the positional parameters to the expansion of x, even if x expands
8470 * with a leading '-' or '+': set -- $x
8472 * So far, we only support "set -- [argument...]" and some of the short names.
8474 static int FAST_FUNC builtin_set(char **argv)
8477 char **pp, **g_argv;
8478 char *arg = *++argv;
8482 for (e = G.top_var; e; e = e->next)
8484 return EXIT_SUCCESS;
8488 if (strcmp(arg, "--") == 0) {
8492 if (arg[0] != '+' && arg[0] != '-')
8494 for (n = 1; arg[n]; ++n) {
8495 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8497 if (arg[n] == 'o' && argv[1])
8500 } while ((arg = *++argv) != NULL);
8501 /* Now argv[0] is 1st argument */
8504 return EXIT_SUCCESS;
8507 /* NB: G.global_argv[0] ($0) is never freed/changed */
8508 g_argv = G.global_argv;
8509 if (G.global_args_malloced) {
8515 G.global_args_malloced = 1;
8516 pp = xzalloc(sizeof(pp[0]) * 2);
8517 pp[0] = g_argv[0]; /* retain $0 */
8520 /* This realloc's G.global_argv */
8521 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8528 return EXIT_SUCCESS;
8530 /* Nothing known, so abort */
8532 bb_error_msg("set: %s: invalid option", arg);
8533 return EXIT_FAILURE;
8536 static int FAST_FUNC builtin_shift(char **argv)
8539 argv = skip_dash_dash(argv);
8543 if (n >= 0 && n < G.global_argc) {
8544 if (G.global_args_malloced) {
8547 free(G.global_argv[m++]);
8550 memmove(&G.global_argv[1], &G.global_argv[n+1],
8551 G.global_argc * sizeof(G.global_argv[0]));
8552 return EXIT_SUCCESS;
8554 return EXIT_FAILURE;
8557 static int FAST_FUNC builtin_source(char **argv)
8559 char *arg_path, *filename;
8562 #if ENABLE_HUSH_FUNCTIONS
8566 argv = skip_dash_dash(argv);
8569 /* bash says: "bash: .: filename argument required" */
8570 return 2; /* bash compat */
8573 if (!strchr(filename, '/')) {
8574 arg_path = find_in_path(filename);
8576 filename = arg_path;
8578 input = fopen_or_warn(filename, "r");
8581 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8582 return EXIT_FAILURE;
8584 close_on_exec_on(fileno(input));
8586 #if ENABLE_HUSH_FUNCTIONS
8587 sv_flg = G.flag_return_in_progress;
8588 /* "we are inside sourced file, ok to use return" */
8589 G.flag_return_in_progress = -1;
8591 save_and_replace_G_args(&sv, argv);
8593 parse_and_run_file(input);
8596 restore_G_args(&sv, argv);
8597 #if ENABLE_HUSH_FUNCTIONS
8598 G.flag_return_in_progress = sv_flg;
8601 return G.last_exitcode;
8604 static int FAST_FUNC builtin_umask(char **argv)
8610 argv = skip_dash_dash(argv);
8612 mode_t old_mask = mask;
8615 rc = bb_parse_mode(argv[0], &mask);
8620 * bash: umask: 'q': invalid symbolic mode operator
8621 * bash: umask: 999: octal number out of range
8623 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8628 printf("%04o\n", (unsigned) mask);
8629 /* fall through and restore mask which we set to 0 */
8633 return !rc; /* rc != 0 - success */
8636 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8637 static int FAST_FUNC builtin_unset(char **argv)
8642 /* "!": do not abort on errors */
8643 /* "+": stop at 1st non-option */
8644 opts = getopt32(argv, "!+vf");
8645 if (opts == (unsigned)-1)
8646 return EXIT_FAILURE;
8648 bb_error_msg("unset: -v and -f are exclusive");
8649 return EXIT_FAILURE;
8655 if (!(opts & 2)) { /* not -f */
8656 if (unset_local_var(*argv)) {
8657 /* unset <nonexistent_var> doesn't fail.
8658 * Error is when one tries to unset RO var.
8659 * Message was printed by unset_local_var. */
8663 #if ENABLE_HUSH_FUNCTIONS
8673 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8674 static int FAST_FUNC builtin_wait(char **argv)
8676 int ret = EXIT_SUCCESS;
8679 argv = skip_dash_dash(argv);
8680 if (argv[0] == NULL) {
8681 /* Don't care about wait results */
8682 /* Note 1: must wait until there are no more children */
8683 /* Note 2: must be interruptible */
8685 * $ sleep 3 & sleep 6 & wait
8690 * $ sleep 3 & sleep 6 & wait
8694 * ^C <-- after ~4 sec from keyboard
8697 sigaddset(&G.blocked_set, SIGCHLD);
8698 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8701 if (errno == ECHILD)
8703 /* Wait for SIGCHLD or any other signal of interest */
8704 /* sigtimedwait with infinite timeout: */
8705 sig = sigwaitinfo(&G.blocked_set, NULL);
8707 sig = check_and_run_traps(sig);
8708 if (sig && sig != SIGCHLD) { /* see note 2 */
8714 sigdelset(&G.blocked_set, SIGCHLD);
8715 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8719 /* This is probably buggy wrt interruptible-ness */
8721 pid_t pid = bb_strtou(*argv, NULL, 10);
8723 /* mimic bash message */
8724 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8725 return EXIT_FAILURE;
8727 if (waitpid(pid, &status, 0) == pid) {
8728 if (WIFSIGNALED(status))
8729 ret = 128 + WTERMSIG(status);
8730 else if (WIFEXITED(status))
8731 ret = WEXITSTATUS(status);
8735 bb_perror_msg("wait %s", *argv);
8744 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8745 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8748 def = bb_strtou(argv[1], NULL, 10);
8749 if (errno || def < def_min || argv[2]) {
8750 bb_error_msg("%s: bad arguments", argv[0]);
8758 #if ENABLE_HUSH_LOOPS
8759 static int FAST_FUNC builtin_break(char **argv)
8762 if (G.depth_of_loop == 0) {
8763 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8764 return EXIT_SUCCESS; /* bash compat */
8766 G.flag_break_continue++; /* BC_BREAK = 1 */
8768 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8769 if (depth == UINT_MAX)
8770 G.flag_break_continue = BC_BREAK;
8771 if (G.depth_of_loop < depth)
8772 G.depth_break_continue = G.depth_of_loop;
8774 return EXIT_SUCCESS;
8777 static int FAST_FUNC builtin_continue(char **argv)
8779 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8780 return builtin_break(argv);
8784 #if ENABLE_HUSH_FUNCTIONS
8785 static int FAST_FUNC builtin_return(char **argv)
8789 if (G.flag_return_in_progress != -1) {
8790 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8791 return EXIT_FAILURE; /* bash compat */
8794 G.flag_return_in_progress = 1;
8797 * out of range: wraps around at 256, does not error out
8798 * non-numeric param:
8799 * f() { false; return qwe; }; f; echo $?
8800 * bash: return: qwe: numeric argument required <== we do this
8801 * 255 <== we also do this
8803 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);