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 smallint has_quoted_part;
404 smallint has_empty_slot;
405 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
408 MAYBE_ASSIGNMENT = 0,
409 DEFINITELY_ASSIGNMENT = 1,
411 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
413 /* Used for initialization: o_string foo = NULL_O_STRING; */
414 #define NULL_O_STRING { NULL }
416 /* I can almost use ordinary FILE*. Is open_memstream() universally
417 * available? Where is it documented? */
418 typedef struct in_str {
420 /* eof_flag=1: last char in ->p is really an EOF */
421 char eof_flag; /* meaningless if ->p == NULL */
423 #if ENABLE_HUSH_INTERACTIVE
425 smallint promptmode; /* 0: PS1, 1: PS2 */
428 int (*get) (struct in_str *) FAST_FUNC;
429 int (*peek) (struct in_str *) FAST_FUNC;
431 #define i_getch(input) ((input)->get(input))
432 #define i_peek(input) ((input)->peek(input))
434 /* The descrip member of this structure is only used to make
435 * debugging output pretty */
436 static const struct {
438 signed char default_fd;
441 { O_RDONLY, 0, "<" },
442 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
443 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
444 { O_CREAT|O_RDWR, 1, "<>" },
445 { O_RDONLY, 0, "<<" },
446 /* Should not be needed. Bogus default_fd helps in debugging */
447 /* { O_RDONLY, 77, "<<" }, */
450 struct redir_struct {
451 struct redir_struct *next;
452 char *rd_filename; /* filename */
453 int rd_fd; /* fd to redirect */
454 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
456 smallint rd_type; /* (enum redir_type) */
457 /* note: for heredocs, rd_filename contains heredoc delimiter,
458 * and subsequently heredoc itself; and rd_dup is a bitmask:
459 * bit 0: do we need to trim leading tabs?
460 * bit 1: is heredoc quoted (<<'delim' syntax) ?
463 typedef enum redir_type {
465 REDIRECT_OVERWRITE = 1,
468 REDIRECT_HEREDOC = 4,
469 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
472 REDIRFD_SYNTAX_ERR = -2,
473 REDIRFD_TO_FILE = -1,
474 /* otherwise, rd_fd is redirected to rd_dup */
476 HEREDOC_SKIPTABS = 1,
482 pid_t pid; /* 0 if exited */
483 int assignment_cnt; /* how many argv[i] are assignments? */
484 smallint is_stopped; /* is the command currently running? */
485 smallint cmd_type; /* CMD_xxx */
487 #define CMD_SUBSHELL 1
489 /* used for "[[ EXPR ]]" */
490 #if ENABLE_HUSH_BASH_COMPAT
491 # define CMD_SINGLEWORD_NOGLOB 2
494 /* used for "export noglob=* glob* a=`echo a b`" */
495 //#define CMD_SINGLEWORD_NOGLOB_COND 3
496 // It is hard to implement correctly, it adds significant amounts of tricky code,
497 // and all this is only useful for really obscure export statements
498 // almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
499 // guards the code which implements it, but I have doubts it works
500 // in all cases (especially with mixed globbed/non-globbed arguments)
502 #if ENABLE_HUSH_FUNCTIONS
503 # define CMD_FUNCDEF 3
506 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
509 char *group_as_string;
511 #if ENABLE_HUSH_FUNCTIONS
512 struct function *child_func;
513 /* This field is used to prevent a bug here:
514 * while...do f1() {a;}; f1; f1() {b;}; f1; done
515 * When we execute "f1() {a;}" cmd, we create new function and clear
516 * cmd->group, cmd->group_as_string, cmd->argv[0].
517 * When we execute "f1() {b;}", we notice that f1 exists,
518 * and that its "parent cmd" struct is still "alive",
519 * we put those fields back into cmd->xxx
520 * (struct function has ->parent_cmd ptr to facilitate that).
521 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
522 * Without this trick, loop would execute a;b;b;b;...
523 * instead of correct sequence a;b;a;b;...
524 * When command is freed, it severs the link
525 * (sets ->child_func->parent_cmd to NULL).
528 char **argv; /* command name and arguments */
529 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
530 * and on execution these are substituted with their values.
531 * Substitution can make _several_ words out of one argv[n]!
532 * Example: argv[0]=='.^C*^C.' here: echo .$*.
533 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
535 struct redir_struct *redirects; /* I/O redirections */
537 /* Is there anything in this command at all? */
538 #define IS_NULL_CMD(cmd) \
539 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
544 int num_cmds; /* total number of commands in pipe */
545 int alive_cmds; /* number of commands running (not exited) */
546 int stopped_cmds; /* number of commands alive, but stopped */
548 int jobid; /* job number */
549 pid_t pgrp; /* process group ID for the job */
550 char *cmdtext; /* name of job */
552 struct command *cmds; /* array of commands in pipe */
553 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
554 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
555 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
557 typedef enum pipe_style {
563 /* Is there anything in this pipe at all? */
564 #define IS_NULL_PIPE(pi) \
565 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
567 /* This holds pointers to the various results of parsing */
568 struct parse_context {
569 /* linked list of pipes */
570 struct pipe *list_head;
571 /* last pipe (being constructed right now) */
573 /* last command in pipe (being constructed right now) */
574 struct command *command;
575 /* last redirect in command->redirects list */
576 struct redir_struct *pending_redirect;
582 smallint ctx_inverted; /* "! cmd | cmd" */
584 smallint ctx_dsemicolon; /* ";;" seen */
586 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
588 /* group we are enclosed in:
589 * example: "if pipe1; pipe2; then pipe3; fi"
590 * when we see "if" or "then", we malloc and copy current context,
591 * and make ->stack point to it. then we parse pipeN.
592 * when closing "then" / fi" / whatever is found,
593 * we move list_head into ->stack->command->group,
594 * copy ->stack into current context, and delete ->stack.
595 * (parsing of { list } and ( list ) doesn't use this method)
597 struct parse_context *stack;
601 /* On program start, environ points to initial environment.
602 * putenv adds new pointers into it, unsetenv removes them.
603 * Neither of these (de)allocates the strings.
604 * setenv allocates new strings in malloc space and does putenv,
605 * and thus setenv is unusable (leaky) for shell's purposes */
606 #define setenv(...) setenv_is_leaky_dont_use()
608 struct variable *next;
609 char *varstr; /* points to "name=" portion */
610 #if ENABLE_HUSH_LOCAL
611 unsigned func_nest_level;
613 int max_len; /* if > 0, name is part of initial env; else name is malloced */
614 smallint flg_export; /* putenv should be done on this var */
615 smallint flg_read_only;
623 #if ENABLE_HUSH_FUNCTIONS
625 struct function *next;
627 struct command *parent_cmd;
630 char *body_as_string;
636 /* "Globals" within this file */
637 /* Sorted roughly by size (smaller offsets == smaller code) */
639 /* interactive_fd != 0 means we are an interactive shell.
640 * If we are, then saved_tty_pgrp can also be != 0, meaning
641 * that controlling tty is available. With saved_tty_pgrp == 0,
642 * job control still works, but terminal signals
643 * (^C, ^Z, ^Y, ^\) won't work at all, and background
644 * process groups can only be created with "cmd &".
645 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
646 * to give tty to the foreground process group,
647 * and will take it back when the group is stopped (^Z)
650 #if ENABLE_HUSH_INTERACTIVE
651 /* 'interactive_fd' is a fd# open to ctty, if we have one
652 * _AND_ if we decided to act interactively */
656 # define G_interactive_fd (G.interactive_fd)
658 # define G_interactive_fd 0
660 #if ENABLE_FEATURE_EDITING
661 line_input_t *line_input_state;
666 #if ENABLE_HUSH_RANDOM_SUPPORT
672 pid_t saved_tty_pgrp;
673 struct pipe *job_list;
674 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
676 # define G_saved_tty_pgrp 0
678 smallint flag_SIGINT;
679 #if ENABLE_HUSH_LOOPS
680 smallint flag_break_continue;
682 #if ENABLE_HUSH_FUNCTIONS
683 /* 0: outside of a function (or sourced file)
684 * -1: inside of a function, ok to use return builtin
685 * 1: return is invoked, skip all till end of func
687 smallint flag_return_in_progress;
690 #if ENABLE_HUSH_MODE_X
692 # define G_x_mode (G.x_mode)
696 smallint exiting; /* used to prevent EXIT trap recursion */
697 /* These four support $?, $#, and $1 */
698 smalluint last_exitcode;
699 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
700 smalluint global_args_malloced;
701 smalluint inherited_set_is_saved;
702 /* how many non-NULL argv's we have. NB: $# + 1 */
706 char *argv0_for_re_execing;
708 #if ENABLE_HUSH_LOOPS
709 unsigned depth_break_continue;
710 unsigned depth_of_loop;
714 struct variable *top_var; /* = &G.shell_ver (set in main()) */
715 struct variable shell_ver;
716 char **expanded_assignments;
717 #if ENABLE_HUSH_FUNCTIONS
718 struct function *top_func;
719 # if ENABLE_HUSH_LOCAL
720 struct variable **shadowed_vars_pp;
721 unsigned func_nest_level;
724 /* Signal and trap handling */
726 unsigned count_SIGCHLD;
727 unsigned handled_SIGCHLD;
728 smallint we_have_children;
730 /* which signals have non-DFL handler (even with no traps set)? */
731 unsigned non_DFL_mask;
732 char **traps; /* char *traps[NSIG] */
733 sigset_t blocked_set;
734 sigset_t inherited_set;
736 unsigned long memleak_value;
739 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
741 #define G (*ptr_to_globals)
742 /* Not #defining name to G.name - this quickly gets unwieldy
743 * (too many defines). Also, I actually prefer to see when a variable
744 * is global, thus "G." prefix is a useful hint */
745 #define INIT_G() do { \
746 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
750 /* Function prototypes for builtins */
751 static int builtin_cd(char **argv) FAST_FUNC;
752 static int builtin_echo(char **argv) FAST_FUNC;
753 static int builtin_eval(char **argv) FAST_FUNC;
754 static int builtin_exec(char **argv) FAST_FUNC;
755 static int builtin_exit(char **argv) FAST_FUNC;
756 static int builtin_export(char **argv) FAST_FUNC;
758 static int builtin_fg_bg(char **argv) FAST_FUNC;
759 static int builtin_jobs(char **argv) FAST_FUNC;
762 static int builtin_help(char **argv) FAST_FUNC;
764 #if ENABLE_HUSH_LOCAL
765 static int builtin_local(char **argv) FAST_FUNC;
768 static int builtin_memleak(char **argv) FAST_FUNC;
771 static int builtin_printf(char **argv) FAST_FUNC;
773 static int builtin_pwd(char **argv) FAST_FUNC;
774 static int builtin_read(char **argv) FAST_FUNC;
775 static int builtin_set(char **argv) FAST_FUNC;
776 static int builtin_shift(char **argv) FAST_FUNC;
777 static int builtin_source(char **argv) FAST_FUNC;
778 static int builtin_test(char **argv) FAST_FUNC;
779 static int builtin_trap(char **argv) FAST_FUNC;
780 static int builtin_type(char **argv) FAST_FUNC;
781 static int builtin_true(char **argv) FAST_FUNC;
782 static int builtin_umask(char **argv) FAST_FUNC;
783 static int builtin_unset(char **argv) FAST_FUNC;
784 static int builtin_wait(char **argv) FAST_FUNC;
785 #if ENABLE_HUSH_LOOPS
786 static int builtin_break(char **argv) FAST_FUNC;
787 static int builtin_continue(char **argv) FAST_FUNC;
789 #if ENABLE_HUSH_FUNCTIONS
790 static int builtin_return(char **argv) FAST_FUNC;
793 /* Table of built-in functions. They can be forked or not, depending on
794 * context: within pipes, they fork. As simple commands, they do not.
795 * When used in non-forking context, they can change global variables
796 * in the parent shell process. If forked, of course they cannot.
797 * For example, 'unset foo | whatever' will parse and run, but foo will
798 * still be set at the end. */
799 struct built_in_command {
801 int (*b_function)(char **argv) FAST_FUNC;
804 # define BLTIN(cmd, func, help) { cmd, func, help }
806 # define BLTIN(cmd, func, help) { cmd, func }
810 static const struct built_in_command bltins1[] = {
811 BLTIN("." , builtin_source , "Run commands in a file"),
812 BLTIN(":" , builtin_true , NULL),
814 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
816 #if ENABLE_HUSH_LOOPS
817 BLTIN("break" , builtin_break , "Exit from a loop"),
819 BLTIN("cd" , builtin_cd , "Change directory"),
820 #if ENABLE_HUSH_LOOPS
821 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
823 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
824 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
825 BLTIN("exit" , builtin_exit , "Exit"),
826 BLTIN("export" , builtin_export , "Set environment variables"),
828 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
831 BLTIN("help" , builtin_help , NULL),
834 BLTIN("jobs" , builtin_jobs , "List jobs"),
836 #if ENABLE_HUSH_LOCAL
837 BLTIN("local" , builtin_local , "Set local variables"),
840 BLTIN("memleak" , builtin_memleak , NULL),
842 BLTIN("read" , builtin_read , "Input into variable"),
843 #if ENABLE_HUSH_FUNCTIONS
844 BLTIN("return" , builtin_return , "Return from a function"),
846 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
847 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
848 #if ENABLE_HUSH_BASH_COMPAT
849 BLTIN("source" , builtin_source , "Run commands in a file"),
851 BLTIN("trap" , builtin_trap , "Trap signals"),
852 BLTIN("type" , builtin_type , "Show command type"),
853 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
854 BLTIN("umask" , builtin_umask , "Set file creation mask"),
855 BLTIN("unset" , builtin_unset , "Unset variables"),
856 BLTIN("wait" , builtin_wait , "Wait for process"),
858 /* For now, echo and test are unconditionally enabled.
859 * Maybe make it configurable? */
860 static const struct built_in_command bltins2[] = {
861 BLTIN("[" , builtin_test , NULL),
862 BLTIN("echo" , builtin_echo , NULL),
864 BLTIN("printf" , builtin_printf , NULL),
866 BLTIN("pwd" , builtin_pwd , NULL),
867 BLTIN("test" , builtin_test , NULL),
874 /* prevent disasters with G.debug_indent < 0 */
875 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
876 # define debug_enter() (G.debug_indent++)
877 # define debug_leave() (G.debug_indent--)
879 # define indent() ((void)0)
880 # define debug_enter() ((void)0)
881 # define debug_leave() ((void)0)
885 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
888 #ifndef debug_printf_parse
889 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 #ifndef debug_printf_exec
893 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
896 #ifndef debug_printf_env
897 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
900 #ifndef debug_printf_jobs
901 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
902 # define DEBUG_JOBS 1
904 # define DEBUG_JOBS 0
907 #ifndef debug_printf_expand
908 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
909 # define DEBUG_EXPAND 1
911 # define DEBUG_EXPAND 0
914 #ifndef debug_printf_varexp
915 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
918 #ifndef debug_printf_glob
919 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 # define DEBUG_GLOB 1
922 # define DEBUG_GLOB 0
925 #ifndef debug_printf_list
926 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
929 #ifndef debug_printf_subst
930 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
933 #ifndef debug_printf_clean
934 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
935 # define DEBUG_CLEAN 1
937 # define DEBUG_CLEAN 0
941 static void debug_print_strings(const char *prefix, char **vv)
944 fprintf(stderr, "%s:\n", prefix);
946 fprintf(stderr, " '%s'\n", *vv++);
949 # define debug_print_strings(prefix, vv) ((void)0)
953 /* Leak hunting. Use hush_leaktool.sh for post-processing.
956 static void *xxmalloc(int lineno, size_t size)
958 void *ptr = xmalloc((size + 0xff) & ~0xff);
959 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
962 static void *xxrealloc(int lineno, void *ptr, size_t size)
964 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
965 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
968 static char *xxstrdup(int lineno, const char *str)
970 char *ptr = xstrdup(str);
971 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
974 static void xxfree(void *ptr)
976 fdprintf(2, "free %p\n", ptr);
979 # define xmalloc(s) xxmalloc(__LINE__, s)
980 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
981 # define xstrdup(s) xxstrdup(__LINE__, s)
982 # define free(p) xxfree(p)
986 /* Syntax and runtime errors. They always abort scripts.
987 * In interactive use they usually discard unparsed and/or unexecuted commands
988 * and return to the prompt.
989 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
992 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
993 # define syntax_error(lineno, msg) syntax_error(msg)
994 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
995 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
996 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
997 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1000 static void die_if_script(unsigned lineno, const char *fmt, ...)
1005 bb_error_msg("hush.c:%u", lineno);
1008 bb_verror_msg(fmt, p, NULL);
1010 if (!G_interactive_fd)
1014 static void syntax_error(unsigned lineno, const char *msg)
1017 die_if_script(lineno, "syntax error: %s", msg);
1019 die_if_script(lineno, "syntax error", NULL);
1022 static void syntax_error_at(unsigned lineno, const char *msg)
1024 die_if_script(lineno, "syntax error at '%s'", msg);
1027 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1029 die_if_script(lineno, "syntax error: unterminated %s", s);
1032 /* It so happens that all such cases are totally fatal
1033 * even if shell is interactive: EOF while looking for closing
1034 * delimiter. There is nowhere to read stuff from after that,
1035 * it's EOF! The only choice is to terminate.
1037 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1038 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1040 char msg[2] = { ch, '\0' };
1041 syntax_error_unterm_str(lineno, msg);
1045 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1050 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1054 # undef die_if_script
1055 # undef syntax_error
1056 # undef syntax_error_at
1057 # undef syntax_error_unterm_ch
1058 # undef syntax_error_unterm_str
1059 # undef syntax_error_unexpected_ch
1061 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1062 # define syntax_error(msg) syntax_error(__LINE__, msg)
1063 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1064 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1065 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1066 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1070 #if ENABLE_HUSH_INTERACTIVE
1071 static void cmdedit_update_prompt(void);
1073 # define cmdedit_update_prompt() ((void)0)
1077 /* Utility functions
1079 /* Replace each \x with x in place, return ptr past NUL. */
1080 static char *unbackslash(char *src)
1082 char *dst = src = strchrnul(src, '\\');
1086 if ((*dst++ = *src++) == '\0')
1092 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1113 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1114 v[count1 + count2] = NULL;
1117 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1121 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1123 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1124 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1127 #define add_strings_to_strings(strings, add, need_to_dup) \
1128 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1131 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1132 static char **add_string_to_strings(char **strings, char *add)
1137 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1140 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1142 char **ptr = add_string_to_strings(strings, add);
1143 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1146 #define add_string_to_strings(strings, add) \
1147 xx_add_string_to_strings(__LINE__, strings, add)
1150 static void free_strings(char **strings)
1165 /* Helpers for setting new $n and restoring them back
1167 typedef struct save_arg_t {
1171 smallint sv_g_malloced;
1174 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1178 sv->sv_argv0 = argv[0];
1179 sv->sv_g_argv = G.global_argv;
1180 sv->sv_g_argc = G.global_argc;
1181 sv->sv_g_malloced = G.global_args_malloced;
1183 argv[0] = G.global_argv[0]; /* retain $0 */
1184 G.global_argv = argv;
1185 G.global_args_malloced = 0;
1193 static void restore_G_args(save_arg_t *sv, char **argv)
1197 if (G.global_args_malloced) {
1198 /* someone ran "set -- arg1 arg2 ...", undo */
1200 while (*++pp) /* note: does not free $0 */
1202 free(G.global_argv);
1204 argv[0] = sv->sv_argv0;
1205 G.global_argv = sv->sv_g_argv;
1206 G.global_argc = sv->sv_g_argc;
1207 G.global_args_malloced = sv->sv_g_malloced;
1211 /* Basic theory of signal handling in shell
1212 * ========================================
1213 * This does not describe what hush does, rather, it is current understanding
1214 * what it _should_ do. If it doesn't, it's a bug.
1215 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1217 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1218 * is finished or backgrounded. It is the same in interactive and
1219 * non-interactive shells, and is the same regardless of whether
1220 * a user trap handler is installed or a shell special one is in effect.
1221 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1222 * backgrounds (i.e. stops) or kills all members of currently running
1225 * Wait builtin in interruptible by signals for which user trap is set
1226 * or by SIGINT in interactive shell.
1228 * Trap handlers will execute even within trap handlers. (right?)
1230 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1231 * except for handlers set to '' (empty string).
1233 * If job control is off, backgrounded commands ("cmd &")
1234 * have SIGINT, SIGQUIT set to SIG_IGN.
1236 * Commands which are run in command substitution ("`cmd`")
1237 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1239 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1240 * by the shell from its parent.
1242 * Signals which differ from SIG_DFL action
1243 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1246 * SIGTERM (interactive): ignore
1247 * SIGHUP (interactive):
1248 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1249 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1250 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1251 * that all pipe members are stopped. Try this in bash:
1252 * while :; do :; done - ^Z does not background it
1253 * (while :; do :; done) - ^Z backgrounds it
1254 * SIGINT (interactive): wait for last pipe, ignore the rest
1255 * of the command line, show prompt. NB: ^C does not send SIGINT
1256 * to interactive shell while shell is waiting for a pipe,
1257 * since shell is bg'ed (is not in foreground process group).
1258 * Example 1: this waits 5 sec, but does not execute ls:
1259 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1260 * Example 2: this does not wait and does not execute ls:
1261 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1262 * Example 3: this does not wait 5 sec, but executes ls:
1263 * "sleep 5; ls -l" + press ^C
1265 * (What happens to signals which are IGN on shell start?)
1266 * (What happens with signal mask on shell start?)
1268 * Implementation in hush
1269 * ======================
1270 * We use in-kernel pending signal mask to determine which signals were sent.
1271 * We block all signals which we don't want to take action immediately,
1272 * i.e. we block all signals which need to have special handling as described
1273 * above, and all signals which have traps set.
1274 * After each pipe execution, we extract any pending signals via sigtimedwait()
1277 * unsigned non_DFL_mask: a mask of such "special" signals
1278 * sigset_t blocked_set: current blocked signal set
1281 * clear bit in blocked_set unless it is also in non_DFL_mask
1282 * "trap 'cmd' SIGxxx":
1283 * set bit in blocked_set (even if 'cmd' is '')
1284 * after [v]fork, if we plan to be a shell:
1285 * unblock signals with special interactive handling
1286 * (child shell is not interactive),
1287 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1288 * after [v]fork, if we plan to exec:
1289 * POSIX says fork clears pending signal mask in child - no need to clear it.
1290 * Restore blocked signal set to one inherited by shell just prior to exec.
1292 * Note: as a result, we do not use signal handlers much. The only uses
1293 * are to count SIGCHLDs
1294 * and to restore tty pgrp on signal-induced exit.
1297 * Standard says "When a subshell is entered, traps that are not being ignored
1298 * are set to the default actions". bash interprets it so that traps which
1299 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1302 SPECIAL_INTERACTIVE_SIGS = 0
1307 SPECIAL_JOB_SIGS = 0
1315 #if ENABLE_HUSH_FAST
1316 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1319 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1325 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1326 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1327 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1328 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1330 /* Restores tty foreground process group, and exits.
1331 * May be called as signal handler for fatal signal
1332 * (will resend signal to itself, producing correct exit state)
1333 * or called directly with -EXITCODE.
1334 * We also call it if xfunc is exiting. */
1335 static void sigexit(int sig) NORETURN;
1336 static void sigexit(int sig)
1338 /* Disable all signals: job control, SIGPIPE, etc. */
1339 sigprocmask_allsigs(SIG_BLOCK);
1341 /* Careful: we can end up here after [v]fork. Do not restore
1342 * tty pgrp then, only top-level shell process does that */
1343 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1344 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1346 /* Not a signal, just exit */
1350 kill_myself_with_sig(sig); /* does not return */
1354 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1355 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1359 /* Restores tty foreground process group, and exits. */
1360 static void hush_exit(int exitcode) NORETURN;
1361 static void hush_exit(int exitcode)
1363 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1364 /* Prevent recursion:
1365 * trap "echo Hi; exit" EXIT; exit
1367 char *argv[] = { NULL, G.traps[0], NULL };
1376 sigexit(- (exitcode & 0xff));
1382 static int check_and_run_traps(int sig)
1384 static const struct timespec zero_timespec;
1385 smalluint save_rcode;
1391 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1396 if (G.traps && G.traps[sig]) {
1397 if (G.traps[sig][0]) {
1398 /* We have user-defined handler */
1399 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1400 save_rcode = G.last_exitcode;
1403 G.last_exitcode = save_rcode;
1404 } /* else: "" trap, ignoring signal */
1407 /* not a trap: special action */
1409 #if ENABLE_HUSH_FAST
1412 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1416 /* Builtin was ^C'ed, make it look prettier: */
1423 /* bash is observed to signal whole process groups,
1424 * not individual processes */
1425 for (job = G.job_list; job; job = job->next) {
1428 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1429 if (kill(- job->pgrp, SIGHUP) == 0)
1430 kill(- job->pgrp, SIGCONT);
1435 default: /* ignored: */
1436 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1444 static const char *get_cwd(int force)
1446 if (force || G.cwd == NULL) {
1447 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1448 * we must not try to free(bb_msg_unknown) */
1449 if (G.cwd == bb_msg_unknown)
1451 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1453 G.cwd = bb_msg_unknown;
1460 * Shell and environment variable support
1462 static struct variable **get_ptr_to_local_var(const char *name)
1464 struct variable **pp;
1465 struct variable *cur;
1470 while ((cur = *pp) != NULL) {
1471 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1478 static struct variable *get_local_var(const char *name)
1480 struct variable **pp = get_ptr_to_local_var(name);
1486 static const char* FAST_FUNC get_local_var_value(const char *name)
1488 struct variable **vpp;
1490 if (G.expanded_assignments) {
1491 char **cpp = G.expanded_assignments;
1492 int len = strlen(name);
1495 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1496 return cp + len + 1;
1501 vpp = get_ptr_to_local_var(name);
1503 return strchr((*vpp)->varstr, '=') + 1;
1505 if (strcmp(name, "PPID") == 0)
1506 return utoa(G.root_ppid);
1507 // bash compat: UID? EUID?
1508 #if ENABLE_HUSH_RANDOM_SUPPORT
1509 if (strcmp(name, "RANDOM") == 0) {
1510 return utoa(next_random(&G.random_gen));
1516 /* str holds "NAME=VAL" and is expected to be malloced.
1517 * We take ownership of it.
1519 * 0: do not change export flag
1520 * (if creating new variable, flag will be 0)
1521 * 1: set export flag and putenv the variable
1522 * -1: clear export flag and unsetenv the variable
1523 * flg_read_only is set only when we handle -R var=val
1525 #if !BB_MMU && ENABLE_HUSH_LOCAL
1526 /* all params are used */
1527 #elif BB_MMU && ENABLE_HUSH_LOCAL
1528 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1529 set_local_var(str, flg_export, local_lvl)
1530 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1531 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export)
1533 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1534 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1535 set_local_var(str, flg_export, flg_read_only)
1537 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1539 struct variable **var_pp;
1540 struct variable *cur;
1544 eq_sign = strchr(str, '=');
1545 if (!eq_sign) { /* not expected to ever happen? */
1550 name_len = eq_sign - str + 1; /* including '=' */
1551 var_pp = &G.top_var;
1552 while ((cur = *var_pp) != NULL) {
1553 if (strncmp(cur->varstr, str, name_len) != 0) {
1554 var_pp = &cur->next;
1557 /* We found an existing var with this name */
1558 if (cur->flg_read_only) {
1562 bb_error_msg("%s: readonly variable", str);
1566 if (flg_export == -1) { // "&& cur->flg_export" ?
1567 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1572 #if ENABLE_HUSH_LOCAL
1573 if (cur->func_nest_level < local_lvl) {
1574 /* New variable is declared as local,
1575 * and existing one is global, or local
1576 * from enclosing function.
1577 * Remove and save old one: */
1578 *var_pp = cur->next;
1579 cur->next = *G.shadowed_vars_pp;
1580 *G.shadowed_vars_pp = cur;
1581 /* bash 3.2.33(1) and exported vars:
1583 * # f() { local z=a; env | grep ^z; }
1589 if (cur->flg_export)
1594 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1599 if (cur->max_len != 0) {
1600 if (cur->max_len >= strlen(str)) {
1601 /* This one is from startup env, reuse space */
1602 strcpy(cur->varstr, str);
1606 /* max_len == 0 signifies "malloced" var, which we can
1607 * (and has to) free */
1611 goto set_str_and_exp;
1614 /* Not found - create new variable struct */
1615 cur = xzalloc(sizeof(*cur));
1616 #if ENABLE_HUSH_LOCAL
1617 cur->func_nest_level = local_lvl;
1619 cur->next = *var_pp;
1625 cur->flg_read_only = flg_read_only;
1628 if (flg_export == 1)
1629 cur->flg_export = 1;
1630 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1631 cmdedit_update_prompt();
1632 if (cur->flg_export) {
1633 if (flg_export == -1) {
1634 cur->flg_export = 0;
1635 /* unsetenv was already done */
1637 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1638 return putenv(cur->varstr);
1644 /* Used at startup and after each cd */
1645 static void set_pwd_var(int exp)
1647 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1648 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1651 static int unset_local_var_len(const char *name, int name_len)
1653 struct variable *cur;
1654 struct variable **var_pp;
1657 return EXIT_SUCCESS;
1658 var_pp = &G.top_var;
1659 while ((cur = *var_pp) != NULL) {
1660 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1661 if (cur->flg_read_only) {
1662 bb_error_msg("%s: readonly variable", name);
1663 return EXIT_FAILURE;
1665 *var_pp = cur->next;
1666 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1667 bb_unsetenv(cur->varstr);
1668 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1669 cmdedit_update_prompt();
1673 return EXIT_SUCCESS;
1675 var_pp = &cur->next;
1677 return EXIT_SUCCESS;
1680 static int unset_local_var(const char *name)
1682 return unset_local_var_len(name, strlen(name));
1685 static void unset_vars(char **strings)
1693 const char *eq = strchrnul(*v, '=');
1694 unset_local_var_len(*v, (int)(eq - *v));
1700 #if ENABLE_SH_MATH_SUPPORT
1701 # define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1702 # define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1703 static char* FAST_FUNC endofname(const char *name)
1711 if (!is_in_name(*p))
1718 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1720 char *var = xasprintf("%s=%s", name, val);
1721 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1726 * Helpers for "var1=val1 var2=val2 cmd" feature
1728 static void add_vars(struct variable *var)
1730 struct variable *next;
1734 var->next = G.top_var;
1736 if (var->flg_export) {
1737 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1738 putenv(var->varstr);
1740 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1746 static struct variable *set_vars_and_save_old(char **strings)
1749 struct variable *old = NULL;
1755 struct variable *var_p;
1756 struct variable **var_pp;
1759 eq = strchr(*s, '=');
1762 var_pp = get_ptr_to_local_var(*s);
1765 /* Remove variable from global linked list */
1767 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1768 *var_pp = var_p->next;
1769 /* Add it to returned list */
1773 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1784 static int FAST_FUNC static_get(struct in_str *i)
1794 static int FAST_FUNC static_peek(struct in_str *i)
1799 #if ENABLE_HUSH_INTERACTIVE
1801 static void cmdedit_update_prompt(void)
1803 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1804 G.PS1 = get_local_var_value("PS1");
1807 G.PS2 = get_local_var_value("PS2");
1815 static const char* setup_prompt_string(int promptmode)
1817 const char *prompt_str;
1818 debug_printf("setup_prompt_string %d ", promptmode);
1819 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1820 /* Set up the prompt */
1821 if (promptmode == 0) { /* PS1 */
1823 /* bash uses $PWD value, even if it is set by user.
1824 * It uses current dir only if PWD is unset.
1825 * We always use current dir. */
1826 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1831 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1832 debug_printf("result '%s'\n", prompt_str);
1836 static void get_user_input(struct in_str *i)
1839 const char *prompt_str;
1841 prompt_str = setup_prompt_string(i->promptmode);
1842 # if ENABLE_FEATURE_EDITING
1843 /* Enable command line editing only while a command line
1844 * is actually being read */
1847 /* buglet: SIGINT will not make new prompt to appear _at once_,
1848 * only after <Enter>. (^C will work) */
1849 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1850 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1851 check_and_run_traps(0);
1852 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1853 i->eof_flag = (r < 0);
1854 if (i->eof_flag) { /* EOF/error detected */
1855 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1856 G.user_input_buf[1] = '\0';
1861 fputs(prompt_str, stdout);
1863 G.user_input_buf[0] = r = fgetc(i->file);
1864 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1865 //do we need check_and_run_traps(0)? (maybe only if stdin)
1866 } while (G.flag_SIGINT);
1867 i->eof_flag = (r == EOF);
1869 i->p = G.user_input_buf;
1872 #endif /* INTERACTIVE */
1874 /* This is the magic location that prints prompts
1875 * and gets data back from the user */
1876 static int FAST_FUNC file_get(struct in_str *i)
1880 /* If there is data waiting, eat it up */
1881 if (i->p && *i->p) {
1882 #if ENABLE_HUSH_INTERACTIVE
1886 if (i->eof_flag && !*i->p)
1888 /* note: ch is never NUL */
1890 /* need to double check i->file because we might be doing something
1891 * more complicated by now, like sourcing or substituting. */
1892 #if ENABLE_HUSH_INTERACTIVE
1893 if (G_interactive_fd && i->promptme && i->file == stdin) {
1896 } while (!*i->p); /* need non-empty line */
1897 i->promptmode = 1; /* PS2 */
1902 do ch = fgetc(i->file); while (ch == '\0');
1904 debug_printf("file_get: got '%c' %d\n", ch, ch);
1905 #if ENABLE_HUSH_INTERACTIVE
1912 /* All callers guarantee this routine will never
1913 * be used right after a newline, so prompting is not needed.
1915 static int FAST_FUNC file_peek(struct in_str *i)
1918 if (i->p && *i->p) {
1919 if (i->eof_flag && !i->p[1])
1922 /* note: ch is never NUL */
1924 do ch = fgetc(i->file); while (ch == '\0');
1925 i->eof_flag = (ch == EOF);
1926 i->peek_buf[0] = ch;
1927 i->peek_buf[1] = '\0';
1929 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1933 static void setup_file_in_str(struct in_str *i, FILE *f)
1935 i->peek = file_peek;
1937 #if ENABLE_HUSH_INTERACTIVE
1939 i->promptmode = 0; /* PS1 */
1945 static void setup_string_in_str(struct in_str *i, const char *s)
1947 i->peek = static_peek;
1948 i->get = static_get;
1949 #if ENABLE_HUSH_INTERACTIVE
1951 i->promptmode = 0; /* PS1 */
1961 #define B_CHUNK (32 * sizeof(char*))
1963 static void o_reset_to_empty_unquoted(o_string *o)
1966 o->has_quoted_part = 0;
1971 static void o_free(o_string *o)
1974 memset(o, 0, sizeof(*o));
1977 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1982 static void o_grow_by(o_string *o, int len)
1984 if (o->length + len > o->maxlen) {
1985 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1986 o->data = xrealloc(o->data, 1 + o->maxlen);
1990 static void o_addchr(o_string *o, int ch)
1992 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1994 o->data[o->length] = ch;
1996 o->data[o->length] = '\0';
1999 static void o_addblock(o_string *o, const char *str, int len)
2002 memcpy(&o->data[o->length], str, len);
2004 o->data[o->length] = '\0';
2007 static void o_addstr(o_string *o, const char *str)
2009 o_addblock(o, str, strlen(str));
2013 static void nommu_addchr(o_string *o, int ch)
2019 # define nommu_addchr(o, str) ((void)0)
2022 static void o_addstr_with_NUL(o_string *o, const char *str)
2024 o_addblock(o, str, strlen(str) + 1);
2027 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2039 #undef HUSH_BRACE_EXP
2041 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2042 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2043 * Apparently, on unquoted $v bash still does globbing
2044 * ("v='*.txt'; echo $v" prints all .txt files),
2045 * but NOT brace expansion! Thus, there should be TWO independent
2046 * quoting mechanisms on $v expansion side: one protects
2047 * $v from brace expansion, and other additionally protects "$v" against globbing.
2048 * We have only second one.
2051 #ifdef HUSH_BRACE_EXP
2052 # define MAYBE_BRACES "{}"
2054 # define MAYBE_BRACES ""
2057 /* My analysis of quoting semantics tells me that state information
2058 * is associated with a destination, not a source.
2060 static void o_addqchr(o_string *o, int ch)
2063 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2068 o->data[o->length] = '\\';
2071 o->data[o->length] = ch;
2073 o->data[o->length] = '\0';
2076 static void o_addQchr(o_string *o, int ch)
2079 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
2081 o->data[o->length] = '\\';
2085 o->data[o->length] = ch;
2087 o->data[o->length] = '\0';
2090 static void o_addQblock(o_string *o, const char *str, int len)
2093 o_addblock(o, str, len);
2099 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2100 if (ordinary_cnt > len) /* paranoia */
2102 o_addblock(o, str, ordinary_cnt);
2103 if (ordinary_cnt == len)
2105 str += ordinary_cnt;
2106 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2110 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2112 o->data[o->length] = '\\';
2116 o->data[o->length] = ch;
2118 o->data[o->length] = '\0';
2122 static void o_addQstr(o_string *o, const char *str)
2124 o_addQblock(o, str, strlen(str));
2127 /* A special kind of o_string for $VAR and `cmd` expansion.
2128 * It contains char* list[] at the beginning, which is grown in 16 element
2129 * increments. Actual string data starts at the next multiple of 16 * (char*).
2130 * list[i] contains an INDEX (int!) into this string data.
2131 * It means that if list[] needs to grow, data needs to be moved higher up
2132 * but list[i]'s need not be modified.
2133 * NB: remembering how many list[i]'s you have there is crucial.
2134 * o_finalize_list() operation post-processes this structure - calculates
2135 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2137 #if DEBUG_EXPAND || DEBUG_GLOB
2138 static void debug_print_list(const char *prefix, o_string *o, int n)
2140 char **list = (char**)o->data;
2141 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2145 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2146 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->has_quoted_part, o->o_escape);
2149 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2150 o->data + (int)list[i] + string_start,
2151 o->data + (int)list[i] + string_start);
2155 const char *p = o->data + (int)list[n - 1] + string_start;
2157 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2161 # define debug_print_list(prefix, o, n) ((void)0)
2164 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2165 * in list[n] so that it points past last stored byte so far.
2166 * It returns n+1. */
2167 static int o_save_ptr_helper(o_string *o, int n)
2169 char **list = (char**)o->data;
2173 if (!o->has_empty_slot) {
2174 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2175 string_len = o->length - string_start;
2176 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2177 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2178 /* list[n] points to string_start, make space for 16 more pointers */
2179 o->maxlen += 0x10 * sizeof(list[0]);
2180 o->data = xrealloc(o->data, o->maxlen + 1);
2181 list = (char**)o->data;
2182 memmove(list + n + 0x10, list + n, string_len);
2183 o->length += 0x10 * sizeof(list[0]);
2185 debug_printf_list("list[%d]=%d string_start=%d\n",
2186 n, string_len, string_start);
2189 /* We have empty slot at list[n], reuse without growth */
2190 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2191 string_len = o->length - string_start;
2192 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2193 n, string_len, string_start);
2194 o->has_empty_slot = 0;
2196 list[n] = (char*)(ptrdiff_t)string_len;
2200 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2201 static int o_get_last_ptr(o_string *o, int n)
2203 char **list = (char**)o->data;
2204 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2206 return ((int)(ptrdiff_t)list[n-1]) + string_start;
2209 #ifdef HUSH_BRACE_EXP
2210 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2211 * first, it processes even {a} (no commas), second,
2212 * I didn't manage to make it return strings when they don't match
2213 * existing files. Need to re-implement it.
2217 static int glob_needed(const char *s)
2226 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2232 /* Return pointer to next closing brace or to comma */
2233 static const char *next_brace_sub(const char *cp)
2237 while (*cp != '\0') {
2244 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2246 if (*cp++ == '{') /*}*/
2250 return *cp != '\0' ? cp : NULL;
2252 /* Recursive brace globber. Note: may garble pattern[]. */
2253 static int glob_brace(char *pattern, o_string *o, int n)
2255 char *new_pattern_buf;
2262 debug_printf_glob("glob_brace('%s')\n", pattern);
2268 if (*begin == '{') /*}*/ {
2269 /* Find the first sub-pattern and at the same time
2270 * find the rest after the closing brace */
2271 next = next_brace_sub(begin);
2273 /* An illegal expression */
2276 /*{*/ if (*next == '}') {
2277 /* "{abc}" with no commas - illegal
2278 * brace expr, disregard and skip it */
2284 if (*begin == '\\' && begin[1] != '\0')
2288 debug_printf_glob("begin:%s\n", begin);
2289 debug_printf_glob("next:%s\n", next);
2291 /* Now find the end of the whole brace expression */
2293 /*{*/ while (*rest != '}') {
2294 rest = next_brace_sub(rest);
2296 /* An illegal expression */
2299 debug_printf_glob("rest:%s\n", rest);
2301 rest_len = strlen(++rest) + 1;
2303 /* We are sure the brace expression is well-formed */
2305 /* Allocate working buffer large enough for our work */
2306 new_pattern_buf = xmalloc(strlen(pattern));
2308 /* We have a brace expression. BEGIN points to the opening {,
2309 * NEXT points past the terminator of the first element, and REST
2310 * points past the final }. We will accumulate result names from
2311 * recursive runs for each brace alternative in the buffer using
2316 /* Construct the new glob expression */
2319 mempcpy(new_pattern_buf,
2320 /* We know the prefix for all sub-patterns */
2321 pattern, begin - pattern),
2325 /* Note: glob_brace() may garble new_pattern_buf[].
2326 * That's why we re-copy prefix every time (1st memcpy above).
2328 n = glob_brace(new_pattern_buf, o, n);
2329 /*{*/ if (*next == '}') {
2330 /* We saw the last entry */
2334 next = next_brace_sub(next);
2336 free(new_pattern_buf);
2344 memset(&globdata, 0, sizeof(globdata));
2345 gr = glob(pattern, 0, NULL, &globdata);
2346 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2348 if (gr == GLOB_NOMATCH) {
2349 globfree(&globdata);
2350 /* NB: garbles parameter */
2351 unbackslash(pattern);
2352 o_addstr_with_NUL(o, pattern);
2353 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2354 return o_save_ptr_helper(o, n);
2356 if (gr == GLOB_NOSPACE)
2357 bb_error_msg_and_die(bb_msg_memory_exhausted);
2358 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2359 * but we didn't specify it. Paranoia again. */
2360 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2362 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2363 char **argv = globdata.gl_pathv;
2365 o_addstr_with_NUL(o, *argv);
2366 n = o_save_ptr_helper(o, n);
2372 globfree(&globdata);
2376 /* Performs globbing on last list[],
2377 * saving each result as a new list[].
2379 static int o_glob(o_string *o, int n)
2381 char *pattern, *copy;
2383 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2385 return o_save_ptr_helper(o, n);
2386 pattern = o->data + o_get_last_ptr(o, n);
2387 debug_printf_glob("glob pattern '%s'\n", pattern);
2388 if (!glob_needed(pattern)) {
2389 /* unbackslash last string in o in place, fix length */
2390 o->length = unbackslash(pattern) - o->data;
2391 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2392 return o_save_ptr_helper(o, n);
2395 copy = xstrdup(pattern);
2396 /* "forget" pattern in o */
2397 o->length = pattern - o->data;
2398 n = glob_brace(copy, o, n);
2401 debug_print_list("o_glob returning", o, n);
2405 #else /* !HUSH_BRACE_EXP */
2408 static int glob_needed(const char *s)
2417 if (*s == '*' || *s == '[' || *s == '?')
2423 /* Performs globbing on last list[],
2424 * saving each result as a new list[].
2426 static int o_glob(o_string *o, int n)
2432 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2434 return o_save_ptr_helper(o, n);
2435 pattern = o->data + o_get_last_ptr(o, n);
2436 debug_printf_glob("glob pattern '%s'\n", pattern);
2437 if (!glob_needed(pattern)) {
2439 /* unbackslash last string in o in place, fix length */
2440 o->length = unbackslash(pattern) - o->data;
2441 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2442 return o_save_ptr_helper(o, n);
2445 memset(&globdata, 0, sizeof(globdata));
2446 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2447 * If we glob "*.\*" and don't find anything, we need
2448 * to fall back to using literal "*.*", but GLOB_NOCHECK
2449 * will return "*.\*"!
2451 gr = glob(pattern, 0, NULL, &globdata);
2452 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2454 if (gr == GLOB_NOMATCH) {
2455 globfree(&globdata);
2458 if (gr == GLOB_NOSPACE)
2459 bb_error_msg_and_die(bb_msg_memory_exhausted);
2460 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2461 * but we didn't specify it. Paranoia again. */
2462 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2464 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2465 char **argv = globdata.gl_pathv;
2466 /* "forget" pattern in o */
2467 o->length = pattern - o->data;
2469 o_addstr_with_NUL(o, *argv);
2470 n = o_save_ptr_helper(o, n);
2476 globfree(&globdata);
2478 debug_print_list("o_glob returning", o, n);
2482 #endif /* !HUSH_BRACE_EXP */
2484 /* If o->o_glob == 1, glob the string so far remembered.
2485 * Otherwise, just finish current list[] and start new */
2486 static int o_save_ptr(o_string *o, int n)
2488 if (o->o_glob) { /* if globbing is requested */
2489 /* If o->has_empty_slot, list[n] was already globbed
2490 * (if it was requested back then when it was filled)
2491 * so don't do that again! */
2492 if (!o->has_empty_slot)
2493 return o_glob(o, n); /* o_save_ptr_helper is inside */
2495 return o_save_ptr_helper(o, n);
2498 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2499 static char **o_finalize_list(o_string *o, int n)
2504 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2506 debug_print_list("finalized", o, n);
2507 debug_printf_expand("finalized n:%d\n", n);
2508 list = (char**)o->data;
2509 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2513 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
2518 static void free_pipe_list(struct pipe *head);
2520 /* Return code is the exit status of the pipe */
2521 static void free_pipe(struct pipe *pi)
2524 struct command *command;
2525 struct redir_struct *r, *rnext;
2528 if (pi->stopped_cmds > 0) /* why? */
2530 debug_printf_clean("run pipe: (pid %d)\n", getpid());
2531 for (i = 0; i < pi->num_cmds; i++) {
2532 command = &pi->cmds[i];
2533 debug_printf_clean(" command %d:\n", i);
2534 if (command->argv) {
2535 for (a = 0, p = command->argv; *p; a++, p++) {
2536 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2538 free_strings(command->argv);
2539 command->argv = NULL;
2541 /* not "else if": on syntax error, we may have both! */
2542 if (command->group) {
2543 debug_printf_clean(" begin group (cmd_type:%d)\n",
2545 free_pipe_list(command->group);
2546 debug_printf_clean(" end group\n");
2547 command->group = NULL;
2549 /* else is crucial here.
2550 * If group != NULL, child_func is meaningless */
2551 #if ENABLE_HUSH_FUNCTIONS
2552 else if (command->child_func) {
2553 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2554 command->child_func->parent_cmd = NULL;
2558 free(command->group_as_string);
2559 command->group_as_string = NULL;
2561 for (r = command->redirects; r; r = rnext) {
2562 debug_printf_clean(" redirect %d%s",
2563 r->rd_fd, redir_table[r->rd_type].descrip);
2564 /* guard against the case >$FOO, where foo is unset or blank */
2565 if (r->rd_filename) {
2566 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2567 free(r->rd_filename);
2568 r->rd_filename = NULL;
2570 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2574 command->redirects = NULL;
2576 free(pi->cmds); /* children are an array, they get freed all at once */
2584 static void free_pipe_list(struct pipe *head)
2586 struct pipe *pi, *next;
2588 for (pi = head; pi; pi = next) {
2590 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
2593 debug_printf_clean("pipe followup code %d\n", pi->followup);
2595 /*pi->next = NULL;*/
2601 /*** Parsing routines ***/
2603 static struct pipe *new_pipe(void)
2606 pi = xzalloc(sizeof(struct pipe));
2607 /*pi->followup = 0; - deliberately invalid value */
2608 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2612 /* Command (member of a pipe) is complete, or we start a new pipe
2613 * if ctx->command is NULL.
2614 * No errors possible here.
2616 static int done_command(struct parse_context *ctx)
2618 /* The command is really already in the pipe structure, so
2619 * advance the pipe counter and make a new, null command. */
2620 struct pipe *pi = ctx->pipe;
2621 struct command *command = ctx->command;
2624 if (IS_NULL_CMD(command)) {
2625 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2629 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2630 //debug_print_tree(ctx->list_head, 20);
2632 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2635 /* Only real trickiness here is that the uncommitted
2636 * command structure is not counted in pi->num_cmds. */
2637 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2638 ctx->command = command = &pi->cmds[pi->num_cmds];
2640 memset(command, 0, sizeof(*command));
2641 return pi->num_cmds; /* used only for 0/nonzero check */
2644 static void done_pipe(struct parse_context *ctx, pipe_style type)
2648 debug_printf_parse("done_pipe entered, followup %d\n", type);
2649 /* Close previous command */
2650 not_null = done_command(ctx);
2651 ctx->pipe->followup = type;
2653 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2654 ctx->ctx_inverted = 0;
2655 ctx->pipe->res_word = ctx->ctx_res_w;
2658 /* Without this check, even just <enter> on command line generates
2659 * tree of three NOPs (!). Which is harmless but annoying.
2660 * IOW: it is safe to do it unconditionally. */
2663 || ctx->ctx_res_w == RES_FI
2665 #if ENABLE_HUSH_LOOPS
2666 || ctx->ctx_res_w == RES_DONE
2667 || ctx->ctx_res_w == RES_FOR
2668 || ctx->ctx_res_w == RES_IN
2670 #if ENABLE_HUSH_CASE
2671 || ctx->ctx_res_w == RES_ESAC
2675 debug_printf_parse("done_pipe: adding new pipe: "
2676 "not_null:%d ctx->ctx_res_w:%d\n",
2677 not_null, ctx->ctx_res_w);
2679 ctx->pipe->next = new_p;
2681 /* RES_THEN, RES_DO etc are "sticky" -
2682 * they remain set for pipes inside if/while.
2683 * This is used to control execution.
2684 * RES_FOR and RES_IN are NOT sticky (needed to support
2685 * cases where variable or value happens to match a keyword):
2687 #if ENABLE_HUSH_LOOPS
2688 if (ctx->ctx_res_w == RES_FOR
2689 || ctx->ctx_res_w == RES_IN)
2690 ctx->ctx_res_w = RES_NONE;
2692 #if ENABLE_HUSH_CASE
2693 if (ctx->ctx_res_w == RES_MATCH)
2694 ctx->ctx_res_w = RES_CASE_BODY;
2695 if (ctx->ctx_res_w == RES_CASE)
2696 ctx->ctx_res_w = RES_CASE_IN;
2698 ctx->command = NULL; /* trick done_command below */
2699 /* Create the memory for command, roughly:
2700 * ctx->pipe->cmds = new struct command;
2701 * ctx->command = &ctx->pipe->cmds[0];
2704 //debug_print_tree(ctx->list_head, 10);
2706 debug_printf_parse("done_pipe return\n");
2709 static void initialize_context(struct parse_context *ctx)
2711 memset(ctx, 0, sizeof(*ctx));
2712 ctx->pipe = ctx->list_head = new_pipe();
2713 /* Create the memory for command, roughly:
2714 * ctx->pipe->cmds = new struct command;
2715 * ctx->command = &ctx->pipe->cmds[0];
2720 /* If a reserved word is found and processed, parse context is modified
2721 * and 1 is returned.
2724 struct reserved_combo {
2727 unsigned char assignment_flag;
2731 FLAG_END = (1 << RES_NONE ),
2733 FLAG_IF = (1 << RES_IF ),
2734 FLAG_THEN = (1 << RES_THEN ),
2735 FLAG_ELIF = (1 << RES_ELIF ),
2736 FLAG_ELSE = (1 << RES_ELSE ),
2737 FLAG_FI = (1 << RES_FI ),
2739 # if ENABLE_HUSH_LOOPS
2740 FLAG_FOR = (1 << RES_FOR ),
2741 FLAG_WHILE = (1 << RES_WHILE),
2742 FLAG_UNTIL = (1 << RES_UNTIL),
2743 FLAG_DO = (1 << RES_DO ),
2744 FLAG_DONE = (1 << RES_DONE ),
2745 FLAG_IN = (1 << RES_IN ),
2747 # if ENABLE_HUSH_CASE
2748 FLAG_MATCH = (1 << RES_MATCH),
2749 FLAG_ESAC = (1 << RES_ESAC ),
2751 FLAG_START = (1 << RES_XXXX ),
2754 static const struct reserved_combo* match_reserved_word(o_string *word)
2756 /* Mostly a list of accepted follow-up reserved words.
2757 * FLAG_END means we are done with the sequence, and are ready
2758 * to turn the compound list into a command.
2759 * FLAG_START means the word must start a new compound list.
2761 static const struct reserved_combo reserved_list[] = {
2763 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2764 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2765 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2766 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2767 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2768 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2770 # if ENABLE_HUSH_LOOPS
2771 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2772 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2773 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2774 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2775 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2776 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2778 # if ENABLE_HUSH_CASE
2779 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2780 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2783 const struct reserved_combo *r;
2785 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2786 if (strcmp(word->data, r->literal) == 0)
2791 /* Return 0: not a keyword, 1: keyword
2793 static int reserved_word(o_string *word, struct parse_context *ctx)
2795 # if ENABLE_HUSH_CASE
2796 static const struct reserved_combo reserved_match = {
2797 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2800 const struct reserved_combo *r;
2802 if (word->has_quoted_part)
2804 r = match_reserved_word(word);
2808 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2809 # if ENABLE_HUSH_CASE
2810 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2811 /* "case word IN ..." - IN part starts first MATCH part */
2812 r = &reserved_match;
2815 if (r->flag == 0) { /* '!' */
2816 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2817 syntax_error("! ! command");
2818 ctx->ctx_res_w = RES_SNTX;
2820 ctx->ctx_inverted = 1;
2823 if (r->flag & FLAG_START) {
2824 struct parse_context *old;
2826 old = xmalloc(sizeof(*old));
2827 debug_printf_parse("push stack %p\n", old);
2828 *old = *ctx; /* physical copy */
2829 initialize_context(ctx);
2831 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2832 syntax_error_at(word->data);
2833 ctx->ctx_res_w = RES_SNTX;
2836 /* "{...} fi" is ok. "{...} if" is not
2838 * if { echo foo; } then { echo bar; } fi */
2839 if (ctx->command->group)
2840 done_pipe(ctx, PIPE_SEQ);
2843 ctx->ctx_res_w = r->res;
2844 ctx->old_flag = r->flag;
2845 word->o_assignment = r->assignment_flag;
2847 if (ctx->old_flag & FLAG_END) {
2848 struct parse_context *old;
2850 done_pipe(ctx, PIPE_SEQ);
2851 debug_printf_parse("pop stack %p\n", ctx->stack);
2853 old->command->group = ctx->list_head;
2854 old->command->cmd_type = CMD_NORMAL;
2856 o_addstr(&old->as_string, ctx->as_string.data);
2857 o_free_unsafe(&ctx->as_string);
2858 old->command->group_as_string = xstrdup(old->as_string.data);
2859 debug_printf_parse("pop, remembering as:'%s'\n",
2860 old->command->group_as_string);
2862 *ctx = *old; /* physical copy */
2867 #endif /* HAS_KEYWORDS */
2869 /* Word is complete, look at it and update parsing context.
2870 * Normal return is 0. Syntax errors return 1.
2871 * Note: on return, word is reset, but not o_free'd!
2873 static int done_word(o_string *word, struct parse_context *ctx)
2875 struct command *command = ctx->command;
2877 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2878 if (word->length == 0 && !word->has_quoted_part) {
2879 debug_printf_parse("done_word return 0: true null, ignored\n");
2883 if (ctx->pending_redirect) {
2884 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2885 * only if run as "bash", not "sh" */
2886 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2888 * ...the word that follows the redirection operator
2889 * shall be subjected to tilde expansion, parameter expansion,
2890 * command substitution, arithmetic expansion, and quote
2891 * removal. Pathname expansion shall not be performed
2892 * on the word by a non-interactive shell; an interactive
2893 * shell may perform it, but shall do so only when
2894 * the expansion would result in one word."
2896 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2897 /* Cater for >\file case:
2898 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2899 * Same with heredocs:
2900 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2902 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2903 unbackslash(ctx->pending_redirect->rd_filename);
2904 /* Is it <<"HEREDOC"? */
2905 if (word->has_quoted_part) {
2906 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2909 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2910 ctx->pending_redirect = NULL;
2912 /* If this word wasn't an assignment, next ones definitely
2913 * can't be assignments. Even if they look like ones. */
2914 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2915 && word->o_assignment != WORD_IS_KEYWORD
2917 word->o_assignment = NOT_ASSIGNMENT;
2919 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2920 command->assignment_cnt++;
2921 word->o_assignment = MAYBE_ASSIGNMENT;
2925 # if ENABLE_HUSH_CASE
2926 if (ctx->ctx_dsemicolon
2927 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2929 /* already done when ctx_dsemicolon was set to 1: */
2930 /* ctx->ctx_res_w = RES_MATCH; */
2931 ctx->ctx_dsemicolon = 0;
2934 if (!command->argv /* if it's the first word... */
2935 # if ENABLE_HUSH_LOOPS
2936 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2937 && ctx->ctx_res_w != RES_IN
2939 # if ENABLE_HUSH_CASE
2940 && ctx->ctx_res_w != RES_CASE
2943 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2944 if (reserved_word(word, ctx)) {
2945 o_reset_to_empty_unquoted(word);
2946 debug_printf_parse("done_word return %d\n",
2947 (ctx->ctx_res_w == RES_SNTX));
2948 return (ctx->ctx_res_w == RES_SNTX);
2950 # ifdef CMD_SINGLEWORD_NOGLOB_COND
2951 if (strcmp(word->data, "export") == 0
2952 # if ENABLE_HUSH_LOCAL
2953 || strcmp(word->data, "local") == 0
2956 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
2959 # if ENABLE_HUSH_BASH_COMPAT
2960 if (strcmp(word->data, "[[") == 0) {
2961 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2967 if (command->group) {
2968 /* "{ echo foo; } echo bar" - bad */
2969 syntax_error_at(word->data);
2970 debug_printf_parse("done_word return 1: syntax error, "
2971 "groups and arglists don't mix\n");
2974 if (word->has_quoted_part
2975 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2976 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2977 /* (otherwise it's known to be not empty and is already safe) */
2979 /* exclude "$@" - it can expand to no word despite "" */
2980 char *p = word->data;
2981 while (p[0] == SPECIAL_VAR_SYMBOL
2982 && (p[1] & 0x7f) == '@'
2983 && p[2] == SPECIAL_VAR_SYMBOL
2987 if (p == word->data || p[0] != '\0') {
2988 /* saw no "$@", or not only "$@" but some
2989 * real text is there too */
2990 /* insert "empty variable" reference, this makes
2991 * e.g. "", $empty"" etc to not disappear */
2992 o_addchr(word, SPECIAL_VAR_SYMBOL);
2993 o_addchr(word, SPECIAL_VAR_SYMBOL);
2996 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2997 debug_print_strings("word appended to argv", command->argv);
3000 #if ENABLE_HUSH_LOOPS
3001 if (ctx->ctx_res_w == RES_FOR) {
3002 if (word->has_quoted_part
3003 || !is_well_formed_var_name(command->argv[0], '\0')
3005 /* bash says just "not a valid identifier" */
3006 syntax_error("not a valid identifier in for");
3009 /* Force FOR to have just one word (variable name) */
3010 /* NB: basically, this makes hush see "for v in ..."
3011 * syntax as if it is "for v; in ...". FOR and IN become
3012 * two pipe structs in parse tree. */
3013 done_pipe(ctx, PIPE_SEQ);
3016 #if ENABLE_HUSH_CASE
3017 /* Force CASE to have just one word */
3018 if (ctx->ctx_res_w == RES_CASE) {
3019 done_pipe(ctx, PIPE_SEQ);
3023 o_reset_to_empty_unquoted(word);
3025 debug_printf_parse("done_word return 0\n");
3030 /* Peek ahead in the input to find out if we have a "&n" construct,
3031 * as in "2>&1", that represents duplicating a file descriptor.
3033 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3034 * REDIRFD_SYNTAX_ERR if syntax error,
3035 * REDIRFD_TO_FILE if no & was seen,
3036 * or the number found.
3039 #define parse_redir_right_fd(as_string, input) \
3040 parse_redir_right_fd(input)
3042 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3048 return REDIRFD_TO_FILE;
3050 ch = i_getch(input); /* get the & */
3051 nommu_addchr(as_string, ch);
3054 ch = i_getch(input);
3055 nommu_addchr(as_string, ch);
3056 return REDIRFD_CLOSE;
3060 while (ch != EOF && isdigit(ch)) {
3061 d = d*10 + (ch-'0');
3063 ch = i_getch(input);
3064 nommu_addchr(as_string, ch);
3069 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3071 bb_error_msg("ambiguous redirect");
3072 return REDIRFD_SYNTAX_ERR;
3075 /* Return code is 0 normal, 1 if a syntax error is detected
3077 static int parse_redirect(struct parse_context *ctx,
3080 struct in_str *input)
3082 struct command *command = ctx->command;
3083 struct redir_struct *redir;
3084 struct redir_struct **redirp;
3087 dup_num = REDIRFD_TO_FILE;
3088 if (style != REDIRECT_HEREDOC) {
3089 /* Check for a '>&1' type redirect */
3090 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3091 if (dup_num == REDIRFD_SYNTAX_ERR)
3094 int ch = i_peek(input);
3095 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3096 if (dup_num) { /* <<-... */
3097 ch = i_getch(input);
3098 nommu_addchr(&ctx->as_string, ch);
3103 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3104 int ch = i_peek(input);
3106 /* >|FILE redirect ("clobbering" >).
3107 * Since we do not support "set -o noclobber" yet,
3108 * >| and > are the same for now. Just eat |.
3110 ch = i_getch(input);
3111 nommu_addchr(&ctx->as_string, ch);
3115 /* Create a new redir_struct and append it to the linked list */
3116 redirp = &command->redirects;
3117 while ((redir = *redirp) != NULL) {
3118 redirp = &(redir->next);
3120 *redirp = redir = xzalloc(sizeof(*redir));
3121 /* redir->next = NULL; */
3122 /* redir->rd_filename = NULL; */
3123 redir->rd_type = style;
3124 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3126 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3127 redir_table[style].descrip);
3129 redir->rd_dup = dup_num;
3130 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3131 /* Erik had a check here that the file descriptor in question
3132 * is legit; I postpone that to "run time"
3133 * A "-" representation of "close me" shows up as a -3 here */
3134 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3135 redir->rd_fd, redir->rd_dup);
3137 /* Set ctx->pending_redirect, so we know what to do at the
3138 * end of the next parsed word. */
3139 ctx->pending_redirect = redir;
3144 /* If a redirect is immediately preceded by a number, that number is
3145 * supposed to tell which file descriptor to redirect. This routine
3146 * looks for such preceding numbers. In an ideal world this routine
3147 * needs to handle all the following classes of redirects...
3148 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3149 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3150 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3151 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3153 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3155 * ... If n is quoted, the number shall not be recognized as part of
3156 * the redirection expression. For example:
3158 * writes the character 2 into file a"
3159 * We are getting it right by setting ->has_quoted_part on any \<char>
3161 * A -1 return means no valid number was found,
3162 * the caller should use the appropriate default for this redirection.
3164 static int redirect_opt_num(o_string *o)
3168 if (o->data == NULL)
3170 num = bb_strtou(o->data, NULL, 10);
3171 if (errno || num < 0)
3173 o_reset_to_empty_unquoted(o);
3178 #define fetch_till_str(as_string, input, word, skip_tabs) \
3179 fetch_till_str(input, word, skip_tabs)
3181 static char *fetch_till_str(o_string *as_string,
3182 struct in_str *input,
3186 o_string heredoc = NULL_O_STRING;
3192 ch = i_getch(input);
3193 nommu_addchr(as_string, ch);
3195 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3196 heredoc.data[past_EOL] = '\0';
3197 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3198 return heredoc.data;
3201 o_addchr(&heredoc, ch);
3202 past_EOL = heredoc.length;
3205 ch = i_getch(input);
3206 nommu_addchr(as_string, ch);
3207 } while (skip_tabs && ch == '\t');
3208 } while (ch == '\n');
3211 o_free_unsafe(&heredoc);
3214 o_addchr(&heredoc, ch);
3215 nommu_addchr(as_string, ch);
3219 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3220 * and load them all. There should be exactly heredoc_cnt of them.
3222 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3224 struct pipe *pi = ctx->list_head;
3226 while (pi && heredoc_cnt) {
3228 struct command *cmd = pi->cmds;
3230 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3232 cmd->argv ? cmd->argv[0] : "NONE");
3233 for (i = 0; i < pi->num_cmds; i++) {
3234 struct redir_struct *redir = cmd->redirects;
3236 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3237 i, cmd->argv ? cmd->argv[0] : "NONE");
3239 if (redir->rd_type == REDIRECT_HEREDOC) {
3242 redir->rd_type = REDIRECT_HEREDOC2;
3243 /* redir->rd_dup is (ab)used to indicate <<- */
3244 p = fetch_till_str(&ctx->as_string, input,
3245 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
3247 syntax_error("unexpected EOF in here document");
3250 free(redir->rd_filename);
3251 redir->rd_filename = p;
3254 redir = redir->next;
3261 /* Should be 0. If it isn't, it's a parse error */
3263 bb_error_msg_and_die("heredoc BUG 2");
3269 static int run_list(struct pipe *pi);
3271 #define parse_stream(pstring, input, end_trigger) \
3272 parse_stream(input, end_trigger)
3274 static struct pipe *parse_stream(char **pstring,
3275 struct in_str *input,
3279 #if !ENABLE_HUSH_FUNCTIONS
3280 #define parse_group(dest, ctx, input, ch) \
3281 parse_group(ctx, input, ch)
3283 static int parse_group(o_string *dest, struct parse_context *ctx,
3284 struct in_str *input, int ch)
3286 /* dest contains characters seen prior to ( or {.
3287 * Typically it's empty, but for function defs,
3288 * it contains function name (without '()'). */
3289 struct pipe *pipe_list;
3291 struct command *command = ctx->command;
3293 debug_printf_parse("parse_group entered\n");
3294 #if ENABLE_HUSH_FUNCTIONS
3295 if (ch == '(' && !dest->has_quoted_part) {
3297 if (done_word(dest, ctx))
3300 goto skip; /* (... */
3301 if (command->argv[1]) { /* word word ... (... */
3302 syntax_error_unexpected_ch('(');
3305 /* it is "word(..." or "word (..." */
3307 ch = i_getch(input);
3308 while (ch == ' ' || ch == '\t');
3310 syntax_error_unexpected_ch(ch);
3313 nommu_addchr(&ctx->as_string, ch);
3315 ch = i_getch(input);
3316 while (ch == ' ' || ch == '\t' || ch == '\n');
3318 syntax_error_unexpected_ch(ch);
3321 nommu_addchr(&ctx->as_string, ch);
3322 command->cmd_type = CMD_FUNCDEF;
3327 #if 0 /* Prevented by caller */
3328 if (command->argv /* word [word]{... */
3329 || dest->length /* word{... */
3330 || dest->has_quoted_part /* ""{... */
3333 debug_printf_parse("parse_group return 1: "
3334 "syntax error, groups and arglists don't mix\n");
3339 #if ENABLE_HUSH_FUNCTIONS
3345 command->cmd_type = CMD_SUBSHELL;
3347 /* bash does not allow "{echo...", requires whitespace */
3348 ch = i_getch(input);
3349 if (ch != ' ' && ch != '\t' && ch != '\n') {
3350 syntax_error_unexpected_ch(ch);
3353 nommu_addchr(&ctx->as_string, ch);
3358 # define as_string NULL
3360 char *as_string = NULL;
3362 pipe_list = parse_stream(&as_string, input, endch);
3365 o_addstr(&ctx->as_string, as_string);
3367 /* empty ()/{} or parse error? */
3368 if (!pipe_list || pipe_list == ERR_PTR) {
3369 /* parse_stream already emitted error msg */
3372 debug_printf_parse("parse_group return 1: "
3373 "parse_stream returned %p\n", pipe_list);
3376 command->group = pipe_list;
3378 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3379 command->group_as_string = as_string;
3380 debug_printf_parse("end of group, remembering as:'%s'\n",
3381 command->group_as_string);
3385 debug_printf_parse("parse_group return 0\n");
3387 /* command remains "open", available for possible redirects */
3390 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3391 /* Subroutines for copying $(...) and `...` things */
3392 static void add_till_backquote(o_string *dest, struct in_str *input);
3394 static void add_till_single_quote(o_string *dest, struct in_str *input)
3397 int ch = i_getch(input);
3399 syntax_error_unterm_ch('\'');
3400 /*xfunc_die(); - redundant */
3407 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3408 static void add_till_double_quote(o_string *dest, struct in_str *input)
3411 int ch = i_getch(input);
3413 syntax_error_unterm_ch('"');
3414 /*xfunc_die(); - redundant */
3418 if (ch == '\\') { /* \x. Copy both chars. */
3420 ch = i_getch(input);
3424 add_till_backquote(dest, input);
3428 //if (ch == '$') ...
3431 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3433 * "Within the backquoted style of command substitution, backslash
3434 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3435 * The search for the matching backquote shall be satisfied by the first
3436 * backquote found without a preceding backslash; during this search,
3437 * if a non-escaped backquote is encountered within a shell comment,
3438 * a here-document, an embedded command substitution of the $(command)
3439 * form, or a quoted string, undefined results occur. A single-quoted
3440 * or double-quoted string that begins, but does not end, within the
3441 * "`...`" sequence produces undefined results."
3443 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3445 static void add_till_backquote(o_string *dest, struct in_str *input)
3448 int ch = i_getch(input);
3450 syntax_error_unterm_ch('`');
3451 /*xfunc_die(); - redundant */
3456 /* \x. Copy both chars unless it is \` */
3457 int ch2 = i_getch(input);
3459 syntax_error_unterm_ch('`');
3460 /*xfunc_die(); - redundant */
3462 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3469 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3470 * quoting and nested ()s.
3471 * "With the $(command) style of command substitution, all characters
3472 * following the open parenthesis to the matching closing parenthesis
3473 * constitute the command. Any valid shell script can be used for command,
3474 * except a script consisting solely of redirections which produces
3475 * unspecified results."
3477 * echo $(echo '(TEST)' BEST) (TEST) BEST
3478 * echo $(echo 'TEST)' BEST) TEST) BEST
3479 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3481 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3482 * can contain arbitrary constructs, just like $(cmd).
3483 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3484 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3486 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3487 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3490 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3491 # if ENABLE_HUSH_BASH_COMPAT
3492 char end_char2 = end_ch >> 8;
3494 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3497 ch = i_getch(input);
3499 syntax_error_unterm_ch(end_ch);
3500 /*xfunc_die(); - redundant */
3502 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3505 /* we look for closing )) of $((EXPR)) */
3506 if (i_peek(input) == end_ch) {
3507 i_getch(input); /* eat second ')' */
3512 if (ch == '(' || ch == '{') {
3513 ch = (ch == '(' ? ')' : '}');
3514 add_till_closing_bracket(dest, input, ch);
3519 add_till_single_quote(dest, input);
3524 add_till_double_quote(dest, input);
3529 add_till_backquote(dest, input);
3534 /* \x. Copy verbatim. Important for \(, \) */
3535 ch = i_getch(input);
3537 syntax_error_unterm_ch(')');
3538 /*xfunc_die(); - redundant */
3546 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3548 /* Return code: 0 for OK, 1 for syntax error */
3550 #define parse_dollar(as_string, dest, input) \
3551 parse_dollar(dest, input)
3552 #define as_string NULL
3554 static int parse_dollar(o_string *as_string,
3556 struct in_str *input)
3558 int ch = i_peek(input); /* first character after the $ */
3559 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
3561 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3563 ch = i_getch(input);
3564 nommu_addchr(as_string, ch);
3566 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3568 debug_printf_parse(": '%c'\n", ch);
3569 o_addchr(dest, ch | quote_mask);
3572 if (!isalnum(ch) && ch != '_')
3574 ch = i_getch(input);
3575 nommu_addchr(as_string, ch);
3577 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3578 } else if (isdigit(ch)) {
3580 ch = i_getch(input);
3581 nommu_addchr(as_string, ch);
3582 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3583 debug_printf_parse(": '%c'\n", ch);
3584 o_addchr(dest, ch | quote_mask);
3585 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3586 } else switch (ch) {
3588 case '!': /* last bg pid */
3589 case '?': /* last exit code */
3590 case '#': /* number of args */
3591 case '*': /* args */
3592 case '@': /* args */
3593 goto make_one_char_var;
3595 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3597 ch = i_getch(input); /* eat '{' */
3598 nommu_addchr(as_string, ch);
3600 ch = i_getch(input); /* first char after '{' */
3601 nommu_addchr(as_string, ch);
3602 /* It should be ${?}, or ${#var},
3603 * or even ${?+subst} - operator acting on a special variable,
3604 * or the beginning of variable name.
3606 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
3608 syntax_error_unterm_str("${name}");
3609 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3614 /* It's possible to just call add_till_closing_bracket() at this point.
3615 * However, this regresses some of our testsuite cases
3616 * which check invalid constructs like ${%}.
3617 * Oh well... let's check that the var name part is fine... */
3623 debug_printf_parse(": '%c'\n", ch);
3625 ch = i_getch(input);
3626 nommu_addchr(as_string, ch);
3630 if (!isalnum(ch) && ch != '_') {
3632 unsigned char last_ch;
3633 /* handle parameter expansions
3634 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3636 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3637 goto bad_dollar_syntax;
3639 /* Eat everything until closing '}' (or ':') */
3641 if (ENABLE_HUSH_BASH_COMPAT
3643 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3645 /* It's ${var:N[:M]} thing */
3646 end_ch = '}' * 0x100 + ':';
3648 if (ENABLE_HUSH_BASH_COMPAT
3651 /* It's ${var/[/]pattern[/repl]} thing */
3652 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3654 nommu_addchr(as_string, '/');
3657 end_ch = '}' * 0x100 + '/';
3663 #if ENABLE_HUSH_DOLLAR_OPS
3664 last_ch = add_till_closing_bracket(dest, input, end_ch);
3666 #error Simple code to only allow ${var} is not implemented
3669 o_addstr(as_string, dest->data + pos);
3670 o_addchr(as_string, last_ch);
3673 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3674 /* close the first block: */
3675 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3676 /* while parsing N from ${var:N[:M]}
3677 * or pattern from ${var/[/]pattern[/repl]} */
3678 if ((end_ch & 0xff) == last_ch) {
3679 /* got ':' or '/'- parse the rest */
3684 if (end_ch == '}' * 0x100 + ':') {
3685 /* it's ${var:N} - emulate :999999999 */
3686 o_addstr(dest, "999999999");
3687 } /* else: it's ${var/[/]pattern} */
3692 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3695 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3699 ch = i_getch(input);
3700 nommu_addchr(as_string, ch);
3701 # if ENABLE_SH_MATH_SUPPORT
3702 if (i_peek(input) == '(') {
3703 ch = i_getch(input);
3704 nommu_addchr(as_string, ch);
3705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3706 o_addchr(dest, /*quote_mask |*/ '+');
3709 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3711 o_addstr(as_string, dest->data + pos);
3712 o_addchr(as_string, ')');
3713 o_addchr(as_string, ')');
3715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3719 # if ENABLE_HUSH_TICK
3720 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3721 o_addchr(dest, quote_mask | '`');
3724 add_till_closing_bracket(dest, input, ')');
3726 o_addstr(as_string, dest->data + pos);
3727 o_addchr(as_string, ')');
3729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3735 ch = i_getch(input);
3736 nommu_addchr(as_string, ch);
3738 if (isalnum(ch)) { /* it's $_name or $_123 */
3743 /* TODO: $_ and $-: */
3744 /* $_ Shell or shell script name; or last argument of last command
3745 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3746 * but in command's env, set to full pathname used to invoke it */
3747 /* $- Option flags set by set builtin or shell options (-i etc) */
3749 o_addQchr(dest, '$');
3751 debug_printf_parse("parse_dollar return 0\n");
3757 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
3758 parse_stream_dquoted(dest, input, dquote_end)
3759 #define as_string NULL
3761 static int parse_stream_dquoted(o_string *as_string,
3763 struct in_str *input,
3770 ch = i_getch(input);
3772 nommu_addchr(as_string, ch);
3773 if (ch == dquote_end) { /* may be only '"' or EOF */
3774 if (dest->o_assignment == NOT_ASSIGNMENT)
3775 dest->o_escape ^= 1;
3776 debug_printf_parse("parse_stream_dquoted return 0\n");
3779 /* note: can't move it above ch == dquote_end check! */
3781 syntax_error_unterm_ch('"');
3782 /*xfunc_die(); - redundant */
3786 next = i_peek(input);
3788 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3789 ch, ch, dest->o_escape);
3792 syntax_error("\\<eof>");
3796 * "The backslash retains its special meaning [in "..."]
3797 * only when followed by one of the following characters:
3798 * $, `, ", \, or <newline>. A double quote may be quoted
3799 * within double quotes by preceding it with a backslash."
3801 if (strchr("$`\"\\\n", next) != NULL) {
3802 ch = i_getch(input);
3804 o_addqchr(dest, ch);
3805 nommu_addchr(as_string, ch);
3808 o_addqchr(dest, '\\');
3809 nommu_addchr(as_string, '\\');
3814 if (parse_dollar(as_string, dest, input) != 0) {
3815 debug_printf_parse("parse_stream_dquoted return 1: "
3816 "parse_dollar returned non-0\n");
3821 #if ENABLE_HUSH_TICK
3823 //unsigned pos = dest->length;
3824 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3825 o_addchr(dest, 0x80 | '`');
3826 add_till_backquote(dest, input);
3827 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3828 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3832 o_addQchr(dest, ch);
3834 && (dest->o_assignment == MAYBE_ASSIGNMENT
3835 || dest->o_assignment == WORD_IS_KEYWORD)
3836 && is_well_formed_var_name(dest->data, '=')
3838 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3845 * Scan input until EOF or end_trigger char.
3846 * Return a list of pipes to execute, or NULL on EOF
3847 * or if end_trigger character is met.
3848 * On syntax error, exit is shell is not interactive,
3849 * reset parsing machinery and start parsing anew,
3850 * or return ERR_PTR.
3852 static struct pipe *parse_stream(char **pstring,
3853 struct in_str *input,
3856 struct parse_context ctx;
3857 o_string dest = NULL_O_STRING;
3861 /* Double-quote state is handled in the state variable is_in_dquote.
3862 * A single-quote triggers a bypass of the main loop until its mate is
3863 * found. When recursing, quote state is passed in via dest->o_escape.
3865 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3866 end_trigger ? end_trigger : 'X');
3869 /* If very first arg is "" or '', dest.data may end up NULL.
3870 * Preventing this: */
3871 o_addchr(&dest, '\0');
3874 G.ifs = get_local_var_value("IFS");
3879 #if ENABLE_HUSH_INTERACTIVE
3880 input->promptmode = 0; /* PS1 */
3882 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
3883 initialize_context(&ctx);
3888 const char *is_special;
3892 redir_type redir_style;
3895 /* dest.has_quoted_part = 1; - already is (see below) */
3896 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
3899 /* We reached closing '"' */
3902 ch = i_getch(input);
3903 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3904 ch, ch, dest.o_escape);
3909 syntax_error_unterm_str("here document");
3912 /* end_trigger == '}' case errors out earlier,
3913 * checking only ')' */
3914 if (end_trigger == ')') {
3915 syntax_error_unterm_ch('('); /* exits */
3916 /* goto parse_error; */
3919 if (done_word(&dest, &ctx)) {
3923 done_pipe(&ctx, PIPE_SEQ);
3925 /* If we got nothing... */
3926 /* (this makes bare "&" cmd a no-op.
3927 * bash says: "syntax error near unexpected token '&'") */
3928 if (pi->num_cmds == 0
3929 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3935 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3937 *pstring = ctx.as_string.data;
3939 o_free_unsafe(&ctx.as_string);
3942 debug_printf_parse("parse_stream return %p\n", pi);
3945 nommu_addchr(&ctx.as_string, ch);
3949 next = i_peek(input);
3951 is_special = "{}<>;&|()#'" /* special outside of "str" */
3952 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3953 /* Are { and } special here? */
3954 if (ctx.command->argv /* word [word]{... - non-special */
3955 || dest.length /* word{... - non-special */
3956 || dest.has_quoted_part /* ""{... - non-special */
3957 || (next != ';' /* }; - special */
3958 && next != ')' /* }) - special */
3959 && next != '&' /* }& and }&& ... - special */
3960 && next != '|' /* }|| ... - special */
3961 && !strchr(G.ifs, next) /* {word - non-special */
3964 /* They are not special, skip "{}" */
3967 is_special = strchr(is_special, ch);
3968 is_ifs = strchr(G.ifs, ch);
3970 if (!is_special && !is_ifs) { /* ordinary char */
3972 o_addQchr(&dest, ch);
3973 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3974 || dest.o_assignment == WORD_IS_KEYWORD)
3976 && is_well_formed_var_name(dest.data, '=')
3978 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3984 if (done_word(&dest, &ctx)) {
3988 #if ENABLE_HUSH_CASE
3989 /* "case ... in <newline> word) ..." -
3990 * newlines are ignored (but ';' wouldn't be) */
3991 if (ctx.command->argv == NULL
3992 && ctx.ctx_res_w == RES_MATCH
3997 /* Treat newline as a command separator. */
3998 done_pipe(&ctx, PIPE_SEQ);
3999 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4001 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4006 dest.o_assignment = MAYBE_ASSIGNMENT;
4008 /* note: if (is_ifs) continue;
4009 * will still trigger for us */
4013 /* "cmd}" or "cmd }..." without semicolon or &:
4014 * } is an ordinary char in this case, even inside { cmd; }
4015 * Pathological example: { ""}; } should exec "}" cmd
4018 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4019 || dest.length != 0 /* word} */
4020 || dest.has_quoted_part /* ""} */
4024 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4025 goto skip_end_trigger;
4026 /* else: } does terminate a group */
4029 if (end_trigger && end_trigger == ch
4030 && (ch != ';' || heredoc_cnt == 0)
4031 #if ENABLE_HUSH_CASE
4033 || ctx.ctx_res_w != RES_MATCH
4034 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4039 /* This is technically valid:
4040 * { cat <<HERE; }; echo Ok
4044 * but we don't support this.
4045 * We require heredoc to be in enclosing {}/(),
4048 syntax_error_unterm_str("here document");
4051 if (done_word(&dest, &ctx)) {
4054 done_pipe(&ctx, PIPE_SEQ);
4055 dest.o_assignment = MAYBE_ASSIGNMENT;
4056 /* Do we sit outside of any if's, loops or case's? */
4058 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4062 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4064 *pstring = ctx.as_string.data;
4066 o_free_unsafe(&ctx.as_string);
4069 debug_printf_parse("parse_stream return %p: "
4070 "end_trigger char found\n",
4072 return ctx.list_head;
4079 /* Catch <, > before deciding whether this word is
4080 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4083 redir_fd = redirect_opt_num(&dest);
4084 if (done_word(&dest, &ctx)) {
4087 redir_style = REDIRECT_OVERWRITE;
4089 redir_style = REDIRECT_APPEND;
4090 ch = i_getch(input);
4091 nommu_addchr(&ctx.as_string, ch);
4094 else if (next == '(') {
4095 syntax_error(">(process) not supported");
4099 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4101 continue; /* back to top of while (1) */
4103 redir_fd = redirect_opt_num(&dest);
4104 if (done_word(&dest, &ctx)) {
4107 redir_style = REDIRECT_INPUT;
4109 redir_style = REDIRECT_HEREDOC;
4111 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4112 ch = i_getch(input);
4113 nommu_addchr(&ctx.as_string, ch);
4114 } else if (next == '>') {
4115 redir_style = REDIRECT_IO;
4116 ch = i_getch(input);
4117 nommu_addchr(&ctx.as_string, ch);
4120 else if (next == '(') {
4121 syntax_error("<(process) not supported");
4125 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4127 continue; /* back to top of while (1) */
4130 if (dest.o_assignment == MAYBE_ASSIGNMENT
4131 /* check that we are not in word in "a=1 2>word b=1": */
4132 && !ctx.pending_redirect
4134 /* ch is a special char and thus this word
4135 * cannot be an assignment */
4136 dest.o_assignment = NOT_ASSIGNMENT;
4139 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4143 if (dest.length == 0) {
4146 if (ch == EOF || ch == '\n')
4149 /* note: we do not add it to &ctx.as_string */
4151 nommu_addchr(&ctx.as_string, '\n');
4153 o_addQchr(&dest, ch);
4158 syntax_error("\\<eof>");
4161 ch = i_getch(input);
4163 o_addchr(&dest, '\\');
4164 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4165 o_addchr(&dest, ch);
4166 nommu_addchr(&ctx.as_string, ch);
4167 /* Example: echo Hello \2>file
4168 * we need to know that word 2 is quoted */
4169 dest.has_quoted_part = 1;
4173 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4174 ctx.as_string.data[--ctx.as_string.length] = '\0';
4179 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
4180 debug_printf_parse("parse_stream parse error: "
4181 "parse_dollar returned non-0\n");
4186 dest.has_quoted_part = 1;
4188 ch = i_getch(input);
4190 syntax_error_unterm_ch('\'');
4191 /*xfunc_die(); - redundant */
4193 nommu_addchr(&ctx.as_string, ch);
4196 o_addqchr(&dest, ch);
4200 dest.has_quoted_part = 1;
4201 is_in_dquote ^= 1; /* invert */
4202 if (dest.o_assignment == NOT_ASSIGNMENT)
4205 #if ENABLE_HUSH_TICK
4209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4210 o_addchr(&dest, '`');
4212 add_till_backquote(&dest, input);
4214 o_addstr(&ctx.as_string, dest.data + pos);
4215 o_addchr(&ctx.as_string, '`');
4217 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4218 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4223 #if ENABLE_HUSH_CASE
4226 if (done_word(&dest, &ctx)) {
4229 done_pipe(&ctx, PIPE_SEQ);
4230 #if ENABLE_HUSH_CASE
4231 /* Eat multiple semicolons, detect
4232 * whether it means something special */
4237 ch = i_getch(input);
4238 nommu_addchr(&ctx.as_string, ch);
4239 if (ctx.ctx_res_w == RES_CASE_BODY) {
4240 ctx.ctx_dsemicolon = 1;
4241 ctx.ctx_res_w = RES_MATCH;
4247 /* We just finished a cmd. New one may start
4248 * with an assignment */
4249 dest.o_assignment = MAYBE_ASSIGNMENT;
4252 if (done_word(&dest, &ctx)) {
4256 ch = i_getch(input);
4257 nommu_addchr(&ctx.as_string, ch);
4258 done_pipe(&ctx, PIPE_AND);
4260 done_pipe(&ctx, PIPE_BG);
4264 if (done_word(&dest, &ctx)) {
4267 #if ENABLE_HUSH_CASE
4268 if (ctx.ctx_res_w == RES_MATCH)
4269 break; /* we are in case's "word | word)" */
4271 if (next == '|') { /* || */
4272 ch = i_getch(input);
4273 nommu_addchr(&ctx.as_string, ch);
4274 done_pipe(&ctx, PIPE_OR);
4276 /* we could pick up a file descriptor choice here
4277 * with redirect_opt_num(), but bash doesn't do it.
4278 * "echo foo 2| cat" yields "foo 2". */
4281 o_reset_to_empty_unquoted(&ctx.as_string);
4286 #if ENABLE_HUSH_CASE
4287 /* "case... in [(]word)..." - skip '(' */
4288 if (ctx.ctx_res_w == RES_MATCH
4289 && ctx.command->argv == NULL /* not (word|(... */
4290 && dest.length == 0 /* not word(... */
4291 && dest.has_quoted_part == 0 /* not ""(... */
4297 if (parse_group(&dest, &ctx, input, ch) != 0) {
4302 #if ENABLE_HUSH_CASE
4303 if (ctx.ctx_res_w == RES_MATCH)
4307 /* proper use of this character is caught by end_trigger:
4308 * if we see {, we call parse_group(..., end_trigger='}')
4309 * and it will match } earlier (not here). */
4310 syntax_error_unexpected_ch(ch);
4314 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4320 struct parse_context *pctx;
4321 IF_HAS_KEYWORDS(struct parse_context *p2;)
4323 /* Clean up allocated tree.
4324 * Sample for finding leaks on syntax error recovery path.
4325 * Run it from interactive shell, watch pmap `pidof hush`.
4326 * while if false; then false; fi; do break; fi
4327 * Samples to catch leaks at execution:
4328 * while if (true | {true;}); then echo ok; fi; do break; done
4329 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4333 /* Update pipe/command counts,
4334 * otherwise freeing may miss some */
4335 done_pipe(pctx, PIPE_SEQ);
4336 debug_printf_clean("freeing list %p from ctx %p\n",
4337 pctx->list_head, pctx);
4338 debug_print_tree(pctx->list_head, 0);
4339 free_pipe_list(pctx->list_head);
4340 debug_printf_clean("freed list %p\n", pctx->list_head);
4342 o_free_unsafe(&pctx->as_string);
4344 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4348 IF_HAS_KEYWORDS(pctx = p2;)
4349 } while (HAS_KEYWORDS && pctx);
4350 /* Free text, clear all dest fields */
4352 /* If we are not in top-level parse, we return,
4353 * our caller will propagate error.
4355 if (end_trigger != ';') {
4363 /* Discard cached input, force prompt */
4365 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4371 /*** Execution routines ***/
4373 /* Expansion can recurse, need forward decls: */
4374 static char *expand_string_to_string(const char *str);
4375 static int process_command_subs(o_string *dest, const char *s);
4377 /* expand_strvec_to_strvec() takes a list of strings, expands
4378 * all variable references within and returns a pointer to
4379 * a list of expanded strings, possibly with larger number
4380 * of strings. (Think VAR="a b"; echo $VAR).
4381 * This new list is allocated as a single malloc block.
4382 * NULL-terminated list of char* pointers is at the beginning of it,
4383 * followed by strings themself.
4384 * Caller can deallocate entire list by single free(list). */
4386 /* Store given string, finalizing the word and starting new one whenever
4387 * we encounter IFS char(s). This is used for expanding variable values.
4388 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4389 static int expand_on_ifs(o_string *output, int n, const char *str)
4392 int word_len = strcspn(str, G.ifs);
4394 if (output->o_escape || !output->o_glob)
4395 o_addQblock(output, str, word_len);
4396 else /* protect backslashes against globbing up :) */
4397 o_addblock_duplicate_backslash(output, str, word_len);
4400 if (!*str) /* EOL - do not finalize word */
4402 o_addchr(output, '\0');
4403 debug_print_list("expand_on_ifs", output, n);
4404 n = o_save_ptr(output, n);
4405 str += strspn(str, G.ifs); /* skip ifs chars */
4407 debug_print_list("expand_on_ifs[1]", output, n);
4411 /* Helper to expand $((...)) and heredoc body. These act as if
4412 * they are in double quotes, with the exception that they are not :).
4413 * Just the rules are similar: "expand only $var and `cmd`"
4415 * Returns malloced string.
4416 * As an optimization, we return NULL if expansion is not needed.
4418 static char *expand_pseudo_dquoted(const char *str)
4421 struct in_str input;
4422 o_string dest = NULL_O_STRING;
4424 if (!strchr(str, '$')
4425 #if ENABLE_HUSH_TICK
4426 && !strchr(str, '`')
4432 /* We need to expand. Example:
4433 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4435 setup_string_in_str(&input, str);
4436 parse_stream_dquoted(NULL, &dest, &input, EOF);
4437 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4438 exp_str = expand_string_to_string(dest.data);
4439 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4440 o_free_unsafe(&dest);
4444 #if ENABLE_SH_MATH_SUPPORT
4445 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4447 arith_eval_hooks_t hooks;
4451 hooks.lookupvar = get_local_var_value;
4452 hooks.setvar = set_local_var_from_halves;
4453 hooks.endofname = endofname;
4454 exp_str = expand_pseudo_dquoted(arg);
4455 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4461 #if ENABLE_HUSH_BASH_COMPAT
4462 /* ${var/[/]pattern[/repl]} helpers */
4463 static char *strstr_pattern(char *val, const char *pattern, int *size)
4466 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4467 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4474 /* Optimization: if "*pat" did not match the start of "string",
4475 * we know that "tring", "ring" etc will not match too:
4477 if (pattern[0] == '*')
4482 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4484 char *result = NULL;
4485 unsigned res_len = 0;
4486 unsigned repl_len = strlen(repl);
4490 char *s = strstr_pattern(val, pattern, &size);
4494 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4495 memcpy(result + res_len, val, s - val);
4497 strcpy(result + res_len, repl);
4498 res_len += repl_len;
4499 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4505 if (val[0] && result) {
4506 result = xrealloc(result, res_len + strlen(val) + 1);
4507 strcpy(result + res_len, val);
4508 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4510 debug_printf_varexp("result:'%s'\n", result);
4516 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4518 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp, char first_ch)
4520 const char *val = NULL;
4521 char *to_be_freed = NULL;
4526 char exp_save = exp_save; /* for compiler */
4527 char *exp_saveptr; /* points to expansion operator */
4528 char *exp_word = exp_word; /* for compiler */
4532 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4533 first_char = arg[0] = first_ch & 0x7f;
4536 if (first_char == '#' && arg[1] && !exp_saveptr) {
4537 /* handle length expansion ${#var} */
4541 /* maybe handle parameter expansion */
4542 if (exp_saveptr /* if 2nd char is one of expansion operators */
4543 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4545 /* ${?:0}, ${#[:]%0} etc */
4546 exp_saveptr = var + 1;
4548 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4549 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4551 exp_op = exp_save = *exp_saveptr;
4553 exp_word = exp_saveptr + 1;
4554 if (exp_op == ':') {
4555 exp_op = *exp_word++;
4556 if (ENABLE_HUSH_BASH_COMPAT
4557 && (exp_op == '\0' || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4559 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4564 *exp_saveptr = '\0';
4565 } /* else: it's not an expansion op, but bare ${var} */
4568 /* lookup the variable in question */
4569 if (isdigit(var[0])) {
4570 /* parse_dollar() should have vetted var for us */
4571 int n = xatoi_positive(var);
4572 if (n < G.global_argc)
4573 val = G.global_argv[n];
4574 /* else val remains NULL: $N with too big N */
4578 val = utoa(G.root_pid);
4580 case '!': /* bg pid */
4581 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4583 case '?': /* exitcode */
4584 val = utoa(G.last_exitcode);
4586 case '#': /* argc */
4587 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4590 val = get_local_var_value(var);
4594 /* Handle any expansions */
4595 if (exp_op == 'L') {
4596 debug_printf_expand("expand: length(%s)=", val);
4597 val = utoa(val ? strlen(val) : 0);
4598 debug_printf_expand("%s\n", val);
4599 } else if (exp_op) {
4600 if (exp_op == '%' || exp_op == '#') {
4601 /* Standard-mandated substring removal ops:
4602 * ${parameter%word} - remove smallest suffix pattern
4603 * ${parameter%%word} - remove largest suffix pattern
4604 * ${parameter#word} - remove smallest prefix pattern
4605 * ${parameter##word} - remove largest prefix pattern
4607 * Word is expanded to produce a glob pattern.
4608 * Then var's value is matched to it and matching part removed.
4610 if (val && val[0]) {
4613 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4614 if (exp_op == *exp_word) /* ## or %% */
4616 //TODO: avoid xstrdup unless needed
4617 // (see HACK ALERT below)
4618 val = to_be_freed = xstrdup(val);
4619 exp_exp_word = expand_pseudo_dquoted(exp_word);
4621 exp_word = exp_exp_word;
4622 loc = scan_and_match(to_be_freed, exp_word, scan_flags);
4623 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4624 // exp_op, to_be_freed, exp_word, loc);
4626 if (loc) { /* match was found */
4627 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4634 #if ENABLE_HUSH_BASH_COMPAT
4635 else if (exp_op == '/' || exp_op == '\\') {
4636 /* Empty variable always gives nothing: */
4637 // "v=''; echo ${v/*/w}" prints ""
4638 if (val && val[0]) {
4639 /* It's ${var/[/]pattern[/repl]} thing */
4640 char *pattern, *repl, *t;
4641 pattern = expand_pseudo_dquoted(exp_word);
4643 pattern = xstrdup(exp_word);
4644 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4645 *p++ = SPECIAL_VAR_SYMBOL;
4647 p = strchr(p, SPECIAL_VAR_SYMBOL);
4649 repl = expand_pseudo_dquoted(exp_word);
4650 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4651 /* HACK ALERT. We depend here on the fact that
4652 * G.global_argv and results of utoa and get_local_var_value
4653 * are actually in writable memory:
4654 * replace_pattern momentarily stores NULs there. */
4656 to_be_freed = replace_pattern(t,
4658 (repl ? repl : exp_word),
4660 if (to_be_freed) /* at least one replace happened */
4667 else if (exp_op == ':') {
4668 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4669 /* It's ${var:N[:M]} bashism.
4670 * Note that in encoded form it has TWO parts:
4671 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4676 beg = expand_and_evaluate_arith(exp_word, &errcode);
4677 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4678 *p++ = SPECIAL_VAR_SYMBOL;
4680 p = strchr(p, SPECIAL_VAR_SYMBOL);
4682 len = expand_and_evaluate_arith(exp_word, &errcode);
4683 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4685 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4686 if (beg < 0) /* bash compat */
4688 debug_printf_varexp("from val:'%s'\n", val);
4689 if (len == 0 || !val || beg >= strlen(val))
4692 /* Paranoia. What if user entered 9999999999999
4693 * which fits in arith_t but not int? */
4696 val = to_be_freed = xstrndup(val + beg, len);
4698 debug_printf_varexp("val:'%s'\n", val);
4702 die_if_script("malformed ${%s:...}", var);
4705 } else { /* one of "-=+?" */
4706 /* Standard-mandated substitution ops:
4707 * ${var?word} - indicate error if unset
4708 * If var is unset, word (or a message indicating it is unset
4709 * if word is null) is written to standard error
4710 * and the shell exits with a non-zero exit status.
4711 * Otherwise, the value of var is substituted.
4712 * ${var-word} - use default value
4713 * If var is unset, word is substituted.
4714 * ${var=word} - assign and use default value
4715 * If var is unset, word is assigned to var.
4716 * In all cases, final value of var is substituted.
4717 * ${var+word} - use alternative value
4718 * If var is unset, null is substituted.
4719 * Otherwise, word is substituted.
4721 * Word is subjected to tilde expansion, parameter expansion,
4722 * command substitution, and arithmetic expansion.
4723 * If word is not needed, it is not expanded.
4725 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4726 * but also treat null var as if it is unset.
4728 int use_word = (!val || ((exp_save == ':') && !val[0]));
4730 use_word = !use_word;
4731 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4732 (exp_save == ':') ? "true" : "false", use_word);
4734 to_be_freed = expand_pseudo_dquoted(exp_word);
4736 exp_word = to_be_freed;
4737 if (exp_op == '?') {
4738 /* mimic bash message */
4739 die_if_script("%s: %s",
4741 exp_word[0] ? exp_word : "parameter null or not set"
4743 //TODO: how interactive bash aborts expansion mid-command?
4748 if (exp_op == '=') {
4749 /* ${var=[word]} or ${var:=[word]} */
4750 if (isdigit(var[0]) || var[0] == '#') {
4751 /* mimic bash message */
4752 die_if_script("$%s: cannot assign in this way", var);
4755 char *new_var = xasprintf("%s=%s", var, val);
4756 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4760 } /* one of "-=+?" */
4762 *exp_saveptr = exp_save;
4768 *to_be_freed_pp = to_be_freed;
4772 /* Expand all variable references in given string, adding words to list[]
4773 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4774 * to be filled). This routine is extremely tricky: has to deal with
4775 * variables/parameters with whitespace, $* and $@, and constructs like
4776 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4777 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
4779 /* or_mask is either 0 (normal case) or 0x80 -
4780 * expansion of right-hand side of assignment == 1-element expand.
4781 * It will also do no globbing, and thus we must not backslash-quote!
4788 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
4789 debug_print_list("expand_vars_to_list", output, n);
4790 n = o_save_ptr(output, n);
4791 debug_print_list("expand_vars_to_list[0]", output, n);
4793 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4796 char *to_be_freed = NULL;
4797 const char *val = NULL;
4798 #if ENABLE_HUSH_TICK
4799 o_string subst_result = NULL_O_STRING;
4801 #if ENABLE_SH_MATH_SUPPORT
4802 char arith_buf[sizeof(arith_t)*3 + 2];
4804 o_addblock(output, arg, p - arg);
4805 debug_print_list("expand_vars_to_list[1]", output, n);
4807 p = strchr(p, SPECIAL_VAR_SYMBOL);
4809 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
4810 /* "$@" is special. Even if quoted, it can still
4811 * expand to nothing (not even an empty string) */
4812 if ((first_ch & 0x7f) != '@')
4813 ored_ch |= first_ch;
4815 switch (first_ch & 0x7f) {
4816 /* Highest bit in first_ch indicates that var is double-quoted */
4820 if (!G.global_argv[i])
4822 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4823 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4824 smallint sv = output->o_escape;
4825 /* unquoted var's contents should be globbed, so don't escape */
4826 output->o_escape = 0;
4827 while (G.global_argv[i]) {
4828 n = expand_on_ifs(output, n, G.global_argv[i]);
4829 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4830 if (G.global_argv[i++][0] && G.global_argv[i]) {
4831 /* this argv[] is not empty and not last:
4832 * put terminating NUL, start new word */
4833 o_addchr(output, '\0');
4834 debug_print_list("expand_vars_to_list[2]", output, n);
4835 n = o_save_ptr(output, n);
4836 debug_print_list("expand_vars_to_list[3]", output, n);
4839 output->o_escape = sv;
4841 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
4842 * and in this case should treat it like '$*' - see 'else...' below */
4843 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
4845 o_addQstr(output, G.global_argv[i]);
4846 if (++i >= G.global_argc)
4848 o_addchr(output, '\0');
4849 debug_print_list("expand_vars_to_list[4]", output, n);
4850 n = o_save_ptr(output, n);
4852 } else { /* quoted $*: add as one word */
4854 o_addQstr(output, G.global_argv[i]);
4855 if (!G.global_argv[++i])
4858 o_addchr(output, G.ifs[0]);
4862 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4863 /* "Empty variable", used to make "" etc to not disappear */
4867 #if ENABLE_HUSH_TICK
4868 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4871 /* Can't just stuff it into output o_string,
4872 * expanded result may need to be globbed
4873 * and $IFS-splitted */
4874 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4875 G.last_exitcode = process_command_subs(&subst_result, arg);
4876 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4877 val = subst_result.data;
4880 #if ENABLE_SH_MATH_SUPPORT
4881 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4885 arg++; /* skip '+' */
4886 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4887 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4888 res = expand_and_evaluate_arith(arg, &errcode);
4891 const char *msg = "error in arithmetic";
4894 msg = "exponent less than 0";
4897 msg = "divide by 0";
4900 msg = "expression recursion loop detected";
4905 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4906 sprintf(arith_buf, arith_t_fmt, res);
4912 val = expand_one_var(&to_be_freed, arg, &p, first_ch);
4913 IF_HUSH_TICK(store_val:)
4914 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4915 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
4916 if (val && val[0]) {
4917 /* unquoted var's contents should be globbed, so don't escape */
4918 smallint sv = output->o_escape;
4919 output->o_escape = 0;
4920 n = expand_on_ifs(output, n, val);
4922 output->o_escape = sv;
4924 } else { /* quoted $VAR, val will be appended below */
4925 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
4929 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4931 if (val && val[0]) {
4932 o_addQstr(output, val);
4935 /* Do the check to avoid writing to a const string */
4936 if (*p != SPECIAL_VAR_SYMBOL)
4937 *p = SPECIAL_VAR_SYMBOL;
4939 #if ENABLE_HUSH_TICK
4940 o_free(&subst_result);
4943 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4946 debug_print_list("expand_vars_to_list[a]", output, n);
4947 /* this part is literal, and it was already pre-quoted
4948 * if needed (much earlier), do not use o_addQstr here! */
4949 o_addstr_with_NUL(output, arg);
4950 debug_print_list("expand_vars_to_list[b]", output, n);
4951 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4952 && !(ored_ch & 0x80) /* and all vars were not quoted. */
4955 /* allow to reuse list[n] later without re-growth */
4956 output->has_empty_slot = 1;
4958 o_addchr(output, '\0');
4965 EXPVAR_FLAG_GLOB = 0x200,
4966 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
4967 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
4969 static char **expand_variables(char **argv, unsigned or_mask)
4974 o_string output = NULL_O_STRING;
4976 /* protect against globbing for "$var"? */
4977 /* (unquoted $var will temporarily switch it off) */
4978 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
4979 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
4984 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
4987 debug_print_list("expand_variables", &output, n);
4989 /* output.data (malloced in one block) gets returned in "list" */
4990 list = o_finalize_list(&output, n);
4991 debug_print_strings("expand_variables[1]", list);
4995 static char **expand_strvec_to_strvec(char **argv)
4997 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
5000 #if ENABLE_HUSH_BASH_COMPAT
5001 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5003 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5007 #ifdef CMD_SINGLEWORD_NOGLOB_COND
5008 static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
5013 o_string output = NULL_O_STRING;
5018 int is_var = is_well_formed_var_name(*v, '=');
5019 /* is_var * 0x80: singleword expansion for vars */
5020 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
5022 /* Subtle! expand_vars_to_list did not glob last word yet.
5023 * It does this only when fed with further data.
5024 * Therefore we set globbing flags AFTER it, not before:
5027 /* if it is not recognizably abc=...; then: */
5028 output.o_escape = !is_var; /* protect against globbing for "$var" */
5029 /* (unquoted $var will temporarily switch it off) */
5030 output.o_glob = !is_var; /* and indeed do globbing */
5033 debug_print_list("expand_cond", &output, n);
5035 /* output.data (malloced in one block) gets returned in "list" */
5036 list = o_finalize_list(&output, n);
5037 debug_print_strings("expand_cond[1]", list);
5042 /* Used for expansion of right hand of assignments */
5043 /* NB: should NOT do globbing!
5044 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
5045 static char *expand_string_to_string(const char *str)
5047 char *argv[2], **list;
5049 /* This is generally an optimization, but it also
5050 * handles "", which otherwise trips over !list[0] check below.
5051 * (is this ever happens that we actually get str="" here?)
5053 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5054 //TODO: Can use on strings with \ too, just unbackslash() them?
5055 debug_printf_expand("string_to_string(fast)='%s'\n", str);
5056 return xstrdup(str);
5059 argv[0] = (char*)str;
5061 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
5063 if (!list[0] || list[1])
5064 bb_error_msg_and_die("BUG in varexp2");
5065 /* actually, just move string 2*sizeof(char*) bytes back */
5066 overlapping_strcpy((char*)list, list[0]);
5067 unbackslash((char*)list);
5068 debug_printf_expand("string_to_string='%s'\n", (char*)list);
5072 /* Used for "eval" builtin */
5073 static char* expand_strvec_to_string(char **argv)
5077 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
5078 /* Convert all NULs to spaces */
5083 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5084 bb_error_msg_and_die("BUG in varexp3");
5085 /* bash uses ' ' regardless of $IFS contents */
5090 overlapping_strcpy((char*)list, list[0]);
5091 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5095 static char **expand_assignments(char **argv, int count)
5100 G.expanded_assignments = p = NULL;
5101 /* Expand assignments into one string each */
5102 for (i = 0; i < count; i++) {
5103 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
5105 G.expanded_assignments = NULL;
5112 void re_execute_shell(char ***to_free, const char *s,
5113 char *g_argv0, char **g_argv,
5114 char **builtin_argv) NORETURN;
5116 static void reset_traps_to_defaults(void)
5118 /* This function is always called in a child shell
5119 * after fork (not vfork, NOMMU doesn't use this function).
5124 /* Child shells are not interactive.
5125 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5126 * Testcase: (while :; do :; done) + ^Z should background.
5127 * Same goes for SIGTERM, SIGHUP, SIGINT.
5129 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5130 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5132 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5133 * Stupid. It can be done with *single* &= op, but we can't use
5134 * the fact that G.blocked_set is implemented as a bitmask
5136 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5140 /* Careful. Only if no trap or trap is not "" */
5141 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5142 sigdelset(&G.blocked_set, sig);
5149 /* Our homegrown sig mask is saner to work with :) */
5150 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5152 /* Resetting all traps to default except empty ones */
5153 mask = G.non_DFL_mask;
5154 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5155 if (!G.traps[sig] || !G.traps[sig][0])
5158 G.traps[sig] = NULL;
5159 /* There is no signal for 0 (EXIT) */
5162 /* There was a trap handler, we just removed it.
5163 * But if sig still has non-DFL handling,
5164 * we should not unblock the sig. */
5167 sigdelset(&G.blocked_set, sig);
5169 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5174 static void re_execute_shell(char ***to_free, const char *s,
5175 char *g_argv0, char **g_argv,
5176 char **builtin_argv) NORETURN;
5177 static void re_execute_shell(char ***to_free, const char *s,
5178 char *g_argv0, char **g_argv,
5179 char **builtin_argv)
5181 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5182 /* delims + 2 * (number of bytes in printed hex numbers) */
5183 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5184 char *heredoc_argv[4];
5185 struct variable *cur;
5186 # if ENABLE_HUSH_FUNCTIONS
5187 struct function *funcp;
5191 unsigned long long empty_trap_mask;
5193 if (!g_argv0) { /* heredoc */
5194 argv = heredoc_argv;
5195 argv[0] = (char *) G.argv0_for_re_execing;
5196 argv[1] = (char *) "-<";
5197 argv[2] = (char *) s;
5199 pp = &argv[3]; /* used as pointer to empty environment */
5205 if (pp) while (*pp++)
5208 empty_trap_mask = 0;
5211 for (sig = 1; sig < NSIG; sig++) {
5212 if (G.traps[sig] && !G.traps[sig][0])
5213 empty_trap_mask |= 1LL << sig;
5217 sprintf(param_buf, NOMMU_HACK_FMT
5218 , (unsigned) G.root_pid
5219 , (unsigned) G.root_ppid
5220 , (unsigned) G.last_bg_pid
5221 , (unsigned) G.last_exitcode
5224 IF_HUSH_LOOPS(, G.depth_of_loop)
5226 # undef NOMMU_HACK_FMT
5227 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5228 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5231 for (cur = G.top_var; cur; cur = cur->next) {
5232 if (!cur->flg_export || cur->flg_read_only)
5235 # if ENABLE_HUSH_FUNCTIONS
5236 for (funcp = G.top_func; funcp; funcp = funcp->next)
5242 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5243 *pp++ = (char *) G.argv0_for_re_execing;
5245 for (cur = G.top_var; cur; cur = cur->next) {
5246 if (strcmp(cur->varstr, hush_version_str) == 0)
5248 if (cur->flg_read_only) {
5249 *pp++ = (char *) "-R";
5250 *pp++ = cur->varstr;
5251 } else if (!cur->flg_export) {
5252 *pp++ = (char *) "-V";
5253 *pp++ = cur->varstr;
5256 # if ENABLE_HUSH_FUNCTIONS
5257 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5258 *pp++ = (char *) "-F";
5259 *pp++ = funcp->name;
5260 *pp++ = funcp->body_as_string;
5263 /* We can pass activated traps here. Say, -Tnn:trap_string
5265 * However, POSIX says that subshells reset signals with traps
5267 * I tested bash-3.2 and it not only does that with true subshells
5268 * of the form ( list ), but with any forked children shells.
5269 * I set trap "echo W" WINCH; and then tried:
5271 * { echo 1; sleep 20; echo 2; } &
5272 * while true; do echo 1; sleep 20; echo 2; break; done &
5273 * true | { echo 1; sleep 20; echo 2; } | cat
5275 * In all these cases sending SIGWINCH to the child shell
5276 * did not run the trap. If I add trap "echo V" WINCH;
5277 * _inside_ group (just before echo 1), it works.
5279 * I conclude it means we don't need to pass active traps here.
5280 * Even if we would use signal handlers instead of signal masking
5281 * in order to implement trap handling,
5282 * exec syscall below resets signals to SIG_DFL for us.
5284 *pp++ = (char *) "-c";
5287 while (*++builtin_argv)
5288 *pp++ = *builtin_argv;
5289 *pp++ = (char *) "";
5294 /* *pp = NULL; - is already there */
5298 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5299 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5300 execve(bb_busybox_exec_path, argv, pp);
5301 /* Fallback. Useful for init=/bin/hush usage etc */
5302 if (argv[0][0] == '/')
5303 execve(argv[0], argv, pp);
5304 xfunc_error_retval = 127;
5305 bb_error_msg_and_die("can't re-execute the shell");
5307 #endif /* !BB_MMU */
5310 static int run_and_free_list(struct pipe *pi);
5312 /* Executing from string: eval, sh -c '...'
5313 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5314 * end_trigger controls how often we stop parsing
5315 * NUL: parse all, execute, return
5316 * ';': parse till ';' or newline, execute, repeat till EOF
5318 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5320 /* Why we need empty flag?
5321 * An obscure corner case "false; ``; echo $?":
5322 * empty command in `` should still set $? to 0.
5323 * But we can't just set $? to 0 at the start,
5324 * this breaks "false; echo `echo $?`" case.
5328 struct pipe *pipe_list;
5330 pipe_list = parse_stream(NULL, inp, end_trigger);
5331 if (!pipe_list) { /* EOF */
5333 G.last_exitcode = 0;
5336 debug_print_tree(pipe_list, 0);
5337 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5338 run_and_free_list(pipe_list);
5343 static void parse_and_run_string(const char *s)
5345 struct in_str input;
5346 setup_string_in_str(&input, s);
5347 parse_and_run_stream(&input, '\0');
5350 static void parse_and_run_file(FILE *f)
5352 struct in_str input;
5353 setup_file_in_str(&input, f);
5354 parse_and_run_stream(&input, ';');
5357 #if ENABLE_HUSH_TICK
5358 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5363 char **to_free = NULL;
5367 pid = BB_MMU ? xfork() : xvfork();
5368 if (pid == 0) { /* child */
5369 disable_restore_tty_pgrp_on_exit();
5370 /* Process substitution is not considered to be usual
5371 * 'command execution'.
5372 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5379 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5380 close(channel[0]); /* NB: close _first_, then move fd! */
5381 xmove_fd(channel[1], 1);
5382 /* Prevent it from trying to handle ctrl-z etc */
5383 IF_HUSH_JOB(G.run_list_level = 1;)
5384 /* Awful hack for `trap` or $(trap).
5386 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5387 * contains an example where "trap" is executed in a subshell:
5389 * save_traps=$(trap)
5391 * eval "$save_traps"
5393 * Standard does not say that "trap" in subshell shall print
5394 * parent shell's traps. It only says that its output
5395 * must have suitable form, but then, in the above example
5396 * (which is not supposed to be normative), it implies that.
5398 * bash (and probably other shell) does implement it
5399 * (traps are reset to defaults, but "trap" still shows them),
5400 * but as a result, "trap" logic is hopelessly messed up:
5403 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5404 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5405 * # true | trap <--- trap is in subshell - no output (ditto)
5406 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5407 * trap -- 'echo Ho' SIGWINCH
5408 * # echo `(trap)` <--- in subshell in subshell - output
5409 * trap -- 'echo Ho' SIGWINCH
5410 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5411 * trap -- 'echo Ho' SIGWINCH
5413 * The rules when to forget and when to not forget traps
5414 * get really complex and nonsensical.
5416 * Our solution: ONLY bare $(trap) or `trap` is special.
5418 s = skip_whitespace(s);
5419 if (strncmp(s, "trap", 4) == 0
5420 && skip_whitespace(s + 4)[0] == '\0'
5422 static const char *const argv[] = { NULL, NULL };
5423 builtin_trap((char**)argv);
5424 exit(0); /* not _exit() - we need to fflush */
5427 reset_traps_to_defaults();
5428 parse_and_run_string(s);
5429 _exit(G.last_exitcode);
5431 /* We re-execute after vfork on NOMMU. This makes this script safe:
5432 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5433 * huge=`cat BIG` # was blocking here forever
5436 re_execute_shell(&to_free,
5446 # if ENABLE_HUSH_FAST
5448 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5449 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5450 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5452 enable_restore_tty_pgrp_on_exit();
5457 close_on_exec_on(channel[0]);
5458 return xfdopen_for_read(channel[0]);
5461 /* Return code is exit status of the process that is run. */
5462 static int process_command_subs(o_string *dest, const char *s)
5465 struct in_str pipe_str;
5467 int status, ch, eol_cnt;
5469 fp = generate_stream_from_string(s, &pid);
5471 /* Now send results of command back into original context */
5472 setup_file_in_str(&pipe_str, fp);
5474 while ((ch = i_getch(&pipe_str)) != EOF) {
5480 o_addchr(dest, '\n');
5483 o_addQchr(dest, ch);
5486 debug_printf("done reading from `cmd` pipe, closing it\n");
5488 /* We need to extract exitcode. Test case
5489 * "true; echo `sleep 1; false` $?"
5491 safe_waitpid(pid, &status, 0);
5492 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5493 return WEXITSTATUS(status);
5495 #endif /* ENABLE_HUSH_TICK */
5498 static void setup_heredoc(struct redir_struct *redir)
5500 struct fd_pair pair;
5503 /* the _body_ of heredoc (misleading field name) */
5504 const char *heredoc = redir->rd_filename;
5511 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5512 expanded = expand_pseudo_dquoted(heredoc);
5516 len = strlen(heredoc);
5518 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5520 xmove_fd(pair.rd, redir->rd_fd);
5522 /* Try writing without forking. Newer kernels have
5523 * dynamically growing pipes. Must use non-blocking write! */
5526 written = write(pair.wr, heredoc, len);
5537 ndelay_off(pair.wr);
5539 /* Okay, pipe buffer was not big enough */
5540 /* Note: we must not create a stray child (bastard? :)
5541 * for the unsuspecting parent process. Child creates a grandchild
5542 * and exits before parent execs the process which consumes heredoc
5543 * (that exec happens after we return from this function) */
5550 disable_restore_tty_pgrp_on_exit();
5551 pid = BB_MMU ? xfork() : xvfork();
5555 close(redir->rd_fd); /* read side of the pipe */
5557 full_write(pair.wr, heredoc, len); /* may loop or block */
5560 /* Delegate blocking writes to another process */
5561 xmove_fd(pair.wr, STDOUT_FILENO);
5562 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5566 #if ENABLE_HUSH_FAST
5568 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5570 enable_restore_tty_pgrp_on_exit();
5576 wait(NULL); /* wait till child has died */
5579 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5580 * and stderr if they are redirected. */
5581 static int setup_redirects(struct command *prog, int squirrel[])
5584 struct redir_struct *redir;
5586 for (redir = prog->redirects; redir; redir = redir->next) {
5587 if (redir->rd_type == REDIRECT_HEREDOC2) {
5588 /* rd_fd<<HERE case */
5589 if (squirrel && redir->rd_fd < 3
5590 && squirrel[redir->rd_fd] < 0
5592 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5594 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5596 debug_printf_parse("set heredoc '%s'\n",
5597 redir->rd_filename);
5598 setup_heredoc(redir);
5602 if (redir->rd_dup == REDIRFD_TO_FILE) {
5603 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5605 if (redir->rd_filename == NULL) {
5606 /* Something went wrong in the parse.
5607 * Pretend it didn't happen */
5608 bb_error_msg("bug in redirect parse");
5611 mode = redir_table[redir->rd_type].mode;
5612 p = expand_string_to_string(redir->rd_filename);
5613 openfd = open_or_warn(p, mode);
5616 /* this could get lost if stderr has been redirected, but
5617 * bash and ash both lose it as well (though zsh doesn't!) */
5618 //what the above comment tries to say?
5622 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5623 openfd = redir->rd_dup;
5626 if (openfd != redir->rd_fd) {
5627 if (squirrel && redir->rd_fd < 3
5628 && squirrel[redir->rd_fd] < 0
5630 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5632 if (openfd == REDIRFD_CLOSE) {
5633 /* "n>-" means "close me" */
5634 close(redir->rd_fd);
5636 xdup2(openfd, redir->rd_fd);
5637 if (redir->rd_dup == REDIRFD_TO_FILE)
5645 static void restore_redirects(int squirrel[])
5648 for (i = 0; i < 3; i++) {
5651 /* We simply die on error */
5657 static char *find_in_path(const char *arg)
5660 const char *PATH = get_local_var_value("PATH");
5666 const char *end = strchrnul(PATH, ':');
5667 int sz = end - PATH; /* must be int! */
5671 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5673 /* We have xxx::yyyy in $PATH,
5674 * it means "use current dir" */
5677 if (access(ret, F_OK) == 0)
5690 static const struct built_in_command* find_builtin_helper(const char *name,
5691 const struct built_in_command *x,
5692 const struct built_in_command *end)
5695 if (strcmp(name, x->b_cmd) != 0) {
5699 debug_printf_exec("found builtin '%s'\n", name);
5704 static const struct built_in_command* find_builtin1(const char *name)
5706 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5708 static const struct built_in_command* find_builtin(const char *name)
5710 const struct built_in_command *x = find_builtin1(name);
5713 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5716 #if ENABLE_HUSH_FUNCTIONS
5717 static struct function **find_function_slot(const char *name)
5719 struct function **funcpp = &G.top_func;
5721 if (strcmp(name, (*funcpp)->name) == 0) {
5724 funcpp = &(*funcpp)->next;
5729 static const struct function *find_function(const char *name)
5731 const struct function *funcp = *find_function_slot(name);
5733 debug_printf_exec("found function '%s'\n", name);
5737 /* Note: takes ownership on name ptr */
5738 static struct function *new_function(char *name)
5740 struct function **funcpp = find_function_slot(name);
5741 struct function *funcp = *funcpp;
5743 if (funcp != NULL) {
5744 struct command *cmd = funcp->parent_cmd;
5745 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5747 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5749 /* Note: if !funcp->body, do not free body_as_string!
5750 * This is a special case of "-F name body" function:
5751 * body_as_string was not malloced! */
5753 free_pipe_list(funcp->body);
5755 free(funcp->body_as_string);
5759 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5760 cmd->argv[0] = funcp->name;
5761 cmd->group = funcp->body;
5763 cmd->group_as_string = funcp->body_as_string;
5767 debug_printf_exec("remembering new function '%s'\n", name);
5768 funcp = *funcpp = xzalloc(sizeof(*funcp));
5769 /*funcp->next = NULL;*/
5776 static void unset_func(const char *name)
5778 struct function **funcpp = find_function_slot(name);
5779 struct function *funcp = *funcpp;
5781 if (funcp != NULL) {
5782 debug_printf_exec("freeing function '%s'\n", funcp->name);
5783 *funcpp = funcp->next;
5784 /* funcp is unlinked now, deleting it.
5785 * Note: if !funcp->body, the function was created by
5786 * "-F name body", do not free ->body_as_string
5787 * and ->name as they were not malloced. */
5789 free_pipe_list(funcp->body);
5792 free(funcp->body_as_string);
5800 #define exec_function(to_free, funcp, argv) \
5801 exec_function(funcp, argv)
5803 static void exec_function(char ***to_free,
5804 const struct function *funcp,
5805 char **argv) NORETURN;
5806 static void exec_function(char ***to_free,
5807 const struct function *funcp,
5813 argv[0] = G.global_argv[0];
5814 G.global_argv = argv;
5818 /* On MMU, funcp->body is always non-NULL */
5819 n = run_list(funcp->body);
5823 re_execute_shell(to_free,
5824 funcp->body_as_string,
5831 static int run_function(const struct function *funcp, char **argv)
5837 save_and_replace_G_args(&sv, argv);
5839 /* "we are in function, ok to use return" */
5840 sv_flg = G.flag_return_in_progress;
5841 G.flag_return_in_progress = -1;
5842 # if ENABLE_HUSH_LOCAL
5843 G.func_nest_level++;
5846 /* On MMU, funcp->body is always non-NULL */
5849 /* Function defined by -F */
5850 parse_and_run_string(funcp->body_as_string);
5851 rc = G.last_exitcode;
5855 rc = run_list(funcp->body);
5858 # if ENABLE_HUSH_LOCAL
5860 struct variable *var;
5861 struct variable **var_pp;
5863 var_pp = &G.top_var;
5864 while ((var = *var_pp) != NULL) {
5865 if (var->func_nest_level < G.func_nest_level) {
5866 var_pp = &var->next;
5870 if (var->flg_export)
5871 bb_unsetenv(var->varstr);
5872 /* Remove from global list */
5873 *var_pp = var->next;
5879 G.func_nest_level--;
5882 G.flag_return_in_progress = sv_flg;
5884 restore_G_args(&sv, argv);
5888 #endif /* ENABLE_HUSH_FUNCTIONS */
5892 #define exec_builtin(to_free, x, argv) \
5893 exec_builtin(x, argv)
5895 #define exec_builtin(to_free, x, argv) \
5896 exec_builtin(to_free, argv)
5898 static void exec_builtin(char ***to_free,
5899 const struct built_in_command *x,
5900 char **argv) NORETURN;
5901 static void exec_builtin(char ***to_free,
5902 const struct built_in_command *x,
5906 int rcode = x->b_function(argv);
5910 /* On NOMMU, we must never block!
5911 * Example: { sleep 99 | read line; } & echo Ok
5913 re_execute_shell(to_free,
5922 static void execvp_or_die(char **argv) NORETURN;
5923 static void execvp_or_die(char **argv)
5925 debug_printf_exec("execing '%s'\n", argv[0]);
5926 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5927 execvp(argv[0], argv);
5928 bb_perror_msg("can't execute '%s'", argv[0]);
5929 _exit(127); /* bash compat */
5932 #if ENABLE_HUSH_MODE_X
5933 static void dump_cmd_in_x_mode(char **argv)
5935 if (G_x_mode && argv) {
5936 /* We want to output the line in one write op */
5944 len += strlen(argv[n++]) + 1;
5950 p += sprintf(p, " %s", argv[n++]);
5958 # define dump_cmd_in_x_mode(argv) ((void)0)
5962 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5963 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5964 #define pseudo_exec(nommu_save, command, argv_expanded) \
5965 pseudo_exec(command, argv_expanded)
5968 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5970 * Don't exit() here. If you don't exec, use _exit instead.
5971 * The at_exit handlers apparently confuse the calling process,
5972 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5973 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5974 char **argv, int assignment_cnt,
5975 char **argv_expanded) NORETURN;
5976 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5977 char **argv, int assignment_cnt,
5978 char **argv_expanded)
5982 new_env = expand_assignments(argv, assignment_cnt);
5983 dump_cmd_in_x_mode(new_env);
5985 if (!argv[assignment_cnt]) {
5986 /* Case when we are here: ... | var=val | ...
5987 * (note that we do not exit early, i.e., do not optimize out
5988 * expand_assignments(): think about ... | var=`sleep 1` | ...
5990 free_strings(new_env);
5991 _exit(EXIT_SUCCESS);
5995 set_vars_and_save_old(new_env);
5996 free(new_env); /* optional */
5997 /* we can also destroy set_vars_and_save_old's return value,
6000 nommu_save->new_env = new_env;
6001 nommu_save->old_vars = set_vars_and_save_old(new_env);
6004 if (argv_expanded) {
6005 argv = argv_expanded;
6007 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6009 nommu_save->argv = argv;
6012 dump_cmd_in_x_mode(argv);
6014 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6015 if (strchr(argv[0], '/') != NULL)
6019 /* Check if the command matches any of the builtins.
6020 * Depending on context, this might be redundant. But it's
6021 * easier to waste a few CPU cycles than it is to figure out
6022 * if this is one of those cases.
6025 /* On NOMMU, it is more expensive to re-execute shell
6026 * just in order to run echo or test builtin.
6027 * It's better to skip it here and run corresponding
6028 * non-builtin later. */
6029 const struct built_in_command *x;
6030 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6032 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6035 #if ENABLE_HUSH_FUNCTIONS
6036 /* Check if the command matches any functions */
6038 const struct function *funcp = find_function(argv[0]);
6040 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6045 #if ENABLE_FEATURE_SH_STANDALONE
6046 /* Check if the command matches any busybox applets */
6048 int a = find_applet_by_name(argv[0]);
6050 # if BB_MMU /* see above why on NOMMU it is not allowed */
6051 if (APPLET_IS_NOEXEC(a)) {
6052 debug_printf_exec("running applet '%s'\n", argv[0]);
6053 run_applet_no_and_exit(a, argv);
6056 /* Re-exec ourselves */
6057 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6058 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6059 execv(bb_busybox_exec_path, argv);
6060 /* If they called chroot or otherwise made the binary no longer
6061 * executable, fall through */
6066 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6069 execvp_or_die(argv);
6072 /* Called after [v]fork() in run_pipe
6074 static void pseudo_exec(nommu_save_t *nommu_save,
6075 struct command *command,
6076 char **argv_expanded) NORETURN;
6077 static void pseudo_exec(nommu_save_t *nommu_save,
6078 struct command *command,
6079 char **argv_expanded)
6081 if (command->argv) {
6082 pseudo_exec_argv(nommu_save, command->argv,
6083 command->assignment_cnt, argv_expanded);
6086 if (command->group) {
6087 /* Cases when we are here:
6090 * ... | ( list ) | ...
6091 * ... | { list } | ...
6095 debug_printf_exec("pseudo_exec: run_list\n");
6096 reset_traps_to_defaults();
6097 rcode = run_list(command->group);
6098 /* OK to leak memory by not calling free_pipe_list,
6099 * since this process is about to exit */
6102 re_execute_shell(&nommu_save->argv_from_re_execing,
6103 command->group_as_string,
6110 /* Case when we are here: ... | >file */
6111 debug_printf_exec("pseudo_exec'ed null command\n");
6112 _exit(EXIT_SUCCESS);
6116 static const char *get_cmdtext(struct pipe *pi)
6122 /* This is subtle. ->cmdtext is created only on first backgrounding.
6123 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6124 * On subsequent bg argv is trashed, but we won't use it */
6127 argv = pi->cmds[0].argv;
6128 if (!argv || !argv[0]) {
6129 pi->cmdtext = xzalloc(1);
6135 len += strlen(*argv) + 1;
6139 argv = pi->cmds[0].argv;
6141 len = strlen(*argv);
6142 memcpy(p, *argv, len);
6150 static void insert_bg_job(struct pipe *pi)
6152 struct pipe *job, **jobp;
6155 /* Linear search for the ID of the job to use */
6157 for (job = G.job_list; job; job = job->next)
6158 if (job->jobid >= pi->jobid)
6159 pi->jobid = job->jobid + 1;
6161 /* Add job to the list of running jobs */
6163 while ((job = *jobp) != NULL)
6165 job = *jobp = xmalloc(sizeof(*job));
6167 *job = *pi; /* physical copy */
6169 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6170 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6171 for (i = 0; i < pi->num_cmds; i++) {
6172 job->cmds[i].pid = pi->cmds[i].pid;
6173 /* all other fields are not used and stay zero */
6175 job->cmdtext = xstrdup(get_cmdtext(pi));
6177 if (G_interactive_fd)
6178 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6179 G.last_jobid = job->jobid;
6182 static void remove_bg_job(struct pipe *pi)
6184 struct pipe *prev_pipe;
6186 if (pi == G.job_list) {
6187 G.job_list = pi->next;
6189 prev_pipe = G.job_list;
6190 while (prev_pipe->next != pi)
6191 prev_pipe = prev_pipe->next;
6192 prev_pipe->next = pi->next;
6195 G.last_jobid = G.job_list->jobid;
6200 /* Remove a backgrounded job */
6201 static void delete_finished_bg_job(struct pipe *pi)
6204 pi->stopped_cmds = 0;
6210 /* Check to see if any processes have exited -- if they
6211 * have, figure out why and see if a job has completed */
6212 static int checkjobs(struct pipe* fg_pipe)
6222 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6224 attributes = WUNTRACED;
6225 if (fg_pipe == NULL)
6226 attributes |= WNOHANG;
6229 #if ENABLE_HUSH_FAST
6230 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6231 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6232 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6233 /* There was neither fork nor SIGCHLD since last waitpid */
6234 /* Avoid doing waitpid syscall if possible */
6235 if (!G.we_have_children) {
6239 if (fg_pipe == NULL) { /* is WNOHANG set? */
6240 /* We have children, but they did not exit
6241 * or stop yet (we saw no SIGCHLD) */
6244 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6248 /* Do we do this right?
6249 * bash-3.00# sleep 20 | false
6251 * [3]+ Stopped sleep 20 | false
6252 * bash-3.00# echo $?
6253 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6254 * [hush 1.14.0: yes we do it right]
6261 #if ENABLE_HUSH_FAST
6262 i = G.count_SIGCHLD;
6264 childpid = waitpid(-1, &status, attributes);
6265 if (childpid <= 0) {
6266 if (childpid && errno != ECHILD)
6267 bb_perror_msg("waitpid");
6268 #if ENABLE_HUSH_FAST
6269 else { /* Until next SIGCHLD, waitpid's are useless */
6270 G.we_have_children = (childpid == 0);
6271 G.handled_SIGCHLD = i;
6272 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6277 dead = WIFEXITED(status) || WIFSIGNALED(status);
6280 if (WIFSTOPPED(status))
6281 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6282 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6283 if (WIFSIGNALED(status))
6284 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6285 childpid, WTERMSIG(status), WEXITSTATUS(status));
6286 if (WIFEXITED(status))
6287 debug_printf_jobs("pid %d exited, exitcode %d\n",
6288 childpid, WEXITSTATUS(status));
6290 /* Were we asked to wait for fg pipe? */
6292 for (i = 0; i < fg_pipe->num_cmds; i++) {
6293 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6294 if (fg_pipe->cmds[i].pid != childpid)
6297 fg_pipe->cmds[i].pid = 0;
6298 fg_pipe->alive_cmds--;
6299 if (i == fg_pipe->num_cmds - 1) {
6300 /* last process gives overall exitstatus */
6301 rcode = WEXITSTATUS(status);
6302 /* bash prints killer signal's name for *last*
6303 * process in pipe (prints just newline for SIGINT).
6304 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6306 if (WIFSIGNALED(status)) {
6307 int sig = WTERMSIG(status);
6308 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6309 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6310 * Maybe we need to use sig | 128? */
6313 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6316 fg_pipe->cmds[i].is_stopped = 1;
6317 fg_pipe->stopped_cmds++;
6319 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6320 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6321 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6322 /* All processes in fg pipe have exited or stopped */
6323 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6324 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6325 * and "killall -STOP cat" */
6326 if (G_interactive_fd) {
6328 if (fg_pipe->alive_cmds)
6329 insert_bg_job(fg_pipe);
6333 if (!fg_pipe->alive_cmds)
6336 /* There are still running processes in the fg pipe */
6337 goto wait_more; /* do waitpid again */
6339 /* it wasnt fg_pipe, look for process in bg pipes */
6343 /* We asked to wait for bg or orphaned children */
6344 /* No need to remember exitcode in this case */
6345 for (pi = G.job_list; pi; pi = pi->next) {
6346 for (i = 0; i < pi->num_cmds; i++) {
6347 if (pi->cmds[i].pid == childpid)
6348 goto found_pi_and_prognum;
6351 /* Happens when shell is used as init process (init=/bin/sh) */
6352 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6353 continue; /* do waitpid again */
6355 found_pi_and_prognum:
6358 pi->cmds[i].pid = 0;
6360 if (!pi->alive_cmds) {
6361 if (G_interactive_fd)
6362 printf(JOB_STATUS_FORMAT, pi->jobid,
6363 "Done", pi->cmdtext);
6364 delete_finished_bg_job(pi);
6368 pi->cmds[i].is_stopped = 1;
6372 } /* while (waitpid succeeds)... */
6378 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
6381 int rcode = checkjobs(fg_pipe);
6382 if (G_saved_tty_pgrp) {
6383 /* Job finished, move the shell to the foreground */
6384 p = getpgrp(); /* our process group id */
6385 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6386 tcsetpgrp(G_interactive_fd, p);
6392 /* Start all the jobs, but don't wait for anything to finish.
6395 * Return code is normally -1, when the caller has to wait for children
6396 * to finish to determine the exit status of the pipe. If the pipe
6397 * is a simple builtin command, however, the action is done by the
6398 * time run_pipe returns, and the exit code is provided as the
6401 * Returns -1 only if started some children. IOW: we have to
6402 * mask out retvals of builtins etc with 0xff!
6404 * The only case when we do not need to [v]fork is when the pipe
6405 * is single, non-backgrounded, non-subshell command. Examples:
6406 * cmd ; ... { list } ; ...
6407 * cmd && ... { list } && ...
6408 * cmd || ... { list } || ...
6409 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6410 * or (if SH_STANDALONE) an applet, and we can run the { list }
6411 * with run_list. If it isn't one of these, we fork and exec cmd.
6413 * Cases when we must fork:
6414 * non-single: cmd | cmd
6415 * backgrounded: cmd & { list } &
6416 * subshell: ( list ) [&]
6418 #if !ENABLE_HUSH_MODE_X
6419 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6420 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6422 static int redirect_and_varexp_helper(char ***new_env_p,
6423 struct variable **old_vars_p,
6424 struct command *command,
6426 char **argv_expanded)
6428 /* setup_redirects acts on file descriptors, not FILEs.
6429 * This is perfect for work that comes after exec().
6430 * Is it really safe for inline use? Experimentally,
6431 * things seem to work. */
6432 int rcode = setup_redirects(command, squirrel);
6434 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6435 *new_env_p = new_env;
6436 dump_cmd_in_x_mode(new_env);
6437 dump_cmd_in_x_mode(argv_expanded);
6439 *old_vars_p = set_vars_and_save_old(new_env);
6443 static NOINLINE int run_pipe(struct pipe *pi)
6445 static const char *const null_ptr = NULL;
6449 struct command *command;
6450 char **argv_expanded;
6452 /* it is not always needed, but we aim to smaller code */
6453 int squirrel[] = { -1, -1, -1 };
6456 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6459 IF_HUSH_JOB(pi->pgrp = -1;)
6460 pi->stopped_cmds = 0;
6461 command = &pi->cmds[0];
6462 argv_expanded = NULL;
6464 if (pi->num_cmds != 1
6465 || pi->followup == PIPE_BG
6466 || command->cmd_type == CMD_SUBSHELL
6473 debug_printf_exec(": group:%p argv:'%s'\n",
6474 command->group, command->argv ? command->argv[0] : "NONE");
6476 if (command->group) {
6477 #if ENABLE_HUSH_FUNCTIONS
6478 if (command->cmd_type == CMD_FUNCDEF) {
6479 /* "executing" func () { list } */
6480 struct function *funcp;
6482 funcp = new_function(command->argv[0]);
6483 /* funcp->name is already set to argv[0] */
6484 funcp->body = command->group;
6486 funcp->body_as_string = command->group_as_string;
6487 command->group_as_string = NULL;
6489 command->group = NULL;
6490 command->argv[0] = NULL;
6491 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6492 funcp->parent_cmd = command;
6493 command->child_func = funcp;
6495 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6497 return EXIT_SUCCESS;
6501 debug_printf("non-subshell group\n");
6502 rcode = 1; /* exitcode if redir failed */
6503 if (setup_redirects(command, squirrel) == 0) {
6504 debug_printf_exec(": run_list\n");
6505 rcode = run_list(command->group) & 0xff;
6507 restore_redirects(squirrel);
6508 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6510 debug_printf_exec("run_pipe: return %d\n", rcode);
6514 argv = command->argv ? command->argv : (char **) &null_ptr;
6516 const struct built_in_command *x;
6517 #if ENABLE_HUSH_FUNCTIONS
6518 const struct function *funcp;
6522 char **new_env = NULL;
6523 struct variable *old_vars = NULL;
6525 if (argv[command->assignment_cnt] == NULL) {
6526 /* Assignments, but no command */
6527 /* Ensure redirects take effect (that is, create files).
6528 * Try "a=t >file" */
6529 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6530 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6531 /* Set shell variables */
6535 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6536 /* Do we need to flag set_local_var() errors?
6537 * "assignment to readonly var" and "putenv error"
6542 /* Redirect error sets $? to 1. Otherwise,
6543 * if evaluating assignment value set $?, retain it.
6544 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6546 rcode = G.last_exitcode;
6547 /* Exit, _skipping_ variable restoring code: */
6548 goto clean_up_and_ret0;
6550 #else /* Older, bigger, but more correct code */
6552 rcode = setup_redirects(command, squirrel);
6553 restore_redirects(squirrel);
6554 /* Set shell variables */
6556 bb_putchar_stderr('+');
6558 char *p = expand_string_to_string(*argv);
6560 fprintf(stderr, " %s", p);
6561 debug_printf_exec("set shell var:'%s'->'%s'\n",
6563 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6564 /* Do we need to flag set_local_var() errors?
6565 * "assignment to readonly var" and "putenv error"
6570 bb_putchar_stderr('\n');
6571 /* Redirect error sets $? to 1. Otherwise,
6572 * if evaluating assignment value set $?, retain it.
6573 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6575 rcode = G.last_exitcode;
6576 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6578 debug_printf_exec("run_pipe: return %d\n", rcode);
6583 /* Expand the rest into (possibly) many strings each */
6585 #if ENABLE_HUSH_BASH_COMPAT
6586 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6587 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6590 #ifdef CMD_SINGLEWORD_NOGLOB_COND
6591 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
6592 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
6596 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6599 /* if someone gives us an empty string: `cmd with empty output` */
6600 if (!argv_expanded[0]) {
6601 free(argv_expanded);
6603 return G.last_exitcode;
6606 x = find_builtin(argv_expanded[0]);
6607 #if ENABLE_HUSH_FUNCTIONS
6610 funcp = find_function(argv_expanded[0]);
6614 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6615 debug_printf("exec with redirects only\n");
6616 rcode = setup_redirects(command, NULL);
6617 goto clean_up_and_ret1;
6620 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6623 debug_printf_exec(": builtin '%s' '%s'...\n",
6624 x->b_cmd, argv_expanded[1]);
6625 rcode = x->b_function(argv_expanded) & 0xff;
6628 #if ENABLE_HUSH_FUNCTIONS
6630 # if ENABLE_HUSH_LOCAL
6631 struct variable **sv;
6632 sv = G.shadowed_vars_pp;
6633 G.shadowed_vars_pp = &old_vars;
6635 debug_printf_exec(": function '%s' '%s'...\n",
6636 funcp->name, argv_expanded[1]);
6637 rcode = run_function(funcp, argv_expanded) & 0xff;
6638 # if ENABLE_HUSH_LOCAL
6639 G.shadowed_vars_pp = sv;
6645 unset_vars(new_env);
6647 /* clean_up_and_ret0: */
6648 restore_redirects(squirrel);
6650 free(argv_expanded);
6651 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6653 debug_printf_exec("run_pipe return %d\n", rcode);
6657 if (ENABLE_FEATURE_SH_STANDALONE) {
6658 int n = find_applet_by_name(argv_expanded[0]);
6659 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6660 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6662 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6663 argv_expanded[0], argv_expanded[1]);
6664 rcode = run_nofork_applet(n, argv_expanded);
6666 goto clean_up_and_ret;
6669 /* It is neither builtin nor applet. We must fork. */
6673 /* NB: argv_expanded may already be created, and that
6674 * might include `cmd` runs! Do not rerun it! We *must*
6675 * use argv_expanded if it's non-NULL */
6677 /* Going to fork a child per each pipe member */
6682 while (cmd_no < pi->num_cmds) {
6683 struct fd_pair pipefds;
6685 volatile nommu_save_t nommu_save;
6686 nommu_save.new_env = NULL;
6687 nommu_save.old_vars = NULL;
6688 nommu_save.argv = NULL;
6689 nommu_save.argv_from_re_execing = NULL;
6691 command = &pi->cmds[cmd_no];
6693 if (command->argv) {
6694 debug_printf_exec(": pipe member '%s' '%s'...\n",
6695 command->argv[0], command->argv[1]);
6697 debug_printf_exec(": pipe member with no argv\n");
6700 /* pipes are inserted between pairs of commands */
6703 if (cmd_no < pi->num_cmds)
6704 xpiped_pair(pipefds);
6706 command->pid = BB_MMU ? fork() : vfork();
6707 if (!command->pid) { /* child */
6709 disable_restore_tty_pgrp_on_exit();
6710 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6712 /* Every child adds itself to new process group
6713 * with pgid == pid_of_first_child_in_pipe */
6714 if (G.run_list_level == 1 && G_interactive_fd) {
6717 if (pgrp < 0) /* true for 1st process only */
6719 if (setpgid(0, pgrp) == 0
6720 && pi->followup != PIPE_BG
6721 && G_saved_tty_pgrp /* we have ctty */
6723 /* We do it in *every* child, not just first,
6725 tcsetpgrp(G_interactive_fd, pgrp);
6729 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6730 /* 1st cmd in backgrounded pipe
6731 * should have its stdin /dev/null'ed */
6733 if (open(bb_dev_null, O_RDONLY))
6734 xopen("/", O_RDONLY);
6736 xmove_fd(next_infd, 0);
6738 xmove_fd(pipefds.wr, 1);
6741 /* Like bash, explicit redirects override pipes,
6742 * and the pipe fd is available for dup'ing. */
6743 if (setup_redirects(command, NULL))
6746 /* Restore default handlers just prior to exec */
6747 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6749 /* Stores to nommu_save list of env vars putenv'ed
6750 * (NOMMU, on MMU we don't need that) */
6751 /* cast away volatility... */
6752 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6753 /* pseudo_exec() does not return */
6756 /* parent or error */
6757 #if ENABLE_HUSH_FAST
6759 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6761 enable_restore_tty_pgrp_on_exit();
6763 /* Clean up after vforked child */
6764 free(nommu_save.argv);
6765 free(nommu_save.argv_from_re_execing);
6766 unset_vars(nommu_save.new_env);
6767 add_vars(nommu_save.old_vars);
6769 free(argv_expanded);
6770 argv_expanded = NULL;
6771 if (command->pid < 0) { /* [v]fork failed */
6772 /* Clearly indicate, was it fork or vfork */
6773 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6777 /* Second and next children need to know pid of first one */
6779 pi->pgrp = command->pid;
6785 if (cmd_no < pi->num_cmds)
6787 /* Pass read (output) pipe end to next iteration */
6788 next_infd = pipefds.rd;
6791 if (!pi->alive_cmds) {
6793 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6798 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6802 #ifndef debug_print_tree
6803 static void debug_print_tree(struct pipe *pi, int lvl)
6805 static const char *const PIPE[] = {
6811 static const char *RES[] = {
6812 [RES_NONE ] = "NONE" ,
6815 [RES_THEN ] = "THEN" ,
6816 [RES_ELIF ] = "ELIF" ,
6817 [RES_ELSE ] = "ELSE" ,
6820 # if ENABLE_HUSH_LOOPS
6821 [RES_FOR ] = "FOR" ,
6822 [RES_WHILE] = "WHILE",
6823 [RES_UNTIL] = "UNTIL",
6825 [RES_DONE ] = "DONE" ,
6827 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6830 # if ENABLE_HUSH_CASE
6831 [RES_CASE ] = "CASE" ,
6832 [RES_CASE_IN ] = "CASE_IN" ,
6833 [RES_MATCH] = "MATCH",
6834 [RES_CASE_BODY] = "CASE_BODY",
6835 [RES_ESAC ] = "ESAC" ,
6837 [RES_XXXX ] = "XXXX" ,
6838 [RES_SNTX ] = "SNTX" ,
6840 static const char *const CMDTYPE[] = {
6844 # if ENABLE_HUSH_FUNCTIONS
6853 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6854 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6856 while (prn < pi->num_cmds) {
6857 struct command *command = &pi->cmds[prn];
6858 char **argv = command->argv;
6860 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6862 command->assignment_cnt);
6863 if (command->group) {
6864 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6865 CMDTYPE[command->cmd_type],
6868 , " group_as_string:", command->group_as_string
6873 debug_print_tree(command->group, lvl+1);
6877 if (argv) while (*argv) {
6878 fprintf(stderr, " '%s'", *argv);
6881 fprintf(stderr, "\n");
6888 #endif /* debug_print_tree */
6890 /* NB: called by pseudo_exec, and therefore must not modify any
6891 * global data until exec/_exit (we can be a child after vfork!) */
6892 static int run_list(struct pipe *pi)
6894 #if ENABLE_HUSH_CASE
6895 char *case_word = NULL;
6897 #if ENABLE_HUSH_LOOPS
6898 struct pipe *loop_top = NULL;
6899 char **for_lcur = NULL;
6900 char **for_list = NULL;
6902 smallint last_followup;
6904 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6905 smalluint cond_code = 0;
6907 enum { cond_code = 0 };
6910 smallint rword; /* enum reserved_style */
6911 smallint last_rword; /* ditto */
6914 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6917 #if ENABLE_HUSH_LOOPS
6918 /* Check syntax for "for" */
6919 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6920 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6922 /* current word is FOR or IN (BOLD in comments below) */
6923 if (cpipe->next == NULL) {
6924 syntax_error("malformed for");
6926 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6929 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6930 if (cpipe->next->res_word == RES_DO)
6932 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6933 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6934 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6936 syntax_error("malformed for");
6938 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6944 /* Past this point, all code paths should jump to ret: label
6945 * in order to return, no direct "return" statements please.
6946 * This helps to ensure that no memory is leaked. */
6954 last_rword = RES_XXXX;
6956 last_followup = PIPE_SEQ;
6957 rcode = G.last_exitcode;
6959 /* Go through list of pipes, (maybe) executing them. */
6960 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6964 IF_HAS_KEYWORDS(rword = pi->res_word;)
6965 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6966 rword, cond_code, last_rword);
6967 #if ENABLE_HUSH_LOOPS
6968 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6969 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6971 /* start of a loop: remember where loop starts */
6976 /* Still in the same "if...", "then..." or "do..." branch? */
6977 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6978 if ((rcode == 0 && last_followup == PIPE_OR)
6979 || (rcode != 0 && last_followup == PIPE_AND)
6981 /* It is "<true> || CMD" or "<false> && CMD"
6982 * and we should not execute CMD */
6983 debug_printf_exec("skipped cmd because of || or &&\n");
6984 last_followup = pi->followup;
6988 last_followup = pi->followup;
6989 IF_HAS_KEYWORDS(last_rword = rword;)
6992 if (rword == RES_THEN) {
6993 /* if false; then ... fi has exitcode 0! */
6994 G.last_exitcode = rcode = EXIT_SUCCESS;
6995 /* "if <false> THEN cmd": skip cmd */
6999 if (rword == RES_ELSE || rword == RES_ELIF) {
7000 /* "if <true> then ... ELSE/ELIF cmd":
7001 * skip cmd and all following ones */
7006 #if ENABLE_HUSH_LOOPS
7007 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7009 /* first loop through for */
7011 static const char encoded_dollar_at[] ALIGN1 = {
7012 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7013 }; /* encoded representation of "$@" */
7014 static const char *const encoded_dollar_at_argv[] = {
7015 encoded_dollar_at, NULL
7016 }; /* argv list with one element: "$@" */
7019 vals = (char**)encoded_dollar_at_argv;
7020 if (pi->next->res_word == RES_IN) {
7021 /* if no variable values after "in" we skip "for" */
7022 if (!pi->next->cmds[0].argv) {
7023 G.last_exitcode = rcode = EXIT_SUCCESS;
7024 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7027 vals = pi->next->cmds[0].argv;
7028 } /* else: "for var; do..." -> assume "$@" list */
7029 /* create list of variable values */
7030 debug_print_strings("for_list made from", vals);
7031 for_list = expand_strvec_to_strvec(vals);
7032 for_lcur = for_list;
7033 debug_print_strings("for_list", for_list);
7036 /* "for" loop is over, clean up */
7042 /* Insert next value from for_lcur */
7043 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7044 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7047 if (rword == RES_IN) {
7048 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7050 if (rword == RES_DONE) {
7051 continue; /* "done" has no cmds too */
7054 #if ENABLE_HUSH_CASE
7055 if (rword == RES_CASE) {
7056 case_word = expand_strvec_to_string(pi->cmds->argv);
7059 if (rword == RES_MATCH) {
7062 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7064 /* all prev words didn't match, does this one match? */
7065 argv = pi->cmds->argv;
7067 char *pattern = expand_string_to_string(*argv);
7068 /* TODO: which FNM_xxx flags to use? */
7069 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7071 if (cond_code == 0) { /* match! we will execute this branch */
7072 free(case_word); /* make future "word)" stop */
7080 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7082 continue; /* not matched yet, skip this pipe */
7085 /* Just pressing <enter> in shell should check for jobs.
7086 * OTOH, in non-interactive shell this is useless
7087 * and only leads to extra job checks */
7088 if (pi->num_cmds == 0) {
7089 if (G_interactive_fd)
7090 goto check_jobs_and_continue;
7094 /* After analyzing all keywords and conditions, we decided
7095 * to execute this pipe. NB: have to do checkjobs(NULL)
7096 * after run_pipe to collect any background children,
7097 * even if list execution is to be stopped. */
7098 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7101 #if ENABLE_HUSH_LOOPS
7102 G.flag_break_continue = 0;
7104 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7106 /* We ran a builtin, function, or group.
7107 * rcode is already known
7108 * and we don't need to wait for anything. */
7109 G.last_exitcode = rcode;
7110 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7111 check_and_run_traps(0);
7112 #if ENABLE_HUSH_LOOPS
7113 /* Was it "break" or "continue"? */
7114 if (G.flag_break_continue) {
7115 smallint fbc = G.flag_break_continue;
7116 /* We might fall into outer *loop*,
7117 * don't want to break it too */
7119 G.depth_break_continue--;
7120 if (G.depth_break_continue == 0)
7121 G.flag_break_continue = 0;
7122 /* else: e.g. "continue 2" should *break* once, *then* continue */
7123 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7124 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7125 goto check_jobs_and_break;
7126 /* "continue": simulate end of loop */
7131 #if ENABLE_HUSH_FUNCTIONS
7132 if (G.flag_return_in_progress == 1) {
7133 /* same as "goto check_jobs_and_break" */
7138 } else if (pi->followup == PIPE_BG) {
7139 /* What does bash do with attempts to background builtins? */
7140 /* even bash 3.2 doesn't do that well with nested bg:
7141 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7142 * I'm NOT treating inner &'s as jobs */
7143 check_and_run_traps(0);
7145 if (G.run_list_level == 1)
7148 /* Last command's pid goes to $! */
7149 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7150 G.last_exitcode = rcode = EXIT_SUCCESS;
7151 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7154 if (G.run_list_level == 1 && G_interactive_fd) {
7155 /* Waits for completion, then fg's main shell */
7156 rcode = checkjobs_and_fg_shell(pi);
7157 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7158 check_and_run_traps(0);
7161 { /* This one just waits for completion */
7162 rcode = checkjobs(pi);
7163 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7164 check_and_run_traps(0);
7166 G.last_exitcode = rcode;
7170 /* Analyze how result affects subsequent commands */
7172 if (rword == RES_IF || rword == RES_ELIF)
7175 #if ENABLE_HUSH_LOOPS
7176 /* Beware of "while false; true; do ..."! */
7177 if (pi->next && pi->next->res_word == RES_DO) {
7178 if (rword == RES_WHILE) {
7180 /* "while false; do...done" - exitcode 0 */
7181 G.last_exitcode = rcode = EXIT_SUCCESS;
7182 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7183 goto check_jobs_and_break;
7186 if (rword == RES_UNTIL) {
7188 debug_printf_exec(": until expr is true: breaking\n");
7189 check_jobs_and_break:
7197 check_jobs_and_continue:
7204 #if ENABLE_HUSH_LOOPS
7209 #if ENABLE_HUSH_CASE
7213 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7217 /* Select which version we will use */
7218 static int run_and_free_list(struct pipe *pi)
7221 debug_printf_exec("run_and_free_list entered\n");
7223 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7224 rcode = run_list(pi);
7226 /* free_pipe_list has the side effect of clearing memory.
7227 * In the long run that function can be merged with run_list,
7228 * but doing that now would hobble the debugging effort. */
7230 debug_printf_exec("run_and_free_list return %d\n", rcode);
7235 /* Called a few times only (or even once if "sh -c") */
7236 static void init_sigmasks(void)
7240 sigset_t old_blocked_set;
7242 if (!G.inherited_set_is_saved) {
7243 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7244 G.inherited_set = G.blocked_set;
7246 old_blocked_set = G.blocked_set;
7248 mask = (1 << SIGQUIT);
7249 if (G_interactive_fd) {
7250 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7251 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7252 mask |= SPECIAL_JOB_SIGS;
7254 G.non_DFL_mask = mask;
7259 sigaddset(&G.blocked_set, sig);
7263 sigdelset(&G.blocked_set, SIGCHLD);
7265 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7266 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7268 /* POSIX allows shell to re-enable SIGCHLD
7269 * even if it was SIG_IGN on entry */
7270 #if ENABLE_HUSH_FAST
7271 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7272 if (!G.inherited_set_is_saved)
7273 signal(SIGCHLD, SIGCHLD_handler);
7275 if (!G.inherited_set_is_saved)
7276 signal(SIGCHLD, SIG_DFL);
7279 G.inherited_set_is_saved = 1;
7284 static void maybe_set_to_sigexit(int sig)
7286 void (*handler)(int);
7287 /* non_DFL_mask'ed signals are, well, masked,
7288 * no need to set handler for them.
7290 if (!((G.non_DFL_mask >> sig) & 1)) {
7291 handler = signal(sig, sigexit);
7292 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7293 signal(sig, handler);
7296 /* Set handlers to restore tty pgrp and exit */
7297 static void set_fatal_handlers(void)
7299 /* We _must_ restore tty pgrp on fatal signals */
7301 maybe_set_to_sigexit(SIGILL );
7302 maybe_set_to_sigexit(SIGFPE );
7303 maybe_set_to_sigexit(SIGBUS );
7304 maybe_set_to_sigexit(SIGSEGV);
7305 maybe_set_to_sigexit(SIGTRAP);
7306 } /* else: hush is perfect. what SEGV? */
7307 maybe_set_to_sigexit(SIGABRT);
7308 /* bash 3.2 seems to handle these just like 'fatal' ones */
7309 maybe_set_to_sigexit(SIGPIPE);
7310 maybe_set_to_sigexit(SIGALRM);
7311 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7312 * if we aren't interactive... but in this case
7313 * we never want to restore pgrp on exit, and this fn is not called */
7314 /*maybe_set_to_sigexit(SIGHUP );*/
7315 /*maybe_set_to_sigexit(SIGTERM);*/
7316 /*maybe_set_to_sigexit(SIGINT );*/
7320 static int set_mode(const char cstate, const char mode)
7322 int state = (cstate == '-' ? 1 : 0);
7324 case 'n': G.n_mode = state; break;
7325 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7326 default: return EXIT_FAILURE;
7328 return EXIT_SUCCESS;
7331 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7332 int hush_main(int argc, char **argv)
7335 unsigned builtin_argc;
7337 struct variable *cur_var;
7340 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7341 G.last_exitcode = EXIT_SUCCESS;
7343 G.argv0_for_re_execing = argv[0];
7345 /* Deal with HUSH_VERSION */
7346 G.shell_ver.flg_export = 1;
7347 G.shell_ver.flg_read_only = 1;
7348 /* Code which handles ${var/P/R} needs writable values for all variables,
7349 * therefore we xstrdup: */
7350 G.shell_ver.varstr = xstrdup(hush_version_str),
7351 G.top_var = &G.shell_ver;
7352 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7353 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7354 /* reinstate HUSH_VERSION in environment */
7355 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7356 putenv(G.shell_ver.varstr);
7358 /* Initialize our shell local variables with the values
7359 * currently living in the environment */
7360 cur_var = G.top_var;
7363 char *value = strchr(*e, '=');
7364 if (value) { /* paranoia */
7365 cur_var->next = xzalloc(sizeof(*cur_var));
7366 cur_var = cur_var->next;
7367 cur_var->varstr = *e;
7368 cur_var->max_len = strlen(*e);
7369 cur_var->flg_export = 1;
7375 set_pwd_var(/*exp:*/ 1);
7376 /* bash also exports SHLVL and _,
7377 * and sets (but doesn't export) the following variables:
7379 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7380 * BASH_VERSION='3.2.0(1)-release'
7382 * MACHTYPE=i386-pc-linux-gnu
7384 * HOSTNAME=<xxxxxxxxxx>
7385 * PPID=<NNNNN> - we also do it elsewhere
7396 * PIPESTATUS=([0]="0")
7397 * HISTFILE=/<xxx>/.bash_history
7401 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7403 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7413 #if ENABLE_FEATURE_EDITING
7414 G.line_input_state = new_line_input_t(FOR_SHELL);
7416 G.global_argc = argc;
7417 G.global_argv = argv;
7418 /* Initialize some more globals to non-zero values */
7419 cmdedit_update_prompt();
7421 if (setjmp(die_jmp)) {
7422 /* xfunc has failed! die die die */
7423 /* no EXIT traps, this is an escape hatch! */
7425 hush_exit(xfunc_error_retval);
7428 /* Shell is non-interactive at first. We need to call
7429 * init_sigmasks() if we are going to execute "sh <script>",
7430 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7431 * If we later decide that we are interactive, we run init_sigmasks()
7432 * in order to intercept (more) signals.
7436 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7439 opt = getopt(argc, argv, "+c:xins"
7442 # if ENABLE_HUSH_FUNCTIONS
7452 * sh ... -c 'script'
7453 * sh ... -c 'script' ARG0 [ARG1...]
7454 * On NOMMU, if builtin_argc != 0,
7455 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7456 * "" needs to be replaced with NULL
7457 * and BARGV vector fed to builtin function.
7458 * Note: the form without ARG0 never happens:
7459 * sh ... -c 'builtin' BARGV... ""
7462 G.root_pid = getpid();
7463 G.root_ppid = getppid();
7465 G.global_argv = argv + optind;
7466 G.global_argc = argc - optind;
7468 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7469 const struct built_in_command *x;
7472 x = find_builtin(optarg);
7473 if (x) { /* paranoia */
7474 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7475 G.global_argv += builtin_argc;
7476 G.global_argv[-1] = NULL; /* replace "" */
7477 G.last_exitcode = x->b_function(argv + optind - 1);
7481 if (!G.global_argv[0]) {
7482 /* -c 'script' (no params): prevent empty $0 */
7483 G.global_argv--; /* points to argv[i] of 'script' */
7484 G.global_argv[0] = argv[0];
7486 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7488 parse_and_run_string(optarg);
7491 /* Well, we cannot just declare interactiveness,
7492 * we have to have some stuff (ctty, etc) */
7493 /* G_interactive_fd++; */
7496 /* "-s" means "read from stdin", but this is how we always
7497 * operate, so simply do nothing here. */
7500 case '<': /* "big heredoc" support */
7501 full_write1_str(optarg);
7504 unsigned long long empty_trap_mask;
7506 G.root_pid = bb_strtou(optarg, &optarg, 16);
7508 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7510 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7512 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7514 builtin_argc = bb_strtou(optarg, &optarg, 16);
7516 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7517 if (empty_trap_mask != 0) {
7520 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7521 for (sig = 1; sig < NSIG; sig++) {
7522 if (empty_trap_mask & (1LL << sig)) {
7523 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7524 sigaddset(&G.blocked_set, sig);
7527 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7529 # if ENABLE_HUSH_LOOPS
7531 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7537 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7539 # if ENABLE_HUSH_FUNCTIONS
7541 struct function *funcp = new_function(optarg);
7542 /* funcp->name is already set to optarg */
7543 /* funcp->body is set to NULL. It's a special case. */
7544 funcp->body_as_string = argv[optind];
7552 if (set_mode('-', opt) == 0) /* no error */
7556 fprintf(stderr, "Usage: sh [FILE]...\n"
7557 " or: sh -c command [args]...\n\n");
7563 } /* option parsing loop */
7566 G.root_pid = getpid();
7567 G.root_ppid = getppid();
7570 /* If we are login shell... */
7571 if (argv[0] && argv[0][0] == '-') {
7573 debug_printf("sourcing /etc/profile\n");
7574 input = fopen_for_read("/etc/profile");
7575 if (input != NULL) {
7576 close_on_exec_on(fileno(input));
7578 parse_and_run_file(input);
7581 /* bash: after sourcing /etc/profile,
7582 * tries to source (in the given order):
7583 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7584 * stopping on first found. --noprofile turns this off.
7585 * bash also sources ~/.bash_logout on exit.
7586 * If called as sh, skips .bash_XXX files.
7593 * "bash <script>" (which is never interactive (unless -i?))
7594 * sources $BASH_ENV here (without scanning $PATH).
7595 * If called as sh, does the same but with $ENV.
7597 debug_printf("running script '%s'\n", argv[optind]);
7598 G.global_argv = argv + optind;
7599 G.global_argc = argc - optind;
7600 input = xfopen_for_read(argv[optind]);
7601 close_on_exec_on(fileno(input));
7603 parse_and_run_file(input);
7604 #if ENABLE_FEATURE_CLEAN_UP
7610 /* Up to here, shell was non-interactive. Now it may become one.
7611 * NB: don't forget to (re)run init_sigmasks() as needed.
7614 /* A shell is interactive if the '-i' flag was given,
7615 * or if all of the following conditions are met:
7617 * no arguments remaining or the -s flag given
7618 * standard input is a terminal
7619 * standard output is a terminal
7620 * Refer to Posix.2, the description of the 'sh' utility.
7623 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7624 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7625 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7626 if (G_saved_tty_pgrp < 0)
7627 G_saved_tty_pgrp = 0;
7629 /* try to dup stdin to high fd#, >= 255 */
7630 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7631 if (G_interactive_fd < 0) {
7632 /* try to dup to any fd */
7633 G_interactive_fd = dup(STDIN_FILENO);
7634 if (G_interactive_fd < 0) {
7636 G_interactive_fd = 0;
7637 G_saved_tty_pgrp = 0;
7640 // TODO: track & disallow any attempts of user
7641 // to (inadvertently) close/redirect G_interactive_fd
7643 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7644 if (G_interactive_fd) {
7645 close_on_exec_on(G_interactive_fd);
7647 if (G_saved_tty_pgrp) {
7648 /* If we were run as 'hush &', sleep until we are
7649 * in the foreground (tty pgrp == our pgrp).
7650 * If we get started under a job aware app (like bash),
7651 * make sure we are now in charge so we don't fight over
7652 * who gets the foreground */
7654 pid_t shell_pgrp = getpgrp();
7655 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7656 if (G_saved_tty_pgrp == shell_pgrp)
7658 /* send TTIN to ourself (should stop us) */
7659 kill(- shell_pgrp, SIGTTIN);
7663 /* Block some signals */
7666 if (G_saved_tty_pgrp) {
7667 /* Set other signals to restore saved_tty_pgrp */
7668 set_fatal_handlers();
7669 /* Put ourselves in our own process group
7670 * (bash, too, does this only if ctty is available) */
7671 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7672 /* Grab control of the terminal */
7673 tcsetpgrp(G_interactive_fd, getpid());
7675 /* -1 is special - makes xfuncs longjmp, not exit
7676 * (we reset die_sleep = 0 whereever we [v]fork) */
7677 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7681 #elif ENABLE_HUSH_INTERACTIVE
7682 /* No job control compiled in, only prompt/line editing */
7683 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7684 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7685 if (G_interactive_fd < 0) {
7686 /* try to dup to any fd */
7687 G_interactive_fd = dup(STDIN_FILENO);
7688 if (G_interactive_fd < 0)
7690 G_interactive_fd = 0;
7693 if (G_interactive_fd) {
7694 close_on_exec_on(G_interactive_fd);
7698 /* We have interactiveness code disabled */
7702 * if interactive but not a login shell, sources ~/.bashrc
7703 * (--norc turns this off, --rcfile <file> overrides)
7706 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7707 /* note: ash and hush share this string */
7708 printf("\n\n%s %s\n"
7709 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7712 "hush - the humble shell"
7716 parse_and_run_file(stdin);
7719 #if ENABLE_FEATURE_CLEAN_UP
7720 if (G.cwd != bb_msg_unknown)
7722 cur_var = G.top_var->next;
7724 struct variable *tmp = cur_var;
7725 if (!cur_var->max_len)
7726 free(cur_var->varstr);
7727 cur_var = cur_var->next;
7731 hush_exit(G.last_exitcode);
7736 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7737 int lash_main(int argc, char **argv)
7739 bb_error_msg("lash is deprecated, please use hush instead");
7740 return hush_main(argc, argv);
7745 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7746 int msh_main(int argc, char **argv)
7748 //bb_error_msg("msh is deprecated, please use hush instead");
7749 return hush_main(argc, argv);
7757 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7762 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7769 return applet_main_func(argc, argv - argc);
7772 static int FAST_FUNC builtin_test(char **argv)
7774 return run_applet_main(argv, test_main);
7777 static int FAST_FUNC builtin_echo(char **argv)
7779 return run_applet_main(argv, echo_main);
7783 static int FAST_FUNC builtin_printf(char **argv)
7785 return run_applet_main(argv, printf_main);
7789 static char **skip_dash_dash(char **argv)
7792 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7797 static int FAST_FUNC builtin_eval(char **argv)
7799 int rcode = EXIT_SUCCESS;
7801 argv = skip_dash_dash(argv);
7803 char *str = expand_strvec_to_string(argv);
7805 * eval "echo Hi; done" ("done" is syntax error):
7806 * "echo Hi" will not execute too.
7808 parse_and_run_string(str);
7810 rcode = G.last_exitcode;
7815 static int FAST_FUNC builtin_cd(char **argv)
7819 argv = skip_dash_dash(argv);
7821 if (newdir == NULL) {
7822 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7823 * bash says "bash: cd: HOME not set" and does nothing
7826 const char *home = get_local_var_value("HOME");
7827 newdir = home ? home : "/";
7829 if (chdir(newdir)) {
7830 /* Mimic bash message exactly */
7831 bb_perror_msg("cd: %s", newdir);
7832 return EXIT_FAILURE;
7834 /* Read current dir (get_cwd(1) is inside) and set PWD.
7835 * Note: do not enforce exporting. If PWD was unset or unexported,
7836 * set it again, but do not export. bash does the same.
7838 set_pwd_var(/*exp:*/ 0);
7839 return EXIT_SUCCESS;
7842 static int FAST_FUNC builtin_exec(char **argv)
7844 argv = skip_dash_dash(argv);
7845 if (argv[0] == NULL)
7846 return EXIT_SUCCESS; /* bash does this */
7848 /* Careful: we can end up here after [v]fork. Do not restore
7849 * tty pgrp then, only top-level shell process does that */
7850 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7851 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7853 /* TODO: if exec fails, bash does NOT exit! We do.
7854 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7855 * and tcsetpgrp, and this is inherently racy.
7857 execvp_or_die(argv);
7860 static int FAST_FUNC builtin_exit(char **argv)
7862 debug_printf_exec("%s()\n", __func__);
7864 /* interactive bash:
7865 * # trap "echo EEE" EXIT
7868 * There are stopped jobs.
7869 * (if there are _stopped_ jobs, running ones don't count)
7872 # EEE (then bash exits)
7874 * we can use G.exiting = -1 as indicator "last cmd was exit"
7877 /* note: EXIT trap is run by hush_exit */
7878 argv = skip_dash_dash(argv);
7879 if (argv[0] == NULL)
7880 hush_exit(G.last_exitcode);
7881 /* mimic bash: exit 123abc == exit 255 + error msg */
7882 xfunc_error_retval = 255;
7883 /* bash: exit -2 == exit 254, no error msg */
7884 hush_exit(xatoi(argv[0]) & 0xff);
7887 static void print_escaped(const char *s)
7892 const char *p = strchrnul(s, '\'');
7893 /* print 'xxxx', possibly just '' */
7894 printf("'%.*s'", (int)(p - s), s);
7899 /* s points to '; print "'''...'''" */
7901 do putchar('\''); while (*++s == '\'');
7906 #if !ENABLE_HUSH_LOCAL
7907 #define helper_export_local(argv, exp, lvl) \
7908 helper_export_local(argv, exp)
7910 static void helper_export_local(char **argv, int exp, int lvl)
7915 /* So far we do not check that name is valid (TODO?) */
7917 if (strchr(name, '=') == NULL) {
7918 struct variable *var;
7920 var = get_local_var(name);
7921 if (exp == -1) { /* unexporting? */
7922 /* export -n NAME (without =VALUE) */
7924 var->flg_export = 0;
7925 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7927 } /* else: export -n NOT_EXISTING_VAR: no-op */
7930 if (exp == 1) { /* exporting? */
7931 /* export NAME (without =VALUE) */
7933 var->flg_export = 1;
7934 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7935 putenv(var->varstr);
7939 /* Exporting non-existing variable.
7940 * bash does not put it in environment,
7941 * but remembers that it is exported,
7942 * and does put it in env when it is set later.
7943 * We just set it to "" and export. */
7944 /* Or, it's "local NAME" (without =VALUE).
7945 * bash sets the value to "". */
7946 name = xasprintf("%s=", name);
7948 /* (Un)exporting/making local NAME=VALUE */
7949 name = xstrdup(name);
7951 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7955 static int FAST_FUNC builtin_export(char **argv)
7957 unsigned opt_unexport;
7959 #if ENABLE_HUSH_EXPORT_N
7960 /* "!": do not abort on errors */
7961 opt_unexport = getopt32(argv, "!n");
7962 if (opt_unexport == (uint32_t)-1)
7963 return EXIT_FAILURE;
7970 if (argv[0] == NULL) {
7977 /* ash emits: export VAR='VAL'
7978 * bash: declare -x VAR="VAL"
7979 * we follow ash example */
7980 const char *s = *e++;
7981 const char *p = strchr(s, '=');
7983 if (!p) /* wtf? take next variable */
7986 printf("export %.*s", (int)(p - s) + 1, s);
7987 print_escaped(p + 1);
7991 /*fflush_all(); - done after each builtin anyway */
7993 return EXIT_SUCCESS;
7996 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7998 return EXIT_SUCCESS;
8001 #if ENABLE_HUSH_LOCAL
8002 static int FAST_FUNC builtin_local(char **argv)
8004 if (G.func_nest_level == 0) {
8005 bb_error_msg("%s: not in a function", argv[0]);
8006 return EXIT_FAILURE; /* bash compat */
8008 helper_export_local(argv, 0, G.func_nest_level);
8009 return EXIT_SUCCESS;
8013 static int FAST_FUNC builtin_trap(char **argv)
8019 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8024 /* No args: print all trapped */
8025 for (i = 0; i < NSIG; ++i) {
8028 print_escaped(G.traps[i]);
8029 /* note: bash adds "SIG", but only if invoked
8030 * as "bash". If called as "sh", or if set -o posix,
8031 * then it prints short signal names.
8032 * We are printing short names: */
8033 printf(" %s\n", get_signame(i));
8036 /*fflush_all(); - done after each builtin anyway */
8037 return EXIT_SUCCESS;
8041 /* If first arg is a number: reset all specified signals */
8042 sig = bb_strtou(*argv, NULL, 10);
8048 sig = get_signum(*argv++);
8049 if (sig < 0 || sig >= NSIG) {
8051 /* Mimic bash message exactly */
8052 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8057 G.traps[sig] = xstrdup(new_cmd);
8059 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8060 get_signame(sig), sig, G.traps[sig]);
8062 /* There is no signal for 0 (EXIT) */
8067 sigaddset(&G.blocked_set, sig);
8069 /* There was a trap handler, we are removing it
8070 * (if sig has non-DFL handling,
8071 * we don't need to do anything) */
8072 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8074 sigdelset(&G.blocked_set, sig);
8077 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8081 if (!argv[1]) { /* no second arg */
8082 bb_error_msg("trap: invalid arguments");
8083 return EXIT_FAILURE;
8086 /* First arg is "-": reset all specified to default */
8087 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8088 /* Everything else: set arg as signal handler
8089 * (includes "" case, which ignores signal) */
8090 if (argv[0][0] == '-') {
8091 if (argv[0][1] == '\0') { /* "-" */
8092 /* new_cmd remains NULL: "reset these sigs" */
8095 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8098 /* else: "-something", no special meaning */
8103 goto process_sig_list;
8106 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8107 static int FAST_FUNC builtin_type(char **argv)
8109 int ret = EXIT_SUCCESS;
8115 if (0) {} /* make conditional compile easier below */
8116 /*else if (find_alias(*argv))
8117 type = "an alias";*/
8118 #if ENABLE_HUSH_FUNCTIONS
8119 else if (find_function(*argv))
8120 type = "a function";
8122 else if (find_builtin(*argv))
8123 type = "a shell builtin";
8124 else if ((path = find_in_path(*argv)) != NULL)
8127 bb_error_msg("type: %s: not found", *argv);
8132 printf("%s is %s\n", *argv, type);
8140 /* built-in 'fg' and 'bg' handler */
8141 static int FAST_FUNC builtin_fg_bg(char **argv)
8146 if (!G_interactive_fd)
8147 return EXIT_FAILURE;
8149 /* If they gave us no args, assume they want the last backgrounded task */
8151 for (pi = G.job_list; pi; pi = pi->next) {
8152 if (pi->jobid == G.last_jobid) {
8156 bb_error_msg("%s: no current job", argv[0]);
8157 return EXIT_FAILURE;
8159 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8160 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8161 return EXIT_FAILURE;
8163 for (pi = G.job_list; pi; pi = pi->next) {
8164 if (pi->jobid == jobnum) {
8168 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8169 return EXIT_FAILURE;
8171 /* TODO: bash prints a string representation
8172 * of job being foregrounded (like "sleep 1 | cat") */
8173 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8174 /* Put the job into the foreground. */
8175 tcsetpgrp(G_interactive_fd, pi->pgrp);
8178 /* Restart the processes in the job */
8179 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8180 for (i = 0; i < pi->num_cmds; i++) {
8181 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8182 pi->cmds[i].is_stopped = 0;
8184 pi->stopped_cmds = 0;
8186 i = kill(- pi->pgrp, SIGCONT);
8188 if (errno == ESRCH) {
8189 delete_finished_bg_job(pi);
8190 return EXIT_SUCCESS;
8192 bb_perror_msg("kill (SIGCONT)");
8195 if (argv[0][0] == 'f') {
8197 return checkjobs_and_fg_shell(pi);
8199 return EXIT_SUCCESS;
8203 #if ENABLE_HUSH_HELP
8204 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8206 const struct built_in_command *x;
8209 "Built-in commands:\n"
8210 "------------------\n");
8211 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8213 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8216 return EXIT_SUCCESS;
8221 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8224 const char *status_string;
8226 for (job = G.job_list; job; job = job->next) {
8227 if (job->alive_cmds == job->stopped_cmds)
8228 status_string = "Stopped";
8230 status_string = "Running";
8232 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8234 return EXIT_SUCCESS;
8239 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8244 # ifdef M_TRIM_THRESHOLD
8245 /* Optional. Reduces probability of false positives */
8248 /* Crude attempt to find where "free memory" starts,
8249 * sans fragmentation. */
8251 l = (unsigned long)p;
8254 if (l < (unsigned long)p) l = (unsigned long)p;
8257 if (!G.memleak_value)
8258 G.memleak_value = l;
8260 l -= G.memleak_value;
8267 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8272 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8275 return EXIT_SUCCESS;
8278 static int FAST_FUNC builtin_read(char **argv)
8287 /* "!": do not abort on errors.
8288 * Option string must start with "sr" to match BUILTIN_READ_xxx
8290 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8291 if (read_flags == (uint32_t)-1)
8292 return EXIT_FAILURE;
8295 r = shell_builtin_read(set_local_var_from_halves,
8297 get_local_var_value("IFS"), /* can be NULL */
8305 if ((uintptr_t)r > 1) {
8306 bb_error_msg("%s", r);
8307 r = (char*)(uintptr_t)1;
8310 return (uintptr_t)r;
8313 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8314 * built-in 'set' handler
8316 * set [-abCefhmnuvx] [-o option] [argument...]
8317 * set [+abCefhmnuvx] [+o option] [argument...]
8318 * set -- [argument...]
8321 * Implementations shall support the options in both their hyphen and
8322 * plus-sign forms. These options can also be specified as options to sh.
8324 * Write out all variables and their values: set
8325 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8326 * Turn on the -x and -v options: set -xv
8327 * Unset all positional parameters: set --
8328 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8329 * Set the positional parameters to the expansion of x, even if x expands
8330 * with a leading '-' or '+': set -- $x
8332 * So far, we only support "set -- [argument...]" and some of the short names.
8334 static int FAST_FUNC builtin_set(char **argv)
8337 char **pp, **g_argv;
8338 char *arg = *++argv;
8342 for (e = G.top_var; e; e = e->next)
8344 return EXIT_SUCCESS;
8348 if (!strcmp(arg, "--")) {
8352 if (arg[0] != '+' && arg[0] != '-')
8354 for (n = 1; arg[n]; ++n)
8355 if (set_mode(arg[0], arg[n]))
8357 } while ((arg = *++argv) != NULL);
8358 /* Now argv[0] is 1st argument */
8361 return EXIT_SUCCESS;
8364 /* NB: G.global_argv[0] ($0) is never freed/changed */
8365 g_argv = G.global_argv;
8366 if (G.global_args_malloced) {
8372 G.global_args_malloced = 1;
8373 pp = xzalloc(sizeof(pp[0]) * 2);
8374 pp[0] = g_argv[0]; /* retain $0 */
8377 /* This realloc's G.global_argv */
8378 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8385 return EXIT_SUCCESS;
8387 /* Nothing known, so abort */
8389 bb_error_msg("set: %s: invalid option", arg);
8390 return EXIT_FAILURE;
8393 static int FAST_FUNC builtin_shift(char **argv)
8396 argv = skip_dash_dash(argv);
8400 if (n >= 0 && n < G.global_argc) {
8401 if (G.global_args_malloced) {
8404 free(G.global_argv[m++]);
8407 memmove(&G.global_argv[1], &G.global_argv[n+1],
8408 G.global_argc * sizeof(G.global_argv[0]));
8409 return EXIT_SUCCESS;
8411 return EXIT_FAILURE;
8414 static int FAST_FUNC builtin_source(char **argv)
8416 char *arg_path, *filename;
8419 #if ENABLE_HUSH_FUNCTIONS
8423 argv = skip_dash_dash(argv);
8426 /* bash says: "bash: .: filename argument required" */
8427 return 2; /* bash compat */
8430 if (!strchr(filename, '/')) {
8431 arg_path = find_in_path(filename);
8433 filename = arg_path;
8435 input = fopen_or_warn(filename, "r");
8438 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8439 return EXIT_FAILURE;
8441 close_on_exec_on(fileno(input));
8443 #if ENABLE_HUSH_FUNCTIONS
8444 sv_flg = G.flag_return_in_progress;
8445 /* "we are inside sourced file, ok to use return" */
8446 G.flag_return_in_progress = -1;
8448 save_and_replace_G_args(&sv, argv);
8450 parse_and_run_file(input);
8453 restore_G_args(&sv, argv);
8454 #if ENABLE_HUSH_FUNCTIONS
8455 G.flag_return_in_progress = sv_flg;
8458 return G.last_exitcode;
8461 static int FAST_FUNC builtin_umask(char **argv)
8467 argv = skip_dash_dash(argv);
8469 mode_t old_mask = mask;
8472 rc = bb_parse_mode(argv[0], &mask);
8477 * bash: umask: 'q': invalid symbolic mode operator
8478 * bash: umask: 999: octal number out of range
8480 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8485 printf("%04o\n", (unsigned) mask);
8486 /* fall through and restore mask which we set to 0 */
8490 return !rc; /* rc != 0 - success */
8493 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8494 static int FAST_FUNC builtin_unset(char **argv)
8499 /* "!": do not abort on errors */
8500 /* "+": stop at 1st non-option */
8501 opts = getopt32(argv, "!+vf");
8502 if (opts == (unsigned)-1)
8503 return EXIT_FAILURE;
8505 bb_error_msg("unset: -v and -f are exclusive");
8506 return EXIT_FAILURE;
8512 if (!(opts & 2)) { /* not -f */
8513 if (unset_local_var(*argv)) {
8514 /* unset <nonexistent_var> doesn't fail.
8515 * Error is when one tries to unset RO var.
8516 * Message was printed by unset_local_var. */
8520 #if ENABLE_HUSH_FUNCTIONS
8530 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8531 static int FAST_FUNC builtin_wait(char **argv)
8533 int ret = EXIT_SUCCESS;
8536 argv = skip_dash_dash(argv);
8537 if (argv[0] == NULL) {
8538 /* Don't care about wait results */
8539 /* Note 1: must wait until there are no more children */
8540 /* Note 2: must be interruptible */
8542 * $ sleep 3 & sleep 6 & wait
8547 * $ sleep 3 & sleep 6 & wait
8551 * ^C <-- after ~4 sec from keyboard
8554 sigaddset(&G.blocked_set, SIGCHLD);
8555 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8558 if (errno == ECHILD)
8560 /* Wait for SIGCHLD or any other signal of interest */
8561 /* sigtimedwait with infinite timeout: */
8562 sig = sigwaitinfo(&G.blocked_set, NULL);
8564 sig = check_and_run_traps(sig);
8565 if (sig && sig != SIGCHLD) { /* see note 2 */
8571 sigdelset(&G.blocked_set, SIGCHLD);
8572 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8576 /* This is probably buggy wrt interruptible-ness */
8578 pid_t pid = bb_strtou(*argv, NULL, 10);
8580 /* mimic bash message */
8581 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8582 return EXIT_FAILURE;
8584 if (waitpid(pid, &status, 0) == pid) {
8585 if (WIFSIGNALED(status))
8586 ret = 128 + WTERMSIG(status);
8587 else if (WIFEXITED(status))
8588 ret = WEXITSTATUS(status);
8592 bb_perror_msg("wait %s", *argv);
8601 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8602 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8605 def = bb_strtou(argv[1], NULL, 10);
8606 if (errno || def < def_min || argv[2]) {
8607 bb_error_msg("%s: bad arguments", argv[0]);
8615 #if ENABLE_HUSH_LOOPS
8616 static int FAST_FUNC builtin_break(char **argv)
8619 if (G.depth_of_loop == 0) {
8620 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8621 return EXIT_SUCCESS; /* bash compat */
8623 G.flag_break_continue++; /* BC_BREAK = 1 */
8625 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8626 if (depth == UINT_MAX)
8627 G.flag_break_continue = BC_BREAK;
8628 if (G.depth_of_loop < depth)
8629 G.depth_break_continue = G.depth_of_loop;
8631 return EXIT_SUCCESS;
8634 static int FAST_FUNC builtin_continue(char **argv)
8636 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8637 return builtin_break(argv);
8641 #if ENABLE_HUSH_FUNCTIONS
8642 static int FAST_FUNC builtin_return(char **argv)
8646 if (G.flag_return_in_progress != -1) {
8647 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8648 return EXIT_FAILURE; /* bash compat */
8651 G.flag_return_in_progress = 1;
8654 * out of range: wraps around at 256, does not error out
8655 * non-numeric param:
8656 * f() { false; return qwe; }; f; echo $?
8657 * bash: return: qwe: numeric argument required <== we do this
8658 * 255 <== we also do this
8660 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);