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>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112 //config: bool "hush"
115 //config: hush is a small shell (25k). It handles the normal flow control
116 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117 //config: case/esac. Redirections, here documents, $((arithmetic))
118 //config: and functions are supported.
120 //config: It will compile and work on no-mmu systems.
122 //config: It does not handle select, aliases, brace expansion,
123 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
125 //config:config HUSH_BASH_COMPAT
126 //config: bool "bash-compatible extensions"
128 //config: depends on HUSH
130 //config: Enable bash-compatible extensions.
132 //config:config HUSH_HELP
133 //config: bool "help builtin"
135 //config: depends on HUSH
137 //config: Enable help builtin in hush. Code size + ~1 kbyte.
139 //config:config HUSH_INTERACTIVE
140 //config: bool "Interactive mode"
142 //config: depends on HUSH
144 //config: Enable interactive mode (prompt and command editing).
145 //config: Without this, hush simply reads and executes commands
146 //config: from stdin just like a shell script from a file.
147 //config: No prompt, no PS1/PS2 magic shell variables.
149 //config:config HUSH_JOB
150 //config: bool "Job control"
152 //config: depends on HUSH_INTERACTIVE
154 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
155 //config: command (not entire shell), fg/bg builtins work. Without this option,
156 //config: "cmd &" still works by simply spawning a process and immediately
157 //config: prompting for next command (or executing next command in a script),
158 //config: but no separate process group is formed.
160 //config:config HUSH_TICK
161 //config: bool "Process substitution"
163 //config: depends on HUSH
165 //config: Enable process substitution `command` and $(command) in hush.
167 //config:config HUSH_IF
168 //config: bool "Support if/then/elif/else/fi"
170 //config: depends on HUSH
172 //config: Enable if/then/elif/else/fi in hush.
174 //config:config HUSH_LOOPS
175 //config: bool "Support for, while and until loops"
177 //config: depends on HUSH
179 //config: Enable for, while and until loops in hush.
181 //config:config HUSH_CASE
182 //config: bool "Support case ... esac statement"
184 //config: depends on HUSH
186 //config: Enable case ... esac statement in hush. +400 bytes.
188 //config:config HUSH_FUNCTIONS
189 //config: bool "Support funcname() { commands; } syntax"
191 //config: depends on HUSH
193 //config: Enable support for shell functions in hush. +800 bytes.
195 //config:config HUSH_LOCAL
196 //config: bool "Support local builtin"
198 //config: depends on HUSH_FUNCTIONS
200 //config: Enable support for local variables in functions.
202 //config:config HUSH_RANDOM_SUPPORT
203 //config: bool "Pseudorandom generator and $RANDOM variable"
205 //config: depends on HUSH
207 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
208 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
210 //config:config HUSH_EXPORT_N
211 //config: bool "Support 'export -n' option"
213 //config: depends on HUSH
215 //config: export -n unexports variables. It is a bash extension.
217 //config:config HUSH_MODE_X
218 //config: bool "Support 'hush -x' option and 'set -x' command"
220 //config: depends on HUSH
222 //config: This instructs hush to print commands before execution.
223 //config: Adds ~300 bytes.
226 //config: bool "msh (deprecated: aliased to hush)"
228 //config: select HUSH
230 //config: msh is deprecated and will be removed, please migrate to hush.
233 //usage:#define hush_trivial_usage NOUSAGE_STR
234 //usage:#define hush_full_usage ""
235 //usage:#define msh_trivial_usage NOUSAGE_STR
236 //usage:#define msh_full_usage ""
240 #define LEAK_HUNTING 0
241 #define BUILD_AS_NOMMU 0
242 /* Enable/disable sanity checks. Ok to enable in production,
243 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
244 * Keeping 1 for now even in released versions.
247 /* Slightly bigger (+200 bytes), but faster hush.
248 * So far it only enables a trick with counting SIGCHLDs and forks,
249 * which allows us to do fewer waitpid's.
250 * (we can detect a case where neither forks were done nor SIGCHLDs happened
251 * and therefore waitpid will return the same result as last time)
253 #define ENABLE_HUSH_FAST 0
254 /* TODO: implement simplified code for users which do not need ${var%...} ops
255 * So far ${var%...} ops are always enabled:
257 #define ENABLE_HUSH_DOLLAR_OPS 1
262 # undef USE_FOR_NOMMU
265 # define USE_FOR_NOMMU(...) __VA_ARGS__
266 # define USE_FOR_MMU(...)
269 #include "NUM_APPLETS.h"
271 /* STANDALONE does not make sense, and won't compile */
272 # undef CONFIG_FEATURE_SH_STANDALONE
273 # undef ENABLE_FEATURE_SH_STANDALONE
274 # undef IF_FEATURE_SH_STANDALONE
275 # undef IF_NOT_FEATURE_SH_STANDALONE
276 # define ENABLE_FEATURE_SH_STANDALONE 0
277 # define IF_FEATURE_SH_STANDALONE(...)
278 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
281 #if !ENABLE_HUSH_INTERACTIVE
282 # undef ENABLE_FEATURE_EDITING
283 # define ENABLE_FEATURE_EDITING 0
284 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
285 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
288 /* Do we support ANY keywords? */
289 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
290 # define HAS_KEYWORDS 1
291 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
292 # define IF_HAS_NO_KEYWORDS(...)
294 # define HAS_KEYWORDS 0
295 # define IF_HAS_KEYWORDS(...)
296 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
299 /* If you comment out one of these below, it will be #defined later
300 * to perform debug printfs to stderr: */
301 #define debug_printf(...) do {} while (0)
302 /* Finer-grained debug switches */
303 #define debug_printf_parse(...) do {} while (0)
304 #define debug_print_tree(a, b) do {} while (0)
305 #define debug_printf_exec(...) do {} while (0)
306 #define debug_printf_env(...) do {} while (0)
307 #define debug_printf_jobs(...) do {} while (0)
308 #define debug_printf_expand(...) do {} while (0)
309 #define debug_printf_varexp(...) do {} while (0)
310 #define debug_printf_glob(...) do {} while (0)
311 #define debug_printf_list(...) do {} while (0)
312 #define debug_printf_subst(...) do {} while (0)
313 #define debug_printf_clean(...) do {} while (0)
315 #define ERR_PTR ((void*)(long)1)
317 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
319 #define _SPECIAL_VARS_STR "_*@$!?#"
320 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
321 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
322 #if ENABLE_HUSH_BASH_COMPAT
323 /* Support / and // replace ops */
324 /* Note that // is stored as \ in "encoded" string representation */
325 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
326 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
327 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
329 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
330 # define VAR_SUBST_OPS "%#:-=+?"
331 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
334 #define SPECIAL_VAR_SYMBOL 3
338 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
340 /* This supports saving pointers malloced in vfork child,
341 * to be freed in the parent.
344 typedef struct nommu_save_t {
346 struct variable *old_vars;
348 char **argv_from_re_execing;
352 typedef enum reserved_style {
361 #if ENABLE_HUSH_LOOPS
368 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
373 /* three pseudo-keywords support contrived "case" syntax: */
374 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
375 RES_MATCH , /* "word)" */
376 RES_CASE_BODY, /* "this command is inside CASE" */
383 typedef struct o_string {
385 int length; /* position where data is appended */
387 /* Protect newly added chars against globbing
388 * (by prepending \ to *, ?, [, \) */
391 /* At least some part of the string was inside '' or "",
392 * possibly empty one: word"", wo''rd etc. */
393 smallint has_quoted_part;
394 smallint has_empty_slot;
395 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
398 MAYBE_ASSIGNMENT = 0,
399 DEFINITELY_ASSIGNMENT = 1,
401 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
403 /* Used for initialization: o_string foo = NULL_O_STRING; */
404 #define NULL_O_STRING { NULL }
406 /* I can almost use ordinary FILE*. Is open_memstream() universally
407 * available? Where is it documented? */
408 typedef struct in_str {
410 /* eof_flag=1: last char in ->p is really an EOF */
411 char eof_flag; /* meaningless if ->p == NULL */
413 #if ENABLE_HUSH_INTERACTIVE
415 smallint promptmode; /* 0: PS1, 1: PS2 */
418 int (*get) (struct in_str *) FAST_FUNC;
419 int (*peek) (struct in_str *) FAST_FUNC;
421 #define i_getch(input) ((input)->get(input))
422 #define i_peek(input) ((input)->peek(input))
424 /* The descrip member of this structure is only used to make
425 * debugging output pretty */
426 static const struct {
428 signed char default_fd;
431 { O_RDONLY, 0, "<" },
432 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
433 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
434 { O_CREAT|O_RDWR, 1, "<>" },
435 { O_RDONLY, 0, "<<" },
436 /* Should not be needed. Bogus default_fd helps in debugging */
437 /* { O_RDONLY, 77, "<<" }, */
440 struct redir_struct {
441 struct redir_struct *next;
442 char *rd_filename; /* filename */
443 int rd_fd; /* fd to redirect */
444 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
446 smallint rd_type; /* (enum redir_type) */
447 /* note: for heredocs, rd_filename contains heredoc delimiter,
448 * and subsequently heredoc itself; and rd_dup is a bitmask:
449 * bit 0: do we need to trim leading tabs?
450 * bit 1: is heredoc quoted (<<'delim' syntax) ?
453 typedef enum redir_type {
455 REDIRECT_OVERWRITE = 1,
458 REDIRECT_HEREDOC = 4,
459 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
462 REDIRFD_SYNTAX_ERR = -2,
463 REDIRFD_TO_FILE = -1,
464 /* otherwise, rd_fd is redirected to rd_dup */
466 HEREDOC_SKIPTABS = 1,
472 pid_t pid; /* 0 if exited */
473 int assignment_cnt; /* how many argv[i] are assignments? */
474 smallint is_stopped; /* is the command currently running? */
475 smallint cmd_type; /* CMD_xxx */
477 #define CMD_SUBSHELL 1
479 /* used for "[[ EXPR ]]" */
480 #if ENABLE_HUSH_BASH_COMPAT
481 # define CMD_SINGLEWORD_NOGLOB 2
484 /* used for "export noglob=* glob* a=`echo a b`" */
485 //#define CMD_SINGLEWORD_NOGLOB_COND 3
486 // It is hard to implement correctly, it adds significant amounts of tricky code,
487 // and all this is only useful for really obscure export statements
488 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
489 // guards the code which implements it, but I have doubts it works
490 // in all cases (especially with mixed globbed/non-globbed arguments)
492 #if ENABLE_HUSH_FUNCTIONS
493 # define CMD_FUNCDEF 3
496 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
499 char *group_as_string;
501 #if ENABLE_HUSH_FUNCTIONS
502 struct function *child_func;
503 /* This field is used to prevent a bug here:
504 * while...do f1() {a;}; f1; f1() {b;}; f1; done
505 * When we execute "f1() {a;}" cmd, we create new function and clear
506 * cmd->group, cmd->group_as_string, cmd->argv[0].
507 * When we execute "f1() {b;}", we notice that f1 exists,
508 * and that its "parent cmd" struct is still "alive",
509 * we put those fields back into cmd->xxx
510 * (struct function has ->parent_cmd ptr to facilitate that).
511 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
512 * Without this trick, loop would execute a;b;b;b;...
513 * instead of correct sequence a;b;a;b;...
514 * When command is freed, it severs the link
515 * (sets ->child_func->parent_cmd to NULL).
518 char **argv; /* command name and arguments */
519 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
520 * and on execution these are substituted with their values.
521 * Substitution can make _several_ words out of one argv[n]!
522 * Example: argv[0]=='.^C*^C.' here: echo .$*.
523 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
525 struct redir_struct *redirects; /* I/O redirections */
527 /* Is there anything in this command at all? */
528 #define IS_NULL_CMD(cmd) \
529 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
534 int num_cmds; /* total number of commands in pipe */
535 int alive_cmds; /* number of commands running (not exited) */
536 int stopped_cmds; /* number of commands alive, but stopped */
538 int jobid; /* job number */
539 pid_t pgrp; /* process group ID for the job */
540 char *cmdtext; /* name of job */
542 struct command *cmds; /* array of commands in pipe */
543 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
544 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
545 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
547 typedef enum pipe_style {
553 /* Is there anything in this pipe at all? */
554 #define IS_NULL_PIPE(pi) \
555 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
557 /* This holds pointers to the various results of parsing */
558 struct parse_context {
559 /* linked list of pipes */
560 struct pipe *list_head;
561 /* last pipe (being constructed right now) */
563 /* last command in pipe (being constructed right now) */
564 struct command *command;
565 /* last redirect in command->redirects list */
566 struct redir_struct *pending_redirect;
572 smallint ctx_inverted; /* "! cmd | cmd" */
574 smallint ctx_dsemicolon; /* ";;" seen */
576 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
578 /* group we are enclosed in:
579 * example: "if pipe1; pipe2; then pipe3; fi"
580 * when we see "if" or "then", we malloc and copy current context,
581 * and make ->stack point to it. then we parse pipeN.
582 * when closing "then" / fi" / whatever is found,
583 * we move list_head into ->stack->command->group,
584 * copy ->stack into current context, and delete ->stack.
585 * (parsing of { list } and ( list ) doesn't use this method)
587 struct parse_context *stack;
591 /* On program start, environ points to initial environment.
592 * putenv adds new pointers into it, unsetenv removes them.
593 * Neither of these (de)allocates the strings.
594 * setenv allocates new strings in malloc space and does putenv,
595 * and thus setenv is unusable (leaky) for shell's purposes */
596 #define setenv(...) setenv_is_leaky_dont_use()
598 struct variable *next;
599 char *varstr; /* points to "name=" portion */
600 #if ENABLE_HUSH_LOCAL
601 unsigned func_nest_level;
603 int max_len; /* if > 0, name is part of initial env; else name is malloced */
604 smallint flg_export; /* putenv should be done on this var */
605 smallint flg_read_only;
613 #if ENABLE_HUSH_FUNCTIONS
615 struct function *next;
617 struct command *parent_cmd;
620 char *body_as_string;
626 /* "Globals" within this file */
627 /* Sorted roughly by size (smaller offsets == smaller code) */
629 /* interactive_fd != 0 means we are an interactive shell.
630 * If we are, then saved_tty_pgrp can also be != 0, meaning
631 * that controlling tty is available. With saved_tty_pgrp == 0,
632 * job control still works, but terminal signals
633 * (^C, ^Z, ^Y, ^\) won't work at all, and background
634 * process groups can only be created with "cmd &".
635 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
636 * to give tty to the foreground process group,
637 * and will take it back when the group is stopped (^Z)
640 #if ENABLE_HUSH_INTERACTIVE
641 /* 'interactive_fd' is a fd# open to ctty, if we have one
642 * _AND_ if we decided to act interactively */
646 # define G_interactive_fd (G.interactive_fd)
648 # define G_interactive_fd 0
650 #if ENABLE_FEATURE_EDITING
651 line_input_t *line_input_state;
656 #if ENABLE_HUSH_RANDOM_SUPPORT
662 pid_t saved_tty_pgrp;
663 struct pipe *job_list;
664 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
666 # define G_saved_tty_pgrp 0
668 smallint flag_SIGINT;
669 #if ENABLE_HUSH_LOOPS
670 smallint flag_break_continue;
672 #if ENABLE_HUSH_FUNCTIONS
673 /* 0: outside of a function (or sourced file)
674 * -1: inside of a function, ok to use return builtin
675 * 1: return is invoked, skip all till end of func
677 smallint flag_return_in_progress;
680 #if ENABLE_HUSH_MODE_X
682 # define G_x_mode (G.x_mode)
686 smallint exiting; /* used to prevent EXIT trap recursion */
687 /* These four support $?, $#, and $1 */
688 smalluint last_exitcode;
689 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
690 smalluint global_args_malloced;
691 smalluint inherited_set_is_saved;
692 /* how many non-NULL argv's we have. NB: $# + 1 */
696 char *argv0_for_re_execing;
698 #if ENABLE_HUSH_LOOPS
699 unsigned depth_break_continue;
700 unsigned depth_of_loop;
704 struct variable *top_var; /* = &G.shell_ver (set in main()) */
705 struct variable shell_ver;
706 char **expanded_assignments;
707 #if ENABLE_HUSH_FUNCTIONS
708 struct function *top_func;
709 # if ENABLE_HUSH_LOCAL
710 struct variable **shadowed_vars_pp;
711 unsigned func_nest_level;
714 /* Signal and trap handling */
716 unsigned count_SIGCHLD;
717 unsigned handled_SIGCHLD;
718 smallint we_have_children;
720 /* which signals have non-DFL handler (even with no traps set)? */
721 unsigned non_DFL_mask;
722 char **traps; /* char *traps[NSIG] */
723 sigset_t blocked_set;
724 sigset_t inherited_set;
726 unsigned long memleak_value;
729 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
731 #define G (*ptr_to_globals)
732 /* Not #defining name to G.name - this quickly gets unwieldy
733 * (too many defines). Also, I actually prefer to see when a variable
734 * is global, thus "G." prefix is a useful hint */
735 #define INIT_G() do { \
736 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
740 /* Function prototypes for builtins */
741 static int builtin_cd(char **argv) FAST_FUNC;
742 static int builtin_echo(char **argv) FAST_FUNC;
743 static int builtin_eval(char **argv) FAST_FUNC;
744 static int builtin_exec(char **argv) FAST_FUNC;
745 static int builtin_exit(char **argv) FAST_FUNC;
746 static int builtin_export(char **argv) FAST_FUNC;
748 static int builtin_fg_bg(char **argv) FAST_FUNC;
749 static int builtin_jobs(char **argv) FAST_FUNC;
752 static int builtin_help(char **argv) FAST_FUNC;
754 #if ENABLE_HUSH_LOCAL
755 static int builtin_local(char **argv) FAST_FUNC;
758 static int builtin_memleak(char **argv) FAST_FUNC;
761 static int builtin_printf(char **argv) FAST_FUNC;
763 static int builtin_pwd(char **argv) FAST_FUNC;
764 static int builtin_read(char **argv) FAST_FUNC;
765 static int builtin_set(char **argv) FAST_FUNC;
766 static int builtin_shift(char **argv) FAST_FUNC;
767 static int builtin_source(char **argv) FAST_FUNC;
768 static int builtin_test(char **argv) FAST_FUNC;
769 static int builtin_trap(char **argv) FAST_FUNC;
770 static int builtin_type(char **argv) FAST_FUNC;
771 static int builtin_true(char **argv) FAST_FUNC;
772 static int builtin_umask(char **argv) FAST_FUNC;
773 static int builtin_unset(char **argv) FAST_FUNC;
774 static int builtin_wait(char **argv) FAST_FUNC;
775 #if ENABLE_HUSH_LOOPS
776 static int builtin_break(char **argv) FAST_FUNC;
777 static int builtin_continue(char **argv) FAST_FUNC;
779 #if ENABLE_HUSH_FUNCTIONS
780 static int builtin_return(char **argv) FAST_FUNC;
783 /* Table of built-in functions. They can be forked or not, depending on
784 * context: within pipes, they fork. As simple commands, they do not.
785 * When used in non-forking context, they can change global variables
786 * in the parent shell process. If forked, of course they cannot.
787 * For example, 'unset foo | whatever' will parse and run, but foo will
788 * still be set at the end. */
789 struct built_in_command {
791 int (*b_function)(char **argv) FAST_FUNC;
794 # define BLTIN(cmd, func, help) { cmd, func, help }
796 # define BLTIN(cmd, func, help) { cmd, func }
800 static const struct built_in_command bltins1[] = {
801 BLTIN("." , builtin_source , "Run commands in a file"),
802 BLTIN(":" , builtin_true , NULL),
804 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
806 #if ENABLE_HUSH_LOOPS
807 BLTIN("break" , builtin_break , "Exit from a loop"),
809 BLTIN("cd" , builtin_cd , "Change directory"),
810 #if ENABLE_HUSH_LOOPS
811 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
813 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
814 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
815 BLTIN("exit" , builtin_exit , "Exit"),
816 BLTIN("export" , builtin_export , "Set environment variables"),
818 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
821 BLTIN("help" , builtin_help , NULL),
824 BLTIN("jobs" , builtin_jobs , "List jobs"),
826 #if ENABLE_HUSH_LOCAL
827 BLTIN("local" , builtin_local , "Set local variables"),
830 BLTIN("memleak" , builtin_memleak , NULL),
832 BLTIN("read" , builtin_read , "Input into variable"),
833 #if ENABLE_HUSH_FUNCTIONS
834 BLTIN("return" , builtin_return , "Return from a function"),
836 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
837 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
838 #if ENABLE_HUSH_BASH_COMPAT
839 BLTIN("source" , builtin_source , "Run commands in a file"),
841 BLTIN("trap" , builtin_trap , "Trap signals"),
842 BLTIN("type" , builtin_type , "Show command type"),
843 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
844 BLTIN("umask" , builtin_umask , "Set file creation mask"),
845 BLTIN("unset" , builtin_unset , "Unset variables"),
846 BLTIN("wait" , builtin_wait , "Wait for process"),
848 /* For now, echo and test are unconditionally enabled.
849 * Maybe make it configurable? */
850 static const struct built_in_command bltins2[] = {
851 BLTIN("[" , builtin_test , NULL),
852 BLTIN("echo" , builtin_echo , NULL),
854 BLTIN("printf" , builtin_printf , NULL),
856 BLTIN("pwd" , builtin_pwd , NULL),
857 BLTIN("test" , builtin_test , NULL),
864 /* prevent disasters with G.debug_indent < 0 */
865 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
866 # define debug_enter() (G.debug_indent++)
867 # define debug_leave() (G.debug_indent--)
869 # define indent() ((void)0)
870 # define debug_enter() ((void)0)
871 # define debug_leave() ((void)0)
875 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
878 #ifndef debug_printf_parse
879 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
882 #ifndef debug_printf_exec
883 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
886 #ifndef debug_printf_env
887 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
890 #ifndef debug_printf_jobs
891 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 # define DEBUG_JOBS 1
894 # define DEBUG_JOBS 0
897 #ifndef debug_printf_expand
898 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
899 # define DEBUG_EXPAND 1
901 # define DEBUG_EXPAND 0
904 #ifndef debug_printf_varexp
905 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
908 #ifndef debug_printf_glob
909 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
910 # define DEBUG_GLOB 1
912 # define DEBUG_GLOB 0
915 #ifndef debug_printf_list
916 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
919 #ifndef debug_printf_subst
920 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
923 #ifndef debug_printf_clean
924 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
925 # define DEBUG_CLEAN 1
927 # define DEBUG_CLEAN 0
931 static void debug_print_strings(const char *prefix, char **vv)
934 fprintf(stderr, "%s:\n", prefix);
936 fprintf(stderr, " '%s'\n", *vv++);
939 # define debug_print_strings(prefix, vv) ((void)0)
943 /* Leak hunting. Use hush_leaktool.sh for post-processing.
946 static void *xxmalloc(int lineno, size_t size)
948 void *ptr = xmalloc((size + 0xff) & ~0xff);
949 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
952 static void *xxrealloc(int lineno, void *ptr, size_t size)
954 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
955 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
958 static char *xxstrdup(int lineno, const char *str)
960 char *ptr = xstrdup(str);
961 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
964 static void xxfree(void *ptr)
966 fdprintf(2, "free %p\n", ptr);
969 # define xmalloc(s) xxmalloc(__LINE__, s)
970 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
971 # define xstrdup(s) xxstrdup(__LINE__, s)
972 # define free(p) xxfree(p)
976 /* Syntax and runtime errors. They always abort scripts.
977 * In interactive use they usually discard unparsed and/or unexecuted commands
978 * and return to the prompt.
979 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
982 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
983 # define syntax_error(lineno, msg) syntax_error(msg)
984 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
985 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
986 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
987 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
990 static void die_if_script(unsigned lineno, const char *fmt, ...)
995 bb_error_msg("hush.c:%u", lineno);
998 bb_verror_msg(fmt, p, NULL);
1000 if (!G_interactive_fd)
1004 static void syntax_error(unsigned lineno, const char *msg)
1007 die_if_script(lineno, "syntax error: %s", msg);
1009 die_if_script(lineno, "syntax error", NULL);
1012 static void syntax_error_at(unsigned lineno, const char *msg)
1014 die_if_script(lineno, "syntax error at '%s'", msg);
1017 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1019 die_if_script(lineno, "syntax error: unterminated %s", s);
1022 /* It so happens that all such cases are totally fatal
1023 * even if shell is interactive: EOF while looking for closing
1024 * delimiter. There is nowhere to read stuff from after that,
1025 * it's EOF! The only choice is to terminate.
1027 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1028 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1030 char msg[2] = { ch, '\0' };
1031 syntax_error_unterm_str(lineno, msg);
1035 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1040 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1044 # undef die_if_script
1045 # undef syntax_error
1046 # undef syntax_error_at
1047 # undef syntax_error_unterm_ch
1048 # undef syntax_error_unterm_str
1049 # undef syntax_error_unexpected_ch
1051 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1052 # define syntax_error(msg) syntax_error(__LINE__, msg)
1053 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1054 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1055 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1056 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1060 #if ENABLE_HUSH_INTERACTIVE
1061 static void cmdedit_update_prompt(void);
1063 # define cmdedit_update_prompt() ((void)0)
1067 /* Utility functions
1069 /* Replace each \x with x in place, return ptr past NUL. */
1070 static char *unbackslash(char *src)
1072 char *dst = src = strchrnul(src, '\\');
1076 if ((*dst++ = *src++) == '\0')
1082 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1103 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1104 v[count1 + count2] = NULL;
1107 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1111 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1113 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1114 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1117 #define add_strings_to_strings(strings, add, need_to_dup) \
1118 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1121 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1122 static char **add_string_to_strings(char **strings, char *add)
1127 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1130 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1132 char **ptr = add_string_to_strings(strings, add);
1133 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1136 #define add_string_to_strings(strings, add) \
1137 xx_add_string_to_strings(__LINE__, strings, add)
1140 static void free_strings(char **strings)
1155 /* Helpers for setting new $n and restoring them back
1157 typedef struct save_arg_t {
1161 smallint sv_g_malloced;
1164 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1168 sv->sv_argv0 = argv[0];
1169 sv->sv_g_argv = G.global_argv;
1170 sv->sv_g_argc = G.global_argc;
1171 sv->sv_g_malloced = G.global_args_malloced;
1173 argv[0] = G.global_argv[0]; /* retain $0 */
1174 G.global_argv = argv;
1175 G.global_args_malloced = 0;
1183 static void restore_G_args(save_arg_t *sv, char **argv)
1187 if (G.global_args_malloced) {
1188 /* someone ran "set -- arg1 arg2 ...", undo */
1190 while (*++pp) /* note: does not free $0 */
1192 free(G.global_argv);
1194 argv[0] = sv->sv_argv0;
1195 G.global_argv = sv->sv_g_argv;
1196 G.global_argc = sv->sv_g_argc;
1197 G.global_args_malloced = sv->sv_g_malloced;
1201 /* Basic theory of signal handling in shell
1202 * ========================================
1203 * This does not describe what hush does, rather, it is current understanding
1204 * what it _should_ do. If it doesn't, it's a bug.
1205 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1207 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1208 * is finished or backgrounded. It is the same in interactive and
1209 * non-interactive shells, and is the same regardless of whether
1210 * a user trap handler is installed or a shell special one is in effect.
1211 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1212 * backgrounds (i.e. stops) or kills all members of currently running
1215 * Wait builtin in interruptible by signals for which user trap is set
1216 * or by SIGINT in interactive shell.
1218 * Trap handlers will execute even within trap handlers. (right?)
1220 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1221 * except for handlers set to '' (empty string).
1223 * If job control is off, backgrounded commands ("cmd &")
1224 * have SIGINT, SIGQUIT set to SIG_IGN.
1226 * Commands which are run in command substitution ("`cmd`")
1227 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1229 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1230 * by the shell from its parent.
1232 * Signals which differ from SIG_DFL action
1233 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1236 * SIGTERM (interactive): ignore
1237 * SIGHUP (interactive):
1238 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1239 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1240 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1241 * that all pipe members are stopped. Try this in bash:
1242 * while :; do :; done - ^Z does not background it
1243 * (while :; do :; done) - ^Z backgrounds it
1244 * SIGINT (interactive): wait for last pipe, ignore the rest
1245 * of the command line, show prompt. NB: ^C does not send SIGINT
1246 * to interactive shell while shell is waiting for a pipe,
1247 * since shell is bg'ed (is not in foreground process group).
1248 * Example 1: this waits 5 sec, but does not execute ls:
1249 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1250 * Example 2: this does not wait and does not execute ls:
1251 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1252 * Example 3: this does not wait 5 sec, but executes ls:
1253 * "sleep 5; ls -l" + press ^C
1255 * (What happens to signals which are IGN on shell start?)
1256 * (What happens with signal mask on shell start?)
1258 * Implementation in hush
1259 * ======================
1260 * We use in-kernel pending signal mask to determine which signals were sent.
1261 * We block all signals which we don't want to take action immediately,
1262 * i.e. we block all signals which need to have special handling as described
1263 * above, and all signals which have traps set.
1264 * After each pipe execution, we extract any pending signals via sigtimedwait()
1267 * unsigned non_DFL_mask: a mask of such "special" signals
1268 * sigset_t blocked_set: current blocked signal set
1271 * clear bit in blocked_set unless it is also in non_DFL_mask
1272 * "trap 'cmd' SIGxxx":
1273 * set bit in blocked_set (even if 'cmd' is '')
1274 * after [v]fork, if we plan to be a shell:
1275 * unblock signals with special interactive handling
1276 * (child shell is not interactive),
1277 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1278 * after [v]fork, if we plan to exec:
1279 * POSIX says fork clears pending signal mask in child - no need to clear it.
1280 * Restore blocked signal set to one inherited by shell just prior to exec.
1282 * Note: as a result, we do not use signal handlers much. The only uses
1283 * are to count SIGCHLDs
1284 * and to restore tty pgrp on signal-induced exit.
1287 * Standard says "When a subshell is entered, traps that are not being ignored
1288 * are set to the default actions". bash interprets it so that traps which
1289 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1292 SPECIAL_INTERACTIVE_SIGS = 0
1297 SPECIAL_JOB_SIGS = 0
1305 #if ENABLE_HUSH_FAST
1306 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1309 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1315 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1316 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1317 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1318 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1320 /* Restores tty foreground process group, and exits.
1321 * May be called as signal handler for fatal signal
1322 * (will resend signal to itself, producing correct exit state)
1323 * or called directly with -EXITCODE.
1324 * We also call it if xfunc is exiting. */
1325 static void sigexit(int sig) NORETURN;
1326 static void sigexit(int sig)
1328 /* Disable all signals: job control, SIGPIPE, etc. */
1329 sigprocmask_allsigs(SIG_BLOCK);
1331 /* Careful: we can end up here after [v]fork. Do not restore
1332 * tty pgrp then, only top-level shell process does that */
1333 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1334 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1336 /* Not a signal, just exit */
1340 kill_myself_with_sig(sig); /* does not return */
1344 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1345 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1349 /* Restores tty foreground process group, and exits. */
1350 static void hush_exit(int exitcode) NORETURN;
1351 static void hush_exit(int exitcode)
1353 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1354 /* Prevent recursion:
1355 * trap "echo Hi; exit" EXIT; exit
1357 char *argv[] = { NULL, G.traps[0], NULL };
1366 sigexit(- (exitcode & 0xff));
1372 static int check_and_run_traps(int sig)
1374 static const struct timespec zero_timespec;
1375 smalluint save_rcode;
1381 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1386 if (G.traps && G.traps[sig]) {
1387 if (G.traps[sig][0]) {
1388 /* We have user-defined handler */
1389 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1390 save_rcode = G.last_exitcode;
1393 G.last_exitcode = save_rcode;
1394 } /* else: "" trap, ignoring signal */
1397 /* not a trap: special action */
1399 #if ENABLE_HUSH_FAST
1402 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1406 /* Builtin was ^C'ed, make it look prettier: */
1413 /* bash is observed to signal whole process groups,
1414 * not individual processes */
1415 for (job = G.job_list; job; job = job->next) {
1418 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1419 if (kill(- job->pgrp, SIGHUP) == 0)
1420 kill(- job->pgrp, SIGCONT);
1425 default: /* ignored: */
1426 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1434 static const char *get_cwd(int force)
1436 if (force || G.cwd == NULL) {
1437 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1438 * we must not try to free(bb_msg_unknown) */
1439 if (G.cwd == bb_msg_unknown)
1441 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1443 G.cwd = bb_msg_unknown;
1450 * Shell and environment variable support
1452 static struct variable **get_ptr_to_local_var(const char *name)
1454 struct variable **pp;
1455 struct variable *cur;
1460 while ((cur = *pp) != NULL) {
1461 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1468 static struct variable *get_local_var(const char *name)
1470 struct variable **pp = get_ptr_to_local_var(name);
1476 static const char* FAST_FUNC get_local_var_value(const char *name)
1478 struct variable **vpp;
1480 if (G.expanded_assignments) {
1481 char **cpp = G.expanded_assignments;
1482 int len = strlen(name);
1485 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1486 return cp + len + 1;
1491 vpp = get_ptr_to_local_var(name);
1493 return strchr((*vpp)->varstr, '=') + 1;
1495 if (strcmp(name, "PPID") == 0)
1496 return utoa(G.root_ppid);
1497 // bash compat: UID? EUID?
1498 #if ENABLE_HUSH_RANDOM_SUPPORT
1499 if (strcmp(name, "RANDOM") == 0) {
1500 return utoa(next_random(&G.random_gen));
1506 /* str holds "NAME=VAL" and is expected to be malloced.
1507 * We take ownership of it.
1509 * 0: do not change export flag
1510 * (if creating new variable, flag will be 0)
1511 * 1: set export flag and putenv the variable
1512 * -1: clear export flag and unsetenv the variable
1513 * flg_read_only is set only when we handle -R var=val
1515 #if !BB_MMU && ENABLE_HUSH_LOCAL
1516 /* all params are used */
1517 #elif BB_MMU && ENABLE_HUSH_LOCAL
1518 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1519 set_local_var(str, flg_export, local_lvl)
1520 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1521 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1522 set_local_var(str, flg_export)
1523 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1524 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1525 set_local_var(str, flg_export, flg_read_only)
1527 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1529 struct variable **var_pp;
1530 struct variable *cur;
1534 eq_sign = strchr(str, '=');
1535 if (!eq_sign) { /* not expected to ever happen? */
1540 name_len = eq_sign - str + 1; /* including '=' */
1541 var_pp = &G.top_var;
1542 while ((cur = *var_pp) != NULL) {
1543 if (strncmp(cur->varstr, str, name_len) != 0) {
1544 var_pp = &cur->next;
1547 /* We found an existing var with this name */
1548 if (cur->flg_read_only) {
1552 bb_error_msg("%s: readonly variable", str);
1556 if (flg_export == -1) { // "&& cur->flg_export" ?
1557 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1562 #if ENABLE_HUSH_LOCAL
1563 if (cur->func_nest_level < local_lvl) {
1564 /* New variable is declared as local,
1565 * and existing one is global, or local
1566 * from enclosing function.
1567 * Remove and save old one: */
1568 *var_pp = cur->next;
1569 cur->next = *G.shadowed_vars_pp;
1570 *G.shadowed_vars_pp = cur;
1571 /* bash 3.2.33(1) and exported vars:
1573 * # f() { local z=a; env | grep ^z; }
1579 if (cur->flg_export)
1584 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1589 if (cur->max_len != 0) {
1590 if (cur->max_len >= strlen(str)) {
1591 /* This one is from startup env, reuse space */
1592 strcpy(cur->varstr, str);
1596 /* max_len == 0 signifies "malloced" var, which we can
1597 * (and has to) free */
1601 goto set_str_and_exp;
1604 /* Not found - create new variable struct */
1605 cur = xzalloc(sizeof(*cur));
1606 #if ENABLE_HUSH_LOCAL
1607 cur->func_nest_level = local_lvl;
1609 cur->next = *var_pp;
1615 cur->flg_read_only = flg_read_only;
1618 if (flg_export == 1)
1619 cur->flg_export = 1;
1620 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1621 cmdedit_update_prompt();
1622 if (cur->flg_export) {
1623 if (flg_export == -1) {
1624 cur->flg_export = 0;
1625 /* unsetenv was already done */
1627 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1628 return putenv(cur->varstr);
1634 /* Used at startup and after each cd */
1635 static void set_pwd_var(int exp)
1637 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1638 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1641 static int unset_local_var_len(const char *name, int name_len)
1643 struct variable *cur;
1644 struct variable **var_pp;
1647 return EXIT_SUCCESS;
1648 var_pp = &G.top_var;
1649 while ((cur = *var_pp) != NULL) {
1650 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1651 if (cur->flg_read_only) {
1652 bb_error_msg("%s: readonly variable", name);
1653 return EXIT_FAILURE;
1655 *var_pp = cur->next;
1656 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1657 bb_unsetenv(cur->varstr);
1658 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1659 cmdedit_update_prompt();
1663 return EXIT_SUCCESS;
1665 var_pp = &cur->next;
1667 return EXIT_SUCCESS;
1670 static int unset_local_var(const char *name)
1672 return unset_local_var_len(name, strlen(name));
1675 static void unset_vars(char **strings)
1683 const char *eq = strchrnul(*v, '=');
1684 unset_local_var_len(*v, (int)(eq - *v));
1690 #if ENABLE_SH_MATH_SUPPORT
1691 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1692 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1693 static char* FAST_FUNC endofname(const char *name)
1701 if (!is_in_name(*p))
1708 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1710 char *var = xasprintf("%s=%s", name, val);
1711 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1716 * Helpers for "var1=val1 var2=val2 cmd" feature
1718 static void add_vars(struct variable *var)
1720 struct variable *next;
1724 var->next = G.top_var;
1726 if (var->flg_export) {
1727 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1728 putenv(var->varstr);
1730 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1736 static struct variable *set_vars_and_save_old(char **strings)
1739 struct variable *old = NULL;
1745 struct variable *var_p;
1746 struct variable **var_pp;
1749 eq = strchr(*s, '=');
1752 var_pp = get_ptr_to_local_var(*s);
1755 /* Remove variable from global linked list */
1757 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1758 *var_pp = var_p->next;
1759 /* Add it to returned list */
1763 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1774 static int FAST_FUNC static_get(struct in_str *i)
1784 static int FAST_FUNC static_peek(struct in_str *i)
1789 #if ENABLE_HUSH_INTERACTIVE
1791 static void cmdedit_update_prompt(void)
1793 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1794 G.PS1 = get_local_var_value("PS1");
1797 G.PS2 = get_local_var_value("PS2");
1805 static const char* setup_prompt_string(int promptmode)
1807 const char *prompt_str;
1808 debug_printf("setup_prompt_string %d ", promptmode);
1809 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1810 /* Set up the prompt */
1811 if (promptmode == 0) { /* PS1 */
1813 /* bash uses $PWD value, even if it is set by user.
1814 * It uses current dir only if PWD is unset.
1815 * We always use current dir. */
1816 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1821 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1822 debug_printf("result '%s'\n", prompt_str);
1826 static void get_user_input(struct in_str *i)
1829 const char *prompt_str;
1831 prompt_str = setup_prompt_string(i->promptmode);
1832 # if ENABLE_FEATURE_EDITING
1833 /* Enable command line editing only while a command line
1834 * is actually being read */
1837 /* buglet: SIGINT will not make new prompt to appear _at once_,
1838 * only after <Enter>. (^C will work) */
1839 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1840 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1841 check_and_run_traps(0);
1842 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1843 i->eof_flag = (r < 0);
1844 if (i->eof_flag) { /* EOF/error detected */
1845 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1846 G.user_input_buf[1] = '\0';
1851 fputs(prompt_str, stdout);
1853 G.user_input_buf[0] = r = fgetc(i->file);
1854 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1855 //do we need check_and_run_traps(0)? (maybe only if stdin)
1856 } while (G.flag_SIGINT);
1857 i->eof_flag = (r == EOF);
1859 i->p = G.user_input_buf;
1862 #endif /* INTERACTIVE */
1864 /* This is the magic location that prints prompts
1865 * and gets data back from the user */
1866 static int FAST_FUNC file_get(struct in_str *i)
1870 /* If there is data waiting, eat it up */
1871 if (i->p && *i->p) {
1872 #if ENABLE_HUSH_INTERACTIVE
1876 if (i->eof_flag && !*i->p)
1878 /* note: ch is never NUL */
1880 /* need to double check i->file because we might be doing something
1881 * more complicated by now, like sourcing or substituting. */
1882 #if ENABLE_HUSH_INTERACTIVE
1883 if (G_interactive_fd && i->promptme && i->file == stdin) {
1886 } while (!*i->p); /* need non-empty line */
1887 i->promptmode = 1; /* PS2 */
1892 do ch = fgetc(i->file); while (ch == '\0');
1894 debug_printf("file_get: got '%c' %d\n", ch, ch);
1895 #if ENABLE_HUSH_INTERACTIVE
1902 /* All callers guarantee this routine will never
1903 * be used right after a newline, so prompting is not needed.
1905 static int FAST_FUNC file_peek(struct in_str *i)
1908 if (i->p && *i->p) {
1909 if (i->eof_flag && !i->p[1])
1912 /* note: ch is never NUL */
1914 do ch = fgetc(i->file); while (ch == '\0');
1915 i->eof_flag = (ch == EOF);
1916 i->peek_buf[0] = ch;
1917 i->peek_buf[1] = '\0';
1919 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1923 static void setup_file_in_str(struct in_str *i, FILE *f)
1925 i->peek = file_peek;
1927 #if ENABLE_HUSH_INTERACTIVE
1929 i->promptmode = 0; /* PS1 */
1935 static void setup_string_in_str(struct in_str *i, const char *s)
1937 i->peek = static_peek;
1938 i->get = static_get;
1939 #if ENABLE_HUSH_INTERACTIVE
1941 i->promptmode = 0; /* PS1 */
1951 #define B_CHUNK (32 * sizeof(char*))
1953 static void o_reset_to_empty_unquoted(o_string *o)
1956 o->has_quoted_part = 0;
1961 static void o_free(o_string *o)
1964 memset(o, 0, sizeof(*o));
1967 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1972 static void o_grow_by(o_string *o, int len)
1974 if (o->length + len > o->maxlen) {
1975 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1976 o->data = xrealloc(o->data, 1 + o->maxlen);
1980 static void o_addchr(o_string *o, int ch)
1982 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1984 o->data[o->length] = ch;
1986 o->data[o->length] = '\0';
1989 static void o_addblock(o_string *o, const char *str, int len)
1992 memcpy(&o->data[o->length], str, len);
1994 o->data[o->length] = '\0';
1997 static void o_addstr(o_string *o, const char *str)
1999 o_addblock(o, str, strlen(str));
2003 static void nommu_addchr(o_string *o, int ch)
2009 # define nommu_addchr(o, str) ((void)0)
2012 static void o_addstr_with_NUL(o_string *o, const char *str)
2014 o_addblock(o, str, strlen(str) + 1);
2017 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2029 #undef HUSH_BRACE_EXP
2031 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2032 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2033 * Apparently, on unquoted $v bash still does globbing
2034 * ("v='*.txt'; echo $v" prints all .txt files),
2035 * but NOT brace expansion! Thus, there should be TWO independent
2036 * quoting mechanisms on $v expansion side: one protects
2037 * $v from brace expansion, and other additionally protects "$v" against globbing.
2038 * We have only second one.
2041 #ifdef HUSH_BRACE_EXP
2042 # define MAYBE_BRACES "{}"
2044 # define MAYBE_BRACES ""
2047 /* My analysis of quoting semantics tells me that state information
2048 * is associated with a destination, not a source.
2050 static void o_addqchr(o_string *o, int ch)
2053 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2058 o->data[o->length] = '\\';
2061 o->data[o->length] = ch;
2063 o->data[o->length] = '\0';
2066 static void o_addQchr(o_string *o, int ch)
2069 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2071 o->data[o->length] = '\\';
2075 o->data[o->length] = ch;
2077 o->data[o->length] = '\0';
2080 static void o_addQblock(o_string *o, const char *str, int len)
2083 o_addblock(o, str, len);
2089 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2090 if (ordinary_cnt > len) /* paranoia */
2092 o_addblock(o, str, ordinary_cnt);
2093 if (ordinary_cnt == len)
2095 str += ordinary_cnt;
2096 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2100 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2102 o->data[o->length] = '\\';
2106 o->data[o->length] = ch;
2108 o->data[o->length] = '\0';
2112 static void o_addQstr(o_string *o, const char *str)
2114 o_addQblock(o, str, strlen(str));
2117 /* A special kind of o_string for $VAR and `cmd` expansion.
2118 * It contains char* list[] at the beginning, which is grown in 16 element
2119 * increments. Actual string data starts at the next multiple of 16 * (char*).
2120 * list[i] contains an INDEX (int!) into this string data.
2121 * It means that if list[] needs to grow, data needs to be moved higher up
2122 * but list[i]'s need not be modified.
2123 * NB: remembering how many list[i]'s you have there is crucial.
2124 * o_finalize_list() operation post-processes this structure - calculates
2125 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2127 #if DEBUG_EXPAND || DEBUG_GLOB
2128 static void debug_print_list(const char *prefix, o_string *o, int n)
2130 char **list = (char**)o->data;
2131 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2135 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2136 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->has_quoted_part, o->o_escape);
2139 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2140 o->data + (int)list[i] + string_start,
2141 o->data + (int)list[i] + string_start);
2145 const char *p = o->data + (int)list[n - 1] + string_start;
2147 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2151 # define debug_print_list(prefix, o, n) ((void)0)
2154 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2155 * in list[n] so that it points past last stored byte so far.
2156 * It returns n+1. */
2157 static int o_save_ptr_helper(o_string *o, int n)
2159 char **list = (char**)o->data;
2163 if (!o->has_empty_slot) {
2164 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2165 string_len = o->length - string_start;
2166 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2167 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2168 /* list[n] points to string_start, make space for 16 more pointers */
2169 o->maxlen += 0x10 * sizeof(list[0]);
2170 o->data = xrealloc(o->data, o->maxlen + 1);
2171 list = (char**)o->data;
2172 memmove(list + n + 0x10, list + n, string_len);
2173 o->length += 0x10 * sizeof(list[0]);
2175 debug_printf_list("list[%d]=%d string_start=%d\n",
2176 n, string_len, string_start);
2179 /* We have empty slot at list[n], reuse without growth */
2180 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2181 string_len = o->length - string_start;
2182 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2183 n, string_len, string_start);
2184 o->has_empty_slot = 0;
2186 list[n] = (char*)(ptrdiff_t)string_len;
2190 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2191 static int o_get_last_ptr(o_string *o, int n)
2193 char **list = (char**)o->data;
2194 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2196 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2199 #ifdef HUSH_BRACE_EXP
2200 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2201 * first, it processes even {a} (no commas), second,
2202 * I didn't manage to make it return strings when they don't match
2203 * existing files. Need to re-implement it.
2207 static int glob_needed(const char *s)
2216 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2222 /* Return pointer to next closing brace or to comma */
2223 static const char *next_brace_sub(const char *cp)
2227 while (*cp != '\0') {
2234 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2236 if (*cp++ == '{') /*}*/
2240 return *cp != '\0' ? cp : NULL;
2242 /* Recursive brace globber. Note: may garble pattern[]. */
2243 static int glob_brace(char *pattern, o_string *o, int n)
2245 char *new_pattern_buf;
2252 debug_printf_glob("glob_brace('%s')\n", pattern);
2258 if (*begin == '{') /*}*/ {
2259 /* Find the first sub-pattern and at the same time
2260 * find the rest after the closing brace */
2261 next = next_brace_sub(begin);
2263 /* An illegal expression */
2266 /*{*/ if (*next == '}') {
2267 /* "{abc}" with no commas - illegal
2268 * brace expr, disregard and skip it */
2274 if (*begin == '\\' && begin[1] != '\0')
2278 debug_printf_glob("begin:%s\n", begin);
2279 debug_printf_glob("next:%s\n", next);
2281 /* Now find the end of the whole brace expression */
2283 /*{*/ while (*rest != '}') {
2284 rest = next_brace_sub(rest);
2286 /* An illegal expression */
2289 debug_printf_glob("rest:%s\n", rest);
2291 rest_len = strlen(++rest) + 1;
2293 /* We are sure the brace expression is well-formed */
2295 /* Allocate working buffer large enough for our work */
2296 new_pattern_buf = xmalloc(strlen(pattern));
2298 /* We have a brace expression. BEGIN points to the opening {,
2299 * NEXT points past the terminator of the first element, and REST
2300 * points past the final }. We will accumulate result names from
2301 * recursive runs for each brace alternative in the buffer using
2306 /* Construct the new glob expression */
2309 mempcpy(new_pattern_buf,
2310 /* We know the prefix for all sub-patterns */
2311 pattern, begin - pattern),
2315 /* Note: glob_brace() may garble new_pattern_buf[].
2316 * That's why we re-copy prefix every time (1st memcpy above).
2318 n = glob_brace(new_pattern_buf, o, n);
2319 /*{*/ if (*next == '}') {
2320 /* We saw the last entry */
2324 next = next_brace_sub(next);
2326 free(new_pattern_buf);
2334 memset(&globdata, 0, sizeof(globdata));
2335 gr = glob(pattern, 0, NULL, &globdata);
2336 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2338 if (gr == GLOB_NOMATCH) {
2339 globfree(&globdata);
2340 /* NB: garbles parameter */
2341 unbackslash(pattern);
2342 o_addstr_with_NUL(o, pattern);
2343 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2344 return o_save_ptr_helper(o, n);
2346 if (gr == GLOB_NOSPACE)
2347 bb_error_msg_and_die(bb_msg_memory_exhausted);
2348 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2349 * but we didn't specify it. Paranoia again. */
2350 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2352 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2353 char **argv = globdata.gl_pathv;
2355 o_addstr_with_NUL(o, *argv);
2356 n = o_save_ptr_helper(o, n);
2362 globfree(&globdata);
2366 /* Performs globbing on last list[],
2367 * saving each result as a new list[].
2369 static int o_glob(o_string *o, int n)
2371 char *pattern, *copy;
2373 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2375 return o_save_ptr_helper(o, n);
2376 pattern = o->data + o_get_last_ptr(o, n);
2377 debug_printf_glob("glob pattern '%s'\n", pattern);
2378 if (!glob_needed(pattern)) {
2379 /* unbackslash last string in o in place, fix length */
2380 o->length = unbackslash(pattern) - o->data;
2381 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2382 return o_save_ptr_helper(o, n);
2385 copy = xstrdup(pattern);
2386 /* "forget" pattern in o */
2387 o->length = pattern - o->data;
2388 n = glob_brace(copy, o, n);
2391 debug_print_list("o_glob returning", o, n);
2395 #else /* !HUSH_BRACE_EXP */
2398 static int glob_needed(const char *s)
2407 if (*s == '*' || *s == '[' || *s == '?')
2413 /* Performs globbing on last list[],
2414 * saving each result as a new list[].
2416 static int o_glob(o_string *o, int n)
2422 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2424 return o_save_ptr_helper(o, n);
2425 pattern = o->data + o_get_last_ptr(o, n);
2426 debug_printf_glob("glob pattern '%s'\n", pattern);
2427 if (!glob_needed(pattern)) {
2429 /* unbackslash last string in o in place, fix length */
2430 o->length = unbackslash(pattern) - o->data;
2431 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2432 return o_save_ptr_helper(o, n);
2435 memset(&globdata, 0, sizeof(globdata));
2436 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2437 * If we glob "*.\*" and don't find anything, we need
2438 * to fall back to using literal "*.*", but GLOB_NOCHECK
2439 * will return "*.\*"!
2441 gr = glob(pattern, 0, NULL, &globdata);
2442 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2444 if (gr == GLOB_NOMATCH) {
2445 globfree(&globdata);
2448 if (gr == GLOB_NOSPACE)
2449 bb_error_msg_and_die(bb_msg_memory_exhausted);
2450 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2451 * but we didn't specify it. Paranoia again. */
2452 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2454 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2455 char **argv = globdata.gl_pathv;
2456 /* "forget" pattern in o */
2457 o->length = pattern - o->data;
2459 o_addstr_with_NUL(o, *argv);
2460 n = o_save_ptr_helper(o, n);
2466 globfree(&globdata);
2468 debug_print_list("o_glob returning", o, n);
2472 #endif /* !HUSH_BRACE_EXP */
2474 /* If o->o_glob == 1, glob the string so far remembered.
2475 * Otherwise, just finish current list[] and start new */
2476 static int o_save_ptr(o_string *o, int n)
2478 if (o->o_glob) { /* if globbing is requested */
2479 /* If o->has_empty_slot, list[n] was already globbed
2480 * (if it was requested back then when it was filled)
2481 * so don't do that again! */
2482 if (!o->has_empty_slot)
2483 return o_glob(o, n); /* o_save_ptr_helper is inside */
2485 return o_save_ptr_helper(o, n);
2488 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2489 static char **o_finalize_list(o_string *o, int n)
2494 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2496 debug_print_list("finalized", o, n);
2497 debug_printf_expand("finalized n:%d\n", n);
2498 list = (char**)o->data;
2499 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2503 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2508 static void free_pipe_list(struct pipe *head);
2510 /* Return code is the exit status of the pipe */
2511 static void free_pipe(struct pipe *pi)
2514 struct command *command;
2515 struct redir_struct *r, *rnext;
2518 if (pi->stopped_cmds > 0) /* why? */
2520 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2521 for (i = 0; i < pi->num_cmds; i++) {
2522 command = &pi->cmds[i];
2523 debug_printf_clean(" command %d:\n", i);
2524 if (command->argv) {
2525 for (a = 0, p = command->argv; *p; a++, p++) {
2526 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2528 free_strings(command->argv);
2529 command->argv = NULL;
2531 /* not "else if": on syntax error, we may have both! */
2532 if (command->group) {
2533 debug_printf_clean(" begin group (cmd_type:%d)\n",
2535 free_pipe_list(command->group);
2536 debug_printf_clean(" end group\n");
2537 command->group = NULL;
2539 /* else is crucial here.
2540 * If group != NULL, child_func is meaningless */
2541 #if ENABLE_HUSH_FUNCTIONS
2542 else if (command->child_func) {
2543 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2544 command->child_func->parent_cmd = NULL;
2548 free(command->group_as_string);
2549 command->group_as_string = NULL;
2551 for (r = command->redirects; r; r = rnext) {
2552 debug_printf_clean(" redirect %d%s",
2553 r->rd_fd, redir_table[r->rd_type].descrip);
2554 /* guard against the case >$FOO, where foo is unset or blank */
2555 if (r->rd_filename) {
2556 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2557 free(r->rd_filename);
2558 r->rd_filename = NULL;
2560 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2564 command->redirects = NULL;
2566 free(pi->cmds); /* children are an array, they get freed all at once */
2574 static void free_pipe_list(struct pipe *head)
2576 struct pipe *pi, *next;
2578 for (pi = head; pi; pi = next) {
2580 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2583 debug_printf_clean("pipe followup code %d\n", pi->followup);
2585 /*pi->next = NULL;*/
2591 /*** Parsing routines ***/
2593 static struct pipe *new_pipe(void)
2596 pi = xzalloc(sizeof(struct pipe));
2597 /*pi->followup = 0; - deliberately invalid value */
2598 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2602 /* Command (member of a pipe) is complete, or we start a new pipe
2603 * if ctx->command is NULL.
2604 * No errors possible here.
2606 static int done_command(struct parse_context *ctx)
2608 /* The command is really already in the pipe structure, so
2609 * advance the pipe counter and make a new, null command. */
2610 struct pipe *pi = ctx->pipe;
2611 struct command *command = ctx->command;
2614 if (IS_NULL_CMD(command)) {
2615 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2619 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2620 //debug_print_tree(ctx->list_head, 20);
2622 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2625 /* Only real trickiness here is that the uncommitted
2626 * command structure is not counted in pi->num_cmds. */
2627 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2628 ctx->command = command = &pi->cmds[pi->num_cmds];
2630 memset(command, 0, sizeof(*command));
2631 return pi->num_cmds; /* used only for 0/nonzero check */
2634 static void done_pipe(struct parse_context *ctx, pipe_style type)
2638 debug_printf_parse("done_pipe entered, followup %d\n", type);
2639 /* Close previous command */
2640 not_null = done_command(ctx);
2641 ctx->pipe->followup = type;
2643 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2644 ctx->ctx_inverted = 0;
2645 ctx->pipe->res_word = ctx->ctx_res_w;
2648 /* Without this check, even just <enter> on command line generates
2649 * tree of three NOPs (!). Which is harmless but annoying.
2650 * IOW: it is safe to do it unconditionally. */
2653 || ctx->ctx_res_w == RES_FI
2655 #if ENABLE_HUSH_LOOPS
2656 || ctx->ctx_res_w == RES_DONE
2657 || ctx->ctx_res_w == RES_FOR
2658 || ctx->ctx_res_w == RES_IN
2660 #if ENABLE_HUSH_CASE
2661 || ctx->ctx_res_w == RES_ESAC
2665 debug_printf_parse("done_pipe: adding new pipe: "
2666 "not_null:%d ctx->ctx_res_w:%d\n",
2667 not_null, ctx->ctx_res_w);
2669 ctx->pipe->next = new_p;
2671 /* RES_THEN, RES_DO etc are "sticky" -
2672 * they remain set for pipes inside if/while.
2673 * This is used to control execution.
2674 * RES_FOR and RES_IN are NOT sticky (needed to support
2675 * cases where variable or value happens to match a keyword):
2677 #if ENABLE_HUSH_LOOPS
2678 if (ctx->ctx_res_w == RES_FOR
2679 || ctx->ctx_res_w == RES_IN)
2680 ctx->ctx_res_w = RES_NONE;
2682 #if ENABLE_HUSH_CASE
2683 if (ctx->ctx_res_w == RES_MATCH)
2684 ctx->ctx_res_w = RES_CASE_BODY;
2685 if (ctx->ctx_res_w == RES_CASE)
2686 ctx->ctx_res_w = RES_CASE_IN;
2688 ctx->command = NULL; /* trick done_command below */
2689 /* Create the memory for command, roughly:
2690 * ctx->pipe->cmds = new struct command;
2691 * ctx->command = &ctx->pipe->cmds[0];
2694 //debug_print_tree(ctx->list_head, 10);
2696 debug_printf_parse("done_pipe return\n");
2699 static void initialize_context(struct parse_context *ctx)
2701 memset(ctx, 0, sizeof(*ctx));
2702 ctx->pipe = ctx->list_head = new_pipe();
2703 /* Create the memory for command, roughly:
2704 * ctx->pipe->cmds = new struct command;
2705 * ctx->command = &ctx->pipe->cmds[0];
2710 /* If a reserved word is found and processed, parse context is modified
2711 * and 1 is returned.
2714 struct reserved_combo {
2717 unsigned char assignment_flag;
2721 FLAG_END = (1 << RES_NONE ),
2723 FLAG_IF = (1 << RES_IF ),
2724 FLAG_THEN = (1 << RES_THEN ),
2725 FLAG_ELIF = (1 << RES_ELIF ),
2726 FLAG_ELSE = (1 << RES_ELSE ),
2727 FLAG_FI = (1 << RES_FI ),
2729 # if ENABLE_HUSH_LOOPS
2730 FLAG_FOR = (1 << RES_FOR ),
2731 FLAG_WHILE = (1 << RES_WHILE),
2732 FLAG_UNTIL = (1 << RES_UNTIL),
2733 FLAG_DO = (1 << RES_DO ),
2734 FLAG_DONE = (1 << RES_DONE ),
2735 FLAG_IN = (1 << RES_IN ),
2737 # if ENABLE_HUSH_CASE
2738 FLAG_MATCH = (1 << RES_MATCH),
2739 FLAG_ESAC = (1 << RES_ESAC ),
2741 FLAG_START = (1 << RES_XXXX ),
2744 static const struct reserved_combo* match_reserved_word(o_string *word)
2746 /* Mostly a list of accepted follow-up reserved words.
2747 * FLAG_END means we are done with the sequence, and are ready
2748 * to turn the compound list into a command.
2749 * FLAG_START means the word must start a new compound list.
2751 static const struct reserved_combo reserved_list[] = {
2753 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2754 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2755 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2756 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2757 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2758 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2760 # if ENABLE_HUSH_LOOPS
2761 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2762 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2763 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2764 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2765 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2766 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2768 # if ENABLE_HUSH_CASE
2769 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2770 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2773 const struct reserved_combo *r;
2775 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2776 if (strcmp(word->data, r->literal) == 0)
2781 /* Return 0: not a keyword, 1: keyword
2783 static int reserved_word(o_string *word, struct parse_context *ctx)
2785 # if ENABLE_HUSH_CASE
2786 static const struct reserved_combo reserved_match = {
2787 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2790 const struct reserved_combo *r;
2792 if (word->has_quoted_part)
2794 r = match_reserved_word(word);
2798 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2799 # if ENABLE_HUSH_CASE
2800 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2801 /* "case word IN ..." - IN part starts first MATCH part */
2802 r = &reserved_match;
2805 if (r->flag == 0) { /* '!' */
2806 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2807 syntax_error("! ! command");
2808 ctx->ctx_res_w = RES_SNTX;
2810 ctx->ctx_inverted = 1;
2813 if (r->flag & FLAG_START) {
2814 struct parse_context *old;
2816 old = xmalloc(sizeof(*old));
2817 debug_printf_parse("push stack %p\n", old);
2818 *old = *ctx; /* physical copy */
2819 initialize_context(ctx);
2821 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2822 syntax_error_at(word->data);
2823 ctx->ctx_res_w = RES_SNTX;
2826 /* "{...} fi" is ok. "{...} if" is not
2828 * if { echo foo; } then { echo bar; } fi */
2829 if (ctx->command->group)
2830 done_pipe(ctx, PIPE_SEQ);
2833 ctx->ctx_res_w = r->res;
2834 ctx->old_flag = r->flag;
2835 word->o_assignment = r->assignment_flag;
2837 if (ctx->old_flag & FLAG_END) {
2838 struct parse_context *old;
2840 done_pipe(ctx, PIPE_SEQ);
2841 debug_printf_parse("pop stack %p\n", ctx->stack);
2843 old->command->group = ctx->list_head;
2844 old->command->cmd_type = CMD_NORMAL;
2846 o_addstr(&old->as_string, ctx->as_string.data);
2847 o_free_unsafe(&ctx->as_string);
2848 old->command->group_as_string = xstrdup(old->as_string.data);
2849 debug_printf_parse("pop, remembering as:'%s'\n",
2850 old->command->group_as_string);
2852 *ctx = *old; /* physical copy */
2857 #endif /* HAS_KEYWORDS */
2859 /* Word is complete, look at it and update parsing context.
2860 * Normal return is 0. Syntax errors return 1.
2861 * Note: on return, word is reset, but not o_free'd!
2863 static int done_word(o_string *word, struct parse_context *ctx)
2865 struct command *command = ctx->command;
2867 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2868 if (word->length == 0 && !word->has_quoted_part) {
2869 debug_printf_parse("done_word return 0: true null, ignored\n");
2873 if (ctx->pending_redirect) {
2874 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2875 * only if run as "bash", not "sh" */
2876 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2878 * ...the word that follows the redirection operator
2879 * shall be subjected to tilde expansion, parameter expansion,
2880 * command substitution, arithmetic expansion, and quote
2881 * removal. Pathname expansion shall not be performed
2882 * on the word by a non-interactive shell; an interactive
2883 * shell may perform it, but shall do so only when
2884 * the expansion would result in one word."
2886 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2887 /* Cater for >\file case:
2888 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2889 * Same with heredocs:
2890 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2892 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2893 unbackslash(ctx->pending_redirect->rd_filename);
2894 /* Is it <<"HEREDOC"? */
2895 if (word->has_quoted_part) {
2896 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2899 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2900 ctx->pending_redirect = NULL;
2902 /* If this word wasn't an assignment, next ones definitely
2903 * can't be assignments. Even if they look like ones. */
2904 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2905 && word->o_assignment != WORD_IS_KEYWORD
2907 word->o_assignment = NOT_ASSIGNMENT;
2909 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2910 command->assignment_cnt++;
2911 word->o_assignment = MAYBE_ASSIGNMENT;
2915 # if ENABLE_HUSH_CASE
2916 if (ctx->ctx_dsemicolon
2917 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2919 /* already done when ctx_dsemicolon was set to 1: */
2920 /* ctx->ctx_res_w = RES_MATCH; */
2921 ctx->ctx_dsemicolon = 0;
2924 if (!command->argv /* if it's the first word... */
2925 # if ENABLE_HUSH_LOOPS
2926 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2927 && ctx->ctx_res_w != RES_IN
2929 # if ENABLE_HUSH_CASE
2930 && ctx->ctx_res_w != RES_CASE
2933 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2934 if (reserved_word(word, ctx)) {
2935 o_reset_to_empty_unquoted(word);
2936 debug_printf_parse("done_word return %d\n",
2937 (ctx->ctx_res_w == RES_SNTX));
2938 return (ctx->ctx_res_w == RES_SNTX);
2940 # ifdef CMD_SINGLEWORD_NOGLOB_COND
2941 if (strcmp(word->data, "export") == 0
2942 # if ENABLE_HUSH_LOCAL
2943 || strcmp(word->data, "local") == 0
2946 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
2949 # if ENABLE_HUSH_BASH_COMPAT
2950 if (strcmp(word->data, "[[") == 0) {
2951 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2957 if (command->group) {
2958 /* "{ echo foo; } echo bar" - bad */
2959 syntax_error_at(word->data);
2960 debug_printf_parse("done_word return 1: syntax error, "
2961 "groups and arglists don't mix\n");
2964 if (word->has_quoted_part
2965 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2966 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2967 /* (otherwise it's known to be not empty and is already safe) */
2969 /* exclude "$@" - it can expand to no word despite "" */
2970 char *p = word->data;
2971 while (p[0] == SPECIAL_VAR_SYMBOL
2972 && (p[1] & 0x7f) == '@'
2973 && p[2] == SPECIAL_VAR_SYMBOL
2977 if (p == word->data || p[0] != '\0') {
2978 /* saw no "$@", or not only "$@" but some
2979 * real text is there too */
2980 /* insert "empty variable" reference, this makes
2981 * e.g. "", $empty"" etc to not disappear */
2982 o_addchr(word, SPECIAL_VAR_SYMBOL);
2983 o_addchr(word, SPECIAL_VAR_SYMBOL);
2986 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2987 debug_print_strings("word appended to argv", command->argv);
2990 #if ENABLE_HUSH_LOOPS
2991 if (ctx->ctx_res_w == RES_FOR) {
2992 if (word->has_quoted_part
2993 || !is_well_formed_var_name(command->argv[0], '\0')
2995 /* bash says just "not a valid identifier" */
2996 syntax_error("not a valid identifier in for");
2999 /* Force FOR to have just one word (variable name) */
3000 /* NB: basically, this makes hush see "for v in ..."
3001 * syntax as if it is "for v; in ...". FOR and IN become
3002 * two pipe structs in parse tree. */
3003 done_pipe(ctx, PIPE_SEQ);
3006 #if ENABLE_HUSH_CASE
3007 /* Force CASE to have just one word */
3008 if (ctx->ctx_res_w == RES_CASE) {
3009 done_pipe(ctx, PIPE_SEQ);
3013 o_reset_to_empty_unquoted(word);
3015 debug_printf_parse("done_word return 0\n");
3020 /* Peek ahead in the input to find out if we have a "&n" construct,
3021 * as in "2>&1", that represents duplicating a file descriptor.
3023 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3024 * REDIRFD_SYNTAX_ERR if syntax error,
3025 * REDIRFD_TO_FILE if no & was seen,
3026 * or the number found.
3029 #define parse_redir_right_fd(as_string, input) \
3030 parse_redir_right_fd(input)
3032 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3038 return REDIRFD_TO_FILE;
3040 ch = i_getch(input); /* get the & */
3041 nommu_addchr(as_string, ch);
3044 ch = i_getch(input);
3045 nommu_addchr(as_string, ch);
3046 return REDIRFD_CLOSE;
3050 while (ch != EOF && isdigit(ch)) {
3051 d = d*10 + (ch-'0');
3053 ch = i_getch(input);
3054 nommu_addchr(as_string, ch);
3059 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3061 bb_error_msg("ambiguous redirect");
3062 return REDIRFD_SYNTAX_ERR;
3065 /* Return code is 0 normal, 1 if a syntax error is detected
3067 static int parse_redirect(struct parse_context *ctx,
3070 struct in_str *input)
3072 struct command *command = ctx->command;
3073 struct redir_struct *redir;
3074 struct redir_struct **redirp;
3077 dup_num = REDIRFD_TO_FILE;
3078 if (style != REDIRECT_HEREDOC) {
3079 /* Check for a '>&1' type redirect */
3080 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3081 if (dup_num == REDIRFD_SYNTAX_ERR)
3084 int ch = i_peek(input);
3085 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3086 if (dup_num) { /* <<-... */
3087 ch = i_getch(input);
3088 nommu_addchr(&ctx->as_string, ch);
3093 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3094 int ch = i_peek(input);
3096 /* >|FILE redirect ("clobbering" >).
3097 * Since we do not support "set -o noclobber" yet,
3098 * >| and > are the same for now. Just eat |.
3100 ch = i_getch(input);
3101 nommu_addchr(&ctx->as_string, ch);
3105 /* Create a new redir_struct and append it to the linked list */
3106 redirp = &command->redirects;
3107 while ((redir = *redirp) != NULL) {
3108 redirp = &(redir->next);
3110 *redirp = redir = xzalloc(sizeof(*redir));
3111 /* redir->next = NULL; */
3112 /* redir->rd_filename = NULL; */
3113 redir->rd_type = style;
3114 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3116 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3117 redir_table[style].descrip);
3119 redir->rd_dup = dup_num;
3120 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3121 /* Erik had a check here that the file descriptor in question
3122 * is legit; I postpone that to "run time"
3123 * A "-" representation of "close me" shows up as a -3 here */
3124 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3125 redir->rd_fd, redir->rd_dup);
3127 /* Set ctx->pending_redirect, so we know what to do at the
3128 * end of the next parsed word. */
3129 ctx->pending_redirect = redir;
3134 /* If a redirect is immediately preceded by a number, that number is
3135 * supposed to tell which file descriptor to redirect. This routine
3136 * looks for such preceding numbers. In an ideal world this routine
3137 * needs to handle all the following classes of redirects...
3138 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3139 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3140 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3141 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3143 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3145 * ... If n is quoted, the number shall not be recognized as part of
3146 * the redirection expression. For example:
3148 * writes the character 2 into file a"
3149 * We are getting it right by setting ->has_quoted_part on any \<char>
3151 * A -1 return means no valid number was found,
3152 * the caller should use the appropriate default for this redirection.
3154 static int redirect_opt_num(o_string *o)
3158 if (o->data == NULL)
3160 num = bb_strtou(o->data, NULL, 10);
3161 if (errno || num < 0)
3163 o_reset_to_empty_unquoted(o);
3168 #define fetch_till_str(as_string, input, word, skip_tabs) \
3169 fetch_till_str(input, word, skip_tabs)
3171 static char *fetch_till_str(o_string *as_string,
3172 struct in_str *input,
3176 o_string heredoc = NULL_O_STRING;
3182 ch = i_getch(input);
3183 nommu_addchr(as_string, ch);
3185 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3186 heredoc.data[past_EOL] = '\0';
3187 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3188 return heredoc.data;
3191 o_addchr(&heredoc, ch);
3192 past_EOL = heredoc.length;
3195 ch = i_getch(input);
3196 nommu_addchr(as_string, ch);
3197 } while (skip_tabs && ch == '\t');
3198 } while (ch == '\n');
3201 o_free_unsafe(&heredoc);
3204 o_addchr(&heredoc, ch);
3205 nommu_addchr(as_string, ch);
3209 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3210 * and load them all. There should be exactly heredoc_cnt of them.
3212 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3214 struct pipe *pi = ctx->list_head;
3216 while (pi && heredoc_cnt) {
3218 struct command *cmd = pi->cmds;
3220 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3222 cmd->argv ? cmd->argv[0] : "NONE");
3223 for (i = 0; i < pi->num_cmds; i++) {
3224 struct redir_struct *redir = cmd->redirects;
3226 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3227 i, cmd->argv ? cmd->argv[0] : "NONE");
3229 if (redir->rd_type == REDIRECT_HEREDOC) {
3232 redir->rd_type = REDIRECT_HEREDOC2;
3233 /* redir->rd_dup is (ab)used to indicate <<- */
3234 p = fetch_till_str(&ctx->as_string, input,
3235 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
3237 syntax_error("unexpected EOF in here document");
3240 free(redir->rd_filename);
3241 redir->rd_filename = p;
3244 redir = redir->next;
3251 /* Should be 0. If it isn't, it's a parse error */
3253 bb_error_msg_and_die("heredoc BUG 2");
3259 static int run_list(struct pipe *pi);
3261 #define parse_stream(pstring, input, end_trigger) \
3262 parse_stream(input, end_trigger)
3264 static struct pipe *parse_stream(char **pstring,
3265 struct in_str *input,
3269 #if !ENABLE_HUSH_FUNCTIONS
3270 #define parse_group(dest, ctx, input, ch) \
3271 parse_group(ctx, input, ch)
3273 static int parse_group(o_string *dest, struct parse_context *ctx,
3274 struct in_str *input, int ch)
3276 /* dest contains characters seen prior to ( or {.
3277 * Typically it's empty, but for function defs,
3278 * it contains function name (without '()'). */
3279 struct pipe *pipe_list;
3281 struct command *command = ctx->command;
3283 debug_printf_parse("parse_group entered\n");
3284 #if ENABLE_HUSH_FUNCTIONS
3285 if (ch == '(' && !dest->has_quoted_part) {
3287 if (done_word(dest, ctx))
3290 goto skip; /* (... */
3291 if (command->argv[1]) { /* word word ... (... */
3292 syntax_error_unexpected_ch('(');
3295 /* it is "word(..." or "word (..." */
3297 ch = i_getch(input);
3298 while (ch == ' ' || ch == '\t');
3300 syntax_error_unexpected_ch(ch);
3303 nommu_addchr(&ctx->as_string, ch);
3305 ch = i_getch(input);
3306 while (ch == ' ' || ch == '\t' || ch == '\n');
3308 syntax_error_unexpected_ch(ch);
3311 nommu_addchr(&ctx->as_string, ch);
3312 command->cmd_type = CMD_FUNCDEF;
3317 #if 0 /* Prevented by caller */
3318 if (command->argv /* word [word]{... */
3319 || dest->length /* word{... */
3320 || dest->has_quoted_part /* ""{... */
3323 debug_printf_parse("parse_group return 1: "
3324 "syntax error, groups and arglists don't mix\n");
3329 #if ENABLE_HUSH_FUNCTIONS
3335 command->cmd_type = CMD_SUBSHELL;
3337 /* bash does not allow "{echo...", requires whitespace */
3338 ch = i_getch(input);
3339 if (ch != ' ' && ch != '\t' && ch != '\n') {
3340 syntax_error_unexpected_ch(ch);
3343 nommu_addchr(&ctx->as_string, ch);
3348 # define as_string NULL
3350 char *as_string = NULL;
3352 pipe_list = parse_stream(&as_string, input, endch);
3355 o_addstr(&ctx->as_string, as_string);
3357 /* empty ()/{} or parse error? */
3358 if (!pipe_list || pipe_list == ERR_PTR) {
3359 /* parse_stream already emitted error msg */
3362 debug_printf_parse("parse_group return 1: "
3363 "parse_stream returned %p\n", pipe_list);
3366 command->group = pipe_list;
3368 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3369 command->group_as_string = as_string;
3370 debug_printf_parse("end of group, remembering as:'%s'\n",
3371 command->group_as_string);
3375 debug_printf_parse("parse_group return 0\n");
3377 /* command remains "open", available for possible redirects */
3380 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3381 /* Subroutines for copying $(...) and `...` things */
3382 static void add_till_backquote(o_string *dest, struct in_str *input);
3384 static void add_till_single_quote(o_string *dest, struct in_str *input)
3387 int ch = i_getch(input);
3389 syntax_error_unterm_ch('\'');
3390 /*xfunc_die(); - redundant */
3397 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3398 static void add_till_double_quote(o_string *dest, struct in_str *input)
3401 int ch = i_getch(input);
3403 syntax_error_unterm_ch('"');
3404 /*xfunc_die(); - redundant */
3408 if (ch == '\\') { /* \x. Copy both chars. */
3410 ch = i_getch(input);
3414 add_till_backquote(dest, input);
3418 //if (ch == '$') ...
3421 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3423 * "Within the backquoted style of command substitution, backslash
3424 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3425 * The search for the matching backquote shall be satisfied by the first
3426 * backquote found without a preceding backslash; during this search,
3427 * if a non-escaped backquote is encountered within a shell comment,
3428 * a here-document, an embedded command substitution of the $(command)
3429 * form, or a quoted string, undefined results occur. A single-quoted
3430 * or double-quoted string that begins, but does not end, within the
3431 * "`...`" sequence produces undefined results."
3433 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3435 static void add_till_backquote(o_string *dest, struct in_str *input)
3438 int ch = i_getch(input);
3440 syntax_error_unterm_ch('`');
3441 /*xfunc_die(); - redundant */
3446 /* \x. Copy both chars unless it is \` */
3447 int ch2 = i_getch(input);
3449 syntax_error_unterm_ch('`');
3450 /*xfunc_die(); - redundant */
3452 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3459 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3460 * quoting and nested ()s.
3461 * "With the $(command) style of command substitution, all characters
3462 * following the open parenthesis to the matching closing parenthesis
3463 * constitute the command. Any valid shell script can be used for command,
3464 * except a script consisting solely of redirections which produces
3465 * unspecified results."
3467 * echo $(echo '(TEST)' BEST) (TEST) BEST
3468 * echo $(echo 'TEST)' BEST) TEST) BEST
3469 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3471 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3472 * can contain arbitrary constructs, just like $(cmd).
3473 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3474 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3476 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3477 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3480 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3481 # if ENABLE_HUSH_BASH_COMPAT
3482 char end_char2 = end_ch >> 8;
3484 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3487 ch = i_getch(input);
3489 syntax_error_unterm_ch(end_ch);
3490 /*xfunc_die(); - redundant */
3492 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3495 /* we look for closing )) of $((EXPR)) */
3496 if (i_peek(input) == end_ch) {
3497 i_getch(input); /* eat second ')' */
3502 if (ch == '(' || ch == '{') {
3503 ch = (ch == '(' ? ')' : '}');
3504 add_till_closing_bracket(dest, input, ch);
3509 add_till_single_quote(dest, input);
3514 add_till_double_quote(dest, input);
3519 add_till_backquote(dest, input);
3524 /* \x. Copy verbatim. Important for \(, \) */
3525 ch = i_getch(input);
3527 syntax_error_unterm_ch(')');
3528 /*xfunc_die(); - redundant */
3536 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3538 /* Return code: 0 for OK, 1 for syntax error */
3540 #define parse_dollar(as_string, dest, input) \
3541 parse_dollar(dest, input)
3542 #define as_string NULL
3544 static int parse_dollar(o_string *as_string,
3546 struct in_str *input)
3548 int ch = i_peek(input); /* first character after the $ */
3549 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
3551 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3553 ch = i_getch(input);
3554 nommu_addchr(as_string, ch);
3556 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3558 debug_printf_parse(": '%c'\n", ch);
3559 o_addchr(dest, ch | quote_mask);
3562 if (!isalnum(ch) && ch != '_')
3564 ch = i_getch(input);
3565 nommu_addchr(as_string, ch);
3567 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3568 } else if (isdigit(ch)) {
3570 ch = i_getch(input);
3571 nommu_addchr(as_string, ch);
3572 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3573 debug_printf_parse(": '%c'\n", ch);
3574 o_addchr(dest, ch | quote_mask);
3575 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3576 } else switch (ch) {
3578 case '!': /* last bg pid */
3579 case '?': /* last exit code */
3580 case '#': /* number of args */
3581 case '*': /* args */
3582 case '@': /* args */
3583 goto make_one_char_var;
3585 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3587 ch = i_getch(input); /* eat '{' */
3588 nommu_addchr(as_string, ch);
3590 ch = i_getch(input); /* first char after '{' */
3591 nommu_addchr(as_string, ch);
3592 /* It should be ${?}, or ${#var},
3593 * or even ${?+subst} - operator acting on a special variable,
3594 * or the beginning of variable name.
3596 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
3598 syntax_error_unterm_str("${name}");
3599 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3604 /* It's possible to just call add_till_closing_bracket() at this point.
3605 * However, this regresses some of our testsuite cases
3606 * which check invalid constructs like ${%}.
3607 * Oh well... let's check that the var name part is fine... */
3613 debug_printf_parse(": '%c'\n", ch);
3615 ch = i_getch(input);
3616 nommu_addchr(as_string, ch);
3620 if (!isalnum(ch) && ch != '_') {
3622 unsigned char last_ch;
3623 /* handle parameter expansions
3624 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3626 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3627 goto bad_dollar_syntax;
3629 /* Eat everything until closing '}' (or ':') */
3631 if (ENABLE_HUSH_BASH_COMPAT
3633 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3635 /* It's ${var:N[:M]} thing */
3636 end_ch = '}' * 0x100 + ':';
3638 if (ENABLE_HUSH_BASH_COMPAT
3641 /* It's ${var/[/]pattern[/repl]} thing */
3642 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3644 nommu_addchr(as_string, '/');
3647 end_ch = '}' * 0x100 + '/';
3653 #if ENABLE_HUSH_DOLLAR_OPS
3654 last_ch = add_till_closing_bracket(dest, input, end_ch);
3656 #error Simple code to only allow ${var} is not implemented
3659 o_addstr(as_string, dest->data + pos);
3660 o_addchr(as_string, last_ch);
3663 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3664 /* close the first block: */
3665 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3666 /* while parsing N from ${var:N[:M]}
3667 * or pattern from ${var/[/]pattern[/repl]} */
3668 if ((end_ch & 0xff) == last_ch) {
3669 /* got ':' or '/'- parse the rest */
3674 if (end_ch == '}' * 0x100 + ':') {
3675 /* it's ${var:N} - emulate :999999999 */
3676 o_addstr(dest, "999999999");
3677 } /* else: it's ${var/[/]pattern} */
3682 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3685 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3689 ch = i_getch(input);
3690 nommu_addchr(as_string, ch);
3691 # if ENABLE_SH_MATH_SUPPORT
3692 if (i_peek(input) == '(') {
3693 ch = i_getch(input);
3694 nommu_addchr(as_string, ch);
3695 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3696 o_addchr(dest, /*quote_mask |*/ '+');
3699 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3701 o_addstr(as_string, dest->data + pos);
3702 o_addchr(as_string, ')');
3703 o_addchr(as_string, ')');
3705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3709 # if ENABLE_HUSH_TICK
3710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3711 o_addchr(dest, quote_mask | '`');
3714 add_till_closing_bracket(dest, input, ')');
3716 o_addstr(as_string, dest->data + pos);
3717 o_addchr(as_string, ')');
3719 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3725 ch = i_getch(input);
3726 nommu_addchr(as_string, ch);
3728 if (isalnum(ch)) { /* it's $_name or $_123 */
3733 /* TODO: $_ and $-: */
3734 /* $_ Shell or shell script name; or last argument of last command
3735 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3736 * but in command's env, set to full pathname used to invoke it */
3737 /* $- Option flags set by set builtin or shell options (-i etc) */
3739 o_addQchr(dest, '$');
3741 debug_printf_parse("parse_dollar return 0\n");
3747 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
3748 parse_stream_dquoted(dest, input, dquote_end)
3749 #define as_string NULL
3751 static int parse_stream_dquoted(o_string *as_string,
3753 struct in_str *input,
3760 ch = i_getch(input);
3762 nommu_addchr(as_string, ch);
3763 if (ch == dquote_end) { /* may be only '"' or EOF */
3764 if (dest->o_assignment == NOT_ASSIGNMENT)
3765 dest->o_escape ^= 1;
3766 debug_printf_parse("parse_stream_dquoted return 0\n");
3769 /* note: can't move it above ch == dquote_end check! */
3771 syntax_error_unterm_ch('"');
3772 /*xfunc_die(); - redundant */
3776 next = i_peek(input);
3778 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3779 ch, ch, dest->o_escape);
3782 syntax_error("\\<eof>");
3786 * "The backslash retains its special meaning [in "..."]
3787 * only when followed by one of the following characters:
3788 * $, `, ", \, or <newline>. A double quote may be quoted
3789 * within double quotes by preceding it with a backslash."
3791 if (strchr("$`\"\\\n", next) != NULL) {
3792 ch = i_getch(input);
3794 o_addqchr(dest, ch);
3795 nommu_addchr(as_string, ch);
3798 o_addqchr(dest, '\\');
3799 nommu_addchr(as_string, '\\');
3804 if (parse_dollar(as_string, dest, input) != 0) {
3805 debug_printf_parse("parse_stream_dquoted return 1: "
3806 "parse_dollar returned non-0\n");
3811 #if ENABLE_HUSH_TICK
3813 //unsigned pos = dest->length;
3814 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3815 o_addchr(dest, 0x80 | '`');
3816 add_till_backquote(dest, input);
3817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3818 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3822 o_addQchr(dest, ch);
3824 && (dest->o_assignment == MAYBE_ASSIGNMENT
3825 || dest->o_assignment == WORD_IS_KEYWORD)
3826 && is_well_formed_var_name(dest->data, '=')
3828 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3835 * Scan input until EOF or end_trigger char.
3836 * Return a list of pipes to execute, or NULL on EOF
3837 * or if end_trigger character is met.
3838 * On syntax error, exit is shell is not interactive,
3839 * reset parsing machinery and start parsing anew,
3840 * or return ERR_PTR.
3842 static struct pipe *parse_stream(char **pstring,
3843 struct in_str *input,
3846 struct parse_context ctx;
3847 o_string dest = NULL_O_STRING;
3851 /* Double-quote state is handled in the state variable is_in_dquote.
3852 * A single-quote triggers a bypass of the main loop until its mate is
3853 * found. When recursing, quote state is passed in via dest->o_escape.
3855 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3856 end_trigger ? end_trigger : 'X');
3859 /* If very first arg is "" or '', dest.data may end up NULL.
3860 * Preventing this: */
3861 o_addchr(&dest, '\0');
3864 G.ifs = get_local_var_value("IFS");
3869 #if ENABLE_HUSH_INTERACTIVE
3870 input->promptmode = 0; /* PS1 */
3872 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3873 initialize_context(&ctx);
3878 const char *is_special;
3882 redir_type redir_style;
3885 /* dest.has_quoted_part = 1; - already is (see below) */
3886 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
3889 /* We reached closing '"' */
3892 ch = i_getch(input);
3893 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3894 ch, ch, dest.o_escape);
3899 syntax_error_unterm_str("here document");
3902 /* end_trigger == '}' case errors out earlier,
3903 * checking only ')' */
3904 if (end_trigger == ')') {
3905 syntax_error_unterm_ch('('); /* exits */
3906 /* goto parse_error; */
3909 if (done_word(&dest, &ctx)) {
3913 done_pipe(&ctx, PIPE_SEQ);
3915 /* If we got nothing... */
3916 /* (this makes bare "&" cmd a no-op.
3917 * bash says: "syntax error near unexpected token '&'") */
3918 if (pi->num_cmds == 0
3919 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3925 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3927 *pstring = ctx.as_string.data;
3929 o_free_unsafe(&ctx.as_string);
3932 debug_printf_parse("parse_stream return %p\n", pi);
3935 nommu_addchr(&ctx.as_string, ch);
3939 next = i_peek(input);
3941 is_special = "{}<>;&|()#'" /* special outside of "str" */
3942 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3943 /* Are { and } special here? */
3944 if (ctx.command->argv /* word [word]{... - non-special */
3945 || dest.length /* word{... - non-special */
3946 || dest.has_quoted_part /* ""{... - non-special */
3947 || (next != ';' /* }; - special */
3948 && next != ')' /* }) - special */
3949 && next != '&' /* }& and }&& ... - special */
3950 && next != '|' /* }|| ... - special */
3951 && !strchr(G.ifs, next) /* {word - non-special */
3954 /* They are not special, skip "{}" */
3957 is_special = strchr(is_special, ch);
3958 is_ifs = strchr(G.ifs, ch);
3960 if (!is_special && !is_ifs) { /* ordinary char */
3962 o_addQchr(&dest, ch);
3963 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3964 || dest.o_assignment == WORD_IS_KEYWORD)
3966 && is_well_formed_var_name(dest.data, '=')
3968 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3974 if (done_word(&dest, &ctx)) {
3978 #if ENABLE_HUSH_CASE
3979 /* "case ... in <newline> word) ..." -
3980 * newlines are ignored (but ';' wouldn't be) */
3981 if (ctx.command->argv == NULL
3982 && ctx.ctx_res_w == RES_MATCH
3987 /* Treat newline as a command separator. */
3988 done_pipe(&ctx, PIPE_SEQ);
3989 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3991 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3996 dest.o_assignment = MAYBE_ASSIGNMENT;
3998 /* note: if (is_ifs) continue;
3999 * will still trigger for us */
4003 /* "cmd}" or "cmd }..." without semicolon or &:
4004 * } is an ordinary char in this case, even inside { cmd; }
4005 * Pathological example: { ""}; } should exec "}" cmd
4008 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4009 || dest.length != 0 /* word} */
4010 || dest.has_quoted_part /* ""} */
4014 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4015 goto skip_end_trigger;
4016 /* else: } does terminate a group */
4019 if (end_trigger && end_trigger == ch
4020 && (ch != ';' || heredoc_cnt == 0)
4021 #if ENABLE_HUSH_CASE
4023 || ctx.ctx_res_w != RES_MATCH
4024 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4029 /* This is technically valid:
4030 * { cat <<HERE; }; echo Ok
4034 * but we don't support this.
4035 * We require heredoc to be in enclosing {}/(),
4038 syntax_error_unterm_str("here document");
4041 if (done_word(&dest, &ctx)) {
4044 done_pipe(&ctx, PIPE_SEQ);
4045 dest.o_assignment = MAYBE_ASSIGNMENT;
4046 /* Do we sit outside of any if's, loops or case's? */
4048 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4052 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4054 *pstring = ctx.as_string.data;
4056 o_free_unsafe(&ctx.as_string);
4059 debug_printf_parse("parse_stream return %p: "
4060 "end_trigger char found\n",
4062 return ctx.list_head;
4069 /* Catch <, > before deciding whether this word is
4070 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4073 redir_fd = redirect_opt_num(&dest);
4074 if (done_word(&dest, &ctx)) {
4077 redir_style = REDIRECT_OVERWRITE;
4079 redir_style = REDIRECT_APPEND;
4080 ch = i_getch(input);
4081 nommu_addchr(&ctx.as_string, ch);
4084 else if (next == '(') {
4085 syntax_error(">(process) not supported");
4089 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4091 continue; /* back to top of while (1) */
4093 redir_fd = redirect_opt_num(&dest);
4094 if (done_word(&dest, &ctx)) {
4097 redir_style = REDIRECT_INPUT;
4099 redir_style = REDIRECT_HEREDOC;
4101 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4104 } else if (next == '>') {
4105 redir_style = REDIRECT_IO;
4106 ch = i_getch(input);
4107 nommu_addchr(&ctx.as_string, ch);
4110 else if (next == '(') {
4111 syntax_error("<(process) not supported");
4115 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4117 continue; /* back to top of while (1) */
4120 if (dest.o_assignment == MAYBE_ASSIGNMENT
4121 /* check that we are not in word in "a=1 2>word b=1": */
4122 && !ctx.pending_redirect
4124 /* ch is a special char and thus this word
4125 * cannot be an assignment */
4126 dest.o_assignment = NOT_ASSIGNMENT;
4129 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4133 if (dest.length == 0) {
4136 if (ch == EOF || ch == '\n')
4139 /* note: we do not add it to &ctx.as_string */
4141 nommu_addchr(&ctx.as_string, '\n');
4143 o_addQchr(&dest, ch);
4148 syntax_error("\\<eof>");
4151 ch = i_getch(input);
4153 o_addchr(&dest, '\\');
4154 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4155 o_addchr(&dest, ch);
4156 nommu_addchr(&ctx.as_string, ch);
4157 /* Example: echo Hello \2>file
4158 * we need to know that word 2 is quoted */
4159 dest.has_quoted_part = 1;
4163 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4164 ctx.as_string.data[--ctx.as_string.length] = '\0';
4169 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
4170 debug_printf_parse("parse_stream parse error: "
4171 "parse_dollar returned non-0\n");
4176 dest.has_quoted_part = 1;
4178 ch = i_getch(input);
4180 syntax_error_unterm_ch('\'');
4181 /*xfunc_die(); - redundant */
4183 nommu_addchr(&ctx.as_string, ch);
4186 o_addqchr(&dest, ch);
4190 dest.has_quoted_part = 1;
4191 is_in_dquote ^= 1; /* invert */
4192 if (dest.o_assignment == NOT_ASSIGNMENT)
4195 #if ENABLE_HUSH_TICK
4199 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4200 o_addchr(&dest, '`');
4202 add_till_backquote(&dest, input);
4204 o_addstr(&ctx.as_string, dest.data + pos);
4205 o_addchr(&ctx.as_string, '`');
4207 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4208 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4213 #if ENABLE_HUSH_CASE
4216 if (done_word(&dest, &ctx)) {
4219 done_pipe(&ctx, PIPE_SEQ);
4220 #if ENABLE_HUSH_CASE
4221 /* Eat multiple semicolons, detect
4222 * whether it means something special */
4227 ch = i_getch(input);
4228 nommu_addchr(&ctx.as_string, ch);
4229 if (ctx.ctx_res_w == RES_CASE_BODY) {
4230 ctx.ctx_dsemicolon = 1;
4231 ctx.ctx_res_w = RES_MATCH;
4237 /* We just finished a cmd. New one may start
4238 * with an assignment */
4239 dest.o_assignment = MAYBE_ASSIGNMENT;
4242 if (done_word(&dest, &ctx)) {
4246 ch = i_getch(input);
4247 nommu_addchr(&ctx.as_string, ch);
4248 done_pipe(&ctx, PIPE_AND);
4250 done_pipe(&ctx, PIPE_BG);
4254 if (done_word(&dest, &ctx)) {
4257 #if ENABLE_HUSH_CASE
4258 if (ctx.ctx_res_w == RES_MATCH)
4259 break; /* we are in case's "word | word)" */
4261 if (next == '|') { /* || */
4262 ch = i_getch(input);
4263 nommu_addchr(&ctx.as_string, ch);
4264 done_pipe(&ctx, PIPE_OR);
4266 /* we could pick up a file descriptor choice here
4267 * with redirect_opt_num(), but bash doesn't do it.
4268 * "echo foo 2| cat" yields "foo 2". */
4271 o_reset_to_empty_unquoted(&ctx.as_string);
4276 #if ENABLE_HUSH_CASE
4277 /* "case... in [(]word)..." - skip '(' */
4278 if (ctx.ctx_res_w == RES_MATCH
4279 && ctx.command->argv == NULL /* not (word|(... */
4280 && dest.length == 0 /* not word(... */
4281 && dest.has_quoted_part == 0 /* not ""(... */
4287 if (parse_group(&dest, &ctx, input, ch) != 0) {
4292 #if ENABLE_HUSH_CASE
4293 if (ctx.ctx_res_w == RES_MATCH)
4297 /* proper use of this character is caught by end_trigger:
4298 * if we see {, we call parse_group(..., end_trigger='}')
4299 * and it will match } earlier (not here). */
4300 syntax_error_unexpected_ch(ch);
4304 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4310 struct parse_context *pctx;
4311 IF_HAS_KEYWORDS(struct parse_context *p2;)
4313 /* Clean up allocated tree.
4314 * Sample for finding leaks on syntax error recovery path.
4315 * Run it from interactive shell, watch pmap `pidof hush`.
4316 * while if false; then false; fi; do break; fi
4317 * Samples to catch leaks at execution:
4318 * while if (true | {true;}); then echo ok; fi; do break; done
4319 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4323 /* Update pipe/command counts,
4324 * otherwise freeing may miss some */
4325 done_pipe(pctx, PIPE_SEQ);
4326 debug_printf_clean("freeing list %p from ctx %p\n",
4327 pctx->list_head, pctx);
4328 debug_print_tree(pctx->list_head, 0);
4329 free_pipe_list(pctx->list_head);
4330 debug_printf_clean("freed list %p\n", pctx->list_head);
4332 o_free_unsafe(&pctx->as_string);
4334 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4338 IF_HAS_KEYWORDS(pctx = p2;)
4339 } while (HAS_KEYWORDS && pctx);
4340 /* Free text, clear all dest fields */
4342 /* If we are not in top-level parse, we return,
4343 * our caller will propagate error.
4345 if (end_trigger != ';') {
4353 /* Discard cached input, force prompt */
4355 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4361 /*** Execution routines ***/
4363 /* Expansion can recurse, need forward decls: */
4364 static char *expand_string_to_string(const char *str);
4365 static int process_command_subs(o_string *dest, const char *s);
4367 /* expand_strvec_to_strvec() takes a list of strings, expands
4368 * all variable references within and returns a pointer to
4369 * a list of expanded strings, possibly with larger number
4370 * of strings. (Think VAR="a b"; echo $VAR).
4371 * This new list is allocated as a single malloc block.
4372 * NULL-terminated list of char* pointers is at the beginning of it,
4373 * followed by strings themself.
4374 * Caller can deallocate entire list by single free(list). */
4376 /* Store given string, finalizing the word and starting new one whenever
4377 * we encounter IFS char(s). This is used for expanding variable values.
4378 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4379 static int expand_on_ifs(o_string *output, int n, const char *str)
4382 int word_len = strcspn(str, G.ifs);
4384 if (output->o_escape || !output->o_glob)
4385 o_addQblock(output, str, word_len);
4386 else /* protect backslashes against globbing up :) */
4387 o_addblock_duplicate_backslash(output, str, word_len);
4390 if (!*str) /* EOL - do not finalize word */
4392 o_addchr(output, '\0');
4393 debug_print_list("expand_on_ifs", output, n);
4394 n = o_save_ptr(output, n);
4395 str += strspn(str, G.ifs); /* skip ifs chars */
4397 debug_print_list("expand_on_ifs[1]", output, n);
4401 /* Helper to expand $((...)) and heredoc body. These act as if
4402 * they are in double quotes, with the exception that they are not :).
4403 * Just the rules are similar: "expand only $var and `cmd`"
4405 * Returns malloced string.
4406 * As an optimization, we return NULL if expansion is not needed.
4408 static char *expand_pseudo_dquoted(const char *str)
4411 struct in_str input;
4412 o_string dest = NULL_O_STRING;
4414 if (!strchr(str, '$')
4415 #if ENABLE_HUSH_TICK
4416 && !strchr(str, '`')
4422 /* We need to expand. Example:
4423 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4425 setup_string_in_str(&input, str);
4426 parse_stream_dquoted(NULL, &dest, &input, EOF);
4427 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4428 exp_str = expand_string_to_string(dest.data);
4429 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4430 o_free_unsafe(&dest);
4434 #if ENABLE_SH_MATH_SUPPORT
4435 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4437 arith_eval_hooks_t hooks;
4441 hooks.lookupvar = get_local_var_value;
4442 hooks.setvar = set_local_var_from_halves;
4443 hooks.endofname = endofname;
4444 exp_str = expand_pseudo_dquoted(arg);
4445 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4451 #if ENABLE_HUSH_BASH_COMPAT
4452 /* ${var/[/]pattern[/repl]} helpers */
4453 static char *strstr_pattern(char *val, const char *pattern, int *size)
4456 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4457 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4464 /* Optimization: if "*pat" did not match the start of "string",
4465 * we know that "tring", "ring" etc will not match too:
4467 if (pattern[0] == '*')
4472 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4474 char *result = NULL;
4475 unsigned res_len = 0;
4476 unsigned repl_len = strlen(repl);
4480 char *s = strstr_pattern(val, pattern, &size);
4484 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4485 memcpy(result + res_len, val, s - val);
4487 strcpy(result + res_len, repl);
4488 res_len += repl_len;
4489 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4495 if (val[0] && result) {
4496 result = xrealloc(result, res_len + strlen(val) + 1);
4497 strcpy(result + res_len, val);
4498 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4500 debug_printf_varexp("result:'%s'\n", result);
4506 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4508 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4510 const char *val = NULL;
4511 char *to_be_freed = NULL;
4516 char exp_save = exp_save; /* for compiler */
4517 char *exp_saveptr; /* points to expansion operator */
4518 char *exp_word = exp_word; /* for compiler */
4522 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4523 first_char = arg[0] = first_ch & 0x7f;
4526 if (first_char == '#' && arg[1] && !exp_saveptr) {
4527 /* handle length expansion ${#var} */
4531 /* maybe handle parameter expansion */
4532 if (exp_saveptr /* if 2nd char is one of expansion operators */
4533 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4535 /* ${?:0}, ${#[:]%0} etc */
4536 exp_saveptr = var + 1;
4538 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4539 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4541 exp_op = exp_save = *exp_saveptr;
4543 exp_word = exp_saveptr + 1;
4544 if (exp_op == ':') {
4545 exp_op = *exp_word++;
4546 if (ENABLE_HUSH_BASH_COMPAT
4547 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4549 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4554 *exp_saveptr = '\0';
4555 } /* else: it's not an expansion op, but bare ${var} */
4558 /* lookup the variable in question */
4559 if (isdigit(var[0])) {
4560 /* parse_dollar() should have vetted var for us */
4561 int n = xatoi_positive(var);
4562 if (n < G.global_argc)
4563 val = G.global_argv[n];
4564 /* else val remains NULL: $N with too big N */
4568 val = utoa(G.root_pid);
4570 case '!': /* bg pid */
4571 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4573 case '?': /* exitcode */
4574 val = utoa(G.last_exitcode);
4576 case '#': /* argc */
4577 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4580 val = get_local_var_value(var);
4584 /* Handle any expansions */
4585 if (exp_op == 'L') {
4586 debug_printf_expand("expand: length(%s)=", val);
4587 val = utoa(val ? strlen(val) : 0);
4588 debug_printf_expand("%s\n", val);
4589 } else if (exp_op) {
4590 if (exp_op == '%' || exp_op == '#') {
4591 /* Standard-mandated substring removal ops:
4592 * ${parameter%word} - remove smallest suffix pattern
4593 * ${parameter%%word} - remove largest suffix pattern
4594 * ${parameter#word} - remove smallest prefix pattern
4595 * ${parameter##word} - remove largest prefix pattern
4597 * Word is expanded to produce a glob pattern.
4598 * Then var's value is matched to it and matching part removed.
4600 if (val && val[0]) {
4603 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4604 if (exp_op == *exp_word) /* ## or %% */
4606 //TODO: avoid xstrdup unless needed
4607 // (see HACK ALERT below)
4608 val = to_be_freed = xstrdup(val);
4609 exp_exp_word = expand_pseudo_dquoted(exp_word);
4611 exp_word = exp_exp_word;
4612 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4613 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4614 // exp_op, to_be_freed, exp_word, loc);
4616 if (loc) { /* match was found */
4617 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4624 #if ENABLE_HUSH_BASH_COMPAT
4625 else if (exp_op == '/' || exp_op == '\\') {
4626 /* Empty variable always gives nothing: */
4627 // "v=''; echo ${v/*/w}" prints ""
4628 if (val && val[0]) {
4629 /* It's ${var/[/]pattern[/repl]} thing */
4630 char *pattern, *repl, *t;
4631 pattern = expand_pseudo_dquoted(exp_word);
4633 pattern = xstrdup(exp_word);
4634 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4635 *p++ = SPECIAL_VAR_SYMBOL;
4637 p = strchr(p, SPECIAL_VAR_SYMBOL);
4639 repl = expand_pseudo_dquoted(exp_word);
4640 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4641 /* HACK ALERT. We depend here on the fact that
4642 * G.global_argv and results of utoa and get_local_var_value
4643 * are actually in writable memory:
4644 * replace_pattern momentarily stores NULs there. */
4646 to_be_freed = replace_pattern(t,
4648 (repl ? repl : exp_word),
4650 if (to_be_freed) /* at least one replace happened */
4657 else if (exp_op == ':') {
4658 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4659 /* It's ${var:N[:M]} bashism.
4660 * Note that in encoded form it has TWO parts:
4661 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4666 beg = expand_and_evaluate_arith(exp_word, &errcode);
4667 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4668 *p++ = SPECIAL_VAR_SYMBOL;
4670 p = strchr(p, SPECIAL_VAR_SYMBOL);
4672 len = expand_and_evaluate_arith(exp_word, &errcode);
4673 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4675 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4676 if (beg < 0) /* bash compat */
4678 debug_printf_varexp("from val:'%s'\n", val);
4679 if (len == 0 || !val || beg >= strlen(val))
4682 /* Paranoia. What if user entered 9999999999999
4683 * which fits in arith_t but not int? */
4686 val = to_be_freed = xstrndup(val + beg, len);
4688 debug_printf_varexp("val:'%s'\n", val);
4692 die_if_script("malformed ${%s:...}", var);
4695 } else { /* one of "-=+?" */
4696 /* Standard-mandated substitution ops:
4697 * ${var?word} - indicate error if unset
4698 * If var is unset, word (or a message indicating it is unset
4699 * if word is null) is written to standard error
4700 * and the shell exits with a non-zero exit status.
4701 * Otherwise, the value of var is substituted.
4702 * ${var-word} - use default value
4703 * If var is unset, word is substituted.
4704 * ${var=word} - assign and use default value
4705 * If var is unset, word is assigned to var.
4706 * In all cases, final value of var is substituted.
4707 * ${var+word} - use alternative value
4708 * If var is unset, null is substituted.
4709 * Otherwise, word is substituted.
4711 * Word is subjected to tilde expansion, parameter expansion,
4712 * command substitution, and arithmetic expansion.
4713 * If word is not needed, it is not expanded.
4715 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4716 * but also treat null var as if it is unset.
4718 int use_word = (!val || ((exp_save == ':') && !val[0]));
4720 use_word = !use_word;
4721 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4722 (exp_save == ':') ? "true" : "false", use_word);
4724 to_be_freed = expand_pseudo_dquoted(exp_word);
4726 exp_word = to_be_freed;
4727 if (exp_op == '?') {
4728 /* mimic bash message */
4729 die_if_script("%s: %s",
4731 exp_word[0] ? exp_word : "parameter null or not set"
4733 //TODO: how interactive bash aborts expansion mid-command?
4738 if (exp_op == '=') {
4739 /* ${var=[word]} or ${var:=[word]} */
4740 if (isdigit(var[0]) || var[0] == '#') {
4741 /* mimic bash message */
4742 die_if_script("$%s: cannot assign in this way", var);
4745 char *new_var = xasprintf("%s=%s", var, val);
4746 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4750 } /* one of "-=+?" */
4752 *exp_saveptr = exp_save;
4758 *to_be_freed_pp = to_be_freed;
4762 /* Expand all variable references in given string, adding words to list[]
4763 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4764 * to be filled). This routine is extremely tricky: has to deal with
4765 * variables/parameters with whitespace, $* and $@, and constructs like
4766 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4767 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4769 /* or_mask is either 0 (normal case) or 0x80 -
4770 * expansion of right-hand side of assignment == 1-element expand.
4771 * It will also do no globbing, and thus we must not backslash-quote!
4778 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4779 debug_print_list("expand_vars_to_list", output, n);
4780 n = o_save_ptr(output, n);
4781 debug_print_list("expand_vars_to_list[0]", output, n);
4783 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4786 char *to_be_freed = NULL;
4787 const char *val = NULL;
4788 #if ENABLE_HUSH_TICK
4789 o_string subst_result = NULL_O_STRING;
4791 #if ENABLE_SH_MATH_SUPPORT
4792 char arith_buf[sizeof(arith_t)*3 + 2];
4794 o_addblock(output, arg, p - arg);
4795 debug_print_list("expand_vars_to_list[1]", output, n);
4797 p = strchr(p, SPECIAL_VAR_SYMBOL);
4799 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4800 /* "$@" is special. Even if quoted, it can still
4801 * expand to nothing (not even an empty string) */
4802 if ((first_ch & 0x7f) != '@')
4803 ored_ch |= first_ch;
4805 switch (first_ch & 0x7f) {
4806 /* Highest bit in first_ch indicates that var is double-quoted */
4810 if (!G.global_argv[i])
4812 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4813 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4814 smallint sv = output->o_escape;
4815 /* unquoted var's contents should be globbed, so don't escape */
4816 output->o_escape = 0;
4817 while (G.global_argv[i]) {
4818 n = expand_on_ifs(output, n, G.global_argv[i]);
4819 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4820 if (G.global_argv[i++][0] && G.global_argv[i]) {
4821 /* this argv[] is not empty and not last:
4822 * put terminating NUL, start new word */
4823 o_addchr(output, '\0');
4824 debug_print_list("expand_vars_to_list[2]", output, n);
4825 n = o_save_ptr(output, n);
4826 debug_print_list("expand_vars_to_list[3]", output, n);
4829 output->o_escape = sv;
4831 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4832 * and in this case should treat it like '$*' - see 'else...' below */
4833 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4835 o_addQstr(output, G.global_argv[i]);
4836 if (++i >= G.global_argc)
4838 o_addchr(output, '\0');
4839 debug_print_list("expand_vars_to_list[4]", output, n);
4840 n = o_save_ptr(output, n);
4842 } else { /* quoted $*: add as one word */
4844 o_addQstr(output, G.global_argv[i]);
4845 if (!G.global_argv[++i])
4848 o_addchr(output, G.ifs[0]);
4852 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4853 /* "Empty variable", used to make "" etc to not disappear */
4857 #if ENABLE_HUSH_TICK
4858 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4861 /* Can't just stuff it into output o_string,
4862 * expanded result may need to be globbed
4863 * and $IFS-splitted */
4864 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4865 G.last_exitcode = process_command_subs(&subst_result, arg);
4866 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4867 val = subst_result.data;
4870 #if ENABLE_SH_MATH_SUPPORT
4871 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4875 arg++; /* skip '+' */
4876 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4877 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4878 res = expand_and_evaluate_arith(arg, &errcode);
4881 const char *msg = "error in arithmetic";
4884 msg = "exponent less than 0";
4887 msg = "divide by 0";
4890 msg = "expression recursion loop detected";
4895 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4896 sprintf(arith_buf, arith_t_fmt, res);
4902 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4903 IF_HUSH_TICK(store_val:)
4904 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4905 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4906 if (val && val[0]) {
4907 /* unquoted var's contents should be globbed, so don't escape */
4908 smallint sv = output->o_escape;
4909 output->o_escape = 0;
4910 n = expand_on_ifs(output, n, val);
4912 output->o_escape = sv;
4914 } else { /* quoted $VAR, val will be appended below */
4915 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4919 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4921 if (val && val[0]) {
4922 o_addQstr(output, val);
4925 /* Do the check to avoid writing to a const string */
4926 if (*p != SPECIAL_VAR_SYMBOL)
4927 *p = SPECIAL_VAR_SYMBOL;
4929 #if ENABLE_HUSH_TICK
4930 o_free(&subst_result);
4933 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4936 debug_print_list("expand_vars_to_list[a]", output, n);
4937 /* this part is literal, and it was already pre-quoted
4938 * if needed (much earlier), do not use o_addQstr here! */
4939 o_addstr_with_NUL(output, arg);
4940 debug_print_list("expand_vars_to_list[b]", output, n);
4941 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4942 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4945 /* allow to reuse list[n] later without re-growth */
4946 output->has_empty_slot = 1;
4948 o_addchr(output, '\0');
4955 EXPVAR_FLAG_GLOB = 0x200,
4956 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4957 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4959 static char **expand_variables(char **argv, unsigned or_mask)
4964 o_string output = NULL_O_STRING;
4966 /* protect against globbing for "$var"? */
4967 /* (unquoted $var will temporarily switch it off) */
4968 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4969 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
4974 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
4977 debug_print_list("expand_variables", &output, n);
4979 /* output.data (malloced in one block) gets returned in "list" */
4980 list = o_finalize_list(&output, n);
4981 debug_print_strings("expand_variables[1]", list);
4985 static char **expand_strvec_to_strvec(char **argv)
4987 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
4990 #if ENABLE_HUSH_BASH_COMPAT
4991 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
4993 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
4997 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4998 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
5003 o_string output = NULL_O_STRING;
5008 int is_var = is_well_formed_var_name(*v, '=');
5009 /* is_var * 0x80: singleword expansion for vars */
5010 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
5012 /* Subtle! expand_vars_to_list did not glob last word yet.
5013 * It does this only when fed with further data.
5014 * Therefore we set globbing flags AFTER it, not before:
5017 /* if it is not recognizably abc=...; then: */
5018 output.o_escape = !is_var; /* protect against globbing for "$var" */
5019 /* (unquoted $var will temporarily switch it off) */
5020 output.o_glob = !is_var; /* and indeed do globbing */
5023 debug_print_list("expand_cond", &output, n);
5025 /* output.data (malloced in one block) gets returned in "list" */
5026 list = o_finalize_list(&output, n);
5027 debug_print_strings("expand_cond[1]", list);
5032 /* Used for expansion of right hand of assignments */
5033 /* NB: should NOT do globbing!
5034 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5035 static char *expand_string_to_string(const char *str)
5037 char *argv[2], **list;
5039 /* This is generally an optimization, but it also
5040 * handles "", which otherwise trips over !list[0] check below.
5041 * (is this ever happens that we actually get str="" here?)
5043 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5044 //TODO: Can use on strings with \ too, just unbackslash() them?
5045 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5046 return xstrdup(str);
5049 argv[0] = (char*)str;
5051 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5053 if (!list[0] || list[1])
5054 bb_error_msg_and_die("BUG in varexp2");
5055 /* actually, just move string 2*sizeof(char*) bytes back */
5056 overlapping_strcpy((char*)list, list[0]);
5057 unbackslash((char*)list);
5058 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5062 /* Used for "eval" builtin */
5063 static char* expand_strvec_to_string(char **argv)
5067 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5068 /* Convert all NULs to spaces */
5073 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5074 bb_error_msg_and_die("BUG in varexp3");
5075 /* bash uses ' ' regardless of $IFS contents */
5080 overlapping_strcpy((char*)list, list[0]);
5081 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5085 static char **expand_assignments(char **argv, int count)
5090 G.expanded_assignments = p = NULL;
5091 /* Expand assignments into one string each */
5092 for (i = 0; i < count; i++) {
5093 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5095 G.expanded_assignments = NULL;
5102 void re_execute_shell(char ***to_free, const char *s,
5103 char *g_argv0, char **g_argv,
5104 char **builtin_argv) NORETURN;
5106 static void reset_traps_to_defaults(void)
5108 /* This function is always called in a child shell
5109 * after fork (not vfork, NOMMU doesn't use this function).
5114 /* Child shells are not interactive.
5115 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5116 * Testcase: (while :; do :; done) + ^Z should background.
5117 * Same goes for SIGTERM, SIGHUP, SIGINT.
5119 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5120 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5122 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5123 * Stupid. It can be done with *single* &= op, but we can't use
5124 * the fact that G.blocked_set is implemented as a bitmask
5126 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5130 /* Careful. Only if no trap or trap is not "" */
5131 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5132 sigdelset(&G.blocked_set, sig);
5139 /* Our homegrown sig mask is saner to work with :) */
5140 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5142 /* Resetting all traps to default except empty ones */
5143 mask = G.non_DFL_mask;
5144 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5145 if (!G.traps[sig] || !G.traps[sig][0])
5148 G.traps[sig] = NULL;
5149 /* There is no signal for 0 (EXIT) */
5152 /* There was a trap handler, we just removed it.
5153 * But if sig still has non-DFL handling,
5154 * we should not unblock the sig. */
5157 sigdelset(&G.blocked_set, sig);
5159 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5164 static void re_execute_shell(char ***to_free, const char *s,
5165 char *g_argv0, char **g_argv,
5166 char **builtin_argv) NORETURN;
5167 static void re_execute_shell(char ***to_free, const char *s,
5168 char *g_argv0, char **g_argv,
5169 char **builtin_argv)
5171 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5172 /* delims + 2 * (number of bytes in printed hex numbers) */
5173 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5174 char *heredoc_argv[4];
5175 struct variable *cur;
5176 # if ENABLE_HUSH_FUNCTIONS
5177 struct function *funcp;
5181 unsigned long long empty_trap_mask;
5183 if (!g_argv0) { /* heredoc */
5184 argv = heredoc_argv;
5185 argv[0] = (char *) G.argv0_for_re_execing;
5186 argv[1] = (char *) "-<";
5187 argv[2] = (char *) s;
5189 pp = &argv[3]; /* used as pointer to empty environment */
5195 if (pp) while (*pp++)
5198 empty_trap_mask = 0;
5201 for (sig = 1; sig < NSIG; sig++) {
5202 if (G.traps[sig] && !G.traps[sig][0])
5203 empty_trap_mask |= 1LL << sig;
5207 sprintf(param_buf, NOMMU_HACK_FMT
5208 , (unsigned) G.root_pid
5209 , (unsigned) G.root_ppid
5210 , (unsigned) G.last_bg_pid
5211 , (unsigned) G.last_exitcode
5214 IF_HUSH_LOOPS(, G.depth_of_loop)
5216 # undef NOMMU_HACK_FMT
5217 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5218 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5221 for (cur = G.top_var; cur; cur = cur->next) {
5222 if (!cur->flg_export || cur->flg_read_only)
5225 # if ENABLE_HUSH_FUNCTIONS
5226 for (funcp = G.top_func; funcp; funcp = funcp->next)
5232 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5233 *pp++ = (char *) G.argv0_for_re_execing;
5235 for (cur = G.top_var; cur; cur = cur->next) {
5236 if (strcmp(cur->varstr, hush_version_str) == 0)
5238 if (cur->flg_read_only) {
5239 *pp++ = (char *) "-R";
5240 *pp++ = cur->varstr;
5241 } else if (!cur->flg_export) {
5242 *pp++ = (char *) "-V";
5243 *pp++ = cur->varstr;
5246 # if ENABLE_HUSH_FUNCTIONS
5247 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5248 *pp++ = (char *) "-F";
5249 *pp++ = funcp->name;
5250 *pp++ = funcp->body_as_string;
5253 /* We can pass activated traps here. Say, -Tnn:trap_string
5255 * However, POSIX says that subshells reset signals with traps
5257 * I tested bash-3.2 and it not only does that with true subshells
5258 * of the form ( list ), but with any forked children shells.
5259 * I set trap "echo W" WINCH; and then tried:
5261 * { echo 1; sleep 20; echo 2; } &
5262 * while true; do echo 1; sleep 20; echo 2; break; done &
5263 * true | { echo 1; sleep 20; echo 2; } | cat
5265 * In all these cases sending SIGWINCH to the child shell
5266 * did not run the trap. If I add trap "echo V" WINCH;
5267 * _inside_ group (just before echo 1), it works.
5269 * I conclude it means we don't need to pass active traps here.
5270 * Even if we would use signal handlers instead of signal masking
5271 * in order to implement trap handling,
5272 * exec syscall below resets signals to SIG_DFL for us.
5274 *pp++ = (char *) "-c";
5277 while (*++builtin_argv)
5278 *pp++ = *builtin_argv;
5279 *pp++ = (char *) "";
5284 /* *pp = NULL; - is already there */
5288 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5289 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5290 execve(bb_busybox_exec_path, argv, pp);
5291 /* Fallback. Useful for init=/bin/hush usage etc */
5292 if (argv[0][0] == '/')
5293 execve(argv[0], argv, pp);
5294 xfunc_error_retval = 127;
5295 bb_error_msg_and_die("can't re-execute the shell");
5297 #endif /* !BB_MMU */
5300 static int run_and_free_list(struct pipe *pi);
5302 /* Executing from string: eval, sh -c '...'
5303 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5304 * end_trigger controls how often we stop parsing
5305 * NUL: parse all, execute, return
5306 * ';': parse till ';' or newline, execute, repeat till EOF
5308 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5310 /* Why we need empty flag?
5311 * An obscure corner case "false; ``; echo $?":
5312 * empty command in `` should still set $? to 0.
5313 * But we can't just set $? to 0 at the start,
5314 * this breaks "false; echo `echo $?`" case.
5318 struct pipe *pipe_list;
5320 pipe_list = parse_stream(NULL, inp, end_trigger);
5321 if (!pipe_list) { /* EOF */
5323 G.last_exitcode = 0;
5326 debug_print_tree(pipe_list, 0);
5327 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5328 run_and_free_list(pipe_list);
5333 static void parse_and_run_string(const char *s)
5335 struct in_str input;
5336 setup_string_in_str(&input, s);
5337 parse_and_run_stream(&input, '\0');
5340 static void parse_and_run_file(FILE *f)
5342 struct in_str input;
5343 setup_file_in_str(&input, f);
5344 parse_and_run_stream(&input, ';');
5347 #if ENABLE_HUSH_TICK
5348 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5353 char **to_free = NULL;
5357 pid = BB_MMU ? xfork() : xvfork();
5358 if (pid == 0) { /* child */
5359 disable_restore_tty_pgrp_on_exit();
5360 /* Process substitution is not considered to be usual
5361 * 'command execution'.
5362 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5369 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5370 close(channel[0]); /* NB: close _first_, then move fd! */
5371 xmove_fd(channel[1], 1);
5372 /* Prevent it from trying to handle ctrl-z etc */
5373 IF_HUSH_JOB(G.run_list_level = 1;)
5374 /* Awful hack for `trap` or $(trap).
5376 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5377 * contains an example where "trap" is executed in a subshell:
5379 * save_traps=$(trap)
5381 * eval "$save_traps"
5383 * Standard does not say that "trap" in subshell shall print
5384 * parent shell's traps. It only says that its output
5385 * must have suitable form, but then, in the above example
5386 * (which is not supposed to be normative), it implies that.
5388 * bash (and probably other shell) does implement it
5389 * (traps are reset to defaults, but "trap" still shows them),
5390 * but as a result, "trap" logic is hopelessly messed up:
5393 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5394 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5395 * # true | trap <--- trap is in subshell - no output (ditto)
5396 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5397 * trap -- 'echo Ho' SIGWINCH
5398 * # echo `(trap)` <--- in subshell in subshell - output
5399 * trap -- 'echo Ho' SIGWINCH
5400 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5401 * trap -- 'echo Ho' SIGWINCH
5403 * The rules when to forget and when to not forget traps
5404 * get really complex and nonsensical.
5406 * Our solution: ONLY bare $(trap) or `trap` is special.
5408 s = skip_whitespace(s);
5409 if (strncmp(s, "trap", 4) == 0
5410 && skip_whitespace(s + 4)[0] == '\0'
5412 static const char *const argv[] = { NULL, NULL };
5413 builtin_trap((char**)argv);
5414 exit(0); /* not _exit() - we need to fflush */
5417 reset_traps_to_defaults();
5418 parse_and_run_string(s);
5419 _exit(G.last_exitcode);
5421 /* We re-execute after vfork on NOMMU. This makes this script safe:
5422 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5423 * huge=`cat BIG` # was blocking here forever
5426 re_execute_shell(&to_free,
5436 # if ENABLE_HUSH_FAST
5438 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5439 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5440 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5442 enable_restore_tty_pgrp_on_exit();
5447 close_on_exec_on(channel[0]);
5448 return xfdopen_for_read(channel[0]);
5451 /* Return code is exit status of the process that is run. */
5452 static int process_command_subs(o_string *dest, const char *s)
5455 struct in_str pipe_str;
5457 int status, ch, eol_cnt;
5459 fp = generate_stream_from_string(s, &pid);
5461 /* Now send results of command back into original context */
5462 setup_file_in_str(&pipe_str, fp);
5464 while ((ch = i_getch(&pipe_str)) != EOF) {
5470 o_addchr(dest, '\n');
5473 o_addQchr(dest, ch);
5476 debug_printf("done reading from `cmd` pipe, closing it\n");
5478 /* We need to extract exitcode. Test case
5479 * "true; echo `sleep 1; false` $?"
5481 safe_waitpid(pid, &status, 0);
5482 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5483 return WEXITSTATUS(status);
5485 #endif /* ENABLE_HUSH_TICK */
5488 static void setup_heredoc(struct redir_struct *redir)
5490 struct fd_pair pair;
5493 /* the _body_ of heredoc (misleading field name) */
5494 const char *heredoc = redir->rd_filename;
5501 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5502 expanded = expand_pseudo_dquoted(heredoc);
5506 len = strlen(heredoc);
5508 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5510 xmove_fd(pair.rd, redir->rd_fd);
5512 /* Try writing without forking. Newer kernels have
5513 * dynamically growing pipes. Must use non-blocking write! */
5516 written = write(pair.wr, heredoc, len);
5527 ndelay_off(pair.wr);
5529 /* Okay, pipe buffer was not big enough */
5530 /* Note: we must not create a stray child (bastard? :)
5531 * for the unsuspecting parent process. Child creates a grandchild
5532 * and exits before parent execs the process which consumes heredoc
5533 * (that exec happens after we return from this function) */
5540 disable_restore_tty_pgrp_on_exit();
5541 pid = BB_MMU ? xfork() : xvfork();
5545 close(redir->rd_fd); /* read side of the pipe */
5547 full_write(pair.wr, heredoc, len); /* may loop or block */
5550 /* Delegate blocking writes to another process */
5551 xmove_fd(pair.wr, STDOUT_FILENO);
5552 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5556 #if ENABLE_HUSH_FAST
5558 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5560 enable_restore_tty_pgrp_on_exit();
5566 wait(NULL); /* wait till child has died */
5569 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5570 * and stderr if they are redirected. */
5571 static int setup_redirects(struct command *prog, int squirrel[])
5574 struct redir_struct *redir;
5576 for (redir = prog->redirects; redir; redir = redir->next) {
5577 if (redir->rd_type == REDIRECT_HEREDOC2) {
5578 /* rd_fd<<HERE case */
5579 if (squirrel && redir->rd_fd < 3
5580 && squirrel[redir->rd_fd] < 0
5582 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5584 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5586 debug_printf_parse("set heredoc '%s'\n",
5587 redir->rd_filename);
5588 setup_heredoc(redir);
5592 if (redir->rd_dup == REDIRFD_TO_FILE) {
5593 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5595 if (redir->rd_filename == NULL) {
5596 /* Something went wrong in the parse.
5597 * Pretend it didn't happen */
5598 bb_error_msg("bug in redirect parse");
5601 mode = redir_table[redir->rd_type].mode;
5602 p = expand_string_to_string(redir->rd_filename);
5603 openfd = open_or_warn(p, mode);
5606 /* this could get lost if stderr has been redirected, but
5607 * bash and ash both lose it as well (though zsh doesn't!) */
5608 //what the above comment tries to say?
5612 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5613 openfd = redir->rd_dup;
5616 if (openfd != redir->rd_fd) {
5617 if (squirrel && redir->rd_fd < 3
5618 && squirrel[redir->rd_fd] < 0
5620 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5622 if (openfd == REDIRFD_CLOSE) {
5623 /* "n>-" means "close me" */
5624 close(redir->rd_fd);
5626 xdup2(openfd, redir->rd_fd);
5627 if (redir->rd_dup == REDIRFD_TO_FILE)
5635 static void restore_redirects(int squirrel[])
5638 for (i = 0; i < 3; i++) {
5641 /* We simply die on error */
5647 static char *find_in_path(const char *arg)
5650 const char *PATH = get_local_var_value("PATH");
5656 const char *end = strchrnul(PATH, ':');
5657 int sz = end - PATH; /* must be int! */
5661 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5663 /* We have xxx::yyyy in $PATH,
5664 * it means "use current dir" */
5667 if (access(ret, F_OK) == 0)
5680 static const struct built_in_command* find_builtin_helper(const char *name,
5681 const struct built_in_command *x,
5682 const struct built_in_command *end)
5685 if (strcmp(name, x->b_cmd) != 0) {
5689 debug_printf_exec("found builtin '%s'\n", name);
5694 static const struct built_in_command* find_builtin1(const char *name)
5696 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5698 static const struct built_in_command* find_builtin(const char *name)
5700 const struct built_in_command *x = find_builtin1(name);
5703 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5706 #if ENABLE_HUSH_FUNCTIONS
5707 static struct function **find_function_slot(const char *name)
5709 struct function **funcpp = &G.top_func;
5711 if (strcmp(name, (*funcpp)->name) == 0) {
5714 funcpp = &(*funcpp)->next;
5719 static const struct function *find_function(const char *name)
5721 const struct function *funcp = *find_function_slot(name);
5723 debug_printf_exec("found function '%s'\n", name);
5727 /* Note: takes ownership on name ptr */
5728 static struct function *new_function(char *name)
5730 struct function **funcpp = find_function_slot(name);
5731 struct function *funcp = *funcpp;
5733 if (funcp != NULL) {
5734 struct command *cmd = funcp->parent_cmd;
5735 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5737 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5739 /* Note: if !funcp->body, do not free body_as_string!
5740 * This is a special case of "-F name body" function:
5741 * body_as_string was not malloced! */
5743 free_pipe_list(funcp->body);
5745 free(funcp->body_as_string);
5749 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5750 cmd->argv[0] = funcp->name;
5751 cmd->group = funcp->body;
5753 cmd->group_as_string = funcp->body_as_string;
5757 debug_printf_exec("remembering new function '%s'\n", name);
5758 funcp = *funcpp = xzalloc(sizeof(*funcp));
5759 /*funcp->next = NULL;*/
5766 static void unset_func(const char *name)
5768 struct function **funcpp = find_function_slot(name);
5769 struct function *funcp = *funcpp;
5771 if (funcp != NULL) {
5772 debug_printf_exec("freeing function '%s'\n", funcp->name);
5773 *funcpp = funcp->next;
5774 /* funcp is unlinked now, deleting it.
5775 * Note: if !funcp->body, the function was created by
5776 * "-F name body", do not free ->body_as_string
5777 * and ->name as they were not malloced. */
5779 free_pipe_list(funcp->body);
5782 free(funcp->body_as_string);
5790 #define exec_function(to_free, funcp, argv) \
5791 exec_function(funcp, argv)
5793 static void exec_function(char ***to_free,
5794 const struct function *funcp,
5795 char **argv) NORETURN;
5796 static void exec_function(char ***to_free,
5797 const struct function *funcp,
5803 argv[0] = G.global_argv[0];
5804 G.global_argv = argv;
5808 /* On MMU, funcp->body is always non-NULL */
5809 n = run_list(funcp->body);
5813 re_execute_shell(to_free,
5814 funcp->body_as_string,
5821 static int run_function(const struct function *funcp, char **argv)
5827 save_and_replace_G_args(&sv, argv);
5829 /* "we are in function, ok to use return" */
5830 sv_flg = G.flag_return_in_progress;
5831 G.flag_return_in_progress = -1;
5832 # if ENABLE_HUSH_LOCAL
5833 G.func_nest_level++;
5836 /* On MMU, funcp->body is always non-NULL */
5839 /* Function defined by -F */
5840 parse_and_run_string(funcp->body_as_string);
5841 rc = G.last_exitcode;
5845 rc = run_list(funcp->body);
5848 # if ENABLE_HUSH_LOCAL
5850 struct variable *var;
5851 struct variable **var_pp;
5853 var_pp = &G.top_var;
5854 while ((var = *var_pp) != NULL) {
5855 if (var->func_nest_level < G.func_nest_level) {
5856 var_pp = &var->next;
5860 if (var->flg_export)
5861 bb_unsetenv(var->varstr);
5862 /* Remove from global list */
5863 *var_pp = var->next;
5869 G.func_nest_level--;
5872 G.flag_return_in_progress = sv_flg;
5874 restore_G_args(&sv, argv);
5878 #endif /* ENABLE_HUSH_FUNCTIONS */
5882 #define exec_builtin(to_free, x, argv) \
5883 exec_builtin(x, argv)
5885 #define exec_builtin(to_free, x, argv) \
5886 exec_builtin(to_free, argv)
5888 static void exec_builtin(char ***to_free,
5889 const struct built_in_command *x,
5890 char **argv) NORETURN;
5891 static void exec_builtin(char ***to_free,
5892 const struct built_in_command *x,
5896 int rcode = x->b_function(argv);
5900 /* On NOMMU, we must never block!
5901 * Example: { sleep 99 | read line; } & echo Ok
5903 re_execute_shell(to_free,
5912 static void execvp_or_die(char **argv) NORETURN;
5913 static void execvp_or_die(char **argv)
5915 debug_printf_exec("execing '%s'\n", argv[0]);
5916 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5917 execvp(argv[0], argv);
5918 bb_perror_msg("can't execute '%s'", argv[0]);
5919 _exit(127); /* bash compat */
5922 #if ENABLE_HUSH_MODE_X
5923 static void dump_cmd_in_x_mode(char **argv)
5925 if (G_x_mode && argv) {
5926 /* We want to output the line in one write op */
5934 len += strlen(argv[n++]) + 1;
5940 p += sprintf(p, " %s", argv[n++]);
5948 # define dump_cmd_in_x_mode(argv) ((void)0)
5952 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5953 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5954 #define pseudo_exec(nommu_save, command, argv_expanded) \
5955 pseudo_exec(command, argv_expanded)
5958 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5960 * Don't exit() here. If you don't exec, use _exit instead.
5961 * The at_exit handlers apparently confuse the calling process,
5962 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5963 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5964 char **argv, int assignment_cnt,
5965 char **argv_expanded) NORETURN;
5966 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5967 char **argv, int assignment_cnt,
5968 char **argv_expanded)
5972 new_env = expand_assignments(argv, assignment_cnt);
5973 dump_cmd_in_x_mode(new_env);
5975 if (!argv[assignment_cnt]) {
5976 /* Case when we are here: ... | var=val | ...
5977 * (note that we do not exit early, i.e., do not optimize out
5978 * expand_assignments(): think about ... | var=`sleep 1` | ...
5980 free_strings(new_env);
5981 _exit(EXIT_SUCCESS);
5985 set_vars_and_save_old(new_env);
5986 free(new_env); /* optional */
5987 /* we can also destroy set_vars_and_save_old's return value,
5990 nommu_save->new_env = new_env;
5991 nommu_save->old_vars = set_vars_and_save_old(new_env);
5994 if (argv_expanded) {
5995 argv = argv_expanded;
5997 argv = expand_strvec_to_strvec(argv + assignment_cnt);
5999 nommu_save->argv = argv;
6002 dump_cmd_in_x_mode(argv);
6004 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6005 if (strchr(argv[0], '/') != NULL)
6009 /* Check if the command matches any of the builtins.
6010 * Depending on context, this might be redundant. But it's
6011 * easier to waste a few CPU cycles than it is to figure out
6012 * if this is one of those cases.
6015 /* On NOMMU, it is more expensive to re-execute shell
6016 * just in order to run echo or test builtin.
6017 * It's better to skip it here and run corresponding
6018 * non-builtin later. */
6019 const struct built_in_command *x;
6020 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6022 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6025 #if ENABLE_HUSH_FUNCTIONS
6026 /* Check if the command matches any functions */
6028 const struct function *funcp = find_function(argv[0]);
6030 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6035 #if ENABLE_FEATURE_SH_STANDALONE
6036 /* Check if the command matches any busybox applets */
6038 int a = find_applet_by_name(argv[0]);
6040 # if BB_MMU /* see above why on NOMMU it is not allowed */
6041 if (APPLET_IS_NOEXEC(a)) {
6042 debug_printf_exec("running applet '%s'\n", argv[0]);
6043 run_applet_no_and_exit(a, argv);
6046 /* Re-exec ourselves */
6047 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6048 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6049 execv(bb_busybox_exec_path, argv);
6050 /* If they called chroot or otherwise made the binary no longer
6051 * executable, fall through */
6056 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6059 execvp_or_die(argv);
6062 /* Called after [v]fork() in run_pipe
6064 static void pseudo_exec(nommu_save_t *nommu_save,
6065 struct command *command,
6066 char **argv_expanded) NORETURN;
6067 static void pseudo_exec(nommu_save_t *nommu_save,
6068 struct command *command,
6069 char **argv_expanded)
6071 if (command->argv) {
6072 pseudo_exec_argv(nommu_save, command->argv,
6073 command->assignment_cnt, argv_expanded);
6076 if (command->group) {
6077 /* Cases when we are here:
6080 * ... | ( list ) | ...
6081 * ... | { list } | ...
6085 debug_printf_exec("pseudo_exec: run_list\n");
6086 reset_traps_to_defaults();
6087 rcode = run_list(command->group);
6088 /* OK to leak memory by not calling free_pipe_list,
6089 * since this process is about to exit */
6092 re_execute_shell(&nommu_save->argv_from_re_execing,
6093 command->group_as_string,
6100 /* Case when we are here: ... | >file */
6101 debug_printf_exec("pseudo_exec'ed null command\n");
6102 _exit(EXIT_SUCCESS);
6106 static const char *get_cmdtext(struct pipe *pi)
6112 /* This is subtle. ->cmdtext is created only on first backgrounding.
6113 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6114 * On subsequent bg argv is trashed, but we won't use it */
6117 argv = pi->cmds[0].argv;
6118 if (!argv || !argv[0]) {
6119 pi->cmdtext = xzalloc(1);
6125 len += strlen(*argv) + 1;
6129 argv = pi->cmds[0].argv;
6131 len = strlen(*argv);
6132 memcpy(p, *argv, len);
6140 static void insert_bg_job(struct pipe *pi)
6142 struct pipe *job, **jobp;
6145 /* Linear search for the ID of the job to use */
6147 for (job = G.job_list; job; job = job->next)
6148 if (job->jobid >= pi->jobid)
6149 pi->jobid = job->jobid + 1;
6151 /* Add job to the list of running jobs */
6153 while ((job = *jobp) != NULL)
6155 job = *jobp = xmalloc(sizeof(*job));
6157 *job = *pi; /* physical copy */
6159 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6160 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6161 for (i = 0; i < pi->num_cmds; i++) {
6162 job->cmds[i].pid = pi->cmds[i].pid;
6163 /* all other fields are not used and stay zero */
6165 job->cmdtext = xstrdup(get_cmdtext(pi));
6167 if (G_interactive_fd)
6168 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6169 G.last_jobid = job->jobid;
6172 static void remove_bg_job(struct pipe *pi)
6174 struct pipe *prev_pipe;
6176 if (pi == G.job_list) {
6177 G.job_list = pi->next;
6179 prev_pipe = G.job_list;
6180 while (prev_pipe->next != pi)
6181 prev_pipe = prev_pipe->next;
6182 prev_pipe->next = pi->next;
6185 G.last_jobid = G.job_list->jobid;
6190 /* Remove a backgrounded job */
6191 static void delete_finished_bg_job(struct pipe *pi)
6194 pi->stopped_cmds = 0;
6200 /* Check to see if any processes have exited -- if they
6201 * have, figure out why and see if a job has completed */
6202 static int checkjobs(struct pipe* fg_pipe)
6212 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6214 attributes = WUNTRACED;
6215 if (fg_pipe == NULL)
6216 attributes |= WNOHANG;
6219 #if ENABLE_HUSH_FAST
6220 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6221 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6222 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6223 /* There was neither fork nor SIGCHLD since last waitpid */
6224 /* Avoid doing waitpid syscall if possible */
6225 if (!G.we_have_children) {
6229 if (fg_pipe == NULL) { /* is WNOHANG set? */
6230 /* We have children, but they did not exit
6231 * or stop yet (we saw no SIGCHLD) */
6234 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6238 /* Do we do this right?
6239 * bash-3.00# sleep 20 | false
6241 * [3]+ Stopped sleep 20 | false
6242 * bash-3.00# echo $?
6243 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6244 * [hush 1.14.0: yes we do it right]
6251 #if ENABLE_HUSH_FAST
6252 i = G.count_SIGCHLD;
6254 childpid = waitpid(-1, &status, attributes);
6255 if (childpid <= 0) {
6256 if (childpid && errno != ECHILD)
6257 bb_perror_msg("waitpid");
6258 #if ENABLE_HUSH_FAST
6259 else { /* Until next SIGCHLD, waitpid's are useless */
6260 G.we_have_children = (childpid == 0);
6261 G.handled_SIGCHLD = i;
6262 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6267 dead = WIFEXITED(status) || WIFSIGNALED(status);
6270 if (WIFSTOPPED(status))
6271 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6272 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6273 if (WIFSIGNALED(status))
6274 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6275 childpid, WTERMSIG(status), WEXITSTATUS(status));
6276 if (WIFEXITED(status))
6277 debug_printf_jobs("pid %d exited, exitcode %d\n",
6278 childpid, WEXITSTATUS(status));
6280 /* Were we asked to wait for fg pipe? */
6282 for (i = 0; i < fg_pipe->num_cmds; i++) {
6283 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6284 if (fg_pipe->cmds[i].pid != childpid)
6287 fg_pipe->cmds[i].pid = 0;
6288 fg_pipe->alive_cmds--;
6289 if (i == fg_pipe->num_cmds - 1) {
6290 /* last process gives overall exitstatus */
6291 rcode = WEXITSTATUS(status);
6292 /* bash prints killer signal's name for *last*
6293 * process in pipe (prints just newline for SIGINT).
6294 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6296 if (WIFSIGNALED(status)) {
6297 int sig = WTERMSIG(status);
6298 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6299 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6300 * Maybe we need to use sig | 128? */
6303 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6306 fg_pipe->cmds[i].is_stopped = 1;
6307 fg_pipe->stopped_cmds++;
6309 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6310 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6311 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6312 /* All processes in fg pipe have exited or stopped */
6313 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6314 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6315 * and "killall -STOP cat" */
6316 if (G_interactive_fd) {
6318 if (fg_pipe->alive_cmds)
6319 insert_bg_job(fg_pipe);
6323 if (!fg_pipe->alive_cmds)
6326 /* There are still running processes in the fg pipe */
6327 goto wait_more; /* do waitpid again */
6329 /* it wasnt fg_pipe, look for process in bg pipes */
6333 /* We asked to wait for bg or orphaned children */
6334 /* No need to remember exitcode in this case */
6335 for (pi = G.job_list; pi; pi = pi->next) {
6336 for (i = 0; i < pi->num_cmds; i++) {
6337 if (pi->cmds[i].pid == childpid)
6338 goto found_pi_and_prognum;
6341 /* Happens when shell is used as init process (init=/bin/sh) */
6342 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6343 continue; /* do waitpid again */
6345 found_pi_and_prognum:
6348 pi->cmds[i].pid = 0;
6350 if (!pi->alive_cmds) {
6351 if (G_interactive_fd)
6352 printf(JOB_STATUS_FORMAT, pi->jobid,
6353 "Done", pi->cmdtext);
6354 delete_finished_bg_job(pi);
6358 pi->cmds[i].is_stopped = 1;
6362 } /* while (waitpid succeeds)... */
6368 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
6371 int rcode = checkjobs(fg_pipe);
6372 if (G_saved_tty_pgrp) {
6373 /* Job finished, move the shell to the foreground */
6374 p = getpgrp(); /* our process group id */
6375 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6376 tcsetpgrp(G_interactive_fd, p);
6382 /* Start all the jobs, but don't wait for anything to finish.
6385 * Return code is normally -1, when the caller has to wait for children
6386 * to finish to determine the exit status of the pipe. If the pipe
6387 * is a simple builtin command, however, the action is done by the
6388 * time run_pipe returns, and the exit code is provided as the
6391 * Returns -1 only if started some children. IOW: we have to
6392 * mask out retvals of builtins etc with 0xff!
6394 * The only case when we do not need to [v]fork is when the pipe
6395 * is single, non-backgrounded, non-subshell command. Examples:
6396 * cmd ; ... { list } ; ...
6397 * cmd && ... { list } && ...
6398 * cmd || ... { list } || ...
6399 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6400 * or (if SH_STANDALONE) an applet, and we can run the { list }
6401 * with run_list. If it isn't one of these, we fork and exec cmd.
6403 * Cases when we must fork:
6404 * non-single: cmd | cmd
6405 * backgrounded: cmd & { list } &
6406 * subshell: ( list ) [&]
6408 #if !ENABLE_HUSH_MODE_X
6409 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6410 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6412 static int redirect_and_varexp_helper(char ***new_env_p,
6413 struct variable **old_vars_p,
6414 struct command *command,
6416 char **argv_expanded)
6418 /* setup_redirects acts on file descriptors, not FILEs.
6419 * This is perfect for work that comes after exec().
6420 * Is it really safe for inline use? Experimentally,
6421 * things seem to work. */
6422 int rcode = setup_redirects(command, squirrel);
6424 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6425 *new_env_p = new_env;
6426 dump_cmd_in_x_mode(new_env);
6427 dump_cmd_in_x_mode(argv_expanded);
6429 *old_vars_p = set_vars_and_save_old(new_env);
6433 static NOINLINE int run_pipe(struct pipe *pi)
6435 static const char *const null_ptr = NULL;
6439 struct command *command;
6440 char **argv_expanded;
6442 /* it is not always needed, but we aim to smaller code */
6443 int squirrel[] = { -1, -1, -1 };
6446 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6449 IF_HUSH_JOB(pi->pgrp = -1;)
6450 pi->stopped_cmds = 0;
6451 command = &pi->cmds[0];
6452 argv_expanded = NULL;
6454 if (pi->num_cmds != 1
6455 || pi->followup == PIPE_BG
6456 || command->cmd_type == CMD_SUBSHELL
6463 debug_printf_exec(": group:%p argv:'%s'\n",
6464 command->group, command->argv ? command->argv[0] : "NONE");
6466 if (command->group) {
6467 #if ENABLE_HUSH_FUNCTIONS
6468 if (command->cmd_type == CMD_FUNCDEF) {
6469 /* "executing" func () { list } */
6470 struct function *funcp;
6472 funcp = new_function(command->argv[0]);
6473 /* funcp->name is already set to argv[0] */
6474 funcp->body = command->group;
6476 funcp->body_as_string = command->group_as_string;
6477 command->group_as_string = NULL;
6479 command->group = NULL;
6480 command->argv[0] = NULL;
6481 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6482 funcp->parent_cmd = command;
6483 command->child_func = funcp;
6485 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6487 return EXIT_SUCCESS;
6491 debug_printf("non-subshell group\n");
6492 rcode = 1; /* exitcode if redir failed */
6493 if (setup_redirects(command, squirrel) == 0) {
6494 debug_printf_exec(": run_list\n");
6495 rcode = run_list(command->group) & 0xff;
6497 restore_redirects(squirrel);
6498 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6500 debug_printf_exec("run_pipe: return %d\n", rcode);
6504 argv = command->argv ? command->argv : (char **) &null_ptr;
6506 const struct built_in_command *x;
6507 #if ENABLE_HUSH_FUNCTIONS
6508 const struct function *funcp;
6512 char **new_env = NULL;
6513 struct variable *old_vars = NULL;
6515 if (argv[command->assignment_cnt] == NULL) {
6516 /* Assignments, but no command */
6517 /* Ensure redirects take effect (that is, create files).
6518 * Try "a=t >file" */
6519 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6520 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6521 /* Set shell variables */
6525 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6526 /* Do we need to flag set_local_var() errors?
6527 * "assignment to readonly var" and "putenv error"
6532 /* Redirect error sets $? to 1. Otherwise,
6533 * if evaluating assignment value set $?, retain it.
6534 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6536 rcode = G.last_exitcode;
6537 /* Exit, _skipping_ variable restoring code: */
6538 goto clean_up_and_ret0;
6540 #else /* Older, bigger, but more correct code */
6542 rcode = setup_redirects(command, squirrel);
6543 restore_redirects(squirrel);
6544 /* Set shell variables */
6546 bb_putchar_stderr('+');
6548 char *p = expand_string_to_string(*argv);
6550 fprintf(stderr, " %s", p);
6551 debug_printf_exec("set shell var:'%s'->'%s'\n",
6553 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6554 /* Do we need to flag set_local_var() errors?
6555 * "assignment to readonly var" and "putenv error"
6560 bb_putchar_stderr('\n');
6561 /* Redirect error sets $? to 1. Otherwise,
6562 * if evaluating assignment value set $?, retain it.
6563 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6565 rcode = G.last_exitcode;
6566 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6568 debug_printf_exec("run_pipe: return %d\n", rcode);
6573 /* Expand the rest into (possibly) many strings each */
6575 #if ENABLE_HUSH_BASH_COMPAT
6576 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6577 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6580 #ifdef CMD_SINGLEWORD_NOGLOB_COND
6581 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
6582 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
6586 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6589 /* if someone gives us an empty string: `cmd with empty output` */
6590 if (!argv_expanded[0]) {
6591 free(argv_expanded);
6593 return G.last_exitcode;
6596 x = find_builtin(argv_expanded[0]);
6597 #if ENABLE_HUSH_FUNCTIONS
6600 funcp = find_function(argv_expanded[0]);
6604 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6605 debug_printf("exec with redirects only\n");
6606 rcode = setup_redirects(command, NULL);
6607 goto clean_up_and_ret1;
6610 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6613 debug_printf_exec(": builtin '%s' '%s'...\n",
6614 x->b_cmd, argv_expanded[1]);
6615 rcode = x->b_function(argv_expanded) & 0xff;
6618 #if ENABLE_HUSH_FUNCTIONS
6620 # if ENABLE_HUSH_LOCAL
6621 struct variable **sv;
6622 sv = G.shadowed_vars_pp;
6623 G.shadowed_vars_pp = &old_vars;
6625 debug_printf_exec(": function '%s' '%s'...\n",
6626 funcp->name, argv_expanded[1]);
6627 rcode = run_function(funcp, argv_expanded) & 0xff;
6628 # if ENABLE_HUSH_LOCAL
6629 G.shadowed_vars_pp = sv;
6635 unset_vars(new_env);
6637 /* clean_up_and_ret0: */
6638 restore_redirects(squirrel);
6640 free(argv_expanded);
6641 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6643 debug_printf_exec("run_pipe return %d\n", rcode);
6647 if (ENABLE_FEATURE_SH_STANDALONE) {
6648 int n = find_applet_by_name(argv_expanded[0]);
6649 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6650 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6652 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6653 argv_expanded[0], argv_expanded[1]);
6654 rcode = run_nofork_applet(n, argv_expanded);
6656 goto clean_up_and_ret;
6659 /* It is neither builtin nor applet. We must fork. */
6663 /* NB: argv_expanded may already be created, and that
6664 * might include `cmd` runs! Do not rerun it! We *must*
6665 * use argv_expanded if it's non-NULL */
6667 /* Going to fork a child per each pipe member */
6672 while (cmd_no < pi->num_cmds) {
6673 struct fd_pair pipefds;
6675 volatile nommu_save_t nommu_save;
6676 nommu_save.new_env = NULL;
6677 nommu_save.old_vars = NULL;
6678 nommu_save.argv = NULL;
6679 nommu_save.argv_from_re_execing = NULL;
6681 command = &pi->cmds[cmd_no];
6683 if (command->argv) {
6684 debug_printf_exec(": pipe member '%s' '%s'...\n",
6685 command->argv[0], command->argv[1]);
6687 debug_printf_exec(": pipe member with no argv\n");
6690 /* pipes are inserted between pairs of commands */
6693 if (cmd_no < pi->num_cmds)
6694 xpiped_pair(pipefds);
6696 command->pid = BB_MMU ? fork() : vfork();
6697 if (!command->pid) { /* child */
6699 disable_restore_tty_pgrp_on_exit();
6700 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6702 /* Every child adds itself to new process group
6703 * with pgid == pid_of_first_child_in_pipe */
6704 if (G.run_list_level == 1 && G_interactive_fd) {
6707 if (pgrp < 0) /* true for 1st process only */
6709 if (setpgid(0, pgrp) == 0
6710 && pi->followup != PIPE_BG
6711 && G_saved_tty_pgrp /* we have ctty */
6713 /* We do it in *every* child, not just first,
6715 tcsetpgrp(G_interactive_fd, pgrp);
6719 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6720 /* 1st cmd in backgrounded pipe
6721 * should have its stdin /dev/null'ed */
6723 if (open(bb_dev_null, O_RDONLY))
6724 xopen("/", O_RDONLY);
6726 xmove_fd(next_infd, 0);
6728 xmove_fd(pipefds.wr, 1);
6731 /* Like bash, explicit redirects override pipes,
6732 * and the pipe fd is available for dup'ing. */
6733 if (setup_redirects(command, NULL))
6736 /* Restore default handlers just prior to exec */
6737 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6739 /* Stores to nommu_save list of env vars putenv'ed
6740 * (NOMMU, on MMU we don't need that) */
6741 /* cast away volatility... */
6742 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6743 /* pseudo_exec() does not return */
6746 /* parent or error */
6747 #if ENABLE_HUSH_FAST
6749 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6751 enable_restore_tty_pgrp_on_exit();
6753 /* Clean up after vforked child */
6754 free(nommu_save.argv);
6755 free(nommu_save.argv_from_re_execing);
6756 unset_vars(nommu_save.new_env);
6757 add_vars(nommu_save.old_vars);
6759 free(argv_expanded);
6760 argv_expanded = NULL;
6761 if (command->pid < 0) { /* [v]fork failed */
6762 /* Clearly indicate, was it fork or vfork */
6763 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6767 /* Second and next children need to know pid of first one */
6769 pi->pgrp = command->pid;
6775 if (cmd_no < pi->num_cmds)
6777 /* Pass read (output) pipe end to next iteration */
6778 next_infd = pipefds.rd;
6781 if (!pi->alive_cmds) {
6783 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6788 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6792 #ifndef debug_print_tree
6793 static void debug_print_tree(struct pipe *pi, int lvl)
6795 static const char *const PIPE[] = {
6801 static const char *RES[] = {
6802 [RES_NONE ] = "NONE" ,
6805 [RES_THEN ] = "THEN" ,
6806 [RES_ELIF ] = "ELIF" ,
6807 [RES_ELSE ] = "ELSE" ,
6810 # if ENABLE_HUSH_LOOPS
6811 [RES_FOR ] = "FOR" ,
6812 [RES_WHILE] = "WHILE",
6813 [RES_UNTIL] = "UNTIL",
6815 [RES_DONE ] = "DONE" ,
6817 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6820 # if ENABLE_HUSH_CASE
6821 [RES_CASE ] = "CASE" ,
6822 [RES_CASE_IN ] = "CASE_IN" ,
6823 [RES_MATCH] = "MATCH",
6824 [RES_CASE_BODY] = "CASE_BODY",
6825 [RES_ESAC ] = "ESAC" ,
6827 [RES_XXXX ] = "XXXX" ,
6828 [RES_SNTX ] = "SNTX" ,
6830 static const char *const CMDTYPE[] = {
6834 # if ENABLE_HUSH_FUNCTIONS
6843 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6844 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6846 while (prn < pi->num_cmds) {
6847 struct command *command = &pi->cmds[prn];
6848 char **argv = command->argv;
6850 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6852 command->assignment_cnt);
6853 if (command->group) {
6854 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6855 CMDTYPE[command->cmd_type],
6858 , " group_as_string:", command->group_as_string
6863 debug_print_tree(command->group, lvl+1);
6867 if (argv) while (*argv) {
6868 fprintf(stderr, " '%s'", *argv);
6871 fprintf(stderr, "\n");
6878 #endif /* debug_print_tree */
6880 /* NB: called by pseudo_exec, and therefore must not modify any
6881 * global data until exec/_exit (we can be a child after vfork!) */
6882 static int run_list(struct pipe *pi)
6884 #if ENABLE_HUSH_CASE
6885 char *case_word = NULL;
6887 #if ENABLE_HUSH_LOOPS
6888 struct pipe *loop_top = NULL;
6889 char **for_lcur = NULL;
6890 char **for_list = NULL;
6892 smallint last_followup;
6894 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6895 smalluint cond_code = 0;
6897 enum { cond_code = 0 };
6900 smallint rword; /* enum reserved_style */
6901 smallint last_rword; /* ditto */
6904 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6907 #if ENABLE_HUSH_LOOPS
6908 /* Check syntax for "for" */
6909 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6910 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6912 /* current word is FOR or IN (BOLD in comments below) */
6913 if (cpipe->next == NULL) {
6914 syntax_error("malformed for");
6916 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6919 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6920 if (cpipe->next->res_word == RES_DO)
6922 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6923 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6924 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6926 syntax_error("malformed for");
6928 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6934 /* Past this point, all code paths should jump to ret: label
6935 * in order to return, no direct "return" statements please.
6936 * This helps to ensure that no memory is leaked. */
6944 last_rword = RES_XXXX;
6946 last_followup = PIPE_SEQ;
6947 rcode = G.last_exitcode;
6949 /* Go through list of pipes, (maybe) executing them. */
6950 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6954 IF_HAS_KEYWORDS(rword = pi->res_word;)
6955 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6956 rword, cond_code, last_rword);
6957 #if ENABLE_HUSH_LOOPS
6958 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6959 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6961 /* start of a loop: remember where loop starts */
6966 /* Still in the same "if...", "then..." or "do..." branch? */
6967 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6968 if ((rcode == 0 && last_followup == PIPE_OR)
6969 || (rcode != 0 && last_followup == PIPE_AND)
6971 /* It is "<true> || CMD" or "<false> && CMD"
6972 * and we should not execute CMD */
6973 debug_printf_exec("skipped cmd because of || or &&\n");
6974 last_followup = pi->followup;
6978 last_followup = pi->followup;
6979 IF_HAS_KEYWORDS(last_rword = rword;)
6982 if (rword == RES_THEN) {
6983 /* if false; then ... fi has exitcode 0! */
6984 G.last_exitcode = rcode = EXIT_SUCCESS;
6985 /* "if <false> THEN cmd": skip cmd */
6989 if (rword == RES_ELSE || rword == RES_ELIF) {
6990 /* "if <true> then ... ELSE/ELIF cmd":
6991 * skip cmd and all following ones */
6996 #if ENABLE_HUSH_LOOPS
6997 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
6999 /* first loop through for */
7001 static const char encoded_dollar_at[] ALIGN1 = {
7002 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7003 }; /* encoded representation of "$@" */
7004 static const char *const encoded_dollar_at_argv[] = {
7005 encoded_dollar_at, NULL
7006 }; /* argv list with one element: "$@" */
7009 vals = (char**)encoded_dollar_at_argv;
7010 if (pi->next->res_word == RES_IN) {
7011 /* if no variable values after "in" we skip "for" */
7012 if (!pi->next->cmds[0].argv) {
7013 G.last_exitcode = rcode = EXIT_SUCCESS;
7014 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7017 vals = pi->next->cmds[0].argv;
7018 } /* else: "for var; do..." -> assume "$@" list */
7019 /* create list of variable values */
7020 debug_print_strings("for_list made from", vals);
7021 for_list = expand_strvec_to_strvec(vals);
7022 for_lcur = for_list;
7023 debug_print_strings("for_list", for_list);
7026 /* "for" loop is over, clean up */
7032 /* Insert next value from for_lcur */
7033 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7034 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7037 if (rword == RES_IN) {
7038 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7040 if (rword == RES_DONE) {
7041 continue; /* "done" has no cmds too */
7044 #if ENABLE_HUSH_CASE
7045 if (rword == RES_CASE) {
7046 case_word = expand_strvec_to_string(pi->cmds->argv);
7049 if (rword == RES_MATCH) {
7052 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7054 /* all prev words didn't match, does this one match? */
7055 argv = pi->cmds->argv;
7057 char *pattern = expand_string_to_string(*argv);
7058 /* TODO: which FNM_xxx flags to use? */
7059 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7061 if (cond_code == 0) { /* match! we will execute this branch */
7062 free(case_word); /* make future "word)" stop */
7070 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7072 continue; /* not matched yet, skip this pipe */
7075 /* Just pressing <enter> in shell should check for jobs.
7076 * OTOH, in non-interactive shell this is useless
7077 * and only leads to extra job checks */
7078 if (pi->num_cmds == 0) {
7079 if (G_interactive_fd)
7080 goto check_jobs_and_continue;
7084 /* After analyzing all keywords and conditions, we decided
7085 * to execute this pipe. NB: have to do checkjobs(NULL)
7086 * after run_pipe to collect any background children,
7087 * even if list execution is to be stopped. */
7088 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7091 #if ENABLE_HUSH_LOOPS
7092 G.flag_break_continue = 0;
7094 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7096 /* We ran a builtin, function, or group.
7097 * rcode is already known
7098 * and we don't need to wait for anything. */
7099 G.last_exitcode = rcode;
7100 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7101 check_and_run_traps(0);
7102 #if ENABLE_HUSH_LOOPS
7103 /* Was it "break" or "continue"? */
7104 if (G.flag_break_continue) {
7105 smallint fbc = G.flag_break_continue;
7106 /* We might fall into outer *loop*,
7107 * don't want to break it too */
7109 G.depth_break_continue--;
7110 if (G.depth_break_continue == 0)
7111 G.flag_break_continue = 0;
7112 /* else: e.g. "continue 2" should *break* once, *then* continue */
7113 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7114 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7115 goto check_jobs_and_break;
7116 /* "continue": simulate end of loop */
7121 #if ENABLE_HUSH_FUNCTIONS
7122 if (G.flag_return_in_progress == 1) {
7123 /* same as "goto check_jobs_and_break" */
7128 } else if (pi->followup == PIPE_BG) {
7129 /* What does bash do with attempts to background builtins? */
7130 /* even bash 3.2 doesn't do that well with nested bg:
7131 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7132 * I'm NOT treating inner &'s as jobs */
7133 check_and_run_traps(0);
7135 if (G.run_list_level == 1)
7138 /* Last command's pid goes to $! */
7139 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7140 G.last_exitcode = rcode = EXIT_SUCCESS;
7141 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7144 if (G.run_list_level == 1 && G_interactive_fd) {
7145 /* Waits for completion, then fg's main shell */
7146 rcode = checkjobs_and_fg_shell(pi);
7147 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7148 check_and_run_traps(0);
7151 { /* This one just waits for completion */
7152 rcode = checkjobs(pi);
7153 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7154 check_and_run_traps(0);
7156 G.last_exitcode = rcode;
7160 /* Analyze how result affects subsequent commands */
7162 if (rword == RES_IF || rword == RES_ELIF)
7165 #if ENABLE_HUSH_LOOPS
7166 /* Beware of "while false; true; do ..."! */
7167 if (pi->next && pi->next->res_word == RES_DO) {
7168 if (rword == RES_WHILE) {
7170 /* "while false; do...done" - exitcode 0 */
7171 G.last_exitcode = rcode = EXIT_SUCCESS;
7172 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7173 goto check_jobs_and_break;
7176 if (rword == RES_UNTIL) {
7178 debug_printf_exec(": until expr is true: breaking\n");
7179 check_jobs_and_break:
7187 check_jobs_and_continue:
7194 #if ENABLE_HUSH_LOOPS
7199 #if ENABLE_HUSH_CASE
7203 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7207 /* Select which version we will use */
7208 static int run_and_free_list(struct pipe *pi)
7211 debug_printf_exec("run_and_free_list entered\n");
7213 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7214 rcode = run_list(pi);
7216 /* free_pipe_list has the side effect of clearing memory.
7217 * In the long run that function can be merged with run_list,
7218 * but doing that now would hobble the debugging effort. */
7220 debug_printf_exec("run_and_free_list return %d\n", rcode);
7225 /* Called a few times only (or even once if "sh -c") */
7226 static void init_sigmasks(void)
7230 sigset_t old_blocked_set;
7232 if (!G.inherited_set_is_saved) {
7233 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7234 G.inherited_set = G.blocked_set;
7236 old_blocked_set = G.blocked_set;
7238 mask = (1 << SIGQUIT);
7239 if (G_interactive_fd) {
7240 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7241 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7242 mask |= SPECIAL_JOB_SIGS;
7244 G.non_DFL_mask = mask;
7249 sigaddset(&G.blocked_set, sig);
7253 sigdelset(&G.blocked_set, SIGCHLD);
7255 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7256 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7258 /* POSIX allows shell to re-enable SIGCHLD
7259 * even if it was SIG_IGN on entry */
7260 #if ENABLE_HUSH_FAST
7261 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7262 if (!G.inherited_set_is_saved)
7263 signal(SIGCHLD, SIGCHLD_handler);
7265 if (!G.inherited_set_is_saved)
7266 signal(SIGCHLD, SIG_DFL);
7269 G.inherited_set_is_saved = 1;
7274 static void maybe_set_to_sigexit(int sig)
7276 void (*handler)(int);
7277 /* non_DFL_mask'ed signals are, well, masked,
7278 * no need to set handler for them.
7280 if (!((G.non_DFL_mask >> sig) & 1)) {
7281 handler = signal(sig, sigexit);
7282 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7283 signal(sig, handler);
7286 /* Set handlers to restore tty pgrp and exit */
7287 static void set_fatal_handlers(void)
7289 /* We _must_ restore tty pgrp on fatal signals */
7291 maybe_set_to_sigexit(SIGILL );
7292 maybe_set_to_sigexit(SIGFPE );
7293 maybe_set_to_sigexit(SIGBUS );
7294 maybe_set_to_sigexit(SIGSEGV);
7295 maybe_set_to_sigexit(SIGTRAP);
7296 } /* else: hush is perfect. what SEGV? */
7297 maybe_set_to_sigexit(SIGABRT);
7298 /* bash 3.2 seems to handle these just like 'fatal' ones */
7299 maybe_set_to_sigexit(SIGPIPE);
7300 maybe_set_to_sigexit(SIGALRM);
7301 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7302 * if we aren't interactive... but in this case
7303 * we never want to restore pgrp on exit, and this fn is not called */
7304 /*maybe_set_to_sigexit(SIGHUP );*/
7305 /*maybe_set_to_sigexit(SIGTERM);*/
7306 /*maybe_set_to_sigexit(SIGINT );*/
7310 static int set_mode(const char cstate, const char mode)
7312 int state = (cstate == '-' ? 1 : 0);
7314 case 'n': G.n_mode = state; break;
7315 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7316 default: return EXIT_FAILURE;
7318 return EXIT_SUCCESS;
7321 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7322 int hush_main(int argc, char **argv)
7325 unsigned builtin_argc;
7327 struct variable *cur_var;
7330 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7331 G.last_exitcode = EXIT_SUCCESS;
7333 G.argv0_for_re_execing = argv[0];
7335 /* Deal with HUSH_VERSION */
7336 G.shell_ver.flg_export = 1;
7337 G.shell_ver.flg_read_only = 1;
7338 /* Code which handles ${var/P/R} needs writable values for all variables,
7339 * therefore we xstrdup: */
7340 G.shell_ver.varstr = xstrdup(hush_version_str),
7341 G.top_var = &G.shell_ver;
7342 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7343 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7344 /* reinstate HUSH_VERSION in environment */
7345 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7346 putenv(G.shell_ver.varstr);
7348 /* Initialize our shell local variables with the values
7349 * currently living in the environment */
7350 cur_var = G.top_var;
7353 char *value = strchr(*e, '=');
7354 if (value) { /* paranoia */
7355 cur_var->next = xzalloc(sizeof(*cur_var));
7356 cur_var = cur_var->next;
7357 cur_var->varstr = *e;
7358 cur_var->max_len = strlen(*e);
7359 cur_var->flg_export = 1;
7365 set_pwd_var(/*exp:*/ 1);
7366 /* bash also exports SHLVL and _,
7367 * and sets (but doesn't export) the following variables:
7369 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7370 * BASH_VERSION='3.2.0(1)-release'
7372 * MACHTYPE=i386-pc-linux-gnu
7374 * HOSTNAME=<xxxxxxxxxx>
7375 * PPID=<NNNNN> - we also do it elsewhere
7386 * PIPESTATUS=([0]="0")
7387 * HISTFILE=/<xxx>/.bash_history
7391 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7393 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7403 #if ENABLE_FEATURE_EDITING
7404 G.line_input_state = new_line_input_t(FOR_SHELL);
7406 G.global_argc = argc;
7407 G.global_argv = argv;
7408 /* Initialize some more globals to non-zero values */
7409 cmdedit_update_prompt();
7411 if (setjmp(die_jmp)) {
7412 /* xfunc has failed! die die die */
7413 /* no EXIT traps, this is an escape hatch! */
7415 hush_exit(xfunc_error_retval);
7418 /* Shell is non-interactive at first. We need to call
7419 * init_sigmasks() if we are going to execute "sh <script>",
7420 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7421 * If we later decide that we are interactive, we run init_sigmasks()
7422 * in order to intercept (more) signals.
7426 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7429 opt = getopt(argc, argv, "+c:xins"
7432 # if ENABLE_HUSH_FUNCTIONS
7442 * sh ... -c 'script'
7443 * sh ... -c 'script' ARG0 [ARG1...]
7444 * On NOMMU, if builtin_argc != 0,
7445 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7446 * "" needs to be replaced with NULL
7447 * and BARGV vector fed to builtin function.
7448 * Note: the form without ARG0 never happens:
7449 * sh ... -c 'builtin' BARGV... ""
7452 G.root_pid = getpid();
7453 G.root_ppid = getppid();
7455 G.global_argv = argv + optind;
7456 G.global_argc = argc - optind;
7458 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7459 const struct built_in_command *x;
7462 x = find_builtin(optarg);
7463 if (x) { /* paranoia */
7464 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7465 G.global_argv += builtin_argc;
7466 G.global_argv[-1] = NULL; /* replace "" */
7467 G.last_exitcode = x->b_function(argv + optind - 1);
7471 if (!G.global_argv[0]) {
7472 /* -c 'script' (no params): prevent empty $0 */
7473 G.global_argv--; /* points to argv[i] of 'script' */
7474 G.global_argv[0] = argv[0];
7476 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7478 parse_and_run_string(optarg);
7481 /* Well, we cannot just declare interactiveness,
7482 * we have to have some stuff (ctty, etc) */
7483 /* G_interactive_fd++; */
7486 /* "-s" means "read from stdin", but this is how we always
7487 * operate, so simply do nothing here. */
7490 case '<': /* "big heredoc" support */
7491 full_write1_str(optarg);
7494 unsigned long long empty_trap_mask;
7496 G.root_pid = bb_strtou(optarg, &optarg, 16);
7498 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7500 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7502 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7504 builtin_argc = bb_strtou(optarg, &optarg, 16);
7506 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7507 if (empty_trap_mask != 0) {
7510 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7511 for (sig = 1; sig < NSIG; sig++) {
7512 if (empty_trap_mask & (1LL << sig)) {
7513 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7514 sigaddset(&G.blocked_set, sig);
7517 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7519 # if ENABLE_HUSH_LOOPS
7521 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7527 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7529 # if ENABLE_HUSH_FUNCTIONS
7531 struct function *funcp = new_function(optarg);
7532 /* funcp->name is already set to optarg */
7533 /* funcp->body is set to NULL. It's a special case. */
7534 funcp->body_as_string = argv[optind];
7542 if (set_mode('-', opt) == 0) /* no error */
7546 fprintf(stderr, "Usage: sh [FILE]...\n"
7547 " or: sh -c command [args]...\n\n");
7553 } /* option parsing loop */
7556 G.root_pid = getpid();
7557 G.root_ppid = getppid();
7560 /* If we are login shell... */
7561 if (argv[0] && argv[0][0] == '-') {
7563 debug_printf("sourcing /etc/profile\n");
7564 input = fopen_for_read("/etc/profile");
7565 if (input != NULL) {
7566 close_on_exec_on(fileno(input));
7568 parse_and_run_file(input);
7571 /* bash: after sourcing /etc/profile,
7572 * tries to source (in the given order):
7573 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7574 * stopping on first found. --noprofile turns this off.
7575 * bash also sources ~/.bash_logout on exit.
7576 * If called as sh, skips .bash_XXX files.
7583 * "bash <script>" (which is never interactive (unless -i?))
7584 * sources $BASH_ENV here (without scanning $PATH).
7585 * If called as sh, does the same but with $ENV.
7587 debug_printf("running script '%s'\n", argv[optind]);
7588 G.global_argv = argv + optind;
7589 G.global_argc = argc - optind;
7590 input = xfopen_for_read(argv[optind]);
7591 close_on_exec_on(fileno(input));
7593 parse_and_run_file(input);
7594 #if ENABLE_FEATURE_CLEAN_UP
7600 /* Up to here, shell was non-interactive. Now it may become one.
7601 * NB: don't forget to (re)run init_sigmasks() as needed.
7604 /* A shell is interactive if the '-i' flag was given,
7605 * or if all of the following conditions are met:
7607 * no arguments remaining or the -s flag given
7608 * standard input is a terminal
7609 * standard output is a terminal
7610 * Refer to Posix.2, the description of the 'sh' utility.
7613 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7614 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7615 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7616 if (G_saved_tty_pgrp < 0)
7617 G_saved_tty_pgrp = 0;
7619 /* try to dup stdin to high fd#, >= 255 */
7620 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7621 if (G_interactive_fd < 0) {
7622 /* try to dup to any fd */
7623 G_interactive_fd = dup(STDIN_FILENO);
7624 if (G_interactive_fd < 0) {
7626 G_interactive_fd = 0;
7627 G_saved_tty_pgrp = 0;
7630 // TODO: track & disallow any attempts of user
7631 // to (inadvertently) close/redirect G_interactive_fd
7633 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7634 if (G_interactive_fd) {
7635 close_on_exec_on(G_interactive_fd);
7637 if (G_saved_tty_pgrp) {
7638 /* If we were run as 'hush &', sleep until we are
7639 * in the foreground (tty pgrp == our pgrp).
7640 * If we get started under a job aware app (like bash),
7641 * make sure we are now in charge so we don't fight over
7642 * who gets the foreground */
7644 pid_t shell_pgrp = getpgrp();
7645 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7646 if (G_saved_tty_pgrp == shell_pgrp)
7648 /* send TTIN to ourself (should stop us) */
7649 kill(- shell_pgrp, SIGTTIN);
7653 /* Block some signals */
7656 if (G_saved_tty_pgrp) {
7657 /* Set other signals to restore saved_tty_pgrp */
7658 set_fatal_handlers();
7659 /* Put ourselves in our own process group
7660 * (bash, too, does this only if ctty is available) */
7661 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7662 /* Grab control of the terminal */
7663 tcsetpgrp(G_interactive_fd, getpid());
7665 /* -1 is special - makes xfuncs longjmp, not exit
7666 * (we reset die_sleep = 0 whereever we [v]fork) */
7667 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7671 #elif ENABLE_HUSH_INTERACTIVE
7672 /* No job control compiled in, only prompt/line editing */
7673 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7674 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7675 if (G_interactive_fd < 0) {
7676 /* try to dup to any fd */
7677 G_interactive_fd = dup(STDIN_FILENO);
7678 if (G_interactive_fd < 0)
7680 G_interactive_fd = 0;
7683 if (G_interactive_fd) {
7684 close_on_exec_on(G_interactive_fd);
7688 /* We have interactiveness code disabled */
7692 * if interactive but not a login shell, sources ~/.bashrc
7693 * (--norc turns this off, --rcfile <file> overrides)
7696 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7697 /* note: ash and hush share this string */
7698 printf("\n\n%s %s\n"
7699 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7702 "hush - the humble shell"
7706 parse_and_run_file(stdin);
7709 #if ENABLE_FEATURE_CLEAN_UP
7710 if (G.cwd != bb_msg_unknown)
7712 cur_var = G.top_var->next;
7714 struct variable *tmp = cur_var;
7715 if (!cur_var->max_len)
7716 free(cur_var->varstr);
7717 cur_var = cur_var->next;
7721 hush_exit(G.last_exitcode);
7726 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7727 int msh_main(int argc, char **argv)
7729 //bb_error_msg("msh is deprecated, please use hush instead");
7730 return hush_main(argc, argv);
7738 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7743 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7750 return applet_main_func(argc, argv - argc);
7753 static int FAST_FUNC builtin_test(char **argv)
7755 return run_applet_main(argv, test_main);
7758 static int FAST_FUNC builtin_echo(char **argv)
7760 return run_applet_main(argv, echo_main);
7764 static int FAST_FUNC builtin_printf(char **argv)
7766 return run_applet_main(argv, printf_main);
7770 static char **skip_dash_dash(char **argv)
7773 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7778 static int FAST_FUNC builtin_eval(char **argv)
7780 int rcode = EXIT_SUCCESS;
7782 argv = skip_dash_dash(argv);
7784 char *str = expand_strvec_to_string(argv);
7786 * eval "echo Hi; done" ("done" is syntax error):
7787 * "echo Hi" will not execute too.
7789 parse_and_run_string(str);
7791 rcode = G.last_exitcode;
7796 static int FAST_FUNC builtin_cd(char **argv)
7800 argv = skip_dash_dash(argv);
7802 if (newdir == NULL) {
7803 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7804 * bash says "bash: cd: HOME not set" and does nothing
7807 const char *home = get_local_var_value("HOME");
7808 newdir = home ? home : "/";
7810 if (chdir(newdir)) {
7811 /* Mimic bash message exactly */
7812 bb_perror_msg("cd: %s", newdir);
7813 return EXIT_FAILURE;
7815 /* Read current dir (get_cwd(1) is inside) and set PWD.
7816 * Note: do not enforce exporting. If PWD was unset or unexported,
7817 * set it again, but do not export. bash does the same.
7819 set_pwd_var(/*exp:*/ 0);
7820 return EXIT_SUCCESS;
7823 static int FAST_FUNC builtin_exec(char **argv)
7825 argv = skip_dash_dash(argv);
7826 if (argv[0] == NULL)
7827 return EXIT_SUCCESS; /* bash does this */
7829 /* Careful: we can end up here after [v]fork. Do not restore
7830 * tty pgrp then, only top-level shell process does that */
7831 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7832 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7834 /* TODO: if exec fails, bash does NOT exit! We do.
7835 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7836 * and tcsetpgrp, and this is inherently racy.
7838 execvp_or_die(argv);
7841 static int FAST_FUNC builtin_exit(char **argv)
7843 debug_printf_exec("%s()\n", __func__);
7845 /* interactive bash:
7846 * # trap "echo EEE" EXIT
7849 * There are stopped jobs.
7850 * (if there are _stopped_ jobs, running ones don't count)
7853 # EEE (then bash exits)
7855 * we can use G.exiting = -1 as indicator "last cmd was exit"
7858 /* note: EXIT trap is run by hush_exit */
7859 argv = skip_dash_dash(argv);
7860 if (argv[0] == NULL)
7861 hush_exit(G.last_exitcode);
7862 /* mimic bash: exit 123abc == exit 255 + error msg */
7863 xfunc_error_retval = 255;
7864 /* bash: exit -2 == exit 254, no error msg */
7865 hush_exit(xatoi(argv[0]) & 0xff);
7868 static void print_escaped(const char *s)
7873 const char *p = strchrnul(s, '\'');
7874 /* print 'xxxx', possibly just '' */
7875 printf("'%.*s'", (int)(p - s), s);
7880 /* s points to '; print "'''...'''" */
7882 do putchar('\''); while (*++s == '\'');
7887 #if !ENABLE_HUSH_LOCAL
7888 #define helper_export_local(argv, exp, lvl) \
7889 helper_export_local(argv, exp)
7891 static void helper_export_local(char **argv, int exp, int lvl)
7896 /* So far we do not check that name is valid (TODO?) */
7898 if (strchr(name, '=') == NULL) {
7899 struct variable *var;
7901 var = get_local_var(name);
7902 if (exp == -1) { /* unexporting? */
7903 /* export -n NAME (without =VALUE) */
7905 var->flg_export = 0;
7906 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7908 } /* else: export -n NOT_EXISTING_VAR: no-op */
7911 if (exp == 1) { /* exporting? */
7912 /* export NAME (without =VALUE) */
7914 var->flg_export = 1;
7915 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7916 putenv(var->varstr);
7920 /* Exporting non-existing variable.
7921 * bash does not put it in environment,
7922 * but remembers that it is exported,
7923 * and does put it in env when it is set later.
7924 * We just set it to "" and export. */
7925 /* Or, it's "local NAME" (without =VALUE).
7926 * bash sets the value to "". */
7927 name = xasprintf("%s=", name);
7929 /* (Un)exporting/making local NAME=VALUE */
7930 name = xstrdup(name);
7932 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7936 static int FAST_FUNC builtin_export(char **argv)
7938 unsigned opt_unexport;
7940 #if ENABLE_HUSH_EXPORT_N
7941 /* "!": do not abort on errors */
7942 opt_unexport = getopt32(argv, "!n");
7943 if (opt_unexport == (uint32_t)-1)
7944 return EXIT_FAILURE;
7951 if (argv[0] == NULL) {
7958 /* ash emits: export VAR='VAL'
7959 * bash: declare -x VAR="VAL"
7960 * we follow ash example */
7961 const char *s = *e++;
7962 const char *p = strchr(s, '=');
7964 if (!p) /* wtf? take next variable */
7967 printf("export %.*s", (int)(p - s) + 1, s);
7968 print_escaped(p + 1);
7972 /*fflush_all(); - done after each builtin anyway */
7974 return EXIT_SUCCESS;
7977 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7979 return EXIT_SUCCESS;
7982 #if ENABLE_HUSH_LOCAL
7983 static int FAST_FUNC builtin_local(char **argv)
7985 if (G.func_nest_level == 0) {
7986 bb_error_msg("%s: not in a function", argv[0]);
7987 return EXIT_FAILURE; /* bash compat */
7989 helper_export_local(argv, 0, G.func_nest_level);
7990 return EXIT_SUCCESS;
7994 static int FAST_FUNC builtin_trap(char **argv)
8000 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8005 /* No args: print all trapped */
8006 for (i = 0; i < NSIG; ++i) {
8009 print_escaped(G.traps[i]);
8010 /* note: bash adds "SIG", but only if invoked
8011 * as "bash". If called as "sh", or if set -o posix,
8012 * then it prints short signal names.
8013 * We are printing short names: */
8014 printf(" %s\n", get_signame(i));
8017 /*fflush_all(); - done after each builtin anyway */
8018 return EXIT_SUCCESS;
8022 /* If first arg is a number: reset all specified signals */
8023 sig = bb_strtou(*argv, NULL, 10);
8029 sig = get_signum(*argv++);
8030 if (sig < 0 || sig >= NSIG) {
8032 /* Mimic bash message exactly */
8033 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8038 G.traps[sig] = xstrdup(new_cmd);
8040 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8041 get_signame(sig), sig, G.traps[sig]);
8043 /* There is no signal for 0 (EXIT) */
8048 sigaddset(&G.blocked_set, sig);
8050 /* There was a trap handler, we are removing it
8051 * (if sig has non-DFL handling,
8052 * we don't need to do anything) */
8053 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8055 sigdelset(&G.blocked_set, sig);
8058 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8062 if (!argv[1]) { /* no second arg */
8063 bb_error_msg("trap: invalid arguments");
8064 return EXIT_FAILURE;
8067 /* First arg is "-": reset all specified to default */
8068 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8069 /* Everything else: set arg as signal handler
8070 * (includes "" case, which ignores signal) */
8071 if (argv[0][0] == '-') {
8072 if (argv[0][1] == '\0') { /* "-" */
8073 /* new_cmd remains NULL: "reset these sigs" */
8076 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8079 /* else: "-something", no special meaning */
8084 goto process_sig_list;
8087 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8088 static int FAST_FUNC builtin_type(char **argv)
8090 int ret = EXIT_SUCCESS;
8096 if (0) {} /* make conditional compile easier below */
8097 /*else if (find_alias(*argv))
8098 type = "an alias";*/
8099 #if ENABLE_HUSH_FUNCTIONS
8100 else if (find_function(*argv))
8101 type = "a function";
8103 else if (find_builtin(*argv))
8104 type = "a shell builtin";
8105 else if ((path = find_in_path(*argv)) != NULL)
8108 bb_error_msg("type: %s: not found", *argv);
8113 printf("%s is %s\n", *argv, type);
8121 /* built-in 'fg' and 'bg' handler */
8122 static int FAST_FUNC builtin_fg_bg(char **argv)
8127 if (!G_interactive_fd)
8128 return EXIT_FAILURE;
8130 /* If they gave us no args, assume they want the last backgrounded task */
8132 for (pi = G.job_list; pi; pi = pi->next) {
8133 if (pi->jobid == G.last_jobid) {
8137 bb_error_msg("%s: no current job", argv[0]);
8138 return EXIT_FAILURE;
8140 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8141 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8142 return EXIT_FAILURE;
8144 for (pi = G.job_list; pi; pi = pi->next) {
8145 if (pi->jobid == jobnum) {
8149 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8150 return EXIT_FAILURE;
8152 /* TODO: bash prints a string representation
8153 * of job being foregrounded (like "sleep 1 | cat") */
8154 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8155 /* Put the job into the foreground. */
8156 tcsetpgrp(G_interactive_fd, pi->pgrp);
8159 /* Restart the processes in the job */
8160 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8161 for (i = 0; i < pi->num_cmds; i++) {
8162 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8163 pi->cmds[i].is_stopped = 0;
8165 pi->stopped_cmds = 0;
8167 i = kill(- pi->pgrp, SIGCONT);
8169 if (errno == ESRCH) {
8170 delete_finished_bg_job(pi);
8171 return EXIT_SUCCESS;
8173 bb_perror_msg("kill (SIGCONT)");
8176 if (argv[0][0] == 'f') {
8178 return checkjobs_and_fg_shell(pi);
8180 return EXIT_SUCCESS;
8184 #if ENABLE_HUSH_HELP
8185 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8187 const struct built_in_command *x;
8190 "Built-in commands:\n"
8191 "------------------\n");
8192 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8194 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8197 return EXIT_SUCCESS;
8202 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8205 const char *status_string;
8207 for (job = G.job_list; job; job = job->next) {
8208 if (job->alive_cmds == job->stopped_cmds)
8209 status_string = "Stopped";
8211 status_string = "Running";
8213 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8215 return EXIT_SUCCESS;
8220 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8225 # ifdef M_TRIM_THRESHOLD
8226 /* Optional. Reduces probability of false positives */
8229 /* Crude attempt to find where "free memory" starts,
8230 * sans fragmentation. */
8232 l = (unsigned long)p;
8235 if (l < (unsigned long)p) l = (unsigned long)p;
8238 if (!G.memleak_value)
8239 G.memleak_value = l;
8241 l -= G.memleak_value;
8248 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8253 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8256 return EXIT_SUCCESS;
8259 static int FAST_FUNC builtin_read(char **argv)
8268 /* "!": do not abort on errors.
8269 * Option string must start with "sr" to match BUILTIN_READ_xxx
8271 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8272 if (read_flags == (uint32_t)-1)
8273 return EXIT_FAILURE;
8276 r = shell_builtin_read(set_local_var_from_halves,
8278 get_local_var_value("IFS"), /* can be NULL */
8286 if ((uintptr_t)r > 1) {
8287 bb_error_msg("%s", r);
8288 r = (char*)(uintptr_t)1;
8291 return (uintptr_t)r;
8294 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8295 * built-in 'set' handler
8297 * set [-abCefhmnuvx] [-o option] [argument...]
8298 * set [+abCefhmnuvx] [+o option] [argument...]
8299 * set -- [argument...]
8302 * Implementations shall support the options in both their hyphen and
8303 * plus-sign forms. These options can also be specified as options to sh.
8305 * Write out all variables and their values: set
8306 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8307 * Turn on the -x and -v options: set -xv
8308 * Unset all positional parameters: set --
8309 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8310 * Set the positional parameters to the expansion of x, even if x expands
8311 * with a leading '-' or '+': set -- $x
8313 * So far, we only support "set -- [argument...]" and some of the short names.
8315 static int FAST_FUNC builtin_set(char **argv)
8318 char **pp, **g_argv;
8319 char *arg = *++argv;
8323 for (e = G.top_var; e; e = e->next)
8325 return EXIT_SUCCESS;
8329 if (!strcmp(arg, "--")) {
8333 if (arg[0] != '+' && arg[0] != '-')
8335 for (n = 1; arg[n]; ++n)
8336 if (set_mode(arg[0], arg[n]))
8338 } while ((arg = *++argv) != NULL);
8339 /* Now argv[0] is 1st argument */
8342 return EXIT_SUCCESS;
8345 /* NB: G.global_argv[0] ($0) is never freed/changed */
8346 g_argv = G.global_argv;
8347 if (G.global_args_malloced) {
8353 G.global_args_malloced = 1;
8354 pp = xzalloc(sizeof(pp[0]) * 2);
8355 pp[0] = g_argv[0]; /* retain $0 */
8358 /* This realloc's G.global_argv */
8359 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8366 return EXIT_SUCCESS;
8368 /* Nothing known, so abort */
8370 bb_error_msg("set: %s: invalid option", arg);
8371 return EXIT_FAILURE;
8374 static int FAST_FUNC builtin_shift(char **argv)
8377 argv = skip_dash_dash(argv);
8381 if (n >= 0 && n < G.global_argc) {
8382 if (G.global_args_malloced) {
8385 free(G.global_argv[m++]);
8388 memmove(&G.global_argv[1], &G.global_argv[n+1],
8389 G.global_argc * sizeof(G.global_argv[0]));
8390 return EXIT_SUCCESS;
8392 return EXIT_FAILURE;
8395 static int FAST_FUNC builtin_source(char **argv)
8397 char *arg_path, *filename;
8400 #if ENABLE_HUSH_FUNCTIONS
8404 argv = skip_dash_dash(argv);
8407 /* bash says: "bash: .: filename argument required" */
8408 return 2; /* bash compat */
8411 if (!strchr(filename, '/')) {
8412 arg_path = find_in_path(filename);
8414 filename = arg_path;
8416 input = fopen_or_warn(filename, "r");
8419 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8420 return EXIT_FAILURE;
8422 close_on_exec_on(fileno(input));
8424 #if ENABLE_HUSH_FUNCTIONS
8425 sv_flg = G.flag_return_in_progress;
8426 /* "we are inside sourced file, ok to use return" */
8427 G.flag_return_in_progress = -1;
8429 save_and_replace_G_args(&sv, argv);
8431 parse_and_run_file(input);
8434 restore_G_args(&sv, argv);
8435 #if ENABLE_HUSH_FUNCTIONS
8436 G.flag_return_in_progress = sv_flg;
8439 return G.last_exitcode;
8442 static int FAST_FUNC builtin_umask(char **argv)
8448 argv = skip_dash_dash(argv);
8450 mode_t old_mask = mask;
8453 rc = bb_parse_mode(argv[0], &mask);
8458 * bash: umask: 'q': invalid symbolic mode operator
8459 * bash: umask: 999: octal number out of range
8461 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8466 printf("%04o\n", (unsigned) mask);
8467 /* fall through and restore mask which we set to 0 */
8471 return !rc; /* rc != 0 - success */
8474 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8475 static int FAST_FUNC builtin_unset(char **argv)
8480 /* "!": do not abort on errors */
8481 /* "+": stop at 1st non-option */
8482 opts = getopt32(argv, "!+vf");
8483 if (opts == (unsigned)-1)
8484 return EXIT_FAILURE;
8486 bb_error_msg("unset: -v and -f are exclusive");
8487 return EXIT_FAILURE;
8493 if (!(opts & 2)) { /* not -f */
8494 if (unset_local_var(*argv)) {
8495 /* unset <nonexistent_var> doesn't fail.
8496 * Error is when one tries to unset RO var.
8497 * Message was printed by unset_local_var. */
8501 #if ENABLE_HUSH_FUNCTIONS
8511 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8512 static int FAST_FUNC builtin_wait(char **argv)
8514 int ret = EXIT_SUCCESS;
8517 argv = skip_dash_dash(argv);
8518 if (argv[0] == NULL) {
8519 /* Don't care about wait results */
8520 /* Note 1: must wait until there are no more children */
8521 /* Note 2: must be interruptible */
8523 * $ sleep 3 & sleep 6 & wait
8528 * $ sleep 3 & sleep 6 & wait
8532 * ^C <-- after ~4 sec from keyboard
8535 sigaddset(&G.blocked_set, SIGCHLD);
8536 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8539 if (errno == ECHILD)
8541 /* Wait for SIGCHLD or any other signal of interest */
8542 /* sigtimedwait with infinite timeout: */
8543 sig = sigwaitinfo(&G.blocked_set, NULL);
8545 sig = check_and_run_traps(sig);
8546 if (sig && sig != SIGCHLD) { /* see note 2 */
8552 sigdelset(&G.blocked_set, SIGCHLD);
8553 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8557 /* This is probably buggy wrt interruptible-ness */
8559 pid_t pid = bb_strtou(*argv, NULL, 10);
8561 /* mimic bash message */
8562 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8563 return EXIT_FAILURE;
8565 if (waitpid(pid, &status, 0) == pid) {
8566 if (WIFSIGNALED(status))
8567 ret = 128 + WTERMSIG(status);
8568 else if (WIFEXITED(status))
8569 ret = WEXITSTATUS(status);
8573 bb_perror_msg("wait %s", *argv);
8582 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8583 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8586 def = bb_strtou(argv[1], NULL, 10);
8587 if (errno || def < def_min || argv[2]) {
8588 bb_error_msg("%s: bad arguments", argv[0]);
8596 #if ENABLE_HUSH_LOOPS
8597 static int FAST_FUNC builtin_break(char **argv)
8600 if (G.depth_of_loop == 0) {
8601 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8602 return EXIT_SUCCESS; /* bash compat */
8604 G.flag_break_continue++; /* BC_BREAK = 1 */
8606 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8607 if (depth == UINT_MAX)
8608 G.flag_break_continue = BC_BREAK;
8609 if (G.depth_of_loop < depth)
8610 G.depth_break_continue = G.depth_of_loop;
8612 return EXIT_SUCCESS;
8615 static int FAST_FUNC builtin_continue(char **argv)
8617 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8618 return builtin_break(argv);
8622 #if ENABLE_HUSH_FUNCTIONS
8623 static int FAST_FUNC builtin_return(char **argv)
8627 if (G.flag_return_in_progress != -1) {
8628 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8629 return EXIT_FAILURE; /* bash compat */
8632 G.flag_return_in_progress = 1;
8635 * out of range: wraps around at 256, does not error out
8636 * non-numeric param:
8637 * f() { false; return qwe; }; f; echo $?
8638 * bash: return: qwe: numeric argument required <== we do this
8639 * 255 <== we also do this
8641 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);