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_LASH(APPLET(lash, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
107 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
109 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
110 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
113 //config: bool "hush"
116 //config: hush is a small shell (25k). It handles the normal flow control
117 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
118 //config: case/esac. Redirections, here documents, $((arithmetic))
119 //config: and functions are supported.
121 //config: It will compile and work on no-mmu systems.
123 //config: It does not handle select, aliases, brace expansion,
124 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
126 //config:config HUSH_BASH_COMPAT
127 //config: bool "bash-compatible extensions"
129 //config: depends on HUSH
131 //config: Enable bash-compatible extensions.
133 //config:config HUSH_HELP
134 //config: bool "help builtin"
136 //config: depends on HUSH
138 //config: Enable help builtin in hush. Code size + ~1 kbyte.
140 //config:config HUSH_INTERACTIVE
141 //config: bool "Interactive mode"
143 //config: depends on HUSH
145 //config: Enable interactive mode (prompt and command editing).
146 //config: Without this, hush simply reads and executes commands
147 //config: from stdin just like a shell script from a file.
148 //config: No prompt, no PS1/PS2 magic shell variables.
150 //config:config HUSH_JOB
151 //config: bool "Job control"
153 //config: depends on HUSH_INTERACTIVE
155 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
156 //config: command (not entire shell), fg/bg builtins work. Without this option,
157 //config: "cmd &" still works by simply spawning a process and immediately
158 //config: prompting for next command (or executing next command in a script),
159 //config: but no separate process group is formed.
161 //config:config HUSH_TICK
162 //config: bool "Process substitution"
164 //config: depends on HUSH
166 //config: Enable process substitution `command` and $(command) in hush.
168 //config:config HUSH_IF
169 //config: bool "Support if/then/elif/else/fi"
171 //config: depends on HUSH
173 //config: Enable if/then/elif/else/fi in hush.
175 //config:config HUSH_LOOPS
176 //config: bool "Support for, while and until loops"
178 //config: depends on HUSH
180 //config: Enable for, while and until loops in hush.
182 //config:config HUSH_CASE
183 //config: bool "Support case ... esac statement"
185 //config: depends on HUSH
187 //config: Enable case ... esac statement in hush. +400 bytes.
189 //config:config HUSH_FUNCTIONS
190 //config: bool "Support funcname() { commands; } syntax"
192 //config: depends on HUSH
194 //config: Enable support for shell functions in hush. +800 bytes.
196 //config:config HUSH_LOCAL
197 //config: bool "Support local builtin"
199 //config: depends on HUSH_FUNCTIONS
201 //config: Enable support for local variables in functions.
203 //config:config HUSH_RANDOM_SUPPORT
204 //config: bool "Pseudorandom generator and $RANDOM variable"
206 //config: depends on HUSH
208 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
209 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
211 //config:config HUSH_EXPORT_N
212 //config: bool "Support 'export -n' option"
214 //config: depends on HUSH
216 //config: export -n unexports variables. It is a bash extension.
218 //config:config HUSH_MODE_X
219 //config: bool "Support 'hush -x' option and 'set -x' command"
221 //config: depends on HUSH
223 //config: This instructs hush to print commands before execution.
224 //config: Adds ~300 bytes.
227 //config: bool "lash (deprecated: aliased to hush)"
229 //config: select HUSH
231 //config: lash is deprecated and will be removed, please migrate to hush.
234 //config: bool "msh (deprecated: aliased to hush)"
236 //config: select HUSH
238 //config: msh is deprecated and will be removed, please migrate to hush.
241 //usage:#define hush_trivial_usage NOUSAGE_STR
242 //usage:#define hush_full_usage ""
243 //usage:#define lash_trivial_usage NOUSAGE_STR
244 //usage:#define lash_full_usage ""
245 //usage:#define msh_trivial_usage NOUSAGE_STR
246 //usage:#define msh_full_usage ""
250 #define LEAK_HUNTING 0
251 #define BUILD_AS_NOMMU 0
252 /* Enable/disable sanity checks. Ok to enable in production,
253 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
254 * Keeping 1 for now even in released versions.
257 /* Slightly bigger (+200 bytes), but faster hush.
258 * So far it only enables a trick with counting SIGCHLDs and forks,
259 * which allows us to do fewer waitpid's.
260 * (we can detect a case where neither forks were done nor SIGCHLDs happened
261 * and therefore waitpid will return the same result as last time)
263 #define ENABLE_HUSH_FAST 0
264 /* TODO: implement simplified code for users which do not need ${var%...} ops
265 * So far ${var%...} ops are always enabled:
267 #define ENABLE_HUSH_DOLLAR_OPS 1
272 # undef USE_FOR_NOMMU
275 # define USE_FOR_NOMMU(...) __VA_ARGS__
276 # define USE_FOR_MMU(...)
279 #include "NUM_APPLETS.h"
281 /* STANDALONE does not make sense, and won't compile */
282 # undef CONFIG_FEATURE_SH_STANDALONE
283 # undef ENABLE_FEATURE_SH_STANDALONE
284 # undef IF_FEATURE_SH_STANDALONE
285 # undef IF_NOT_FEATURE_SH_STANDALONE
286 # define ENABLE_FEATURE_SH_STANDALONE 0
287 # define IF_FEATURE_SH_STANDALONE(...)
288 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
291 #if !ENABLE_HUSH_INTERACTIVE
292 # undef ENABLE_FEATURE_EDITING
293 # define ENABLE_FEATURE_EDITING 0
294 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
295 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
298 /* Do we support ANY keywords? */
299 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
300 # define HAS_KEYWORDS 1
301 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
302 # define IF_HAS_NO_KEYWORDS(...)
304 # define HAS_KEYWORDS 0
305 # define IF_HAS_KEYWORDS(...)
306 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
309 /* If you comment out one of these below, it will be #defined later
310 * to perform debug printfs to stderr: */
311 #define debug_printf(...) do {} while (0)
312 /* Finer-grained debug switches */
313 #define debug_printf_parse(...) do {} while (0)
314 #define debug_print_tree(a, b) do {} while (0)
315 #define debug_printf_exec(...) do {} while (0)
316 #define debug_printf_env(...) do {} while (0)
317 #define debug_printf_jobs(...) do {} while (0)
318 #define debug_printf_expand(...) do {} while (0)
319 #define debug_printf_varexp(...) do {} while (0)
320 #define debug_printf_glob(...) do {} while (0)
321 #define debug_printf_list(...) do {} while (0)
322 #define debug_printf_subst(...) do {} while (0)
323 #define debug_printf_clean(...) do {} while (0)
325 #define ERR_PTR ((void*)(long)1)
327 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
329 #define _SPECIAL_VARS_STR "_*@$!?#"
330 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
331 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
332 #if ENABLE_HUSH_BASH_COMPAT
333 /* Support / and // replace ops */
334 /* Note that // is stored as \ in "encoded" string representation */
335 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
336 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
337 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
339 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
340 # define VAR_SUBST_OPS "%#:-=+?"
341 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
344 #define SPECIAL_VAR_SYMBOL 3
348 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
350 /* This supports saving pointers malloced in vfork child,
351 * to be freed in the parent.
354 typedef struct nommu_save_t {
356 struct variable *old_vars;
358 char **argv_from_re_execing;
362 typedef enum reserved_style {
371 #if ENABLE_HUSH_LOOPS
378 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
383 /* three pseudo-keywords support contrived "case" syntax: */
384 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
385 RES_MATCH , /* "word)" */
386 RES_CASE_BODY, /* "this command is inside CASE" */
393 typedef struct o_string {
395 int length; /* position where data is appended */
397 /* Protect newly added chars against globbing
398 * (by prepending \ to *, ?, [, \) */
401 /* At least some part of the string was inside '' or "",
402 * possibly empty one: word"", wo''rd etc. */
403 //TODO: rename to no_empty_expansion?
405 smallint has_empty_slot;
406 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
409 MAYBE_ASSIGNMENT = 0,
410 DEFINITELY_ASSIGNMENT = 1,
412 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
414 /* Used for initialization: o_string foo = NULL_O_STRING; */
415 #define NULL_O_STRING { NULL }
417 /* I can almost use ordinary FILE*. Is open_memstream() universally
418 * available? Where is it documented? */
419 typedef struct in_str {
421 /* eof_flag=1: last char in ->p is really an EOF */
422 char eof_flag; /* meaningless if ->p == NULL */
424 #if ENABLE_HUSH_INTERACTIVE
426 smallint promptmode; /* 0: PS1, 1: PS2 */
429 int (*get) (struct in_str *) FAST_FUNC;
430 int (*peek) (struct in_str *) FAST_FUNC;
432 #define i_getch(input) ((input)->get(input))
433 #define i_peek(input) ((input)->peek(input))
435 /* The descrip member of this structure is only used to make
436 * debugging output pretty */
437 static const struct {
439 signed char default_fd;
442 { O_RDONLY, 0, "<" },
443 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
444 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
445 { O_CREAT|O_RDWR, 1, "<>" },
446 { O_RDONLY, 0, "<<" },
447 /* Should not be needed. Bogus default_fd helps in debugging */
448 /* { O_RDONLY, 77, "<<" }, */
451 struct redir_struct {
452 struct redir_struct *next;
453 char *rd_filename; /* filename */
454 int rd_fd; /* fd to redirect */
455 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
457 smallint rd_type; /* (enum redir_type) */
458 /* note: for heredocs, rd_filename contains heredoc delimiter,
459 * and subsequently heredoc itself; and rd_dup is a bitmask:
460 * bit 0: do we need to trim leading tabs?
461 * bit 1: is heredoc quoted (<<'delim' syntax) ?
464 typedef enum redir_type {
466 REDIRECT_OVERWRITE = 1,
469 REDIRECT_HEREDOC = 4,
470 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
473 REDIRFD_SYNTAX_ERR = -2,
474 REDIRFD_TO_FILE = -1,
475 /* otherwise, rd_fd is redirected to rd_dup */
477 HEREDOC_SKIPTABS = 1,
483 pid_t pid; /* 0 if exited */
484 int assignment_cnt; /* how many argv[i] are assignments? */
485 smallint is_stopped; /* is the command currently running? */
486 smallint cmd_type; /* CMD_xxx */
488 #define CMD_SUBSHELL 1
490 /* used for "[[ EXPR ]]" */
491 #if ENABLE_HUSH_BASH_COMPAT
492 # define CMD_SINGLEWORD_NOGLOB 2
495 /* used for "export noglob=* glob* a=`echo a b`" */
496 //#define CMD_SINGLEWORD_NOGLOB_COND 3
497 // It is hard to implement correctly, it adds significant amounts of tricky code,
498 // and all this is only useful for really obscure export statements
499 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
500 // guards the code which implements it, but I have doubts it works
501 // in all cases (especially with mixed globbed/non-globbed arguments)
503 #if ENABLE_HUSH_FUNCTIONS
504 # define CMD_FUNCDEF 3
507 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
510 char *group_as_string;
512 #if ENABLE_HUSH_FUNCTIONS
513 struct function *child_func;
514 /* This field is used to prevent a bug here:
515 * while...do f1() {a;}; f1; f1() {b;}; f1; done
516 * When we execute "f1() {a;}" cmd, we create new function and clear
517 * cmd->group, cmd->group_as_string, cmd->argv[0].
518 * When we execute "f1() {b;}", we notice that f1 exists,
519 * and that its "parent cmd" struct is still "alive",
520 * we put those fields back into cmd->xxx
521 * (struct function has ->parent_cmd ptr to facilitate that).
522 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
523 * Without this trick, loop would execute a;b;b;b;...
524 * instead of correct sequence a;b;a;b;...
525 * When command is freed, it severs the link
526 * (sets ->child_func->parent_cmd to NULL).
529 char **argv; /* command name and arguments */
530 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
531 * and on execution these are substituted with their values.
532 * Substitution can make _several_ words out of one argv[n]!
533 * Example: argv[0]=='.^C*^C.' here: echo .$*.
534 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
536 struct redir_struct *redirects; /* I/O redirections */
538 /* Is there anything in this command at all? */
539 #define IS_NULL_CMD(cmd) \
540 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
545 int num_cmds; /* total number of commands in pipe */
546 int alive_cmds; /* number of commands running (not exited) */
547 int stopped_cmds; /* number of commands alive, but stopped */
549 int jobid; /* job number */
550 pid_t pgrp; /* process group ID for the job */
551 char *cmdtext; /* name of job */
553 struct command *cmds; /* array of commands in pipe */
554 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
555 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
556 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
558 typedef enum pipe_style {
564 /* Is there anything in this pipe at all? */
565 #define IS_NULL_PIPE(pi) \
566 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
568 /* This holds pointers to the various results of parsing */
569 struct parse_context {
570 /* linked list of pipes */
571 struct pipe *list_head;
572 /* last pipe (being constructed right now) */
574 /* last command in pipe (being constructed right now) */
575 struct command *command;
576 /* last redirect in command->redirects list */
577 struct redir_struct *pending_redirect;
583 smallint ctx_inverted; /* "! cmd | cmd" */
585 smallint ctx_dsemicolon; /* ";;" seen */
587 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
589 /* group we are enclosed in:
590 * example: "if pipe1; pipe2; then pipe3; fi"
591 * when we see "if" or "then", we malloc and copy current context,
592 * and make ->stack point to it. then we parse pipeN.
593 * when closing "then" / fi" / whatever is found,
594 * we move list_head into ->stack->command->group,
595 * copy ->stack into current context, and delete ->stack.
596 * (parsing of { list } and ( list ) doesn't use this method)
598 struct parse_context *stack;
602 /* On program start, environ points to initial environment.
603 * putenv adds new pointers into it, unsetenv removes them.
604 * Neither of these (de)allocates the strings.
605 * setenv allocates new strings in malloc space and does putenv,
606 * and thus setenv is unusable (leaky) for shell's purposes */
607 #define setenv(...) setenv_is_leaky_dont_use()
609 struct variable *next;
610 char *varstr; /* points to "name=" portion */
611 #if ENABLE_HUSH_LOCAL
612 unsigned func_nest_level;
614 int max_len; /* if > 0, name is part of initial env; else name is malloced */
615 smallint flg_export; /* putenv should be done on this var */
616 smallint flg_read_only;
624 #if ENABLE_HUSH_FUNCTIONS
626 struct function *next;
628 struct command *parent_cmd;
631 char *body_as_string;
637 /* "Globals" within this file */
638 /* Sorted roughly by size (smaller offsets == smaller code) */
640 /* interactive_fd != 0 means we are an interactive shell.
641 * If we are, then saved_tty_pgrp can also be != 0, meaning
642 * that controlling tty is available. With saved_tty_pgrp == 0,
643 * job control still works, but terminal signals
644 * (^C, ^Z, ^Y, ^\) won't work at all, and background
645 * process groups can only be created with "cmd &".
646 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
647 * to give tty to the foreground process group,
648 * and will take it back when the group is stopped (^Z)
651 #if ENABLE_HUSH_INTERACTIVE
652 /* 'interactive_fd' is a fd# open to ctty, if we have one
653 * _AND_ if we decided to act interactively */
657 # define G_interactive_fd (G.interactive_fd)
659 # define G_interactive_fd 0
661 #if ENABLE_FEATURE_EDITING
662 line_input_t *line_input_state;
667 #if ENABLE_HUSH_RANDOM_SUPPORT
673 pid_t saved_tty_pgrp;
674 struct pipe *job_list;
675 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
677 # define G_saved_tty_pgrp 0
679 smallint flag_SIGINT;
680 #if ENABLE_HUSH_LOOPS
681 smallint flag_break_continue;
683 #if ENABLE_HUSH_FUNCTIONS
684 /* 0: outside of a function (or sourced file)
685 * -1: inside of a function, ok to use return builtin
686 * 1: return is invoked, skip all till end of func
688 smallint flag_return_in_progress;
691 #if ENABLE_HUSH_MODE_X
693 # define G_x_mode (G.x_mode)
697 smallint exiting; /* used to prevent EXIT trap recursion */
698 /* These four support $?, $#, and $1 */
699 smalluint last_exitcode;
700 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
701 smalluint global_args_malloced;
702 smalluint inherited_set_is_saved;
703 /* how many non-NULL argv's we have. NB: $# + 1 */
707 char *argv0_for_re_execing;
709 #if ENABLE_HUSH_LOOPS
710 unsigned depth_break_continue;
711 unsigned depth_of_loop;
715 struct variable *top_var; /* = &G.shell_ver (set in main()) */
716 struct variable shell_ver;
717 char **expanded_assignments;
718 #if ENABLE_HUSH_FUNCTIONS
719 struct function *top_func;
720 # if ENABLE_HUSH_LOCAL
721 struct variable **shadowed_vars_pp;
722 unsigned func_nest_level;
725 /* Signal and trap handling */
727 unsigned count_SIGCHLD;
728 unsigned handled_SIGCHLD;
729 smallint we_have_children;
731 /* which signals have non-DFL handler (even with no traps set)? */
732 unsigned non_DFL_mask;
733 char **traps; /* char *traps[NSIG] */
734 sigset_t blocked_set;
735 sigset_t inherited_set;
737 unsigned long memleak_value;
740 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
742 #define G (*ptr_to_globals)
743 /* Not #defining name to G.name - this quickly gets unwieldy
744 * (too many defines). Also, I actually prefer to see when a variable
745 * is global, thus "G." prefix is a useful hint */
746 #define INIT_G() do { \
747 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
751 /* Function prototypes for builtins */
752 static int builtin_cd(char **argv) FAST_FUNC;
753 static int builtin_echo(char **argv) FAST_FUNC;
754 static int builtin_eval(char **argv) FAST_FUNC;
755 static int builtin_exec(char **argv) FAST_FUNC;
756 static int builtin_exit(char **argv) FAST_FUNC;
757 static int builtin_export(char **argv) FAST_FUNC;
759 static int builtin_fg_bg(char **argv) FAST_FUNC;
760 static int builtin_jobs(char **argv) FAST_FUNC;
763 static int builtin_help(char **argv) FAST_FUNC;
765 #if ENABLE_HUSH_LOCAL
766 static int builtin_local(char **argv) FAST_FUNC;
769 static int builtin_memleak(char **argv) FAST_FUNC;
772 static int builtin_printf(char **argv) FAST_FUNC;
774 static int builtin_pwd(char **argv) FAST_FUNC;
775 static int builtin_read(char **argv) FAST_FUNC;
776 static int builtin_set(char **argv) FAST_FUNC;
777 static int builtin_shift(char **argv) FAST_FUNC;
778 static int builtin_source(char **argv) FAST_FUNC;
779 static int builtin_test(char **argv) FAST_FUNC;
780 static int builtin_trap(char **argv) FAST_FUNC;
781 static int builtin_type(char **argv) FAST_FUNC;
782 static int builtin_true(char **argv) FAST_FUNC;
783 static int builtin_umask(char **argv) FAST_FUNC;
784 static int builtin_unset(char **argv) FAST_FUNC;
785 static int builtin_wait(char **argv) FAST_FUNC;
786 #if ENABLE_HUSH_LOOPS
787 static int builtin_break(char **argv) FAST_FUNC;
788 static int builtin_continue(char **argv) FAST_FUNC;
790 #if ENABLE_HUSH_FUNCTIONS
791 static int builtin_return(char **argv) FAST_FUNC;
794 /* Table of built-in functions. They can be forked or not, depending on
795 * context: within pipes, they fork. As simple commands, they do not.
796 * When used in non-forking context, they can change global variables
797 * in the parent shell process. If forked, of course they cannot.
798 * For example, 'unset foo | whatever' will parse and run, but foo will
799 * still be set at the end. */
800 struct built_in_command {
802 int (*b_function)(char **argv) FAST_FUNC;
805 # define BLTIN(cmd, func, help) { cmd, func, help }
807 # define BLTIN(cmd, func, help) { cmd, func }
811 static const struct built_in_command bltins1[] = {
812 BLTIN("." , builtin_source , "Run commands in a file"),
813 BLTIN(":" , builtin_true , NULL),
815 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
817 #if ENABLE_HUSH_LOOPS
818 BLTIN("break" , builtin_break , "Exit from a loop"),
820 BLTIN("cd" , builtin_cd , "Change directory"),
821 #if ENABLE_HUSH_LOOPS
822 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
824 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
825 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
826 BLTIN("exit" , builtin_exit , "Exit"),
827 BLTIN("export" , builtin_export , "Set environment variables"),
829 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
832 BLTIN("help" , builtin_help , NULL),
835 BLTIN("jobs" , builtin_jobs , "List jobs"),
837 #if ENABLE_HUSH_LOCAL
838 BLTIN("local" , builtin_local , "Set local variables"),
841 BLTIN("memleak" , builtin_memleak , NULL),
843 BLTIN("read" , builtin_read , "Input into variable"),
844 #if ENABLE_HUSH_FUNCTIONS
845 BLTIN("return" , builtin_return , "Return from a function"),
847 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
848 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
849 #if ENABLE_HUSH_BASH_COMPAT
850 BLTIN("source" , builtin_source , "Run commands in a file"),
852 BLTIN("trap" , builtin_trap , "Trap signals"),
853 BLTIN("type" , builtin_type , "Show command type"),
854 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
855 BLTIN("umask" , builtin_umask , "Set file creation mask"),
856 BLTIN("unset" , builtin_unset , "Unset variables"),
857 BLTIN("wait" , builtin_wait , "Wait for process"),
859 /* For now, echo and test are unconditionally enabled.
860 * Maybe make it configurable? */
861 static const struct built_in_command bltins2[] = {
862 BLTIN("[" , builtin_test , NULL),
863 BLTIN("echo" , builtin_echo , NULL),
865 BLTIN("printf" , builtin_printf , NULL),
867 BLTIN("pwd" , builtin_pwd , NULL),
868 BLTIN("test" , builtin_test , NULL),
875 /* prevent disasters with G.debug_indent < 0 */
876 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
877 # define debug_enter() (G.debug_indent++)
878 # define debug_leave() (G.debug_indent--)
880 # define indent() ((void)0)
881 # define debug_enter() ((void)0)
882 # define debug_leave() ((void)0)
886 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
889 #ifndef debug_printf_parse
890 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
893 #ifndef debug_printf_exec
894 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
897 #ifndef debug_printf_env
898 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
901 #ifndef debug_printf_jobs
902 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
903 # define DEBUG_JOBS 1
905 # define DEBUG_JOBS 0
908 #ifndef debug_printf_expand
909 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
910 # define DEBUG_EXPAND 1
912 # define DEBUG_EXPAND 0
915 #ifndef debug_printf_varexp
916 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
919 #ifndef debug_printf_glob
920 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
921 # define DEBUG_GLOB 1
923 # define DEBUG_GLOB 0
926 #ifndef debug_printf_list
927 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
930 #ifndef debug_printf_subst
931 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
934 #ifndef debug_printf_clean
935 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
936 # define DEBUG_CLEAN 1
938 # define DEBUG_CLEAN 0
942 static void debug_print_strings(const char *prefix, char **vv)
945 fprintf(stderr, "%s:\n", prefix);
947 fprintf(stderr, " '%s'\n", *vv++);
950 # define debug_print_strings(prefix, vv) ((void)0)
954 /* Leak hunting. Use hush_leaktool.sh for post-processing.
957 static void *xxmalloc(int lineno, size_t size)
959 void *ptr = xmalloc((size + 0xff) & ~0xff);
960 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
963 static void *xxrealloc(int lineno, void *ptr, size_t size)
965 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
966 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
969 static char *xxstrdup(int lineno, const char *str)
971 char *ptr = xstrdup(str);
972 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
975 static void xxfree(void *ptr)
977 fdprintf(2, "free %p\n", ptr);
980 # define xmalloc(s) xxmalloc(__LINE__, s)
981 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
982 # define xstrdup(s) xxstrdup(__LINE__, s)
983 # define free(p) xxfree(p)
987 /* Syntax and runtime errors. They always abort scripts.
988 * In interactive use they usually discard unparsed and/or unexecuted commands
989 * and return to the prompt.
990 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
993 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
994 # define syntax_error(lineno, msg) syntax_error(msg)
995 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
996 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
997 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
998 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1001 static void die_if_script(unsigned lineno, const char *fmt, ...)
1006 bb_error_msg("hush.c:%u", lineno);
1009 bb_verror_msg(fmt, p, NULL);
1011 if (!G_interactive_fd)
1015 static void syntax_error(unsigned lineno, const char *msg)
1018 die_if_script(lineno, "syntax error: %s", msg);
1020 die_if_script(lineno, "syntax error", NULL);
1023 static void syntax_error_at(unsigned lineno, const char *msg)
1025 die_if_script(lineno, "syntax error at '%s'", msg);
1028 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1030 die_if_script(lineno, "syntax error: unterminated %s", s);
1033 /* It so happens that all such cases are totally fatal
1034 * even if shell is interactive: EOF while looking for closing
1035 * delimiter. There is nowhere to read stuff from after that,
1036 * it's EOF! The only choice is to terminate.
1038 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1039 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1041 char msg[2] = { ch, '\0' };
1042 syntax_error_unterm_str(lineno, msg);
1046 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1051 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1055 # undef die_if_script
1056 # undef syntax_error
1057 # undef syntax_error_at
1058 # undef syntax_error_unterm_ch
1059 # undef syntax_error_unterm_str
1060 # undef syntax_error_unexpected_ch
1062 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1063 # define syntax_error(msg) syntax_error(__LINE__, msg)
1064 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1065 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1066 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1067 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1071 #if ENABLE_HUSH_INTERACTIVE
1072 static void cmdedit_update_prompt(void);
1074 # define cmdedit_update_prompt() ((void)0)
1078 /* Utility functions
1080 /* Replace each \x with x in place, return ptr past NUL. */
1081 static char *unbackslash(char *src)
1083 char *dst = src = strchrnul(src, '\\');
1087 if ((*dst++ = *src++) == '\0')
1093 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1114 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1115 v[count1 + count2] = NULL;
1118 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1122 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1124 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1125 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1128 #define add_strings_to_strings(strings, add, need_to_dup) \
1129 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1132 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1133 static char **add_string_to_strings(char **strings, char *add)
1138 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1141 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1143 char **ptr = add_string_to_strings(strings, add);
1144 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1147 #define add_string_to_strings(strings, add) \
1148 xx_add_string_to_strings(__LINE__, strings, add)
1151 static void free_strings(char **strings)
1166 /* Helpers for setting new $n and restoring them back
1168 typedef struct save_arg_t {
1172 smallint sv_g_malloced;
1175 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1179 sv->sv_argv0 = argv[0];
1180 sv->sv_g_argv = G.global_argv;
1181 sv->sv_g_argc = G.global_argc;
1182 sv->sv_g_malloced = G.global_args_malloced;
1184 argv[0] = G.global_argv[0]; /* retain $0 */
1185 G.global_argv = argv;
1186 G.global_args_malloced = 0;
1194 static void restore_G_args(save_arg_t *sv, char **argv)
1198 if (G.global_args_malloced) {
1199 /* someone ran "set -- arg1 arg2 ...", undo */
1201 while (*++pp) /* note: does not free $0 */
1203 free(G.global_argv);
1205 argv[0] = sv->sv_argv0;
1206 G.global_argv = sv->sv_g_argv;
1207 G.global_argc = sv->sv_g_argc;
1208 G.global_args_malloced = sv->sv_g_malloced;
1212 /* Basic theory of signal handling in shell
1213 * ========================================
1214 * This does not describe what hush does, rather, it is current understanding
1215 * what it _should_ do. If it doesn't, it's a bug.
1216 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1218 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1219 * is finished or backgrounded. It is the same in interactive and
1220 * non-interactive shells, and is the same regardless of whether
1221 * a user trap handler is installed or a shell special one is in effect.
1222 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1223 * backgrounds (i.e. stops) or kills all members of currently running
1226 * Wait builtin in interruptible by signals for which user trap is set
1227 * or by SIGINT in interactive shell.
1229 * Trap handlers will execute even within trap handlers. (right?)
1231 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1232 * except for handlers set to '' (empty string).
1234 * If job control is off, backgrounded commands ("cmd &")
1235 * have SIGINT, SIGQUIT set to SIG_IGN.
1237 * Commands which are run in command substitution ("`cmd`")
1238 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1240 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1241 * by the shell from its parent.
1243 * Signals which differ from SIG_DFL action
1244 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1247 * SIGTERM (interactive): ignore
1248 * SIGHUP (interactive):
1249 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1250 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1251 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1252 * that all pipe members are stopped. Try this in bash:
1253 * while :; do :; done - ^Z does not background it
1254 * (while :; do :; done) - ^Z backgrounds it
1255 * SIGINT (interactive): wait for last pipe, ignore the rest
1256 * of the command line, show prompt. NB: ^C does not send SIGINT
1257 * to interactive shell while shell is waiting for a pipe,
1258 * since shell is bg'ed (is not in foreground process group).
1259 * Example 1: this waits 5 sec, but does not execute ls:
1260 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1261 * Example 2: this does not wait and does not execute ls:
1262 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1263 * Example 3: this does not wait 5 sec, but executes ls:
1264 * "sleep 5; ls -l" + press ^C
1266 * (What happens to signals which are IGN on shell start?)
1267 * (What happens with signal mask on shell start?)
1269 * Implementation in hush
1270 * ======================
1271 * We use in-kernel pending signal mask to determine which signals were sent.
1272 * We block all signals which we don't want to take action immediately,
1273 * i.e. we block all signals which need to have special handling as described
1274 * above, and all signals which have traps set.
1275 * After each pipe execution, we extract any pending signals via sigtimedwait()
1278 * unsigned non_DFL_mask: a mask of such "special" signals
1279 * sigset_t blocked_set: current blocked signal set
1282 * clear bit in blocked_set unless it is also in non_DFL_mask
1283 * "trap 'cmd' SIGxxx":
1284 * set bit in blocked_set (even if 'cmd' is '')
1285 * after [v]fork, if we plan to be a shell:
1286 * unblock signals with special interactive handling
1287 * (child shell is not interactive),
1288 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1289 * after [v]fork, if we plan to exec:
1290 * POSIX says fork clears pending signal mask in child - no need to clear it.
1291 * Restore blocked signal set to one inherited by shell just prior to exec.
1293 * Note: as a result, we do not use signal handlers much. The only uses
1294 * are to count SIGCHLDs
1295 * and to restore tty pgrp on signal-induced exit.
1298 * Standard says "When a subshell is entered, traps that are not being ignored
1299 * are set to the default actions". bash interprets it so that traps which
1300 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1303 SPECIAL_INTERACTIVE_SIGS = 0
1308 SPECIAL_JOB_SIGS = 0
1316 #if ENABLE_HUSH_FAST
1317 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1320 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1326 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1327 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1328 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1329 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1331 /* Restores tty foreground process group, and exits.
1332 * May be called as signal handler for fatal signal
1333 * (will resend signal to itself, producing correct exit state)
1334 * or called directly with -EXITCODE.
1335 * We also call it if xfunc is exiting. */
1336 static void sigexit(int sig) NORETURN;
1337 static void sigexit(int sig)
1339 /* Disable all signals: job control, SIGPIPE, etc. */
1340 sigprocmask_allsigs(SIG_BLOCK);
1342 /* Careful: we can end up here after [v]fork. Do not restore
1343 * tty pgrp then, only top-level shell process does that */
1344 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1345 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1347 /* Not a signal, just exit */
1351 kill_myself_with_sig(sig); /* does not return */
1355 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1356 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1360 /* Restores tty foreground process group, and exits. */
1361 static void hush_exit(int exitcode) NORETURN;
1362 static void hush_exit(int exitcode)
1364 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1365 /* Prevent recursion:
1366 * trap "echo Hi; exit" EXIT; exit
1368 char *argv[] = { NULL, G.traps[0], NULL };
1377 sigexit(- (exitcode & 0xff));
1383 static int check_and_run_traps(int sig)
1385 static const struct timespec zero_timespec;
1386 smalluint save_rcode;
1392 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1397 if (G.traps && G.traps[sig]) {
1398 if (G.traps[sig][0]) {
1399 /* We have user-defined handler */
1400 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1401 save_rcode = G.last_exitcode;
1404 G.last_exitcode = save_rcode;
1405 } /* else: "" trap, ignoring signal */
1408 /* not a trap: special action */
1410 #if ENABLE_HUSH_FAST
1413 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1417 /* Builtin was ^C'ed, make it look prettier: */
1424 /* bash is observed to signal whole process groups,
1425 * not individual processes */
1426 for (job = G.job_list; job; job = job->next) {
1429 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1430 if (kill(- job->pgrp, SIGHUP) == 0)
1431 kill(- job->pgrp, SIGCONT);
1436 default: /* ignored: */
1437 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1445 static const char *get_cwd(int force)
1447 if (force || G.cwd == NULL) {
1448 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1449 * we must not try to free(bb_msg_unknown) */
1450 if (G.cwd == bb_msg_unknown)
1452 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1454 G.cwd = bb_msg_unknown;
1461 * Shell and environment variable support
1463 static struct variable **get_ptr_to_local_var(const char *name)
1465 struct variable **pp;
1466 struct variable *cur;
1471 while ((cur = *pp) != NULL) {
1472 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1479 static struct variable *get_local_var(const char *name)
1481 struct variable **pp = get_ptr_to_local_var(name);
1487 static const char* FAST_FUNC get_local_var_value(const char *name)
1489 struct variable **vpp;
1491 if (G.expanded_assignments) {
1492 char **cpp = G.expanded_assignments;
1493 int len = strlen(name);
1496 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1497 return cp + len + 1;
1502 vpp = get_ptr_to_local_var(name);
1504 return strchr((*vpp)->varstr, '=') + 1;
1506 if (strcmp(name, "PPID") == 0)
1507 return utoa(G.root_ppid);
1508 // bash compat: UID? EUID?
1509 #if ENABLE_HUSH_RANDOM_SUPPORT
1510 if (strcmp(name, "RANDOM") == 0) {
1511 return utoa(next_random(&G.random_gen));
1517 /* str holds "NAME=VAL" and is expected to be malloced.
1518 * We take ownership of it.
1520 * 0: do not change export flag
1521 * (if creating new variable, flag will be 0)
1522 * 1: set export flag and putenv the variable
1523 * -1: clear export flag and unsetenv the variable
1524 * flg_read_only is set only when we handle -R var=val
1526 #if !BB_MMU && ENABLE_HUSH_LOCAL
1527 /* all params are used */
1528 #elif BB_MMU && ENABLE_HUSH_LOCAL
1529 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1530 set_local_var(str, flg_export, local_lvl)
1531 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1532 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1533 set_local_var(str, flg_export)
1534 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1535 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1536 set_local_var(str, flg_export, flg_read_only)
1538 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1540 struct variable **var_pp;
1541 struct variable *cur;
1545 eq_sign = strchr(str, '=');
1546 if (!eq_sign) { /* not expected to ever happen? */
1551 name_len = eq_sign - str + 1; /* including '=' */
1552 var_pp = &G.top_var;
1553 while ((cur = *var_pp) != NULL) {
1554 if (strncmp(cur->varstr, str, name_len) != 0) {
1555 var_pp = &cur->next;
1558 /* We found an existing var with this name */
1559 if (cur->flg_read_only) {
1563 bb_error_msg("%s: readonly variable", str);
1567 if (flg_export == -1) { // "&& cur->flg_export" ?
1568 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1573 #if ENABLE_HUSH_LOCAL
1574 if (cur->func_nest_level < local_lvl) {
1575 /* New variable is declared as local,
1576 * and existing one is global, or local
1577 * from enclosing function.
1578 * Remove and save old one: */
1579 *var_pp = cur->next;
1580 cur->next = *G.shadowed_vars_pp;
1581 *G.shadowed_vars_pp = cur;
1582 /* bash 3.2.33(1) and exported vars:
1584 * # f() { local z=a; env | grep ^z; }
1590 if (cur->flg_export)
1595 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1600 if (cur->max_len != 0) {
1601 if (cur->max_len >= strlen(str)) {
1602 /* This one is from startup env, reuse space */
1603 strcpy(cur->varstr, str);
1607 /* max_len == 0 signifies "malloced" var, which we can
1608 * (and has to) free */
1612 goto set_str_and_exp;
1615 /* Not found - create new variable struct */
1616 cur = xzalloc(sizeof(*cur));
1617 #if ENABLE_HUSH_LOCAL
1618 cur->func_nest_level = local_lvl;
1620 cur->next = *var_pp;
1626 cur->flg_read_only = flg_read_only;
1629 if (flg_export == 1)
1630 cur->flg_export = 1;
1631 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1632 cmdedit_update_prompt();
1633 if (cur->flg_export) {
1634 if (flg_export == -1) {
1635 cur->flg_export = 0;
1636 /* unsetenv was already done */
1638 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1639 return putenv(cur->varstr);
1645 /* Used at startup and after each cd */
1646 static void set_pwd_var(int exp)
1648 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1649 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1652 static int unset_local_var_len(const char *name, int name_len)
1654 struct variable *cur;
1655 struct variable **var_pp;
1658 return EXIT_SUCCESS;
1659 var_pp = &G.top_var;
1660 while ((cur = *var_pp) != NULL) {
1661 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1662 if (cur->flg_read_only) {
1663 bb_error_msg("%s: readonly variable", name);
1664 return EXIT_FAILURE;
1666 *var_pp = cur->next;
1667 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1668 bb_unsetenv(cur->varstr);
1669 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1670 cmdedit_update_prompt();
1674 return EXIT_SUCCESS;
1676 var_pp = &cur->next;
1678 return EXIT_SUCCESS;
1681 static int unset_local_var(const char *name)
1683 return unset_local_var_len(name, strlen(name));
1686 static void unset_vars(char **strings)
1694 const char *eq = strchrnul(*v, '=');
1695 unset_local_var_len(*v, (int)(eq - *v));
1701 #if ENABLE_SH_MATH_SUPPORT
1702 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1703 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1704 static char* FAST_FUNC endofname(const char *name)
1712 if (!is_in_name(*p))
1719 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1721 char *var = xasprintf("%s=%s", name, val);
1722 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1727 * Helpers for "var1=val1 var2=val2 cmd" feature
1729 static void add_vars(struct variable *var)
1731 struct variable *next;
1735 var->next = G.top_var;
1737 if (var->flg_export) {
1738 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1739 putenv(var->varstr);
1741 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1747 static struct variable *set_vars_and_save_old(char **strings)
1750 struct variable *old = NULL;
1756 struct variable *var_p;
1757 struct variable **var_pp;
1760 eq = strchr(*s, '=');
1763 var_pp = get_ptr_to_local_var(*s);
1766 /* Remove variable from global linked list */
1768 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1769 *var_pp = var_p->next;
1770 /* Add it to returned list */
1774 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1785 static int FAST_FUNC static_get(struct in_str *i)
1795 static int FAST_FUNC static_peek(struct in_str *i)
1800 #if ENABLE_HUSH_INTERACTIVE
1802 static void cmdedit_update_prompt(void)
1804 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1805 G.PS1 = get_local_var_value("PS1");
1808 G.PS2 = get_local_var_value("PS2");
1816 static const char* setup_prompt_string(int promptmode)
1818 const char *prompt_str;
1819 debug_printf("setup_prompt_string %d ", promptmode);
1820 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1821 /* Set up the prompt */
1822 if (promptmode == 0) { /* PS1 */
1824 /* bash uses $PWD value, even if it is set by user.
1825 * It uses current dir only if PWD is unset.
1826 * We always use current dir. */
1827 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1832 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1833 debug_printf("result '%s'\n", prompt_str);
1837 static void get_user_input(struct in_str *i)
1840 const char *prompt_str;
1842 prompt_str = setup_prompt_string(i->promptmode);
1843 # if ENABLE_FEATURE_EDITING
1844 /* Enable command line editing only while a command line
1845 * is actually being read */
1848 /* buglet: SIGINT will not make new prompt to appear _at once_,
1849 * only after <Enter>. (^C will work) */
1850 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1851 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1852 check_and_run_traps(0);
1853 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1854 i->eof_flag = (r < 0);
1855 if (i->eof_flag) { /* EOF/error detected */
1856 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1857 G.user_input_buf[1] = '\0';
1862 fputs(prompt_str, stdout);
1864 G.user_input_buf[0] = r = fgetc(i->file);
1865 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1866 //do we need check_and_run_traps(0)? (maybe only if stdin)
1867 } while (G.flag_SIGINT);
1868 i->eof_flag = (r == EOF);
1870 i->p = G.user_input_buf;
1873 #endif /* INTERACTIVE */
1875 /* This is the magic location that prints prompts
1876 * and gets data back from the user */
1877 static int FAST_FUNC file_get(struct in_str *i)
1881 /* If there is data waiting, eat it up */
1882 if (i->p && *i->p) {
1883 #if ENABLE_HUSH_INTERACTIVE
1887 if (i->eof_flag && !*i->p)
1889 /* note: ch is never NUL */
1891 /* need to double check i->file because we might be doing something
1892 * more complicated by now, like sourcing or substituting. */
1893 #if ENABLE_HUSH_INTERACTIVE
1894 if (G_interactive_fd && i->promptme && i->file == stdin) {
1897 } while (!*i->p); /* need non-empty line */
1898 i->promptmode = 1; /* PS2 */
1903 do ch = fgetc(i->file); while (ch == '\0');
1905 debug_printf("file_get: got '%c' %d\n", ch, ch);
1906 #if ENABLE_HUSH_INTERACTIVE
1913 /* All callers guarantee this routine will never
1914 * be used right after a newline, so prompting is not needed.
1916 static int FAST_FUNC file_peek(struct in_str *i)
1919 if (i->p && *i->p) {
1920 if (i->eof_flag && !i->p[1])
1923 /* note: ch is never NUL */
1925 do ch = fgetc(i->file); while (ch == '\0');
1926 i->eof_flag = (ch == EOF);
1927 i->peek_buf[0] = ch;
1928 i->peek_buf[1] = '\0';
1930 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1934 static void setup_file_in_str(struct in_str *i, FILE *f)
1936 i->peek = file_peek;
1938 #if ENABLE_HUSH_INTERACTIVE
1940 i->promptmode = 0; /* PS1 */
1946 static void setup_string_in_str(struct in_str *i, const char *s)
1948 i->peek = static_peek;
1949 i->get = static_get;
1950 #if ENABLE_HUSH_INTERACTIVE
1952 i->promptmode = 0; /* PS1 */
1962 #define B_CHUNK (32 * sizeof(char*))
1964 static void o_reset_to_empty_unquoted(o_string *o)
1972 static void o_free(o_string *o)
1975 memset(o, 0, sizeof(*o));
1978 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1983 static void o_grow_by(o_string *o, int len)
1985 if (o->length + len > o->maxlen) {
1986 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1987 o->data = xrealloc(o->data, 1 + o->maxlen);
1991 static void o_addchr(o_string *o, int ch)
1993 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1995 o->data[o->length] = ch;
1997 o->data[o->length] = '\0';
2000 static void o_addblock(o_string *o, const char *str, int len)
2003 memcpy(&o->data[o->length], str, len);
2005 o->data[o->length] = '\0';
2008 static void o_addstr(o_string *o, const char *str)
2010 o_addblock(o, str, strlen(str));
2014 static void nommu_addchr(o_string *o, int ch)
2020 # define nommu_addchr(o, str) ((void)0)
2023 static void o_addstr_with_NUL(o_string *o, const char *str)
2025 o_addblock(o, str, strlen(str) + 1);
2028 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2040 #undef HUSH_BRACE_EXP
2042 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2043 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2044 * Apparently, on unquoted $v bash still does globbing
2045 * ("v='*.txt'; echo $v" prints all .txt files),
2046 * but NOT brace expansion! Thus, there should be TWO independent
2047 * quoting mechanisms on $v expansion side: one protects
2048 * $v from brace expansion, and other additionally protects "$v" against globbing.
2049 * We have only second one.
2052 #ifdef HUSH_BRACE_EXP
2053 # define MAYBE_BRACES "{}"
2055 # define MAYBE_BRACES ""
2058 /* My analysis of quoting semantics tells me that state information
2059 * is associated with a destination, not a source.
2061 static void o_addqchr(o_string *o, int ch)
2064 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2069 o->data[o->length] = '\\';
2072 o->data[o->length] = ch;
2074 o->data[o->length] = '\0';
2077 static void o_addQchr(o_string *o, int ch)
2080 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2082 o->data[o->length] = '\\';
2086 o->data[o->length] = ch;
2088 o->data[o->length] = '\0';
2091 static void o_addQstr(o_string *o, const char *str, int len)
2094 o_addblock(o, str, len);
2100 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2101 if (ordinary_cnt > len) /* paranoia */
2103 o_addblock(o, str, ordinary_cnt);
2104 if (ordinary_cnt == len)
2106 str += ordinary_cnt;
2107 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2111 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2113 o->data[o->length] = '\\';
2117 o->data[o->length] = ch;
2119 o->data[o->length] = '\0';
2123 /* A special kind of o_string for $VAR and `cmd` expansion.
2124 * It contains char* list[] at the beginning, which is grown in 16 element
2125 * increments. Actual string data starts at the next multiple of 16 * (char*).
2126 * list[i] contains an INDEX (int!) into this string data.
2127 * It means that if list[] needs to grow, data needs to be moved higher up
2128 * but list[i]'s need not be modified.
2129 * NB: remembering how many list[i]'s you have there is crucial.
2130 * o_finalize_list() operation post-processes this structure - calculates
2131 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2133 #if DEBUG_EXPAND || DEBUG_GLOB
2134 static void debug_print_list(const char *prefix, o_string *o, int n)
2136 char **list = (char**)o->data;
2137 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2141 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2142 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->o_quoted, o->o_escape);
2145 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2146 o->data + (int)list[i] + string_start,
2147 o->data + (int)list[i] + string_start);
2151 const char *p = o->data + (int)list[n - 1] + string_start;
2153 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2157 # define debug_print_list(prefix, o, n) ((void)0)
2160 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2161 * in list[n] so that it points past last stored byte so far.
2162 * It returns n+1. */
2163 static int o_save_ptr_helper(o_string *o, int n)
2165 char **list = (char**)o->data;
2169 if (!o->has_empty_slot) {
2170 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2171 string_len = o->length - string_start;
2172 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2173 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2174 /* list[n] points to string_start, make space for 16 more pointers */
2175 o->maxlen += 0x10 * sizeof(list[0]);
2176 o->data = xrealloc(o->data, o->maxlen + 1);
2177 list = (char**)o->data;
2178 memmove(list + n + 0x10, list + n, string_len);
2179 o->length += 0x10 * sizeof(list[0]);
2181 debug_printf_list("list[%d]=%d string_start=%d\n",
2182 n, string_len, string_start);
2185 /* We have empty slot at list[n], reuse without growth */
2186 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2187 string_len = o->length - string_start;
2188 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2189 n, string_len, string_start);
2190 o->has_empty_slot = 0;
2192 list[n] = (char*)(ptrdiff_t)string_len;
2196 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2197 static int o_get_last_ptr(o_string *o, int n)
2199 char **list = (char**)o->data;
2200 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2202 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2205 #ifdef HUSH_BRACE_EXP
2206 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2207 * first, it processes even {a} (no commas), second,
2208 * I didn't manage to make it return strings when they don't match
2209 * existing files. Need to re-implement it.
2213 static int glob_needed(const char *s)
2222 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2228 /* Return pointer to next closing brace or to comma */
2229 static const char *next_brace_sub(const char *cp)
2233 while (*cp != '\0') {
2240 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2242 if (*cp++ == '{') /*}*/
2246 return *cp != '\0' ? cp : NULL;
2248 /* Recursive brace globber. Note: may garble pattern[]. */
2249 static int glob_brace(char *pattern, o_string *o, int n)
2251 char *new_pattern_buf;
2258 debug_printf_glob("glob_brace('%s')\n", pattern);
2264 if (*begin == '{') /*}*/ {
2265 /* Find the first sub-pattern and at the same time
2266 * find the rest after the closing brace */
2267 next = next_brace_sub(begin);
2269 /* An illegal expression */
2272 /*{*/ if (*next == '}') {
2273 /* "{abc}" with no commas - illegal
2274 * brace expr, disregard and skip it */
2280 if (*begin == '\\' && begin[1] != '\0')
2284 debug_printf_glob("begin:%s\n", begin);
2285 debug_printf_glob("next:%s\n", next);
2287 /* Now find the end of the whole brace expression */
2289 /*{*/ while (*rest != '}') {
2290 rest = next_brace_sub(rest);
2292 /* An illegal expression */
2295 debug_printf_glob("rest:%s\n", rest);
2297 rest_len = strlen(++rest) + 1;
2299 /* We are sure the brace expression is well-formed */
2301 /* Allocate working buffer large enough for our work */
2302 new_pattern_buf = xmalloc(strlen(pattern));
2304 /* We have a brace expression. BEGIN points to the opening {,
2305 * NEXT points past the terminator of the first element, and REST
2306 * points past the final }. We will accumulate result names from
2307 * recursive runs for each brace alternative in the buffer using
2312 /* Construct the new glob expression */
2315 mempcpy(new_pattern_buf,
2316 /* We know the prefix for all sub-patterns */
2317 pattern, begin - pattern),
2321 /* Note: glob_brace() may garble new_pattern_buf[].
2322 * That's why we re-copy prefix every time (1st memcpy above).
2324 n = glob_brace(new_pattern_buf, o, n);
2325 /*{*/ if (*next == '}') {
2326 /* We saw the last entry */
2330 next = next_brace_sub(next);
2332 free(new_pattern_buf);
2340 memset(&globdata, 0, sizeof(globdata));
2341 gr = glob(pattern, 0, NULL, &globdata);
2342 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2344 if (gr == GLOB_NOMATCH) {
2345 globfree(&globdata);
2346 /* NB: garbles parameter */
2347 unbackslash(pattern);
2348 o_addstr_with_NUL(o, pattern);
2349 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2350 return o_save_ptr_helper(o, n);
2352 if (gr == GLOB_NOSPACE)
2353 bb_error_msg_and_die(bb_msg_memory_exhausted);
2354 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2355 * but we didn't specify it. Paranoia again. */
2356 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2358 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2359 char **argv = globdata.gl_pathv;
2361 o_addstr_with_NUL(o, *argv);
2362 n = o_save_ptr_helper(o, n);
2368 globfree(&globdata);
2372 /* Performs globbing on last list[],
2373 * saving each result as a new list[].
2375 static int o_glob(o_string *o, int n)
2377 char *pattern, *copy;
2379 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2381 return o_save_ptr_helper(o, n);
2382 pattern = o->data + o_get_last_ptr(o, n);
2383 debug_printf_glob("glob pattern '%s'\n", pattern);
2384 if (!glob_needed(pattern)) {
2385 /* unbackslash last string in o in place, fix length */
2386 o->length = unbackslash(pattern) - o->data;
2387 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2388 return o_save_ptr_helper(o, n);
2391 copy = xstrdup(pattern);
2392 /* "forget" pattern in o */
2393 o->length = pattern - o->data;
2394 n = glob_brace(copy, o, n);
2397 debug_print_list("o_glob returning", o, n);
2401 #else /* !HUSH_BRACE_EXP */
2404 static int glob_needed(const char *s)
2413 if (*s == '*' || *s == '[' || *s == '?')
2419 /* Performs globbing on last list[],
2420 * saving each result as a new list[].
2422 static int o_glob(o_string *o, int n)
2428 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2430 return o_save_ptr_helper(o, n);
2431 pattern = o->data + o_get_last_ptr(o, n);
2432 debug_printf_glob("glob pattern '%s'\n", pattern);
2433 if (!glob_needed(pattern)) {
2435 /* unbackslash last string in o in place, fix length */
2436 o->length = unbackslash(pattern) - o->data;
2437 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2438 return o_save_ptr_helper(o, n);
2441 memset(&globdata, 0, sizeof(globdata));
2442 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2443 * If we glob "*.\*" and don't find anything, we need
2444 * to fall back to using literal "*.*", but GLOB_NOCHECK
2445 * will return "*.\*"!
2447 gr = glob(pattern, 0, NULL, &globdata);
2448 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2450 if (gr == GLOB_NOMATCH) {
2451 globfree(&globdata);
2454 if (gr == GLOB_NOSPACE)
2455 bb_error_msg_and_die(bb_msg_memory_exhausted);
2456 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2457 * but we didn't specify it. Paranoia again. */
2458 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2460 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2461 char **argv = globdata.gl_pathv;
2462 /* "forget" pattern in o */
2463 o->length = pattern - o->data;
2465 o_addstr_with_NUL(o, *argv);
2466 n = o_save_ptr_helper(o, n);
2472 globfree(&globdata);
2474 debug_print_list("o_glob returning", o, n);
2478 #endif /* !HUSH_BRACE_EXP */
2480 /* If o->o_glob == 1, glob the string so far remembered.
2481 * Otherwise, just finish current list[] and start new */
2482 static int o_save_ptr(o_string *o, int n)
2484 if (o->o_glob) { /* if globbing is requested */
2485 /* If o->has_empty_slot, list[n] was already globbed
2486 * (if it was requested back then when it was filled)
2487 * so don't do that again! */
2488 if (!o->has_empty_slot)
2489 return o_glob(o, n); /* o_save_ptr_helper is inside */
2491 return o_save_ptr_helper(o, n);
2494 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2495 static char **o_finalize_list(o_string *o, int n)
2500 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2502 debug_print_list("finalized", o, n);
2503 debug_printf_expand("finalized n:%d\n", n);
2504 list = (char**)o->data;
2505 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2509 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2515 /* Expansion can recurse */
2516 #if ENABLE_HUSH_TICK
2517 static int process_command_subs(o_string *dest, const char *s);
2519 static char *expand_string_to_string(const char *str);
2521 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
2522 parse_stream_dquoted(dest, input, dquote_end)
2524 static int parse_stream_dquoted(o_string *as_string,
2526 struct in_str *input,
2529 /* expand_strvec_to_strvec() takes a list of strings, expands
2530 * all variable references within and returns a pointer to
2531 * a list of expanded strings, possibly with larger number
2532 * of strings. (Think VAR="a b"; echo $VAR).
2533 * This new list is allocated as a single malloc block.
2534 * NULL-terminated list of char* pointers is at the beginning of it,
2535 * followed by strings themself.
2536 * Caller can deallocate entire list by single free(list). */
2538 /* Store given string, finalizing the word and starting new one whenever
2539 * we encounter IFS char(s). This is used for expanding variable values.
2540 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2541 static int expand_on_ifs(o_string *output, int n, const char *str)
2544 int word_len = strcspn(str, G.ifs);
2546 if (output->o_escape || !output->o_glob)
2547 o_addQstr(output, str, word_len);
2548 else /* protect backslashes against globbing up :) */
2549 o_addblock_duplicate_backslash(output, str, word_len);
2552 if (!*str) /* EOL - do not finalize word */
2554 o_addchr(output, '\0');
2555 debug_print_list("expand_on_ifs", output, n);
2556 n = o_save_ptr(output, n);
2557 str += strspn(str, G.ifs); /* skip ifs chars */
2559 debug_print_list("expand_on_ifs[1]", output, n);
2563 /* Helper to expand $((...)) and heredoc body. These act as if
2564 * they are in double quotes, with the exception that they are not :).
2565 * Just the rules are similar: "expand only $var and `cmd`"
2567 * Returns malloced string.
2568 * As an optimization, we return NULL if expansion is not needed.
2570 static char *expand_pseudo_dquoted(const char *str)
2573 struct in_str input;
2574 o_string dest = NULL_O_STRING;
2576 if (!strchr(str, '$')
2577 #if ENABLE_HUSH_TICK
2578 && !strchr(str, '`')
2584 /* We need to expand. Example:
2585 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2587 setup_string_in_str(&input, str);
2588 parse_stream_dquoted(NULL, &dest, &input, EOF);
2589 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2590 exp_str = expand_string_to_string(dest.data);
2591 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2592 o_free_unsafe(&dest);
2596 #if ENABLE_SH_MATH_SUPPORT
2597 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2599 arith_eval_hooks_t hooks;
2603 hooks.lookupvar = get_local_var_value;
2604 hooks.setvar = set_local_var_from_halves;
2605 hooks.endofname = endofname;
2606 exp_str = expand_pseudo_dquoted(arg);
2607 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2613 #if ENABLE_HUSH_BASH_COMPAT
2614 /* ${var/[/]pattern[/repl]} helpers */
2615 static char *strstr_pattern(char *val, const char *pattern, int *size)
2618 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
2619 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
2626 /* Optimization: if "*pat" did not match the start of "string",
2627 * we know that "tring", "ring" etc will not match too:
2629 if (pattern[0] == '*')
2634 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
2636 char *result = NULL;
2637 unsigned res_len = 0;
2638 unsigned repl_len = strlen(repl);
2642 char *s = strstr_pattern(val, pattern, &size);
2646 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
2647 memcpy(result + res_len, val, s - val);
2649 strcpy(result + res_len, repl);
2650 res_len += repl_len;
2651 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
2657 if (val[0] && result) {
2658 result = xrealloc(result, res_len + strlen(val) + 1);
2659 strcpy(result + res_len, val);
2660 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
2662 debug_printf_varexp("result:'%s'\n", result);
2668 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
2670 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
2672 const char *val = NULL;
2673 char *to_be_freed = NULL;
2678 char exp_save = exp_save; /* for compiler */
2679 char *exp_saveptr; /* points to expansion operator */
2680 char *exp_word = exp_word; /* for compiler */
2684 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
2685 first_char = arg[0] = first_ch & 0x7f;
2688 if (first_char == '#' && arg[1] && !exp_saveptr) {
2689 /* handle length expansion ${#var} */
2693 /* maybe handle parameter expansion */
2694 if (exp_saveptr /* if 2nd char is one of expansion operators */
2695 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2697 /* ${?:0}, ${#[:]%0} etc */
2698 exp_saveptr = var + 1;
2700 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2701 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
2703 exp_op = exp_save = *exp_saveptr;
2705 exp_word = exp_saveptr + 1;
2706 if (exp_op == ':') {
2707 exp_op = *exp_word++;
2708 if (ENABLE_HUSH_BASH_COMPAT
2709 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
2711 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2716 *exp_saveptr = '\0';
2717 } /* else: it's not an expansion op, but bare ${var} */
2720 /* lookup the variable in question */
2721 if (isdigit(var[0])) {
2722 /* parse_dollar() should have vetted var for us */
2723 int n = xatoi_positive(var);
2724 if (n < G.global_argc)
2725 val = G.global_argv[n];
2726 /* else val remains NULL: $N with too big N */
2730 val = utoa(G.root_pid);
2732 case '!': /* bg pid */
2733 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
2735 case '?': /* exitcode */
2736 val = utoa(G.last_exitcode);
2738 case '#': /* argc */
2739 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2742 val = get_local_var_value(var);
2746 /* Handle any expansions */
2747 if (exp_op == 'L') {
2748 debug_printf_expand("expand: length(%s)=", val);
2749 val = utoa(val ? strlen(val) : 0);
2750 debug_printf_expand("%s\n", val);
2751 } else if (exp_op) {
2752 if (exp_op == '%' || exp_op == '#') {
2753 /* Standard-mandated substring removal ops:
2754 * ${parameter%word} - remove smallest suffix pattern
2755 * ${parameter%%word} - remove largest suffix pattern
2756 * ${parameter#word} - remove smallest prefix pattern
2757 * ${parameter##word} - remove largest prefix pattern
2759 * Word is expanded to produce a glob pattern.
2760 * Then var's value is matched to it and matching part removed.
2762 if (val && val[0]) {
2765 unsigned scan_flags = pick_scan(exp_op, *exp_word);
2766 if (exp_op == *exp_word) /* ## or %% */
2768 //TODO: avoid xstrdup unless needed
2769 // (see HACK ALERT below)
2770 val = to_be_freed = xstrdup(val);
2771 exp_exp_word = expand_pseudo_dquoted(exp_word);
2773 exp_word = exp_exp_word;
2774 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
2775 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2776 // exp_op, to_be_freed, exp_word, loc);
2778 if (loc) { /* match was found */
2779 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
2786 #if ENABLE_HUSH_BASH_COMPAT
2787 else if (exp_op == '/' || exp_op == '\\') {
2788 /* Empty variable always gives nothing: */
2789 // "v=''; echo ${v/*/w}" prints ""
2790 if (val && val[0]) {
2791 /* It's ${var/[/]pattern[/repl]} thing */
2792 char *pattern, *repl, *t;
2793 pattern = expand_pseudo_dquoted(exp_word);
2795 pattern = xstrdup(exp_word);
2796 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
2797 *p++ = SPECIAL_VAR_SYMBOL;
2799 p = strchr(p, SPECIAL_VAR_SYMBOL);
2801 repl = expand_pseudo_dquoted(exp_word);
2802 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
2803 /* HACK ALERT. We depend here on the fact that
2804 * G.global_argv and results of utoa and get_local_var_value
2805 * are actually in writable memory:
2806 * replace_pattern momentarily stores NULs there. */
2808 to_be_freed = replace_pattern(t,
2810 (repl ? repl : exp_word),
2812 if (to_be_freed) /* at least one replace happened */
2819 else if (exp_op == ':') {
2820 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
2821 /* It's ${var:N[:M]} bashism.
2822 * Note that in encoded form it has TWO parts:
2823 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
2828 beg = expand_and_evaluate_arith(exp_word, &errcode);
2829 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2830 *p++ = SPECIAL_VAR_SYMBOL;
2832 p = strchr(p, SPECIAL_VAR_SYMBOL);
2834 len = expand_and_evaluate_arith(exp_word, &errcode);
2835 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2837 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2838 if (beg < 0) /* bash compat */
2840 debug_printf_varexp("from val:'%s'\n", val);
2841 if (len == 0 || !val || beg >= strlen(val))
2844 /* Paranoia. What if user entered 9999999999999
2845 * which fits in arith_t but not int? */
2848 val = to_be_freed = xstrndup(val + beg, len);
2850 debug_printf_varexp("val:'%s'\n", val);
2854 die_if_script("malformed ${%s:...}", var);
2857 } else { /* one of "-=+?" */
2858 /* Standard-mandated substitution ops:
2859 * ${var?word} - indicate error if unset
2860 * If var is unset, word (or a message indicating it is unset
2861 * if word is null) is written to standard error
2862 * and the shell exits with a non-zero exit status.
2863 * Otherwise, the value of var is substituted.
2864 * ${var-word} - use default value
2865 * If var is unset, word is substituted.
2866 * ${var=word} - assign and use default value
2867 * If var is unset, word is assigned to var.
2868 * In all cases, final value of var is substituted.
2869 * ${var+word} - use alternative value
2870 * If var is unset, null is substituted.
2871 * Otherwise, word is substituted.
2873 * Word is subjected to tilde expansion, parameter expansion,
2874 * command substitution, and arithmetic expansion.
2875 * If word is not needed, it is not expanded.
2877 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2878 * but also treat null var as if it is unset.
2880 int use_word = (!val || ((exp_save == ':') && !val[0]));
2882 use_word = !use_word;
2883 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2884 (exp_save == ':') ? "true" : "false", use_word);
2886 to_be_freed = expand_pseudo_dquoted(exp_word);
2888 exp_word = to_be_freed;
2889 if (exp_op == '?') {
2890 /* mimic bash message */
2891 die_if_script("%s: %s",
2893 exp_word[0] ? exp_word : "parameter null or not set"
2895 //TODO: how interactive bash aborts expansion mid-command?
2900 if (exp_op == '=') {
2901 /* ${var=[word]} or ${var:=[word]} */
2902 if (isdigit(var[0]) || var[0] == '#') {
2903 /* mimic bash message */
2904 die_if_script("$%s: cannot assign in this way", var);
2907 char *new_var = xasprintf("%s=%s", var, val);
2908 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
2912 } /* one of "-=+?" */
2914 *exp_saveptr = exp_save;
2920 *to_be_freed_pp = to_be_freed;
2924 /* Expand all variable references in given string, adding words to list[]
2925 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2926 * to be filled). This routine is extremely tricky: has to deal with
2927 * variables/parameters with whitespace, $* and $@, and constructs like
2928 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2929 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2931 /* or_mask is either 0 (normal case) or 0x80 -
2932 * expansion of right-hand side of assignment == 1-element expand.
2933 * It will also do no globbing, and thus we must not backslash-quote!
2940 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
2941 debug_print_list("expand_vars_to_list", output, n);
2942 n = o_save_ptr(output, n);
2943 debug_print_list("expand_vars_to_list[0]", output, n);
2945 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2948 char *to_be_freed = NULL;
2949 const char *val = NULL;
2950 #if ENABLE_HUSH_TICK
2951 o_string subst_result = NULL_O_STRING;
2953 #if ENABLE_SH_MATH_SUPPORT
2954 char arith_buf[sizeof(arith_t)*3 + 2];
2956 o_addblock(output, arg, p - arg);
2957 debug_print_list("expand_vars_to_list[1]", output, n);
2959 p = strchr(p, SPECIAL_VAR_SYMBOL);
2961 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2962 /* "$@" is special. Even if quoted, it can still
2963 * expand to nothing (not even an empty string) */
2964 if ((first_ch & 0x7f) != '@')
2965 ored_ch |= first_ch;
2967 switch (first_ch & 0x7f) {
2968 /* Highest bit in first_ch indicates that var is double-quoted */
2972 if (!G.global_argv[i])
2974 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2975 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2976 smallint sv = output->o_escape;
2977 /* unquoted var's contents should be globbed, so don't escape */
2978 output->o_escape = 0;
2979 while (G.global_argv[i]) {
2980 n = expand_on_ifs(output, n, G.global_argv[i]);
2981 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2982 if (G.global_argv[i++][0] && G.global_argv[i]) {
2983 /* this argv[] is not empty and not last:
2984 * put terminating NUL, start new word */
2985 o_addchr(output, '\0');
2986 debug_print_list("expand_vars_to_list[2]", output, n);
2987 n = o_save_ptr(output, n);
2988 debug_print_list("expand_vars_to_list[3]", output, n);
2991 output->o_escape = sv;
2993 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2994 * and in this case should treat it like '$*' - see 'else...' below */
2995 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2997 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2998 if (++i >= G.global_argc)
3000 o_addchr(output, '\0');
3001 debug_print_list("expand_vars_to_list[4]", output, n);
3002 n = o_save_ptr(output, n);
3004 } else { /* quoted $*: add as one word */
3006 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
3007 if (!G.global_argv[++i])
3010 o_addchr(output, G.ifs[0]);
3014 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
3015 /* "Empty variable", used to make "" etc to not disappear */
3019 #if ENABLE_HUSH_TICK
3020 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
3023 /* Can't just stuff it into output o_string,
3024 * expanded result may need to be globbed
3025 * and $IFS-splitted */
3026 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
3027 G.last_exitcode = process_command_subs(&subst_result, arg);
3028 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
3029 val = subst_result.data;
3032 #if ENABLE_SH_MATH_SUPPORT
3033 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
3037 arg++; /* skip '+' */
3038 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
3039 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
3040 res = expand_and_evaluate_arith(arg, &errcode);
3043 const char *msg = "error in arithmetic";
3046 msg = "exponent less than 0";
3049 msg = "divide by 0";
3052 msg = "expression recursion loop detected";
3057 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
3058 sprintf(arith_buf, arith_t_fmt, res);
3064 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
3065 IF_HUSH_TICK(store_val:)
3066 if (!(first_ch & 0x80)) { /* unquoted $VAR */
3067 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
3068 if (val && val[0]) {
3069 /* unquoted var's contents should be globbed, so don't escape */
3070 smallint sv = output->o_escape;
3071 output->o_escape = 0;
3072 n = expand_on_ifs(output, n, val);
3074 output->o_escape = sv;
3076 } else { /* quoted $VAR, val will be appended below */
3077 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
3081 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
3083 if (val && val[0]) {
3084 o_addQstr(output, val, strlen(val));
3087 /* Do the check to avoid writing to a const string */
3088 if (*p != SPECIAL_VAR_SYMBOL)
3089 *p = SPECIAL_VAR_SYMBOL;
3091 #if ENABLE_HUSH_TICK
3092 o_free(&subst_result);
3095 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
3098 debug_print_list("expand_vars_to_list[a]", output, n);
3099 /* this part is literal, and it was already pre-quoted
3100 * if needed (much earlier), do not use o_addQstr here! */
3101 o_addstr_with_NUL(output, arg);
3102 debug_print_list("expand_vars_to_list[b]", output, n);
3103 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
3104 && !(ored_ch & 0x80) /* and all vars were not quoted. */
3107 /* allow to reuse list[n] later without re-growth */
3108 output->has_empty_slot = 1;
3110 o_addchr(output, '\0');
3116 EXPVAR_FLAG_GLOB = 0x200,
3117 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
3118 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
3120 static char **expand_variables(char **argv, unsigned or_mask)
3125 o_string output = NULL_O_STRING;
3127 /* protect against globbing for "$var"? */
3128 /* (unquoted $var will temporarily switch it off) */
3129 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
3130 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
3135 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
3138 debug_print_list("expand_variables", &output, n);
3140 /* output.data (malloced in one block) gets returned in "list" */
3141 list = o_finalize_list(&output, n);
3142 debug_print_strings("expand_variables[1]", list);
3146 static char **expand_strvec_to_strvec(char **argv)
3148 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
3151 #if ENABLE_HUSH_BASH_COMPAT
3152 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3154 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3158 #ifdef CMD_SINGLEWORD_NOGLOB_COND
3159 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3164 o_string output = NULL_O_STRING;
3169 int is_var = is_well_formed_var_name(*v, '=');
3170 /* is_var * 0x80: singleword expansion for vars */
3171 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3173 /* Subtle! expand_vars_to_list did not glob last word yet.
3174 * It does this only when fed with further data.
3175 * Therefore we set globbing flags AFTER it, not before:
3178 /* if it is not recognizably abc=...; then: */
3179 output.o_escape = !is_var; /* protect against globbing for "$var" */
3180 /* (unquoted $var will temporarily switch it off) */
3181 output.o_glob = !is_var; /* and indeed do globbing */
3184 debug_print_list("expand_cond", &output, n);
3186 /* output.data (malloced in one block) gets returned in "list" */
3187 list = o_finalize_list(&output, n);
3188 debug_print_strings("expand_cond[1]", list);
3193 /* Used for expansion of right hand of assignments */
3194 /* NB: should NOT do globbing!
3195 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
3196 static char *expand_string_to_string(const char *str)
3198 char *argv[2], **list;
3200 /* This is generally an optimization, but it also
3201 * handles "", which otherwise trips over !list[0] check below.
3202 * (is this ever happens that we actually get str="" here?)
3204 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
3205 //TODO: Can use on strings with \ too, just unbackslash() them?
3206 debug_printf_expand("string_to_string(fast)='%s'\n", str);
3207 return xstrdup(str);
3210 argv[0] = (char*)str;
3212 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
3214 if (!list[0] || list[1])
3215 bb_error_msg_and_die("BUG in varexp2");
3216 /* actually, just move string 2*sizeof(char*) bytes back */
3217 overlapping_strcpy((char*)list, list[0]);
3218 unbackslash((char*)list);
3219 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3223 /* Used for "eval" builtin */
3224 static char* expand_strvec_to_string(char **argv)
3228 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
3229 /* Convert all NULs to spaces */
3234 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3235 bb_error_msg_and_die("BUG in varexp3");
3236 /* bash uses ' ' regardless of $IFS contents */
3241 overlapping_strcpy((char*)list, list[0]);
3242 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3246 static char **expand_assignments(char **argv, int count)
3251 G.expanded_assignments = p = NULL;
3252 /* Expand assignments into one string each */
3253 for (i = 0; i < count; i++) {
3254 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
3256 G.expanded_assignments = NULL;
3263 void re_execute_shell(char ***to_free, const char *s,
3264 char *g_argv0, char **g_argv,
3265 char **builtin_argv) NORETURN;
3267 static void reset_traps_to_defaults(void)
3269 /* This function is always called in a child shell
3270 * after fork (not vfork, NOMMU doesn't use this function).
3275 /* Child shells are not interactive.
3276 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3277 * Testcase: (while :; do :; done) + ^Z should background.
3278 * Same goes for SIGTERM, SIGHUP, SIGINT.
3280 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
3281 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
3283 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3284 * Stupid. It can be done with *single* &= op, but we can't use
3285 * the fact that G.blocked_set is implemented as a bitmask
3287 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3291 /* Careful. Only if no trap or trap is not "" */
3292 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3293 sigdelset(&G.blocked_set, sig);
3300 /* Our homegrown sig mask is saner to work with :) */
3301 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
3303 /* Resetting all traps to default except empty ones */
3304 mask = G.non_DFL_mask;
3305 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
3306 if (!G.traps[sig] || !G.traps[sig][0])
3309 G.traps[sig] = NULL;
3310 /* There is no signal for 0 (EXIT) */
3313 /* There was a trap handler, we just removed it.
3314 * But if sig still has non-DFL handling,
3315 * we should not unblock the sig. */
3318 sigdelset(&G.blocked_set, sig);
3320 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
3325 static void re_execute_shell(char ***to_free, const char *s,
3326 char *g_argv0, char **g_argv,
3327 char **builtin_argv) NORETURN;
3328 static void re_execute_shell(char ***to_free, const char *s,
3329 char *g_argv0, char **g_argv,
3330 char **builtin_argv)
3332 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
3333 /* delims + 2 * (number of bytes in printed hex numbers) */
3334 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
3335 char *heredoc_argv[4];
3336 struct variable *cur;
3337 # if ENABLE_HUSH_FUNCTIONS
3338 struct function *funcp;
3342 unsigned long long empty_trap_mask;
3344 if (!g_argv0) { /* heredoc */
3345 argv = heredoc_argv;
3346 argv[0] = (char *) G.argv0_for_re_execing;
3347 argv[1] = (char *) "-<";
3348 argv[2] = (char *) s;
3350 pp = &argv[3]; /* used as pointer to empty environment */
3356 if (pp) while (*pp++)
3359 empty_trap_mask = 0;
3362 for (sig = 1; sig < NSIG; sig++) {
3363 if (G.traps[sig] && !G.traps[sig][0])
3364 empty_trap_mask |= 1LL << sig;
3368 sprintf(param_buf, NOMMU_HACK_FMT
3369 , (unsigned) G.root_pid
3370 , (unsigned) G.root_ppid
3371 , (unsigned) G.last_bg_pid
3372 , (unsigned) G.last_exitcode
3375 IF_HUSH_LOOPS(, G.depth_of_loop)
3377 # undef NOMMU_HACK_FMT
3378 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
3379 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
3382 for (cur = G.top_var; cur; cur = cur->next) {
3383 if (!cur->flg_export || cur->flg_read_only)
3386 # if ENABLE_HUSH_FUNCTIONS
3387 for (funcp = G.top_func; funcp; funcp = funcp->next)
3393 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
3394 *pp++ = (char *) G.argv0_for_re_execing;
3396 for (cur = G.top_var; cur; cur = cur->next) {
3397 if (strcmp(cur->varstr, hush_version_str) == 0)
3399 if (cur->flg_read_only) {
3400 *pp++ = (char *) "-R";
3401 *pp++ = cur->varstr;
3402 } else if (!cur->flg_export) {
3403 *pp++ = (char *) "-V";
3404 *pp++ = cur->varstr;
3407 # if ENABLE_HUSH_FUNCTIONS
3408 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3409 *pp++ = (char *) "-F";
3410 *pp++ = funcp->name;
3411 *pp++ = funcp->body_as_string;
3414 /* We can pass activated traps here. Say, -Tnn:trap_string
3416 * However, POSIX says that subshells reset signals with traps
3418 * I tested bash-3.2 and it not only does that with true subshells
3419 * of the form ( list ), but with any forked children shells.
3420 * I set trap "echo W" WINCH; and then tried:
3422 * { echo 1; sleep 20; echo 2; } &
3423 * while true; do echo 1; sleep 20; echo 2; break; done &
3424 * true | { echo 1; sleep 20; echo 2; } | cat
3426 * In all these cases sending SIGWINCH to the child shell
3427 * did not run the trap. If I add trap "echo V" WINCH;
3428 * _inside_ group (just before echo 1), it works.
3430 * I conclude it means we don't need to pass active traps here.
3431 * Even if we would use signal handlers instead of signal masking
3432 * in order to implement trap handling,
3433 * exec syscall below resets signals to SIG_DFL for us.
3435 *pp++ = (char *) "-c";
3438 while (*++builtin_argv)
3439 *pp++ = *builtin_argv;
3440 *pp++ = (char *) "";
3445 /* *pp = NULL; - is already there */
3449 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3450 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3451 execve(bb_busybox_exec_path, argv, pp);
3452 /* Fallback. Useful for init=/bin/hush usage etc */
3453 if (argv[0][0] == '/')
3454 execve(argv[0], argv, pp);
3455 xfunc_error_retval = 127;
3456 bb_error_msg_and_die("can't re-execute the shell");
3458 #endif /* !BB_MMU */
3461 static void setup_heredoc(struct redir_struct *redir)
3463 struct fd_pair pair;
3466 /* the _body_ of heredoc (misleading field name) */
3467 const char *heredoc = redir->rd_filename;
3474 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3475 expanded = expand_pseudo_dquoted(heredoc);
3479 len = strlen(heredoc);
3481 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
3483 xmove_fd(pair.rd, redir->rd_fd);
3485 /* Try writing without forking. Newer kernels have
3486 * dynamically growing pipes. Must use non-blocking write! */
3489 written = write(pair.wr, heredoc, len);
3500 ndelay_off(pair.wr);
3502 /* Okay, pipe buffer was not big enough */
3503 /* Note: we must not create a stray child (bastard? :)
3504 * for the unsuspecting parent process. Child creates a grandchild
3505 * and exits before parent execs the process which consumes heredoc
3506 * (that exec happens after we return from this function) */
3513 disable_restore_tty_pgrp_on_exit();
3514 pid = BB_MMU ? xfork() : xvfork();
3518 close(redir->rd_fd); /* read side of the pipe */
3520 full_write(pair.wr, heredoc, len); /* may loop or block */
3523 /* Delegate blocking writes to another process */
3524 xmove_fd(pair.wr, STDOUT_FILENO);
3525 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
3529 #if ENABLE_HUSH_FAST
3531 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3533 enable_restore_tty_pgrp_on_exit();
3539 wait(NULL); /* wait till child has died */
3542 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
3543 * and stderr if they are redirected. */
3544 static int setup_redirects(struct command *prog, int squirrel[])
3547 struct redir_struct *redir;
3549 for (redir = prog->redirects; redir; redir = redir->next) {
3550 if (redir->rd_type == REDIRECT_HEREDOC2) {
3551 /* rd_fd<<HERE case */
3552 if (squirrel && redir->rd_fd < 3
3553 && squirrel[redir->rd_fd] < 0
3555 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3557 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3559 debug_printf_parse("set heredoc '%s'\n",
3560 redir->rd_filename);
3561 setup_heredoc(redir);
3565 if (redir->rd_dup == REDIRFD_TO_FILE) {
3566 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
3568 if (redir->rd_filename == NULL) {
3569 /* Something went wrong in the parse.
3570 * Pretend it didn't happen */
3571 bb_error_msg("bug in redirect parse");
3574 mode = redir_table[redir->rd_type].mode;
3575 p = expand_string_to_string(redir->rd_filename);
3576 openfd = open_or_warn(p, mode);
3579 /* this could get lost if stderr has been redirected, but
3580 * bash and ash both lose it as well (though zsh doesn't!) */
3581 //what the above comment tries to say?
3585 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
3586 openfd = redir->rd_dup;
3589 if (openfd != redir->rd_fd) {
3590 if (squirrel && redir->rd_fd < 3
3591 && squirrel[redir->rd_fd] < 0
3593 squirrel[redir->rd_fd] = dup(redir->rd_fd);
3595 if (openfd == REDIRFD_CLOSE) {
3596 /* "n>-" means "close me" */
3597 close(redir->rd_fd);
3599 xdup2(openfd, redir->rd_fd);
3600 if (redir->rd_dup == REDIRFD_TO_FILE)
3608 static void restore_redirects(int squirrel[])
3611 for (i = 0; i < 3; i++) {
3614 /* We simply die on error */
3621 static void free_pipe_list(struct pipe *head);
3623 /* Return code is the exit status of the pipe */
3624 static void free_pipe(struct pipe *pi)
3627 struct command *command;
3628 struct redir_struct *r, *rnext;
3631 if (pi->stopped_cmds > 0) /* why? */
3633 debug_printf_clean("run pipe: (pid %d)\n", getpid());
3634 for (i = 0; i < pi->num_cmds; i++) {
3635 command = &pi->cmds[i];
3636 debug_printf_clean(" command %d:\n", i);
3637 if (command->argv) {
3638 for (a = 0, p = command->argv; *p; a++, p++) {
3639 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3641 free_strings(command->argv);
3642 command->argv = NULL;
3644 /* not "else if": on syntax error, we may have both! */
3645 if (command->group) {
3646 debug_printf_clean(" begin group (cmd_type:%d)\n",
3648 free_pipe_list(command->group);
3649 debug_printf_clean(" end group\n");
3650 command->group = NULL;
3652 /* else is crucial here.
3653 * If group != NULL, child_func is meaningless */
3654 #if ENABLE_HUSH_FUNCTIONS
3655 else if (command->child_func) {
3656 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3657 command->child_func->parent_cmd = NULL;
3661 free(command->group_as_string);
3662 command->group_as_string = NULL;
3664 for (r = command->redirects; r; r = rnext) {
3665 debug_printf_clean(" redirect %d%s",
3666 r->rd_fd, redir_table[r->rd_type].descrip);
3667 /* guard against the case >$FOO, where foo is unset or blank */
3668 if (r->rd_filename) {
3669 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3670 free(r->rd_filename);
3671 r->rd_filename = NULL;
3673 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
3677 command->redirects = NULL;
3679 free(pi->cmds); /* children are an array, they get freed all at once */
3687 static void free_pipe_list(struct pipe *head)
3689 struct pipe *pi, *next;
3691 for (pi = head; pi; pi = next) {
3693 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
3696 debug_printf_clean("pipe followup code %d\n", pi->followup);
3698 /*pi->next = NULL;*/
3704 static int run_list(struct pipe *pi);
3706 #define parse_stream(pstring, input, end_trigger) \
3707 parse_stream(input, end_trigger)
3709 static struct pipe *parse_stream(char **pstring,
3710 struct in_str *input,
3712 static void parse_and_run_string(const char *s);
3715 static char *find_in_path(const char *arg)
3718 const char *PATH = get_local_var_value("PATH");
3724 const char *end = strchrnul(PATH, ':');
3725 int sz = end - PATH; /* must be int! */
3729 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3731 /* We have xxx::yyyy in $PATH,
3732 * it means "use current dir" */
3735 if (access(ret, F_OK) == 0)
3748 static const struct built_in_command* find_builtin_helper(const char *name,
3749 const struct built_in_command *x,
3750 const struct built_in_command *end)
3753 if (strcmp(name, x->b_cmd) != 0) {
3757 debug_printf_exec("found builtin '%s'\n", name);
3762 static const struct built_in_command* find_builtin1(const char *name)
3764 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3766 static const struct built_in_command* find_builtin(const char *name)
3768 const struct built_in_command *x = find_builtin1(name);
3771 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3774 #if ENABLE_HUSH_FUNCTIONS
3775 static struct function **find_function_slot(const char *name)
3777 struct function **funcpp = &G.top_func;
3779 if (strcmp(name, (*funcpp)->name) == 0) {
3782 funcpp = &(*funcpp)->next;
3787 static const struct function *find_function(const char *name)
3789 const struct function *funcp = *find_function_slot(name);
3791 debug_printf_exec("found function '%s'\n", name);
3795 /* Note: takes ownership on name ptr */
3796 static struct function *new_function(char *name)
3798 struct function **funcpp = find_function_slot(name);
3799 struct function *funcp = *funcpp;
3801 if (funcp != NULL) {
3802 struct command *cmd = funcp->parent_cmd;
3803 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3805 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3807 /* Note: if !funcp->body, do not free body_as_string!
3808 * This is a special case of "-F name body" function:
3809 * body_as_string was not malloced! */
3811 free_pipe_list(funcp->body);
3813 free(funcp->body_as_string);
3817 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3818 cmd->argv[0] = funcp->name;
3819 cmd->group = funcp->body;
3821 cmd->group_as_string = funcp->body_as_string;
3825 debug_printf_exec("remembering new function '%s'\n", name);
3826 funcp = *funcpp = xzalloc(sizeof(*funcp));
3827 /*funcp->next = NULL;*/
3834 static void unset_func(const char *name)
3836 struct function **funcpp = find_function_slot(name);
3837 struct function *funcp = *funcpp;
3839 if (funcp != NULL) {
3840 debug_printf_exec("freeing function '%s'\n", funcp->name);
3841 *funcpp = funcp->next;
3842 /* funcp is unlinked now, deleting it.
3843 * Note: if !funcp->body, the function was created by
3844 * "-F name body", do not free ->body_as_string
3845 * and ->name as they were not malloced. */
3847 free_pipe_list(funcp->body);
3850 free(funcp->body_as_string);
3858 #define exec_function(to_free, funcp, argv) \
3859 exec_function(funcp, argv)
3861 static void exec_function(char ***to_free,
3862 const struct function *funcp,
3863 char **argv) NORETURN;
3864 static void exec_function(char ***to_free,
3865 const struct function *funcp,
3871 argv[0] = G.global_argv[0];
3872 G.global_argv = argv;
3876 /* On MMU, funcp->body is always non-NULL */
3877 n = run_list(funcp->body);
3881 re_execute_shell(to_free,
3882 funcp->body_as_string,
3889 static int run_function(const struct function *funcp, char **argv)
3895 save_and_replace_G_args(&sv, argv);
3897 /* "we are in function, ok to use return" */
3898 sv_flg = G.flag_return_in_progress;
3899 G.flag_return_in_progress = -1;
3900 # if ENABLE_HUSH_LOCAL
3901 G.func_nest_level++;
3904 /* On MMU, funcp->body is always non-NULL */
3907 /* Function defined by -F */
3908 parse_and_run_string(funcp->body_as_string);
3909 rc = G.last_exitcode;
3913 rc = run_list(funcp->body);
3916 # if ENABLE_HUSH_LOCAL
3918 struct variable *var;
3919 struct variable **var_pp;
3921 var_pp = &G.top_var;
3922 while ((var = *var_pp) != NULL) {
3923 if (var->func_nest_level < G.func_nest_level) {
3924 var_pp = &var->next;
3928 if (var->flg_export)
3929 bb_unsetenv(var->varstr);
3930 /* Remove from global list */
3931 *var_pp = var->next;
3937 G.func_nest_level--;
3940 G.flag_return_in_progress = sv_flg;
3942 restore_G_args(&sv, argv);
3946 #endif /* ENABLE_HUSH_FUNCTIONS */
3950 #define exec_builtin(to_free, x, argv) \
3951 exec_builtin(x, argv)
3953 #define exec_builtin(to_free, x, argv) \
3954 exec_builtin(to_free, argv)
3956 static void exec_builtin(char ***to_free,
3957 const struct built_in_command *x,
3958 char **argv) NORETURN;
3959 static void exec_builtin(char ***to_free,
3960 const struct built_in_command *x,
3964 int rcode = x->b_function(argv);
3968 /* On NOMMU, we must never block!
3969 * Example: { sleep 99 | read line; } & echo Ok
3971 re_execute_shell(to_free,
3980 static void execvp_or_die(char **argv) NORETURN;
3981 static void execvp_or_die(char **argv)
3983 debug_printf_exec("execing '%s'\n", argv[0]);
3984 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3985 execvp(argv[0], argv);
3986 bb_perror_msg("can't execute '%s'", argv[0]);
3987 _exit(127); /* bash compat */
3990 #if ENABLE_HUSH_MODE_X
3991 static void dump_cmd_in_x_mode(char **argv)
3993 if (G_x_mode && argv) {
3994 /* We want to output the line in one write op */
4002 len += strlen(argv[n++]) + 1;
4008 p += sprintf(p, " %s", argv[n++]);
4016 # define dump_cmd_in_x_mode(argv) ((void)0)
4020 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
4021 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
4022 #define pseudo_exec(nommu_save, command, argv_expanded) \
4023 pseudo_exec(command, argv_expanded)
4026 /* Called after [v]fork() in run_pipe, or from builtin_exec.
4028 * Don't exit() here. If you don't exec, use _exit instead.
4029 * The at_exit handlers apparently confuse the calling process,
4030 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
4031 static void pseudo_exec_argv(nommu_save_t *nommu_save,
4032 char **argv, int assignment_cnt,
4033 char **argv_expanded) NORETURN;
4034 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
4035 char **argv, int assignment_cnt,
4036 char **argv_expanded)
4040 new_env = expand_assignments(argv, assignment_cnt);
4041 dump_cmd_in_x_mode(new_env);
4043 if (!argv[assignment_cnt]) {
4044 /* Case when we are here: ... | var=val | ...
4045 * (note that we do not exit early, i.e., do not optimize out
4046 * expand_assignments(): think about ... | var=`sleep 1` | ...
4048 free_strings(new_env);
4049 _exit(EXIT_SUCCESS);
4053 set_vars_and_save_old(new_env);
4054 free(new_env); /* optional */
4055 /* we can also destroy set_vars_and_save_old's return value,
4058 nommu_save->new_env = new_env;
4059 nommu_save->old_vars = set_vars_and_save_old(new_env);
4062 if (argv_expanded) {
4063 argv = argv_expanded;
4065 argv = expand_strvec_to_strvec(argv + assignment_cnt);
4067 nommu_save->argv = argv;
4070 dump_cmd_in_x_mode(argv);
4072 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4073 if (strchr(argv[0], '/') != NULL)
4077 /* Check if the command matches any of the builtins.
4078 * Depending on context, this might be redundant. But it's
4079 * easier to waste a few CPU cycles than it is to figure out
4080 * if this is one of those cases.
4083 /* On NOMMU, it is more expensive to re-execute shell
4084 * just in order to run echo or test builtin.
4085 * It's better to skip it here and run corresponding
4086 * non-builtin later. */
4087 const struct built_in_command *x;
4088 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
4090 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
4093 #if ENABLE_HUSH_FUNCTIONS
4094 /* Check if the command matches any functions */
4096 const struct function *funcp = find_function(argv[0]);
4098 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
4103 #if ENABLE_FEATURE_SH_STANDALONE
4104 /* Check if the command matches any busybox applets */
4106 int a = find_applet_by_name(argv[0]);
4108 # if BB_MMU /* see above why on NOMMU it is not allowed */
4109 if (APPLET_IS_NOEXEC(a)) {
4110 debug_printf_exec("running applet '%s'\n", argv[0]);
4111 run_applet_no_and_exit(a, argv);
4114 /* Re-exec ourselves */
4115 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
4116 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
4117 execv(bb_busybox_exec_path, argv);
4118 /* If they called chroot or otherwise made the binary no longer
4119 * executable, fall through */
4124 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
4127 execvp_or_die(argv);
4130 /* Called after [v]fork() in run_pipe
4132 static void pseudo_exec(nommu_save_t *nommu_save,
4133 struct command *command,
4134 char **argv_expanded) NORETURN;
4135 static void pseudo_exec(nommu_save_t *nommu_save,
4136 struct command *command,
4137 char **argv_expanded)
4139 if (command->argv) {
4140 pseudo_exec_argv(nommu_save, command->argv,
4141 command->assignment_cnt, argv_expanded);
4144 if (command->group) {
4145 /* Cases when we are here:
4148 * ... | ( list ) | ...
4149 * ... | { list } | ...
4153 debug_printf_exec("pseudo_exec: run_list\n");
4154 reset_traps_to_defaults();
4155 rcode = run_list(command->group);
4156 /* OK to leak memory by not calling free_pipe_list,
4157 * since this process is about to exit */
4160 re_execute_shell(&nommu_save->argv_from_re_execing,
4161 command->group_as_string,
4168 /* Case when we are here: ... | >file */
4169 debug_printf_exec("pseudo_exec'ed null command\n");
4170 _exit(EXIT_SUCCESS);
4174 static const char *get_cmdtext(struct pipe *pi)
4180 /* This is subtle. ->cmdtext is created only on first backgrounding.
4181 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
4182 * On subsequent bg argv is trashed, but we won't use it */
4185 argv = pi->cmds[0].argv;
4186 if (!argv || !argv[0]) {
4187 pi->cmdtext = xzalloc(1);
4193 len += strlen(*argv) + 1;
4197 argv = pi->cmds[0].argv;
4199 len = strlen(*argv);
4200 memcpy(p, *argv, len);
4208 static void insert_bg_job(struct pipe *pi)
4210 struct pipe *job, **jobp;
4213 /* Linear search for the ID of the job to use */
4215 for (job = G.job_list; job; job = job->next)
4216 if (job->jobid >= pi->jobid)
4217 pi->jobid = job->jobid + 1;
4219 /* Add job to the list of running jobs */
4221 while ((job = *jobp) != NULL)
4223 job = *jobp = xmalloc(sizeof(*job));
4225 *job = *pi; /* physical copy */
4227 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4228 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
4229 for (i = 0; i < pi->num_cmds; i++) {
4230 job->cmds[i].pid = pi->cmds[i].pid;
4231 /* all other fields are not used and stay zero */
4233 job->cmdtext = xstrdup(get_cmdtext(pi));
4235 if (G_interactive_fd)
4236 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
4237 G.last_jobid = job->jobid;
4240 static void remove_bg_job(struct pipe *pi)
4242 struct pipe *prev_pipe;
4244 if (pi == G.job_list) {
4245 G.job_list = pi->next;
4247 prev_pipe = G.job_list;
4248 while (prev_pipe->next != pi)
4249 prev_pipe = prev_pipe->next;
4250 prev_pipe->next = pi->next;
4253 G.last_jobid = G.job_list->jobid;
4258 /* Remove a backgrounded job */
4259 static void delete_finished_bg_job(struct pipe *pi)
4262 pi->stopped_cmds = 0;
4268 /* Check to see if any processes have exited -- if they
4269 * have, figure out why and see if a job has completed */
4270 static int checkjobs(struct pipe* fg_pipe)
4280 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4282 attributes = WUNTRACED;
4283 if (fg_pipe == NULL)
4284 attributes |= WNOHANG;
4287 #if ENABLE_HUSH_FAST
4288 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4289 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4290 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
4291 /* There was neither fork nor SIGCHLD since last waitpid */
4292 /* Avoid doing waitpid syscall if possible */
4293 if (!G.we_have_children) {
4297 if (fg_pipe == NULL) { /* is WNOHANG set? */
4298 /* We have children, but they did not exit
4299 * or stop yet (we saw no SIGCHLD) */
4302 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4306 /* Do we do this right?
4307 * bash-3.00# sleep 20 | false
4309 * [3]+ Stopped sleep 20 | false
4310 * bash-3.00# echo $?
4311 * 1 <========== bg pipe is not fully done, but exitcode is already known!
4312 * [hush 1.14.0: yes we do it right]
4319 #if ENABLE_HUSH_FAST
4320 i = G.count_SIGCHLD;
4322 childpid = waitpid(-1, &status, attributes);
4323 if (childpid <= 0) {
4324 if (childpid && errno != ECHILD)
4325 bb_perror_msg("waitpid");
4326 #if ENABLE_HUSH_FAST
4327 else { /* Until next SIGCHLD, waitpid's are useless */
4328 G.we_have_children = (childpid == 0);
4329 G.handled_SIGCHLD = i;
4330 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4335 dead = WIFEXITED(status) || WIFSIGNALED(status);
4338 if (WIFSTOPPED(status))
4339 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
4340 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4341 if (WIFSIGNALED(status))
4342 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
4343 childpid, WTERMSIG(status), WEXITSTATUS(status));
4344 if (WIFEXITED(status))
4345 debug_printf_jobs("pid %d exited, exitcode %d\n",
4346 childpid, WEXITSTATUS(status));
4348 /* Were we asked to wait for fg pipe? */
4350 for (i = 0; i < fg_pipe->num_cmds; i++) {
4351 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4352 if (fg_pipe->cmds[i].pid != childpid)
4355 fg_pipe->cmds[i].pid = 0;
4356 fg_pipe->alive_cmds--;
4357 if (i == fg_pipe->num_cmds - 1) {
4358 /* last process gives overall exitstatus */
4359 rcode = WEXITSTATUS(status);
4360 /* bash prints killer signal's name for *last*
4361 * process in pipe (prints just newline for SIGINT).
4362 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
4364 if (WIFSIGNALED(status)) {
4365 int sig = WTERMSIG(status);
4366 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
4367 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4368 * Maybe we need to use sig | 128? */
4371 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
4374 fg_pipe->cmds[i].is_stopped = 1;
4375 fg_pipe->stopped_cmds++;
4377 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4378 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4379 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
4380 /* All processes in fg pipe have exited or stopped */
4381 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
4382 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4383 * and "killall -STOP cat" */
4384 if (G_interactive_fd) {
4386 if (fg_pipe->alive_cmds)
4387 insert_bg_job(fg_pipe);
4391 if (!fg_pipe->alive_cmds)
4394 /* There are still running processes in the fg pipe */
4395 goto wait_more; /* do waitpid again */
4397 /* it wasnt fg_pipe, look for process in bg pipes */
4401 /* We asked to wait for bg or orphaned children */
4402 /* No need to remember exitcode in this case */
4403 for (pi = G.job_list; pi; pi = pi->next) {
4404 for (i = 0; i < pi->num_cmds; i++) {
4405 if (pi->cmds[i].pid == childpid)
4406 goto found_pi_and_prognum;
4409 /* Happens when shell is used as init process (init=/bin/sh) */
4410 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
4411 continue; /* do waitpid again */
4413 found_pi_and_prognum:
4416 pi->cmds[i].pid = 0;
4418 if (!pi->alive_cmds) {
4419 if (G_interactive_fd)
4420 printf(JOB_STATUS_FORMAT, pi->jobid,
4421 "Done", pi->cmdtext);
4422 delete_finished_bg_job(pi);
4426 pi->cmds[i].is_stopped = 1;
4430 } /* while (waitpid succeeds)... */
4436 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4439 int rcode = checkjobs(fg_pipe);
4440 if (G_saved_tty_pgrp) {
4441 /* Job finished, move the shell to the foreground */
4442 p = getpgrp(); /* our process group id */
4443 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4444 tcsetpgrp(G_interactive_fd, p);
4450 /* Start all the jobs, but don't wait for anything to finish.
4453 * Return code is normally -1, when the caller has to wait for children
4454 * to finish to determine the exit status of the pipe. If the pipe
4455 * is a simple builtin command, however, the action is done by the
4456 * time run_pipe returns, and the exit code is provided as the
4459 * Returns -1 only if started some children. IOW: we have to
4460 * mask out retvals of builtins etc with 0xff!
4462 * The only case when we do not need to [v]fork is when the pipe
4463 * is single, non-backgrounded, non-subshell command. Examples:
4464 * cmd ; ... { list } ; ...
4465 * cmd && ... { list } && ...
4466 * cmd || ... { list } || ...
4467 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4468 * or (if SH_STANDALONE) an applet, and we can run the { list }
4469 * with run_list. If it isn't one of these, we fork and exec cmd.
4471 * Cases when we must fork:
4472 * non-single: cmd | cmd
4473 * backgrounded: cmd & { list } &
4474 * subshell: ( list ) [&]
4476 #if !ENABLE_HUSH_MODE_X
4477 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4478 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4480 static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4482 /* setup_redirects acts on file descriptors, not FILEs.
4483 * This is perfect for work that comes after exec().
4484 * Is it really safe for inline use? Experimentally,
4485 * things seem to work. */
4486 int rcode = setup_redirects(command, squirrel);
4488 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4489 *new_env_p = new_env;
4490 dump_cmd_in_x_mode(new_env);
4491 dump_cmd_in_x_mode(argv_expanded);
4493 *old_vars_p = set_vars_and_save_old(new_env);
4497 static NOINLINE int run_pipe(struct pipe *pi)
4499 static const char *const null_ptr = NULL;
4503 struct command *command;
4504 char **argv_expanded;
4506 /* it is not always needed, but we aim to smaller code */
4507 int squirrel[] = { -1, -1, -1 };
4510 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
4513 IF_HUSH_JOB(pi->pgrp = -1;)
4514 pi->stopped_cmds = 0;
4515 command = &pi->cmds[0];
4516 argv_expanded = NULL;
4518 if (pi->num_cmds != 1
4519 || pi->followup == PIPE_BG
4520 || command->cmd_type == CMD_SUBSHELL
4527 debug_printf_exec(": group:%p argv:'%s'\n",
4528 command->group, command->argv ? command->argv[0] : "NONE");
4530 if (command->group) {
4531 #if ENABLE_HUSH_FUNCTIONS
4532 if (command->cmd_type == CMD_FUNCDEF) {
4533 /* "executing" func () { list } */
4534 struct function *funcp;
4536 funcp = new_function(command->argv[0]);
4537 /* funcp->name is already set to argv[0] */
4538 funcp->body = command->group;
4540 funcp->body_as_string = command->group_as_string;
4541 command->group_as_string = NULL;
4543 command->group = NULL;
4544 command->argv[0] = NULL;
4545 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4546 funcp->parent_cmd = command;
4547 command->child_func = funcp;
4549 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4551 return EXIT_SUCCESS;
4555 debug_printf("non-subshell group\n");
4556 rcode = 1; /* exitcode if redir failed */
4557 if (setup_redirects(command, squirrel) == 0) {
4558 debug_printf_exec(": run_list\n");
4559 rcode = run_list(command->group) & 0xff;
4561 restore_redirects(squirrel);
4562 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4564 debug_printf_exec("run_pipe: return %d\n", rcode);
4568 argv = command->argv ? command->argv : (char **) &null_ptr;
4570 const struct built_in_command *x;
4571 #if ENABLE_HUSH_FUNCTIONS
4572 const struct function *funcp;
4576 char **new_env = NULL;
4577 struct variable *old_vars = NULL;
4579 if (argv[command->assignment_cnt] == NULL) {
4580 /* Assignments, but no command */
4581 /* Ensure redirects take effect (that is, create files).
4582 * Try "a=t >file" */
4583 #if 0 /* A few cases in testsuite fail with this code. FIXME */
4584 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4585 /* Set shell variables */
4589 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4590 /* Do we need to flag set_local_var() errors?
4591 * "assignment to readonly var" and "putenv error"
4596 /* Redirect error sets $? to 1. Otherwise,
4597 * if evaluating assignment value set $?, retain it.
4598 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4600 rcode = G.last_exitcode;
4601 /* Exit, _skipping_ variable restoring code: */
4602 goto clean_up_and_ret0;
4604 #else /* Older, bigger, but more correct code */
4606 rcode = setup_redirects(command, squirrel);
4607 restore_redirects(squirrel);
4608 /* Set shell variables */
4610 bb_putchar_stderr('+');
4612 char *p = expand_string_to_string(*argv);
4614 fprintf(stderr, " %s", p);
4615 debug_printf_exec("set shell var:'%s'->'%s'\n",
4617 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4618 /* Do we need to flag set_local_var() errors?
4619 * "assignment to readonly var" and "putenv error"
4624 bb_putchar_stderr('\n');
4625 /* Redirect error sets $? to 1. Otherwise,
4626 * if evaluating assignment value set $?, retain it.
4627 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4629 rcode = G.last_exitcode;
4630 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4632 debug_printf_exec("run_pipe: return %d\n", rcode);
4637 /* Expand the rest into (possibly) many strings each */
4639 #if ENABLE_HUSH_BASH_COMPAT
4640 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
4641 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4644 #ifdef CMD_SINGLEWORD_NOGLOB_COND
4645 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4646 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4650 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4653 /* if someone gives us an empty string: `cmd with empty output` */
4654 if (!argv_expanded[0]) {
4655 free(argv_expanded);
4657 return G.last_exitcode;
4660 x = find_builtin(argv_expanded[0]);
4661 #if ENABLE_HUSH_FUNCTIONS
4664 funcp = find_function(argv_expanded[0]);
4668 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
4669 debug_printf("exec with redirects only\n");
4670 rcode = setup_redirects(command, NULL);
4671 goto clean_up_and_ret1;
4674 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4677 debug_printf_exec(": builtin '%s' '%s'...\n",
4678 x->b_cmd, argv_expanded[1]);
4679 rcode = x->b_function(argv_expanded) & 0xff;
4682 #if ENABLE_HUSH_FUNCTIONS
4684 # if ENABLE_HUSH_LOCAL
4685 struct variable **sv;
4686 sv = G.shadowed_vars_pp;
4687 G.shadowed_vars_pp = &old_vars;
4689 debug_printf_exec(": function '%s' '%s'...\n",
4690 funcp->name, argv_expanded[1]);
4691 rcode = run_function(funcp, argv_expanded) & 0xff;
4692 # if ENABLE_HUSH_LOCAL
4693 G.shadowed_vars_pp = sv;
4699 unset_vars(new_env);
4701 /* clean_up_and_ret0: */
4702 restore_redirects(squirrel);
4704 free(argv_expanded);
4705 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
4707 debug_printf_exec("run_pipe return %d\n", rcode);
4711 if (ENABLE_FEATURE_SH_STANDALONE) {
4712 int n = find_applet_by_name(argv_expanded[0]);
4713 if (n >= 0 && APPLET_IS_NOFORK(n)) {
4714 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
4716 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4717 argv_expanded[0], argv_expanded[1]);
4718 rcode = run_nofork_applet(n, argv_expanded);
4720 goto clean_up_and_ret;
4723 /* It is neither builtin nor applet. We must fork. */
4727 /* NB: argv_expanded may already be created, and that
4728 * might include `cmd` runs! Do not rerun it! We *must*
4729 * use argv_expanded if it's non-NULL */
4731 /* Going to fork a child per each pipe member */
4736 while (cmd_no < pi->num_cmds) {
4737 struct fd_pair pipefds;
4739 volatile nommu_save_t nommu_save;
4740 nommu_save.new_env = NULL;
4741 nommu_save.old_vars = NULL;
4742 nommu_save.argv = NULL;
4743 nommu_save.argv_from_re_execing = NULL;
4745 command = &pi->cmds[cmd_no];
4747 if (command->argv) {
4748 debug_printf_exec(": pipe member '%s' '%s'...\n",
4749 command->argv[0], command->argv[1]);
4751 debug_printf_exec(": pipe member with no argv\n");
4754 /* pipes are inserted between pairs of commands */
4757 if (cmd_no < pi->num_cmds)
4758 xpiped_pair(pipefds);
4760 command->pid = BB_MMU ? fork() : vfork();
4761 if (!command->pid) { /* child */
4763 disable_restore_tty_pgrp_on_exit();
4764 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
4766 /* Every child adds itself to new process group
4767 * with pgid == pid_of_first_child_in_pipe */
4768 if (G.run_list_level == 1 && G_interactive_fd) {
4771 if (pgrp < 0) /* true for 1st process only */
4773 if (setpgid(0, pgrp) == 0
4774 && pi->followup != PIPE_BG
4775 && G_saved_tty_pgrp /* we have ctty */
4777 /* We do it in *every* child, not just first,
4779 tcsetpgrp(G_interactive_fd, pgrp);
4783 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4784 /* 1st cmd in backgrounded pipe
4785 * should have its stdin /dev/null'ed */
4787 if (open(bb_dev_null, O_RDONLY))
4788 xopen("/", O_RDONLY);
4790 xmove_fd(next_infd, 0);
4792 xmove_fd(pipefds.wr, 1);
4795 /* Like bash, explicit redirects override pipes,
4796 * and the pipe fd is available for dup'ing. */
4797 if (setup_redirects(command, NULL))
4800 /* Restore default handlers just prior to exec */
4801 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4803 /* Stores to nommu_save list of env vars putenv'ed
4804 * (NOMMU, on MMU we don't need that) */
4805 /* cast away volatility... */
4806 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
4807 /* pseudo_exec() does not return */
4810 /* parent or error */
4811 #if ENABLE_HUSH_FAST
4813 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4815 enable_restore_tty_pgrp_on_exit();
4817 /* Clean up after vforked child */
4818 free(nommu_save.argv);
4819 free(nommu_save.argv_from_re_execing);
4820 unset_vars(nommu_save.new_env);
4821 add_vars(nommu_save.old_vars);
4823 free(argv_expanded);
4824 argv_expanded = NULL;
4825 if (command->pid < 0) { /* [v]fork failed */
4826 /* Clearly indicate, was it fork or vfork */
4827 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
4831 /* Second and next children need to know pid of first one */
4833 pi->pgrp = command->pid;
4839 if (cmd_no < pi->num_cmds)
4841 /* Pass read (output) pipe end to next iteration */
4842 next_infd = pipefds.rd;
4845 if (!pi->alive_cmds) {
4847 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4852 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
4856 #ifndef debug_print_tree
4857 static void debug_print_tree(struct pipe *pi, int lvl)
4859 static const char *const PIPE[] = {
4865 static const char *RES[] = {
4866 [RES_NONE ] = "NONE" ,
4869 [RES_THEN ] = "THEN" ,
4870 [RES_ELIF ] = "ELIF" ,
4871 [RES_ELSE ] = "ELSE" ,
4874 # if ENABLE_HUSH_LOOPS
4875 [RES_FOR ] = "FOR" ,
4876 [RES_WHILE] = "WHILE",
4877 [RES_UNTIL] = "UNTIL",
4879 [RES_DONE ] = "DONE" ,
4881 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
4884 # if ENABLE_HUSH_CASE
4885 [RES_CASE ] = "CASE" ,
4886 [RES_CASE_IN ] = "CASE_IN" ,
4887 [RES_MATCH] = "MATCH",
4888 [RES_CASE_BODY] = "CASE_BODY",
4889 [RES_ESAC ] = "ESAC" ,
4891 [RES_XXXX ] = "XXXX" ,
4892 [RES_SNTX ] = "SNTX" ,
4894 static const char *const CMDTYPE[] = {
4898 # if ENABLE_HUSH_FUNCTIONS
4907 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4908 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
4910 while (prn < pi->num_cmds) {
4911 struct command *command = &pi->cmds[prn];
4912 char **argv = command->argv;
4914 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
4916 command->assignment_cnt);
4917 if (command->group) {
4918 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
4919 CMDTYPE[command->cmd_type],
4922 , " group_as_string:", command->group_as_string
4927 debug_print_tree(command->group, lvl+1);
4931 if (argv) while (*argv) {
4932 fprintf(stderr, " '%s'", *argv);
4935 fprintf(stderr, "\n");
4942 #endif /* debug_print_tree */
4944 /* NB: called by pseudo_exec, and therefore must not modify any
4945 * global data until exec/_exit (we can be a child after vfork!) */
4946 static int run_list(struct pipe *pi)
4948 #if ENABLE_HUSH_CASE
4949 char *case_word = NULL;
4951 #if ENABLE_HUSH_LOOPS
4952 struct pipe *loop_top = NULL;
4953 char **for_lcur = NULL;
4954 char **for_list = NULL;
4956 smallint last_followup;
4958 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
4959 smalluint cond_code = 0;
4961 enum { cond_code = 0 };
4964 smallint rword; /* enum reserved_style */
4965 smallint last_rword; /* ditto */
4968 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
4971 #if ENABLE_HUSH_LOOPS
4972 /* Check syntax for "for" */
4973 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4974 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
4976 /* current word is FOR or IN (BOLD in comments below) */
4977 if (cpipe->next == NULL) {
4978 syntax_error("malformed for");
4980 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4983 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
4984 if (cpipe->next->res_word == RES_DO)
4986 /* next word is not "do". It must be "in" then ("FOR v in ...") */
4987 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4988 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
4990 syntax_error("malformed for");
4992 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
4998 /* Past this point, all code paths should jump to ret: label
4999 * in order to return, no direct "return" statements please.
5000 * This helps to ensure that no memory is leaked. */
5008 last_rword = RES_XXXX;
5010 last_followup = PIPE_SEQ;
5011 rcode = G.last_exitcode;
5013 /* Go through list of pipes, (maybe) executing them. */
5014 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
5018 IF_HAS_KEYWORDS(rword = pi->res_word;)
5019 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
5020 rword, cond_code, last_rword);
5021 #if ENABLE_HUSH_LOOPS
5022 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
5023 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
5025 /* start of a loop: remember where loop starts */
5030 /* Still in the same "if...", "then..." or "do..." branch? */
5031 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
5032 if ((rcode == 0 && last_followup == PIPE_OR)
5033 || (rcode != 0 && last_followup == PIPE_AND)
5035 /* It is "<true> || CMD" or "<false> && CMD"
5036 * and we should not execute CMD */
5037 debug_printf_exec("skipped cmd because of || or &&\n");
5038 last_followup = pi->followup;
5042 last_followup = pi->followup;
5043 IF_HAS_KEYWORDS(last_rword = rword;)
5046 if (rword == RES_THEN) {
5047 /* if false; then ... fi has exitcode 0! */
5048 G.last_exitcode = rcode = EXIT_SUCCESS;
5049 /* "if <false> THEN cmd": skip cmd */
5053 if (rword == RES_ELSE || rword == RES_ELIF) {
5054 /* "if <true> then ... ELSE/ELIF cmd":
5055 * skip cmd and all following ones */
5060 #if ENABLE_HUSH_LOOPS
5061 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
5063 /* first loop through for */
5065 static const char encoded_dollar_at[] ALIGN1 = {
5066 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
5067 }; /* encoded representation of "$@" */
5068 static const char *const encoded_dollar_at_argv[] = {
5069 encoded_dollar_at, NULL
5070 }; /* argv list with one element: "$@" */
5073 vals = (char**)encoded_dollar_at_argv;
5074 if (pi->next->res_word == RES_IN) {
5075 /* if no variable values after "in" we skip "for" */
5076 if (!pi->next->cmds[0].argv) {
5077 G.last_exitcode = rcode = EXIT_SUCCESS;
5078 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
5081 vals = pi->next->cmds[0].argv;
5082 } /* else: "for var; do..." -> assume "$@" list */
5083 /* create list of variable values */
5084 debug_print_strings("for_list made from", vals);
5085 for_list = expand_strvec_to_strvec(vals);
5086 for_lcur = for_list;
5087 debug_print_strings("for_list", for_list);
5090 /* "for" loop is over, clean up */
5096 /* Insert next value from for_lcur */
5097 /* note: *for_lcur already has quotes removed, $var expanded, etc */
5098 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5101 if (rword == RES_IN) {
5102 continue; /* "for v IN list;..." - "in" has no cmds anyway */
5104 if (rword == RES_DONE) {
5105 continue; /* "done" has no cmds too */
5108 #if ENABLE_HUSH_CASE
5109 if (rword == RES_CASE) {
5110 case_word = expand_strvec_to_string(pi->cmds->argv);
5113 if (rword == RES_MATCH) {
5116 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
5118 /* all prev words didn't match, does this one match? */
5119 argv = pi->cmds->argv;
5121 char *pattern = expand_string_to_string(*argv);
5122 /* TODO: which FNM_xxx flags to use? */
5123 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
5125 if (cond_code == 0) { /* match! we will execute this branch */
5126 free(case_word); /* make future "word)" stop */
5134 if (rword == RES_CASE_BODY) { /* inside of a case branch */
5136 continue; /* not matched yet, skip this pipe */
5139 /* Just pressing <enter> in shell should check for jobs.
5140 * OTOH, in non-interactive shell this is useless
5141 * and only leads to extra job checks */
5142 if (pi->num_cmds == 0) {
5143 if (G_interactive_fd)
5144 goto check_jobs_and_continue;
5148 /* After analyzing all keywords and conditions, we decided
5149 * to execute this pipe. NB: have to do checkjobs(NULL)
5150 * after run_pipe to collect any background children,
5151 * even if list execution is to be stopped. */
5152 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
5155 #if ENABLE_HUSH_LOOPS
5156 G.flag_break_continue = 0;
5158 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5160 /* We ran a builtin, function, or group.
5161 * rcode is already known
5162 * and we don't need to wait for anything. */
5163 G.last_exitcode = rcode;
5164 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
5165 check_and_run_traps(0);
5166 #if ENABLE_HUSH_LOOPS
5167 /* Was it "break" or "continue"? */
5168 if (G.flag_break_continue) {
5169 smallint fbc = G.flag_break_continue;
5170 /* We might fall into outer *loop*,
5171 * don't want to break it too */
5173 G.depth_break_continue--;
5174 if (G.depth_break_continue == 0)
5175 G.flag_break_continue = 0;
5176 /* else: e.g. "continue 2" should *break* once, *then* continue */
5177 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
5178 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
5179 goto check_jobs_and_break;
5180 /* "continue": simulate end of loop */
5185 #if ENABLE_HUSH_FUNCTIONS
5186 if (G.flag_return_in_progress == 1) {
5187 /* same as "goto check_jobs_and_break" */
5192 } else if (pi->followup == PIPE_BG) {
5193 /* What does bash do with attempts to background builtins? */
5194 /* even bash 3.2 doesn't do that well with nested bg:
5195 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5196 * I'm NOT treating inner &'s as jobs */
5197 check_and_run_traps(0);
5199 if (G.run_list_level == 1)
5202 /* Last command's pid goes to $! */
5203 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
5204 G.last_exitcode = rcode = EXIT_SUCCESS;
5205 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
5208 if (G.run_list_level == 1 && G_interactive_fd) {
5209 /* Waits for completion, then fg's main shell */
5210 rcode = checkjobs_and_fg_shell(pi);
5211 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
5212 check_and_run_traps(0);
5215 { /* This one just waits for completion */
5216 rcode = checkjobs(pi);
5217 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
5218 check_and_run_traps(0);
5220 G.last_exitcode = rcode;
5224 /* Analyze how result affects subsequent commands */
5226 if (rword == RES_IF || rword == RES_ELIF)
5229 #if ENABLE_HUSH_LOOPS
5230 /* Beware of "while false; true; do ..."! */
5231 if (pi->next && pi->next->res_word == RES_DO) {
5232 if (rword == RES_WHILE) {
5234 /* "while false; do...done" - exitcode 0 */
5235 G.last_exitcode = rcode = EXIT_SUCCESS;
5236 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5237 goto check_jobs_and_break;
5240 if (rword == RES_UNTIL) {
5242 debug_printf_exec(": until expr is true: breaking\n");
5243 check_jobs_and_break:
5251 check_jobs_and_continue:
5258 #if ENABLE_HUSH_LOOPS
5263 #if ENABLE_HUSH_CASE
5267 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
5271 /* Select which version we will use */
5272 static int run_and_free_list(struct pipe *pi)
5275 debug_printf_exec("run_and_free_list entered\n");
5277 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
5278 rcode = run_list(pi);
5280 /* free_pipe_list has the side effect of clearing memory.
5281 * In the long run that function can be merged with run_list,
5282 * but doing that now would hobble the debugging effort. */
5284 debug_printf_exec("run_and_free_list return %d\n", rcode);
5289 static struct pipe *new_pipe(void)
5292 pi = xzalloc(sizeof(struct pipe));
5293 /*pi->followup = 0; - deliberately invalid value */
5294 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
5298 /* Command (member of a pipe) is complete, or we start a new pipe
5299 * if ctx->command is NULL.
5300 * No errors possible here.
5302 static int done_command(struct parse_context *ctx)
5304 /* The command is really already in the pipe structure, so
5305 * advance the pipe counter and make a new, null command. */
5306 struct pipe *pi = ctx->pipe;
5307 struct command *command = ctx->command;
5310 if (IS_NULL_CMD(command)) {
5311 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
5315 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
5316 //debug_print_tree(ctx->list_head, 20);
5318 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5321 /* Only real trickiness here is that the uncommitted
5322 * command structure is not counted in pi->num_cmds. */
5323 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
5324 ctx->command = command = &pi->cmds[pi->num_cmds];
5326 memset(command, 0, sizeof(*command));
5327 return pi->num_cmds; /* used only for 0/nonzero check */
5330 static void done_pipe(struct parse_context *ctx, pipe_style type)
5334 debug_printf_parse("done_pipe entered, followup %d\n", type);
5335 /* Close previous command */
5336 not_null = done_command(ctx);
5337 ctx->pipe->followup = type;
5339 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5340 ctx->ctx_inverted = 0;
5341 ctx->pipe->res_word = ctx->ctx_res_w;
5344 /* Without this check, even just <enter> on command line generates
5345 * tree of three NOPs (!). Which is harmless but annoying.
5346 * IOW: it is safe to do it unconditionally. */
5349 || ctx->ctx_res_w == RES_FI
5351 #if ENABLE_HUSH_LOOPS
5352 || ctx->ctx_res_w == RES_DONE
5353 || ctx->ctx_res_w == RES_FOR
5354 || ctx->ctx_res_w == RES_IN
5356 #if ENABLE_HUSH_CASE
5357 || ctx->ctx_res_w == RES_ESAC
5361 debug_printf_parse("done_pipe: adding new pipe: "
5362 "not_null:%d ctx->ctx_res_w:%d\n",
5363 not_null, ctx->ctx_res_w);
5365 ctx->pipe->next = new_p;
5367 /* RES_THEN, RES_DO etc are "sticky" -
5368 * they remain set for pipes inside if/while.
5369 * This is used to control execution.
5370 * RES_FOR and RES_IN are NOT sticky (needed to support
5371 * cases where variable or value happens to match a keyword):
5373 #if ENABLE_HUSH_LOOPS
5374 if (ctx->ctx_res_w == RES_FOR
5375 || ctx->ctx_res_w == RES_IN)
5376 ctx->ctx_res_w = RES_NONE;
5378 #if ENABLE_HUSH_CASE
5379 if (ctx->ctx_res_w == RES_MATCH)
5380 ctx->ctx_res_w = RES_CASE_BODY;
5381 if (ctx->ctx_res_w == RES_CASE)
5382 ctx->ctx_res_w = RES_CASE_IN;
5384 ctx->command = NULL; /* trick done_command below */
5385 /* Create the memory for command, roughly:
5386 * ctx->pipe->cmds = new struct command;
5387 * ctx->command = &ctx->pipe->cmds[0];
5390 //debug_print_tree(ctx->list_head, 10);
5392 debug_printf_parse("done_pipe return\n");
5395 static void initialize_context(struct parse_context *ctx)
5397 memset(ctx, 0, sizeof(*ctx));
5398 ctx->pipe = ctx->list_head = new_pipe();
5399 /* Create the memory for command, roughly:
5400 * ctx->pipe->cmds = new struct command;
5401 * ctx->command = &ctx->pipe->cmds[0];
5406 /* If a reserved word is found and processed, parse context is modified
5407 * and 1 is returned.
5410 struct reserved_combo {
5413 unsigned char assignment_flag;
5417 FLAG_END = (1 << RES_NONE ),
5419 FLAG_IF = (1 << RES_IF ),
5420 FLAG_THEN = (1 << RES_THEN ),
5421 FLAG_ELIF = (1 << RES_ELIF ),
5422 FLAG_ELSE = (1 << RES_ELSE ),
5423 FLAG_FI = (1 << RES_FI ),
5425 # if ENABLE_HUSH_LOOPS
5426 FLAG_FOR = (1 << RES_FOR ),
5427 FLAG_WHILE = (1 << RES_WHILE),
5428 FLAG_UNTIL = (1 << RES_UNTIL),
5429 FLAG_DO = (1 << RES_DO ),
5430 FLAG_DONE = (1 << RES_DONE ),
5431 FLAG_IN = (1 << RES_IN ),
5433 # if ENABLE_HUSH_CASE
5434 FLAG_MATCH = (1 << RES_MATCH),
5435 FLAG_ESAC = (1 << RES_ESAC ),
5437 FLAG_START = (1 << RES_XXXX ),
5440 static const struct reserved_combo* match_reserved_word(o_string *word)
5442 /* Mostly a list of accepted follow-up reserved words.
5443 * FLAG_END means we are done with the sequence, and are ready
5444 * to turn the compound list into a command.
5445 * FLAG_START means the word must start a new compound list.
5447 static const struct reserved_combo reserved_list[] = {
5449 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5450 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5451 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5452 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5453 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5454 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
5456 # if ENABLE_HUSH_LOOPS
5457 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5458 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5459 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5460 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5461 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5462 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
5464 # if ENABLE_HUSH_CASE
5465 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5466 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
5469 const struct reserved_combo *r;
5471 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5472 if (strcmp(word->data, r->literal) == 0)
5477 /* Return 0: not a keyword, 1: keyword
5479 static int reserved_word(o_string *word, struct parse_context *ctx)
5481 # if ENABLE_HUSH_CASE
5482 static const struct reserved_combo reserved_match = {
5483 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
5486 const struct reserved_combo *r;
5490 r = match_reserved_word(word);
5494 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
5495 # if ENABLE_HUSH_CASE
5496 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5497 /* "case word IN ..." - IN part starts first MATCH part */
5498 r = &reserved_match;
5501 if (r->flag == 0) { /* '!' */
5502 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
5503 syntax_error("! ! command");
5504 ctx->ctx_res_w = RES_SNTX;
5506 ctx->ctx_inverted = 1;
5509 if (r->flag & FLAG_START) {
5510 struct parse_context *old;
5512 old = xmalloc(sizeof(*old));
5513 debug_printf_parse("push stack %p\n", old);
5514 *old = *ctx; /* physical copy */
5515 initialize_context(ctx);
5517 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
5518 syntax_error_at(word->data);
5519 ctx->ctx_res_w = RES_SNTX;
5522 /* "{...} fi" is ok. "{...} if" is not
5524 * if { echo foo; } then { echo bar; } fi */
5525 if (ctx->command->group)
5526 done_pipe(ctx, PIPE_SEQ);
5529 ctx->ctx_res_w = r->res;
5530 ctx->old_flag = r->flag;
5531 word->o_assignment = r->assignment_flag;
5533 if (ctx->old_flag & FLAG_END) {
5534 struct parse_context *old;
5536 done_pipe(ctx, PIPE_SEQ);
5537 debug_printf_parse("pop stack %p\n", ctx->stack);
5539 old->command->group = ctx->list_head;
5540 old->command->cmd_type = CMD_NORMAL;
5542 o_addstr(&old->as_string, ctx->as_string.data);
5543 o_free_unsafe(&ctx->as_string);
5544 old->command->group_as_string = xstrdup(old->as_string.data);
5545 debug_printf_parse("pop, remembering as:'%s'\n",
5546 old->command->group_as_string);
5548 *ctx = *old; /* physical copy */
5553 #endif /* HAS_KEYWORDS */
5555 /* Word is complete, look at it and update parsing context.
5556 * Normal return is 0. Syntax errors return 1.
5557 * Note: on return, word is reset, but not o_free'd!
5559 static int done_word(o_string *word, struct parse_context *ctx)
5561 struct command *command = ctx->command;
5563 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
5564 if (word->length == 0 && word->o_quoted == 0) {
5565 debug_printf_parse("done_word return 0: true null, ignored\n");
5569 if (ctx->pending_redirect) {
5570 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5571 * only if run as "bash", not "sh" */
5572 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5574 * ...the word that follows the redirection operator
5575 * shall be subjected to tilde expansion, parameter expansion,
5576 * command substitution, arithmetic expansion, and quote
5577 * removal. Pathname expansion shall not be performed
5578 * on the word by a non-interactive shell; an interactive
5579 * shell may perform it, but shall do so only when
5580 * the expansion would result in one word."
5582 ctx->pending_redirect->rd_filename = xstrdup(word->data);
5583 /* Cater for >\file case:
5584 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5585 * Same with heredocs:
5586 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5588 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5589 unbackslash(ctx->pending_redirect->rd_filename);
5590 /* Is it <<"HEREDOC"? */
5591 if (word->o_quoted) {
5592 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5595 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
5596 ctx->pending_redirect = NULL;
5598 /* If this word wasn't an assignment, next ones definitely
5599 * can't be assignments. Even if they look like ones. */
5600 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5601 && word->o_assignment != WORD_IS_KEYWORD
5603 word->o_assignment = NOT_ASSIGNMENT;
5605 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5606 command->assignment_cnt++;
5607 word->o_assignment = MAYBE_ASSIGNMENT;
5611 # if ENABLE_HUSH_CASE
5612 if (ctx->ctx_dsemicolon
5613 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5615 /* already done when ctx_dsemicolon was set to 1: */
5616 /* ctx->ctx_res_w = RES_MATCH; */
5617 ctx->ctx_dsemicolon = 0;
5620 if (!command->argv /* if it's the first word... */
5621 # if ENABLE_HUSH_LOOPS
5622 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5623 && ctx->ctx_res_w != RES_IN
5625 # if ENABLE_HUSH_CASE
5626 && ctx->ctx_res_w != RES_CASE
5629 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
5630 if (reserved_word(word, ctx)) {
5631 o_reset_to_empty_unquoted(word);
5632 debug_printf_parse("done_word return %d\n",
5633 (ctx->ctx_res_w == RES_SNTX));
5634 return (ctx->ctx_res_w == RES_SNTX);
5636 # ifdef CMD_SINGLEWORD_NOGLOB_COND
5637 if (strcmp(word->data, "export") == 0
5638 # if ENABLE_HUSH_LOCAL
5639 || strcmp(word->data, "local") == 0
5642 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5645 # if ENABLE_HUSH_BASH_COMPAT
5646 if (strcmp(word->data, "[[") == 0) {
5647 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5653 if (command->group) {
5654 /* "{ echo foo; } echo bar" - bad */
5655 syntax_error_at(word->data);
5656 debug_printf_parse("done_word return 1: syntax error, "
5657 "groups and arglists don't mix\n");
5660 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
5661 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5662 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
5663 /* (otherwise it's known to be not empty and is already safe) */
5665 /* exclude "$@" - it can expand to no word despite "" */
5666 char *p = word->data;
5667 while (p[0] == SPECIAL_VAR_SYMBOL
5668 && (p[1] & 0x7f) == '@'
5669 && p[2] == SPECIAL_VAR_SYMBOL
5673 if (p == word->data || p[0] != '\0') {
5674 /* saw no "$@", or not only "$@" but some
5675 * real text is there too */
5676 /* insert "empty variable" reference, this makes
5677 * e.g. "", $empty"" etc to not disappear */
5678 o_addchr(word, SPECIAL_VAR_SYMBOL);
5679 o_addchr(word, SPECIAL_VAR_SYMBOL);
5682 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
5683 debug_print_strings("word appended to argv", command->argv);
5686 #if ENABLE_HUSH_LOOPS
5687 if (ctx->ctx_res_w == RES_FOR) {
5689 || !is_well_formed_var_name(command->argv[0], '\0')
5691 /* bash says just "not a valid identifier" */
5692 syntax_error("not a valid identifier in for");
5695 /* Force FOR to have just one word (variable name) */
5696 /* NB: basically, this makes hush see "for v in ..."
5697 * syntax as if it is "for v; in ...". FOR and IN become
5698 * two pipe structs in parse tree. */
5699 done_pipe(ctx, PIPE_SEQ);
5702 #if ENABLE_HUSH_CASE
5703 /* Force CASE to have just one word */
5704 if (ctx->ctx_res_w == RES_CASE) {
5705 done_pipe(ctx, PIPE_SEQ);
5709 o_reset_to_empty_unquoted(word);
5711 debug_printf_parse("done_word return 0\n");
5716 /* Peek ahead in the input to find out if we have a "&n" construct,
5717 * as in "2>&1", that represents duplicating a file descriptor.
5719 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5720 * REDIRFD_SYNTAX_ERR if syntax error,
5721 * REDIRFD_TO_FILE if no & was seen,
5722 * or the number found.
5725 #define parse_redir_right_fd(as_string, input) \
5726 parse_redir_right_fd(input)
5728 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
5734 return REDIRFD_TO_FILE;
5736 ch = i_getch(input); /* get the & */
5737 nommu_addchr(as_string, ch);
5740 ch = i_getch(input);
5741 nommu_addchr(as_string, ch);
5742 return REDIRFD_CLOSE;
5746 while (ch != EOF && isdigit(ch)) {
5747 d = d*10 + (ch-'0');
5749 ch = i_getch(input);
5750 nommu_addchr(as_string, ch);
5755 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5757 bb_error_msg("ambiguous redirect");
5758 return REDIRFD_SYNTAX_ERR;
5761 /* Return code is 0 normal, 1 if a syntax error is detected
5763 static int parse_redirect(struct parse_context *ctx,
5766 struct in_str *input)
5768 struct command *command = ctx->command;
5769 struct redir_struct *redir;
5770 struct redir_struct **redirp;
5773 dup_num = REDIRFD_TO_FILE;
5774 if (style != REDIRECT_HEREDOC) {
5775 /* Check for a '>&1' type redirect */
5776 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5777 if (dup_num == REDIRFD_SYNTAX_ERR)
5780 int ch = i_peek(input);
5781 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
5782 if (dup_num) { /* <<-... */
5783 ch = i_getch(input);
5784 nommu_addchr(&ctx->as_string, ch);
5789 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
5790 int ch = i_peek(input);
5792 /* >|FILE redirect ("clobbering" >).
5793 * Since we do not support "set -o noclobber" yet,
5794 * >| and > are the same for now. Just eat |.
5796 ch = i_getch(input);
5797 nommu_addchr(&ctx->as_string, ch);
5801 /* Create a new redir_struct and append it to the linked list */
5802 redirp = &command->redirects;
5803 while ((redir = *redirp) != NULL) {
5804 redirp = &(redir->next);
5806 *redirp = redir = xzalloc(sizeof(*redir));
5807 /* redir->next = NULL; */
5808 /* redir->rd_filename = NULL; */
5809 redir->rd_type = style;
5810 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
5812 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5813 redir_table[style].descrip);
5815 redir->rd_dup = dup_num;
5816 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
5817 /* Erik had a check here that the file descriptor in question
5818 * is legit; I postpone that to "run time"
5819 * A "-" representation of "close me" shows up as a -3 here */
5820 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5821 redir->rd_fd, redir->rd_dup);
5823 /* Set ctx->pending_redirect, so we know what to do at the
5824 * end of the next parsed word. */
5825 ctx->pending_redirect = redir;
5830 /* If a redirect is immediately preceded by a number, that number is
5831 * supposed to tell which file descriptor to redirect. This routine
5832 * looks for such preceding numbers. In an ideal world this routine
5833 * needs to handle all the following classes of redirects...
5834 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5835 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5836 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5837 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
5839 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5841 * ... If n is quoted, the number shall not be recognized as part of
5842 * the redirection expression. For example:
5844 * writes the character 2 into file a"
5845 * We are getting it right by setting ->o_quoted on any \<char>
5847 * A -1 return means no valid number was found,
5848 * the caller should use the appropriate default for this redirection.
5850 static int redirect_opt_num(o_string *o)
5854 if (o->data == NULL)
5856 num = bb_strtou(o->data, NULL, 10);
5857 if (errno || num < 0)
5859 o_reset_to_empty_unquoted(o);
5864 #define fetch_till_str(as_string, input, word, skip_tabs) \
5865 fetch_till_str(input, word, skip_tabs)
5867 static char *fetch_till_str(o_string *as_string,
5868 struct in_str *input,
5872 o_string heredoc = NULL_O_STRING;
5878 ch = i_getch(input);
5879 nommu_addchr(as_string, ch);
5881 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5882 heredoc.data[past_EOL] = '\0';
5883 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5884 return heredoc.data;
5887 o_addchr(&heredoc, ch);
5888 past_EOL = heredoc.length;
5891 ch = i_getch(input);
5892 nommu_addchr(as_string, ch);
5893 } while (skip_tabs && ch == '\t');
5894 } while (ch == '\n');
5897 o_free_unsafe(&heredoc);
5900 o_addchr(&heredoc, ch);
5901 nommu_addchr(as_string, ch);
5905 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5906 * and load them all. There should be exactly heredoc_cnt of them.
5908 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5910 struct pipe *pi = ctx->list_head;
5912 while (pi && heredoc_cnt) {
5914 struct command *cmd = pi->cmds;
5916 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5918 cmd->argv ? cmd->argv[0] : "NONE");
5919 for (i = 0; i < pi->num_cmds; i++) {
5920 struct redir_struct *redir = cmd->redirects;
5922 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5923 i, cmd->argv ? cmd->argv[0] : "NONE");
5925 if (redir->rd_type == REDIRECT_HEREDOC) {
5928 redir->rd_type = REDIRECT_HEREDOC2;
5929 /* redir->rd_dup is (ab)used to indicate <<- */
5930 p = fetch_till_str(&ctx->as_string, input,
5931 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
5933 syntax_error("unexpected EOF in here document");
5936 free(redir->rd_filename);
5937 redir->rd_filename = p;
5940 redir = redir->next;
5947 /* Should be 0. If it isn't, it's a parse error */
5949 bb_error_msg_and_die("heredoc BUG 2");
5955 #if ENABLE_HUSH_TICK
5956 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5961 char **to_free = NULL;
5965 pid = BB_MMU ? xfork() : xvfork();
5966 if (pid == 0) { /* child */
5967 disable_restore_tty_pgrp_on_exit();
5968 /* Process substitution is not considered to be usual
5969 * 'command execution'.
5970 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5977 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5978 close(channel[0]); /* NB: close _first_, then move fd! */
5979 xmove_fd(channel[1], 1);
5980 /* Prevent it from trying to handle ctrl-z etc */
5981 IF_HUSH_JOB(G.run_list_level = 1;)
5982 /* Awful hack for `trap` or $(trap).
5984 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5985 * contains an example where "trap" is executed in a subshell:
5987 * save_traps=$(trap)
5989 * eval "$save_traps"
5991 * Standard does not say that "trap" in subshell shall print
5992 * parent shell's traps. It only says that its output
5993 * must have suitable form, but then, in the above example
5994 * (which is not supposed to be normative), it implies that.
5996 * bash (and probably other shell) does implement it
5997 * (traps are reset to defaults, but "trap" still shows them),
5998 * but as a result, "trap" logic is hopelessly messed up:
6001 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6002 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6003 * # true | trap <--- trap is in subshell - no output (ditto)
6004 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6005 * trap -- 'echo Ho' SIGWINCH
6006 * # echo `(trap)` <--- in subshell in subshell - output
6007 * trap -- 'echo Ho' SIGWINCH
6008 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6009 * trap -- 'echo Ho' SIGWINCH
6011 * The rules when to forget and when to not forget traps
6012 * get really complex and nonsensical.
6014 * Our solution: ONLY bare $(trap) or `trap` is special.
6016 s = skip_whitespace(s);
6017 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
6019 static const char *const argv[] = { NULL, NULL };
6020 builtin_trap((char**)argv);
6021 exit(0); /* not _exit() - we need to fflush */
6024 reset_traps_to_defaults();
6025 parse_and_run_string(s);
6026 _exit(G.last_exitcode);
6028 /* We re-execute after vfork on NOMMU. This makes this script safe:
6029 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6030 * huge=`cat BIG` # was blocking here forever
6033 re_execute_shell(&to_free,
6043 # if ENABLE_HUSH_FAST
6045 //bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6047 enable_restore_tty_pgrp_on_exit();
6052 close_on_exec_on(channel[0]);
6053 return xfdopen_for_read(channel[0]);
6056 /* Return code is exit status of the process that is run. */
6057 static int process_command_subs(o_string *dest, const char *s)
6060 struct in_str pipe_str;
6062 int status, ch, eol_cnt;
6064 fp = generate_stream_from_string(s, &pid);
6066 /* Now send results of command back into original context */
6067 setup_file_in_str(&pipe_str, fp);
6069 while ((ch = i_getch(&pipe_str)) != EOF) {
6075 o_addchr(dest, '\n');
6078 o_addQchr(dest, ch);
6081 debug_printf("done reading from `cmd` pipe, closing it\n");
6083 /* We need to extract exitcode. Test case
6084 * "true; echo `sleep 1; false` $?"
6086 safe_waitpid(pid, &status, 0);
6087 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6088 return WEXITSTATUS(status);
6090 #endif /* ENABLE_HUSH_TICK */
6092 #if !ENABLE_HUSH_FUNCTIONS
6093 #define parse_group(dest, ctx, input, ch) \
6094 parse_group(ctx, input, ch)
6096 static int parse_group(o_string *dest, struct parse_context *ctx,
6097 struct in_str *input, int ch)
6099 /* dest contains characters seen prior to ( or {.
6100 * Typically it's empty, but for function defs,
6101 * it contains function name (without '()'). */
6102 struct pipe *pipe_list;
6104 struct command *command = ctx->command;
6106 debug_printf_parse("parse_group entered\n");
6107 #if ENABLE_HUSH_FUNCTIONS
6108 if (ch == '(' && !dest->o_quoted) {
6110 if (done_word(dest, ctx))
6113 goto skip; /* (... */
6114 if (command->argv[1]) { /* word word ... (... */
6115 syntax_error_unexpected_ch('(');
6118 /* it is "word(..." or "word (..." */
6120 ch = i_getch(input);
6121 while (ch == ' ' || ch == '\t');
6123 syntax_error_unexpected_ch(ch);
6126 nommu_addchr(&ctx->as_string, ch);
6128 ch = i_getch(input);
6129 while (ch == ' ' || ch == '\t' || ch == '\n');
6131 syntax_error_unexpected_ch(ch);
6134 nommu_addchr(&ctx->as_string, ch);
6135 command->cmd_type = CMD_FUNCDEF;
6140 #if 0 /* Prevented by caller */
6141 if (command->argv /* word [word]{... */
6142 || dest->length /* word{... */
6143 || dest->o_quoted /* ""{... */
6146 debug_printf_parse("parse_group return 1: "
6147 "syntax error, groups and arglists don't mix\n");
6152 #if ENABLE_HUSH_FUNCTIONS
6158 command->cmd_type = CMD_SUBSHELL;
6160 /* bash does not allow "{echo...", requires whitespace */
6161 ch = i_getch(input);
6162 if (ch != ' ' && ch != '\t' && ch != '\n') {
6163 syntax_error_unexpected_ch(ch);
6166 nommu_addchr(&ctx->as_string, ch);
6171 # define as_string NULL
6173 char *as_string = NULL;
6175 pipe_list = parse_stream(&as_string, input, endch);
6178 o_addstr(&ctx->as_string, as_string);
6180 /* empty ()/{} or parse error? */
6181 if (!pipe_list || pipe_list == ERR_PTR) {
6182 /* parse_stream already emitted error msg */
6185 debug_printf_parse("parse_group return 1: "
6186 "parse_stream returned %p\n", pipe_list);
6189 command->group = pipe_list;
6191 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6192 command->group_as_string = as_string;
6193 debug_printf_parse("end of group, remembering as:'%s'\n",
6194 command->group_as_string);
6198 debug_printf_parse("parse_group return 0\n");
6200 /* command remains "open", available for possible redirects */
6203 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
6204 /* Subroutines for copying $(...) and `...` things */
6205 static void add_till_backquote(o_string *dest, struct in_str *input);
6207 static void add_till_single_quote(o_string *dest, struct in_str *input)
6210 int ch = i_getch(input);
6212 syntax_error_unterm_ch('\'');
6213 /*xfunc_die(); - redundant */
6220 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
6221 static void add_till_double_quote(o_string *dest, struct in_str *input)
6224 int ch = i_getch(input);
6226 syntax_error_unterm_ch('"');
6227 /*xfunc_die(); - redundant */
6231 if (ch == '\\') { /* \x. Copy both chars. */
6233 ch = i_getch(input);
6237 add_till_backquote(dest, input);
6241 //if (ch == '$') ...
6244 /* Process `cmd` - copy contents until "`" is seen. Complicated by
6246 * "Within the backquoted style of command substitution, backslash
6247 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6248 * The search for the matching backquote shall be satisfied by the first
6249 * backquote found without a preceding backslash; during this search,
6250 * if a non-escaped backquote is encountered within a shell comment,
6251 * a here-document, an embedded command substitution of the $(command)
6252 * form, or a quoted string, undefined results occur. A single-quoted
6253 * or double-quoted string that begins, but does not end, within the
6254 * "`...`" sequence produces undefined results."
6256 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6258 static void add_till_backquote(o_string *dest, struct in_str *input)
6261 int ch = i_getch(input);
6263 syntax_error_unterm_ch('`');
6264 /*xfunc_die(); - redundant */
6269 /* \x. Copy both chars unless it is \` */
6270 int ch2 = i_getch(input);
6272 syntax_error_unterm_ch('`');
6273 /*xfunc_die(); - redundant */
6275 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
6282 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
6283 * quoting and nested ()s.
6284 * "With the $(command) style of command substitution, all characters
6285 * following the open parenthesis to the matching closing parenthesis
6286 * constitute the command. Any valid shell script can be used for command,
6287 * except a script consisting solely of redirections which produces
6288 * unspecified results."
6290 * echo $(echo '(TEST)' BEST) (TEST) BEST
6291 * echo $(echo 'TEST)' BEST) TEST) BEST
6292 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
6294 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
6295 * can contain arbitrary constructs, just like $(cmd).
6296 * In bash compat mode, it needs to also be able to stop on ':' or '/'
6297 * for ${var:N[:M]} and ${var/P[/R]} parsing.
6299 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
6300 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
6303 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
6304 # if ENABLE_HUSH_BASH_COMPAT
6305 char end_char2 = end_ch >> 8;
6307 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6310 ch = i_getch(input);
6312 syntax_error_unterm_ch(end_ch);
6313 /*xfunc_die(); - redundant */
6315 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
6318 /* we look for closing )) of $((EXPR)) */
6319 if (i_peek(input) == end_ch) {
6320 i_getch(input); /* eat second ')' */
6325 if (ch == '(' || ch == '{') {
6326 ch = (ch == '(' ? ')' : '}');
6327 add_till_closing_bracket(dest, input, ch);
6332 add_till_single_quote(dest, input);
6337 add_till_double_quote(dest, input);
6342 add_till_backquote(dest, input);
6347 /* \x. Copy verbatim. Important for \(, \) */
6348 ch = i_getch(input);
6350 syntax_error_unterm_ch(')');
6351 /*xfunc_die(); - redundant */
6359 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
6361 /* Return code: 0 for OK, 1 for syntax error */
6363 #define parse_dollar(as_string, dest, input) \
6364 parse_dollar(dest, input)
6365 #define as_string NULL
6367 static int parse_dollar(o_string *as_string,
6369 struct in_str *input)
6371 int ch = i_peek(input); /* first character after the $ */
6372 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
6374 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
6376 ch = i_getch(input);
6377 nommu_addchr(as_string, ch);
6379 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6381 debug_printf_parse(": '%c'\n", ch);
6382 o_addchr(dest, ch | quote_mask);
6385 if (!isalnum(ch) && ch != '_')
6387 ch = i_getch(input);
6388 nommu_addchr(as_string, ch);
6390 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6391 } else if (isdigit(ch)) {
6393 ch = i_getch(input);
6394 nommu_addchr(as_string, ch);
6395 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6396 debug_printf_parse(": '%c'\n", ch);
6397 o_addchr(dest, ch | quote_mask);
6398 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6399 } else switch (ch) {
6401 case '!': /* last bg pid */
6402 case '?': /* last exit code */
6403 case '#': /* number of args */
6404 case '*': /* args */
6405 case '@': /* args */
6406 goto make_one_char_var;
6408 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6410 ch = i_getch(input); /* eat '{' */
6411 nommu_addchr(as_string, ch);
6413 ch = i_getch(input); /* first char after '{' */
6414 nommu_addchr(as_string, ch);
6415 /* It should be ${?}, or ${#var},
6416 * or even ${?+subst} - operator acting on a special variable,
6417 * or the beginning of variable name.
6419 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
6421 syntax_error_unterm_str("${name}");
6422 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
6427 /* It's possible to just call add_till_closing_bracket() at this point.
6428 * However, this regresses some of our testsuite cases
6429 * which check invalid constructs like ${%}.
6430 * Oh well... let's check that the var name part is fine... */
6436 debug_printf_parse(": '%c'\n", ch);
6438 ch = i_getch(input);
6439 nommu_addchr(as_string, ch);
6443 if (!isalnum(ch) && ch != '_') {
6445 unsigned char last_ch;
6446 /* handle parameter expansions
6447 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6449 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
6450 goto bad_dollar_syntax;
6452 /* Eat everything until closing '}' (or ':') */
6454 if (ENABLE_HUSH_BASH_COMPAT
6456 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
6458 /* It's ${var:N[:M]} thing */
6459 end_ch = '}' * 0x100 + ':';
6461 if (ENABLE_HUSH_BASH_COMPAT
6464 /* It's ${var/[/]pattern[/repl]} thing */
6465 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
6467 nommu_addchr(as_string, '/');
6470 end_ch = '}' * 0x100 + '/';
6476 #if ENABLE_HUSH_DOLLAR_OPS
6477 last_ch = add_till_closing_bracket(dest, input, end_ch);
6479 #error Simple code to only allow ${var} is not implemented
6482 o_addstr(as_string, dest->data + pos);
6483 o_addchr(as_string, last_ch);
6486 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6487 /* close the first block: */
6488 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6489 /* while parsing N from ${var:N[:M]}
6490 * or pattern from ${var/[/]pattern[/repl]} */
6491 if ((end_ch & 0xff) == last_ch) {
6492 /* got ':' or '/'- parse the rest */
6497 if (end_ch == '}' * 0x100 + ':') {
6498 /* it's ${var:N} - emulate :999999999 */
6499 o_addstr(dest, "999999999");
6500 } /* else: it's ${var/[/]pattern} */
6505 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6508 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
6512 ch = i_getch(input);
6513 nommu_addchr(as_string, ch);
6514 # if ENABLE_SH_MATH_SUPPORT
6515 if (i_peek(input) == '(') {
6516 ch = i_getch(input);
6517 nommu_addchr(as_string, ch);
6518 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6519 o_addchr(dest, /*quote_mask |*/ '+');
6522 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
6524 o_addstr(as_string, dest->data + pos);
6525 o_addchr(as_string, ')');
6526 o_addchr(as_string, ')');
6528 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6532 # if ENABLE_HUSH_TICK
6533 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6534 o_addchr(dest, quote_mask | '`');
6537 add_till_closing_bracket(dest, input, ')');
6539 o_addstr(as_string, dest->data + pos);
6540 o_addchr(as_string, ')');
6542 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6548 ch = i_getch(input);
6549 nommu_addchr(as_string, ch);
6551 if (isalnum(ch)) { /* it's $_name or $_123 */
6556 /* TODO: $_ and $-: */
6557 /* $_ Shell or shell script name; or last argument of last command
6558 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6559 * but in command's env, set to full pathname used to invoke it */
6560 /* $- Option flags set by set builtin or shell options (-i etc) */
6562 o_addQchr(dest, '$');
6564 debug_printf_parse("parse_dollar return 0\n");
6570 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
6571 parse_stream_dquoted(dest, input, dquote_end)
6572 #define as_string NULL
6574 static int parse_stream_dquoted(o_string *as_string,
6576 struct in_str *input,
6583 ch = i_getch(input);
6585 nommu_addchr(as_string, ch);
6586 if (ch == dquote_end) { /* may be only '"' or EOF */
6587 if (dest->o_assignment == NOT_ASSIGNMENT)
6588 dest->o_escape ^= 1;
6589 debug_printf_parse("parse_stream_dquoted return 0\n");
6592 /* note: can't move it above ch == dquote_end check! */
6594 syntax_error_unterm_ch('"');
6595 /*xfunc_die(); - redundant */
6599 next = i_peek(input);
6601 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
6602 ch, ch, dest->o_escape);
6605 syntax_error("\\<eof>");
6609 * "The backslash retains its special meaning [in "..."]
6610 * only when followed by one of the following characters:
6611 * $, `, ", \, or <newline>. A double quote may be quoted
6612 * within double quotes by preceding it with a backslash."
6614 if (strchr("$`\"\\\n", next) != NULL) {
6615 ch = i_getch(input);
6617 o_addqchr(dest, ch);
6618 nommu_addchr(as_string, ch);
6621 o_addqchr(dest, '\\');
6622 nommu_addchr(as_string, '\\');
6627 if (parse_dollar(as_string, dest, input) != 0) {
6628 debug_printf_parse("parse_stream_dquoted return 1: "
6629 "parse_dollar returned non-0\n");
6634 #if ENABLE_HUSH_TICK
6636 //unsigned pos = dest->length;
6637 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6638 o_addchr(dest, 0x80 | '`');
6639 add_till_backquote(dest, input);
6640 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6641 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
6645 o_addQchr(dest, ch);
6647 && (dest->o_assignment == MAYBE_ASSIGNMENT
6648 || dest->o_assignment == WORD_IS_KEYWORD)
6649 && is_well_formed_var_name(dest->data, '=')
6651 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6658 * Scan input until EOF or end_trigger char.
6659 * Return a list of pipes to execute, or NULL on EOF
6660 * or if end_trigger character is met.
6661 * On syntax error, exit is shell is not interactive,
6662 * reset parsing machinery and start parsing anew,
6663 * or return ERR_PTR.
6665 static struct pipe *parse_stream(char **pstring,
6666 struct in_str *input,
6669 struct parse_context ctx;
6670 o_string dest = NULL_O_STRING;
6674 /* Double-quote state is handled in the state variable is_in_dquote.
6675 * A single-quote triggers a bypass of the main loop until its mate is
6676 * found. When recursing, quote state is passed in via dest->o_escape.
6678 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
6679 end_trigger ? end_trigger : 'X');
6682 /* If very first arg is "" or '', dest.data may end up NULL.
6683 * Preventing this: */
6684 o_addchr(&dest, '\0');
6687 G.ifs = get_local_var_value("IFS");
6692 #if ENABLE_HUSH_INTERACTIVE
6693 input->promptmode = 0; /* PS1 */
6695 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6696 initialize_context(&ctx);
6701 const char *is_special;
6705 redir_type redir_style;
6708 /* dest.o_quoted = 1; - already is (see below) */
6709 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
6712 /* We reached closing '"' */
6715 ch = i_getch(input);
6716 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6717 ch, ch, dest.o_escape);
6722 syntax_error_unterm_str("here document");
6725 /* end_trigger == '}' case errors out earlier,
6726 * checking only ')' */
6727 if (end_trigger == ')') {
6728 syntax_error_unterm_ch('('); /* exits */
6729 /* goto parse_error; */
6732 if (done_word(&dest, &ctx)) {
6736 done_pipe(&ctx, PIPE_SEQ);
6738 /* If we got nothing... */
6739 /* (this makes bare "&" cmd a no-op.
6740 * bash says: "syntax error near unexpected token '&'") */
6741 if (pi->num_cmds == 0
6742 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6748 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6750 *pstring = ctx.as_string.data;
6752 o_free_unsafe(&ctx.as_string);
6755 debug_printf_parse("parse_stream return %p\n", pi);
6758 nommu_addchr(&ctx.as_string, ch);
6762 next = i_peek(input);
6764 is_special = "{}<>;&|()#'" /* special outside of "str" */
6765 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6766 /* Are { and } special here? */
6767 if (ctx.command->argv /* word [word]{... - non-special */
6768 || dest.length /* word{... - non-special */
6769 || dest.o_quoted /* ""{... - non-special */
6770 || (next != ';' /* }; - special */
6771 && next != ')' /* }) - special */
6772 && next != '&' /* }& and }&& ... - special */
6773 && next != '|' /* }|| ... - special */
6774 && !strchr(G.ifs, next) /* {word - non-special */
6777 /* They are not special, skip "{}" */
6780 is_special = strchr(is_special, ch);
6781 is_ifs = strchr(G.ifs, ch);
6783 if (!is_special && !is_ifs) { /* ordinary char */
6785 o_addQchr(&dest, ch);
6786 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6787 || dest.o_assignment == WORD_IS_KEYWORD)
6789 && is_well_formed_var_name(dest.data, '=')
6791 dest.o_assignment = DEFINITELY_ASSIGNMENT;
6797 if (done_word(&dest, &ctx)) {
6801 #if ENABLE_HUSH_CASE
6802 /* "case ... in <newline> word) ..." -
6803 * newlines are ignored (but ';' wouldn't be) */
6804 if (ctx.command->argv == NULL
6805 && ctx.ctx_res_w == RES_MATCH
6810 /* Treat newline as a command separator. */
6811 done_pipe(&ctx, PIPE_SEQ);
6812 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6814 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
6819 dest.o_assignment = MAYBE_ASSIGNMENT;
6821 /* note: if (is_ifs) continue;
6822 * will still trigger for us */
6826 /* "cmd}" or "cmd }..." without semicolon or &:
6827 * } is an ordinary char in this case, even inside { cmd; }
6828 * Pathological example: { ""}; } should exec "}" cmd
6831 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6832 || dest.length != 0 /* word} */
6833 || dest.o_quoted /* ""} */
6837 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6838 goto skip_end_trigger;
6839 /* else: } does terminate a group */
6842 if (end_trigger && end_trigger == ch
6843 && (ch != ';' || heredoc_cnt == 0)
6844 #if ENABLE_HUSH_CASE
6846 || ctx.ctx_res_w != RES_MATCH
6847 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6852 /* This is technically valid:
6853 * { cat <<HERE; }; echo Ok
6857 * but we don't support this.
6858 * We require heredoc to be in enclosing {}/(),
6861 syntax_error_unterm_str("here document");
6864 if (done_word(&dest, &ctx)) {
6867 done_pipe(&ctx, PIPE_SEQ);
6868 dest.o_assignment = MAYBE_ASSIGNMENT;
6869 /* Do we sit outside of any if's, loops or case's? */
6871 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
6875 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6877 *pstring = ctx.as_string.data;
6879 o_free_unsafe(&ctx.as_string);
6882 debug_printf_parse("parse_stream return %p: "
6883 "end_trigger char found\n",
6885 return ctx.list_head;
6892 /* Catch <, > before deciding whether this word is
6893 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6896 redir_fd = redirect_opt_num(&dest);
6897 if (done_word(&dest, &ctx)) {
6900 redir_style = REDIRECT_OVERWRITE;
6902 redir_style = REDIRECT_APPEND;
6903 ch = i_getch(input);
6904 nommu_addchr(&ctx.as_string, ch);
6907 else if (next == '(') {
6908 syntax_error(">(process) not supported");
6912 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6914 continue; /* back to top of while (1) */
6916 redir_fd = redirect_opt_num(&dest);
6917 if (done_word(&dest, &ctx)) {
6920 redir_style = REDIRECT_INPUT;
6922 redir_style = REDIRECT_HEREDOC;
6924 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6925 ch = i_getch(input);
6926 nommu_addchr(&ctx.as_string, ch);
6927 } else if (next == '>') {
6928 redir_style = REDIRECT_IO;
6929 ch = i_getch(input);
6930 nommu_addchr(&ctx.as_string, ch);
6933 else if (next == '(') {
6934 syntax_error("<(process) not supported");
6938 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6940 continue; /* back to top of while (1) */
6943 if (dest.o_assignment == MAYBE_ASSIGNMENT
6944 /* check that we are not in word in "a=1 2>word b=1": */
6945 && !ctx.pending_redirect
6947 /* ch is a special char and thus this word
6948 * cannot be an assignment */
6949 dest.o_assignment = NOT_ASSIGNMENT;
6952 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6956 if (dest.length == 0) {
6959 if (ch == EOF || ch == '\n')
6962 /* note: we do not add it to &ctx.as_string */
6964 nommu_addchr(&ctx.as_string, '\n');
6966 o_addQchr(&dest, ch);
6971 syntax_error("\\<eof>");
6974 ch = i_getch(input);
6976 o_addchr(&dest, '\\');
6977 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
6978 o_addchr(&dest, ch);
6979 nommu_addchr(&ctx.as_string, ch);
6980 /* Example: echo Hello \2>file
6981 * we need to know that word 2 is quoted */
6986 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6987 ctx.as_string.data[--ctx.as_string.length] = '\0';
6992 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
6993 debug_printf_parse("parse_stream parse error: "
6994 "parse_dollar returned non-0\n");
7001 ch = i_getch(input);
7003 syntax_error_unterm_ch('\'');
7004 /*xfunc_die(); - redundant */
7006 nommu_addchr(&ctx.as_string, ch);
7009 o_addqchr(&dest, ch);
7014 is_in_dquote ^= 1; /* invert */
7015 if (dest.o_assignment == NOT_ASSIGNMENT)
7018 #if ENABLE_HUSH_TICK
7022 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
7023 o_addchr(&dest, '`');
7025 add_till_backquote(&dest, input);
7027 o_addstr(&ctx.as_string, dest.data + pos);
7028 o_addchr(&ctx.as_string, '`');
7030 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
7031 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
7036 #if ENABLE_HUSH_CASE
7039 if (done_word(&dest, &ctx)) {
7042 done_pipe(&ctx, PIPE_SEQ);
7043 #if ENABLE_HUSH_CASE
7044 /* Eat multiple semicolons, detect
7045 * whether it means something special */
7050 ch = i_getch(input);
7051 nommu_addchr(&ctx.as_string, ch);
7052 if (ctx.ctx_res_w == RES_CASE_BODY) {
7053 ctx.ctx_dsemicolon = 1;
7054 ctx.ctx_res_w = RES_MATCH;
7060 /* We just finished a cmd. New one may start
7061 * with an assignment */
7062 dest.o_assignment = MAYBE_ASSIGNMENT;
7065 if (done_word(&dest, &ctx)) {
7069 ch = i_getch(input);
7070 nommu_addchr(&ctx.as_string, ch);
7071 done_pipe(&ctx, PIPE_AND);
7073 done_pipe(&ctx, PIPE_BG);
7077 if (done_word(&dest, &ctx)) {
7080 #if ENABLE_HUSH_CASE
7081 if (ctx.ctx_res_w == RES_MATCH)
7082 break; /* we are in case's "word | word)" */
7084 if (next == '|') { /* || */
7085 ch = i_getch(input);
7086 nommu_addchr(&ctx.as_string, ch);
7087 done_pipe(&ctx, PIPE_OR);
7089 /* we could pick up a file descriptor choice here
7090 * with redirect_opt_num(), but bash doesn't do it.
7091 * "echo foo 2| cat" yields "foo 2". */
7094 o_reset_to_empty_unquoted(&ctx.as_string);
7099 #if ENABLE_HUSH_CASE
7100 /* "case... in [(]word)..." - skip '(' */
7101 if (ctx.ctx_res_w == RES_MATCH
7102 && ctx.command->argv == NULL /* not (word|(... */
7103 && dest.length == 0 /* not word(... */
7104 && dest.o_quoted == 0 /* not ""(... */
7110 if (parse_group(&dest, &ctx, input, ch) != 0) {
7115 #if ENABLE_HUSH_CASE
7116 if (ctx.ctx_res_w == RES_MATCH)
7120 /* proper use of this character is caught by end_trigger:
7121 * if we see {, we call parse_group(..., end_trigger='}')
7122 * and it will match } earlier (not here). */
7123 syntax_error_unexpected_ch(ch);
7127 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
7133 struct parse_context *pctx;
7134 IF_HAS_KEYWORDS(struct parse_context *p2;)
7136 /* Clean up allocated tree.
7137 * Sample for finding leaks on syntax error recovery path.
7138 * Run it from interactive shell, watch pmap `pidof hush`.
7139 * while if false; then false; fi; do break; fi
7140 * Samples to catch leaks at execution:
7141 * while if (true | {true;}); then echo ok; fi; do break; done
7142 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
7146 /* Update pipe/command counts,
7147 * otherwise freeing may miss some */
7148 done_pipe(pctx, PIPE_SEQ);
7149 debug_printf_clean("freeing list %p from ctx %p\n",
7150 pctx->list_head, pctx);
7151 debug_print_tree(pctx->list_head, 0);
7152 free_pipe_list(pctx->list_head);
7153 debug_printf_clean("freed list %p\n", pctx->list_head);
7155 o_free_unsafe(&pctx->as_string);
7157 IF_HAS_KEYWORDS(p2 = pctx->stack;)
7161 IF_HAS_KEYWORDS(pctx = p2;)
7162 } while (HAS_KEYWORDS && pctx);
7163 /* Free text, clear all dest fields */
7165 /* If we are not in top-level parse, we return,
7166 * our caller will propagate error.
7168 if (end_trigger != ';') {
7176 /* Discard cached input, force prompt */
7178 IF_HUSH_INTERACTIVE(input->promptme = 1;)
7183 /* Executing from string: eval, sh -c '...'
7184 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7185 * end_trigger controls how often we stop parsing
7186 * NUL: parse all, execute, return
7187 * ';': parse till ';' or newline, execute, repeat till EOF
7189 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
7191 /* Why we need empty flag?
7192 * An obscure corner case "false; ``; echo $?":
7193 * empty command in `` should still set $? to 0.
7194 * But we can't just set $? to 0 at the start,
7195 * this breaks "false; echo `echo $?`" case.
7199 struct pipe *pipe_list;
7201 pipe_list = parse_stream(NULL, inp, end_trigger);
7202 if (!pipe_list) { /* EOF */
7204 G.last_exitcode = 0;
7207 debug_print_tree(pipe_list, 0);
7208 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7209 run_and_free_list(pipe_list);
7214 static void parse_and_run_string(const char *s)
7216 struct in_str input;
7217 setup_string_in_str(&input, s);
7218 parse_and_run_stream(&input, '\0');
7221 static void parse_and_run_file(FILE *f)
7223 struct in_str input;
7224 setup_file_in_str(&input, f);
7225 parse_and_run_stream(&input, ';');
7228 /* Called a few times only (or even once if "sh -c") */
7229 static void init_sigmasks(void)
7233 sigset_t old_blocked_set;
7235 if (!G.inherited_set_is_saved) {
7236 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7237 G.inherited_set = G.blocked_set;
7239 old_blocked_set = G.blocked_set;
7241 mask = (1 << SIGQUIT);
7242 if (G_interactive_fd) {
7243 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7244 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7245 mask |= SPECIAL_JOB_SIGS;
7247 G.non_DFL_mask = mask;
7252 sigaddset(&G.blocked_set, sig);
7256 sigdelset(&G.blocked_set, SIGCHLD);
7258 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7259 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7261 /* POSIX allows shell to re-enable SIGCHLD
7262 * even if it was SIG_IGN on entry */
7263 #if ENABLE_HUSH_FAST
7264 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7265 if (!G.inherited_set_is_saved)
7266 signal(SIGCHLD, SIGCHLD_handler);
7268 if (!G.inherited_set_is_saved)
7269 signal(SIGCHLD, SIG_DFL);
7272 G.inherited_set_is_saved = 1;
7277 static void maybe_set_to_sigexit(int sig)
7279 void (*handler)(int);
7280 /* non_DFL_mask'ed signals are, well, masked,
7281 * no need to set handler for them.
7283 if (!((G.non_DFL_mask >> sig) & 1)) {
7284 handler = signal(sig, sigexit);
7285 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7286 signal(sig, handler);
7289 /* Set handlers to restore tty pgrp and exit */
7290 static void set_fatal_handlers(void)
7292 /* We _must_ restore tty pgrp on fatal signals */
7294 maybe_set_to_sigexit(SIGILL );
7295 maybe_set_to_sigexit(SIGFPE );
7296 maybe_set_to_sigexit(SIGBUS );
7297 maybe_set_to_sigexit(SIGSEGV);
7298 maybe_set_to_sigexit(SIGTRAP);
7299 } /* else: hush is perfect. what SEGV? */
7300 maybe_set_to_sigexit(SIGABRT);
7301 /* bash 3.2 seems to handle these just like 'fatal' ones */
7302 maybe_set_to_sigexit(SIGPIPE);
7303 maybe_set_to_sigexit(SIGALRM);
7304 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7305 * if we aren't interactive... but in this case
7306 * we never want to restore pgrp on exit, and this fn is not called */
7307 /*maybe_set_to_sigexit(SIGHUP );*/
7308 /*maybe_set_to_sigexit(SIGTERM);*/
7309 /*maybe_set_to_sigexit(SIGINT );*/
7313 static int set_mode(const char cstate, const char mode)
7315 int state = (cstate == '-' ? 1 : 0);
7317 case 'n': G.n_mode = state; break;
7318 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7319 default: return EXIT_FAILURE;
7321 return EXIT_SUCCESS;
7324 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7325 int hush_main(int argc, char **argv)
7328 unsigned builtin_argc;
7330 struct variable *cur_var;
7333 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7334 G.last_exitcode = EXIT_SUCCESS;
7336 G.argv0_for_re_execing = argv[0];
7338 /* Deal with HUSH_VERSION */
7339 G.shell_ver.flg_export = 1;
7340 G.shell_ver.flg_read_only = 1;
7341 /* Code which handles ${var/P/R} needs writable values for all variables,
7342 * therefore we xstrdup: */
7343 G.shell_ver.varstr = xstrdup(hush_version_str),
7344 G.top_var = &G.shell_ver;
7345 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7346 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7347 /* reinstate HUSH_VERSION in environment */
7348 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7349 putenv(G.shell_ver.varstr);
7351 /* Initialize our shell local variables with the values
7352 * currently living in the environment */
7353 cur_var = G.top_var;
7356 char *value = strchr(*e, '=');
7357 if (value) { /* paranoia */
7358 cur_var->next = xzalloc(sizeof(*cur_var));
7359 cur_var = cur_var->next;
7360 cur_var->varstr = *e;
7361 cur_var->max_len = strlen(*e);
7362 cur_var->flg_export = 1;
7368 set_pwd_var(/*exp:*/ 1);
7369 /* bash also exports SHLVL and _,
7370 * and sets (but doesn't export) the following variables:
7372 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7373 * BASH_VERSION='3.2.0(1)-release'
7375 * MACHTYPE=i386-pc-linux-gnu
7377 * HOSTNAME=<xxxxxxxxxx>
7378 * PPID=<NNNNN> - we also do it elsewhere
7389 * PIPESTATUS=([0]="0")
7390 * HISTFILE=/<xxx>/.bash_history
7394 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7396 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7406 #if ENABLE_FEATURE_EDITING
7407 G.line_input_state = new_line_input_t(FOR_SHELL);
7409 G.global_argc = argc;
7410 G.global_argv = argv;
7411 /* Initialize some more globals to non-zero values */
7412 cmdedit_update_prompt();
7414 if (setjmp(die_jmp)) {
7415 /* xfunc has failed! die die die */
7416 /* no EXIT traps, this is an escape hatch! */
7418 hush_exit(xfunc_error_retval);
7421 /* Shell is non-interactive at first. We need to call
7422 * init_sigmasks() if we are going to execute "sh <script>",
7423 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7424 * If we later decide that we are interactive, we run init_sigmasks()
7425 * in order to intercept (more) signals.
7429 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7432 opt = getopt(argc, argv, "+c:xins"
7435 # if ENABLE_HUSH_FUNCTIONS
7445 * sh ... -c 'script'
7446 * sh ... -c 'script' ARG0 [ARG1...]
7447 * On NOMMU, if builtin_argc != 0,
7448 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7449 * "" needs to be replaced with NULL
7450 * and BARGV vector fed to builtin function.
7451 * Note: the form without ARG0 never happens:
7452 * sh ... -c 'builtin' BARGV... ""
7455 G.root_pid = getpid();
7456 G.root_ppid = getppid();
7458 G.global_argv = argv + optind;
7459 G.global_argc = argc - optind;
7461 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7462 const struct built_in_command *x;
7465 x = find_builtin(optarg);
7466 if (x) { /* paranoia */
7467 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7468 G.global_argv += builtin_argc;
7469 G.global_argv[-1] = NULL; /* replace "" */
7470 G.last_exitcode = x->b_function(argv + optind - 1);
7474 if (!G.global_argv[0]) {
7475 /* -c 'script' (no params): prevent empty $0 */
7476 G.global_argv--; /* points to argv[i] of 'script' */
7477 G.global_argv[0] = argv[0];
7479 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7481 parse_and_run_string(optarg);
7484 /* Well, we cannot just declare interactiveness,
7485 * we have to have some stuff (ctty, etc) */
7486 /* G_interactive_fd++; */
7489 /* "-s" means "read from stdin", but this is how we always
7490 * operate, so simply do nothing here. */
7493 case '<': /* "big heredoc" support */
7494 full_write1_str(optarg);
7497 unsigned long long empty_trap_mask;
7499 G.root_pid = bb_strtou(optarg, &optarg, 16);
7501 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7503 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7505 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7507 builtin_argc = bb_strtou(optarg, &optarg, 16);
7509 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7510 if (empty_trap_mask != 0) {
7513 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7514 for (sig = 1; sig < NSIG; sig++) {
7515 if (empty_trap_mask & (1LL << sig)) {
7516 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7517 sigaddset(&G.blocked_set, sig);
7520 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7522 # if ENABLE_HUSH_LOOPS
7524 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7530 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7532 # if ENABLE_HUSH_FUNCTIONS
7534 struct function *funcp = new_function(optarg);
7535 /* funcp->name is already set to optarg */
7536 /* funcp->body is set to NULL. It's a special case. */
7537 funcp->body_as_string = argv[optind];
7545 if (set_mode('-', opt) == 0) /* no error */
7549 fprintf(stderr, "Usage: sh [FILE]...\n"
7550 " or: sh -c command [args]...\n\n");
7556 } /* option parsing loop */
7559 G.root_pid = getpid();
7560 G.root_ppid = getppid();
7563 /* If we are login shell... */
7564 if (argv[0] && argv[0][0] == '-') {
7566 debug_printf("sourcing /etc/profile\n");
7567 input = fopen_for_read("/etc/profile");
7568 if (input != NULL) {
7569 close_on_exec_on(fileno(input));
7571 parse_and_run_file(input);
7574 /* bash: after sourcing /etc/profile,
7575 * tries to source (in the given order):
7576 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7577 * stopping on first found. --noprofile turns this off.
7578 * bash also sources ~/.bash_logout on exit.
7579 * If called as sh, skips .bash_XXX files.
7586 * "bash <script>" (which is never interactive (unless -i?))
7587 * sources $BASH_ENV here (without scanning $PATH).
7588 * If called as sh, does the same but with $ENV.
7590 debug_printf("running script '%s'\n", argv[optind]);
7591 G.global_argv = argv + optind;
7592 G.global_argc = argc - optind;
7593 input = xfopen_for_read(argv[optind]);
7594 close_on_exec_on(fileno(input));
7596 parse_and_run_file(input);
7597 #if ENABLE_FEATURE_CLEAN_UP
7603 /* Up to here, shell was non-interactive. Now it may become one.
7604 * NB: don't forget to (re)run init_sigmasks() as needed.
7607 /* A shell is interactive if the '-i' flag was given,
7608 * or if all of the following conditions are met:
7610 * no arguments remaining or the -s flag given
7611 * standard input is a terminal
7612 * standard output is a terminal
7613 * Refer to Posix.2, the description of the 'sh' utility.
7616 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7617 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7618 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7619 if (G_saved_tty_pgrp < 0)
7620 G_saved_tty_pgrp = 0;
7622 /* try to dup stdin to high fd#, >= 255 */
7623 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7624 if (G_interactive_fd < 0) {
7625 /* try to dup to any fd */
7626 G_interactive_fd = dup(STDIN_FILENO);
7627 if (G_interactive_fd < 0) {
7629 G_interactive_fd = 0;
7630 G_saved_tty_pgrp = 0;
7633 // TODO: track & disallow any attempts of user
7634 // to (inadvertently) close/redirect G_interactive_fd
7636 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7637 if (G_interactive_fd) {
7638 close_on_exec_on(G_interactive_fd);
7640 if (G_saved_tty_pgrp) {
7641 /* If we were run as 'hush &', sleep until we are
7642 * in the foreground (tty pgrp == our pgrp).
7643 * If we get started under a job aware app (like bash),
7644 * make sure we are now in charge so we don't fight over
7645 * who gets the foreground */
7647 pid_t shell_pgrp = getpgrp();
7648 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7649 if (G_saved_tty_pgrp == shell_pgrp)
7651 /* send TTIN to ourself (should stop us) */
7652 kill(- shell_pgrp, SIGTTIN);
7656 /* Block some signals */
7659 if (G_saved_tty_pgrp) {
7660 /* Set other signals to restore saved_tty_pgrp */
7661 set_fatal_handlers();
7662 /* Put ourselves in our own process group
7663 * (bash, too, does this only if ctty is available) */
7664 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7665 /* Grab control of the terminal */
7666 tcsetpgrp(G_interactive_fd, getpid());
7668 /* -1 is special - makes xfuncs longjmp, not exit
7669 * (we reset die_sleep = 0 whereever we [v]fork) */
7670 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7674 #elif ENABLE_HUSH_INTERACTIVE
7675 /* No job control compiled in, only prompt/line editing */
7676 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7677 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7678 if (G_interactive_fd < 0) {
7679 /* try to dup to any fd */
7680 G_interactive_fd = dup(STDIN_FILENO);
7681 if (G_interactive_fd < 0)
7683 G_interactive_fd = 0;
7686 if (G_interactive_fd) {
7687 close_on_exec_on(G_interactive_fd);
7691 /* We have interactiveness code disabled */
7695 * if interactive but not a login shell, sources ~/.bashrc
7696 * (--norc turns this off, --rcfile <file> overrides)
7699 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7700 /* note: ash and hush share this string */
7701 printf("\n\n%s %s\n"
7702 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7705 "hush - the humble shell"
7709 parse_and_run_file(stdin);
7712 #if ENABLE_FEATURE_CLEAN_UP
7713 if (G.cwd != bb_msg_unknown)
7715 cur_var = G.top_var->next;
7717 struct variable *tmp = cur_var;
7718 if (!cur_var->max_len)
7719 free(cur_var->varstr);
7720 cur_var = cur_var->next;
7724 hush_exit(G.last_exitcode);
7729 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7730 int lash_main(int argc, char **argv)
7732 bb_error_msg("lash is deprecated, please use hush instead");
7733 return hush_main(argc, argv);
7738 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7739 int msh_main(int argc, char **argv)
7741 //bb_error_msg("msh is deprecated, please use hush instead");
7742 return hush_main(argc, argv);
7750 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7755 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7762 return applet_main_func(argc, argv - argc);
7765 static int FAST_FUNC builtin_test(char **argv)
7767 return run_applet_main(argv, test_main);
7770 static int FAST_FUNC builtin_echo(char **argv)
7772 return run_applet_main(argv, echo_main);
7776 static int FAST_FUNC builtin_printf(char **argv)
7778 return run_applet_main(argv, printf_main);
7782 static char **skip_dash_dash(char **argv)
7785 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7790 static int FAST_FUNC builtin_eval(char **argv)
7792 int rcode = EXIT_SUCCESS;
7794 argv = skip_dash_dash(argv);
7796 char *str = expand_strvec_to_string(argv);
7798 * eval "echo Hi; done" ("done" is syntax error):
7799 * "echo Hi" will not execute too.
7801 parse_and_run_string(str);
7803 rcode = G.last_exitcode;
7808 static int FAST_FUNC builtin_cd(char **argv)
7812 argv = skip_dash_dash(argv);
7814 if (newdir == NULL) {
7815 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7816 * bash says "bash: cd: HOME not set" and does nothing
7819 const char *home = get_local_var_value("HOME");
7820 newdir = home ? home : "/";
7822 if (chdir(newdir)) {
7823 /* Mimic bash message exactly */
7824 bb_perror_msg("cd: %s", newdir);
7825 return EXIT_FAILURE;
7827 /* Read current dir (get_cwd(1) is inside) and set PWD.
7828 * Note: do not enforce exporting. If PWD was unset or unexported,
7829 * set it again, but do not export. bash does the same.
7831 set_pwd_var(/*exp:*/ 0);
7832 return EXIT_SUCCESS;
7835 static int FAST_FUNC builtin_exec(char **argv)
7837 argv = skip_dash_dash(argv);
7838 if (argv[0] == NULL)
7839 return EXIT_SUCCESS; /* bash does this */
7841 /* Careful: we can end up here after [v]fork. Do not restore
7842 * tty pgrp then, only top-level shell process does that */
7843 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7844 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7846 /* TODO: if exec fails, bash does NOT exit! We do.
7847 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7848 * and tcsetpgrp, and this is inherently racy.
7850 execvp_or_die(argv);
7853 static int FAST_FUNC builtin_exit(char **argv)
7855 debug_printf_exec("%s()\n", __func__);
7857 /* interactive bash:
7858 * # trap "echo EEE" EXIT
7861 * There are stopped jobs.
7862 * (if there are _stopped_ jobs, running ones don't count)
7865 # EEE (then bash exits)
7867 * we can use G.exiting = -1 as indicator "last cmd was exit"
7870 /* note: EXIT trap is run by hush_exit */
7871 argv = skip_dash_dash(argv);
7872 if (argv[0] == NULL)
7873 hush_exit(G.last_exitcode);
7874 /* mimic bash: exit 123abc == exit 255 + error msg */
7875 xfunc_error_retval = 255;
7876 /* bash: exit -2 == exit 254, no error msg */
7877 hush_exit(xatoi(argv[0]) & 0xff);
7880 static void print_escaped(const char *s)
7885 const char *p = strchrnul(s, '\'');
7886 /* print 'xxxx', possibly just '' */
7887 printf("'%.*s'", (int)(p - s), s);
7892 /* s points to '; print "'''...'''" */
7894 do putchar('\''); while (*++s == '\'');
7899 #if !ENABLE_HUSH_LOCAL
7900 #define helper_export_local(argv, exp, lvl) \
7901 helper_export_local(argv, exp)
7903 static void helper_export_local(char **argv, int exp, int lvl)
7908 /* So far we do not check that name is valid (TODO?) */
7910 if (strchr(name, '=') == NULL) {
7911 struct variable *var;
7913 var = get_local_var(name);
7914 if (exp == -1) { /* unexporting? */
7915 /* export -n NAME (without =VALUE) */
7917 var->flg_export = 0;
7918 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7920 } /* else: export -n NOT_EXISTING_VAR: no-op */
7923 if (exp == 1) { /* exporting? */
7924 /* export NAME (without =VALUE) */
7926 var->flg_export = 1;
7927 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7928 putenv(var->varstr);
7932 /* Exporting non-existing variable.
7933 * bash does not put it in environment,
7934 * but remembers that it is exported,
7935 * and does put it in env when it is set later.
7936 * We just set it to "" and export. */
7937 /* Or, it's "local NAME" (without =VALUE).
7938 * bash sets the value to "". */
7939 name = xasprintf("%s=", name);
7941 /* (Un)exporting/making local NAME=VALUE */
7942 name = xstrdup(name);
7944 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7948 static int FAST_FUNC builtin_export(char **argv)
7950 unsigned opt_unexport;
7952 #if ENABLE_HUSH_EXPORT_N
7953 /* "!": do not abort on errors */
7954 opt_unexport = getopt32(argv, "!n");
7955 if (opt_unexport == (uint32_t)-1)
7956 return EXIT_FAILURE;
7963 if (argv[0] == NULL) {
7970 /* ash emits: export VAR='VAL'
7971 * bash: declare -x VAR="VAL"
7972 * we follow ash example */
7973 const char *s = *e++;
7974 const char *p = strchr(s, '=');
7976 if (!p) /* wtf? take next variable */
7979 printf("export %.*s", (int)(p - s) + 1, s);
7980 print_escaped(p + 1);
7984 /*fflush_all(); - done after each builtin anyway */
7986 return EXIT_SUCCESS;
7989 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7991 return EXIT_SUCCESS;
7994 #if ENABLE_HUSH_LOCAL
7995 static int FAST_FUNC builtin_local(char **argv)
7997 if (G.func_nest_level == 0) {
7998 bb_error_msg("%s: not in a function", argv[0]);
7999 return EXIT_FAILURE; /* bash compat */
8001 helper_export_local(argv, 0, G.func_nest_level);
8002 return EXIT_SUCCESS;
8006 static int FAST_FUNC builtin_trap(char **argv)
8012 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8017 /* No args: print all trapped */
8018 for (i = 0; i < NSIG; ++i) {
8021 print_escaped(G.traps[i]);
8022 /* note: bash adds "SIG", but only if invoked
8023 * as "bash". If called as "sh", or if set -o posix,
8024 * then it prints short signal names.
8025 * We are printing short names: */
8026 printf(" %s\n", get_signame(i));
8029 /*fflush_all(); - done after each builtin anyway */
8030 return EXIT_SUCCESS;
8034 /* If first arg is a number: reset all specified signals */
8035 sig = bb_strtou(*argv, NULL, 10);
8041 sig = get_signum(*argv++);
8042 if (sig < 0 || sig >= NSIG) {
8044 /* Mimic bash message exactly */
8045 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8050 G.traps[sig] = xstrdup(new_cmd);
8052 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8053 get_signame(sig), sig, G.traps[sig]);
8055 /* There is no signal for 0 (EXIT) */
8060 sigaddset(&G.blocked_set, sig);
8062 /* There was a trap handler, we are removing it
8063 * (if sig has non-DFL handling,
8064 * we don't need to do anything) */
8065 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8067 sigdelset(&G.blocked_set, sig);
8070 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8074 if (!argv[1]) { /* no second arg */
8075 bb_error_msg("trap: invalid arguments");
8076 return EXIT_FAILURE;
8079 /* First arg is "-": reset all specified to default */
8080 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8081 /* Everything else: set arg as signal handler
8082 * (includes "" case, which ignores signal) */
8083 if (argv[0][0] == '-') {
8084 if (argv[0][1] == '\0') { /* "-" */
8085 /* new_cmd remains NULL: "reset these sigs" */
8088 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8091 /* else: "-something", no special meaning */
8096 goto process_sig_list;
8099 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8100 static int FAST_FUNC builtin_type(char **argv)
8102 int ret = EXIT_SUCCESS;
8108 if (0) {} /* make conditional compile easier below */
8109 /*else if (find_alias(*argv))
8110 type = "an alias";*/
8111 #if ENABLE_HUSH_FUNCTIONS
8112 else if (find_function(*argv))
8113 type = "a function";
8115 else if (find_builtin(*argv))
8116 type = "a shell builtin";
8117 else if ((path = find_in_path(*argv)) != NULL)
8120 bb_error_msg("type: %s: not found", *argv);
8125 printf("%s is %s\n", *argv, type);
8133 /* built-in 'fg' and 'bg' handler */
8134 static int FAST_FUNC builtin_fg_bg(char **argv)
8139 if (!G_interactive_fd)
8140 return EXIT_FAILURE;
8142 /* If they gave us no args, assume they want the last backgrounded task */
8144 for (pi = G.job_list; pi; pi = pi->next) {
8145 if (pi->jobid == G.last_jobid) {
8149 bb_error_msg("%s: no current job", argv[0]);
8150 return EXIT_FAILURE;
8152 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8153 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8154 return EXIT_FAILURE;
8156 for (pi = G.job_list; pi; pi = pi->next) {
8157 if (pi->jobid == jobnum) {
8161 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8162 return EXIT_FAILURE;
8164 /* TODO: bash prints a string representation
8165 * of job being foregrounded (like "sleep 1 | cat") */
8166 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8167 /* Put the job into the foreground. */
8168 tcsetpgrp(G_interactive_fd, pi->pgrp);
8171 /* Restart the processes in the job */
8172 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8173 for (i = 0; i < pi->num_cmds; i++) {
8174 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8175 pi->cmds[i].is_stopped = 0;
8177 pi->stopped_cmds = 0;
8179 i = kill(- pi->pgrp, SIGCONT);
8181 if (errno == ESRCH) {
8182 delete_finished_bg_job(pi);
8183 return EXIT_SUCCESS;
8185 bb_perror_msg("kill (SIGCONT)");
8188 if (argv[0][0] == 'f') {
8190 return checkjobs_and_fg_shell(pi);
8192 return EXIT_SUCCESS;
8196 #if ENABLE_HUSH_HELP
8197 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8199 const struct built_in_command *x;
8202 "Built-in commands:\n"
8203 "------------------\n");
8204 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8206 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8209 return EXIT_SUCCESS;
8214 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8217 const char *status_string;
8219 for (job = G.job_list; job; job = job->next) {
8220 if (job->alive_cmds == job->stopped_cmds)
8221 status_string = "Stopped";
8223 status_string = "Running";
8225 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8227 return EXIT_SUCCESS;
8232 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8237 # ifdef M_TRIM_THRESHOLD
8238 /* Optional. Reduces probability of false positives */
8241 /* Crude attempt to find where "free memory" starts,
8242 * sans fragmentation. */
8244 l = (unsigned long)p;
8247 if (l < (unsigned long)p) l = (unsigned long)p;
8250 if (!G.memleak_value)
8251 G.memleak_value = l;
8253 l -= G.memleak_value;
8260 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8265 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8268 return EXIT_SUCCESS;
8271 static int FAST_FUNC builtin_read(char **argv)
8280 /* "!": do not abort on errors.
8281 * Option string must start with "sr" to match BUILTIN_READ_xxx
8283 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8284 if (read_flags == (uint32_t)-1)
8285 return EXIT_FAILURE;
8288 r = shell_builtin_read(set_local_var_from_halves,
8290 get_local_var_value("IFS"), /* can be NULL */
8298 if ((uintptr_t)r > 1) {
8299 bb_error_msg("%s", r);
8300 r = (char*)(uintptr_t)1;
8303 return (uintptr_t)r;
8306 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8307 * built-in 'set' handler
8309 * set [-abCefhmnuvx] [-o option] [argument...]
8310 * set [+abCefhmnuvx] [+o option] [argument...]
8311 * set -- [argument...]
8314 * Implementations shall support the options in both their hyphen and
8315 * plus-sign forms. These options can also be specified as options to sh.
8317 * Write out all variables and their values: set
8318 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8319 * Turn on the -x and -v options: set -xv
8320 * Unset all positional parameters: set --
8321 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8322 * Set the positional parameters to the expansion of x, even if x expands
8323 * with a leading '-' or '+': set -- $x
8325 * So far, we only support "set -- [argument...]" and some of the short names.
8327 static int FAST_FUNC builtin_set(char **argv)
8330 char **pp, **g_argv;
8331 char *arg = *++argv;
8335 for (e = G.top_var; e; e = e->next)
8337 return EXIT_SUCCESS;
8341 if (!strcmp(arg, "--")) {
8345 if (arg[0] != '+' && arg[0] != '-')
8347 for (n = 1; arg[n]; ++n)
8348 if (set_mode(arg[0], arg[n]))
8350 } while ((arg = *++argv) != NULL);
8351 /* Now argv[0] is 1st argument */
8354 return EXIT_SUCCESS;
8357 /* NB: G.global_argv[0] ($0) is never freed/changed */
8358 g_argv = G.global_argv;
8359 if (G.global_args_malloced) {
8365 G.global_args_malloced = 1;
8366 pp = xzalloc(sizeof(pp[0]) * 2);
8367 pp[0] = g_argv[0]; /* retain $0 */
8370 /* This realloc's G.global_argv */
8371 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8378 return EXIT_SUCCESS;
8380 /* Nothing known, so abort */
8382 bb_error_msg("set: %s: invalid option", arg);
8383 return EXIT_FAILURE;
8386 static int FAST_FUNC builtin_shift(char **argv)
8389 argv = skip_dash_dash(argv);
8393 if (n >= 0 && n < G.global_argc) {
8394 if (G.global_args_malloced) {
8397 free(G.global_argv[m++]);
8400 memmove(&G.global_argv[1], &G.global_argv[n+1],
8401 G.global_argc * sizeof(G.global_argv[0]));
8402 return EXIT_SUCCESS;
8404 return EXIT_FAILURE;
8407 static int FAST_FUNC builtin_source(char **argv)
8409 char *arg_path, *filename;
8412 #if ENABLE_HUSH_FUNCTIONS
8416 argv = skip_dash_dash(argv);
8419 /* bash says: "bash: .: filename argument required" */
8420 return 2; /* bash compat */
8423 if (!strchr(filename, '/')) {
8424 arg_path = find_in_path(filename);
8426 filename = arg_path;
8428 input = fopen_or_warn(filename, "r");
8431 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8432 return EXIT_FAILURE;
8434 close_on_exec_on(fileno(input));
8436 #if ENABLE_HUSH_FUNCTIONS
8437 sv_flg = G.flag_return_in_progress;
8438 /* "we are inside sourced file, ok to use return" */
8439 G.flag_return_in_progress = -1;
8441 save_and_replace_G_args(&sv, argv);
8443 parse_and_run_file(input);
8446 restore_G_args(&sv, argv);
8447 #if ENABLE_HUSH_FUNCTIONS
8448 G.flag_return_in_progress = sv_flg;
8451 return G.last_exitcode;
8454 static int FAST_FUNC builtin_umask(char **argv)
8460 argv = skip_dash_dash(argv);
8462 mode_t old_mask = mask;
8465 rc = bb_parse_mode(argv[0], &mask);
8470 * bash: umask: 'q': invalid symbolic mode operator
8471 * bash: umask: 999: octal number out of range
8473 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8478 printf("%04o\n", (unsigned) mask);
8479 /* fall through and restore mask which we set to 0 */
8483 return !rc; /* rc != 0 - success */
8486 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8487 static int FAST_FUNC builtin_unset(char **argv)
8492 /* "!": do not abort on errors */
8493 /* "+": stop at 1st non-option */
8494 opts = getopt32(argv, "!+vf");
8495 if (opts == (unsigned)-1)
8496 return EXIT_FAILURE;
8498 bb_error_msg("unset: -v and -f are exclusive");
8499 return EXIT_FAILURE;
8505 if (!(opts & 2)) { /* not -f */
8506 if (unset_local_var(*argv)) {
8507 /* unset <nonexistent_var> doesn't fail.
8508 * Error is when one tries to unset RO var.
8509 * Message was printed by unset_local_var. */
8513 #if ENABLE_HUSH_FUNCTIONS
8523 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8524 static int FAST_FUNC builtin_wait(char **argv)
8526 int ret = EXIT_SUCCESS;
8529 argv = skip_dash_dash(argv);
8530 if (argv[0] == NULL) {
8531 /* Don't care about wait results */
8532 /* Note 1: must wait until there are no more children */
8533 /* Note 2: must be interruptible */
8535 * $ sleep 3 & sleep 6 & wait
8540 * $ sleep 3 & sleep 6 & wait
8544 * ^C <-- after ~4 sec from keyboard
8547 sigaddset(&G.blocked_set, SIGCHLD);
8548 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8551 if (errno == ECHILD)
8553 /* Wait for SIGCHLD or any other signal of interest */
8554 /* sigtimedwait with infinite timeout: */
8555 sig = sigwaitinfo(&G.blocked_set, NULL);
8557 sig = check_and_run_traps(sig);
8558 if (sig && sig != SIGCHLD) { /* see note 2 */
8564 sigdelset(&G.blocked_set, SIGCHLD);
8565 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8569 /* This is probably buggy wrt interruptible-ness */
8571 pid_t pid = bb_strtou(*argv, NULL, 10);
8573 /* mimic bash message */
8574 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8575 return EXIT_FAILURE;
8577 if (waitpid(pid, &status, 0) == pid) {
8578 if (WIFSIGNALED(status))
8579 ret = 128 + WTERMSIG(status);
8580 else if (WIFEXITED(status))
8581 ret = WEXITSTATUS(status);
8585 bb_perror_msg("wait %s", *argv);
8594 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8595 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8598 def = bb_strtou(argv[1], NULL, 10);
8599 if (errno || def < def_min || argv[2]) {
8600 bb_error_msg("%s: bad arguments", argv[0]);
8608 #if ENABLE_HUSH_LOOPS
8609 static int FAST_FUNC builtin_break(char **argv)
8612 if (G.depth_of_loop == 0) {
8613 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8614 return EXIT_SUCCESS; /* bash compat */
8616 G.flag_break_continue++; /* BC_BREAK = 1 */
8618 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8619 if (depth == UINT_MAX)
8620 G.flag_break_continue = BC_BREAK;
8621 if (G.depth_of_loop < depth)
8622 G.depth_break_continue = G.depth_of_loop;
8624 return EXIT_SUCCESS;
8627 static int FAST_FUNC builtin_continue(char **argv)
8629 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8630 return builtin_break(argv);
8634 #if ENABLE_HUSH_FUNCTIONS
8635 static int FAST_FUNC builtin_return(char **argv)
8639 if (G.flag_return_in_progress != -1) {
8640 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8641 return EXIT_FAILURE; /* bash compat */
8644 G.flag_return_in_progress = 1;
8647 * out of range: wraps around at 256, does not error out
8648 * non-numeric param:
8649 * f() { false; return qwe; }; f; echo $?
8650 * bash: return: qwe: numeric argument required <== we do this
8651 * 255 <== we also do this
8653 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);