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
478 #if ENABLE_HUSH_BASH_COMPAT
479 /* used for "[[ EXPR ]]" */
480 # define CMD_SINGLEWORD_NOGLOB 2
482 #if ENABLE_HUSH_FUNCTIONS
483 # define CMD_FUNCDEF 3
486 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
489 char *group_as_string;
491 #if ENABLE_HUSH_FUNCTIONS
492 struct function *child_func;
493 /* This field is used to prevent a bug here:
494 * while...do f1() {a;}; f1; f1() {b;}; f1; done
495 * When we execute "f1() {a;}" cmd, we create new function and clear
496 * cmd->group, cmd->group_as_string, cmd->argv[0].
497 * When we execute "f1() {b;}", we notice that f1 exists,
498 * and that its "parent cmd" struct is still "alive",
499 * we put those fields back into cmd->xxx
500 * (struct function has ->parent_cmd ptr to facilitate that).
501 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
502 * Without this trick, loop would execute a;b;b;b;...
503 * instead of correct sequence a;b;a;b;...
504 * When command is freed, it severs the link
505 * (sets ->child_func->parent_cmd to NULL).
508 char **argv; /* command name and arguments */
509 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
510 * and on execution these are substituted with their values.
511 * Substitution can make _several_ words out of one argv[n]!
512 * Example: argv[0]=='.^C*^C.' here: echo .$*.
513 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
515 struct redir_struct *redirects; /* I/O redirections */
517 /* Is there anything in this command at all? */
518 #define IS_NULL_CMD(cmd) \
519 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
524 int num_cmds; /* total number of commands in pipe */
525 int alive_cmds; /* number of commands running (not exited) */
526 int stopped_cmds; /* number of commands alive, but stopped */
528 int jobid; /* job number */
529 pid_t pgrp; /* process group ID for the job */
530 char *cmdtext; /* name of job */
532 struct command *cmds; /* array of commands in pipe */
533 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
534 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
535 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
537 typedef enum pipe_style {
543 /* Is there anything in this pipe at all? */
544 #define IS_NULL_PIPE(pi) \
545 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
547 /* This holds pointers to the various results of parsing */
548 struct parse_context {
549 /* linked list of pipes */
550 struct pipe *list_head;
551 /* last pipe (being constructed right now) */
553 /* last command in pipe (being constructed right now) */
554 struct command *command;
555 /* last redirect in command->redirects list */
556 struct redir_struct *pending_redirect;
562 smallint ctx_inverted; /* "! cmd | cmd" */
564 smallint ctx_dsemicolon; /* ";;" seen */
566 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
568 /* group we are enclosed in:
569 * example: "if pipe1; pipe2; then pipe3; fi"
570 * when we see "if" or "then", we malloc and copy current context,
571 * and make ->stack point to it. then we parse pipeN.
572 * when closing "then" / fi" / whatever is found,
573 * we move list_head into ->stack->command->group,
574 * copy ->stack into current context, and delete ->stack.
575 * (parsing of { list } and ( list ) doesn't use this method)
577 struct parse_context *stack;
581 /* On program start, environ points to initial environment.
582 * putenv adds new pointers into it, unsetenv removes them.
583 * Neither of these (de)allocates the strings.
584 * setenv allocates new strings in malloc space and does putenv,
585 * and thus setenv is unusable (leaky) for shell's purposes */
586 #define setenv(...) setenv_is_leaky_dont_use()
588 struct variable *next;
589 char *varstr; /* points to "name=" portion */
590 #if ENABLE_HUSH_LOCAL
591 unsigned func_nest_level;
593 int max_len; /* if > 0, name is part of initial env; else name is malloced */
594 smallint flg_export; /* putenv should be done on this var */
595 smallint flg_read_only;
603 #if ENABLE_HUSH_FUNCTIONS
605 struct function *next;
607 struct command *parent_cmd;
610 char *body_as_string;
616 /* "Globals" within this file */
617 /* Sorted roughly by size (smaller offsets == smaller code) */
619 /* interactive_fd != 0 means we are an interactive shell.
620 * If we are, then saved_tty_pgrp can also be != 0, meaning
621 * that controlling tty is available. With saved_tty_pgrp == 0,
622 * job control still works, but terminal signals
623 * (^C, ^Z, ^Y, ^\) won't work at all, and background
624 * process groups can only be created with "cmd &".
625 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
626 * to give tty to the foreground process group,
627 * and will take it back when the group is stopped (^Z)
630 #if ENABLE_HUSH_INTERACTIVE
631 /* 'interactive_fd' is a fd# open to ctty, if we have one
632 * _AND_ if we decided to act interactively */
636 # define G_interactive_fd (G.interactive_fd)
638 # define G_interactive_fd 0
640 #if ENABLE_FEATURE_EDITING
641 line_input_t *line_input_state;
646 #if ENABLE_HUSH_RANDOM_SUPPORT
652 pid_t saved_tty_pgrp;
653 struct pipe *job_list;
654 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
656 # define G_saved_tty_pgrp 0
658 smallint flag_SIGINT;
659 #if ENABLE_HUSH_LOOPS
660 smallint flag_break_continue;
662 #if ENABLE_HUSH_FUNCTIONS
663 /* 0: outside of a function (or sourced file)
664 * -1: inside of a function, ok to use return builtin
665 * 1: return is invoked, skip all till end of func
667 smallint flag_return_in_progress;
670 #if ENABLE_HUSH_MODE_X
672 # define G_x_mode (G.x_mode)
676 smallint exiting; /* used to prevent EXIT trap recursion */
677 /* These four support $?, $#, and $1 */
678 smalluint last_exitcode;
679 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
680 smalluint global_args_malloced;
681 smalluint inherited_set_is_saved;
682 /* how many non-NULL argv's we have. NB: $# + 1 */
686 char *argv0_for_re_execing;
688 #if ENABLE_HUSH_LOOPS
689 unsigned depth_break_continue;
690 unsigned depth_of_loop;
694 struct variable *top_var; /* = &G.shell_ver (set in main()) */
695 struct variable shell_ver;
696 char **expanded_assignments;
697 #if ENABLE_HUSH_FUNCTIONS
698 struct function *top_func;
699 # if ENABLE_HUSH_LOCAL
700 struct variable **shadowed_vars_pp;
701 unsigned func_nest_level;
704 /* Signal and trap handling */
706 unsigned count_SIGCHLD;
707 unsigned handled_SIGCHLD;
708 smallint we_have_children;
710 /* which signals have non-DFL handler (even with no traps set)? */
711 unsigned non_DFL_mask;
712 char **traps; /* char *traps[NSIG] */
713 sigset_t blocked_set;
714 sigset_t inherited_set;
716 unsigned long memleak_value;
719 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
721 #define G (*ptr_to_globals)
722 /* Not #defining name to G.name - this quickly gets unwieldy
723 * (too many defines). Also, I actually prefer to see when a variable
724 * is global, thus "G." prefix is a useful hint */
725 #define INIT_G() do { \
726 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
730 /* Function prototypes for builtins */
731 static int builtin_cd(char **argv) FAST_FUNC;
732 static int builtin_echo(char **argv) FAST_FUNC;
733 static int builtin_eval(char **argv) FAST_FUNC;
734 static int builtin_exec(char **argv) FAST_FUNC;
735 static int builtin_exit(char **argv) FAST_FUNC;
736 static int builtin_export(char **argv) FAST_FUNC;
738 static int builtin_fg_bg(char **argv) FAST_FUNC;
739 static int builtin_jobs(char **argv) FAST_FUNC;
742 static int builtin_help(char **argv) FAST_FUNC;
744 #if ENABLE_HUSH_LOCAL
745 static int builtin_local(char **argv) FAST_FUNC;
748 static int builtin_memleak(char **argv) FAST_FUNC;
751 static int builtin_printf(char **argv) FAST_FUNC;
753 static int builtin_pwd(char **argv) FAST_FUNC;
754 static int builtin_read(char **argv) FAST_FUNC;
755 static int builtin_set(char **argv) FAST_FUNC;
756 static int builtin_shift(char **argv) FAST_FUNC;
757 static int builtin_source(char **argv) FAST_FUNC;
758 static int builtin_test(char **argv) FAST_FUNC;
759 static int builtin_trap(char **argv) FAST_FUNC;
760 static int builtin_type(char **argv) FAST_FUNC;
761 static int builtin_true(char **argv) FAST_FUNC;
762 static int builtin_umask(char **argv) FAST_FUNC;
763 static int builtin_unset(char **argv) FAST_FUNC;
764 static int builtin_wait(char **argv) FAST_FUNC;
765 #if ENABLE_HUSH_LOOPS
766 static int builtin_break(char **argv) FAST_FUNC;
767 static int builtin_continue(char **argv) FAST_FUNC;
769 #if ENABLE_HUSH_FUNCTIONS
770 static int builtin_return(char **argv) FAST_FUNC;
773 /* Table of built-in functions. They can be forked or not, depending on
774 * context: within pipes, they fork. As simple commands, they do not.
775 * When used in non-forking context, they can change global variables
776 * in the parent shell process. If forked, of course they cannot.
777 * For example, 'unset foo | whatever' will parse and run, but foo will
778 * still be set at the end. */
779 struct built_in_command {
781 int (*b_function)(char **argv) FAST_FUNC;
784 # define BLTIN(cmd, func, help) { cmd, func, help }
786 # define BLTIN(cmd, func, help) { cmd, func }
790 static const struct built_in_command bltins1[] = {
791 BLTIN("." , builtin_source , "Run commands in a file"),
792 BLTIN(":" , builtin_true , NULL),
794 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
796 #if ENABLE_HUSH_LOOPS
797 BLTIN("break" , builtin_break , "Exit from a loop"),
799 BLTIN("cd" , builtin_cd , "Change directory"),
800 #if ENABLE_HUSH_LOOPS
801 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
803 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
804 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
805 BLTIN("exit" , builtin_exit , "Exit"),
806 BLTIN("export" , builtin_export , "Set environment variables"),
808 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
811 BLTIN("help" , builtin_help , NULL),
814 BLTIN("jobs" , builtin_jobs , "List jobs"),
816 #if ENABLE_HUSH_LOCAL
817 BLTIN("local" , builtin_local , "Set local variables"),
820 BLTIN("memleak" , builtin_memleak , NULL),
822 BLTIN("read" , builtin_read , "Input into variable"),
823 #if ENABLE_HUSH_FUNCTIONS
824 BLTIN("return" , builtin_return , "Return from a function"),
826 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
827 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
828 #if ENABLE_HUSH_BASH_COMPAT
829 BLTIN("source" , builtin_source , "Run commands in a file"),
831 BLTIN("trap" , builtin_trap , "Trap signals"),
832 BLTIN("type" , builtin_type , "Show command type"),
833 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
834 BLTIN("umask" , builtin_umask , "Set file creation mask"),
835 BLTIN("unset" , builtin_unset , "Unset variables"),
836 BLTIN("wait" , builtin_wait , "Wait for process"),
838 /* For now, echo and test are unconditionally enabled.
839 * Maybe make it configurable? */
840 static const struct built_in_command bltins2[] = {
841 BLTIN("[" , builtin_test , NULL),
842 BLTIN("echo" , builtin_echo , NULL),
844 BLTIN("printf" , builtin_printf , NULL),
846 BLTIN("pwd" , builtin_pwd , NULL),
847 BLTIN("test" , builtin_test , NULL),
854 /* prevent disasters with G.debug_indent < 0 */
855 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
856 # define debug_enter() (G.debug_indent++)
857 # define debug_leave() (G.debug_indent--)
859 # define indent() ((void)0)
860 # define debug_enter() ((void)0)
861 # define debug_leave() ((void)0)
865 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
868 #ifndef debug_printf_parse
869 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
872 #ifndef debug_printf_exec
873 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
876 #ifndef debug_printf_env
877 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
880 #ifndef debug_printf_jobs
881 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
882 # define DEBUG_JOBS 1
884 # define DEBUG_JOBS 0
887 #ifndef debug_printf_expand
888 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
889 # define DEBUG_EXPAND 1
891 # define DEBUG_EXPAND 0
894 #ifndef debug_printf_varexp
895 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
898 #ifndef debug_printf_glob
899 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
900 # define DEBUG_GLOB 1
902 # define DEBUG_GLOB 0
905 #ifndef debug_printf_list
906 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 #ifndef debug_printf_subst
910 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
913 #ifndef debug_printf_clean
914 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
915 # define DEBUG_CLEAN 1
917 # define DEBUG_CLEAN 0
921 static void debug_print_strings(const char *prefix, char **vv)
924 fprintf(stderr, "%s:\n", prefix);
926 fprintf(stderr, " '%s'\n", *vv++);
929 # define debug_print_strings(prefix, vv) ((void)0)
933 /* Leak hunting. Use hush_leaktool.sh for post-processing.
936 static void *xxmalloc(int lineno, size_t size)
938 void *ptr = xmalloc((size + 0xff) & ~0xff);
939 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
942 static void *xxrealloc(int lineno, void *ptr, size_t size)
944 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
945 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
948 static char *xxstrdup(int lineno, const char *str)
950 char *ptr = xstrdup(str);
951 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
954 static void xxfree(void *ptr)
956 fdprintf(2, "free %p\n", ptr);
959 # define xmalloc(s) xxmalloc(__LINE__, s)
960 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
961 # define xstrdup(s) xxstrdup(__LINE__, s)
962 # define free(p) xxfree(p)
966 /* Syntax and runtime errors. They always abort scripts.
967 * In interactive use they usually discard unparsed and/or unexecuted commands
968 * and return to the prompt.
969 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
972 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
973 # define syntax_error(lineno, msg) syntax_error(msg)
974 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
975 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
976 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
977 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
980 static void die_if_script(unsigned lineno, const char *fmt, ...)
985 bb_error_msg("hush.c:%u", lineno);
988 bb_verror_msg(fmt, p, NULL);
990 if (!G_interactive_fd)
994 static void syntax_error(unsigned lineno, const char *msg)
997 die_if_script(lineno, "syntax error: %s", msg);
999 die_if_script(lineno, "syntax error", NULL);
1002 static void syntax_error_at(unsigned lineno, const char *msg)
1004 die_if_script(lineno, "syntax error at '%s'", msg);
1007 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1009 die_if_script(lineno, "syntax error: unterminated %s", s);
1012 /* It so happens that all such cases are totally fatal
1013 * even if shell is interactive: EOF while looking for closing
1014 * delimiter. There is nowhere to read stuff from after that,
1015 * it's EOF! The only choice is to terminate.
1017 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1018 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1020 char msg[2] = { ch, '\0' };
1021 syntax_error_unterm_str(lineno, msg);
1025 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1030 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1034 # undef die_if_script
1035 # undef syntax_error
1036 # undef syntax_error_at
1037 # undef syntax_error_unterm_ch
1038 # undef syntax_error_unterm_str
1039 # undef syntax_error_unexpected_ch
1041 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1042 # define syntax_error(msg) syntax_error(__LINE__, msg)
1043 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1044 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1045 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1046 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1050 #if ENABLE_HUSH_INTERACTIVE
1051 static void cmdedit_update_prompt(void);
1053 # define cmdedit_update_prompt() ((void)0)
1057 /* Utility functions
1059 /* Replace each \x with x in place, return ptr past NUL. */
1060 static char *unbackslash(char *src)
1062 char *dst = src = strchrnul(src, '\\');
1066 if ((*dst++ = *src++) == '\0')
1072 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1093 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1094 v[count1 + count2] = NULL;
1097 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1101 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1103 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1104 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1107 #define add_strings_to_strings(strings, add, need_to_dup) \
1108 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1111 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1112 static char **add_string_to_strings(char **strings, char *add)
1117 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1120 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1122 char **ptr = add_string_to_strings(strings, add);
1123 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1126 #define add_string_to_strings(strings, add) \
1127 xx_add_string_to_strings(__LINE__, strings, add)
1130 static void free_strings(char **strings)
1145 /* Helpers for setting new $n and restoring them back
1147 typedef struct save_arg_t {
1151 smallint sv_g_malloced;
1154 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1158 sv->sv_argv0 = argv[0];
1159 sv->sv_g_argv = G.global_argv;
1160 sv->sv_g_argc = G.global_argc;
1161 sv->sv_g_malloced = G.global_args_malloced;
1163 argv[0] = G.global_argv[0]; /* retain $0 */
1164 G.global_argv = argv;
1165 G.global_args_malloced = 0;
1173 static void restore_G_args(save_arg_t *sv, char **argv)
1177 if (G.global_args_malloced) {
1178 /* someone ran "set -- arg1 arg2 ...", undo */
1180 while (*++pp) /* note: does not free $0 */
1182 free(G.global_argv);
1184 argv[0] = sv->sv_argv0;
1185 G.global_argv = sv->sv_g_argv;
1186 G.global_argc = sv->sv_g_argc;
1187 G.global_args_malloced = sv->sv_g_malloced;
1191 /* Basic theory of signal handling in shell
1192 * ========================================
1193 * This does not describe what hush does, rather, it is current understanding
1194 * what it _should_ do. If it doesn't, it's a bug.
1195 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1197 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1198 * is finished or backgrounded. It is the same in interactive and
1199 * non-interactive shells, and is the same regardless of whether
1200 * a user trap handler is installed or a shell special one is in effect.
1201 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1202 * backgrounds (i.e. stops) or kills all members of currently running
1205 * Wait builtin in interruptible by signals for which user trap is set
1206 * or by SIGINT in interactive shell.
1208 * Trap handlers will execute even within trap handlers. (right?)
1210 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1211 * except for handlers set to '' (empty string).
1213 * If job control is off, backgrounded commands ("cmd &")
1214 * have SIGINT, SIGQUIT set to SIG_IGN.
1216 * Commands which are run in command substitution ("`cmd`")
1217 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1219 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1220 * by the shell from its parent.
1222 * Signals which differ from SIG_DFL action
1223 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1226 * SIGTERM (interactive): ignore
1227 * SIGHUP (interactive):
1228 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1229 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1230 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1231 * that all pipe members are stopped. Try this in bash:
1232 * while :; do :; done - ^Z does not background it
1233 * (while :; do :; done) - ^Z backgrounds it
1234 * SIGINT (interactive): wait for last pipe, ignore the rest
1235 * of the command line, show prompt. NB: ^C does not send SIGINT
1236 * to interactive shell while shell is waiting for a pipe,
1237 * since shell is bg'ed (is not in foreground process group).
1238 * Example 1: this waits 5 sec, but does not execute ls:
1239 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1240 * Example 2: this does not wait and does not execute ls:
1241 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1242 * Example 3: this does not wait 5 sec, but executes ls:
1243 * "sleep 5; ls -l" + press ^C
1245 * (What happens to signals which are IGN on shell start?)
1246 * (What happens with signal mask on shell start?)
1248 * Implementation in hush
1249 * ======================
1250 * We use in-kernel pending signal mask to determine which signals were sent.
1251 * We block all signals which we don't want to take action immediately,
1252 * i.e. we block all signals which need to have special handling as described
1253 * above, and all signals which have traps set.
1254 * After each pipe execution, we extract any pending signals via sigtimedwait()
1257 * unsigned non_DFL_mask: a mask of such "special" signals
1258 * sigset_t blocked_set: current blocked signal set
1261 * clear bit in blocked_set unless it is also in non_DFL_mask
1262 * "trap 'cmd' SIGxxx":
1263 * set bit in blocked_set (even if 'cmd' is '')
1264 * after [v]fork, if we plan to be a shell:
1265 * unblock signals with special interactive handling
1266 * (child shell is not interactive),
1267 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1268 * after [v]fork, if we plan to exec:
1269 * POSIX says fork clears pending signal mask in child - no need to clear it.
1270 * Restore blocked signal set to one inherited by shell just prior to exec.
1272 * Note: as a result, we do not use signal handlers much. The only uses
1273 * are to count SIGCHLDs
1274 * and to restore tty pgrp on signal-induced exit.
1277 * Standard says "When a subshell is entered, traps that are not being ignored
1278 * are set to the default actions". bash interprets it so that traps which
1279 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1282 SPECIAL_INTERACTIVE_SIGS = 0
1287 SPECIAL_JOB_SIGS = 0
1295 #if ENABLE_HUSH_FAST
1296 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1299 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1305 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1306 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1307 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1308 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1310 /* Restores tty foreground process group, and exits.
1311 * May be called as signal handler for fatal signal
1312 * (will resend signal to itself, producing correct exit state)
1313 * or called directly with -EXITCODE.
1314 * We also call it if xfunc is exiting. */
1315 static void sigexit(int sig) NORETURN;
1316 static void sigexit(int sig)
1318 /* Disable all signals: job control, SIGPIPE, etc. */
1319 sigprocmask_allsigs(SIG_BLOCK);
1321 /* Careful: we can end up here after [v]fork. Do not restore
1322 * tty pgrp then, only top-level shell process does that */
1323 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1324 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1326 /* Not a signal, just exit */
1330 kill_myself_with_sig(sig); /* does not return */
1334 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1335 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1339 /* Restores tty foreground process group, and exits. */
1340 static void hush_exit(int exitcode) NORETURN;
1341 static void hush_exit(int exitcode)
1343 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1344 /* Prevent recursion:
1345 * trap "echo Hi; exit" EXIT; exit
1347 char *argv[] = { NULL, G.traps[0], NULL };
1356 sigexit(- (exitcode & 0xff));
1362 static int check_and_run_traps(int sig)
1364 static const struct timespec zero_timespec;
1365 smalluint save_rcode;
1371 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1376 if (G.traps && G.traps[sig]) {
1377 if (G.traps[sig][0]) {
1378 /* We have user-defined handler */
1379 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1380 save_rcode = G.last_exitcode;
1383 G.last_exitcode = save_rcode;
1384 } /* else: "" trap, ignoring signal */
1387 /* not a trap: special action */
1389 #if ENABLE_HUSH_FAST
1392 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1396 /* Builtin was ^C'ed, make it look prettier: */
1403 /* bash is observed to signal whole process groups,
1404 * not individual processes */
1405 for (job = G.job_list; job; job = job->next) {
1408 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1409 if (kill(- job->pgrp, SIGHUP) == 0)
1410 kill(- job->pgrp, SIGCONT);
1415 default: /* ignored: */
1416 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1424 static const char *get_cwd(int force)
1426 if (force || G.cwd == NULL) {
1427 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1428 * we must not try to free(bb_msg_unknown) */
1429 if (G.cwd == bb_msg_unknown)
1431 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1433 G.cwd = bb_msg_unknown;
1440 * Shell and environment variable support
1442 static struct variable **get_ptr_to_local_var(const char *name)
1444 struct variable **pp;
1445 struct variable *cur;
1450 while ((cur = *pp) != NULL) {
1451 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1458 static struct variable *get_local_var(const char *name)
1460 struct variable **pp = get_ptr_to_local_var(name);
1466 static const char* FAST_FUNC get_local_var_value(const char *name)
1468 struct variable **vpp;
1470 if (G.expanded_assignments) {
1471 char **cpp = G.expanded_assignments;
1472 int len = strlen(name);
1475 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1476 return cp + len + 1;
1481 vpp = get_ptr_to_local_var(name);
1483 return strchr((*vpp)->varstr, '=') + 1;
1485 if (strcmp(name, "PPID") == 0)
1486 return utoa(G.root_ppid);
1487 // bash compat: UID? EUID?
1488 #if ENABLE_HUSH_RANDOM_SUPPORT
1489 if (strcmp(name, "RANDOM") == 0) {
1490 return utoa(next_random(&G.random_gen));
1496 /* str holds "NAME=VAL" and is expected to be malloced.
1497 * We take ownership of it.
1499 * 0: do not change export flag
1500 * (if creating new variable, flag will be 0)
1501 * 1: set export flag and putenv the variable
1502 * -1: clear export flag and unsetenv the variable
1503 * flg_read_only is set only when we handle -R var=val
1505 #if !BB_MMU && ENABLE_HUSH_LOCAL
1506 /* all params are used */
1507 #elif BB_MMU && ENABLE_HUSH_LOCAL
1508 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1509 set_local_var(str, flg_export, local_lvl)
1510 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1511 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1512 set_local_var(str, flg_export)
1513 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1514 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1515 set_local_var(str, flg_export, flg_read_only)
1517 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1519 struct variable **var_pp;
1520 struct variable *cur;
1524 eq_sign = strchr(str, '=');
1525 if (!eq_sign) { /* not expected to ever happen? */
1530 name_len = eq_sign - str + 1; /* including '=' */
1531 var_pp = &G.top_var;
1532 while ((cur = *var_pp) != NULL) {
1533 if (strncmp(cur->varstr, str, name_len) != 0) {
1534 var_pp = &cur->next;
1537 /* We found an existing var with this name */
1538 if (cur->flg_read_only) {
1542 bb_error_msg("%s: readonly variable", str);
1546 if (flg_export == -1) { // "&& cur->flg_export" ?
1547 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1552 #if ENABLE_HUSH_LOCAL
1553 if (cur->func_nest_level < local_lvl) {
1554 /* New variable is declared as local,
1555 * and existing one is global, or local
1556 * from enclosing function.
1557 * Remove and save old one: */
1558 *var_pp = cur->next;
1559 cur->next = *G.shadowed_vars_pp;
1560 *G.shadowed_vars_pp = cur;
1561 /* bash 3.2.33(1) and exported vars:
1563 * # f() { local z=a; env | grep ^z; }
1569 if (cur->flg_export)
1574 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1579 if (cur->max_len != 0) {
1580 if (cur->max_len >= strlen(str)) {
1581 /* This one is from startup env, reuse space */
1582 strcpy(cur->varstr, str);
1586 /* max_len == 0 signifies "malloced" var, which we can
1587 * (and has to) free */
1591 goto set_str_and_exp;
1594 /* Not found - create new variable struct */
1595 cur = xzalloc(sizeof(*cur));
1596 #if ENABLE_HUSH_LOCAL
1597 cur->func_nest_level = local_lvl;
1599 cur->next = *var_pp;
1605 cur->flg_read_only = flg_read_only;
1608 if (flg_export == 1)
1609 cur->flg_export = 1;
1610 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1611 cmdedit_update_prompt();
1612 if (cur->flg_export) {
1613 if (flg_export == -1) {
1614 cur->flg_export = 0;
1615 /* unsetenv was already done */
1617 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1618 return putenv(cur->varstr);
1624 /* Used at startup and after each cd */
1625 static void set_pwd_var(int exp)
1627 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1628 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1631 static int unset_local_var_len(const char *name, int name_len)
1633 struct variable *cur;
1634 struct variable **var_pp;
1637 return EXIT_SUCCESS;
1638 var_pp = &G.top_var;
1639 while ((cur = *var_pp) != NULL) {
1640 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1641 if (cur->flg_read_only) {
1642 bb_error_msg("%s: readonly variable", name);
1643 return EXIT_FAILURE;
1645 *var_pp = cur->next;
1646 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1647 bb_unsetenv(cur->varstr);
1648 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1649 cmdedit_update_prompt();
1653 return EXIT_SUCCESS;
1655 var_pp = &cur->next;
1657 return EXIT_SUCCESS;
1660 static int unset_local_var(const char *name)
1662 return unset_local_var_len(name, strlen(name));
1665 static void unset_vars(char **strings)
1673 const char *eq = strchrnul(*v, '=');
1674 unset_local_var_len(*v, (int)(eq - *v));
1680 #if ENABLE_SH_MATH_SUPPORT
1681 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1682 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1683 static char* FAST_FUNC endofname(const char *name)
1691 if (!is_in_name(*p))
1698 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1700 char *var = xasprintf("%s=%s", name, val);
1701 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1706 * Helpers for "var1=val1 var2=val2 cmd" feature
1708 static void add_vars(struct variable *var)
1710 struct variable *next;
1714 var->next = G.top_var;
1716 if (var->flg_export) {
1717 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1718 putenv(var->varstr);
1720 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1726 static struct variable *set_vars_and_save_old(char **strings)
1729 struct variable *old = NULL;
1735 struct variable *var_p;
1736 struct variable **var_pp;
1739 eq = strchr(*s, '=');
1742 var_pp = get_ptr_to_local_var(*s);
1745 /* Remove variable from global linked list */
1747 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1748 *var_pp = var_p->next;
1749 /* Add it to returned list */
1753 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1764 static int FAST_FUNC static_get(struct in_str *i)
1774 static int FAST_FUNC static_peek(struct in_str *i)
1779 #if ENABLE_HUSH_INTERACTIVE
1781 static void cmdedit_update_prompt(void)
1783 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1784 G.PS1 = get_local_var_value("PS1");
1787 G.PS2 = get_local_var_value("PS2");
1795 static const char* setup_prompt_string(int promptmode)
1797 const char *prompt_str;
1798 debug_printf("setup_prompt_string %d ", promptmode);
1799 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1800 /* Set up the prompt */
1801 if (promptmode == 0) { /* PS1 */
1803 /* bash uses $PWD value, even if it is set by user.
1804 * It uses current dir only if PWD is unset.
1805 * We always use current dir. */
1806 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1811 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1812 debug_printf("result '%s'\n", prompt_str);
1816 static void get_user_input(struct in_str *i)
1819 const char *prompt_str;
1821 prompt_str = setup_prompt_string(i->promptmode);
1822 # if ENABLE_FEATURE_EDITING
1823 /* Enable command line editing only while a command line
1824 * is actually being read */
1827 /* buglet: SIGINT will not make new prompt to appear _at once_,
1828 * only after <Enter>. (^C will work) */
1829 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1830 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1831 check_and_run_traps(0);
1832 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1833 i->eof_flag = (r < 0);
1834 if (i->eof_flag) { /* EOF/error detected */
1835 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1836 G.user_input_buf[1] = '\0';
1841 fputs(prompt_str, stdout);
1843 G.user_input_buf[0] = r = fgetc(i->file);
1844 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1845 //do we need check_and_run_traps(0)? (maybe only if stdin)
1846 } while (G.flag_SIGINT);
1847 i->eof_flag = (r == EOF);
1849 i->p = G.user_input_buf;
1852 #endif /* INTERACTIVE */
1854 /* This is the magic location that prints prompts
1855 * and gets data back from the user */
1856 static int FAST_FUNC file_get(struct in_str *i)
1860 /* If there is data waiting, eat it up */
1861 if (i->p && *i->p) {
1862 #if ENABLE_HUSH_INTERACTIVE
1866 if (i->eof_flag && !*i->p)
1868 /* note: ch is never NUL */
1870 /* need to double check i->file because we might be doing something
1871 * more complicated by now, like sourcing or substituting. */
1872 #if ENABLE_HUSH_INTERACTIVE
1873 if (G_interactive_fd && i->promptme && i->file == stdin) {
1876 } while (!*i->p); /* need non-empty line */
1877 i->promptmode = 1; /* PS2 */
1882 do ch = fgetc(i->file); while (ch == '\0');
1884 debug_printf("file_get: got '%c' %d\n", ch, ch);
1885 #if ENABLE_HUSH_INTERACTIVE
1892 /* All callers guarantee this routine will never
1893 * be used right after a newline, so prompting is not needed.
1895 static int FAST_FUNC file_peek(struct in_str *i)
1898 if (i->p && *i->p) {
1899 if (i->eof_flag && !i->p[1])
1902 /* note: ch is never NUL */
1904 do ch = fgetc(i->file); while (ch == '\0');
1905 i->eof_flag = (ch == EOF);
1906 i->peek_buf[0] = ch;
1907 i->peek_buf[1] = '\0';
1909 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1913 static void setup_file_in_str(struct in_str *i, FILE *f)
1915 i->peek = file_peek;
1917 #if ENABLE_HUSH_INTERACTIVE
1919 i->promptmode = 0; /* PS1 */
1925 static void setup_string_in_str(struct in_str *i, const char *s)
1927 i->peek = static_peek;
1928 i->get = static_get;
1929 #if ENABLE_HUSH_INTERACTIVE
1931 i->promptmode = 0; /* PS1 */
1941 #define B_CHUNK (32 * sizeof(char*))
1943 static void o_reset_to_empty_unquoted(o_string *o)
1946 o->has_quoted_part = 0;
1951 static void o_free(o_string *o)
1954 memset(o, 0, sizeof(*o));
1957 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1962 static void o_grow_by(o_string *o, int len)
1964 if (o->length + len > o->maxlen) {
1965 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1966 o->data = xrealloc(o->data, 1 + o->maxlen);
1970 static void o_addchr(o_string *o, int ch)
1972 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1974 o->data[o->length] = ch;
1976 o->data[o->length] = '\0';
1979 static void o_addblock(o_string *o, const char *str, int len)
1982 memcpy(&o->data[o->length], str, len);
1984 o->data[o->length] = '\0';
1987 static void o_addstr(o_string *o, const char *str)
1989 o_addblock(o, str, strlen(str));
1993 static void nommu_addchr(o_string *o, int ch)
1999 # define nommu_addchr(o, str) ((void)0)
2002 static void o_addstr_with_NUL(o_string *o, const char *str)
2004 o_addblock(o, str, strlen(str) + 1);
2007 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2012 if (*str++ == '\\') {
2013 /* \z -> \\\z; \<eol> -> \\<eol> */
2018 o_addchr(o, *str++);
2024 #undef HUSH_BRACE_EXP
2026 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2027 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2028 * Apparently, on unquoted $v bash still does globbing
2029 * ("v='*.txt'; echo $v" prints all .txt files),
2030 * but NOT brace expansion! Thus, there should be TWO independent
2031 * quoting mechanisms on $v expansion side: one protects
2032 * $v from brace expansion, and other additionally protects "$v" against globbing.
2033 * We have only second one.
2036 #ifdef HUSH_BRACE_EXP
2037 # define MAYBE_BRACES "{}"
2039 # define MAYBE_BRACES ""
2042 /* My analysis of quoting semantics tells me that state information
2043 * is associated with a destination, not a source.
2045 static void o_addqchr(o_string *o, int ch)
2048 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2053 o->data[o->length] = '\\';
2056 o->data[o->length] = ch;
2058 o->data[o->length] = '\0';
2061 static void o_addQchr(o_string *o, int ch)
2064 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2066 o->data[o->length] = '\\';
2070 o->data[o->length] = ch;
2072 o->data[o->length] = '\0';
2075 static void o_addqblock(o_string *o, const char *str, int len)
2080 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2081 if (ordinary_cnt > len) /* paranoia */
2083 o_addblock(o, str, ordinary_cnt);
2084 if (ordinary_cnt == len)
2086 str += ordinary_cnt;
2087 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2091 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2093 o->data[o->length] = '\\';
2097 o->data[o->length] = ch;
2099 o->data[o->length] = '\0';
2103 static void o_addQblock(o_string *o, const char *str, int len)
2106 o_addblock(o, str, len);
2109 o_addqblock(o, str, len);
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 perform_glob(o_string *o, int n)
2371 char *pattern, *copy;
2373 debug_printf_glob("start perform_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("perform_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 perform_glob(o_string *o, int n)
2422 debug_printf_glob("start perform_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("perform_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 perform_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 # if ENABLE_HUSH_BASH_COMPAT
2941 if (strcmp(word->data, "[[") == 0) {
2942 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2948 if (command->group) {
2949 /* "{ echo foo; } echo bar" - bad */
2950 syntax_error_at(word->data);
2951 debug_printf_parse("done_word return 1: syntax error, "
2952 "groups and arglists don't mix\n");
2955 if (word->has_quoted_part
2956 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2957 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2958 /* (otherwise it's known to be not empty and is already safe) */
2960 /* exclude "$@" - it can expand to no word despite "" */
2961 char *p = word->data;
2962 while (p[0] == SPECIAL_VAR_SYMBOL
2963 && (p[1] & 0x7f) == '@'
2964 && p[2] == SPECIAL_VAR_SYMBOL
2968 if (p == word->data || p[0] != '\0') {
2969 /* saw no "$@", or not only "$@" but some
2970 * real text is there too */
2971 /* insert "empty variable" reference, this makes
2972 * e.g. "", $empty"" etc to not disappear */
2973 o_addchr(word, SPECIAL_VAR_SYMBOL);
2974 o_addchr(word, SPECIAL_VAR_SYMBOL);
2977 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2978 debug_print_strings("word appended to argv", command->argv);
2981 #if ENABLE_HUSH_LOOPS
2982 if (ctx->ctx_res_w == RES_FOR) {
2983 if (word->has_quoted_part
2984 || !is_well_formed_var_name(command->argv[0], '\0')
2986 /* bash says just "not a valid identifier" */
2987 syntax_error("not a valid identifier in for");
2990 /* Force FOR to have just one word (variable name) */
2991 /* NB: basically, this makes hush see "for v in ..."
2992 * syntax as if it is "for v; in ...". FOR and IN become
2993 * two pipe structs in parse tree. */
2994 done_pipe(ctx, PIPE_SEQ);
2997 #if ENABLE_HUSH_CASE
2998 /* Force CASE to have just one word */
2999 if (ctx->ctx_res_w == RES_CASE) {
3000 done_pipe(ctx, PIPE_SEQ);
3004 o_reset_to_empty_unquoted(word);
3006 debug_printf_parse("done_word return 0\n");
3011 /* Peek ahead in the input to find out if we have a "&n" construct,
3012 * as in "2>&1", that represents duplicating a file descriptor.
3014 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3015 * REDIRFD_SYNTAX_ERR if syntax error,
3016 * REDIRFD_TO_FILE if no & was seen,
3017 * or the number found.
3020 #define parse_redir_right_fd(as_string, input) \
3021 parse_redir_right_fd(input)
3023 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3029 return REDIRFD_TO_FILE;
3031 ch = i_getch(input); /* get the & */
3032 nommu_addchr(as_string, ch);
3035 ch = i_getch(input);
3036 nommu_addchr(as_string, ch);
3037 return REDIRFD_CLOSE;
3041 while (ch != EOF && isdigit(ch)) {
3042 d = d*10 + (ch-'0');
3044 ch = i_getch(input);
3045 nommu_addchr(as_string, ch);
3050 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3052 bb_error_msg("ambiguous redirect");
3053 return REDIRFD_SYNTAX_ERR;
3056 /* Return code is 0 normal, 1 if a syntax error is detected
3058 static int parse_redirect(struct parse_context *ctx,
3061 struct in_str *input)
3063 struct command *command = ctx->command;
3064 struct redir_struct *redir;
3065 struct redir_struct **redirp;
3068 dup_num = REDIRFD_TO_FILE;
3069 if (style != REDIRECT_HEREDOC) {
3070 /* Check for a '>&1' type redirect */
3071 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3072 if (dup_num == REDIRFD_SYNTAX_ERR)
3075 int ch = i_peek(input);
3076 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3077 if (dup_num) { /* <<-... */
3078 ch = i_getch(input);
3079 nommu_addchr(&ctx->as_string, ch);
3084 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3085 int ch = i_peek(input);
3087 /* >|FILE redirect ("clobbering" >).
3088 * Since we do not support "set -o noclobber" yet,
3089 * >| and > are the same for now. Just eat |.
3091 ch = i_getch(input);
3092 nommu_addchr(&ctx->as_string, ch);
3096 /* Create a new redir_struct and append it to the linked list */
3097 redirp = &command->redirects;
3098 while ((redir = *redirp) != NULL) {
3099 redirp = &(redir->next);
3101 *redirp = redir = xzalloc(sizeof(*redir));
3102 /* redir->next = NULL; */
3103 /* redir->rd_filename = NULL; */
3104 redir->rd_type = style;
3105 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3107 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3108 redir_table[style].descrip);
3110 redir->rd_dup = dup_num;
3111 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3112 /* Erik had a check here that the file descriptor in question
3113 * is legit; I postpone that to "run time"
3114 * A "-" representation of "close me" shows up as a -3 here */
3115 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3116 redir->rd_fd, redir->rd_dup);
3118 /* Set ctx->pending_redirect, so we know what to do at the
3119 * end of the next parsed word. */
3120 ctx->pending_redirect = redir;
3125 /* If a redirect is immediately preceded by a number, that number is
3126 * supposed to tell which file descriptor to redirect. This routine
3127 * looks for such preceding numbers. In an ideal world this routine
3128 * needs to handle all the following classes of redirects...
3129 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3130 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3131 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3132 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3134 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3136 * ... If n is quoted, the number shall not be recognized as part of
3137 * the redirection expression. For example:
3139 * writes the character 2 into file a"
3140 * We are getting it right by setting ->has_quoted_part on any \<char>
3142 * A -1 return means no valid number was found,
3143 * the caller should use the appropriate default for this redirection.
3145 static int redirect_opt_num(o_string *o)
3149 if (o->data == NULL)
3151 num = bb_strtou(o->data, NULL, 10);
3152 if (errno || num < 0)
3154 o_reset_to_empty_unquoted(o);
3159 #define fetch_till_str(as_string, input, word, skip_tabs) \
3160 fetch_till_str(input, word, skip_tabs)
3162 static char *fetch_till_str(o_string *as_string,
3163 struct in_str *input,
3167 o_string heredoc = NULL_O_STRING;
3169 int prev = 0; /* not \ */
3174 ch = i_getch(input);
3175 nommu_addchr(as_string, ch);
3177 /* TODO: or EOF? (heredoc delimiter may end with <eof>, not only <eol>) */
3178 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3180 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3181 heredoc.data[past_EOL] = '\0';
3182 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3183 return heredoc.data;
3186 o_addchr(&heredoc, '\n');
3187 prev = 0; /* not \ */
3188 past_EOL = heredoc.length;
3191 ch = i_getch(input);
3192 nommu_addchr(as_string, ch);
3193 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3194 } while (ch == '\n');
3197 o_free_unsafe(&heredoc);
3200 o_addchr(&heredoc, ch);
3201 if (prev == '\\' && ch == '\\')
3202 /* Correctly handle foo\\<eol> (not a line cont.) */
3203 prev = 0; /* not \ */
3206 nommu_addchr(as_string, ch);
3210 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3211 * and load them all. There should be exactly heredoc_cnt of them.
3213 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3215 struct pipe *pi = ctx->list_head;
3217 while (pi && heredoc_cnt) {
3219 struct command *cmd = pi->cmds;
3221 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3223 cmd->argv ? cmd->argv[0] : "NONE");
3224 for (i = 0; i < pi->num_cmds; i++) {
3225 struct redir_struct *redir = cmd->redirects;
3227 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3228 i, cmd->argv ? cmd->argv[0] : "NONE");
3230 if (redir->rd_type == REDIRECT_HEREDOC) {
3233 redir->rd_type = REDIRECT_HEREDOC2;
3234 /* redir->rd_dup is (ab)used to indicate <<- */
3235 p = fetch_till_str(&ctx->as_string, input,
3236 redir->rd_filename, redir->rd_dup);
3238 syntax_error("unexpected EOF in here document");
3241 free(redir->rd_filename);
3242 redir->rd_filename = p;
3245 redir = redir->next;
3252 /* Should be 0. If it isn't, it's a parse error */
3254 bb_error_msg_and_die("heredoc BUG 2");
3260 static int run_list(struct pipe *pi);
3262 #define parse_stream(pstring, input, end_trigger) \
3263 parse_stream(input, end_trigger)
3265 static struct pipe *parse_stream(char **pstring,
3266 struct in_str *input,
3270 #if !ENABLE_HUSH_FUNCTIONS
3271 #define parse_group(dest, ctx, input, ch) \
3272 parse_group(ctx, input, ch)
3274 static int parse_group(o_string *dest, struct parse_context *ctx,
3275 struct in_str *input, int ch)
3277 /* dest contains characters seen prior to ( or {.
3278 * Typically it's empty, but for function defs,
3279 * it contains function name (without '()'). */
3280 struct pipe *pipe_list;
3282 struct command *command = ctx->command;
3284 debug_printf_parse("parse_group entered\n");
3285 #if ENABLE_HUSH_FUNCTIONS
3286 if (ch == '(' && !dest->has_quoted_part) {
3288 if (done_word(dest, ctx))
3291 goto skip; /* (... */
3292 if (command->argv[1]) { /* word word ... (... */
3293 syntax_error_unexpected_ch('(');
3296 /* it is "word(..." or "word (..." */
3298 ch = i_getch(input);
3299 while (ch == ' ' || ch == '\t');
3301 syntax_error_unexpected_ch(ch);
3304 nommu_addchr(&ctx->as_string, ch);
3306 ch = i_getch(input);
3307 while (ch == ' ' || ch == '\t' || ch == '\n');
3309 syntax_error_unexpected_ch(ch);
3312 nommu_addchr(&ctx->as_string, ch);
3313 command->cmd_type = CMD_FUNCDEF;
3318 #if 0 /* Prevented by caller */
3319 if (command->argv /* word [word]{... */
3320 || dest->length /* word{... */
3321 || dest->has_quoted_part /* ""{... */
3324 debug_printf_parse("parse_group return 1: "
3325 "syntax error, groups and arglists don't mix\n");
3330 #if ENABLE_HUSH_FUNCTIONS
3336 command->cmd_type = CMD_SUBSHELL;
3338 /* bash does not allow "{echo...", requires whitespace */
3339 ch = i_getch(input);
3340 if (ch != ' ' && ch != '\t' && ch != '\n') {
3341 syntax_error_unexpected_ch(ch);
3344 nommu_addchr(&ctx->as_string, ch);
3349 # define as_string NULL
3351 char *as_string = NULL;
3353 pipe_list = parse_stream(&as_string, input, endch);
3356 o_addstr(&ctx->as_string, as_string);
3358 /* empty ()/{} or parse error? */
3359 if (!pipe_list || pipe_list == ERR_PTR) {
3360 /* parse_stream already emitted error msg */
3363 debug_printf_parse("parse_group return 1: "
3364 "parse_stream returned %p\n", pipe_list);
3367 command->group = pipe_list;
3369 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3370 command->group_as_string = as_string;
3371 debug_printf_parse("end of group, remembering as:'%s'\n",
3372 command->group_as_string);
3376 debug_printf_parse("parse_group return 0\n");
3378 /* command remains "open", available for possible redirects */
3381 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3382 /* Subroutines for copying $(...) and `...` things */
3383 static void add_till_backquote(o_string *dest, struct in_str *input);
3385 static void add_till_single_quote(o_string *dest, struct in_str *input)
3388 int ch = i_getch(input);
3390 syntax_error_unterm_ch('\'');
3391 /*xfunc_die(); - redundant */
3398 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3399 static void add_till_double_quote(o_string *dest, struct in_str *input)
3402 int ch = i_getch(input);
3404 syntax_error_unterm_ch('"');
3405 /*xfunc_die(); - redundant */
3409 if (ch == '\\') { /* \x. Copy both chars. */
3411 ch = i_getch(input);
3415 add_till_backquote(dest, input);
3419 //if (ch == '$') ...
3422 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3424 * "Within the backquoted style of command substitution, backslash
3425 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3426 * The search for the matching backquote shall be satisfied by the first
3427 * backquote found without a preceding backslash; during this search,
3428 * if a non-escaped backquote is encountered within a shell comment,
3429 * a here-document, an embedded command substitution of the $(command)
3430 * form, or a quoted string, undefined results occur. A single-quoted
3431 * or double-quoted string that begins, but does not end, within the
3432 * "`...`" sequence produces undefined results."
3434 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3436 static void add_till_backquote(o_string *dest, struct in_str *input)
3439 int ch = i_getch(input);
3441 syntax_error_unterm_ch('`');
3442 /*xfunc_die(); - redundant */
3447 /* \x. Copy both chars unless it is \` */
3448 int ch2 = i_getch(input);
3450 syntax_error_unterm_ch('`');
3451 /*xfunc_die(); - redundant */
3453 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3460 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3461 * quoting and nested ()s.
3462 * "With the $(command) style of command substitution, all characters
3463 * following the open parenthesis to the matching closing parenthesis
3464 * constitute the command. Any valid shell script can be used for command,
3465 * except a script consisting solely of redirections which produces
3466 * unspecified results."
3468 * echo $(echo '(TEST)' BEST) (TEST) BEST
3469 * echo $(echo 'TEST)' BEST) TEST) BEST
3470 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3472 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3473 * can contain arbitrary constructs, just like $(cmd).
3474 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3475 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3477 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3478 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3481 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3482 # if ENABLE_HUSH_BASH_COMPAT
3483 char end_char2 = end_ch >> 8;
3485 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3488 ch = i_getch(input);
3490 syntax_error_unterm_ch(end_ch);
3491 /*xfunc_die(); - redundant */
3493 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3496 /* we look for closing )) of $((EXPR)) */
3497 if (i_peek(input) == end_ch) {
3498 i_getch(input); /* eat second ')' */
3503 if (ch == '(' || ch == '{') {
3504 ch = (ch == '(' ? ')' : '}');
3505 add_till_closing_bracket(dest, input, ch);
3510 add_till_single_quote(dest, input);
3515 add_till_double_quote(dest, input);
3520 add_till_backquote(dest, input);
3525 /* \x. Copy verbatim. Important for \(, \) */
3526 ch = i_getch(input);
3528 syntax_error_unterm_ch(')');
3529 /*xfunc_die(); - redundant */
3537 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3539 /* Return code: 0 for OK, 1 for syntax error */
3541 #define parse_dollar(as_string, dest, input) \
3542 parse_dollar(dest, input)
3543 #define as_string NULL
3545 static int parse_dollar(o_string *as_string,
3547 struct in_str *input)
3549 int ch = i_peek(input); /* first character after the $ */
3550 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
3552 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3554 ch = i_getch(input);
3555 nommu_addchr(as_string, ch);
3557 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3559 debug_printf_parse(": '%c'\n", ch);
3560 o_addchr(dest, ch | quote_mask);
3563 if (!isalnum(ch) && ch != '_')
3565 ch = i_getch(input);
3566 nommu_addchr(as_string, ch);
3568 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3569 } else if (isdigit(ch)) {
3571 ch = i_getch(input);
3572 nommu_addchr(as_string, ch);
3573 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3574 debug_printf_parse(": '%c'\n", ch);
3575 o_addchr(dest, ch | quote_mask);
3576 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3577 } else switch (ch) {
3579 case '!': /* last bg pid */
3580 case '?': /* last exit code */
3581 case '#': /* number of args */
3582 case '*': /* args */
3583 case '@': /* args */
3584 goto make_one_char_var;
3586 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3588 ch = i_getch(input); /* eat '{' */
3589 nommu_addchr(as_string, ch);
3591 ch = i_getch(input); /* first char after '{' */
3592 nommu_addchr(as_string, ch);
3593 /* It should be ${?}, or ${#var},
3594 * or even ${?+subst} - operator acting on a special variable,
3595 * or the beginning of variable name.
3597 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
3599 syntax_error_unterm_str("${name}");
3600 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3605 /* It's possible to just call add_till_closing_bracket() at this point.
3606 * However, this regresses some of our testsuite cases
3607 * which check invalid constructs like ${%}.
3608 * Oh well... let's check that the var name part is fine... */
3614 debug_printf_parse(": '%c'\n", ch);
3616 ch = i_getch(input);
3617 nommu_addchr(as_string, ch);
3621 if (!isalnum(ch) && ch != '_') {
3623 unsigned char last_ch;
3624 /* handle parameter expansions
3625 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3627 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3628 goto bad_dollar_syntax;
3630 /* Eat everything until closing '}' (or ':') */
3632 if (ENABLE_HUSH_BASH_COMPAT
3634 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3636 /* It's ${var:N[:M]} thing */
3637 end_ch = '}' * 0x100 + ':';
3639 if (ENABLE_HUSH_BASH_COMPAT
3642 /* It's ${var/[/]pattern[/repl]} thing */
3643 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3645 nommu_addchr(as_string, '/');
3648 end_ch = '}' * 0x100 + '/';
3654 #if ENABLE_HUSH_DOLLAR_OPS
3655 last_ch = add_till_closing_bracket(dest, input, end_ch);
3657 #error Simple code to only allow ${var} is not implemented
3660 o_addstr(as_string, dest->data + pos);
3661 o_addchr(as_string, last_ch);
3664 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3665 /* close the first block: */
3666 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3667 /* while parsing N from ${var:N[:M]}
3668 * or pattern from ${var/[/]pattern[/repl]} */
3669 if ((end_ch & 0xff) == last_ch) {
3670 /* got ':' or '/'- parse the rest */
3675 if (end_ch == '}' * 0x100 + ':') {
3676 /* it's ${var:N} - emulate :999999999 */
3677 o_addstr(dest, "999999999");
3678 } /* else: it's ${var/[/]pattern} */
3683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3686 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3690 ch = i_getch(input);
3691 nommu_addchr(as_string, ch);
3692 # if ENABLE_SH_MATH_SUPPORT
3693 if (i_peek(input) == '(') {
3694 ch = i_getch(input);
3695 nommu_addchr(as_string, ch);
3696 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3697 o_addchr(dest, /*quote_mask |*/ '+');
3700 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3702 o_addstr(as_string, dest->data + pos);
3703 o_addchr(as_string, ')');
3704 o_addchr(as_string, ')');
3706 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3710 # if ENABLE_HUSH_TICK
3711 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3712 o_addchr(dest, quote_mask | '`');
3715 add_till_closing_bracket(dest, input, ')');
3717 o_addstr(as_string, dest->data + pos);
3718 o_addchr(as_string, ')');
3720 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3726 ch = i_getch(input);
3727 nommu_addchr(as_string, ch);
3729 if (isalnum(ch)) { /* it's $_name or $_123 */
3734 /* TODO: $_ and $-: */
3735 /* $_ Shell or shell script name; or last argument of last command
3736 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3737 * but in command's env, set to full pathname used to invoke it */
3738 /* $- Option flags set by set builtin or shell options (-i etc) */
3740 o_addQchr(dest, '$');
3742 debug_printf_parse("parse_dollar return 0\n");
3748 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
3749 parse_stream_dquoted(dest, input, dquote_end)
3750 #define as_string NULL
3752 static int parse_stream_dquoted(o_string *as_string,
3754 struct in_str *input,
3761 ch = i_getch(input);
3763 nommu_addchr(as_string, ch);
3764 if (ch == dquote_end) { /* may be only '"' or EOF */
3765 if (dest->o_assignment == NOT_ASSIGNMENT)
3766 dest->o_escape ^= 1;
3767 debug_printf_parse("parse_stream_dquoted return 0\n");
3770 /* note: can't move it above ch == dquote_end check! */
3772 syntax_error_unterm_ch('"');
3773 /*xfunc_die(); - redundant */
3777 next = i_peek(input);
3779 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3780 ch, ch, dest->o_escape);
3783 syntax_error("\\<eof>");
3787 * "The backslash retains its special meaning [in "..."]
3788 * only when followed by one of the following characters:
3789 * $, `, ", \, or <newline>. A double quote may be quoted
3790 * within double quotes by preceding it with a backslash."
3791 * NB: in (unquoted) heredoc, above does not apply to ".
3793 if (next == dquote_end || strchr("$`\\\n", next) != NULL) {
3794 ch = i_getch(input);
3796 o_addqchr(dest, ch);
3797 nommu_addchr(as_string, ch);
3800 o_addqchr(dest, '\\');
3801 nommu_addchr(as_string, '\\');
3806 if (parse_dollar(as_string, dest, input) != 0) {
3807 debug_printf_parse("parse_stream_dquoted return 1: "
3808 "parse_dollar returned non-0\n");
3813 #if ENABLE_HUSH_TICK
3815 //unsigned pos = dest->length;
3816 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3817 o_addchr(dest, 0x80 | '`');
3818 add_till_backquote(dest, input);
3819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3820 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3824 o_addQchr(dest, ch);
3826 && (dest->o_assignment == MAYBE_ASSIGNMENT
3827 || dest->o_assignment == WORD_IS_KEYWORD)
3828 && is_well_formed_var_name(dest->data, '=')
3830 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3837 * Scan input until EOF or end_trigger char.
3838 * Return a list of pipes to execute, or NULL on EOF
3839 * or if end_trigger character is met.
3840 * On syntax error, exit is shell is not interactive,
3841 * reset parsing machinery and start parsing anew,
3842 * or return ERR_PTR.
3844 static struct pipe *parse_stream(char **pstring,
3845 struct in_str *input,
3848 struct parse_context ctx;
3849 o_string dest = NULL_O_STRING;
3853 /* Double-quote state is handled in the state variable is_in_dquote.
3854 * A single-quote triggers a bypass of the main loop until its mate is
3855 * found. When recursing, quote state is passed in via dest->o_escape.
3857 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3858 end_trigger ? end_trigger : 'X');
3861 /* If very first arg is "" or '', dest.data may end up NULL.
3862 * Preventing this: */
3863 o_addchr(&dest, '\0');
3866 G.ifs = get_local_var_value("IFS");
3871 #if ENABLE_HUSH_INTERACTIVE
3872 input->promptmode = 0; /* PS1 */
3874 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3875 initialize_context(&ctx);
3880 const char *is_special;
3884 redir_type redir_style;
3887 /* dest.has_quoted_part = 1; - already is (see below) */
3888 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
3891 /* We reached closing '"' */
3894 ch = i_getch(input);
3895 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3896 ch, ch, dest.o_escape);
3901 syntax_error_unterm_str("here document");
3904 /* end_trigger == '}' case errors out earlier,
3905 * checking only ')' */
3906 if (end_trigger == ')') {
3907 syntax_error_unterm_ch('('); /* exits */
3908 /* goto parse_error; */
3911 if (done_word(&dest, &ctx)) {
3915 done_pipe(&ctx, PIPE_SEQ);
3917 /* If we got nothing... */
3918 /* (this makes bare "&" cmd a no-op.
3919 * bash says: "syntax error near unexpected token '&'") */
3920 if (pi->num_cmds == 0
3921 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3927 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3929 *pstring = ctx.as_string.data;
3931 o_free_unsafe(&ctx.as_string);
3934 debug_printf_parse("parse_stream return %p\n", pi);
3937 nommu_addchr(&ctx.as_string, ch);
3941 next = i_peek(input);
3943 is_special = "{}<>;&|()#'" /* special outside of "str" */
3944 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3945 /* Are { and } special here? */
3946 if (ctx.command->argv /* word [word]{... - non-special */
3947 || dest.length /* word{... - non-special */
3948 || dest.has_quoted_part /* ""{... - non-special */
3949 || (next != ';' /* }; - special */
3950 && next != ')' /* }) - special */
3951 && next != '&' /* }& and }&& ... - special */
3952 && next != '|' /* }|| ... - special */
3953 && !strchr(G.ifs, next) /* {word - non-special */
3956 /* They are not special, skip "{}" */
3959 is_special = strchr(is_special, ch);
3960 is_ifs = strchr(G.ifs, ch);
3962 if (!is_special && !is_ifs) { /* ordinary char */
3964 o_addQchr(&dest, ch);
3965 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3966 || dest.o_assignment == WORD_IS_KEYWORD)
3968 && is_well_formed_var_name(dest.data, '=')
3970 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3976 if (done_word(&dest, &ctx)) {
3980 #if ENABLE_HUSH_CASE
3981 /* "case ... in <newline> word) ..." -
3982 * newlines are ignored (but ';' wouldn't be) */
3983 if (ctx.command->argv == NULL
3984 && ctx.ctx_res_w == RES_MATCH
3989 /* Treat newline as a command separator. */
3990 done_pipe(&ctx, PIPE_SEQ);
3991 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3993 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3998 dest.o_assignment = MAYBE_ASSIGNMENT;
4000 /* note: if (is_ifs) continue;
4001 * will still trigger for us */
4005 /* "cmd}" or "cmd }..." without semicolon or &:
4006 * } is an ordinary char in this case, even inside { cmd; }
4007 * Pathological example: { ""}; } should exec "}" cmd
4010 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4011 || dest.length != 0 /* word} */
4012 || dest.has_quoted_part /* ""} */
4016 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4017 goto skip_end_trigger;
4018 /* else: } does terminate a group */
4021 if (end_trigger && end_trigger == ch
4022 && (ch != ';' || heredoc_cnt == 0)
4023 #if ENABLE_HUSH_CASE
4025 || ctx.ctx_res_w != RES_MATCH
4026 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4031 /* This is technically valid:
4032 * { cat <<HERE; }; echo Ok
4036 * but we don't support this.
4037 * We require heredoc to be in enclosing {}/(),
4040 syntax_error_unterm_str("here document");
4043 if (done_word(&dest, &ctx)) {
4046 done_pipe(&ctx, PIPE_SEQ);
4047 dest.o_assignment = MAYBE_ASSIGNMENT;
4048 /* Do we sit outside of any if's, loops or case's? */
4050 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4054 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4056 *pstring = ctx.as_string.data;
4058 o_free_unsafe(&ctx.as_string);
4061 debug_printf_parse("parse_stream return %p: "
4062 "end_trigger char found\n",
4064 return ctx.list_head;
4071 /* Catch <, > before deciding whether this word is
4072 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4075 redir_fd = redirect_opt_num(&dest);
4076 if (done_word(&dest, &ctx)) {
4079 redir_style = REDIRECT_OVERWRITE;
4081 redir_style = REDIRECT_APPEND;
4082 ch = i_getch(input);
4083 nommu_addchr(&ctx.as_string, ch);
4086 else if (next == '(') {
4087 syntax_error(">(process) not supported");
4091 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4093 continue; /* back to top of while (1) */
4095 redir_fd = redirect_opt_num(&dest);
4096 if (done_word(&dest, &ctx)) {
4099 redir_style = REDIRECT_INPUT;
4101 redir_style = REDIRECT_HEREDOC;
4103 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4104 ch = i_getch(input);
4105 nommu_addchr(&ctx.as_string, ch);
4106 } else if (next == '>') {
4107 redir_style = REDIRECT_IO;
4108 ch = i_getch(input);
4109 nommu_addchr(&ctx.as_string, ch);
4112 else if (next == '(') {
4113 syntax_error("<(process) not supported");
4117 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4119 continue; /* back to top of while (1) */
4122 if (dest.o_assignment == MAYBE_ASSIGNMENT
4123 /* check that we are not in word in "a=1 2>word b=1": */
4124 && !ctx.pending_redirect
4126 /* ch is a special char and thus this word
4127 * cannot be an assignment */
4128 dest.o_assignment = NOT_ASSIGNMENT;
4131 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4135 if (dest.length == 0) {
4138 if (ch == EOF || ch == '\n')
4141 /* note: we do not add it to &ctx.as_string */
4143 nommu_addchr(&ctx.as_string, '\n');
4145 o_addQchr(&dest, ch);
4150 syntax_error("\\<eof>");
4153 ch = i_getch(input);
4155 o_addchr(&dest, '\\');
4156 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4157 o_addchr(&dest, ch);
4158 nommu_addchr(&ctx.as_string, ch);
4159 /* Example: echo Hello \2>file
4160 * we need to know that word 2 is quoted */
4161 dest.has_quoted_part = 1;
4165 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4166 ctx.as_string.data[--ctx.as_string.length] = '\0';
4171 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
4172 debug_printf_parse("parse_stream parse error: "
4173 "parse_dollar returned non-0\n");
4178 dest.has_quoted_part = 1;
4180 ch = i_getch(input);
4182 syntax_error_unterm_ch('\'');
4183 /*xfunc_die(); - redundant */
4185 nommu_addchr(&ctx.as_string, ch);
4188 o_addqchr(&dest, ch);
4192 dest.has_quoted_part = 1;
4193 is_in_dquote ^= 1; /* invert */
4194 if (dest.o_assignment == NOT_ASSIGNMENT)
4197 #if ENABLE_HUSH_TICK
4201 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4202 o_addchr(&dest, '`');
4204 add_till_backquote(&dest, input);
4206 o_addstr(&ctx.as_string, dest.data + pos);
4207 o_addchr(&ctx.as_string, '`');
4209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4210 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4215 #if ENABLE_HUSH_CASE
4218 if (done_word(&dest, &ctx)) {
4221 done_pipe(&ctx, PIPE_SEQ);
4222 #if ENABLE_HUSH_CASE
4223 /* Eat multiple semicolons, detect
4224 * whether it means something special */
4229 ch = i_getch(input);
4230 nommu_addchr(&ctx.as_string, ch);
4231 if (ctx.ctx_res_w == RES_CASE_BODY) {
4232 ctx.ctx_dsemicolon = 1;
4233 ctx.ctx_res_w = RES_MATCH;
4239 /* We just finished a cmd. New one may start
4240 * with an assignment */
4241 dest.o_assignment = MAYBE_ASSIGNMENT;
4244 if (done_word(&dest, &ctx)) {
4248 ch = i_getch(input);
4249 nommu_addchr(&ctx.as_string, ch);
4250 done_pipe(&ctx, PIPE_AND);
4252 done_pipe(&ctx, PIPE_BG);
4256 if (done_word(&dest, &ctx)) {
4259 #if ENABLE_HUSH_CASE
4260 if (ctx.ctx_res_w == RES_MATCH)
4261 break; /* we are in case's "word | word)" */
4263 if (next == '|') { /* || */
4264 ch = i_getch(input);
4265 nommu_addchr(&ctx.as_string, ch);
4266 done_pipe(&ctx, PIPE_OR);
4268 /* we could pick up a file descriptor choice here
4269 * with redirect_opt_num(), but bash doesn't do it.
4270 * "echo foo 2| cat" yields "foo 2". */
4273 o_reset_to_empty_unquoted(&ctx.as_string);
4278 #if ENABLE_HUSH_CASE
4279 /* "case... in [(]word)..." - skip '(' */
4280 if (ctx.ctx_res_w == RES_MATCH
4281 && ctx.command->argv == NULL /* not (word|(... */
4282 && dest.length == 0 /* not word(... */
4283 && dest.has_quoted_part == 0 /* not ""(... */
4289 if (parse_group(&dest, &ctx, input, ch) != 0) {
4294 #if ENABLE_HUSH_CASE
4295 if (ctx.ctx_res_w == RES_MATCH)
4299 /* proper use of this character is caught by end_trigger:
4300 * if we see {, we call parse_group(..., end_trigger='}')
4301 * and it will match } earlier (not here). */
4302 syntax_error_unexpected_ch(ch);
4306 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4312 struct parse_context *pctx;
4313 IF_HAS_KEYWORDS(struct parse_context *p2;)
4315 /* Clean up allocated tree.
4316 * Sample for finding leaks on syntax error recovery path.
4317 * Run it from interactive shell, watch pmap `pidof hush`.
4318 * while if false; then false; fi; do break; fi
4319 * Samples to catch leaks at execution:
4320 * while if (true | {true;}); then echo ok; fi; do break; done
4321 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4325 /* Update pipe/command counts,
4326 * otherwise freeing may miss some */
4327 done_pipe(pctx, PIPE_SEQ);
4328 debug_printf_clean("freeing list %p from ctx %p\n",
4329 pctx->list_head, pctx);
4330 debug_print_tree(pctx->list_head, 0);
4331 free_pipe_list(pctx->list_head);
4332 debug_printf_clean("freed list %p\n", pctx->list_head);
4334 o_free_unsafe(&pctx->as_string);
4336 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4340 IF_HAS_KEYWORDS(pctx = p2;)
4341 } while (HAS_KEYWORDS && pctx);
4342 /* Free text, clear all dest fields */
4344 /* If we are not in top-level parse, we return,
4345 * our caller will propagate error.
4347 if (end_trigger != ';') {
4355 /* Discard cached input, force prompt */
4357 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4363 /*** Execution routines ***/
4365 /* Expansion can recurse, need forward decls: */
4366 static char *expand_string_to_string(const char *str);
4367 static int process_command_subs(o_string *dest, const char *s);
4369 /* expand_strvec_to_strvec() takes a list of strings, expands
4370 * all variable references within and returns a pointer to
4371 * a list of expanded strings, possibly with larger number
4372 * of strings. (Think VAR="a b"; echo $VAR).
4373 * This new list is allocated as a single malloc block.
4374 * NULL-terminated list of char* pointers is at the beginning of it,
4375 * followed by strings themself.
4376 * Caller can deallocate entire list by single free(list). */
4378 /* Store given string, finalizing the word and starting new one whenever
4379 * we encounter IFS char(s). This is used for expanding variable values.
4380 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4381 static int expand_on_ifs(o_string *output, int n, const char *str)
4384 int word_len = strcspn(str, G.ifs);
4386 if (output->o_escape)
4387 o_addqblock(output, str, word_len);
4388 else if (!output->o_glob)
4389 o_addblock(output, str, word_len);
4390 else /* if (!escape && glob) */ {
4391 /* Protect backslashes against globbing up :)
4392 * Example: "v='\*'; echo b$v"
4394 o_addblock_duplicate_backslash(output, str, word_len);
4395 /*/ Why can't we do it easier? */
4396 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4397 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4401 if (!*str) /* EOL - do not finalize word */
4403 o_addchr(output, '\0');
4404 debug_print_list("expand_on_ifs", output, n);
4405 n = o_save_ptr(output, n);
4406 str += strspn(str, G.ifs); /* skip ifs chars */
4408 debug_print_list("expand_on_ifs[1]", output, n);
4412 /* Helper to expand $((...)) and heredoc body. These act as if
4413 * they are in double quotes, with the exception that they are not :).
4414 * Just the rules are similar: "expand only $var and `cmd`"
4416 * Returns malloced string.
4417 * As an optimization, we return NULL if expansion is not needed.
4419 static char *expand_pseudo_dquoted(const char *str)
4422 struct in_str input;
4423 o_string dest = NULL_O_STRING;
4425 if (!strchr(str, '$')
4426 && !strchr(str, '\\')
4427 #if ENABLE_HUSH_TICK
4428 && !strchr(str, '`')
4434 /* We need to expand. Example:
4435 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4437 setup_string_in_str(&input, str);
4438 parse_stream_dquoted(NULL, &dest, &input, EOF);
4439 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4440 exp_str = expand_string_to_string(dest.data);
4441 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4442 o_free_unsafe(&dest);
4446 #if ENABLE_SH_MATH_SUPPORT
4447 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4449 arith_eval_hooks_t hooks;
4453 hooks.lookupvar = get_local_var_value;
4454 hooks.setvar = set_local_var_from_halves;
4455 hooks.endofname = endofname;
4456 exp_str = expand_pseudo_dquoted(arg);
4457 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4463 #if ENABLE_HUSH_BASH_COMPAT
4464 /* ${var/[/]pattern[/repl]} helpers */
4465 static char *strstr_pattern(char *val, const char *pattern, int *size)
4468 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4469 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4476 /* Optimization: if "*pat" did not match the start of "string",
4477 * we know that "tring", "ring" etc will not match too:
4479 if (pattern[0] == '*')
4484 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4486 char *result = NULL;
4487 unsigned res_len = 0;
4488 unsigned repl_len = strlen(repl);
4492 char *s = strstr_pattern(val, pattern, &size);
4496 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4497 memcpy(result + res_len, val, s - val);
4499 strcpy(result + res_len, repl);
4500 res_len += repl_len;
4501 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4507 if (val[0] && result) {
4508 result = xrealloc(result, res_len + strlen(val) + 1);
4509 strcpy(result + res_len, val);
4510 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4512 debug_printf_varexp("result:'%s'\n", result);
4518 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4520 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4522 const char *val = NULL;
4523 char *to_be_freed = NULL;
4528 char exp_save = exp_save; /* for compiler */
4529 char *exp_saveptr; /* points to expansion operator */
4530 char *exp_word = exp_word; /* for compiler */
4534 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4535 first_char = arg[0] = first_ch & 0x7f;
4538 if (first_char == '#' && arg[1] && !exp_saveptr) {
4539 /* handle length expansion ${#var} */
4543 /* maybe handle parameter expansion */
4544 if (exp_saveptr /* if 2nd char is one of expansion operators */
4545 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4547 /* ${?:0}, ${#[:]%0} etc */
4548 exp_saveptr = var + 1;
4550 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4551 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4553 exp_op = exp_save = *exp_saveptr;
4555 exp_word = exp_saveptr + 1;
4556 if (exp_op == ':') {
4557 exp_op = *exp_word++;
4558 if (ENABLE_HUSH_BASH_COMPAT
4559 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4561 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4566 *exp_saveptr = '\0';
4567 } /* else: it's not an expansion op, but bare ${var} */
4570 /* lookup the variable in question */
4571 if (isdigit(var[0])) {
4572 /* parse_dollar() should have vetted var for us */
4573 int n = xatoi_positive(var);
4574 if (n < G.global_argc)
4575 val = G.global_argv[n];
4576 /* else val remains NULL: $N with too big N */
4580 val = utoa(G.root_pid);
4582 case '!': /* bg pid */
4583 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4585 case '?': /* exitcode */
4586 val = utoa(G.last_exitcode);
4588 case '#': /* argc */
4589 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4592 val = get_local_var_value(var);
4596 /* Handle any expansions */
4597 if (exp_op == 'L') {
4598 debug_printf_expand("expand: length(%s)=", val);
4599 val = utoa(val ? strlen(val) : 0);
4600 debug_printf_expand("%s\n", val);
4601 } else if (exp_op) {
4602 if (exp_op == '%' || exp_op == '#') {
4603 /* Standard-mandated substring removal ops:
4604 * ${parameter%word} - remove smallest suffix pattern
4605 * ${parameter%%word} - remove largest suffix pattern
4606 * ${parameter#word} - remove smallest prefix pattern
4607 * ${parameter##word} - remove largest prefix pattern
4609 * Word is expanded to produce a glob pattern.
4610 * Then var's value is matched to it and matching part removed.
4612 if (val && val[0]) {
4615 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4616 if (exp_op == *exp_word) /* ## or %% */
4618 //TODO: avoid xstrdup unless needed
4619 // (see HACK ALERT below for an example)
4620 val = to_be_freed = xstrdup(val);
4621 //TODO: fix expansion rules:
4622 exp_exp_word = expand_pseudo_dquoted(exp_word);
4624 exp_word = exp_exp_word;
4625 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4626 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4627 // exp_op, to_be_freed, exp_word, loc);
4629 if (loc) { /* match was found */
4630 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4637 #if ENABLE_HUSH_BASH_COMPAT
4638 else if (exp_op == '/' || exp_op == '\\') {
4639 /* It's ${var/[/]pattern[/repl]} thing.
4640 * Note that in encoded form it has TWO parts:
4641 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4643 /* Empty variable always gives nothing: */
4644 // "v=''; echo ${v/*/w}" prints "", not "w"
4645 if (val && val[0]) {
4646 /* It's ${var/[/]pattern[/repl]} thing */
4648 * Pattern is taken literally, while
4649 * repl should be de-backslased and globbed
4650 * by the usual expansion rules:
4652 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4653 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4654 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4655 * v='a bz'; echo ${v/a*z/\z} prints "z"
4656 * (note that a*z _pattern_ is never globbed!)
4658 //TODO: fix expansion rules:
4659 char *pattern, *repl, *t;
4660 pattern = expand_pseudo_dquoted(exp_word);
4662 pattern = xstrdup(exp_word);
4663 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4664 *p++ = SPECIAL_VAR_SYMBOL;
4666 p = strchr(p, SPECIAL_VAR_SYMBOL);
4668 repl = expand_pseudo_dquoted(exp_word);
4669 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4670 /* HACK ALERT. We depend here on the fact that
4671 * G.global_argv and results of utoa and get_local_var_value
4672 * are actually in writable memory:
4673 * replace_pattern momentarily stores NULs there. */
4675 to_be_freed = replace_pattern(t,
4677 (repl ? repl : exp_word),
4679 if (to_be_freed) /* at least one replace happened */
4686 else if (exp_op == ':') {
4687 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4688 /* It's ${var:N[:M]} bashism.
4689 * Note that in encoded form it has TWO parts:
4690 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4695 beg = expand_and_evaluate_arith(exp_word, &errcode);
4696 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4697 *p++ = SPECIAL_VAR_SYMBOL;
4699 p = strchr(p, SPECIAL_VAR_SYMBOL);
4701 len = expand_and_evaluate_arith(exp_word, &errcode);
4702 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4704 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4705 if (beg < 0) /* bash compat */
4707 debug_printf_varexp("from val:'%s'\n", val);
4708 if (len == 0 || !val || beg >= strlen(val))
4711 /* Paranoia. What if user entered 9999999999999
4712 * which fits in arith_t but not int? */
4715 val = to_be_freed = xstrndup(val + beg, len);
4717 debug_printf_varexp("val:'%s'\n", val);
4721 die_if_script("malformed ${%s:...}", var);
4724 } else { /* one of "-=+?" */
4725 /* Standard-mandated substitution ops:
4726 * ${var?word} - indicate error if unset
4727 * If var is unset, word (or a message indicating it is unset
4728 * if word is null) is written to standard error
4729 * and the shell exits with a non-zero exit status.
4730 * Otherwise, the value of var is substituted.
4731 * ${var-word} - use default value
4732 * If var is unset, word is substituted.
4733 * ${var=word} - assign and use default value
4734 * If var is unset, word is assigned to var.
4735 * In all cases, final value of var is substituted.
4736 * ${var+word} - use alternative value
4737 * If var is unset, null is substituted.
4738 * Otherwise, word is substituted.
4740 * Word is subjected to tilde expansion, parameter expansion,
4741 * command substitution, and arithmetic expansion.
4742 * If word is not needed, it is not expanded.
4744 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4745 * but also treat null var as if it is unset.
4747 int use_word = (!val || ((exp_save == ':') && !val[0]));
4749 use_word = !use_word;
4750 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4751 (exp_save == ':') ? "true" : "false", use_word);
4753 to_be_freed = expand_pseudo_dquoted(exp_word);
4755 exp_word = to_be_freed;
4756 if (exp_op == '?') {
4757 /* mimic bash message */
4758 die_if_script("%s: %s",
4760 exp_word[0] ? exp_word : "parameter null or not set"
4762 //TODO: how interactive bash aborts expansion mid-command?
4767 if (exp_op == '=') {
4768 /* ${var=[word]} or ${var:=[word]} */
4769 if (isdigit(var[0]) || var[0] == '#') {
4770 /* mimic bash message */
4771 die_if_script("$%s: cannot assign in this way", var);
4774 char *new_var = xasprintf("%s=%s", var, val);
4775 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4779 } /* one of "-=+?" */
4781 *exp_saveptr = exp_save;
4787 *to_be_freed_pp = to_be_freed;
4791 /* Expand all variable references in given string, adding words to list[]
4792 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4793 * to be filled). This routine is extremely tricky: has to deal with
4794 * variables/parameters with whitespace, $* and $@, and constructs like
4795 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4796 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4798 /* or_mask is either 0 (normal case) or 0x80 -
4799 * expansion of right-hand side of assignment == 1-element expand.
4800 * It will also do no globbing, and thus we must not backslash-quote!
4807 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4808 debug_print_list("expand_vars_to_list", output, n);
4809 n = o_save_ptr(output, n);
4810 debug_print_list("expand_vars_to_list[0]", output, n);
4812 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4814 char *to_be_freed = NULL;
4815 const char *val = NULL;
4816 #if ENABLE_HUSH_TICK
4817 o_string subst_result = NULL_O_STRING;
4819 #if ENABLE_SH_MATH_SUPPORT
4820 char arith_buf[sizeof(arith_t)*3 + 2];
4822 o_addblock(output, arg, p - arg);
4823 debug_print_list("expand_vars_to_list[1]", output, n);
4825 p = strchr(p, SPECIAL_VAR_SYMBOL);
4827 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4828 /* "$@" is special. Even if quoted, it can still
4829 * expand to nothing (not even an empty string) */
4830 if ((first_ch & 0x7f) != '@')
4831 ored_ch |= first_ch;
4833 switch (first_ch & 0x7f) {
4834 /* Highest bit in first_ch indicates that var is double-quoted */
4838 if (!G.global_argv[1])
4841 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4842 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4843 smallint sv = output->o_escape;
4844 /* unquoted var's contents should be globbed, so don't escape */
4845 output->o_escape = 0;
4846 while (G.global_argv[i]) {
4847 n = expand_on_ifs(output, n, G.global_argv[i]);
4848 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4849 if (G.global_argv[i++][0] && G.global_argv[i]) {
4850 /* this argv[] is not empty and not last:
4851 * put terminating NUL, start new word */
4852 o_addchr(output, '\0');
4853 debug_print_list("expand_vars_to_list[2]", output, n);
4854 n = o_save_ptr(output, n);
4855 debug_print_list("expand_vars_to_list[3]", output, n);
4858 output->o_escape = sv;
4860 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4861 * and in this case should treat it like '$*' - see 'else...' below */
4862 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4864 o_addQstr(output, G.global_argv[i]);
4865 if (++i >= G.global_argc)
4867 o_addchr(output, '\0');
4868 debug_print_list("expand_vars_to_list[4]", output, n);
4869 n = o_save_ptr(output, n);
4871 } else { /* quoted $*: add as one word */
4873 o_addQstr(output, G.global_argv[i]);
4874 if (!G.global_argv[++i])
4877 o_addchr(output, G.ifs[0]);
4882 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4883 /* "Empty variable", used to make "" etc to not disappear */
4887 #if ENABLE_HUSH_TICK
4888 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4891 /* Can't just stuff it into output o_string,
4892 * expanded result may need to be globbed
4893 * and $IFS-splitted */
4894 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4895 G.last_exitcode = process_command_subs(&subst_result, arg);
4896 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4897 val = subst_result.data;
4900 #if ENABLE_SH_MATH_SUPPORT
4901 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4905 arg++; /* skip '+' */
4906 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4907 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4908 res = expand_and_evaluate_arith(arg, &errcode);
4911 const char *msg = "error in arithmetic";
4914 msg = "exponent less than 0";
4917 msg = "divide by 0";
4920 msg = "expression recursion loop detected";
4925 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4926 sprintf(arith_buf, arith_t_fmt, res);
4932 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4933 IF_HUSH_TICK(store_val:)
4934 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4935 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4936 if (val && val[0]) {
4937 /* unquoted var's contents should be globbed, so don't escape */
4938 smallint sv = output->o_escape;
4939 output->o_escape = 0;
4940 n = expand_on_ifs(output, n, val);
4942 output->o_escape = sv;
4944 } else { /* quoted $VAR, val will be appended below */
4945 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4949 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4951 if (val && val[0]) {
4952 o_addQstr(output, val);
4955 /* Do the check to avoid writing to a const string */
4956 if (*p != SPECIAL_VAR_SYMBOL)
4957 *p = SPECIAL_VAR_SYMBOL;
4959 #if ENABLE_HUSH_TICK
4960 o_free(&subst_result);
4963 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4966 debug_print_list("expand_vars_to_list[a]", output, n);
4967 /* this part is literal, and it was already pre-quoted
4968 * if needed (much earlier), do not use o_addQstr here! */
4969 o_addstr_with_NUL(output, arg);
4970 debug_print_list("expand_vars_to_list[b]", output, n);
4971 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4972 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4975 /* allow to reuse list[n] later without re-growth */
4976 output->has_empty_slot = 1;
4978 o_addchr(output, '\0');
4985 EXPVAR_FLAG_GLOB = 0x200,
4986 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4987 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4989 static char **expand_variables(char **argv, unsigned or_mask)
4994 o_string output = NULL_O_STRING;
4996 /* protect against globbing for "$var"? */
4997 /* (unquoted $var will temporarily switch it off) */
4998 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4999 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
5004 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
5007 debug_print_list("expand_variables", &output, n);
5009 /* output.data (malloced in one block) gets returned in "list" */
5010 list = o_finalize_list(&output, n);
5011 debug_print_strings("expand_variables[1]", list);
5015 static char **expand_strvec_to_strvec(char **argv)
5017 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
5020 #if ENABLE_HUSH_BASH_COMPAT
5021 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5023 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5027 /* Used for expansion of right hand of assignments */
5028 /* NB: should NOT do globbing!
5029 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5030 static char *expand_string_to_string(const char *str)
5032 char *argv[2], **list;
5034 /* This is generally an optimization, but it also
5035 * handles "", which otherwise trips over !list[0] check below.
5036 * (is this ever happens that we actually get str="" here?)
5038 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5039 //TODO: Can use on strings with \ too, just unbackslash() them?
5040 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5041 return xstrdup(str);
5044 argv[0] = (char*)str;
5046 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5048 if (!list[0] || list[1])
5049 bb_error_msg_and_die("BUG in varexp2");
5050 /* actually, just move string 2*sizeof(char*) bytes back */
5051 overlapping_strcpy((char*)list, list[0]);
5052 unbackslash((char*)list);
5053 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5057 /* Used for "eval" builtin */
5058 static char* expand_strvec_to_string(char **argv)
5062 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5063 /* Convert all NULs to spaces */
5068 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5069 bb_error_msg_and_die("BUG in varexp3");
5070 /* bash uses ' ' regardless of $IFS contents */
5075 overlapping_strcpy((char*)list, list[0]);
5076 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5080 static char **expand_assignments(char **argv, int count)
5085 G.expanded_assignments = p = NULL;
5086 /* Expand assignments into one string each */
5087 for (i = 0; i < count; i++) {
5088 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5090 G.expanded_assignments = NULL;
5097 void re_execute_shell(char ***to_free, const char *s,
5098 char *g_argv0, char **g_argv,
5099 char **builtin_argv) NORETURN;
5101 static void reset_traps_to_defaults(void)
5103 /* This function is always called in a child shell
5104 * after fork (not vfork, NOMMU doesn't use this function).
5109 /* Child shells are not interactive.
5110 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5111 * Testcase: (while :; do :; done) + ^Z should background.
5112 * Same goes for SIGTERM, SIGHUP, SIGINT.
5114 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5115 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5117 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5118 * Stupid. It can be done with *single* &= op, but we can't use
5119 * the fact that G.blocked_set is implemented as a bitmask
5121 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5125 /* Careful. Only if no trap or trap is not "" */
5126 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5127 sigdelset(&G.blocked_set, sig);
5134 /* Our homegrown sig mask is saner to work with :) */
5135 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5137 /* Resetting all traps to default except empty ones */
5138 mask = G.non_DFL_mask;
5139 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5140 if (!G.traps[sig] || !G.traps[sig][0])
5143 G.traps[sig] = NULL;
5144 /* There is no signal for 0 (EXIT) */
5147 /* There was a trap handler, we just removed it.
5148 * But if sig still has non-DFL handling,
5149 * we should not unblock the sig. */
5152 sigdelset(&G.blocked_set, sig);
5154 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5159 static void re_execute_shell(char ***to_free, const char *s,
5160 char *g_argv0, char **g_argv,
5161 char **builtin_argv) NORETURN;
5162 static void re_execute_shell(char ***to_free, const char *s,
5163 char *g_argv0, char **g_argv,
5164 char **builtin_argv)
5166 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5167 /* delims + 2 * (number of bytes in printed hex numbers) */
5168 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5169 char *heredoc_argv[4];
5170 struct variable *cur;
5171 # if ENABLE_HUSH_FUNCTIONS
5172 struct function *funcp;
5176 unsigned long long empty_trap_mask;
5178 if (!g_argv0) { /* heredoc */
5179 argv = heredoc_argv;
5180 argv[0] = (char *) G.argv0_for_re_execing;
5181 argv[1] = (char *) "-<";
5182 argv[2] = (char *) s;
5184 pp = &argv[3]; /* used as pointer to empty environment */
5190 if (pp) while (*pp++)
5193 empty_trap_mask = 0;
5196 for (sig = 1; sig < NSIG; sig++) {
5197 if (G.traps[sig] && !G.traps[sig][0])
5198 empty_trap_mask |= 1LL << sig;
5202 sprintf(param_buf, NOMMU_HACK_FMT
5203 , (unsigned) G.root_pid
5204 , (unsigned) G.root_ppid
5205 , (unsigned) G.last_bg_pid
5206 , (unsigned) G.last_exitcode
5209 IF_HUSH_LOOPS(, G.depth_of_loop)
5211 # undef NOMMU_HACK_FMT
5212 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5213 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5216 for (cur = G.top_var; cur; cur = cur->next) {
5217 if (!cur->flg_export || cur->flg_read_only)
5220 # if ENABLE_HUSH_FUNCTIONS
5221 for (funcp = G.top_func; funcp; funcp = funcp->next)
5227 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5228 *pp++ = (char *) G.argv0_for_re_execing;
5230 for (cur = G.top_var; cur; cur = cur->next) {
5231 if (strcmp(cur->varstr, hush_version_str) == 0)
5233 if (cur->flg_read_only) {
5234 *pp++ = (char *) "-R";
5235 *pp++ = cur->varstr;
5236 } else if (!cur->flg_export) {
5237 *pp++ = (char *) "-V";
5238 *pp++ = cur->varstr;
5241 # if ENABLE_HUSH_FUNCTIONS
5242 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5243 *pp++ = (char *) "-F";
5244 *pp++ = funcp->name;
5245 *pp++ = funcp->body_as_string;
5248 /* We can pass activated traps here. Say, -Tnn:trap_string
5250 * However, POSIX says that subshells reset signals with traps
5252 * I tested bash-3.2 and it not only does that with true subshells
5253 * of the form ( list ), but with any forked children shells.
5254 * I set trap "echo W" WINCH; and then tried:
5256 * { echo 1; sleep 20; echo 2; } &
5257 * while true; do echo 1; sleep 20; echo 2; break; done &
5258 * true | { echo 1; sleep 20; echo 2; } | cat
5260 * In all these cases sending SIGWINCH to the child shell
5261 * did not run the trap. If I add trap "echo V" WINCH;
5262 * _inside_ group (just before echo 1), it works.
5264 * I conclude it means we don't need to pass active traps here.
5265 * Even if we would use signal handlers instead of signal masking
5266 * in order to implement trap handling,
5267 * exec syscall below resets signals to SIG_DFL for us.
5269 *pp++ = (char *) "-c";
5272 while (*++builtin_argv)
5273 *pp++ = *builtin_argv;
5274 *pp++ = (char *) "";
5279 /* *pp = NULL; - is already there */
5283 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5284 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5285 execve(bb_busybox_exec_path, argv, pp);
5286 /* Fallback. Useful for init=/bin/hush usage etc */
5287 if (argv[0][0] == '/')
5288 execve(argv[0], argv, pp);
5289 xfunc_error_retval = 127;
5290 bb_error_msg_and_die("can't re-execute the shell");
5292 #endif /* !BB_MMU */
5295 static int run_and_free_list(struct pipe *pi);
5297 /* Executing from string: eval, sh -c '...'
5298 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5299 * end_trigger controls how often we stop parsing
5300 * NUL: parse all, execute, return
5301 * ';': parse till ';' or newline, execute, repeat till EOF
5303 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5305 /* Why we need empty flag?
5306 * An obscure corner case "false; ``; echo $?":
5307 * empty command in `` should still set $? to 0.
5308 * But we can't just set $? to 0 at the start,
5309 * this breaks "false; echo `echo $?`" case.
5313 struct pipe *pipe_list;
5315 pipe_list = parse_stream(NULL, inp, end_trigger);
5316 if (!pipe_list) { /* EOF */
5318 G.last_exitcode = 0;
5321 debug_print_tree(pipe_list, 0);
5322 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5323 run_and_free_list(pipe_list);
5328 static void parse_and_run_string(const char *s)
5330 struct in_str input;
5331 setup_string_in_str(&input, s);
5332 parse_and_run_stream(&input, '\0');
5335 static void parse_and_run_file(FILE *f)
5337 struct in_str input;
5338 setup_file_in_str(&input, f);
5339 parse_and_run_stream(&input, ';');
5342 #if ENABLE_HUSH_TICK
5343 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5348 char **to_free = NULL;
5352 pid = BB_MMU ? xfork() : xvfork();
5353 if (pid == 0) { /* child */
5354 disable_restore_tty_pgrp_on_exit();
5355 /* Process substitution is not considered to be usual
5356 * 'command execution'.
5357 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5364 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5365 close(channel[0]); /* NB: close _first_, then move fd! */
5366 xmove_fd(channel[1], 1);
5367 /* Prevent it from trying to handle ctrl-z etc */
5368 IF_HUSH_JOB(G.run_list_level = 1;)
5369 /* Awful hack for `trap` or $(trap).
5371 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5372 * contains an example where "trap" is executed in a subshell:
5374 * save_traps=$(trap)
5376 * eval "$save_traps"
5378 * Standard does not say that "trap" in subshell shall print
5379 * parent shell's traps. It only says that its output
5380 * must have suitable form, but then, in the above example
5381 * (which is not supposed to be normative), it implies that.
5383 * bash (and probably other shell) does implement it
5384 * (traps are reset to defaults, but "trap" still shows them),
5385 * but as a result, "trap" logic is hopelessly messed up:
5388 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5389 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5390 * # true | trap <--- trap is in subshell - no output (ditto)
5391 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5392 * trap -- 'echo Ho' SIGWINCH
5393 * # echo `(trap)` <--- in subshell in subshell - output
5394 * trap -- 'echo Ho' SIGWINCH
5395 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5396 * trap -- 'echo Ho' SIGWINCH
5398 * The rules when to forget and when to not forget traps
5399 * get really complex and nonsensical.
5401 * Our solution: ONLY bare $(trap) or `trap` is special.
5403 s = skip_whitespace(s);
5404 if (strncmp(s, "trap", 4) == 0
5405 && skip_whitespace(s + 4)[0] == '\0'
5407 static const char *const argv[] = { NULL, NULL };
5408 builtin_trap((char**)argv);
5409 exit(0); /* not _exit() - we need to fflush */
5412 reset_traps_to_defaults();
5413 parse_and_run_string(s);
5414 _exit(G.last_exitcode);
5416 /* We re-execute after vfork on NOMMU. This makes this script safe:
5417 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5418 * huge=`cat BIG` # was blocking here forever
5421 re_execute_shell(&to_free,
5431 # if ENABLE_HUSH_FAST
5433 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5434 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5435 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5437 enable_restore_tty_pgrp_on_exit();
5442 close_on_exec_on(channel[0]);
5443 return xfdopen_for_read(channel[0]);
5446 /* Return code is exit status of the process that is run. */
5447 static int process_command_subs(o_string *dest, const char *s)
5450 struct in_str pipe_str;
5452 int status, ch, eol_cnt;
5454 fp = generate_stream_from_string(s, &pid);
5456 /* Now send results of command back into original context */
5457 setup_file_in_str(&pipe_str, fp);
5459 while ((ch = i_getch(&pipe_str)) != EOF) {
5465 o_addchr(dest, '\n');
5468 o_addQchr(dest, ch);
5471 debug_printf("done reading from `cmd` pipe, closing it\n");
5473 /* We need to extract exitcode. Test case
5474 * "true; echo `sleep 1; false` $?"
5476 safe_waitpid(pid, &status, 0);
5477 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5478 return WEXITSTATUS(status);
5480 #endif /* ENABLE_HUSH_TICK */
5483 static void setup_heredoc(struct redir_struct *redir)
5485 struct fd_pair pair;
5488 /* the _body_ of heredoc (misleading field name) */
5489 const char *heredoc = redir->rd_filename;
5496 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5497 expanded = expand_pseudo_dquoted(heredoc);
5501 len = strlen(heredoc);
5503 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5505 xmove_fd(pair.rd, redir->rd_fd);
5507 /* Try writing without forking. Newer kernels have
5508 * dynamically growing pipes. Must use non-blocking write! */
5511 written = write(pair.wr, heredoc, len);
5522 ndelay_off(pair.wr);
5524 /* Okay, pipe buffer was not big enough */
5525 /* Note: we must not create a stray child (bastard? :)
5526 * for the unsuspecting parent process. Child creates a grandchild
5527 * and exits before parent execs the process which consumes heredoc
5528 * (that exec happens after we return from this function) */
5535 disable_restore_tty_pgrp_on_exit();
5536 pid = BB_MMU ? xfork() : xvfork();
5540 close(redir->rd_fd); /* read side of the pipe */
5542 full_write(pair.wr, heredoc, len); /* may loop or block */
5545 /* Delegate blocking writes to another process */
5546 xmove_fd(pair.wr, STDOUT_FILENO);
5547 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5551 #if ENABLE_HUSH_FAST
5553 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5555 enable_restore_tty_pgrp_on_exit();
5561 wait(NULL); /* wait till child has died */
5564 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5565 * and stderr if they are redirected. */
5566 static int setup_redirects(struct command *prog, int squirrel[])
5569 struct redir_struct *redir;
5571 for (redir = prog->redirects; redir; redir = redir->next) {
5572 if (redir->rd_type == REDIRECT_HEREDOC2) {
5573 /* rd_fd<<HERE case */
5574 if (squirrel && redir->rd_fd < 3
5575 && squirrel[redir->rd_fd] < 0
5577 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5579 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5581 debug_printf_parse("set heredoc '%s'\n",
5582 redir->rd_filename);
5583 setup_heredoc(redir);
5587 if (redir->rd_dup == REDIRFD_TO_FILE) {
5588 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5590 if (redir->rd_filename == NULL) {
5591 /* Something went wrong in the parse.
5592 * Pretend it didn't happen */
5593 bb_error_msg("bug in redirect parse");
5596 mode = redir_table[redir->rd_type].mode;
5597 p = expand_string_to_string(redir->rd_filename);
5598 openfd = open_or_warn(p, mode);
5601 /* this could get lost if stderr has been redirected, but
5602 * bash and ash both lose it as well (though zsh doesn't!) */
5603 //what the above comment tries to say?
5607 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5608 openfd = redir->rd_dup;
5611 if (openfd != redir->rd_fd) {
5612 if (squirrel && redir->rd_fd < 3
5613 && squirrel[redir->rd_fd] < 0
5615 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5617 if (openfd == REDIRFD_CLOSE) {
5618 /* "n>-" means "close me" */
5619 close(redir->rd_fd);
5621 xdup2(openfd, redir->rd_fd);
5622 if (redir->rd_dup == REDIRFD_TO_FILE)
5630 static void restore_redirects(int squirrel[])
5633 for (i = 0; i < 3; i++) {
5636 /* We simply die on error */
5642 static char *find_in_path(const char *arg)
5645 const char *PATH = get_local_var_value("PATH");
5651 const char *end = strchrnul(PATH, ':');
5652 int sz = end - PATH; /* must be int! */
5656 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5658 /* We have xxx::yyyy in $PATH,
5659 * it means "use current dir" */
5662 if (access(ret, F_OK) == 0)
5675 static const struct built_in_command* find_builtin_helper(const char *name,
5676 const struct built_in_command *x,
5677 const struct built_in_command *end)
5680 if (strcmp(name, x->b_cmd) != 0) {
5684 debug_printf_exec("found builtin '%s'\n", name);
5689 static const struct built_in_command* find_builtin1(const char *name)
5691 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5693 static const struct built_in_command* find_builtin(const char *name)
5695 const struct built_in_command *x = find_builtin1(name);
5698 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5701 #if ENABLE_HUSH_FUNCTIONS
5702 static struct function **find_function_slot(const char *name)
5704 struct function **funcpp = &G.top_func;
5706 if (strcmp(name, (*funcpp)->name) == 0) {
5709 funcpp = &(*funcpp)->next;
5714 static const struct function *find_function(const char *name)
5716 const struct function *funcp = *find_function_slot(name);
5718 debug_printf_exec("found function '%s'\n", name);
5722 /* Note: takes ownership on name ptr */
5723 static struct function *new_function(char *name)
5725 struct function **funcpp = find_function_slot(name);
5726 struct function *funcp = *funcpp;
5728 if (funcp != NULL) {
5729 struct command *cmd = funcp->parent_cmd;
5730 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5732 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5734 /* Note: if !funcp->body, do not free body_as_string!
5735 * This is a special case of "-F name body" function:
5736 * body_as_string was not malloced! */
5738 free_pipe_list(funcp->body);
5740 free(funcp->body_as_string);
5744 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5745 cmd->argv[0] = funcp->name;
5746 cmd->group = funcp->body;
5748 cmd->group_as_string = funcp->body_as_string;
5752 debug_printf_exec("remembering new function '%s'\n", name);
5753 funcp = *funcpp = xzalloc(sizeof(*funcp));
5754 /*funcp->next = NULL;*/
5761 static void unset_func(const char *name)
5763 struct function **funcpp = find_function_slot(name);
5764 struct function *funcp = *funcpp;
5766 if (funcp != NULL) {
5767 debug_printf_exec("freeing function '%s'\n", funcp->name);
5768 *funcpp = funcp->next;
5769 /* funcp is unlinked now, deleting it.
5770 * Note: if !funcp->body, the function was created by
5771 * "-F name body", do not free ->body_as_string
5772 * and ->name as they were not malloced. */
5774 free_pipe_list(funcp->body);
5777 free(funcp->body_as_string);
5785 #define exec_function(to_free, funcp, argv) \
5786 exec_function(funcp, argv)
5788 static void exec_function(char ***to_free,
5789 const struct function *funcp,
5790 char **argv) NORETURN;
5791 static void exec_function(char ***to_free,
5792 const struct function *funcp,
5798 argv[0] = G.global_argv[0];
5799 G.global_argv = argv;
5803 /* On MMU, funcp->body is always non-NULL */
5804 n = run_list(funcp->body);
5808 re_execute_shell(to_free,
5809 funcp->body_as_string,
5816 static int run_function(const struct function *funcp, char **argv)
5822 save_and_replace_G_args(&sv, argv);
5824 /* "we are in function, ok to use return" */
5825 sv_flg = G.flag_return_in_progress;
5826 G.flag_return_in_progress = -1;
5827 # if ENABLE_HUSH_LOCAL
5828 G.func_nest_level++;
5831 /* On MMU, funcp->body is always non-NULL */
5834 /* Function defined by -F */
5835 parse_and_run_string(funcp->body_as_string);
5836 rc = G.last_exitcode;
5840 rc = run_list(funcp->body);
5843 # if ENABLE_HUSH_LOCAL
5845 struct variable *var;
5846 struct variable **var_pp;
5848 var_pp = &G.top_var;
5849 while ((var = *var_pp) != NULL) {
5850 if (var->func_nest_level < G.func_nest_level) {
5851 var_pp = &var->next;
5855 if (var->flg_export)
5856 bb_unsetenv(var->varstr);
5857 /* Remove from global list */
5858 *var_pp = var->next;
5864 G.func_nest_level--;
5867 G.flag_return_in_progress = sv_flg;
5869 restore_G_args(&sv, argv);
5873 #endif /* ENABLE_HUSH_FUNCTIONS */
5877 #define exec_builtin(to_free, x, argv) \
5878 exec_builtin(x, argv)
5880 #define exec_builtin(to_free, x, argv) \
5881 exec_builtin(to_free, argv)
5883 static void exec_builtin(char ***to_free,
5884 const struct built_in_command *x,
5885 char **argv) NORETURN;
5886 static void exec_builtin(char ***to_free,
5887 const struct built_in_command *x,
5891 int rcode = x->b_function(argv);
5895 /* On NOMMU, we must never block!
5896 * Example: { sleep 99 | read line; } & echo Ok
5898 re_execute_shell(to_free,
5907 static void execvp_or_die(char **argv) NORETURN;
5908 static void execvp_or_die(char **argv)
5910 debug_printf_exec("execing '%s'\n", argv[0]);
5911 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5912 execvp(argv[0], argv);
5913 bb_perror_msg("can't execute '%s'", argv[0]);
5914 _exit(127); /* bash compat */
5917 #if ENABLE_HUSH_MODE_X
5918 static void dump_cmd_in_x_mode(char **argv)
5920 if (G_x_mode && argv) {
5921 /* We want to output the line in one write op */
5929 len += strlen(argv[n++]) + 1;
5935 p += sprintf(p, " %s", argv[n++]);
5943 # define dump_cmd_in_x_mode(argv) ((void)0)
5947 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5948 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5949 #define pseudo_exec(nommu_save, command, argv_expanded) \
5950 pseudo_exec(command, argv_expanded)
5953 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5955 * Don't exit() here. If you don't exec, use _exit instead.
5956 * The at_exit handlers apparently confuse the calling process,
5957 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5958 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5959 char **argv, int assignment_cnt,
5960 char **argv_expanded) NORETURN;
5961 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5962 char **argv, int assignment_cnt,
5963 char **argv_expanded)
5967 new_env = expand_assignments(argv, assignment_cnt);
5968 dump_cmd_in_x_mode(new_env);
5970 if (!argv[assignment_cnt]) {
5971 /* Case when we are here: ... | var=val | ...
5972 * (note that we do not exit early, i.e., do not optimize out
5973 * expand_assignments(): think about ... | var=`sleep 1` | ...
5975 free_strings(new_env);
5976 _exit(EXIT_SUCCESS);
5980 set_vars_and_save_old(new_env);
5981 free(new_env); /* optional */
5982 /* we can also destroy set_vars_and_save_old's return value,
5985 nommu_save->new_env = new_env;
5986 nommu_save->old_vars = set_vars_and_save_old(new_env);
5989 if (argv_expanded) {
5990 argv = argv_expanded;
5992 argv = expand_strvec_to_strvec(argv + assignment_cnt);
5994 nommu_save->argv = argv;
5997 dump_cmd_in_x_mode(argv);
5999 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6000 if (strchr(argv[0], '/') != NULL)
6004 /* Check if the command matches any of the builtins.
6005 * Depending on context, this might be redundant. But it's
6006 * easier to waste a few CPU cycles than it is to figure out
6007 * if this is one of those cases.
6010 /* On NOMMU, it is more expensive to re-execute shell
6011 * just in order to run echo or test builtin.
6012 * It's better to skip it here and run corresponding
6013 * non-builtin later. */
6014 const struct built_in_command *x;
6015 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6017 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6020 #if ENABLE_HUSH_FUNCTIONS
6021 /* Check if the command matches any functions */
6023 const struct function *funcp = find_function(argv[0]);
6025 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6030 #if ENABLE_FEATURE_SH_STANDALONE
6031 /* Check if the command matches any busybox applets */
6033 int a = find_applet_by_name(argv[0]);
6035 # if BB_MMU /* see above why on NOMMU it is not allowed */
6036 if (APPLET_IS_NOEXEC(a)) {
6037 debug_printf_exec("running applet '%s'\n", argv[0]);
6038 run_applet_no_and_exit(a, argv);
6041 /* Re-exec ourselves */
6042 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6043 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6044 execv(bb_busybox_exec_path, argv);
6045 /* If they called chroot or otherwise made the binary no longer
6046 * executable, fall through */
6051 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6054 execvp_or_die(argv);
6057 /* Called after [v]fork() in run_pipe
6059 static void pseudo_exec(nommu_save_t *nommu_save,
6060 struct command *command,
6061 char **argv_expanded) NORETURN;
6062 static void pseudo_exec(nommu_save_t *nommu_save,
6063 struct command *command,
6064 char **argv_expanded)
6066 if (command->argv) {
6067 pseudo_exec_argv(nommu_save, command->argv,
6068 command->assignment_cnt, argv_expanded);
6071 if (command->group) {
6072 /* Cases when we are here:
6075 * ... | ( list ) | ...
6076 * ... | { list } | ...
6080 debug_printf_exec("pseudo_exec: run_list\n");
6081 reset_traps_to_defaults();
6082 rcode = run_list(command->group);
6083 /* OK to leak memory by not calling free_pipe_list,
6084 * since this process is about to exit */
6087 re_execute_shell(&nommu_save->argv_from_re_execing,
6088 command->group_as_string,
6095 /* Case when we are here: ... | >file */
6096 debug_printf_exec("pseudo_exec'ed null command\n");
6097 _exit(EXIT_SUCCESS);
6101 static const char *get_cmdtext(struct pipe *pi)
6107 /* This is subtle. ->cmdtext is created only on first backgrounding.
6108 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6109 * On subsequent bg argv is trashed, but we won't use it */
6112 argv = pi->cmds[0].argv;
6113 if (!argv || !argv[0]) {
6114 pi->cmdtext = xzalloc(1);
6120 len += strlen(*argv) + 1;
6124 argv = pi->cmds[0].argv;
6126 len = strlen(*argv);
6127 memcpy(p, *argv, len);
6135 static void insert_bg_job(struct pipe *pi)
6137 struct pipe *job, **jobp;
6140 /* Linear search for the ID of the job to use */
6142 for (job = G.job_list; job; job = job->next)
6143 if (job->jobid >= pi->jobid)
6144 pi->jobid = job->jobid + 1;
6146 /* Add job to the list of running jobs */
6148 while ((job = *jobp) != NULL)
6150 job = *jobp = xmalloc(sizeof(*job));
6152 *job = *pi; /* physical copy */
6154 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6155 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6156 for (i = 0; i < pi->num_cmds; i++) {
6157 job->cmds[i].pid = pi->cmds[i].pid;
6158 /* all other fields are not used and stay zero */
6160 job->cmdtext = xstrdup(get_cmdtext(pi));
6162 if (G_interactive_fd)
6163 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6164 G.last_jobid = job->jobid;
6167 static void remove_bg_job(struct pipe *pi)
6169 struct pipe *prev_pipe;
6171 if (pi == G.job_list) {
6172 G.job_list = pi->next;
6174 prev_pipe = G.job_list;
6175 while (prev_pipe->next != pi)
6176 prev_pipe = prev_pipe->next;
6177 prev_pipe->next = pi->next;
6180 G.last_jobid = G.job_list->jobid;
6185 /* Remove a backgrounded job */
6186 static void delete_finished_bg_job(struct pipe *pi)
6189 pi->stopped_cmds = 0;
6195 /* Check to see if any processes have exited -- if they
6196 * have, figure out why and see if a job has completed */
6197 static int checkjobs(struct pipe* fg_pipe)
6207 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6209 attributes = WUNTRACED;
6210 if (fg_pipe == NULL)
6211 attributes |= WNOHANG;
6214 #if ENABLE_HUSH_FAST
6215 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6216 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6217 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6218 /* There was neither fork nor SIGCHLD since last waitpid */
6219 /* Avoid doing waitpid syscall if possible */
6220 if (!G.we_have_children) {
6224 if (fg_pipe == NULL) { /* is WNOHANG set? */
6225 /* We have children, but they did not exit
6226 * or stop yet (we saw no SIGCHLD) */
6229 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6233 /* Do we do this right?
6234 * bash-3.00# sleep 20 | false
6236 * [3]+ Stopped sleep 20 | false
6237 * bash-3.00# echo $?
6238 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6239 * [hush 1.14.0: yes we do it right]
6246 #if ENABLE_HUSH_FAST
6247 i = G.count_SIGCHLD;
6249 childpid = waitpid(-1, &status, attributes);
6250 if (childpid <= 0) {
6251 if (childpid && errno != ECHILD)
6252 bb_perror_msg("waitpid");
6253 #if ENABLE_HUSH_FAST
6254 else { /* Until next SIGCHLD, waitpid's are useless */
6255 G.we_have_children = (childpid == 0);
6256 G.handled_SIGCHLD = i;
6257 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6262 dead = WIFEXITED(status) || WIFSIGNALED(status);
6265 if (WIFSTOPPED(status))
6266 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6267 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6268 if (WIFSIGNALED(status))
6269 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6270 childpid, WTERMSIG(status), WEXITSTATUS(status));
6271 if (WIFEXITED(status))
6272 debug_printf_jobs("pid %d exited, exitcode %d\n",
6273 childpid, WEXITSTATUS(status));
6275 /* Were we asked to wait for fg pipe? */
6277 for (i = 0; i < fg_pipe->num_cmds; i++) {
6278 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6279 if (fg_pipe->cmds[i].pid != childpid)
6282 fg_pipe->cmds[i].pid = 0;
6283 fg_pipe->alive_cmds--;
6284 if (i == fg_pipe->num_cmds - 1) {
6285 /* last process gives overall exitstatus */
6286 rcode = WEXITSTATUS(status);
6287 /* bash prints killer signal's name for *last*
6288 * process in pipe (prints just newline for SIGINT).
6289 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6291 if (WIFSIGNALED(status)) {
6292 int sig = WTERMSIG(status);
6293 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6294 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6295 * Maybe we need to use sig | 128? */
6298 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6301 fg_pipe->cmds[i].is_stopped = 1;
6302 fg_pipe->stopped_cmds++;
6304 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6305 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6306 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6307 /* All processes in fg pipe have exited or stopped */
6308 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6309 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6310 * and "killall -STOP cat" */
6311 if (G_interactive_fd) {
6313 if (fg_pipe->alive_cmds)
6314 insert_bg_job(fg_pipe);
6318 if (!fg_pipe->alive_cmds)
6321 /* There are still running processes in the fg pipe */
6322 goto wait_more; /* do waitpid again */
6324 /* it wasnt fg_pipe, look for process in bg pipes */
6328 /* We asked to wait for bg or orphaned children */
6329 /* No need to remember exitcode in this case */
6330 for (pi = G.job_list; pi; pi = pi->next) {
6331 for (i = 0; i < pi->num_cmds; i++) {
6332 if (pi->cmds[i].pid == childpid)
6333 goto found_pi_and_prognum;
6336 /* Happens when shell is used as init process (init=/bin/sh) */
6337 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6338 continue; /* do waitpid again */
6340 found_pi_and_prognum:
6343 pi->cmds[i].pid = 0;
6345 if (!pi->alive_cmds) {
6346 if (G_interactive_fd)
6347 printf(JOB_STATUS_FORMAT, pi->jobid,
6348 "Done", pi->cmdtext);
6349 delete_finished_bg_job(pi);
6353 pi->cmds[i].is_stopped = 1;
6357 } /* while (waitpid succeeds)... */
6363 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
6366 int rcode = checkjobs(fg_pipe);
6367 if (G_saved_tty_pgrp) {
6368 /* Job finished, move the shell to the foreground */
6369 p = getpgrp(); /* our process group id */
6370 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6371 tcsetpgrp(G_interactive_fd, p);
6377 /* Start all the jobs, but don't wait for anything to finish.
6380 * Return code is normally -1, when the caller has to wait for children
6381 * to finish to determine the exit status of the pipe. If the pipe
6382 * is a simple builtin command, however, the action is done by the
6383 * time run_pipe returns, and the exit code is provided as the
6386 * Returns -1 only if started some children. IOW: we have to
6387 * mask out retvals of builtins etc with 0xff!
6389 * The only case when we do not need to [v]fork is when the pipe
6390 * is single, non-backgrounded, non-subshell command. Examples:
6391 * cmd ; ... { list } ; ...
6392 * cmd && ... { list } && ...
6393 * cmd || ... { list } || ...
6394 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6395 * or (if SH_STANDALONE) an applet, and we can run the { list }
6396 * with run_list. If it isn't one of these, we fork and exec cmd.
6398 * Cases when we must fork:
6399 * non-single: cmd | cmd
6400 * backgrounded: cmd & { list } &
6401 * subshell: ( list ) [&]
6403 #if !ENABLE_HUSH_MODE_X
6404 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6405 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6407 static int redirect_and_varexp_helper(char ***new_env_p,
6408 struct variable **old_vars_p,
6409 struct command *command,
6411 char **argv_expanded)
6413 /* setup_redirects acts on file descriptors, not FILEs.
6414 * This is perfect for work that comes after exec().
6415 * Is it really safe for inline use? Experimentally,
6416 * things seem to work. */
6417 int rcode = setup_redirects(command, squirrel);
6419 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6420 *new_env_p = new_env;
6421 dump_cmd_in_x_mode(new_env);
6422 dump_cmd_in_x_mode(argv_expanded);
6424 *old_vars_p = set_vars_and_save_old(new_env);
6428 static NOINLINE int run_pipe(struct pipe *pi)
6430 static const char *const null_ptr = NULL;
6434 struct command *command;
6435 char **argv_expanded;
6437 /* it is not always needed, but we aim to smaller code */
6438 int squirrel[] = { -1, -1, -1 };
6441 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6444 IF_HUSH_JOB(pi->pgrp = -1;)
6445 pi->stopped_cmds = 0;
6446 command = &pi->cmds[0];
6447 argv_expanded = NULL;
6449 if (pi->num_cmds != 1
6450 || pi->followup == PIPE_BG
6451 || command->cmd_type == CMD_SUBSHELL
6458 debug_printf_exec(": group:%p argv:'%s'\n",
6459 command->group, command->argv ? command->argv[0] : "NONE");
6461 if (command->group) {
6462 #if ENABLE_HUSH_FUNCTIONS
6463 if (command->cmd_type == CMD_FUNCDEF) {
6464 /* "executing" func () { list } */
6465 struct function *funcp;
6467 funcp = new_function(command->argv[0]);
6468 /* funcp->name is already set to argv[0] */
6469 funcp->body = command->group;
6471 funcp->body_as_string = command->group_as_string;
6472 command->group_as_string = NULL;
6474 command->group = NULL;
6475 command->argv[0] = NULL;
6476 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6477 funcp->parent_cmd = command;
6478 command->child_func = funcp;
6480 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6482 return EXIT_SUCCESS;
6486 debug_printf("non-subshell group\n");
6487 rcode = 1; /* exitcode if redir failed */
6488 if (setup_redirects(command, squirrel) == 0) {
6489 debug_printf_exec(": run_list\n");
6490 rcode = run_list(command->group) & 0xff;
6492 restore_redirects(squirrel);
6493 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6495 debug_printf_exec("run_pipe: return %d\n", rcode);
6499 argv = command->argv ? command->argv : (char **) &null_ptr;
6501 const struct built_in_command *x;
6502 #if ENABLE_HUSH_FUNCTIONS
6503 const struct function *funcp;
6507 char **new_env = NULL;
6508 struct variable *old_vars = NULL;
6510 if (argv[command->assignment_cnt] == NULL) {
6511 /* Assignments, but no command */
6512 /* Ensure redirects take effect (that is, create files).
6513 * Try "a=t >file" */
6514 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6515 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6516 /* Set shell variables */
6520 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6521 /* Do we need to flag set_local_var() errors?
6522 * "assignment to readonly var" and "putenv error"
6527 /* Redirect error sets $? to 1. Otherwise,
6528 * if evaluating assignment value set $?, retain it.
6529 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6531 rcode = G.last_exitcode;
6532 /* Exit, _skipping_ variable restoring code: */
6533 goto clean_up_and_ret0;
6535 #else /* Older, bigger, but more correct code */
6537 rcode = setup_redirects(command, squirrel);
6538 restore_redirects(squirrel);
6539 /* Set shell variables */
6541 bb_putchar_stderr('+');
6543 char *p = expand_string_to_string(*argv);
6545 fprintf(stderr, " %s", p);
6546 debug_printf_exec("set shell var:'%s'->'%s'\n",
6548 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6549 /* Do we need to flag set_local_var() errors?
6550 * "assignment to readonly var" and "putenv error"
6555 bb_putchar_stderr('\n');
6556 /* Redirect error sets $? to 1. Otherwise,
6557 * if evaluating assignment value set $?, retain it.
6558 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6560 rcode = G.last_exitcode;
6561 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6563 debug_printf_exec("run_pipe: return %d\n", rcode);
6568 /* Expand the rest into (possibly) many strings each */
6570 #if ENABLE_HUSH_BASH_COMPAT
6571 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6572 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6576 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6579 /* if someone gives us an empty string: `cmd with empty output` */
6580 if (!argv_expanded[0]) {
6581 free(argv_expanded);
6583 return G.last_exitcode;
6586 x = find_builtin(argv_expanded[0]);
6587 #if ENABLE_HUSH_FUNCTIONS
6590 funcp = find_function(argv_expanded[0]);
6594 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6595 debug_printf("exec with redirects only\n");
6596 rcode = setup_redirects(command, NULL);
6597 goto clean_up_and_ret1;
6600 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6603 debug_printf_exec(": builtin '%s' '%s'...\n",
6604 x->b_cmd, argv_expanded[1]);
6605 rcode = x->b_function(argv_expanded) & 0xff;
6608 #if ENABLE_HUSH_FUNCTIONS
6610 # if ENABLE_HUSH_LOCAL
6611 struct variable **sv;
6612 sv = G.shadowed_vars_pp;
6613 G.shadowed_vars_pp = &old_vars;
6615 debug_printf_exec(": function '%s' '%s'...\n",
6616 funcp->name, argv_expanded[1]);
6617 rcode = run_function(funcp, argv_expanded) & 0xff;
6618 # if ENABLE_HUSH_LOCAL
6619 G.shadowed_vars_pp = sv;
6625 unset_vars(new_env);
6627 /* clean_up_and_ret0: */
6628 restore_redirects(squirrel);
6630 free(argv_expanded);
6631 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6633 debug_printf_exec("run_pipe return %d\n", rcode);
6637 if (ENABLE_FEATURE_SH_STANDALONE) {
6638 int n = find_applet_by_name(argv_expanded[0]);
6639 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6640 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6642 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6643 argv_expanded[0], argv_expanded[1]);
6644 rcode = run_nofork_applet(n, argv_expanded);
6646 goto clean_up_and_ret;
6649 /* It is neither builtin nor applet. We must fork. */
6653 /* NB: argv_expanded may already be created, and that
6654 * might include `cmd` runs! Do not rerun it! We *must*
6655 * use argv_expanded if it's non-NULL */
6657 /* Going to fork a child per each pipe member */
6662 while (cmd_no < pi->num_cmds) {
6663 struct fd_pair pipefds;
6665 volatile nommu_save_t nommu_save;
6666 nommu_save.new_env = NULL;
6667 nommu_save.old_vars = NULL;
6668 nommu_save.argv = NULL;
6669 nommu_save.argv_from_re_execing = NULL;
6671 command = &pi->cmds[cmd_no];
6673 if (command->argv) {
6674 debug_printf_exec(": pipe member '%s' '%s'...\n",
6675 command->argv[0], command->argv[1]);
6677 debug_printf_exec(": pipe member with no argv\n");
6680 /* pipes are inserted between pairs of commands */
6683 if (cmd_no < pi->num_cmds)
6684 xpiped_pair(pipefds);
6686 command->pid = BB_MMU ? fork() : vfork();
6687 if (!command->pid) { /* child */
6689 disable_restore_tty_pgrp_on_exit();
6690 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6692 /* Every child adds itself to new process group
6693 * with pgid == pid_of_first_child_in_pipe */
6694 if (G.run_list_level == 1 && G_interactive_fd) {
6697 if (pgrp < 0) /* true for 1st process only */
6699 if (setpgid(0, pgrp) == 0
6700 && pi->followup != PIPE_BG
6701 && G_saved_tty_pgrp /* we have ctty */
6703 /* We do it in *every* child, not just first,
6705 tcsetpgrp(G_interactive_fd, pgrp);
6709 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6710 /* 1st cmd in backgrounded pipe
6711 * should have its stdin /dev/null'ed */
6713 if (open(bb_dev_null, O_RDONLY))
6714 xopen("/", O_RDONLY);
6716 xmove_fd(next_infd, 0);
6718 xmove_fd(pipefds.wr, 1);
6721 /* Like bash, explicit redirects override pipes,
6722 * and the pipe fd is available for dup'ing. */
6723 if (setup_redirects(command, NULL))
6726 /* Restore default handlers just prior to exec */
6727 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6729 /* Stores to nommu_save list of env vars putenv'ed
6730 * (NOMMU, on MMU we don't need that) */
6731 /* cast away volatility... */
6732 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6733 /* pseudo_exec() does not return */
6736 /* parent or error */
6737 #if ENABLE_HUSH_FAST
6739 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6741 enable_restore_tty_pgrp_on_exit();
6743 /* Clean up after vforked child */
6744 free(nommu_save.argv);
6745 free(nommu_save.argv_from_re_execing);
6746 unset_vars(nommu_save.new_env);
6747 add_vars(nommu_save.old_vars);
6749 free(argv_expanded);
6750 argv_expanded = NULL;
6751 if (command->pid < 0) { /* [v]fork failed */
6752 /* Clearly indicate, was it fork or vfork */
6753 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6757 /* Second and next children need to know pid of first one */
6759 pi->pgrp = command->pid;
6765 if (cmd_no < pi->num_cmds)
6767 /* Pass read (output) pipe end to next iteration */
6768 next_infd = pipefds.rd;
6771 if (!pi->alive_cmds) {
6773 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6778 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6782 #ifndef debug_print_tree
6783 static void debug_print_tree(struct pipe *pi, int lvl)
6785 static const char *const PIPE[] = {
6791 static const char *RES[] = {
6792 [RES_NONE ] = "NONE" ,
6795 [RES_THEN ] = "THEN" ,
6796 [RES_ELIF ] = "ELIF" ,
6797 [RES_ELSE ] = "ELSE" ,
6800 # if ENABLE_HUSH_LOOPS
6801 [RES_FOR ] = "FOR" ,
6802 [RES_WHILE] = "WHILE",
6803 [RES_UNTIL] = "UNTIL",
6805 [RES_DONE ] = "DONE" ,
6807 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6810 # if ENABLE_HUSH_CASE
6811 [RES_CASE ] = "CASE" ,
6812 [RES_CASE_IN ] = "CASE_IN" ,
6813 [RES_MATCH] = "MATCH",
6814 [RES_CASE_BODY] = "CASE_BODY",
6815 [RES_ESAC ] = "ESAC" ,
6817 [RES_XXXX ] = "XXXX" ,
6818 [RES_SNTX ] = "SNTX" ,
6820 static const char *const CMDTYPE[] = {
6824 # if ENABLE_HUSH_FUNCTIONS
6833 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6834 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6836 while (prn < pi->num_cmds) {
6837 struct command *command = &pi->cmds[prn];
6838 char **argv = command->argv;
6840 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6842 command->assignment_cnt);
6843 if (command->group) {
6844 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6845 CMDTYPE[command->cmd_type],
6848 , " group_as_string:", command->group_as_string
6853 debug_print_tree(command->group, lvl+1);
6857 if (argv) while (*argv) {
6858 fprintf(stderr, " '%s'", *argv);
6861 fprintf(stderr, "\n");
6868 #endif /* debug_print_tree */
6870 /* NB: called by pseudo_exec, and therefore must not modify any
6871 * global data until exec/_exit (we can be a child after vfork!) */
6872 static int run_list(struct pipe *pi)
6874 #if ENABLE_HUSH_CASE
6875 char *case_word = NULL;
6877 #if ENABLE_HUSH_LOOPS
6878 struct pipe *loop_top = NULL;
6879 char **for_lcur = NULL;
6880 char **for_list = NULL;
6882 smallint last_followup;
6884 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6885 smalluint cond_code = 0;
6887 enum { cond_code = 0 };
6890 smallint rword; /* enum reserved_style */
6891 smallint last_rword; /* ditto */
6894 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6897 #if ENABLE_HUSH_LOOPS
6898 /* Check syntax for "for" */
6899 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6900 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6902 /* current word is FOR or IN (BOLD in comments below) */
6903 if (cpipe->next == NULL) {
6904 syntax_error("malformed for");
6906 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6909 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6910 if (cpipe->next->res_word == RES_DO)
6912 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6913 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6914 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6916 syntax_error("malformed for");
6918 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6924 /* Past this point, all code paths should jump to ret: label
6925 * in order to return, no direct "return" statements please.
6926 * This helps to ensure that no memory is leaked. */
6934 last_rword = RES_XXXX;
6936 last_followup = PIPE_SEQ;
6937 rcode = G.last_exitcode;
6939 /* Go through list of pipes, (maybe) executing them. */
6940 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6944 IF_HAS_KEYWORDS(rword = pi->res_word;)
6945 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6946 rword, cond_code, last_rword);
6947 #if ENABLE_HUSH_LOOPS
6948 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6949 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6951 /* start of a loop: remember where loop starts */
6956 /* Still in the same "if...", "then..." or "do..." branch? */
6957 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6958 if ((rcode == 0 && last_followup == PIPE_OR)
6959 || (rcode != 0 && last_followup == PIPE_AND)
6961 /* It is "<true> || CMD" or "<false> && CMD"
6962 * and we should not execute CMD */
6963 debug_printf_exec("skipped cmd because of || or &&\n");
6964 last_followup = pi->followup;
6968 last_followup = pi->followup;
6969 IF_HAS_KEYWORDS(last_rword = rword;)
6972 if (rword == RES_THEN) {
6973 /* if false; then ... fi has exitcode 0! */
6974 G.last_exitcode = rcode = EXIT_SUCCESS;
6975 /* "if <false> THEN cmd": skip cmd */
6979 if (rword == RES_ELSE || rword == RES_ELIF) {
6980 /* "if <true> then ... ELSE/ELIF cmd":
6981 * skip cmd and all following ones */
6986 #if ENABLE_HUSH_LOOPS
6987 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
6989 /* first loop through for */
6991 static const char encoded_dollar_at[] ALIGN1 = {
6992 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
6993 }; /* encoded representation of "$@" */
6994 static const char *const encoded_dollar_at_argv[] = {
6995 encoded_dollar_at, NULL
6996 }; /* argv list with one element: "$@" */
6999 vals = (char**)encoded_dollar_at_argv;
7000 if (pi->next->res_word == RES_IN) {
7001 /* if no variable values after "in" we skip "for" */
7002 if (!pi->next->cmds[0].argv) {
7003 G.last_exitcode = rcode = EXIT_SUCCESS;
7004 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7007 vals = pi->next->cmds[0].argv;
7008 } /* else: "for var; do..." -> assume "$@" list */
7009 /* create list of variable values */
7010 debug_print_strings("for_list made from", vals);
7011 for_list = expand_strvec_to_strvec(vals);
7012 for_lcur = for_list;
7013 debug_print_strings("for_list", for_list);
7016 /* "for" loop is over, clean up */
7022 /* Insert next value from for_lcur */
7023 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7024 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7027 if (rword == RES_IN) {
7028 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7030 if (rword == RES_DONE) {
7031 continue; /* "done" has no cmds too */
7034 #if ENABLE_HUSH_CASE
7035 if (rword == RES_CASE) {
7036 case_word = expand_strvec_to_string(pi->cmds->argv);
7039 if (rword == RES_MATCH) {
7042 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7044 /* all prev words didn't match, does this one match? */
7045 argv = pi->cmds->argv;
7047 char *pattern = expand_string_to_string(*argv);
7048 /* TODO: which FNM_xxx flags to use? */
7049 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7051 if (cond_code == 0) { /* match! we will execute this branch */
7052 free(case_word); /* make future "word)" stop */
7060 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7062 continue; /* not matched yet, skip this pipe */
7065 /* Just pressing <enter> in shell should check for jobs.
7066 * OTOH, in non-interactive shell this is useless
7067 * and only leads to extra job checks */
7068 if (pi->num_cmds == 0) {
7069 if (G_interactive_fd)
7070 goto check_jobs_and_continue;
7074 /* After analyzing all keywords and conditions, we decided
7075 * to execute this pipe. NB: have to do checkjobs(NULL)
7076 * after run_pipe to collect any background children,
7077 * even if list execution is to be stopped. */
7078 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7081 #if ENABLE_HUSH_LOOPS
7082 G.flag_break_continue = 0;
7084 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7086 /* We ran a builtin, function, or group.
7087 * rcode is already known
7088 * and we don't need to wait for anything. */
7089 G.last_exitcode = rcode;
7090 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7091 check_and_run_traps(0);
7092 #if ENABLE_HUSH_LOOPS
7093 /* Was it "break" or "continue"? */
7094 if (G.flag_break_continue) {
7095 smallint fbc = G.flag_break_continue;
7096 /* We might fall into outer *loop*,
7097 * don't want to break it too */
7099 G.depth_break_continue--;
7100 if (G.depth_break_continue == 0)
7101 G.flag_break_continue = 0;
7102 /* else: e.g. "continue 2" should *break* once, *then* continue */
7103 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7104 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7105 goto check_jobs_and_break;
7106 /* "continue": simulate end of loop */
7111 #if ENABLE_HUSH_FUNCTIONS
7112 if (G.flag_return_in_progress == 1) {
7113 /* same as "goto check_jobs_and_break" */
7118 } else if (pi->followup == PIPE_BG) {
7119 /* What does bash do with attempts to background builtins? */
7120 /* even bash 3.2 doesn't do that well with nested bg:
7121 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7122 * I'm NOT treating inner &'s as jobs */
7123 check_and_run_traps(0);
7125 if (G.run_list_level == 1)
7128 /* Last command's pid goes to $! */
7129 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7130 G.last_exitcode = rcode = EXIT_SUCCESS;
7131 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7134 if (G.run_list_level == 1 && G_interactive_fd) {
7135 /* Waits for completion, then fg's main shell */
7136 rcode = checkjobs_and_fg_shell(pi);
7137 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7138 check_and_run_traps(0);
7141 { /* This one just waits for completion */
7142 rcode = checkjobs(pi);
7143 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7144 check_and_run_traps(0);
7146 G.last_exitcode = rcode;
7150 /* Analyze how result affects subsequent commands */
7152 if (rword == RES_IF || rword == RES_ELIF)
7155 #if ENABLE_HUSH_LOOPS
7156 /* Beware of "while false; true; do ..."! */
7157 if (pi->next && pi->next->res_word == RES_DO) {
7158 if (rword == RES_WHILE) {
7160 /* "while false; do...done" - exitcode 0 */
7161 G.last_exitcode = rcode = EXIT_SUCCESS;
7162 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7163 goto check_jobs_and_break;
7166 if (rword == RES_UNTIL) {
7168 debug_printf_exec(": until expr is true: breaking\n");
7169 check_jobs_and_break:
7177 check_jobs_and_continue:
7184 #if ENABLE_HUSH_LOOPS
7189 #if ENABLE_HUSH_CASE
7193 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7197 /* Select which version we will use */
7198 static int run_and_free_list(struct pipe *pi)
7201 debug_printf_exec("run_and_free_list entered\n");
7203 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7204 rcode = run_list(pi);
7206 /* free_pipe_list has the side effect of clearing memory.
7207 * In the long run that function can be merged with run_list,
7208 * but doing that now would hobble the debugging effort. */
7210 debug_printf_exec("run_and_free_list return %d\n", rcode);
7215 /* Called a few times only (or even once if "sh -c") */
7216 static void init_sigmasks(void)
7220 sigset_t old_blocked_set;
7222 if (!G.inherited_set_is_saved) {
7223 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7224 G.inherited_set = G.blocked_set;
7226 old_blocked_set = G.blocked_set;
7228 mask = (1 << SIGQUIT);
7229 if (G_interactive_fd) {
7230 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7231 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7232 mask |= SPECIAL_JOB_SIGS;
7234 G.non_DFL_mask = mask;
7239 sigaddset(&G.blocked_set, sig);
7243 sigdelset(&G.blocked_set, SIGCHLD);
7245 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7246 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7248 /* POSIX allows shell to re-enable SIGCHLD
7249 * even if it was SIG_IGN on entry */
7250 #if ENABLE_HUSH_FAST
7251 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7252 if (!G.inherited_set_is_saved)
7253 signal(SIGCHLD, SIGCHLD_handler);
7255 if (!G.inherited_set_is_saved)
7256 signal(SIGCHLD, SIG_DFL);
7259 G.inherited_set_is_saved = 1;
7264 static void maybe_set_to_sigexit(int sig)
7266 void (*handler)(int);
7267 /* non_DFL_mask'ed signals are, well, masked,
7268 * no need to set handler for them.
7270 if (!((G.non_DFL_mask >> sig) & 1)) {
7271 handler = signal(sig, sigexit);
7272 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7273 signal(sig, handler);
7276 /* Set handlers to restore tty pgrp and exit */
7277 static void set_fatal_handlers(void)
7279 /* We _must_ restore tty pgrp on fatal signals */
7281 maybe_set_to_sigexit(SIGILL );
7282 maybe_set_to_sigexit(SIGFPE );
7283 maybe_set_to_sigexit(SIGBUS );
7284 maybe_set_to_sigexit(SIGSEGV);
7285 maybe_set_to_sigexit(SIGTRAP);
7286 } /* else: hush is perfect. what SEGV? */
7287 maybe_set_to_sigexit(SIGABRT);
7288 /* bash 3.2 seems to handle these just like 'fatal' ones */
7289 maybe_set_to_sigexit(SIGPIPE);
7290 maybe_set_to_sigexit(SIGALRM);
7291 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7292 * if we aren't interactive... but in this case
7293 * we never want to restore pgrp on exit, and this fn is not called */
7294 /*maybe_set_to_sigexit(SIGHUP );*/
7295 /*maybe_set_to_sigexit(SIGTERM);*/
7296 /*maybe_set_to_sigexit(SIGINT );*/
7300 static int set_mode(const char cstate, const char mode)
7302 int state = (cstate == '-' ? 1 : 0);
7304 case 'n': G.n_mode = state; break;
7305 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7306 default: return EXIT_FAILURE;
7308 return EXIT_SUCCESS;
7311 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7312 int hush_main(int argc, char **argv)
7315 unsigned builtin_argc;
7317 struct variable *cur_var;
7320 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7321 G.last_exitcode = EXIT_SUCCESS;
7323 G.argv0_for_re_execing = argv[0];
7325 /* Deal with HUSH_VERSION */
7326 G.shell_ver.flg_export = 1;
7327 G.shell_ver.flg_read_only = 1;
7328 /* Code which handles ${var/P/R} needs writable values for all variables,
7329 * therefore we xstrdup: */
7330 G.shell_ver.varstr = xstrdup(hush_version_str),
7331 G.top_var = &G.shell_ver;
7332 /* Create shell local variables from the values
7333 * currently living in the environment */
7334 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7335 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7336 cur_var = G.top_var;
7339 char *value = strchr(*e, '=');
7340 if (value) { /* paranoia */
7341 cur_var->next = xzalloc(sizeof(*cur_var));
7342 cur_var = cur_var->next;
7343 cur_var->varstr = *e;
7344 cur_var->max_len = strlen(*e);
7345 cur_var->flg_export = 1;
7349 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7350 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7351 putenv(G.shell_ver.varstr);
7354 set_pwd_var(/*exp:*/ 1);
7355 /* bash also exports SHLVL and _,
7356 * and sets (but doesn't export) the following variables:
7358 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7359 * BASH_VERSION='3.2.0(1)-release'
7361 * MACHTYPE=i386-pc-linux-gnu
7363 * HOSTNAME=<xxxxxxxxxx>
7364 * PPID=<NNNNN> - we also do it elsewhere
7375 * PIPESTATUS=([0]="0")
7376 * HISTFILE=/<xxx>/.bash_history
7380 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7382 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7392 #if ENABLE_FEATURE_EDITING
7393 G.line_input_state = new_line_input_t(FOR_SHELL);
7395 G.global_argc = argc;
7396 G.global_argv = argv;
7397 /* Initialize some more globals to non-zero values */
7398 cmdedit_update_prompt();
7400 if (setjmp(die_jmp)) {
7401 /* xfunc has failed! die die die */
7402 /* no EXIT traps, this is an escape hatch! */
7404 hush_exit(xfunc_error_retval);
7407 /* Shell is non-interactive at first. We need to call
7408 * init_sigmasks() if we are going to execute "sh <script>",
7409 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7410 * If we later decide that we are interactive, we run init_sigmasks()
7411 * in order to intercept (more) signals.
7415 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7418 opt = getopt(argc, argv, "+c:xins"
7421 # if ENABLE_HUSH_FUNCTIONS
7431 * sh ... -c 'script'
7432 * sh ... -c 'script' ARG0 [ARG1...]
7433 * On NOMMU, if builtin_argc != 0,
7434 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7435 * "" needs to be replaced with NULL
7436 * and BARGV vector fed to builtin function.
7437 * Note: the form without ARG0 never happens:
7438 * sh ... -c 'builtin' BARGV... ""
7441 G.root_pid = getpid();
7442 G.root_ppid = getppid();
7444 G.global_argv = argv + optind;
7445 G.global_argc = argc - optind;
7447 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7448 const struct built_in_command *x;
7451 x = find_builtin(optarg);
7452 if (x) { /* paranoia */
7453 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7454 G.global_argv += builtin_argc;
7455 G.global_argv[-1] = NULL; /* replace "" */
7456 G.last_exitcode = x->b_function(argv + optind - 1);
7460 if (!G.global_argv[0]) {
7461 /* -c 'script' (no params): prevent empty $0 */
7462 G.global_argv--; /* points to argv[i] of 'script' */
7463 G.global_argv[0] = argv[0];
7465 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7467 parse_and_run_string(optarg);
7470 /* Well, we cannot just declare interactiveness,
7471 * we have to have some stuff (ctty, etc) */
7472 /* G_interactive_fd++; */
7475 /* "-s" means "read from stdin", but this is how we always
7476 * operate, so simply do nothing here. */
7479 case '<': /* "big heredoc" support */
7480 full_write1_str(optarg);
7483 unsigned long long empty_trap_mask;
7485 G.root_pid = bb_strtou(optarg, &optarg, 16);
7487 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7489 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7491 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7493 builtin_argc = bb_strtou(optarg, &optarg, 16);
7495 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7496 if (empty_trap_mask != 0) {
7499 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7500 for (sig = 1; sig < NSIG; sig++) {
7501 if (empty_trap_mask & (1LL << sig)) {
7502 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7503 sigaddset(&G.blocked_set, sig);
7506 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7508 # if ENABLE_HUSH_LOOPS
7510 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7516 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7518 # if ENABLE_HUSH_FUNCTIONS
7520 struct function *funcp = new_function(optarg);
7521 /* funcp->name is already set to optarg */
7522 /* funcp->body is set to NULL. It's a special case. */
7523 funcp->body_as_string = argv[optind];
7531 if (set_mode('-', opt) == 0) /* no error */
7535 fprintf(stderr, "Usage: sh [FILE]...\n"
7536 " or: sh -c command [args]...\n\n");
7542 } /* option parsing loop */
7545 G.root_pid = getpid();
7546 G.root_ppid = getppid();
7549 /* If we are login shell... */
7550 if (argv[0] && argv[0][0] == '-') {
7552 debug_printf("sourcing /etc/profile\n");
7553 input = fopen_for_read("/etc/profile");
7554 if (input != NULL) {
7555 close_on_exec_on(fileno(input));
7557 parse_and_run_file(input);
7560 /* bash: after sourcing /etc/profile,
7561 * tries to source (in the given order):
7562 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7563 * stopping on first found. --noprofile turns this off.
7564 * bash also sources ~/.bash_logout on exit.
7565 * If called as sh, skips .bash_XXX files.
7572 * "bash <script>" (which is never interactive (unless -i?))
7573 * sources $BASH_ENV here (without scanning $PATH).
7574 * If called as sh, does the same but with $ENV.
7576 debug_printf("running script '%s'\n", argv[optind]);
7577 G.global_argv = argv + optind;
7578 G.global_argc = argc - optind;
7579 input = xfopen_for_read(argv[optind]);
7580 close_on_exec_on(fileno(input));
7582 parse_and_run_file(input);
7583 #if ENABLE_FEATURE_CLEAN_UP
7589 /* Up to here, shell was non-interactive. Now it may become one.
7590 * NB: don't forget to (re)run init_sigmasks() as needed.
7593 /* A shell is interactive if the '-i' flag was given,
7594 * or if all of the following conditions are met:
7596 * no arguments remaining or the -s flag given
7597 * standard input is a terminal
7598 * standard output is a terminal
7599 * Refer to Posix.2, the description of the 'sh' utility.
7602 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7603 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7604 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7605 if (G_saved_tty_pgrp < 0)
7606 G_saved_tty_pgrp = 0;
7608 /* try to dup stdin to high fd#, >= 255 */
7609 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7610 if (G_interactive_fd < 0) {
7611 /* try to dup to any fd */
7612 G_interactive_fd = dup(STDIN_FILENO);
7613 if (G_interactive_fd < 0) {
7615 G_interactive_fd = 0;
7616 G_saved_tty_pgrp = 0;
7619 // TODO: track & disallow any attempts of user
7620 // to (inadvertently) close/redirect G_interactive_fd
7622 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7623 if (G_interactive_fd) {
7624 close_on_exec_on(G_interactive_fd);
7626 if (G_saved_tty_pgrp) {
7627 /* If we were run as 'hush &', sleep until we are
7628 * in the foreground (tty pgrp == our pgrp).
7629 * If we get started under a job aware app (like bash),
7630 * make sure we are now in charge so we don't fight over
7631 * who gets the foreground */
7633 pid_t shell_pgrp = getpgrp();
7634 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7635 if (G_saved_tty_pgrp == shell_pgrp)
7637 /* send TTIN to ourself (should stop us) */
7638 kill(- shell_pgrp, SIGTTIN);
7642 /* Block some signals */
7645 if (G_saved_tty_pgrp) {
7646 /* Set other signals to restore saved_tty_pgrp */
7647 set_fatal_handlers();
7648 /* Put ourselves in our own process group
7649 * (bash, too, does this only if ctty is available) */
7650 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7651 /* Grab control of the terminal */
7652 tcsetpgrp(G_interactive_fd, getpid());
7654 /* -1 is special - makes xfuncs longjmp, not exit
7655 * (we reset die_sleep = 0 whereever we [v]fork) */
7656 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7660 #elif ENABLE_HUSH_INTERACTIVE
7661 /* No job control compiled in, only prompt/line editing */
7662 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7663 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7664 if (G_interactive_fd < 0) {
7665 /* try to dup to any fd */
7666 G_interactive_fd = dup(STDIN_FILENO);
7667 if (G_interactive_fd < 0)
7669 G_interactive_fd = 0;
7672 if (G_interactive_fd) {
7673 close_on_exec_on(G_interactive_fd);
7677 /* We have interactiveness code disabled */
7681 * if interactive but not a login shell, sources ~/.bashrc
7682 * (--norc turns this off, --rcfile <file> overrides)
7685 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7686 /* note: ash and hush share this string */
7687 printf("\n\n%s %s\n"
7688 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7691 "hush - the humble shell"
7695 parse_and_run_file(stdin);
7698 #if ENABLE_FEATURE_CLEAN_UP
7699 if (G.cwd != bb_msg_unknown)
7701 cur_var = G.top_var->next;
7703 struct variable *tmp = cur_var;
7704 if (!cur_var->max_len)
7705 free(cur_var->varstr);
7706 cur_var = cur_var->next;
7710 hush_exit(G.last_exitcode);
7715 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7716 int msh_main(int argc, char **argv)
7718 //bb_error_msg("msh is deprecated, please use hush instead");
7719 return hush_main(argc, argv);
7727 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7732 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7739 return applet_main_func(argc, argv - argc);
7742 static int FAST_FUNC builtin_test(char **argv)
7744 return run_applet_main(argv, test_main);
7747 static int FAST_FUNC builtin_echo(char **argv)
7749 return run_applet_main(argv, echo_main);
7753 static int FAST_FUNC builtin_printf(char **argv)
7755 return run_applet_main(argv, printf_main);
7759 static char **skip_dash_dash(char **argv)
7762 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7767 static int FAST_FUNC builtin_eval(char **argv)
7769 int rcode = EXIT_SUCCESS;
7771 argv = skip_dash_dash(argv);
7773 char *str = expand_strvec_to_string(argv);
7775 * eval "echo Hi; done" ("done" is syntax error):
7776 * "echo Hi" will not execute too.
7778 parse_and_run_string(str);
7780 rcode = G.last_exitcode;
7785 static int FAST_FUNC builtin_cd(char **argv)
7789 argv = skip_dash_dash(argv);
7791 if (newdir == NULL) {
7792 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7793 * bash says "bash: cd: HOME not set" and does nothing
7796 const char *home = get_local_var_value("HOME");
7797 newdir = home ? home : "/";
7799 if (chdir(newdir)) {
7800 /* Mimic bash message exactly */
7801 bb_perror_msg("cd: %s", newdir);
7802 return EXIT_FAILURE;
7804 /* Read current dir (get_cwd(1) is inside) and set PWD.
7805 * Note: do not enforce exporting. If PWD was unset or unexported,
7806 * set it again, but do not export. bash does the same.
7808 set_pwd_var(/*exp:*/ 0);
7809 return EXIT_SUCCESS;
7812 static int FAST_FUNC builtin_exec(char **argv)
7814 argv = skip_dash_dash(argv);
7815 if (argv[0] == NULL)
7816 return EXIT_SUCCESS; /* bash does this */
7818 /* Careful: we can end up here after [v]fork. Do not restore
7819 * tty pgrp then, only top-level shell process does that */
7820 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7821 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7823 /* TODO: if exec fails, bash does NOT exit! We do.
7824 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7825 * and tcsetpgrp, and this is inherently racy.
7827 execvp_or_die(argv);
7830 static int FAST_FUNC builtin_exit(char **argv)
7832 debug_printf_exec("%s()\n", __func__);
7834 /* interactive bash:
7835 * # trap "echo EEE" EXIT
7838 * There are stopped jobs.
7839 * (if there are _stopped_ jobs, running ones don't count)
7842 # EEE (then bash exits)
7844 * we can use G.exiting = -1 as indicator "last cmd was exit"
7847 /* note: EXIT trap is run by hush_exit */
7848 argv = skip_dash_dash(argv);
7849 if (argv[0] == NULL)
7850 hush_exit(G.last_exitcode);
7851 /* mimic bash: exit 123abc == exit 255 + error msg */
7852 xfunc_error_retval = 255;
7853 /* bash: exit -2 == exit 254, no error msg */
7854 hush_exit(xatoi(argv[0]) & 0xff);
7857 static void print_escaped(const char *s)
7862 const char *p = strchrnul(s, '\'');
7863 /* print 'xxxx', possibly just '' */
7864 printf("'%.*s'", (int)(p - s), s);
7869 /* s points to '; print "'''...'''" */
7871 do putchar('\''); while (*++s == '\'');
7876 #if !ENABLE_HUSH_LOCAL
7877 #define helper_export_local(argv, exp, lvl) \
7878 helper_export_local(argv, exp)
7880 static void helper_export_local(char **argv, int exp, int lvl)
7885 /* So far we do not check that name is valid (TODO?) */
7887 if (strchr(name, '=') == NULL) {
7888 struct variable *var;
7890 var = get_local_var(name);
7891 if (exp == -1) { /* unexporting? */
7892 /* export -n NAME (without =VALUE) */
7894 var->flg_export = 0;
7895 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7897 } /* else: export -n NOT_EXISTING_VAR: no-op */
7900 if (exp == 1) { /* exporting? */
7901 /* export NAME (without =VALUE) */
7903 var->flg_export = 1;
7904 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7905 putenv(var->varstr);
7909 /* Exporting non-existing variable.
7910 * bash does not put it in environment,
7911 * but remembers that it is exported,
7912 * and does put it in env when it is set later.
7913 * We just set it to "" and export. */
7914 /* Or, it's "local NAME" (without =VALUE).
7915 * bash sets the value to "". */
7916 name = xasprintf("%s=", name);
7918 /* (Un)exporting/making local NAME=VALUE */
7919 name = xstrdup(name);
7921 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7925 static int FAST_FUNC builtin_export(char **argv)
7927 unsigned opt_unexport;
7929 #if ENABLE_HUSH_EXPORT_N
7930 /* "!": do not abort on errors */
7931 opt_unexport = getopt32(argv, "!n");
7932 if (opt_unexport == (uint32_t)-1)
7933 return EXIT_FAILURE;
7940 if (argv[0] == NULL) {
7947 /* ash emits: export VAR='VAL'
7948 * bash: declare -x VAR="VAL"
7949 * we follow ash example */
7950 const char *s = *e++;
7951 const char *p = strchr(s, '=');
7953 if (!p) /* wtf? take next variable */
7956 printf("export %.*s", (int)(p - s) + 1, s);
7957 print_escaped(p + 1);
7961 /*fflush_all(); - done after each builtin anyway */
7963 return EXIT_SUCCESS;
7966 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7968 return EXIT_SUCCESS;
7971 #if ENABLE_HUSH_LOCAL
7972 static int FAST_FUNC builtin_local(char **argv)
7974 if (G.func_nest_level == 0) {
7975 bb_error_msg("%s: not in a function", argv[0]);
7976 return EXIT_FAILURE; /* bash compat */
7978 helper_export_local(argv, 0, G.func_nest_level);
7979 return EXIT_SUCCESS;
7983 static int FAST_FUNC builtin_trap(char **argv)
7989 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7994 /* No args: print all trapped */
7995 for (i = 0; i < NSIG; ++i) {
7998 print_escaped(G.traps[i]);
7999 /* note: bash adds "SIG", but only if invoked
8000 * as "bash". If called as "sh", or if set -o posix,
8001 * then it prints short signal names.
8002 * We are printing short names: */
8003 printf(" %s\n", get_signame(i));
8006 /*fflush_all(); - done after each builtin anyway */
8007 return EXIT_SUCCESS;
8011 /* If first arg is a number: reset all specified signals */
8012 sig = bb_strtou(*argv, NULL, 10);
8018 sig = get_signum(*argv++);
8019 if (sig < 0 || sig >= NSIG) {
8021 /* Mimic bash message exactly */
8022 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8027 G.traps[sig] = xstrdup(new_cmd);
8029 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8030 get_signame(sig), sig, G.traps[sig]);
8032 /* There is no signal for 0 (EXIT) */
8037 sigaddset(&G.blocked_set, sig);
8039 /* There was a trap handler, we are removing it
8040 * (if sig has non-DFL handling,
8041 * we don't need to do anything) */
8042 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8044 sigdelset(&G.blocked_set, sig);
8047 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8051 if (!argv[1]) { /* no second arg */
8052 bb_error_msg("trap: invalid arguments");
8053 return EXIT_FAILURE;
8056 /* First arg is "-": reset all specified to default */
8057 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8058 /* Everything else: set arg as signal handler
8059 * (includes "" case, which ignores signal) */
8060 if (argv[0][0] == '-') {
8061 if (argv[0][1] == '\0') { /* "-" */
8062 /* new_cmd remains NULL: "reset these sigs" */
8065 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8068 /* else: "-something", no special meaning */
8073 goto process_sig_list;
8076 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8077 static int FAST_FUNC builtin_type(char **argv)
8079 int ret = EXIT_SUCCESS;
8085 if (0) {} /* make conditional compile easier below */
8086 /*else if (find_alias(*argv))
8087 type = "an alias";*/
8088 #if ENABLE_HUSH_FUNCTIONS
8089 else if (find_function(*argv))
8090 type = "a function";
8092 else if (find_builtin(*argv))
8093 type = "a shell builtin";
8094 else if ((path = find_in_path(*argv)) != NULL)
8097 bb_error_msg("type: %s: not found", *argv);
8102 printf("%s is %s\n", *argv, type);
8110 /* built-in 'fg' and 'bg' handler */
8111 static int FAST_FUNC builtin_fg_bg(char **argv)
8116 if (!G_interactive_fd)
8117 return EXIT_FAILURE;
8119 /* If they gave us no args, assume they want the last backgrounded task */
8121 for (pi = G.job_list; pi; pi = pi->next) {
8122 if (pi->jobid == G.last_jobid) {
8126 bb_error_msg("%s: no current job", argv[0]);
8127 return EXIT_FAILURE;
8129 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8130 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8131 return EXIT_FAILURE;
8133 for (pi = G.job_list; pi; pi = pi->next) {
8134 if (pi->jobid == jobnum) {
8138 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8139 return EXIT_FAILURE;
8141 /* TODO: bash prints a string representation
8142 * of job being foregrounded (like "sleep 1 | cat") */
8143 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8144 /* Put the job into the foreground. */
8145 tcsetpgrp(G_interactive_fd, pi->pgrp);
8148 /* Restart the processes in the job */
8149 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8150 for (i = 0; i < pi->num_cmds; i++) {
8151 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8152 pi->cmds[i].is_stopped = 0;
8154 pi->stopped_cmds = 0;
8156 i = kill(- pi->pgrp, SIGCONT);
8158 if (errno == ESRCH) {
8159 delete_finished_bg_job(pi);
8160 return EXIT_SUCCESS;
8162 bb_perror_msg("kill (SIGCONT)");
8165 if (argv[0][0] == 'f') {
8167 return checkjobs_and_fg_shell(pi);
8169 return EXIT_SUCCESS;
8173 #if ENABLE_HUSH_HELP
8174 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8176 const struct built_in_command *x;
8179 "Built-in commands:\n"
8180 "------------------\n");
8181 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8183 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8186 return EXIT_SUCCESS;
8191 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8194 const char *status_string;
8196 for (job = G.job_list; job; job = job->next) {
8197 if (job->alive_cmds == job->stopped_cmds)
8198 status_string = "Stopped";
8200 status_string = "Running";
8202 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8204 return EXIT_SUCCESS;
8209 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8214 # ifdef M_TRIM_THRESHOLD
8215 /* Optional. Reduces probability of false positives */
8218 /* Crude attempt to find where "free memory" starts,
8219 * sans fragmentation. */
8221 l = (unsigned long)p;
8224 if (l < (unsigned long)p) l = (unsigned long)p;
8227 if (!G.memleak_value)
8228 G.memleak_value = l;
8230 l -= G.memleak_value;
8237 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8242 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8245 return EXIT_SUCCESS;
8248 static int FAST_FUNC builtin_read(char **argv)
8257 /* "!": do not abort on errors.
8258 * Option string must start with "sr" to match BUILTIN_READ_xxx
8260 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8261 if (read_flags == (uint32_t)-1)
8262 return EXIT_FAILURE;
8265 r = shell_builtin_read(set_local_var_from_halves,
8267 get_local_var_value("IFS"), /* can be NULL */
8275 if ((uintptr_t)r > 1) {
8276 bb_error_msg("%s", r);
8277 r = (char*)(uintptr_t)1;
8280 return (uintptr_t)r;
8283 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8284 * built-in 'set' handler
8286 * set [-abCefhmnuvx] [-o option] [argument...]
8287 * set [+abCefhmnuvx] [+o option] [argument...]
8288 * set -- [argument...]
8291 * Implementations shall support the options in both their hyphen and
8292 * plus-sign forms. These options can also be specified as options to sh.
8294 * Write out all variables and their values: set
8295 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8296 * Turn on the -x and -v options: set -xv
8297 * Unset all positional parameters: set --
8298 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8299 * Set the positional parameters to the expansion of x, even if x expands
8300 * with a leading '-' or '+': set -- $x
8302 * So far, we only support "set -- [argument...]" and some of the short names.
8304 static int FAST_FUNC builtin_set(char **argv)
8307 char **pp, **g_argv;
8308 char *arg = *++argv;
8312 for (e = G.top_var; e; e = e->next)
8314 return EXIT_SUCCESS;
8318 if (!strcmp(arg, "--")) {
8322 if (arg[0] != '+' && arg[0] != '-')
8324 for (n = 1; arg[n]; ++n)
8325 if (set_mode(arg[0], arg[n]))
8327 } while ((arg = *++argv) != NULL);
8328 /* Now argv[0] is 1st argument */
8331 return EXIT_SUCCESS;
8334 /* NB: G.global_argv[0] ($0) is never freed/changed */
8335 g_argv = G.global_argv;
8336 if (G.global_args_malloced) {
8342 G.global_args_malloced = 1;
8343 pp = xzalloc(sizeof(pp[0]) * 2);
8344 pp[0] = g_argv[0]; /* retain $0 */
8347 /* This realloc's G.global_argv */
8348 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8355 return EXIT_SUCCESS;
8357 /* Nothing known, so abort */
8359 bb_error_msg("set: %s: invalid option", arg);
8360 return EXIT_FAILURE;
8363 static int FAST_FUNC builtin_shift(char **argv)
8366 argv = skip_dash_dash(argv);
8370 if (n >= 0 && n < G.global_argc) {
8371 if (G.global_args_malloced) {
8374 free(G.global_argv[m++]);
8377 memmove(&G.global_argv[1], &G.global_argv[n+1],
8378 G.global_argc * sizeof(G.global_argv[0]));
8379 return EXIT_SUCCESS;
8381 return EXIT_FAILURE;
8384 static int FAST_FUNC builtin_source(char **argv)
8386 char *arg_path, *filename;
8389 #if ENABLE_HUSH_FUNCTIONS
8393 argv = skip_dash_dash(argv);
8396 /* bash says: "bash: .: filename argument required" */
8397 return 2; /* bash compat */
8400 if (!strchr(filename, '/')) {
8401 arg_path = find_in_path(filename);
8403 filename = arg_path;
8405 input = fopen_or_warn(filename, "r");
8408 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8409 return EXIT_FAILURE;
8411 close_on_exec_on(fileno(input));
8413 #if ENABLE_HUSH_FUNCTIONS
8414 sv_flg = G.flag_return_in_progress;
8415 /* "we are inside sourced file, ok to use return" */
8416 G.flag_return_in_progress = -1;
8418 save_and_replace_G_args(&sv, argv);
8420 parse_and_run_file(input);
8423 restore_G_args(&sv, argv);
8424 #if ENABLE_HUSH_FUNCTIONS
8425 G.flag_return_in_progress = sv_flg;
8428 return G.last_exitcode;
8431 static int FAST_FUNC builtin_umask(char **argv)
8437 argv = skip_dash_dash(argv);
8439 mode_t old_mask = mask;
8442 rc = bb_parse_mode(argv[0], &mask);
8447 * bash: umask: 'q': invalid symbolic mode operator
8448 * bash: umask: 999: octal number out of range
8450 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8455 printf("%04o\n", (unsigned) mask);
8456 /* fall through and restore mask which we set to 0 */
8460 return !rc; /* rc != 0 - success */
8463 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8464 static int FAST_FUNC builtin_unset(char **argv)
8469 /* "!": do not abort on errors */
8470 /* "+": stop at 1st non-option */
8471 opts = getopt32(argv, "!+vf");
8472 if (opts == (unsigned)-1)
8473 return EXIT_FAILURE;
8475 bb_error_msg("unset: -v and -f are exclusive");
8476 return EXIT_FAILURE;
8482 if (!(opts & 2)) { /* not -f */
8483 if (unset_local_var(*argv)) {
8484 /* unset <nonexistent_var> doesn't fail.
8485 * Error is when one tries to unset RO var.
8486 * Message was printed by unset_local_var. */
8490 #if ENABLE_HUSH_FUNCTIONS
8500 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8501 static int FAST_FUNC builtin_wait(char **argv)
8503 int ret = EXIT_SUCCESS;
8506 argv = skip_dash_dash(argv);
8507 if (argv[0] == NULL) {
8508 /* Don't care about wait results */
8509 /* Note 1: must wait until there are no more children */
8510 /* Note 2: must be interruptible */
8512 * $ sleep 3 & sleep 6 & wait
8517 * $ sleep 3 & sleep 6 & wait
8521 * ^C <-- after ~4 sec from keyboard
8524 sigaddset(&G.blocked_set, SIGCHLD);
8525 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8528 if (errno == ECHILD)
8530 /* Wait for SIGCHLD or any other signal of interest */
8531 /* sigtimedwait with infinite timeout: */
8532 sig = sigwaitinfo(&G.blocked_set, NULL);
8534 sig = check_and_run_traps(sig);
8535 if (sig && sig != SIGCHLD) { /* see note 2 */
8541 sigdelset(&G.blocked_set, SIGCHLD);
8542 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8546 /* This is probably buggy wrt interruptible-ness */
8548 pid_t pid = bb_strtou(*argv, NULL, 10);
8550 /* mimic bash message */
8551 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8552 return EXIT_FAILURE;
8554 if (waitpid(pid, &status, 0) == pid) {
8555 if (WIFSIGNALED(status))
8556 ret = 128 + WTERMSIG(status);
8557 else if (WIFEXITED(status))
8558 ret = WEXITSTATUS(status);
8562 bb_perror_msg("wait %s", *argv);
8571 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8572 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8575 def = bb_strtou(argv[1], NULL, 10);
8576 if (errno || def < def_min || argv[2]) {
8577 bb_error_msg("%s: bad arguments", argv[0]);
8585 #if ENABLE_HUSH_LOOPS
8586 static int FAST_FUNC builtin_break(char **argv)
8589 if (G.depth_of_loop == 0) {
8590 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8591 return EXIT_SUCCESS; /* bash compat */
8593 G.flag_break_continue++; /* BC_BREAK = 1 */
8595 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8596 if (depth == UINT_MAX)
8597 G.flag_break_continue = BC_BREAK;
8598 if (G.depth_of_loop < depth)
8599 G.depth_break_continue = G.depth_of_loop;
8601 return EXIT_SUCCESS;
8604 static int FAST_FUNC builtin_continue(char **argv)
8606 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8607 return builtin_break(argv);
8611 #if ENABLE_HUSH_FUNCTIONS
8612 static int FAST_FUNC builtin_return(char **argv)
8616 if (G.flag_return_in_progress != -1) {
8617 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8618 return EXIT_FAILURE; /* bash compat */
8621 G.flag_return_in_progress = 1;
8624 * out of range: wraps around at 256, does not error out
8625 * non-numeric param:
8626 * f() { false; return qwe; }; f; echo $?
8627 * bash: return: qwe: numeric argument required <== we do this
8628 * 255 <== we also do this
8630 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);