1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112 //config: bool "hush"
115 //config: hush is a small shell (25k). It handles the normal flow control
116 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117 //config: case/esac. Redirections, here documents, $((arithmetic))
118 //config: and functions are supported.
120 //config: It will compile and work on no-mmu systems.
122 //config: It does not handle select, aliases, brace expansion,
123 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
125 //config:config HUSH_BASH_COMPAT
126 //config: bool "bash-compatible extensions"
128 //config: depends on HUSH
130 //config: Enable bash-compatible extensions.
132 //config:config HUSH_HELP
133 //config: bool "help builtin"
135 //config: depends on HUSH
137 //config: Enable help builtin in hush. Code size + ~1 kbyte.
139 //config:config HUSH_INTERACTIVE
140 //config: bool "Interactive mode"
142 //config: depends on HUSH
144 //config: Enable interactive mode (prompt and command editing).
145 //config: Without this, hush simply reads and executes commands
146 //config: from stdin just like a shell script from a file.
147 //config: No prompt, no PS1/PS2 magic shell variables.
149 //config:config HUSH_SAVEHISTORY
150 //config: bool "Save command history to .hush_history"
152 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
154 //config: Enable history saving in hush.
156 //config:config HUSH_JOB
157 //config: bool "Job control"
159 //config: depends on HUSH_INTERACTIVE
161 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
162 //config: command (not entire shell), fg/bg builtins work. Without this option,
163 //config: "cmd &" still works by simply spawning a process and immediately
164 //config: prompting for next command (or executing next command in a script),
165 //config: but no separate process group is formed.
167 //config:config HUSH_TICK
168 //config: bool "Process substitution"
170 //config: depends on HUSH
172 //config: Enable process substitution `command` and $(command) in hush.
174 //config:config HUSH_IF
175 //config: bool "Support if/then/elif/else/fi"
177 //config: depends on HUSH
179 //config: Enable if/then/elif/else/fi in hush.
181 //config:config HUSH_LOOPS
182 //config: bool "Support for, while and until loops"
184 //config: depends on HUSH
186 //config: Enable for, while and until loops in hush.
188 //config:config HUSH_CASE
189 //config: bool "Support case ... esac statement"
191 //config: depends on HUSH
193 //config: Enable case ... esac statement in hush. +400 bytes.
195 //config:config HUSH_FUNCTIONS
196 //config: bool "Support funcname() { commands; } syntax"
198 //config: depends on HUSH
200 //config: Enable support for shell functions in hush. +800 bytes.
202 //config:config HUSH_LOCAL
203 //config: bool "Support local builtin"
205 //config: depends on HUSH_FUNCTIONS
207 //config: Enable support for local variables in functions.
209 //config:config HUSH_RANDOM_SUPPORT
210 //config: bool "Pseudorandom generator and $RANDOM variable"
212 //config: depends on HUSH
214 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
215 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
217 //config:config HUSH_EXPORT_N
218 //config: bool "Support 'export -n' option"
220 //config: depends on HUSH
222 //config: export -n unexports variables. It is a bash extension.
224 //config:config HUSH_MODE_X
225 //config: bool "Support 'hush -x' option and 'set -x' command"
227 //config: depends on HUSH
229 //config: This instructs hush to print commands before execution.
230 //config: Adds ~300 bytes.
233 //config: bool "msh (deprecated: aliased to hush)"
235 //config: select HUSH
237 //config: msh is deprecated and will be removed, please migrate to hush.
240 //usage:#define hush_trivial_usage NOUSAGE_STR
241 //usage:#define hush_full_usage ""
242 //usage:#define msh_trivial_usage NOUSAGE_STR
243 //usage:#define msh_full_usage ""
244 //usage:#define sh_trivial_usage NOUSAGE_STR
245 //usage:#define sh_full_usage ""
246 //usage:#define bash_trivial_usage NOUSAGE_STR
247 //usage:#define bash_full_usage ""
251 #define LEAK_HUNTING 0
252 #define BUILD_AS_NOMMU 0
253 /* Enable/disable sanity checks. Ok to enable in production,
254 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
255 * Keeping 1 for now even in released versions.
258 /* Slightly bigger (+200 bytes), but faster hush.
259 * So far it only enables a trick with counting SIGCHLDs and forks,
260 * which allows us to do fewer waitpid's.
261 * (we can detect a case where neither forks were done nor SIGCHLDs happened
262 * and therefore waitpid will return the same result as last time)
264 #define ENABLE_HUSH_FAST 0
265 /* TODO: implement simplified code for users which do not need ${var%...} ops
266 * So far ${var%...} ops are always enabled:
268 #define ENABLE_HUSH_DOLLAR_OPS 1
273 # undef USE_FOR_NOMMU
276 # define USE_FOR_NOMMU(...) __VA_ARGS__
277 # define USE_FOR_MMU(...)
280 #include "NUM_APPLETS.h"
282 /* STANDALONE does not make sense, and won't compile */
283 # undef CONFIG_FEATURE_SH_STANDALONE
284 # undef ENABLE_FEATURE_SH_STANDALONE
285 # undef IF_FEATURE_SH_STANDALONE
286 # undef IF_NOT_FEATURE_SH_STANDALONE
287 # define ENABLE_FEATURE_SH_STANDALONE 0
288 # define IF_FEATURE_SH_STANDALONE(...)
289 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
292 #if !ENABLE_HUSH_INTERACTIVE
293 # undef ENABLE_FEATURE_EDITING
294 # define ENABLE_FEATURE_EDITING 0
295 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
296 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
299 /* Do we support ANY keywords? */
300 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
301 # define HAS_KEYWORDS 1
302 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
303 # define IF_HAS_NO_KEYWORDS(...)
305 # define HAS_KEYWORDS 0
306 # define IF_HAS_KEYWORDS(...)
307 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
310 /* If you comment out one of these below, it will be #defined later
311 * to perform debug printfs to stderr: */
312 #define debug_printf(...) do {} while (0)
313 /* Finer-grained debug switches */
314 #define debug_printf_parse(...) do {} while (0)
315 #define debug_print_tree(a, b) do {} while (0)
316 #define debug_printf_exec(...) do {} while (0)
317 #define debug_printf_env(...) do {} while (0)
318 #define debug_printf_jobs(...) do {} while (0)
319 #define debug_printf_expand(...) do {} while (0)
320 #define debug_printf_varexp(...) do {} while (0)
321 #define debug_printf_glob(...) do {} while (0)
322 #define debug_printf_list(...) do {} while (0)
323 #define debug_printf_subst(...) do {} while (0)
324 #define debug_printf_clean(...) do {} while (0)
326 #define ERR_PTR ((void*)(long)1)
328 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
330 #define _SPECIAL_VARS_STR "_*@$!?#"
331 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
332 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
333 #if ENABLE_HUSH_BASH_COMPAT
334 /* Support / and // replace ops */
335 /* Note that // is stored as \ in "encoded" string representation */
336 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
337 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
338 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
340 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
341 # define VAR_SUBST_OPS "%#:-=+?"
342 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
345 #define SPECIAL_VAR_SYMBOL 3
349 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
351 /* This supports saving pointers malloced in vfork child,
352 * to be freed in the parent.
355 typedef struct nommu_save_t {
357 struct variable *old_vars;
359 char **argv_from_re_execing;
372 #if ENABLE_HUSH_LOOPS
379 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
384 /* three pseudo-keywords support contrived "case" syntax: */
385 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
386 RES_MATCH , /* "word)" */
387 RES_CASE_BODY, /* "this command is inside CASE" */
395 EXP_FLAG_GLOB = 0x200,
396 EXP_FLAG_ESC_GLOB_CHARS = 0x100,
397 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
400 typedef struct o_string {
402 int length; /* position where data is appended */
404 /* Protect newly added chars against globbing
405 * (by prepending \ to *, ?, [, \) */
407 /* At least some part of the string was inside '' or "",
408 * possibly empty one: word"", wo''rd etc. */
409 smallint has_quoted_part;
410 smallint has_empty_slot;
411 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
414 MAYBE_ASSIGNMENT = 0,
415 DEFINITELY_ASSIGNMENT = 1,
417 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
419 /* Used for initialization: o_string foo = NULL_O_STRING; */
420 #define NULL_O_STRING { NULL }
422 /* I can almost use ordinary FILE*. Is open_memstream() universally
423 * available? Where is it documented? */
424 typedef struct in_str {
426 /* eof_flag=1: last char in ->p is really an EOF */
427 char eof_flag; /* meaningless if ->p == NULL */
429 #if ENABLE_HUSH_INTERACTIVE
431 smallint promptmode; /* 0: PS1, 1: PS2 */
434 int (*get) (struct in_str *) FAST_FUNC;
435 int (*peek) (struct in_str *) FAST_FUNC;
437 #define i_getch(input) ((input)->get(input))
438 #define i_peek(input) ((input)->peek(input))
440 /* The descrip member of this structure is only used to make
441 * debugging output pretty */
442 static const struct {
444 signed char default_fd;
447 { O_RDONLY, 0, "<" },
448 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
449 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
450 { O_CREAT|O_RDWR, 1, "<>" },
451 { O_RDONLY, 0, "<<" },
452 /* Should not be needed. Bogus default_fd helps in debugging */
453 /* { O_RDONLY, 77, "<<" }, */
456 struct redir_struct {
457 struct redir_struct *next;
458 char *rd_filename; /* filename */
459 int rd_fd; /* fd to redirect */
460 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
462 smallint rd_type; /* (enum redir_type) */
463 /* note: for heredocs, rd_filename contains heredoc delimiter,
464 * and subsequently heredoc itself; and rd_dup is a bitmask:
465 * bit 0: do we need to trim leading tabs?
466 * bit 1: is heredoc quoted (<<'delim' syntax) ?
469 typedef enum redir_type {
471 REDIRECT_OVERWRITE = 1,
474 REDIRECT_HEREDOC = 4,
475 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
478 REDIRFD_SYNTAX_ERR = -2,
479 REDIRFD_TO_FILE = -1,
480 /* otherwise, rd_fd is redirected to rd_dup */
482 HEREDOC_SKIPTABS = 1,
488 pid_t pid; /* 0 if exited */
489 int assignment_cnt; /* how many argv[i] are assignments? */
490 smallint is_stopped; /* is the command currently running? */
491 smallint cmd_type; /* CMD_xxx */
493 #define CMD_SUBSHELL 1
494 #if ENABLE_HUSH_BASH_COMPAT
495 /* used for "[[ EXPR ]]" */
496 # define CMD_SINGLEWORD_NOGLOB 2
498 #if ENABLE_HUSH_FUNCTIONS
499 # define CMD_FUNCDEF 3
502 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
505 char *group_as_string;
507 #if ENABLE_HUSH_FUNCTIONS
508 struct function *child_func;
509 /* This field is used to prevent a bug here:
510 * while...do f1() {a;}; f1; f1() {b;}; f1; done
511 * When we execute "f1() {a;}" cmd, we create new function and clear
512 * cmd->group, cmd->group_as_string, cmd->argv[0].
513 * When we execute "f1() {b;}", we notice that f1 exists,
514 * and that its "parent cmd" struct is still "alive",
515 * we put those fields back into cmd->xxx
516 * (struct function has ->parent_cmd ptr to facilitate that).
517 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
518 * Without this trick, loop would execute a;b;b;b;...
519 * instead of correct sequence a;b;a;b;...
520 * When command is freed, it severs the link
521 * (sets ->child_func->parent_cmd to NULL).
524 char **argv; /* command name and arguments */
525 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
526 * and on execution these are substituted with their values.
527 * Substitution can make _several_ words out of one argv[n]!
528 * Example: argv[0]=='.^C*^C.' here: echo .$*.
529 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
531 struct redir_struct *redirects; /* I/O redirections */
533 /* Is there anything in this command at all? */
534 #define IS_NULL_CMD(cmd) \
535 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
540 int num_cmds; /* total number of commands in pipe */
541 int alive_cmds; /* number of commands running (not exited) */
542 int stopped_cmds; /* number of commands alive, but stopped */
544 int jobid; /* job number */
545 pid_t pgrp; /* process group ID for the job */
546 char *cmdtext; /* name of job */
548 struct command *cmds; /* array of commands in pipe */
549 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
550 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
551 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
553 typedef enum pipe_style {
559 /* Is there anything in this pipe at all? */
560 #define IS_NULL_PIPE(pi) \
561 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
563 /* This holds pointers to the various results of parsing */
564 struct parse_context {
565 /* linked list of pipes */
566 struct pipe *list_head;
567 /* last pipe (being constructed right now) */
569 /* last command in pipe (being constructed right now) */
570 struct command *command;
571 /* last redirect in command->redirects list */
572 struct redir_struct *pending_redirect;
578 smallint ctx_inverted; /* "! cmd | cmd" */
580 smallint ctx_dsemicolon; /* ";;" seen */
582 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
584 /* group we are enclosed in:
585 * example: "if pipe1; pipe2; then pipe3; fi"
586 * when we see "if" or "then", we malloc and copy current context,
587 * and make ->stack point to it. then we parse pipeN.
588 * when closing "then" / fi" / whatever is found,
589 * we move list_head into ->stack->command->group,
590 * copy ->stack into current context, and delete ->stack.
591 * (parsing of { list } and ( list ) doesn't use this method)
593 struct parse_context *stack;
597 /* On program start, environ points to initial environment.
598 * putenv adds new pointers into it, unsetenv removes them.
599 * Neither of these (de)allocates the strings.
600 * setenv allocates new strings in malloc space and does putenv,
601 * and thus setenv is unusable (leaky) for shell's purposes */
602 #define setenv(...) setenv_is_leaky_dont_use()
604 struct variable *next;
605 char *varstr; /* points to "name=" portion */
606 #if ENABLE_HUSH_LOCAL
607 unsigned func_nest_level;
609 int max_len; /* if > 0, name is part of initial env; else name is malloced */
610 smallint flg_export; /* putenv should be done on this var */
611 smallint flg_read_only;
619 #if ENABLE_HUSH_FUNCTIONS
621 struct function *next;
623 struct command *parent_cmd;
626 char *body_as_string;
632 /* "Globals" within this file */
633 /* Sorted roughly by size (smaller offsets == smaller code) */
635 /* interactive_fd != 0 means we are an interactive shell.
636 * If we are, then saved_tty_pgrp can also be != 0, meaning
637 * that controlling tty is available. With saved_tty_pgrp == 0,
638 * job control still works, but terminal signals
639 * (^C, ^Z, ^Y, ^\) won't work at all, and background
640 * process groups can only be created with "cmd &".
641 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
642 * to give tty to the foreground process group,
643 * and will take it back when the group is stopped (^Z)
646 #if ENABLE_HUSH_INTERACTIVE
647 /* 'interactive_fd' is a fd# open to ctty, if we have one
648 * _AND_ if we decided to act interactively */
652 # define G_interactive_fd (G.interactive_fd)
654 # define G_interactive_fd 0
656 #if ENABLE_FEATURE_EDITING
657 line_input_t *line_input_state;
662 #if ENABLE_HUSH_RANDOM_SUPPORT
668 pid_t saved_tty_pgrp;
669 struct pipe *job_list;
670 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
672 # define G_saved_tty_pgrp 0
674 smallint flag_SIGINT;
675 #if ENABLE_HUSH_LOOPS
676 smallint flag_break_continue;
678 #if ENABLE_HUSH_FUNCTIONS
679 /* 0: outside of a function (or sourced file)
680 * -1: inside of a function, ok to use return builtin
681 * 1: return is invoked, skip all till end of func
683 smallint flag_return_in_progress;
686 #if ENABLE_HUSH_MODE_X
688 # define G_x_mode (G.x_mode)
692 smallint exiting; /* used to prevent EXIT trap recursion */
693 /* These four support $?, $#, and $1 */
694 smalluint last_exitcode;
695 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
696 smalluint global_args_malloced;
697 smalluint inherited_set_is_saved;
698 /* how many non-NULL argv's we have. NB: $# + 1 */
702 char *argv0_for_re_execing;
704 #if ENABLE_HUSH_LOOPS
705 unsigned depth_break_continue;
706 unsigned depth_of_loop;
710 struct variable *top_var; /* = &G.shell_ver (set in main()) */
711 struct variable shell_ver;
712 char **expanded_assignments;
713 #if ENABLE_HUSH_FUNCTIONS
714 struct function *top_func;
715 # if ENABLE_HUSH_LOCAL
716 struct variable **shadowed_vars_pp;
717 unsigned func_nest_level;
720 /* Signal and trap handling */
722 unsigned count_SIGCHLD;
723 unsigned handled_SIGCHLD;
724 smallint we_have_children;
726 /* which signals have non-DFL handler (even with no traps set)? */
727 unsigned non_DFL_mask;
728 char **traps; /* char *traps[NSIG] */
729 sigset_t blocked_set;
730 sigset_t inherited_set;
732 unsigned long memleak_value;
735 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
737 #define G (*ptr_to_globals)
738 /* Not #defining name to G.name - this quickly gets unwieldy
739 * (too many defines). Also, I actually prefer to see when a variable
740 * is global, thus "G." prefix is a useful hint */
741 #define INIT_G() do { \
742 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
746 /* Function prototypes for builtins */
747 static int builtin_cd(char **argv) FAST_FUNC;
748 static int builtin_echo(char **argv) FAST_FUNC;
749 static int builtin_eval(char **argv) FAST_FUNC;
750 static int builtin_exec(char **argv) FAST_FUNC;
751 static int builtin_exit(char **argv) FAST_FUNC;
752 static int builtin_export(char **argv) FAST_FUNC;
754 static int builtin_fg_bg(char **argv) FAST_FUNC;
755 static int builtin_jobs(char **argv) FAST_FUNC;
758 static int builtin_help(char **argv) FAST_FUNC;
760 #if ENABLE_HUSH_LOCAL
761 static int builtin_local(char **argv) FAST_FUNC;
764 static int builtin_memleak(char **argv) FAST_FUNC;
767 static int builtin_printf(char **argv) FAST_FUNC;
769 static int builtin_pwd(char **argv) FAST_FUNC;
770 static int builtin_read(char **argv) FAST_FUNC;
771 static int builtin_set(char **argv) FAST_FUNC;
772 static int builtin_shift(char **argv) FAST_FUNC;
773 static int builtin_source(char **argv) FAST_FUNC;
774 static int builtin_test(char **argv) FAST_FUNC;
775 static int builtin_trap(char **argv) FAST_FUNC;
776 static int builtin_type(char **argv) FAST_FUNC;
777 static int builtin_true(char **argv) FAST_FUNC;
778 static int builtin_umask(char **argv) FAST_FUNC;
779 static int builtin_unset(char **argv) FAST_FUNC;
780 static int builtin_wait(char **argv) FAST_FUNC;
781 #if ENABLE_HUSH_LOOPS
782 static int builtin_break(char **argv) FAST_FUNC;
783 static int builtin_continue(char **argv) FAST_FUNC;
785 #if ENABLE_HUSH_FUNCTIONS
786 static int builtin_return(char **argv) FAST_FUNC;
789 /* Table of built-in functions. They can be forked or not, depending on
790 * context: within pipes, they fork. As simple commands, they do not.
791 * When used in non-forking context, they can change global variables
792 * in the parent shell process. If forked, of course they cannot.
793 * For example, 'unset foo | whatever' will parse and run, but foo will
794 * still be set at the end. */
795 struct built_in_command {
797 int (*b_function)(char **argv) FAST_FUNC;
800 # define BLTIN(cmd, func, help) { cmd, func, help }
802 # define BLTIN(cmd, func, help) { cmd, func }
806 static const struct built_in_command bltins1[] = {
807 BLTIN("." , builtin_source , "Run commands in a file"),
808 BLTIN(":" , builtin_true , NULL),
810 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
812 #if ENABLE_HUSH_LOOPS
813 BLTIN("break" , builtin_break , "Exit from a loop"),
815 BLTIN("cd" , builtin_cd , "Change directory"),
816 #if ENABLE_HUSH_LOOPS
817 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
819 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
820 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
821 BLTIN("exit" , builtin_exit , "Exit"),
822 BLTIN("export" , builtin_export , "Set environment variables"),
824 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
827 BLTIN("help" , builtin_help , NULL),
830 BLTIN("jobs" , builtin_jobs , "List jobs"),
832 #if ENABLE_HUSH_LOCAL
833 BLTIN("local" , builtin_local , "Set local variables"),
836 BLTIN("memleak" , builtin_memleak , NULL),
838 BLTIN("read" , builtin_read , "Input into variable"),
839 #if ENABLE_HUSH_FUNCTIONS
840 BLTIN("return" , builtin_return , "Return from a function"),
842 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
843 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
844 #if ENABLE_HUSH_BASH_COMPAT
845 BLTIN("source" , builtin_source , "Run commands in a file"),
847 BLTIN("trap" , builtin_trap , "Trap signals"),
848 BLTIN("type" , builtin_type , "Show command type"),
849 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
850 BLTIN("umask" , builtin_umask , "Set file creation mask"),
851 BLTIN("unset" , builtin_unset , "Unset variables"),
852 BLTIN("wait" , builtin_wait , "Wait for process"),
854 /* For now, echo and test are unconditionally enabled.
855 * Maybe make it configurable? */
856 static const struct built_in_command bltins2[] = {
857 BLTIN("[" , builtin_test , NULL),
858 BLTIN("echo" , builtin_echo , NULL),
860 BLTIN("printf" , builtin_printf , NULL),
862 BLTIN("pwd" , builtin_pwd , NULL),
863 BLTIN("test" , builtin_test , NULL),
870 /* prevent disasters with G.debug_indent < 0 */
871 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
872 # define debug_enter() (G.debug_indent++)
873 # define debug_leave() (G.debug_indent--)
875 # define indent() ((void)0)
876 # define debug_enter() ((void)0)
877 # define debug_leave() ((void)0)
881 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
884 #ifndef debug_printf_parse
885 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
888 #ifndef debug_printf_exec
889 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
892 #ifndef debug_printf_env
893 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
896 #ifndef debug_printf_jobs
897 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
898 # define DEBUG_JOBS 1
900 # define DEBUG_JOBS 0
903 #ifndef debug_printf_expand
904 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
905 # define DEBUG_EXPAND 1
907 # define DEBUG_EXPAND 0
910 #ifndef debug_printf_varexp
911 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
914 #ifndef debug_printf_glob
915 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
916 # define DEBUG_GLOB 1
918 # define DEBUG_GLOB 0
921 #ifndef debug_printf_list
922 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
925 #ifndef debug_printf_subst
926 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
929 #ifndef debug_printf_clean
930 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
931 # define DEBUG_CLEAN 1
933 # define DEBUG_CLEAN 0
937 static void debug_print_strings(const char *prefix, char **vv)
940 fprintf(stderr, "%s:\n", prefix);
942 fprintf(stderr, " '%s'\n", *vv++);
945 # define debug_print_strings(prefix, vv) ((void)0)
949 /* Leak hunting. Use hush_leaktool.sh for post-processing.
952 static void *xxmalloc(int lineno, size_t size)
954 void *ptr = xmalloc((size + 0xff) & ~0xff);
955 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
958 static void *xxrealloc(int lineno, void *ptr, size_t size)
960 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
961 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
964 static char *xxstrdup(int lineno, const char *str)
966 char *ptr = xstrdup(str);
967 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
970 static void xxfree(void *ptr)
972 fdprintf(2, "free %p\n", ptr);
975 # define xmalloc(s) xxmalloc(__LINE__, s)
976 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
977 # define xstrdup(s) xxstrdup(__LINE__, s)
978 # define free(p) xxfree(p)
982 /* Syntax and runtime errors. They always abort scripts.
983 * In interactive use they usually discard unparsed and/or unexecuted commands
984 * and return to the prompt.
985 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
988 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
989 # define syntax_error(lineno, msg) syntax_error(msg)
990 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
991 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
992 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
993 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
996 static void die_if_script(unsigned lineno, const char *fmt, ...)
1001 bb_error_msg("hush.c:%u", lineno);
1004 bb_verror_msg(fmt, p, NULL);
1006 if (!G_interactive_fd)
1010 static void syntax_error(unsigned lineno, const char *msg)
1013 die_if_script(lineno, "syntax error: %s", msg);
1015 die_if_script(lineno, "syntax error", NULL);
1018 static void syntax_error_at(unsigned lineno, const char *msg)
1020 die_if_script(lineno, "syntax error at '%s'", msg);
1023 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1025 die_if_script(lineno, "syntax error: unterminated %s", s);
1028 /* It so happens that all such cases are totally fatal
1029 * even if shell is interactive: EOF while looking for closing
1030 * delimiter. There is nowhere to read stuff from after that,
1031 * it's EOF! The only choice is to terminate.
1033 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1034 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1036 char msg[2] = { ch, '\0' };
1037 syntax_error_unterm_str(lineno, msg);
1041 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1046 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1050 # undef die_if_script
1051 # undef syntax_error
1052 # undef syntax_error_at
1053 # undef syntax_error_unterm_ch
1054 # undef syntax_error_unterm_str
1055 # undef syntax_error_unexpected_ch
1057 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1058 # define syntax_error(msg) syntax_error(__LINE__, msg)
1059 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1060 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1061 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1062 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1066 #if ENABLE_HUSH_INTERACTIVE
1067 static void cmdedit_update_prompt(void);
1069 # define cmdedit_update_prompt() ((void)0)
1073 /* Utility functions
1075 /* Replace each \x with x in place, return ptr past NUL. */
1076 static char *unbackslash(char *src)
1078 char *dst = src = strchrnul(src, '\\');
1082 if ((*dst++ = *src++) == '\0')
1088 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1109 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1110 v[count1 + count2] = NULL;
1113 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1117 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1119 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1120 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1123 #define add_strings_to_strings(strings, add, need_to_dup) \
1124 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1127 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1128 static char **add_string_to_strings(char **strings, char *add)
1133 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1136 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1138 char **ptr = add_string_to_strings(strings, add);
1139 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1142 #define add_string_to_strings(strings, add) \
1143 xx_add_string_to_strings(__LINE__, strings, add)
1146 static void free_strings(char **strings)
1161 /* Helpers for setting new $n and restoring them back
1163 typedef struct save_arg_t {
1167 smallint sv_g_malloced;
1170 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1174 sv->sv_argv0 = argv[0];
1175 sv->sv_g_argv = G.global_argv;
1176 sv->sv_g_argc = G.global_argc;
1177 sv->sv_g_malloced = G.global_args_malloced;
1179 argv[0] = G.global_argv[0]; /* retain $0 */
1180 G.global_argv = argv;
1181 G.global_args_malloced = 0;
1189 static void restore_G_args(save_arg_t *sv, char **argv)
1193 if (G.global_args_malloced) {
1194 /* someone ran "set -- arg1 arg2 ...", undo */
1196 while (*++pp) /* note: does not free $0 */
1198 free(G.global_argv);
1200 argv[0] = sv->sv_argv0;
1201 G.global_argv = sv->sv_g_argv;
1202 G.global_argc = sv->sv_g_argc;
1203 G.global_args_malloced = sv->sv_g_malloced;
1207 /* Basic theory of signal handling in shell
1208 * ========================================
1209 * This does not describe what hush does, rather, it is current understanding
1210 * what it _should_ do. If it doesn't, it's a bug.
1211 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1213 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1214 * is finished or backgrounded. It is the same in interactive and
1215 * non-interactive shells, and is the same regardless of whether
1216 * a user trap handler is installed or a shell special one is in effect.
1217 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1218 * backgrounds (i.e. stops) or kills all members of currently running
1221 * Wait builtin in interruptible by signals for which user trap is set
1222 * or by SIGINT in interactive shell.
1224 * Trap handlers will execute even within trap handlers. (right?)
1226 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1227 * except for handlers set to '' (empty string).
1229 * If job control is off, backgrounded commands ("cmd &")
1230 * have SIGINT, SIGQUIT set to SIG_IGN.
1232 * Commands which are run in command substitution ("`cmd`")
1233 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1235 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1236 * by the shell from its parent.
1238 * Signals which differ from SIG_DFL action
1239 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1242 * SIGTERM (interactive): ignore
1243 * SIGHUP (interactive):
1244 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1245 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1246 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1247 * that all pipe members are stopped. Try this in bash:
1248 * while :; do :; done - ^Z does not background it
1249 * (while :; do :; done) - ^Z backgrounds it
1250 * SIGINT (interactive): wait for last pipe, ignore the rest
1251 * of the command line, show prompt. NB: ^C does not send SIGINT
1252 * to interactive shell while shell is waiting for a pipe,
1253 * since shell is bg'ed (is not in foreground process group).
1254 * Example 1: this waits 5 sec, but does not execute ls:
1255 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1256 * Example 2: this does not wait and does not execute ls:
1257 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1258 * Example 3: this does not wait 5 sec, but executes ls:
1259 * "sleep 5; ls -l" + press ^C
1261 * (What happens to signals which are IGN on shell start?)
1262 * (What happens with signal mask on shell start?)
1264 * Implementation in hush
1265 * ======================
1266 * We use in-kernel pending signal mask to determine which signals were sent.
1267 * We block all signals which we don't want to take action immediately,
1268 * i.e. we block all signals which need to have special handling as described
1269 * above, and all signals which have traps set.
1270 * After each pipe execution, we extract any pending signals via sigtimedwait()
1273 * unsigned non_DFL_mask: a mask of such "special" signals
1274 * sigset_t blocked_set: current blocked signal set
1277 * clear bit in blocked_set unless it is also in non_DFL_mask
1278 * "trap 'cmd' SIGxxx":
1279 * set bit in blocked_set (even if 'cmd' is '')
1280 * after [v]fork, if we plan to be a shell:
1281 * unblock signals with special interactive handling
1282 * (child shell is not interactive),
1283 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1284 * after [v]fork, if we plan to exec:
1285 * POSIX says fork clears pending signal mask in child - no need to clear it.
1286 * Restore blocked signal set to one inherited by shell just prior to exec.
1288 * Note: as a result, we do not use signal handlers much. The only uses
1289 * are to count SIGCHLDs
1290 * and to restore tty pgrp on signal-induced exit.
1293 * Standard says "When a subshell is entered, traps that are not being ignored
1294 * are set to the default actions". bash interprets it so that traps which
1295 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1298 SPECIAL_INTERACTIVE_SIGS = 0
1303 SPECIAL_JOB_SIGS = 0
1311 #if ENABLE_HUSH_FAST
1312 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1315 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1321 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1322 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1323 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1324 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1326 /* Restores tty foreground process group, and exits.
1327 * May be called as signal handler for fatal signal
1328 * (will resend signal to itself, producing correct exit state)
1329 * or called directly with -EXITCODE.
1330 * We also call it if xfunc is exiting. */
1331 static void sigexit(int sig) NORETURN;
1332 static void sigexit(int sig)
1334 /* Disable all signals: job control, SIGPIPE, etc. */
1335 sigprocmask_allsigs(SIG_BLOCK);
1337 /* Careful: we can end up here after [v]fork. Do not restore
1338 * tty pgrp then, only top-level shell process does that */
1339 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1340 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1342 /* Not a signal, just exit */
1346 kill_myself_with_sig(sig); /* does not return */
1350 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1351 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1355 /* Restores tty foreground process group, and exits. */
1356 static void hush_exit(int exitcode) NORETURN;
1357 static void hush_exit(int exitcode)
1359 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1360 /* Prevent recursion:
1361 * trap "echo Hi; exit" EXIT; exit
1364 /* argv[0] is unused */
1365 argv[1] = G.traps[0];
1367 G.exiting = 1; /* prevent EXIT trap recursion */
1368 /* Note: G.traps[0] is not cleared!
1369 * "trap" will still show it, if executed
1376 sigexit(- (exitcode & 0xff));
1383 static int check_and_run_traps(int sig)
1385 /* I want it in rodata, not in bss.
1386 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1387 * initializer. But other compilers may still use bss.
1388 * TODO: find more portable solution.
1390 static const struct timespec zero_timespec = { 0, 0 };
1391 smalluint save_rcode;
1397 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1402 if (G.traps && G.traps[sig]) {
1403 if (G.traps[sig][0]) {
1404 /* We have user-defined handler */
1406 /* argv[0] is unused */
1407 argv[1] = G.traps[sig];
1409 save_rcode = G.last_exitcode;
1411 G.last_exitcode = save_rcode;
1412 } /* else: "" trap, ignoring signal */
1415 /* not a trap: special action */
1417 #if ENABLE_HUSH_FAST
1420 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1424 /* Builtin was ^C'ed, make it look prettier: */
1431 /* bash is observed to signal whole process groups,
1432 * not individual processes */
1433 for (job = G.job_list; job; job = job->next) {
1436 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1437 if (kill(- job->pgrp, SIGHUP) == 0)
1438 kill(- job->pgrp, SIGCONT);
1443 default: /* ignored: */
1444 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1452 static const char *get_cwd(int force)
1454 if (force || G.cwd == NULL) {
1455 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1456 * we must not try to free(bb_msg_unknown) */
1457 if (G.cwd == bb_msg_unknown)
1459 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1461 G.cwd = bb_msg_unknown;
1468 * Shell and environment variable support
1470 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1472 struct variable **pp;
1473 struct variable *cur;
1476 while ((cur = *pp) != NULL) {
1477 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1484 static const char* FAST_FUNC get_local_var_value(const char *name)
1486 struct variable **vpp;
1487 unsigned len = strlen(name);
1489 if (G.expanded_assignments) {
1490 char **cpp = G.expanded_assignments;
1493 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1494 return cp + len + 1;
1499 vpp = get_ptr_to_local_var(name, len);
1501 return (*vpp)->varstr + len + 1;
1503 if (strcmp(name, "PPID") == 0)
1504 return utoa(G.root_ppid);
1505 // bash compat: UID? EUID?
1506 #if ENABLE_HUSH_RANDOM_SUPPORT
1507 if (strcmp(name, "RANDOM") == 0)
1508 return utoa(next_random(&G.random_gen));
1513 /* str holds "NAME=VAL" and is expected to be malloced.
1514 * We take ownership of it.
1516 * 0: do not change export flag
1517 * (if creating new variable, flag will be 0)
1518 * 1: set export flag and putenv the variable
1519 * -1: clear export flag and unsetenv the variable
1520 * flg_read_only is set only when we handle -R var=val
1522 #if !BB_MMU && ENABLE_HUSH_LOCAL
1523 /* all params are used */
1524 #elif BB_MMU && ENABLE_HUSH_LOCAL
1525 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1526 set_local_var(str, flg_export, local_lvl)
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)
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, flg_read_only)
1534 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1536 struct variable **var_pp;
1537 struct variable *cur;
1541 eq_sign = strchr(str, '=');
1542 if (!eq_sign) { /* not expected to ever happen? */
1547 name_len = eq_sign - str + 1; /* including '=' */
1548 var_pp = &G.top_var;
1549 while ((cur = *var_pp) != NULL) {
1550 if (strncmp(cur->varstr, str, name_len) != 0) {
1551 var_pp = &cur->next;
1554 /* We found an existing var with this name */
1555 if (cur->flg_read_only) {
1559 bb_error_msg("%s: readonly variable", str);
1563 if (flg_export == -1) { // "&& cur->flg_export" ?
1564 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1569 #if ENABLE_HUSH_LOCAL
1570 if (cur->func_nest_level < local_lvl) {
1571 /* New variable is declared as local,
1572 * and existing one is global, or local
1573 * from enclosing function.
1574 * Remove and save old one: */
1575 *var_pp = cur->next;
1576 cur->next = *G.shadowed_vars_pp;
1577 *G.shadowed_vars_pp = cur;
1578 /* bash 3.2.33(1) and exported vars:
1580 * # f() { local z=a; env | grep ^z; }
1586 if (cur->flg_export)
1591 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1596 if (cur->max_len != 0) {
1597 if (cur->max_len >= strlen(str)) {
1598 /* This one is from startup env, reuse space */
1599 strcpy(cur->varstr, str);
1603 /* max_len == 0 signifies "malloced" var, which we can
1604 * (and has to) free */
1608 goto set_str_and_exp;
1611 /* Not found - create new variable struct */
1612 cur = xzalloc(sizeof(*cur));
1613 #if ENABLE_HUSH_LOCAL
1614 cur->func_nest_level = local_lvl;
1616 cur->next = *var_pp;
1622 cur->flg_read_only = flg_read_only;
1625 if (flg_export == 1)
1626 cur->flg_export = 1;
1627 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1628 cmdedit_update_prompt();
1629 if (cur->flg_export) {
1630 if (flg_export == -1) {
1631 cur->flg_export = 0;
1632 /* unsetenv was already done */
1634 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1635 return putenv(cur->varstr);
1641 /* Used at startup and after each cd */
1642 static void set_pwd_var(int exp)
1644 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1645 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1648 static int unset_local_var_len(const char *name, int name_len)
1650 struct variable *cur;
1651 struct variable **var_pp;
1654 return EXIT_SUCCESS;
1655 var_pp = &G.top_var;
1656 while ((cur = *var_pp) != NULL) {
1657 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1658 if (cur->flg_read_only) {
1659 bb_error_msg("%s: readonly variable", name);
1660 return EXIT_FAILURE;
1662 *var_pp = cur->next;
1663 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1664 bb_unsetenv(cur->varstr);
1665 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1666 cmdedit_update_prompt();
1670 return EXIT_SUCCESS;
1672 var_pp = &cur->next;
1674 return EXIT_SUCCESS;
1677 static int unset_local_var(const char *name)
1679 return unset_local_var_len(name, strlen(name));
1682 static void unset_vars(char **strings)
1690 const char *eq = strchrnul(*v, '=');
1691 unset_local_var_len(*v, (int)(eq - *v));
1697 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1699 char *var = xasprintf("%s=%s", name, val);
1700 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1705 * Helpers for "var1=val1 var2=val2 cmd" feature
1707 static void add_vars(struct variable *var)
1709 struct variable *next;
1713 var->next = G.top_var;
1715 if (var->flg_export) {
1716 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1717 putenv(var->varstr);
1719 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1725 static struct variable *set_vars_and_save_old(char **strings)
1728 struct variable *old = NULL;
1734 struct variable *var_p;
1735 struct variable **var_pp;
1738 eq = strchr(*s, '=');
1740 var_pp = get_ptr_to_local_var(*s, eq - *s);
1742 /* Remove variable from global linked list */
1744 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1745 *var_pp = var_p->next;
1746 /* Add it to returned list */
1750 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1761 static int FAST_FUNC static_get(struct in_str *i)
1771 static int FAST_FUNC static_peek(struct in_str *i)
1776 #if ENABLE_HUSH_INTERACTIVE
1778 static void cmdedit_update_prompt(void)
1780 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1781 G.PS1 = get_local_var_value("PS1");
1784 G.PS2 = get_local_var_value("PS2");
1792 static const char *setup_prompt_string(int promptmode)
1794 const char *prompt_str;
1795 debug_printf("setup_prompt_string %d ", promptmode);
1796 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1797 /* Set up the prompt */
1798 if (promptmode == 0) { /* PS1 */
1800 /* bash uses $PWD value, even if it is set by user.
1801 * It uses current dir only if PWD is unset.
1802 * We always use current dir. */
1803 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1808 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1809 debug_printf("result '%s'\n", prompt_str);
1813 static void get_user_input(struct in_str *i)
1816 const char *prompt_str;
1818 prompt_str = setup_prompt_string(i->promptmode);
1819 # if ENABLE_FEATURE_EDITING
1820 /* Enable command line editing only while a command line
1821 * is actually being read */
1824 /* buglet: SIGINT will not make new prompt to appear _at once_,
1825 * only after <Enter>. (^C will work) */
1826 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1827 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1828 check_and_run_traps(0);
1829 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1830 i->eof_flag = (r < 0);
1831 if (i->eof_flag) { /* EOF/error detected */
1832 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1833 G.user_input_buf[1] = '\0';
1838 fputs(prompt_str, stdout);
1840 G.user_input_buf[0] = r = fgetc(i->file);
1841 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1842 //do we need check_and_run_traps(0)? (maybe only if stdin)
1843 } while (G.flag_SIGINT);
1844 i->eof_flag = (r == EOF);
1846 i->p = G.user_input_buf;
1849 #endif /* INTERACTIVE */
1851 /* This is the magic location that prints prompts
1852 * and gets data back from the user */
1853 static int FAST_FUNC file_get(struct in_str *i)
1857 /* If there is data waiting, eat it up */
1858 if (i->p && *i->p) {
1859 #if ENABLE_HUSH_INTERACTIVE
1863 if (i->eof_flag && !*i->p)
1865 /* note: ch is never NUL */
1867 /* need to double check i->file because we might be doing something
1868 * more complicated by now, like sourcing or substituting. */
1869 #if ENABLE_HUSH_INTERACTIVE
1870 if (G_interactive_fd && i->promptme && i->file == stdin) {
1873 } while (!*i->p); /* need non-empty line */
1874 i->promptmode = 1; /* PS2 */
1879 do ch = fgetc(i->file); while (ch == '\0');
1881 debug_printf("file_get: got '%c' %d\n", ch, ch);
1882 #if ENABLE_HUSH_INTERACTIVE
1889 /* All callers guarantee this routine will never
1890 * be used right after a newline, so prompting is not needed.
1892 static int FAST_FUNC file_peek(struct in_str *i)
1895 if (i->p && *i->p) {
1896 if (i->eof_flag && !i->p[1])
1899 /* note: ch is never NUL */
1901 do ch = fgetc(i->file); while (ch == '\0');
1902 i->eof_flag = (ch == EOF);
1903 i->peek_buf[0] = ch;
1904 i->peek_buf[1] = '\0';
1906 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1910 static void setup_file_in_str(struct in_str *i, FILE *f)
1912 i->peek = file_peek;
1914 #if ENABLE_HUSH_INTERACTIVE
1916 i->promptmode = 0; /* PS1 */
1922 static void setup_string_in_str(struct in_str *i, const char *s)
1924 i->peek = static_peek;
1925 i->get = static_get;
1926 #if ENABLE_HUSH_INTERACTIVE
1928 i->promptmode = 0; /* PS1 */
1938 #define B_CHUNK (32 * sizeof(char*))
1940 static void o_reset_to_empty_unquoted(o_string *o)
1943 o->has_quoted_part = 0;
1948 static void o_free(o_string *o)
1951 memset(o, 0, sizeof(*o));
1954 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1959 static void o_grow_by(o_string *o, int len)
1961 if (o->length + len > o->maxlen) {
1962 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1963 o->data = xrealloc(o->data, 1 + o->maxlen);
1967 static void o_addchr(o_string *o, int ch)
1969 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1971 o->data[o->length] = ch;
1973 o->data[o->length] = '\0';
1976 static void o_addblock(o_string *o, const char *str, int len)
1979 memcpy(&o->data[o->length], str, len);
1981 o->data[o->length] = '\0';
1984 static void o_addstr(o_string *o, const char *str)
1986 o_addblock(o, str, strlen(str));
1990 static void nommu_addchr(o_string *o, int ch)
1996 # define nommu_addchr(o, str) ((void)0)
1999 static void o_addstr_with_NUL(o_string *o, const char *str)
2001 o_addblock(o, str, strlen(str) + 1);
2004 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
2009 if (*str++ == '\\') {
2010 /* \z -> \\\z; \<eol> -> \\<eol> */
2015 o_addchr(o, *str++);
2021 #undef HUSH_BRACE_EXP
2023 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2024 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2025 * Apparently, on unquoted $v bash still does globbing
2026 * ("v='*.txt'; echo $v" prints all .txt files),
2027 * but NOT brace expansion! Thus, there should be TWO independent
2028 * quoting mechanisms on $v expansion side: one protects
2029 * $v from brace expansion, and other additionally protects "$v" against globbing.
2030 * We have only second one.
2033 #ifdef HUSH_BRACE_EXP
2034 # define MAYBE_BRACES "{}"
2036 # define MAYBE_BRACES ""
2039 /* My analysis of quoting semantics tells me that state information
2040 * is associated with a destination, not a source.
2042 static void o_addqchr(o_string *o, int ch)
2045 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2050 o->data[o->length] = '\\';
2053 o->data[o->length] = ch;
2055 o->data[o->length] = '\0';
2058 static void o_addQchr(o_string *o, int ch)
2061 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2062 && strchr("*?[\\" MAYBE_BRACES, ch)
2065 o->data[o->length] = '\\';
2069 o->data[o->length] = ch;
2071 o->data[o->length] = '\0';
2074 static void o_addqblock(o_string *o, const char *str, int len)
2079 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2080 if (ordinary_cnt > len) /* paranoia */
2082 o_addblock(o, str, ordinary_cnt);
2083 if (ordinary_cnt == len)
2085 str += ordinary_cnt;
2086 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2090 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2092 o->data[o->length] = '\\';
2096 o->data[o->length] = ch;
2098 o->data[o->length] = '\0';
2102 static void o_addQblock(o_string *o, const char *str, int len)
2104 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2105 o_addblock(o, str, len);
2108 o_addqblock(o, str, len);
2111 static void o_addQstr(o_string *o, const char *str)
2113 o_addQblock(o, str, strlen(str));
2116 /* A special kind of o_string for $VAR and `cmd` expansion.
2117 * It contains char* list[] at the beginning, which is grown in 16 element
2118 * increments. Actual string data starts at the next multiple of 16 * (char*).
2119 * list[i] contains an INDEX (int!) into this string data.
2120 * It means that if list[] needs to grow, data needs to be moved higher up
2121 * but list[i]'s need not be modified.
2122 * NB: remembering how many list[i]'s you have there is crucial.
2123 * o_finalize_list() operation post-processes this structure - calculates
2124 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2126 #if DEBUG_EXPAND || DEBUG_GLOB
2127 static void debug_print_list(const char *prefix, o_string *o, int n)
2129 char **list = (char**)o->data;
2130 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2134 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2135 prefix, list, n, string_start, o->length, o->maxlen,
2136 !!(o->o_expflags & EXP_FLAG_GLOB),
2138 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2141 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2142 o->data + (int)list[i] + string_start,
2143 o->data + (int)list[i] + string_start);
2147 const char *p = o->data + (int)list[n - 1] + string_start;
2149 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2153 # define debug_print_list(prefix, o, n) ((void)0)
2156 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2157 * in list[n] so that it points past last stored byte so far.
2158 * It returns n+1. */
2159 static int o_save_ptr_helper(o_string *o, int n)
2161 char **list = (char**)o->data;
2165 if (!o->has_empty_slot) {
2166 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2167 string_len = o->length - string_start;
2168 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2169 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2170 /* list[n] points to string_start, make space for 16 more pointers */
2171 o->maxlen += 0x10 * sizeof(list[0]);
2172 o->data = xrealloc(o->data, o->maxlen + 1);
2173 list = (char**)o->data;
2174 memmove(list + n + 0x10, list + n, string_len);
2175 o->length += 0x10 * sizeof(list[0]);
2177 debug_printf_list("list[%d]=%d string_start=%d\n",
2178 n, string_len, string_start);
2181 /* We have empty slot at list[n], reuse without growth */
2182 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2183 string_len = o->length - string_start;
2184 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2185 n, string_len, string_start);
2186 o->has_empty_slot = 0;
2188 list[n] = (char*)(uintptr_t)string_len;
2192 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2193 static int o_get_last_ptr(o_string *o, int n)
2195 char **list = (char**)o->data;
2196 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2198 return ((int)(uintptr_t)list[n-1]) + string_start;
2201 #ifdef HUSH_BRACE_EXP
2202 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2203 * first, it processes even {a} (no commas), second,
2204 * I didn't manage to make it return strings when they don't match
2205 * existing files. Need to re-implement it.
2209 static int glob_needed(const char *s)
2218 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2224 /* Return pointer to next closing brace or to comma */
2225 static const char *next_brace_sub(const char *cp)
2229 while (*cp != '\0') {
2236 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2242 return *cp != '\0' ? cp : NULL;
2244 /* Recursive brace globber. Note: may garble pattern[]. */
2245 static int glob_brace(char *pattern, o_string *o, int n)
2247 char *new_pattern_buf;
2254 debug_printf_glob("glob_brace('%s')\n", pattern);
2260 if (*begin == '{') {
2261 /* Find the first sub-pattern and at the same time
2262 * find the rest after the closing brace */
2263 next = next_brace_sub(begin);
2265 /* An illegal expression */
2269 /* "{abc}" with no commas - illegal
2270 * brace expr, disregard and skip it */
2276 if (*begin == '\\' && begin[1] != '\0')
2280 debug_printf_glob("begin:%s\n", begin);
2281 debug_printf_glob("next:%s\n", next);
2283 /* Now find the end of the whole brace expression */
2285 while (*rest != '}') {
2286 rest = next_brace_sub(rest);
2288 /* An illegal expression */
2291 debug_printf_glob("rest:%s\n", rest);
2293 rest_len = strlen(++rest) + 1;
2295 /* We are sure the brace expression is well-formed */
2297 /* Allocate working buffer large enough for our work */
2298 new_pattern_buf = xmalloc(strlen(pattern));
2300 /* We have a brace expression. BEGIN points to the opening {,
2301 * NEXT points past the terminator of the first element, and REST
2302 * points past the final }. We will accumulate result names from
2303 * recursive runs for each brace alternative in the buffer using
2308 /* Construct the new glob expression */
2311 mempcpy(new_pattern_buf,
2312 /* We know the prefix for all sub-patterns */
2313 pattern, begin - pattern),
2317 /* Note: glob_brace() may garble new_pattern_buf[].
2318 * That's why we re-copy prefix every time (1st memcpy above).
2320 n = glob_brace(new_pattern_buf, o, n);
2322 /* We saw the last entry */
2326 next = next_brace_sub(next);
2328 free(new_pattern_buf);
2336 memset(&globdata, 0, sizeof(globdata));
2337 gr = glob(pattern, 0, NULL, &globdata);
2338 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2340 if (gr == GLOB_NOMATCH) {
2341 globfree(&globdata);
2342 /* NB: garbles parameter */
2343 unbackslash(pattern);
2344 o_addstr_with_NUL(o, pattern);
2345 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2346 return o_save_ptr_helper(o, n);
2348 if (gr == GLOB_NOSPACE)
2349 bb_error_msg_and_die(bb_msg_memory_exhausted);
2350 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2351 * but we didn't specify it. Paranoia again. */
2352 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2354 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2355 char **argv = globdata.gl_pathv;
2357 o_addstr_with_NUL(o, *argv);
2358 n = o_save_ptr_helper(o, n);
2364 globfree(&globdata);
2368 /* Performs globbing on last list[],
2369 * saving each result as a new list[].
2371 static int perform_glob(o_string *o, int n)
2373 char *pattern, *copy;
2375 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2377 return o_save_ptr_helper(o, n);
2378 pattern = o->data + o_get_last_ptr(o, n);
2379 debug_printf_glob("glob pattern '%s'\n", pattern);
2380 if (!glob_needed(pattern)) {
2381 /* unbackslash last string in o in place, fix length */
2382 o->length = unbackslash(pattern) - o->data;
2383 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2384 return o_save_ptr_helper(o, n);
2387 copy = xstrdup(pattern);
2388 /* "forget" pattern in o */
2389 o->length = pattern - o->data;
2390 n = glob_brace(copy, o, n);
2393 debug_print_list("perform_glob returning", o, n);
2397 #else /* !HUSH_BRACE_EXP */
2400 static int glob_needed(const char *s)
2409 if (*s == '*' || *s == '[' || *s == '?')
2415 /* Performs globbing on last list[],
2416 * saving each result as a new list[].
2418 static int perform_glob(o_string *o, int n)
2424 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2426 return o_save_ptr_helper(o, n);
2427 pattern = o->data + o_get_last_ptr(o, n);
2428 debug_printf_glob("glob pattern '%s'\n", pattern);
2429 if (!glob_needed(pattern)) {
2431 /* unbackslash last string in o in place, fix length */
2432 o->length = unbackslash(pattern) - o->data;
2433 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2434 return o_save_ptr_helper(o, n);
2437 memset(&globdata, 0, sizeof(globdata));
2438 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2439 * If we glob "*.\*" and don't find anything, we need
2440 * to fall back to using literal "*.*", but GLOB_NOCHECK
2441 * will return "*.\*"!
2443 gr = glob(pattern, 0, NULL, &globdata);
2444 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2446 if (gr == GLOB_NOMATCH) {
2447 globfree(&globdata);
2450 if (gr == GLOB_NOSPACE)
2451 bb_error_msg_and_die(bb_msg_memory_exhausted);
2452 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2453 * but we didn't specify it. Paranoia again. */
2454 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2456 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2457 char **argv = globdata.gl_pathv;
2458 /* "forget" pattern in o */
2459 o->length = pattern - o->data;
2461 o_addstr_with_NUL(o, *argv);
2462 n = o_save_ptr_helper(o, n);
2468 globfree(&globdata);
2470 debug_print_list("perform_glob returning", o, n);
2474 #endif /* !HUSH_BRACE_EXP */
2476 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2477 * Otherwise, just finish current list[] and start new */
2478 static int o_save_ptr(o_string *o, int n)
2480 if (o->o_expflags & EXP_FLAG_GLOB) {
2481 /* If o->has_empty_slot, list[n] was already globbed
2482 * (if it was requested back then when it was filled)
2483 * so don't do that again! */
2484 if (!o->has_empty_slot)
2485 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2487 return o_save_ptr_helper(o, n);
2490 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2491 static char **o_finalize_list(o_string *o, int n)
2496 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2498 debug_print_list("finalized", o, n);
2499 debug_printf_expand("finalized n:%d\n", n);
2500 list = (char**)o->data;
2501 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2505 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2510 static void free_pipe_list(struct pipe *pi);
2512 /* Returns pi->next - next pipe in the list */
2513 static struct pipe *free_pipe(struct pipe *pi)
2518 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2519 for (i = 0; i < pi->num_cmds; i++) {
2520 struct command *command;
2521 struct redir_struct *r, *rnext;
2523 command = &pi->cmds[i];
2524 debug_printf_clean(" command %d:\n", i);
2525 if (command->argv) {
2529 for (a = 0, p = command->argv; *p; a++, p++) {
2530 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2533 free_strings(command->argv);
2534 //command->argv = NULL;
2536 /* not "else if": on syntax error, we may have both! */
2537 if (command->group) {
2538 debug_printf_clean(" begin group (cmd_type:%d)\n",
2540 free_pipe_list(command->group);
2541 debug_printf_clean(" end group\n");
2542 //command->group = NULL;
2544 /* else is crucial here.
2545 * If group != NULL, child_func is meaningless */
2546 #if ENABLE_HUSH_FUNCTIONS
2547 else if (command->child_func) {
2548 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2549 command->child_func->parent_cmd = NULL;
2553 free(command->group_as_string);
2554 //command->group_as_string = NULL;
2556 for (r = command->redirects; r; r = rnext) {
2557 debug_printf_clean(" redirect %d%s",
2558 r->rd_fd, redir_table[r->rd_type].descrip);
2559 /* guard against the case >$FOO, where foo is unset or blank */
2560 if (r->rd_filename) {
2561 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2562 free(r->rd_filename);
2563 //r->rd_filename = NULL;
2565 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2569 //command->redirects = NULL;
2571 free(pi->cmds); /* children are an array, they get freed all at once */
2575 //pi->cmdtext = NULL;
2583 static void free_pipe_list(struct pipe *pi)
2587 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2589 debug_printf_clean("pipe followup code %d\n", pi->followup);
2595 /*** Parsing routines ***/
2597 static struct pipe *new_pipe(void)
2600 pi = xzalloc(sizeof(struct pipe));
2601 /*pi->followup = 0; - deliberately invalid value */
2602 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2606 /* Command (member of a pipe) is complete, or we start a new pipe
2607 * if ctx->command is NULL.
2608 * No errors possible here.
2610 static int done_command(struct parse_context *ctx)
2612 /* The command is really already in the pipe structure, so
2613 * advance the pipe counter and make a new, null command. */
2614 struct pipe *pi = ctx->pipe;
2615 struct command *command = ctx->command;
2618 if (IS_NULL_CMD(command)) {
2619 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2623 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2624 //debug_print_tree(ctx->list_head, 20);
2626 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2629 /* Only real trickiness here is that the uncommitted
2630 * command structure is not counted in pi->num_cmds. */
2631 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2632 ctx->command = command = &pi->cmds[pi->num_cmds];
2634 memset(command, 0, sizeof(*command));
2635 return pi->num_cmds; /* used only for 0/nonzero check */
2638 static void done_pipe(struct parse_context *ctx, pipe_style type)
2642 debug_printf_parse("done_pipe entered, followup %d\n", type);
2643 /* Close previous command */
2644 not_null = done_command(ctx);
2645 ctx->pipe->followup = type;
2647 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2648 ctx->ctx_inverted = 0;
2649 ctx->pipe->res_word = ctx->ctx_res_w;
2652 /* Without this check, even just <enter> on command line generates
2653 * tree of three NOPs (!). Which is harmless but annoying.
2654 * IOW: it is safe to do it unconditionally. */
2657 || ctx->ctx_res_w == RES_FI
2659 #if ENABLE_HUSH_LOOPS
2660 || ctx->ctx_res_w == RES_DONE
2661 || ctx->ctx_res_w == RES_FOR
2662 || ctx->ctx_res_w == RES_IN
2664 #if ENABLE_HUSH_CASE
2665 || ctx->ctx_res_w == RES_ESAC
2669 debug_printf_parse("done_pipe: adding new pipe: "
2670 "not_null:%d ctx->ctx_res_w:%d\n",
2671 not_null, ctx->ctx_res_w);
2673 ctx->pipe->next = new_p;
2675 /* RES_THEN, RES_DO etc are "sticky" -
2676 * they remain set for pipes inside if/while.
2677 * This is used to control execution.
2678 * RES_FOR and RES_IN are NOT sticky (needed to support
2679 * cases where variable or value happens to match a keyword):
2681 #if ENABLE_HUSH_LOOPS
2682 if (ctx->ctx_res_w == RES_FOR
2683 || ctx->ctx_res_w == RES_IN)
2684 ctx->ctx_res_w = RES_NONE;
2686 #if ENABLE_HUSH_CASE
2687 if (ctx->ctx_res_w == RES_MATCH)
2688 ctx->ctx_res_w = RES_CASE_BODY;
2689 if (ctx->ctx_res_w == RES_CASE)
2690 ctx->ctx_res_w = RES_CASE_IN;
2692 ctx->command = NULL; /* trick done_command below */
2693 /* Create the memory for command, roughly:
2694 * ctx->pipe->cmds = new struct command;
2695 * ctx->command = &ctx->pipe->cmds[0];
2698 //debug_print_tree(ctx->list_head, 10);
2700 debug_printf_parse("done_pipe return\n");
2703 static void initialize_context(struct parse_context *ctx)
2705 memset(ctx, 0, sizeof(*ctx));
2706 ctx->pipe = ctx->list_head = new_pipe();
2707 /* Create the memory for command, roughly:
2708 * ctx->pipe->cmds = new struct command;
2709 * ctx->command = &ctx->pipe->cmds[0];
2714 /* If a reserved word is found and processed, parse context is modified
2715 * and 1 is returned.
2718 struct reserved_combo {
2721 unsigned char assignment_flag;
2725 FLAG_END = (1 << RES_NONE ),
2727 FLAG_IF = (1 << RES_IF ),
2728 FLAG_THEN = (1 << RES_THEN ),
2729 FLAG_ELIF = (1 << RES_ELIF ),
2730 FLAG_ELSE = (1 << RES_ELSE ),
2731 FLAG_FI = (1 << RES_FI ),
2733 # if ENABLE_HUSH_LOOPS
2734 FLAG_FOR = (1 << RES_FOR ),
2735 FLAG_WHILE = (1 << RES_WHILE),
2736 FLAG_UNTIL = (1 << RES_UNTIL),
2737 FLAG_DO = (1 << RES_DO ),
2738 FLAG_DONE = (1 << RES_DONE ),
2739 FLAG_IN = (1 << RES_IN ),
2741 # if ENABLE_HUSH_CASE
2742 FLAG_MATCH = (1 << RES_MATCH),
2743 FLAG_ESAC = (1 << RES_ESAC ),
2745 FLAG_START = (1 << RES_XXXX ),
2748 static const struct reserved_combo* match_reserved_word(o_string *word)
2750 /* Mostly a list of accepted follow-up reserved words.
2751 * FLAG_END means we are done with the sequence, and are ready
2752 * to turn the compound list into a command.
2753 * FLAG_START means the word must start a new compound list.
2755 static const struct reserved_combo reserved_list[] = {
2757 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2758 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2759 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2760 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2761 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2762 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2764 # if ENABLE_HUSH_LOOPS
2765 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2766 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2767 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2768 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2769 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2770 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2772 # if ENABLE_HUSH_CASE
2773 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2774 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2777 const struct reserved_combo *r;
2779 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2780 if (strcmp(word->data, r->literal) == 0)
2785 /* Return 0: not a keyword, 1: keyword
2787 static int reserved_word(o_string *word, struct parse_context *ctx)
2789 # if ENABLE_HUSH_CASE
2790 static const struct reserved_combo reserved_match = {
2791 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2794 const struct reserved_combo *r;
2796 if (word->has_quoted_part)
2798 r = match_reserved_word(word);
2802 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2803 # if ENABLE_HUSH_CASE
2804 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2805 /* "case word IN ..." - IN part starts first MATCH part */
2806 r = &reserved_match;
2809 if (r->flag == 0) { /* '!' */
2810 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2811 syntax_error("! ! command");
2812 ctx->ctx_res_w = RES_SNTX;
2814 ctx->ctx_inverted = 1;
2817 if (r->flag & FLAG_START) {
2818 struct parse_context *old;
2820 old = xmalloc(sizeof(*old));
2821 debug_printf_parse("push stack %p\n", old);
2822 *old = *ctx; /* physical copy */
2823 initialize_context(ctx);
2825 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2826 syntax_error_at(word->data);
2827 ctx->ctx_res_w = RES_SNTX;
2830 /* "{...} fi" is ok. "{...} if" is not
2832 * if { echo foo; } then { echo bar; } fi */
2833 if (ctx->command->group)
2834 done_pipe(ctx, PIPE_SEQ);
2837 ctx->ctx_res_w = r->res;
2838 ctx->old_flag = r->flag;
2839 word->o_assignment = r->assignment_flag;
2841 if (ctx->old_flag & FLAG_END) {
2842 struct parse_context *old;
2844 done_pipe(ctx, PIPE_SEQ);
2845 debug_printf_parse("pop stack %p\n", ctx->stack);
2847 old->command->group = ctx->list_head;
2848 old->command->cmd_type = CMD_NORMAL;
2850 o_addstr(&old->as_string, ctx->as_string.data);
2851 o_free_unsafe(&ctx->as_string);
2852 old->command->group_as_string = xstrdup(old->as_string.data);
2853 debug_printf_parse("pop, remembering as:'%s'\n",
2854 old->command->group_as_string);
2856 *ctx = *old; /* physical copy */
2861 #endif /* HAS_KEYWORDS */
2863 /* Word is complete, look at it and update parsing context.
2864 * Normal return is 0. Syntax errors return 1.
2865 * Note: on return, word is reset, but not o_free'd!
2867 static int done_word(o_string *word, struct parse_context *ctx)
2869 struct command *command = ctx->command;
2871 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2872 if (word->length == 0 && !word->has_quoted_part) {
2873 debug_printf_parse("done_word return 0: true null, ignored\n");
2877 if (ctx->pending_redirect) {
2878 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2879 * only if run as "bash", not "sh" */
2880 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2882 * ...the word that follows the redirection operator
2883 * shall be subjected to tilde expansion, parameter expansion,
2884 * command substitution, arithmetic expansion, and quote
2885 * removal. Pathname expansion shall not be performed
2886 * on the word by a non-interactive shell; an interactive
2887 * shell may perform it, but shall do so only when
2888 * the expansion would result in one word."
2890 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2891 /* Cater for >\file case:
2892 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2893 * Same with heredocs:
2894 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2896 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2897 unbackslash(ctx->pending_redirect->rd_filename);
2898 /* Is it <<"HEREDOC"? */
2899 if (word->has_quoted_part) {
2900 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2903 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2904 ctx->pending_redirect = NULL;
2906 /* If this word wasn't an assignment, next ones definitely
2907 * can't be assignments. Even if they look like ones. */
2908 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2909 && word->o_assignment != WORD_IS_KEYWORD
2911 word->o_assignment = NOT_ASSIGNMENT;
2913 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2914 command->assignment_cnt++;
2915 word->o_assignment = MAYBE_ASSIGNMENT;
2919 # if ENABLE_HUSH_CASE
2920 if (ctx->ctx_dsemicolon
2921 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2923 /* already done when ctx_dsemicolon was set to 1: */
2924 /* ctx->ctx_res_w = RES_MATCH; */
2925 ctx->ctx_dsemicolon = 0;
2928 if (!command->argv /* if it's the first word... */
2929 # if ENABLE_HUSH_LOOPS
2930 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2931 && ctx->ctx_res_w != RES_IN
2933 # if ENABLE_HUSH_CASE
2934 && ctx->ctx_res_w != RES_CASE
2937 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2938 if (reserved_word(word, ctx)) {
2939 o_reset_to_empty_unquoted(word);
2940 debug_printf_parse("done_word return %d\n",
2941 (ctx->ctx_res_w == RES_SNTX));
2942 return (ctx->ctx_res_w == RES_SNTX);
2944 # if ENABLE_HUSH_BASH_COMPAT
2945 if (strcmp(word->data, "[[") == 0) {
2946 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2952 if (command->group) {
2953 /* "{ echo foo; } echo bar" - bad */
2954 syntax_error_at(word->data);
2955 debug_printf_parse("done_word return 1: syntax error, "
2956 "groups and arglists don't mix\n");
2959 if (word->has_quoted_part
2960 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2961 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2962 /* (otherwise it's known to be not empty and is already safe) */
2964 /* exclude "$@" - it can expand to no word despite "" */
2965 char *p = word->data;
2966 while (p[0] == SPECIAL_VAR_SYMBOL
2967 && (p[1] & 0x7f) == '@'
2968 && p[2] == SPECIAL_VAR_SYMBOL
2972 if (p == word->data || p[0] != '\0') {
2973 /* saw no "$@", or not only "$@" but some
2974 * real text is there too */
2975 /* insert "empty variable" reference, this makes
2976 * e.g. "", $empty"" etc to not disappear */
2977 o_addchr(word, SPECIAL_VAR_SYMBOL);
2978 o_addchr(word, SPECIAL_VAR_SYMBOL);
2981 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2982 debug_print_strings("word appended to argv", command->argv);
2985 #if ENABLE_HUSH_LOOPS
2986 if (ctx->ctx_res_w == RES_FOR) {
2987 if (word->has_quoted_part
2988 || !is_well_formed_var_name(command->argv[0], '\0')
2990 /* bash says just "not a valid identifier" */
2991 syntax_error("not a valid identifier in for");
2994 /* Force FOR to have just one word (variable name) */
2995 /* NB: basically, this makes hush see "for v in ..."
2996 * syntax as if it is "for v; in ...". FOR and IN become
2997 * two pipe structs in parse tree. */
2998 done_pipe(ctx, PIPE_SEQ);
3001 #if ENABLE_HUSH_CASE
3002 /* Force CASE to have just one word */
3003 if (ctx->ctx_res_w == RES_CASE) {
3004 done_pipe(ctx, PIPE_SEQ);
3008 o_reset_to_empty_unquoted(word);
3010 debug_printf_parse("done_word return 0\n");
3015 /* Peek ahead in the input to find out if we have a "&n" construct,
3016 * as in "2>&1", that represents duplicating a file descriptor.
3018 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3019 * REDIRFD_SYNTAX_ERR if syntax error,
3020 * REDIRFD_TO_FILE if no & was seen,
3021 * or the number found.
3024 #define parse_redir_right_fd(as_string, input) \
3025 parse_redir_right_fd(input)
3027 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3033 return REDIRFD_TO_FILE;
3035 ch = i_getch(input); /* get the & */
3036 nommu_addchr(as_string, ch);
3039 ch = i_getch(input);
3040 nommu_addchr(as_string, ch);
3041 return REDIRFD_CLOSE;
3045 while (ch != EOF && isdigit(ch)) {
3046 d = d*10 + (ch-'0');
3048 ch = i_getch(input);
3049 nommu_addchr(as_string, ch);
3054 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3056 bb_error_msg("ambiguous redirect");
3057 return REDIRFD_SYNTAX_ERR;
3060 /* Return code is 0 normal, 1 if a syntax error is detected
3062 static int parse_redirect(struct parse_context *ctx,
3065 struct in_str *input)
3067 struct command *command = ctx->command;
3068 struct redir_struct *redir;
3069 struct redir_struct **redirp;
3072 dup_num = REDIRFD_TO_FILE;
3073 if (style != REDIRECT_HEREDOC) {
3074 /* Check for a '>&1' type redirect */
3075 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3076 if (dup_num == REDIRFD_SYNTAX_ERR)
3079 int ch = i_peek(input);
3080 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3081 if (dup_num) { /* <<-... */
3082 ch = i_getch(input);
3083 nommu_addchr(&ctx->as_string, ch);
3088 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3089 int ch = i_peek(input);
3091 /* >|FILE redirect ("clobbering" >).
3092 * Since we do not support "set -o noclobber" yet,
3093 * >| and > are the same for now. Just eat |.
3095 ch = i_getch(input);
3096 nommu_addchr(&ctx->as_string, ch);
3100 /* Create a new redir_struct and append it to the linked list */
3101 redirp = &command->redirects;
3102 while ((redir = *redirp) != NULL) {
3103 redirp = &(redir->next);
3105 *redirp = redir = xzalloc(sizeof(*redir));
3106 /* redir->next = NULL; */
3107 /* redir->rd_filename = NULL; */
3108 redir->rd_type = style;
3109 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3111 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3112 redir_table[style].descrip);
3114 redir->rd_dup = dup_num;
3115 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3116 /* Erik had a check here that the file descriptor in question
3117 * is legit; I postpone that to "run time"
3118 * A "-" representation of "close me" shows up as a -3 here */
3119 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3120 redir->rd_fd, redir->rd_dup);
3122 /* Set ctx->pending_redirect, so we know what to do at the
3123 * end of the next parsed word. */
3124 ctx->pending_redirect = redir;
3129 /* If a redirect is immediately preceded by a number, that number is
3130 * supposed to tell which file descriptor to redirect. This routine
3131 * looks for such preceding numbers. In an ideal world this routine
3132 * needs to handle all the following classes of redirects...
3133 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3134 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3135 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3136 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3138 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3140 * ... If n is quoted, the number shall not be recognized as part of
3141 * the redirection expression. For example:
3143 * writes the character 2 into file a"
3144 * We are getting it right by setting ->has_quoted_part on any \<char>
3146 * A -1 return means no valid number was found,
3147 * the caller should use the appropriate default for this redirection.
3149 static int redirect_opt_num(o_string *o)
3153 if (o->data == NULL)
3155 num = bb_strtou(o->data, NULL, 10);
3156 if (errno || num < 0)
3158 o_reset_to_empty_unquoted(o);
3163 #define fetch_till_str(as_string, input, word, skip_tabs) \
3164 fetch_till_str(input, word, skip_tabs)
3166 static char *fetch_till_str(o_string *as_string,
3167 struct in_str *input,
3171 o_string heredoc = NULL_O_STRING;
3173 int prev = 0; /* not \ */
3178 ch = i_getch(input);
3180 nommu_addchr(as_string, ch);
3181 if ((ch == '\n' || ch == EOF)
3182 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3184 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3185 heredoc.data[past_EOL] = '\0';
3186 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3187 return heredoc.data;
3189 while (ch == '\n') {
3190 o_addchr(&heredoc, ch);
3193 past_EOL = heredoc.length;
3195 ch = i_getch(input);
3197 nommu_addchr(as_string, ch);
3198 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3202 o_free_unsafe(&heredoc);
3205 o_addchr(&heredoc, ch);
3206 nommu_addchr(as_string, ch);
3207 if (prev == '\\' && ch == '\\')
3208 /* Correctly handle foo\\<eol> (not a line cont.) */
3209 prev = 0; /* not \ */
3215 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3216 * and load them all. There should be exactly heredoc_cnt of them.
3218 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3220 struct pipe *pi = ctx->list_head;
3222 while (pi && heredoc_cnt) {
3224 struct command *cmd = pi->cmds;
3226 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3228 cmd->argv ? cmd->argv[0] : "NONE");
3229 for (i = 0; i < pi->num_cmds; i++) {
3230 struct redir_struct *redir = cmd->redirects;
3232 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3233 i, cmd->argv ? cmd->argv[0] : "NONE");
3235 if (redir->rd_type == REDIRECT_HEREDOC) {
3238 redir->rd_type = REDIRECT_HEREDOC2;
3239 /* redir->rd_dup is (ab)used to indicate <<- */
3240 p = fetch_till_str(&ctx->as_string, input,
3241 redir->rd_filename, redir->rd_dup);
3243 syntax_error("unexpected EOF in here document");
3246 free(redir->rd_filename);
3247 redir->rd_filename = p;
3250 redir = redir->next;
3257 /* Should be 0. If it isn't, it's a parse error */
3259 bb_error_msg_and_die("heredoc BUG 2");
3265 static int run_list(struct pipe *pi);
3267 #define parse_stream(pstring, input, end_trigger) \
3268 parse_stream(input, end_trigger)
3270 static struct pipe *parse_stream(char **pstring,
3271 struct in_str *input,
3275 #if !ENABLE_HUSH_FUNCTIONS
3276 #define parse_group(dest, ctx, input, ch) \
3277 parse_group(ctx, input, ch)
3279 static int parse_group(o_string *dest, struct parse_context *ctx,
3280 struct in_str *input, int ch)
3282 /* dest contains characters seen prior to ( or {.
3283 * Typically it's empty, but for function defs,
3284 * it contains function name (without '()'). */
3285 struct pipe *pipe_list;
3287 struct command *command = ctx->command;
3289 debug_printf_parse("parse_group entered\n");
3290 #if ENABLE_HUSH_FUNCTIONS
3291 if (ch == '(' && !dest->has_quoted_part) {
3293 if (done_word(dest, ctx))
3296 goto skip; /* (... */
3297 if (command->argv[1]) { /* word word ... (... */
3298 syntax_error_unexpected_ch('(');
3301 /* it is "word(..." or "word (..." */
3303 ch = i_getch(input);
3304 while (ch == ' ' || ch == '\t');
3306 syntax_error_unexpected_ch(ch);
3309 nommu_addchr(&ctx->as_string, ch);
3311 ch = i_getch(input);
3312 while (ch == ' ' || ch == '\t' || ch == '\n');
3314 syntax_error_unexpected_ch(ch);
3317 nommu_addchr(&ctx->as_string, ch);
3318 command->cmd_type = CMD_FUNCDEF;
3323 #if 0 /* Prevented by caller */
3324 if (command->argv /* word [word]{... */
3325 || dest->length /* word{... */
3326 || dest->has_quoted_part /* ""{... */
3329 debug_printf_parse("parse_group return 1: "
3330 "syntax error, groups and arglists don't mix\n");
3335 #if ENABLE_HUSH_FUNCTIONS
3341 command->cmd_type = CMD_SUBSHELL;
3343 /* bash does not allow "{echo...", requires whitespace */
3344 ch = i_getch(input);
3345 if (ch != ' ' && ch != '\t' && ch != '\n') {
3346 syntax_error_unexpected_ch(ch);
3349 nommu_addchr(&ctx->as_string, ch);
3354 # define as_string NULL
3356 char *as_string = NULL;
3358 pipe_list = parse_stream(&as_string, input, endch);
3361 o_addstr(&ctx->as_string, as_string);
3363 /* empty ()/{} or parse error? */
3364 if (!pipe_list || pipe_list == ERR_PTR) {
3365 /* parse_stream already emitted error msg */
3368 debug_printf_parse("parse_group return 1: "
3369 "parse_stream returned %p\n", pipe_list);
3372 command->group = pipe_list;
3374 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3375 command->group_as_string = as_string;
3376 debug_printf_parse("end of group, remembering as:'%s'\n",
3377 command->group_as_string);
3381 debug_printf_parse("parse_group return 0\n");
3383 /* command remains "open", available for possible redirects */
3386 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3387 /* Subroutines for copying $(...) and `...` things */
3388 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3390 static void add_till_single_quote(o_string *dest, struct in_str *input)
3393 int ch = i_getch(input);
3395 syntax_error_unterm_ch('\'');
3396 /*xfunc_die(); - redundant */
3403 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3404 static void add_till_double_quote(o_string *dest, struct in_str *input)
3407 int ch = i_getch(input);
3409 syntax_error_unterm_ch('"');
3410 /*xfunc_die(); - redundant */
3414 if (ch == '\\') { /* \x. Copy both chars. */
3416 ch = i_getch(input);
3420 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3424 //if (ch == '$') ...
3427 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3429 * "Within the backquoted style of command substitution, backslash
3430 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3431 * The search for the matching backquote shall be satisfied by the first
3432 * backquote found without a preceding backslash; during this search,
3433 * if a non-escaped backquote is encountered within a shell comment,
3434 * a here-document, an embedded command substitution of the $(command)
3435 * form, or a quoted string, undefined results occur. A single-quoted
3436 * or double-quoted string that begins, but does not end, within the
3437 * "`...`" sequence produces undefined results."
3439 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3441 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3444 int ch = i_getch(input);
3448 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3449 ch = i_getch(input);
3453 && (!in_dquote || ch != '"')
3455 o_addchr(dest, '\\');
3459 syntax_error_unterm_ch('`');
3460 /*xfunc_die(); - redundant */
3465 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3466 * quoting and nested ()s.
3467 * "With the $(command) style of command substitution, all characters
3468 * following the open parenthesis to the matching closing parenthesis
3469 * constitute the command. Any valid shell script can be used for command,
3470 * except a script consisting solely of redirections which produces
3471 * unspecified results."
3473 * echo $(echo '(TEST)' BEST) (TEST) BEST
3474 * echo $(echo 'TEST)' BEST) TEST) BEST
3475 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3477 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3478 * can contain arbitrary constructs, just like $(cmd).
3479 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3480 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3482 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3483 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3486 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3487 # if ENABLE_HUSH_BASH_COMPAT
3488 char end_char2 = end_ch >> 8;
3490 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3493 ch = i_getch(input);
3495 syntax_error_unterm_ch(end_ch);
3496 /*xfunc_die(); - redundant */
3498 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3501 /* we look for closing )) of $((EXPR)) */
3502 if (i_peek(input) == end_ch) {
3503 i_getch(input); /* eat second ')' */
3508 if (ch == '(' || ch == '{') {
3509 ch = (ch == '(' ? ')' : '}');
3510 add_till_closing_bracket(dest, input, ch);
3515 add_till_single_quote(dest, input);
3520 add_till_double_quote(dest, input);
3525 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3530 /* \x. Copy verbatim. Important for \(, \) */
3531 ch = i_getch(input);
3533 syntax_error_unterm_ch(')');
3534 /*xfunc_die(); - redundant */
3542 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3544 /* Return code: 0 for OK, 1 for syntax error */
3546 #define parse_dollar(as_string, dest, input, quote_mask) \
3547 parse_dollar(dest, input, quote_mask)
3548 #define as_string NULL
3550 static int parse_dollar(o_string *as_string,
3552 struct in_str *input, unsigned char quote_mask)
3554 int ch = i_peek(input); /* first character after the $ */
3556 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3558 ch = i_getch(input);
3559 nommu_addchr(as_string, ch);
3561 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3563 debug_printf_parse(": '%c'\n", ch);
3564 o_addchr(dest, ch | quote_mask);
3567 if (!isalnum(ch) && ch != '_')
3569 ch = i_getch(input);
3570 nommu_addchr(as_string, ch);
3572 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3573 } else if (isdigit(ch)) {
3575 ch = i_getch(input);
3576 nommu_addchr(as_string, ch);
3577 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3578 debug_printf_parse(": '%c'\n", ch);
3579 o_addchr(dest, ch | quote_mask);
3580 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3581 } else switch (ch) {
3583 case '!': /* last bg pid */
3584 case '?': /* last exit code */
3585 case '#': /* number of args */
3586 case '*': /* args */
3587 case '@': /* args */
3588 goto make_one_char_var;
3590 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3592 ch = i_getch(input); /* eat '{' */
3593 nommu_addchr(as_string, ch);
3595 ch = i_getch(input); /* first char after '{' */
3596 /* It should be ${?}, or ${#var},
3597 * or even ${?+subst} - operator acting on a special variable,
3598 * or the beginning of variable name.
3601 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3604 syntax_error_unterm_str("${name}");
3605 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3608 nommu_addchr(as_string, ch);
3611 /* It's possible to just call add_till_closing_bracket() at this point.
3612 * However, this regresses some of our testsuite cases
3613 * which check invalid constructs like ${%}.
3614 * Oh well... let's check that the var name part is fine... */
3620 debug_printf_parse(": '%c'\n", ch);
3622 ch = i_getch(input);
3623 nommu_addchr(as_string, ch);
3627 if (!isalnum(ch) && ch != '_') {
3629 unsigned char last_ch;
3630 /* handle parameter expansions
3631 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3633 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3634 goto bad_dollar_syntax;
3636 /* Eat everything until closing '}' (or ':') */
3638 if (ENABLE_HUSH_BASH_COMPAT
3640 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3642 /* It's ${var:N[:M]} thing */
3643 end_ch = '}' * 0x100 + ':';
3645 if (ENABLE_HUSH_BASH_COMPAT
3648 /* It's ${var/[/]pattern[/repl]} thing */
3649 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3651 nommu_addchr(as_string, '/');
3654 end_ch = '}' * 0x100 + '/';
3660 #if ENABLE_HUSH_DOLLAR_OPS
3661 last_ch = add_till_closing_bracket(dest, input, end_ch);
3663 #error Simple code to only allow ${var} is not implemented
3666 o_addstr(as_string, dest->data + pos);
3667 o_addchr(as_string, last_ch);
3670 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3671 /* close the first block: */
3672 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3673 /* while parsing N from ${var:N[:M]}
3674 * or pattern from ${var/[/]pattern[/repl]} */
3675 if ((end_ch & 0xff) == last_ch) {
3676 /* got ':' or '/'- parse the rest */
3681 if (end_ch == '}' * 0x100 + ':') {
3682 /* it's ${var:N} - emulate :999999999 */
3683 o_addstr(dest, "999999999");
3684 } /* else: it's ${var/[/]pattern} */
3689 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3692 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3696 ch = i_getch(input);
3697 nommu_addchr(as_string, ch);
3698 # if ENABLE_SH_MATH_SUPPORT
3699 if (i_peek(input) == '(') {
3700 ch = i_getch(input);
3701 nommu_addchr(as_string, ch);
3702 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3703 o_addchr(dest, /*quote_mask |*/ '+');
3706 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3708 o_addstr(as_string, dest->data + pos);
3709 o_addchr(as_string, ')');
3710 o_addchr(as_string, ')');
3712 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3716 # if ENABLE_HUSH_TICK
3717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3718 o_addchr(dest, quote_mask | '`');
3721 add_till_closing_bracket(dest, input, ')');
3723 o_addstr(as_string, dest->data + pos);
3724 o_addchr(as_string, ')');
3726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3732 ch = i_getch(input);
3733 nommu_addchr(as_string, ch);
3735 if (isalnum(ch)) { /* it's $_name or $_123 */
3740 /* TODO: $_ and $-: */
3741 /* $_ Shell or shell script name; or last argument of last command
3742 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3743 * but in command's env, set to full pathname used to invoke it */
3744 /* $- Option flags set by set builtin or shell options (-i etc) */
3746 o_addQchr(dest, '$');
3748 debug_printf_parse("parse_dollar return 0\n");
3754 # if ENABLE_HUSH_BASH_COMPAT
3755 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3756 encode_string(dest, input, dquote_end, process_bkslash)
3758 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3759 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3760 encode_string(dest, input, dquote_end)
3762 #define as_string NULL
3766 # if ENABLE_HUSH_BASH_COMPAT
3767 /* all parameters are needed, no macro tricks */
3769 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3770 encode_string(as_string, dest, input, dquote_end)
3773 static int encode_string(o_string *as_string,
3775 struct in_str *input,
3777 int process_bkslash)
3779 #if !ENABLE_HUSH_BASH_COMPAT
3780 const int process_bkslash = 1;
3786 ch = i_getch(input);
3788 nommu_addchr(as_string, ch);
3789 if (ch == dquote_end) { /* may be only '"' or EOF */
3790 debug_printf_parse("encode_string return 0\n");
3793 /* note: can't move it above ch == dquote_end check! */
3795 syntax_error_unterm_ch('"');
3796 /*xfunc_die(); - redundant */
3800 next = i_peek(input);
3802 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3803 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3804 if (process_bkslash && ch == '\\') {
3806 syntax_error("\\<eof>");
3810 * "The backslash retains its special meaning [in "..."]
3811 * only when followed by one of the following characters:
3812 * $, `, ", \, or <newline>. A double quote may be quoted
3813 * within double quotes by preceding it with a backslash."
3814 * NB: in (unquoted) heredoc, above does not apply to ",
3815 * therefore we check for it by "next == dquote_end" cond.
3817 if (next == dquote_end || strchr("$`\\\n", next)) {
3818 ch = i_getch(input); /* eat next */
3820 goto again; /* skip \<newline> */
3821 } /* else: ch remains == '\\', and we double it below: */
3822 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3823 nommu_addchr(as_string, ch);
3827 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3828 debug_printf_parse("encode_string return 1: "
3829 "parse_dollar returned non-0\n");
3834 #if ENABLE_HUSH_TICK
3836 //unsigned pos = dest->length;
3837 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3838 o_addchr(dest, 0x80 | '`');
3839 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3840 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3841 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3845 o_addQchr(dest, ch);
3851 * Scan input until EOF or end_trigger char.
3852 * Return a list of pipes to execute, or NULL on EOF
3853 * or if end_trigger character is met.
3854 * On syntax error, exit is shell is not interactive,
3855 * reset parsing machinery and start parsing anew,
3856 * or return ERR_PTR.
3858 static struct pipe *parse_stream(char **pstring,
3859 struct in_str *input,
3862 struct parse_context ctx;
3863 o_string dest = NULL_O_STRING;
3866 /* Single-quote triggers a bypass of the main loop until its mate is
3867 * found. When recursing, quote state is passed in via dest->o_expflags.
3869 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3870 end_trigger ? end_trigger : 'X');
3873 /* If very first arg is "" or '', dest.data may end up NULL.
3874 * Preventing this: */
3875 o_addchr(&dest, '\0');
3878 /* We used to separate words on $IFS here. This was wrong.
3879 * $IFS is used only for word splitting when $var is expanded,
3880 * here we should use blank chars as separators, not $IFS
3883 reset: /* we come back here only on syntax errors in interactive shell */
3885 #if ENABLE_HUSH_INTERACTIVE
3886 input->promptmode = 0; /* PS1 */
3888 if (MAYBE_ASSIGNMENT != 0)
3889 dest.o_assignment = MAYBE_ASSIGNMENT;
3890 initialize_context(&ctx);
3893 const char *is_blank;
3894 const char *is_special;
3898 redir_type redir_style;
3900 ch = i_getch(input);
3901 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3902 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3907 syntax_error_unterm_str("here document");
3910 /* end_trigger == '}' case errors out earlier,
3911 * checking only ')' */
3912 if (end_trigger == ')') {
3913 syntax_error_unterm_ch('('); /* exits */
3914 /* goto parse_error; */
3917 if (done_word(&dest, &ctx)) {
3921 done_pipe(&ctx, PIPE_SEQ);
3923 /* If we got nothing... */
3924 /* (this makes bare "&" cmd a no-op.
3925 * bash says: "syntax error near unexpected token '&'") */
3926 if (pi->num_cmds == 0
3927 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3933 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3935 *pstring = ctx.as_string.data;
3937 o_free_unsafe(&ctx.as_string);
3940 debug_printf_parse("parse_stream return %p\n", pi);
3943 nommu_addchr(&ctx.as_string, ch);
3947 next = i_peek(input);
3949 is_special = "{}<>;&|()#'" /* special outside of "str" */
3950 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3951 /* Are { and } special here? */
3952 if (ctx.command->argv /* word [word]{... - non-special */
3953 || dest.length /* word{... - non-special */
3954 || dest.has_quoted_part /* ""{... - non-special */
3955 || (next != ';' /* }; - special */
3956 && next != ')' /* }) - special */
3957 && next != '&' /* }& and }&& ... - special */
3958 && next != '|' /* }|| ... - special */
3959 && !strchr(defifs, next) /* {word - non-special */
3962 /* They are not special, skip "{}" */
3965 is_special = strchr(is_special, ch);
3966 is_blank = strchr(defifs, ch);
3968 if (!is_special && !is_blank) { /* ordinary char */
3970 o_addQchr(&dest, ch);
3971 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3972 || dest.o_assignment == WORD_IS_KEYWORD)
3974 && is_well_formed_var_name(dest.data, '=')
3976 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3982 if (done_word(&dest, &ctx)) {
3986 #if ENABLE_HUSH_CASE
3987 /* "case ... in <newline> word) ..." -
3988 * newlines are ignored (but ';' wouldn't be) */
3989 if (ctx.command->argv == NULL
3990 && ctx.ctx_res_w == RES_MATCH
3995 /* Treat newline as a command separator. */
3996 done_pipe(&ctx, PIPE_SEQ);
3997 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3999 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4004 dest.o_assignment = MAYBE_ASSIGNMENT;
4006 /* note: if (is_blank) continue;
4007 * will still trigger for us */
4011 /* "cmd}" or "cmd }..." without semicolon or &:
4012 * } is an ordinary char in this case, even inside { cmd; }
4013 * Pathological example: { ""}; } should exec "}" cmd
4016 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4017 || dest.length != 0 /* word} */
4018 || dest.has_quoted_part /* ""} */
4022 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4023 goto skip_end_trigger;
4024 /* else: } does terminate a group */
4027 if (end_trigger && end_trigger == ch
4028 && (ch != ';' || heredoc_cnt == 0)
4029 #if ENABLE_HUSH_CASE
4031 || ctx.ctx_res_w != RES_MATCH
4032 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4037 /* This is technically valid:
4038 * { cat <<HERE; }; echo Ok
4042 * but we don't support this.
4043 * We require heredoc to be in enclosing {}/(),
4046 syntax_error_unterm_str("here document");
4049 if (done_word(&dest, &ctx)) {
4052 done_pipe(&ctx, PIPE_SEQ);
4053 dest.o_assignment = MAYBE_ASSIGNMENT;
4054 /* Do we sit outside of any if's, loops or case's? */
4056 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4060 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4062 *pstring = ctx.as_string.data;
4064 o_free_unsafe(&ctx.as_string);
4067 debug_printf_parse("parse_stream return %p: "
4068 "end_trigger char found\n",
4070 return ctx.list_head;
4077 /* Catch <, > before deciding whether this word is
4078 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4081 redir_fd = redirect_opt_num(&dest);
4082 if (done_word(&dest, &ctx)) {
4085 redir_style = REDIRECT_OVERWRITE;
4087 redir_style = REDIRECT_APPEND;
4088 ch = i_getch(input);
4089 nommu_addchr(&ctx.as_string, ch);
4092 else if (next == '(') {
4093 syntax_error(">(process) not supported");
4097 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4099 continue; /* back to top of while (1) */
4101 redir_fd = redirect_opt_num(&dest);
4102 if (done_word(&dest, &ctx)) {
4105 redir_style = REDIRECT_INPUT;
4107 redir_style = REDIRECT_HEREDOC;
4109 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4110 ch = i_getch(input);
4111 nommu_addchr(&ctx.as_string, ch);
4112 } else if (next == '>') {
4113 redir_style = REDIRECT_IO;
4114 ch = i_getch(input);
4115 nommu_addchr(&ctx.as_string, ch);
4118 else if (next == '(') {
4119 syntax_error("<(process) not supported");
4123 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4125 continue; /* back to top of while (1) */
4128 if (dest.o_assignment == MAYBE_ASSIGNMENT
4129 /* check that we are not in word in "a=1 2>word b=1": */
4130 && !ctx.pending_redirect
4132 /* ch is a special char and thus this word
4133 * cannot be an assignment */
4134 dest.o_assignment = NOT_ASSIGNMENT;
4137 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4141 if (dest.length == 0) {
4144 if (ch == EOF || ch == '\n')
4147 /* note: we do not add it to &ctx.as_string */
4149 nommu_addchr(&ctx.as_string, '\n');
4151 o_addQchr(&dest, ch);
4156 syntax_error("\\<eof>");
4159 ch = i_getch(input);
4161 o_addchr(&dest, '\\');
4162 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4163 o_addchr(&dest, ch);
4164 nommu_addchr(&ctx.as_string, ch);
4165 /* Example: echo Hello \2>file
4166 * we need to know that word 2 is quoted */
4167 dest.has_quoted_part = 1;
4171 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4172 ctx.as_string.data[--ctx.as_string.length] = '\0';
4177 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4178 debug_printf_parse("parse_stream parse error: "
4179 "parse_dollar returned non-0\n");
4184 dest.has_quoted_part = 1;
4186 ch = i_getch(input);
4188 syntax_error_unterm_ch('\'');
4189 /*xfunc_die(); - redundant */
4191 nommu_addchr(&ctx.as_string, ch);
4194 o_addqchr(&dest, ch);
4198 dest.has_quoted_part = 1;
4199 if (dest.o_assignment == NOT_ASSIGNMENT)
4200 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4201 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4203 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4205 #if ENABLE_HUSH_TICK
4209 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4210 o_addchr(&dest, '`');
4212 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
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 #if !ENABLE_HUSH_BASH_COMPAT
4375 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4376 #define expand_string_to_string(str, do_unbackslash) \
4377 expand_string_to_string(str)
4379 static char *expand_string_to_string(const char *str, int do_unbackslash);
4380 static int process_command_subs(o_string *dest, const char *s);
4382 /* expand_strvec_to_strvec() takes a list of strings, expands
4383 * all variable references within and returns a pointer to
4384 * a list of expanded strings, possibly with larger number
4385 * of strings. (Think VAR="a b"; echo $VAR).
4386 * This new list is allocated as a single malloc block.
4387 * NULL-terminated list of char* pointers is at the beginning of it,
4388 * followed by strings themselves.
4389 * Caller can deallocate entire list by single free(list). */
4391 /* Store given string, finalizing the word and starting new one whenever
4392 * we encounter IFS char(s). This is used for expanding variable values.
4393 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4394 static int expand_on_ifs(o_string *output, int n, const char *str)
4397 int word_len = strcspn(str, G.ifs);
4399 if (!(output->o_expflags & EXP_FLAG_GLOB))
4400 o_addblock(output, str, word_len);
4402 /* Protect backslashes against globbing up :)
4403 * Example: "v='\*'; echo b$v" prints "b\*"
4404 * (and does not try to glob on "*")
4406 o_addblock_duplicate_backslash(output, str, word_len);
4407 /*/ Why can't we do it easier? */
4408 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4409 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4413 if (!*str) /* EOL - do not finalize word */
4415 o_addchr(output, '\0');
4416 debug_print_list("expand_on_ifs", output, n);
4417 n = o_save_ptr(output, n);
4418 str += strspn(str, G.ifs); /* skip ifs chars */
4420 debug_print_list("expand_on_ifs[1]", output, n);
4424 /* Helper to expand $((...)) and heredoc body. These act as if
4425 * they are in double quotes, with the exception that they are not :).
4426 * Just the rules are similar: "expand only $var and `cmd`"
4428 * Returns malloced string.
4429 * As an optimization, we return NULL if expansion is not needed.
4431 #if !ENABLE_HUSH_BASH_COMPAT
4432 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4433 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4434 encode_then_expand_string(str)
4436 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4439 struct in_str input;
4440 o_string dest = NULL_O_STRING;
4442 if (!strchr(str, '$')
4443 && !strchr(str, '\\')
4444 #if ENABLE_HUSH_TICK
4445 && !strchr(str, '`')
4451 /* We need to expand. Example:
4452 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4454 setup_string_in_str(&input, str);
4455 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4456 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4457 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4458 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4459 o_free_unsafe(&dest);
4463 #if ENABLE_SH_MATH_SUPPORT
4464 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4466 arith_state_t math_state;
4470 math_state.lookupvar = get_local_var_value;
4471 math_state.setvar = set_local_var_from_halves;
4472 //math_state.endofname = endofname;
4473 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4474 res = arith(&math_state, exp_str ? exp_str : arg);
4477 *errmsg_p = math_state.errmsg;
4478 if (math_state.errmsg)
4479 die_if_script(math_state.errmsg);
4484 #if ENABLE_HUSH_BASH_COMPAT
4485 /* ${var/[/]pattern[/repl]} helpers */
4486 static char *strstr_pattern(char *val, const char *pattern, int *size)
4489 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4490 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4497 /* Optimization: if "*pat" did not match the start of "string",
4498 * we know that "tring", "ring" etc will not match too:
4500 if (pattern[0] == '*')
4505 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4507 char *result = NULL;
4508 unsigned res_len = 0;
4509 unsigned repl_len = strlen(repl);
4513 char *s = strstr_pattern(val, pattern, &size);
4517 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4518 memcpy(result + res_len, val, s - val);
4520 strcpy(result + res_len, repl);
4521 res_len += repl_len;
4522 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4528 if (val[0] && result) {
4529 result = xrealloc(result, res_len + strlen(val) + 1);
4530 strcpy(result + res_len, val);
4531 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4533 debug_printf_varexp("result:'%s'\n", result);
4539 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4541 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4543 const char *val = NULL;
4544 char *to_be_freed = NULL;
4549 char exp_save = exp_save; /* for compiler */
4550 char *exp_saveptr; /* points to expansion operator */
4551 char *exp_word = exp_word; /* for compiler */
4554 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4556 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4558 first_char = arg[0] = arg0 & 0x7f;
4561 if (first_char == '#' /* ${#... */
4562 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4564 /* It must be length operator: ${#var} */
4568 /* Maybe handle parameter expansion */
4569 if (exp_saveptr /* if 2nd char is one of expansion operators */
4570 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4572 /* ${?:0}, ${#[:]%0} etc */
4573 exp_saveptr = var + 1;
4575 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4576 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4578 exp_op = exp_save = *exp_saveptr;
4580 exp_word = exp_saveptr + 1;
4581 if (exp_op == ':') {
4582 exp_op = *exp_word++;
4583 //TODO: try ${var:} and ${var:bogus} in non-bash config
4584 if (ENABLE_HUSH_BASH_COMPAT
4585 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4587 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4592 *exp_saveptr = '\0';
4593 } /* else: it's not an expansion op, but bare ${var} */
4596 /* Look up the variable in question */
4597 if (isdigit(var[0])) {
4598 /* parse_dollar should have vetted var for us */
4599 int n = xatoi_positive(var);
4600 if (n < G.global_argc)
4601 val = G.global_argv[n];
4602 /* else val remains NULL: $N with too big N */
4606 val = utoa(G.root_pid);
4608 case '!': /* bg pid */
4609 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4611 case '?': /* exitcode */
4612 val = utoa(G.last_exitcode);
4614 case '#': /* argc */
4615 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4618 val = get_local_var_value(var);
4622 /* Handle any expansions */
4623 if (exp_op == 'L') {
4624 debug_printf_expand("expand: length(%s)=", val);
4625 val = utoa(val ? strlen(val) : 0);
4626 debug_printf_expand("%s\n", val);
4627 } else if (exp_op) {
4628 if (exp_op == '%' || exp_op == '#') {
4629 /* Standard-mandated substring removal ops:
4630 * ${parameter%word} - remove smallest suffix pattern
4631 * ${parameter%%word} - remove largest suffix pattern
4632 * ${parameter#word} - remove smallest prefix pattern
4633 * ${parameter##word} - remove largest prefix pattern
4635 * Word is expanded to produce a glob pattern.
4636 * Then var's value is matched to it and matching part removed.
4638 if (val && val[0]) {
4642 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4643 if (exp_op == *exp_word) /* ## or %% */
4645 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4647 exp_word = exp_exp_word;
4648 /* HACK ALERT. We depend here on the fact that
4649 * G.global_argv and results of utoa and get_local_var_value
4650 * are actually in writable memory:
4651 * scan_and_match momentarily stores NULs there. */
4653 loc = scan_and_match(t, exp_word, scan_flags);
4654 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4655 // exp_op, t, exp_word, loc);
4657 if (loc) { /* match was found */
4658 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4659 val = loc; /* take right part */
4661 val = to_be_freed = xstrndup(val, loc - val); /* left */
4665 #if ENABLE_HUSH_BASH_COMPAT
4666 else if (exp_op == '/' || exp_op == '\\') {
4667 /* It's ${var/[/]pattern[/repl]} thing.
4668 * Note that in encoded form it has TWO parts:
4669 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4670 * and if // is used, it is encoded as \:
4671 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4673 /* Empty variable always gives nothing: */
4674 // "v=''; echo ${v/*/w}" prints "", not "w"
4675 if (val && val[0]) {
4676 /* pattern uses non-standard expansion.
4677 * repl should be unbackslashed and globbed
4678 * by the usual expansion rules:
4680 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4681 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4682 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4683 * v='a bz'; echo ${v/a*z/\z} prints "z"
4684 * (note that a*z _pattern_ is never globbed!)
4686 char *pattern, *repl, *t;
4687 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4689 pattern = xstrdup(exp_word);
4690 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4691 *p++ = SPECIAL_VAR_SYMBOL;
4693 p = strchr(p, SPECIAL_VAR_SYMBOL);
4695 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4696 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4697 /* HACK ALERT. We depend here on the fact that
4698 * G.global_argv and results of utoa and get_local_var_value
4699 * are actually in writable memory:
4700 * replace_pattern momentarily stores NULs there. */
4702 to_be_freed = replace_pattern(t,
4704 (repl ? repl : exp_word),
4706 if (to_be_freed) /* at least one replace happened */
4713 else if (exp_op == ':') {
4714 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4715 /* It's ${var:N[:M]} bashism.
4716 * Note that in encoded form it has TWO parts:
4717 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4722 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4725 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4726 *p++ = SPECIAL_VAR_SYMBOL;
4728 p = strchr(p, SPECIAL_VAR_SYMBOL);
4730 len = expand_and_evaluate_arith(exp_word, &errmsg);
4733 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4734 if (len >= 0) { /* bash compat: len < 0 is illegal */
4735 if (beg < 0) /* bash compat */
4737 debug_printf_varexp("from val:'%s'\n", val);
4738 if (len == 0 || !val || beg >= strlen(val)) {
4742 /* Paranoia. What if user entered 9999999999999
4743 * which fits in arith_t but not int? */
4746 val = to_be_freed = xstrndup(val + beg, len);
4748 debug_printf_varexp("val:'%s'\n", val);
4752 die_if_script("malformed ${%s:...}", var);
4755 } else { /* one of "-=+?" */
4756 /* Standard-mandated substitution ops:
4757 * ${var?word} - indicate error if unset
4758 * If var is unset, word (or a message indicating it is unset
4759 * if word is null) is written to standard error
4760 * and the shell exits with a non-zero exit status.
4761 * Otherwise, the value of var is substituted.
4762 * ${var-word} - use default value
4763 * If var is unset, word is substituted.
4764 * ${var=word} - assign and use default value
4765 * If var is unset, word is assigned to var.
4766 * In all cases, final value of var is substituted.
4767 * ${var+word} - use alternative value
4768 * If var is unset, null is substituted.
4769 * Otherwise, word is substituted.
4771 * Word is subjected to tilde expansion, parameter expansion,
4772 * command substitution, and arithmetic expansion.
4773 * If word is not needed, it is not expanded.
4775 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4776 * but also treat null var as if it is unset.
4778 int use_word = (!val || ((exp_save == ':') && !val[0]));
4780 use_word = !use_word;
4781 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4782 (exp_save == ':') ? "true" : "false", use_word);
4784 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4786 exp_word = to_be_freed;
4787 if (exp_op == '?') {
4788 /* mimic bash message */
4789 die_if_script("%s: %s",
4791 exp_word[0] ? exp_word : "parameter null or not set"
4793 //TODO: how interactive bash aborts expansion mid-command?
4798 if (exp_op == '=') {
4799 /* ${var=[word]} or ${var:=[word]} */
4800 if (isdigit(var[0]) || var[0] == '#') {
4801 /* mimic bash message */
4802 die_if_script("$%s: cannot assign in this way", var);
4805 char *new_var = xasprintf("%s=%s", var, val);
4806 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4810 } /* one of "-=+?" */
4812 *exp_saveptr = exp_save;
4818 *to_be_freed_pp = to_be_freed;
4822 /* Expand all variable references in given string, adding words to list[]
4823 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4824 * to be filled). This routine is extremely tricky: has to deal with
4825 * variables/parameters with whitespace, $* and $@, and constructs like
4826 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4827 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4829 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4830 * expansion of right-hand side of assignment == 1-element expand.
4832 char cant_be_null = 0; /* only bit 0x80 matters */
4835 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4836 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4837 debug_print_list("expand_vars_to_list", output, n);
4838 n = o_save_ptr(output, n);
4839 debug_print_list("expand_vars_to_list[0]", output, n);
4841 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4843 char *to_be_freed = NULL;
4844 const char *val = NULL;
4845 #if ENABLE_HUSH_TICK
4846 o_string subst_result = NULL_O_STRING;
4848 #if ENABLE_SH_MATH_SUPPORT
4849 char arith_buf[sizeof(arith_t)*3 + 2];
4851 o_addblock(output, arg, p - arg);
4852 debug_print_list("expand_vars_to_list[1]", output, n);
4854 p = strchr(p, SPECIAL_VAR_SYMBOL);
4856 /* Fetch special var name (if it is indeed one of them)
4857 * and quote bit, force the bit on if singleword expansion -
4858 * important for not getting v=$@ expand to many words. */
4859 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4861 /* Is this variable quoted and thus expansion can't be null?
4862 * "$@" is special. Even if quoted, it can still
4863 * expand to nothing (not even an empty string),
4864 * thus it is excluded. */
4865 if ((first_ch & 0x7f) != '@')
4866 cant_be_null |= first_ch;
4868 switch (first_ch & 0x7f) {
4869 /* Highest bit in first_ch indicates that var is double-quoted */
4873 if (!G.global_argv[1])
4876 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4877 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4878 while (G.global_argv[i]) {
4879 n = expand_on_ifs(output, n, G.global_argv[i]);
4880 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4881 if (G.global_argv[i++][0] && G.global_argv[i]) {
4882 /* this argv[] is not empty and not last:
4883 * put terminating NUL, start new word */
4884 o_addchr(output, '\0');
4885 debug_print_list("expand_vars_to_list[2]", output, n);
4886 n = o_save_ptr(output, n);
4887 debug_print_list("expand_vars_to_list[3]", output, n);
4891 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4892 * and in this case should treat it like '$*' - see 'else...' below */
4893 if (first_ch == ('@'|0x80) /* quoted $@ */
4894 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4897 o_addQstr(output, G.global_argv[i]);
4898 if (++i >= G.global_argc)
4900 o_addchr(output, '\0');
4901 debug_print_list("expand_vars_to_list[4]", output, n);
4902 n = o_save_ptr(output, n);
4904 } else { /* quoted $* (or v="$@" case): add as one word */
4906 o_addQstr(output, G.global_argv[i]);
4907 if (!G.global_argv[++i])
4910 o_addchr(output, G.ifs[0]);
4915 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4916 /* "Empty variable", used to make "" etc to not disappear */
4918 cant_be_null = 0x80;
4920 #if ENABLE_HUSH_TICK
4921 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4922 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4924 /* Can't just stuff it into output o_string,
4925 * expanded result may need to be globbed
4926 * and $IFS-splitted */
4927 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4928 G.last_exitcode = process_command_subs(&subst_result, arg);
4929 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4930 val = subst_result.data;
4933 #if ENABLE_SH_MATH_SUPPORT
4934 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4937 arg++; /* skip '+' */
4938 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4939 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4940 res = expand_and_evaluate_arith(arg, NULL);
4941 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
4942 sprintf(arith_buf, ARITH_FMT, res);
4948 val = expand_one_var(&to_be_freed, arg, &p);
4949 IF_HUSH_TICK(store_val:)
4950 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4951 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4952 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4953 if (val && val[0]) {
4954 n = expand_on_ifs(output, n, val);
4957 } else { /* quoted $VAR, val will be appended below */
4958 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4959 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4963 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4965 if (val && val[0]) {
4966 o_addQstr(output, val);
4970 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4971 * Do the check to avoid writing to a const string. */
4972 if (*p != SPECIAL_VAR_SYMBOL)
4973 *p = SPECIAL_VAR_SYMBOL;
4975 #if ENABLE_HUSH_TICK
4976 o_free(&subst_result);
4979 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4982 debug_print_list("expand_vars_to_list[a]", output, n);
4983 /* this part is literal, and it was already pre-quoted
4984 * if needed (much earlier), do not use o_addQstr here! */
4985 o_addstr_with_NUL(output, arg);
4986 debug_print_list("expand_vars_to_list[b]", output, n);
4987 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4988 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
4991 /* allow to reuse list[n] later without re-growth */
4992 output->has_empty_slot = 1;
4994 o_addchr(output, '\0');
5000 static char **expand_variables(char **argv, unsigned expflags)
5004 o_string output = NULL_O_STRING;
5006 output.o_expflags = expflags;
5010 n = expand_vars_to_list(&output, n, *argv);
5013 debug_print_list("expand_variables", &output, n);
5015 /* output.data (malloced in one block) gets returned in "list" */
5016 list = o_finalize_list(&output, n);
5017 debug_print_strings("expand_variables[1]", list);
5021 static char **expand_strvec_to_strvec(char **argv)
5023 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5026 #if ENABLE_HUSH_BASH_COMPAT
5027 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5029 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5033 /* Used for expansion of right hand of assignments,
5034 * $((...)), heredocs, variable espansion parts.
5036 * NB: should NOT do globbing!
5037 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5039 static char *expand_string_to_string(const char *str, int do_unbackslash)
5041 #if !ENABLE_HUSH_BASH_COMPAT
5042 const int do_unbackslash = 1;
5044 char *argv[2], **list;
5046 debug_printf_expand("string_to_string<='%s'\n", str);
5047 /* This is generally an optimization, but it also
5048 * handles "", which otherwise trips over !list[0] check below.
5049 * (is this ever happens that we actually get str="" here?)
5051 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5052 //TODO: Can use on strings with \ too, just unbackslash() them?
5053 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5054 return xstrdup(str);
5057 argv[0] = (char*)str;
5059 list = expand_variables(argv, do_unbackslash
5060 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5061 : EXP_FLAG_SINGLEWORD
5064 if (!list[0] || list[1])
5065 bb_error_msg_and_die("BUG in varexp2");
5066 /* actually, just move string 2*sizeof(char*) bytes back */
5067 overlapping_strcpy((char*)list, list[0]);
5069 unbackslash((char*)list);
5070 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5074 /* Used for "eval" builtin */
5075 static char* expand_strvec_to_string(char **argv)
5079 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5080 /* Convert all NULs to spaces */
5085 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5086 bb_error_msg_and_die("BUG in varexp3");
5087 /* bash uses ' ' regardless of $IFS contents */
5092 overlapping_strcpy((char*)list, list[0]);
5093 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5097 static char **expand_assignments(char **argv, int count)
5102 G.expanded_assignments = p = NULL;
5103 /* Expand assignments into one string each */
5104 for (i = 0; i < count; i++) {
5105 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5107 G.expanded_assignments = NULL;
5114 void re_execute_shell(char ***to_free, const char *s,
5115 char *g_argv0, char **g_argv,
5116 char **builtin_argv) NORETURN;
5118 static void reset_traps_to_defaults(void)
5120 /* This function is always called in a child shell
5121 * after fork (not vfork, NOMMU doesn't use this function).
5126 /* Child shells are not interactive.
5127 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5128 * Testcase: (while :; do :; done) + ^Z should background.
5129 * Same goes for SIGTERM, SIGHUP, SIGINT.
5131 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5132 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5134 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5135 * Stupid. It can be done with *single* &= op, but we can't use
5136 * the fact that G.blocked_set is implemented as a bitmask
5138 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5142 /* Careful. Only if no trap or trap is not "" */
5143 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5144 sigdelset(&G.blocked_set, sig);
5151 /* Our homegrown sig mask is saner to work with :) */
5152 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5154 /* Resetting all traps to default except empty ones */
5155 mask = G.non_DFL_mask;
5156 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5157 if (!G.traps[sig] || !G.traps[sig][0])
5160 G.traps[sig] = NULL;
5161 /* There is no signal for 0 (EXIT) */
5164 /* There was a trap handler, we just removed it.
5165 * But if sig still has non-DFL handling,
5166 * we should not unblock the sig. */
5169 sigdelset(&G.blocked_set, sig);
5171 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5176 static void re_execute_shell(char ***to_free, const char *s,
5177 char *g_argv0, char **g_argv,
5178 char **builtin_argv) NORETURN;
5179 static void re_execute_shell(char ***to_free, const char *s,
5180 char *g_argv0, char **g_argv,
5181 char **builtin_argv)
5183 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5184 /* delims + 2 * (number of bytes in printed hex numbers) */
5185 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5186 char *heredoc_argv[4];
5187 struct variable *cur;
5188 # if ENABLE_HUSH_FUNCTIONS
5189 struct function *funcp;
5193 unsigned long long empty_trap_mask;
5195 if (!g_argv0) { /* heredoc */
5196 argv = heredoc_argv;
5197 argv[0] = (char *) G.argv0_for_re_execing;
5198 argv[1] = (char *) "-<";
5199 argv[2] = (char *) s;
5201 pp = &argv[3]; /* used as pointer to empty environment */
5207 if (pp) while (*pp++)
5210 empty_trap_mask = 0;
5213 for (sig = 1; sig < NSIG; sig++) {
5214 if (G.traps[sig] && !G.traps[sig][0])
5215 empty_trap_mask |= 1LL << sig;
5219 sprintf(param_buf, NOMMU_HACK_FMT
5220 , (unsigned) G.root_pid
5221 , (unsigned) G.root_ppid
5222 , (unsigned) G.last_bg_pid
5223 , (unsigned) G.last_exitcode
5226 IF_HUSH_LOOPS(, G.depth_of_loop)
5228 # undef NOMMU_HACK_FMT
5229 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5230 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5233 for (cur = G.top_var; cur; cur = cur->next) {
5234 if (!cur->flg_export || cur->flg_read_only)
5237 # if ENABLE_HUSH_FUNCTIONS
5238 for (funcp = G.top_func; funcp; funcp = funcp->next)
5244 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5245 *pp++ = (char *) G.argv0_for_re_execing;
5247 for (cur = G.top_var; cur; cur = cur->next) {
5248 if (strcmp(cur->varstr, hush_version_str) == 0)
5250 if (cur->flg_read_only) {
5251 *pp++ = (char *) "-R";
5252 *pp++ = cur->varstr;
5253 } else if (!cur->flg_export) {
5254 *pp++ = (char *) "-V";
5255 *pp++ = cur->varstr;
5258 # if ENABLE_HUSH_FUNCTIONS
5259 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5260 *pp++ = (char *) "-F";
5261 *pp++ = funcp->name;
5262 *pp++ = funcp->body_as_string;
5265 /* We can pass activated traps here. Say, -Tnn:trap_string
5267 * However, POSIX says that subshells reset signals with traps
5269 * I tested bash-3.2 and it not only does that with true subshells
5270 * of the form ( list ), but with any forked children shells.
5271 * I set trap "echo W" WINCH; and then tried:
5273 * { echo 1; sleep 20; echo 2; } &
5274 * while true; do echo 1; sleep 20; echo 2; break; done &
5275 * true | { echo 1; sleep 20; echo 2; } | cat
5277 * In all these cases sending SIGWINCH to the child shell
5278 * did not run the trap. If I add trap "echo V" WINCH;
5279 * _inside_ group (just before echo 1), it works.
5281 * I conclude it means we don't need to pass active traps here.
5282 * Even if we would use signal handlers instead of signal masking
5283 * in order to implement trap handling,
5284 * exec syscall below resets signals to SIG_DFL for us.
5286 *pp++ = (char *) "-c";
5289 while (*++builtin_argv)
5290 *pp++ = *builtin_argv;
5291 *pp++ = (char *) "";
5296 /* *pp = NULL; - is already there */
5300 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5301 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5302 execve(bb_busybox_exec_path, argv, pp);
5303 /* Fallback. Useful for init=/bin/hush usage etc */
5304 if (argv[0][0] == '/')
5305 execve(argv[0], argv, pp);
5306 xfunc_error_retval = 127;
5307 bb_error_msg_and_die("can't re-execute the shell");
5309 #endif /* !BB_MMU */
5312 static int run_and_free_list(struct pipe *pi);
5314 /* Executing from string: eval, sh -c '...'
5315 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5316 * end_trigger controls how often we stop parsing
5317 * NUL: parse all, execute, return
5318 * ';': parse till ';' or newline, execute, repeat till EOF
5320 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5322 /* Why we need empty flag?
5323 * An obscure corner case "false; ``; echo $?":
5324 * empty command in `` should still set $? to 0.
5325 * But we can't just set $? to 0 at the start,
5326 * this breaks "false; echo `echo $?`" case.
5330 struct pipe *pipe_list;
5332 pipe_list = parse_stream(NULL, inp, end_trigger);
5333 if (!pipe_list) { /* EOF */
5335 G.last_exitcode = 0;
5338 debug_print_tree(pipe_list, 0);
5339 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5340 run_and_free_list(pipe_list);
5345 static void parse_and_run_string(const char *s)
5347 struct in_str input;
5348 setup_string_in_str(&input, s);
5349 parse_and_run_stream(&input, '\0');
5352 static void parse_and_run_file(FILE *f)
5354 struct in_str input;
5355 setup_file_in_str(&input, f);
5356 parse_and_run_stream(&input, ';');
5359 #if ENABLE_HUSH_TICK
5360 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5365 char **to_free = NULL;
5369 pid = BB_MMU ? xfork() : xvfork();
5370 if (pid == 0) { /* child */
5371 disable_restore_tty_pgrp_on_exit();
5372 /* Process substitution is not considered to be usual
5373 * 'command execution'.
5374 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5381 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5382 close(channel[0]); /* NB: close _first_, then move fd! */
5383 xmove_fd(channel[1], 1);
5384 /* Prevent it from trying to handle ctrl-z etc */
5385 IF_HUSH_JOB(G.run_list_level = 1;)
5386 /* Awful hack for `trap` or $(trap).
5388 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5389 * contains an example where "trap" is executed in a subshell:
5391 * save_traps=$(trap)
5393 * eval "$save_traps"
5395 * Standard does not say that "trap" in subshell shall print
5396 * parent shell's traps. It only says that its output
5397 * must have suitable form, but then, in the above example
5398 * (which is not supposed to be normative), it implies that.
5400 * bash (and probably other shell) does implement it
5401 * (traps are reset to defaults, but "trap" still shows them),
5402 * but as a result, "trap" logic is hopelessly messed up:
5405 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5406 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5407 * # true | trap <--- trap is in subshell - no output (ditto)
5408 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5409 * trap -- 'echo Ho' SIGWINCH
5410 * # echo `(trap)` <--- in subshell in subshell - output
5411 * trap -- 'echo Ho' SIGWINCH
5412 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5413 * trap -- 'echo Ho' SIGWINCH
5415 * The rules when to forget and when to not forget traps
5416 * get really complex and nonsensical.
5418 * Our solution: ONLY bare $(trap) or `trap` is special.
5420 s = skip_whitespace(s);
5421 if (strncmp(s, "trap", 4) == 0
5422 && skip_whitespace(s + 4)[0] == '\0'
5424 static const char *const argv[] = { NULL, NULL };
5425 builtin_trap((char**)argv);
5426 exit(0); /* not _exit() - we need to fflush */
5429 reset_traps_to_defaults();
5430 parse_and_run_string(s);
5431 _exit(G.last_exitcode);
5433 /* We re-execute after vfork on NOMMU. This makes this script safe:
5434 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5435 * huge=`cat BIG` # was blocking here forever
5438 re_execute_shell(&to_free,
5448 # if ENABLE_HUSH_FAST
5450 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5451 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5452 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5454 enable_restore_tty_pgrp_on_exit();
5459 close_on_exec_on(channel[0]);
5460 return xfdopen_for_read(channel[0]);
5463 /* Return code is exit status of the process that is run. */
5464 static int process_command_subs(o_string *dest, const char *s)
5467 struct in_str pipe_str;
5469 int status, ch, eol_cnt;
5471 fp = generate_stream_from_string(s, &pid);
5473 /* Now send results of command back into original context */
5474 setup_file_in_str(&pipe_str, fp);
5476 while ((ch = i_getch(&pipe_str)) != EOF) {
5482 o_addchr(dest, '\n');
5485 o_addQchr(dest, ch);
5488 debug_printf("done reading from `cmd` pipe, closing it\n");
5490 /* We need to extract exitcode. Test case
5491 * "true; echo `sleep 1; false` $?"
5493 safe_waitpid(pid, &status, 0);
5494 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5495 return WEXITSTATUS(status);
5497 #endif /* ENABLE_HUSH_TICK */
5500 static void setup_heredoc(struct redir_struct *redir)
5502 struct fd_pair pair;
5505 /* the _body_ of heredoc (misleading field name) */
5506 const char *heredoc = redir->rd_filename;
5513 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5514 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5518 len = strlen(heredoc);
5520 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5522 xmove_fd(pair.rd, redir->rd_fd);
5524 /* Try writing without forking. Newer kernels have
5525 * dynamically growing pipes. Must use non-blocking write! */
5528 written = write(pair.wr, heredoc, len);
5539 ndelay_off(pair.wr);
5541 /* Okay, pipe buffer was not big enough */
5542 /* Note: we must not create a stray child (bastard? :)
5543 * for the unsuspecting parent process. Child creates a grandchild
5544 * and exits before parent execs the process which consumes heredoc
5545 * (that exec happens after we return from this function) */
5552 disable_restore_tty_pgrp_on_exit();
5553 pid = BB_MMU ? xfork() : xvfork();
5557 close(redir->rd_fd); /* read side of the pipe */
5559 full_write(pair.wr, heredoc, len); /* may loop or block */
5562 /* Delegate blocking writes to another process */
5563 xmove_fd(pair.wr, STDOUT_FILENO);
5564 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5568 #if ENABLE_HUSH_FAST
5570 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5572 enable_restore_tty_pgrp_on_exit();
5578 wait(NULL); /* wait till child has died */
5581 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5582 * and stderr if they are redirected. */
5583 static int setup_redirects(struct command *prog, int squirrel[])
5586 struct redir_struct *redir;
5588 for (redir = prog->redirects; redir; redir = redir->next) {
5589 if (redir->rd_type == REDIRECT_HEREDOC2) {
5590 /* rd_fd<<HERE case */
5591 if (squirrel && redir->rd_fd < 3
5592 && squirrel[redir->rd_fd] < 0
5594 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5596 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5598 debug_printf_parse("set heredoc '%s'\n",
5599 redir->rd_filename);
5600 setup_heredoc(redir);
5604 if (redir->rd_dup == REDIRFD_TO_FILE) {
5605 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5607 if (redir->rd_filename == NULL) {
5608 /* Something went wrong in the parse.
5609 * Pretend it didn't happen */
5610 bb_error_msg("bug in redirect parse");
5613 mode = redir_table[redir->rd_type].mode;
5614 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5615 openfd = open_or_warn(p, mode);
5618 /* this could get lost if stderr has been redirected, but
5619 * bash and ash both lose it as well (though zsh doesn't!) */
5620 //what the above comment tries to say?
5624 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5625 openfd = redir->rd_dup;
5628 if (openfd != redir->rd_fd) {
5629 if (squirrel && redir->rd_fd < 3
5630 && squirrel[redir->rd_fd] < 0
5632 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5634 if (openfd == REDIRFD_CLOSE) {
5635 /* "n>-" means "close me" */
5636 close(redir->rd_fd);
5638 xdup2(openfd, redir->rd_fd);
5639 if (redir->rd_dup == REDIRFD_TO_FILE)
5647 static void restore_redirects(int squirrel[])
5650 for (i = 0; i < 3; i++) {
5653 /* We simply die on error */
5659 static char *find_in_path(const char *arg)
5662 const char *PATH = get_local_var_value("PATH");
5668 const char *end = strchrnul(PATH, ':');
5669 int sz = end - PATH; /* must be int! */
5673 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5675 /* We have xxx::yyyy in $PATH,
5676 * it means "use current dir" */
5679 if (access(ret, F_OK) == 0)
5692 static const struct built_in_command *find_builtin_helper(const char *name,
5693 const struct built_in_command *x,
5694 const struct built_in_command *end)
5697 if (strcmp(name, x->b_cmd) != 0) {
5701 debug_printf_exec("found builtin '%s'\n", name);
5706 static const struct built_in_command *find_builtin1(const char *name)
5708 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5710 static const struct built_in_command *find_builtin(const char *name)
5712 const struct built_in_command *x = find_builtin1(name);
5715 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5718 #if ENABLE_HUSH_FUNCTIONS
5719 static struct function **find_function_slot(const char *name)
5721 struct function **funcpp = &G.top_func;
5723 if (strcmp(name, (*funcpp)->name) == 0) {
5726 funcpp = &(*funcpp)->next;
5731 static const struct function *find_function(const char *name)
5733 const struct function *funcp = *find_function_slot(name);
5735 debug_printf_exec("found function '%s'\n", name);
5739 /* Note: takes ownership on name ptr */
5740 static struct function *new_function(char *name)
5742 struct function **funcpp = find_function_slot(name);
5743 struct function *funcp = *funcpp;
5745 if (funcp != NULL) {
5746 struct command *cmd = funcp->parent_cmd;
5747 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5749 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5751 /* Note: if !funcp->body, do not free body_as_string!
5752 * This is a special case of "-F name body" function:
5753 * body_as_string was not malloced! */
5755 free_pipe_list(funcp->body);
5757 free(funcp->body_as_string);
5761 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5762 cmd->argv[0] = funcp->name;
5763 cmd->group = funcp->body;
5765 cmd->group_as_string = funcp->body_as_string;
5769 debug_printf_exec("remembering new function '%s'\n", name);
5770 funcp = *funcpp = xzalloc(sizeof(*funcp));
5771 /*funcp->next = NULL;*/
5778 static void unset_func(const char *name)
5780 struct function **funcpp = find_function_slot(name);
5781 struct function *funcp = *funcpp;
5783 if (funcp != NULL) {
5784 debug_printf_exec("freeing function '%s'\n", funcp->name);
5785 *funcpp = funcp->next;
5786 /* funcp is unlinked now, deleting it.
5787 * Note: if !funcp->body, the function was created by
5788 * "-F name body", do not free ->body_as_string
5789 * and ->name as they were not malloced. */
5791 free_pipe_list(funcp->body);
5794 free(funcp->body_as_string);
5802 #define exec_function(to_free, funcp, argv) \
5803 exec_function(funcp, argv)
5805 static void exec_function(char ***to_free,
5806 const struct function *funcp,
5807 char **argv) NORETURN;
5808 static void exec_function(char ***to_free,
5809 const struct function *funcp,
5815 argv[0] = G.global_argv[0];
5816 G.global_argv = argv;
5820 /* On MMU, funcp->body is always non-NULL */
5821 n = run_list(funcp->body);
5825 re_execute_shell(to_free,
5826 funcp->body_as_string,
5833 static int run_function(const struct function *funcp, char **argv)
5839 save_and_replace_G_args(&sv, argv);
5841 /* "we are in function, ok to use return" */
5842 sv_flg = G.flag_return_in_progress;
5843 G.flag_return_in_progress = -1;
5844 # if ENABLE_HUSH_LOCAL
5845 G.func_nest_level++;
5848 /* On MMU, funcp->body is always non-NULL */
5851 /* Function defined by -F */
5852 parse_and_run_string(funcp->body_as_string);
5853 rc = G.last_exitcode;
5857 rc = run_list(funcp->body);
5860 # if ENABLE_HUSH_LOCAL
5862 struct variable *var;
5863 struct variable **var_pp;
5865 var_pp = &G.top_var;
5866 while ((var = *var_pp) != NULL) {
5867 if (var->func_nest_level < G.func_nest_level) {
5868 var_pp = &var->next;
5872 if (var->flg_export)
5873 bb_unsetenv(var->varstr);
5874 /* Remove from global list */
5875 *var_pp = var->next;
5881 G.func_nest_level--;
5884 G.flag_return_in_progress = sv_flg;
5886 restore_G_args(&sv, argv);
5890 #endif /* ENABLE_HUSH_FUNCTIONS */
5894 #define exec_builtin(to_free, x, argv) \
5895 exec_builtin(x, argv)
5897 #define exec_builtin(to_free, x, argv) \
5898 exec_builtin(to_free, argv)
5900 static void exec_builtin(char ***to_free,
5901 const struct built_in_command *x,
5902 char **argv) NORETURN;
5903 static void exec_builtin(char ***to_free,
5904 const struct built_in_command *x,
5908 int rcode = x->b_function(argv);
5912 /* On NOMMU, we must never block!
5913 * Example: { sleep 99 | read line; } & echo Ok
5915 re_execute_shell(to_free,
5924 static void execvp_or_die(char **argv) NORETURN;
5925 static void execvp_or_die(char **argv)
5927 debug_printf_exec("execing '%s'\n", argv[0]);
5928 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5929 execvp(argv[0], argv);
5930 bb_perror_msg("can't execute '%s'", argv[0]);
5931 _exit(127); /* bash compat */
5934 #if ENABLE_HUSH_MODE_X
5935 static void dump_cmd_in_x_mode(char **argv)
5937 if (G_x_mode && argv) {
5938 /* We want to output the line in one write op */
5946 len += strlen(argv[n++]) + 1;
5952 p += sprintf(p, " %s", argv[n++]);
5960 # define dump_cmd_in_x_mode(argv) ((void)0)
5964 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5965 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5966 #define pseudo_exec(nommu_save, command, argv_expanded) \
5967 pseudo_exec(command, argv_expanded)
5970 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5972 * Don't exit() here. If you don't exec, use _exit instead.
5973 * The at_exit handlers apparently confuse the calling process,
5974 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5975 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5976 char **argv, int assignment_cnt,
5977 char **argv_expanded) NORETURN;
5978 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5979 char **argv, int assignment_cnt,
5980 char **argv_expanded)
5984 new_env = expand_assignments(argv, assignment_cnt);
5985 dump_cmd_in_x_mode(new_env);
5987 if (!argv[assignment_cnt]) {
5988 /* Case when we are here: ... | var=val | ...
5989 * (note that we do not exit early, i.e., do not optimize out
5990 * expand_assignments(): think about ... | var=`sleep 1` | ...
5992 free_strings(new_env);
5993 _exit(EXIT_SUCCESS);
5997 set_vars_and_save_old(new_env);
5998 free(new_env); /* optional */
5999 /* we can also destroy set_vars_and_save_old's return value,
6002 nommu_save->new_env = new_env;
6003 nommu_save->old_vars = set_vars_and_save_old(new_env);
6006 if (argv_expanded) {
6007 argv = argv_expanded;
6009 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6011 nommu_save->argv = argv;
6014 dump_cmd_in_x_mode(argv);
6016 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6017 if (strchr(argv[0], '/') != NULL)
6021 /* Check if the command matches any of the builtins.
6022 * Depending on context, this might be redundant. But it's
6023 * easier to waste a few CPU cycles than it is to figure out
6024 * if this is one of those cases.
6027 /* On NOMMU, it is more expensive to re-execute shell
6028 * just in order to run echo or test builtin.
6029 * It's better to skip it here and run corresponding
6030 * non-builtin later. */
6031 const struct built_in_command *x;
6032 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6034 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6037 #if ENABLE_HUSH_FUNCTIONS
6038 /* Check if the command matches any functions */
6040 const struct function *funcp = find_function(argv[0]);
6042 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6047 #if ENABLE_FEATURE_SH_STANDALONE
6048 /* Check if the command matches any busybox applets */
6050 int a = find_applet_by_name(argv[0]);
6052 # if BB_MMU /* see above why on NOMMU it is not allowed */
6053 if (APPLET_IS_NOEXEC(a)) {
6054 debug_printf_exec("running applet '%s'\n", argv[0]);
6055 run_applet_no_and_exit(a, argv);
6058 /* Re-exec ourselves */
6059 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6060 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6061 execv(bb_busybox_exec_path, argv);
6062 /* If they called chroot or otherwise made the binary no longer
6063 * executable, fall through */
6068 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6071 execvp_or_die(argv);
6074 /* Called after [v]fork() in run_pipe
6076 static void pseudo_exec(nommu_save_t *nommu_save,
6077 struct command *command,
6078 char **argv_expanded) NORETURN;
6079 static void pseudo_exec(nommu_save_t *nommu_save,
6080 struct command *command,
6081 char **argv_expanded)
6083 if (command->argv) {
6084 pseudo_exec_argv(nommu_save, command->argv,
6085 command->assignment_cnt, argv_expanded);
6088 if (command->group) {
6089 /* Cases when we are here:
6092 * ... | ( list ) | ...
6093 * ... | { list } | ...
6097 debug_printf_exec("pseudo_exec: run_list\n");
6098 reset_traps_to_defaults();
6099 rcode = run_list(command->group);
6100 /* OK to leak memory by not calling free_pipe_list,
6101 * since this process is about to exit */
6104 re_execute_shell(&nommu_save->argv_from_re_execing,
6105 command->group_as_string,
6112 /* Case when we are here: ... | >file */
6113 debug_printf_exec("pseudo_exec'ed null command\n");
6114 _exit(EXIT_SUCCESS);
6118 static const char *get_cmdtext(struct pipe *pi)
6124 /* This is subtle. ->cmdtext is created only on first backgrounding.
6125 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6126 * On subsequent bg argv is trashed, but we won't use it */
6129 argv = pi->cmds[0].argv;
6130 if (!argv || !argv[0]) {
6131 pi->cmdtext = xzalloc(1);
6137 len += strlen(*argv) + 1;
6141 argv = pi->cmds[0].argv;
6143 len = strlen(*argv);
6144 memcpy(p, *argv, len);
6152 static void insert_bg_job(struct pipe *pi)
6154 struct pipe *job, **jobp;
6157 /* Linear search for the ID of the job to use */
6159 for (job = G.job_list; job; job = job->next)
6160 if (job->jobid >= pi->jobid)
6161 pi->jobid = job->jobid + 1;
6163 /* Add job to the list of running jobs */
6165 while ((job = *jobp) != NULL)
6167 job = *jobp = xmalloc(sizeof(*job));
6169 *job = *pi; /* physical copy */
6171 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6172 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6173 for (i = 0; i < pi->num_cmds; i++) {
6174 job->cmds[i].pid = pi->cmds[i].pid;
6175 /* all other fields are not used and stay zero */
6177 job->cmdtext = xstrdup(get_cmdtext(pi));
6179 if (G_interactive_fd)
6180 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6181 G.last_jobid = job->jobid;
6184 static void remove_bg_job(struct pipe *pi)
6186 struct pipe *prev_pipe;
6188 if (pi == G.job_list) {
6189 G.job_list = pi->next;
6191 prev_pipe = G.job_list;
6192 while (prev_pipe->next != pi)
6193 prev_pipe = prev_pipe->next;
6194 prev_pipe->next = pi->next;
6197 G.last_jobid = G.job_list->jobid;
6202 /* Remove a backgrounded job */
6203 static void delete_finished_bg_job(struct pipe *pi)
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 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6460 * Result should be 3 lines: q w e, qwe, q w e
6462 G.ifs = get_local_var_value("IFS");
6466 IF_HUSH_JOB(pi->pgrp = -1;)
6467 pi->stopped_cmds = 0;
6468 command = &pi->cmds[0];
6469 argv_expanded = NULL;
6471 if (pi->num_cmds != 1
6472 || pi->followup == PIPE_BG
6473 || command->cmd_type == CMD_SUBSHELL
6480 debug_printf_exec(": group:%p argv:'%s'\n",
6481 command->group, command->argv ? command->argv[0] : "NONE");
6483 if (command->group) {
6484 #if ENABLE_HUSH_FUNCTIONS
6485 if (command->cmd_type == CMD_FUNCDEF) {
6486 /* "executing" func () { list } */
6487 struct function *funcp;
6489 funcp = new_function(command->argv[0]);
6490 /* funcp->name is already set to argv[0] */
6491 funcp->body = command->group;
6493 funcp->body_as_string = command->group_as_string;
6494 command->group_as_string = NULL;
6496 command->group = NULL;
6497 command->argv[0] = NULL;
6498 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6499 funcp->parent_cmd = command;
6500 command->child_func = funcp;
6502 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6504 return EXIT_SUCCESS;
6508 debug_printf("non-subshell group\n");
6509 rcode = 1; /* exitcode if redir failed */
6510 if (setup_redirects(command, squirrel) == 0) {
6511 debug_printf_exec(": run_list\n");
6512 rcode = run_list(command->group) & 0xff;
6514 restore_redirects(squirrel);
6515 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6517 debug_printf_exec("run_pipe: return %d\n", rcode);
6521 argv = command->argv ? command->argv : (char **) &null_ptr;
6523 const struct built_in_command *x;
6524 #if ENABLE_HUSH_FUNCTIONS
6525 const struct function *funcp;
6529 char **new_env = NULL;
6530 struct variable *old_vars = NULL;
6532 if (argv[command->assignment_cnt] == NULL) {
6533 /* Assignments, but no command */
6534 /* Ensure redirects take effect (that is, create files).
6535 * Try "a=t >file" */
6536 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6537 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6538 /* Set shell variables */
6542 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6543 /* Do we need to flag set_local_var() errors?
6544 * "assignment to readonly var" and "putenv error"
6549 /* Redirect error sets $? to 1. Otherwise,
6550 * if evaluating assignment value set $?, retain it.
6551 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6553 rcode = G.last_exitcode;
6554 /* Exit, _skipping_ variable restoring code: */
6555 goto clean_up_and_ret0;
6557 #else /* Older, bigger, but more correct code */
6559 rcode = setup_redirects(command, squirrel);
6560 restore_redirects(squirrel);
6561 /* Set shell variables */
6563 bb_putchar_stderr('+');
6565 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6567 fprintf(stderr, " %s", p);
6568 debug_printf_exec("set shell var:'%s'->'%s'\n",
6570 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6571 /* Do we need to flag set_local_var() errors?
6572 * "assignment to readonly var" and "putenv error"
6577 bb_putchar_stderr('\n');
6578 /* Redirect error sets $? to 1. Otherwise,
6579 * if evaluating assignment value set $?, retain it.
6580 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6582 rcode = G.last_exitcode;
6583 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6585 debug_printf_exec("run_pipe: return %d\n", rcode);
6590 /* Expand the rest into (possibly) many strings each */
6592 #if ENABLE_HUSH_BASH_COMPAT
6593 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6594 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6598 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6601 /* if someone gives us an empty string: `cmd with empty output` */
6602 if (!argv_expanded[0]) {
6603 free(argv_expanded);
6605 return G.last_exitcode;
6608 x = find_builtin(argv_expanded[0]);
6609 #if ENABLE_HUSH_FUNCTIONS
6612 funcp = find_function(argv_expanded[0]);
6616 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6617 debug_printf("exec with redirects only\n");
6618 rcode = setup_redirects(command, NULL);
6619 goto clean_up_and_ret1;
6622 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6625 debug_printf_exec(": builtin '%s' '%s'...\n",
6626 x->b_cmd, argv_expanded[1]);
6627 rcode = x->b_function(argv_expanded) & 0xff;
6630 #if ENABLE_HUSH_FUNCTIONS
6632 # if ENABLE_HUSH_LOCAL
6633 struct variable **sv;
6634 sv = G.shadowed_vars_pp;
6635 G.shadowed_vars_pp = &old_vars;
6637 debug_printf_exec(": function '%s' '%s'...\n",
6638 funcp->name, argv_expanded[1]);
6639 rcode = run_function(funcp, argv_expanded) & 0xff;
6640 # if ENABLE_HUSH_LOCAL
6641 G.shadowed_vars_pp = sv;
6647 unset_vars(new_env);
6649 /* clean_up_and_ret0: */
6650 restore_redirects(squirrel);
6652 free(argv_expanded);
6653 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6655 debug_printf_exec("run_pipe return %d\n", rcode);
6659 if (ENABLE_FEATURE_SH_STANDALONE) {
6660 int n = find_applet_by_name(argv_expanded[0]);
6661 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6662 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6664 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6665 argv_expanded[0], argv_expanded[1]);
6666 rcode = run_nofork_applet(n, argv_expanded);
6668 goto clean_up_and_ret;
6671 /* It is neither builtin nor applet. We must fork. */
6675 /* NB: argv_expanded may already be created, and that
6676 * might include `cmd` runs! Do not rerun it! We *must*
6677 * use argv_expanded if it's non-NULL */
6679 /* Going to fork a child per each pipe member */
6684 while (cmd_no < pi->num_cmds) {
6685 struct fd_pair pipefds;
6687 volatile nommu_save_t nommu_save;
6688 nommu_save.new_env = NULL;
6689 nommu_save.old_vars = NULL;
6690 nommu_save.argv = NULL;
6691 nommu_save.argv_from_re_execing = NULL;
6693 command = &pi->cmds[cmd_no];
6695 if (command->argv) {
6696 debug_printf_exec(": pipe member '%s' '%s'...\n",
6697 command->argv[0], command->argv[1]);
6699 debug_printf_exec(": pipe member with no argv\n");
6702 /* pipes are inserted between pairs of commands */
6705 if (cmd_no < pi->num_cmds)
6706 xpiped_pair(pipefds);
6708 command->pid = BB_MMU ? fork() : vfork();
6709 if (!command->pid) { /* child */
6711 disable_restore_tty_pgrp_on_exit();
6712 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6714 /* Every child adds itself to new process group
6715 * with pgid == pid_of_first_child_in_pipe */
6716 if (G.run_list_level == 1 && G_interactive_fd) {
6719 if (pgrp < 0) /* true for 1st process only */
6721 if (setpgid(0, pgrp) == 0
6722 && pi->followup != PIPE_BG
6723 && G_saved_tty_pgrp /* we have ctty */
6725 /* We do it in *every* child, not just first,
6727 tcsetpgrp(G_interactive_fd, pgrp);
6731 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6732 /* 1st cmd in backgrounded pipe
6733 * should have its stdin /dev/null'ed */
6735 if (open(bb_dev_null, O_RDONLY))
6736 xopen("/", O_RDONLY);
6738 xmove_fd(next_infd, 0);
6740 xmove_fd(pipefds.wr, 1);
6743 /* Like bash, explicit redirects override pipes,
6744 * and the pipe fd is available for dup'ing. */
6745 if (setup_redirects(command, NULL))
6748 /* Restore default handlers just prior to exec */
6749 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6751 /* Stores to nommu_save list of env vars putenv'ed
6752 * (NOMMU, on MMU we don't need that) */
6753 /* cast away volatility... */
6754 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6755 /* pseudo_exec() does not return */
6758 /* parent or error */
6759 #if ENABLE_HUSH_FAST
6761 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6763 enable_restore_tty_pgrp_on_exit();
6765 /* Clean up after vforked child */
6766 free(nommu_save.argv);
6767 free(nommu_save.argv_from_re_execing);
6768 unset_vars(nommu_save.new_env);
6769 add_vars(nommu_save.old_vars);
6771 free(argv_expanded);
6772 argv_expanded = NULL;
6773 if (command->pid < 0) { /* [v]fork failed */
6774 /* Clearly indicate, was it fork or vfork */
6775 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6779 /* Second and next children need to know pid of first one */
6781 pi->pgrp = command->pid;
6787 if (cmd_no < pi->num_cmds)
6789 /* Pass read (output) pipe end to next iteration */
6790 next_infd = pipefds.rd;
6793 if (!pi->alive_cmds) {
6795 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6800 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6804 #ifndef debug_print_tree
6805 static void debug_print_tree(struct pipe *pi, int lvl)
6807 static const char *const PIPE[] = {
6813 static const char *RES[] = {
6814 [RES_NONE ] = "NONE" ,
6817 [RES_THEN ] = "THEN" ,
6818 [RES_ELIF ] = "ELIF" ,
6819 [RES_ELSE ] = "ELSE" ,
6822 # if ENABLE_HUSH_LOOPS
6823 [RES_FOR ] = "FOR" ,
6824 [RES_WHILE] = "WHILE",
6825 [RES_UNTIL] = "UNTIL",
6827 [RES_DONE ] = "DONE" ,
6829 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6832 # if ENABLE_HUSH_CASE
6833 [RES_CASE ] = "CASE" ,
6834 [RES_CASE_IN ] = "CASE_IN" ,
6835 [RES_MATCH] = "MATCH",
6836 [RES_CASE_BODY] = "CASE_BODY",
6837 [RES_ESAC ] = "ESAC" ,
6839 [RES_XXXX ] = "XXXX" ,
6840 [RES_SNTX ] = "SNTX" ,
6842 static const char *const CMDTYPE[] = {
6846 # if ENABLE_HUSH_FUNCTIONS
6855 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6856 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6858 while (prn < pi->num_cmds) {
6859 struct command *command = &pi->cmds[prn];
6860 char **argv = command->argv;
6862 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6864 command->assignment_cnt);
6865 if (command->group) {
6866 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6867 CMDTYPE[command->cmd_type],
6870 , " group_as_string:", command->group_as_string
6875 debug_print_tree(command->group, lvl+1);
6879 if (argv) while (*argv) {
6880 fprintf(stderr, " '%s'", *argv);
6883 fprintf(stderr, "\n");
6890 #endif /* debug_print_tree */
6892 /* NB: called by pseudo_exec, and therefore must not modify any
6893 * global data until exec/_exit (we can be a child after vfork!) */
6894 static int run_list(struct pipe *pi)
6896 #if ENABLE_HUSH_CASE
6897 char *case_word = NULL;
6899 #if ENABLE_HUSH_LOOPS
6900 struct pipe *loop_top = NULL;
6901 char **for_lcur = NULL;
6902 char **for_list = NULL;
6904 smallint last_followup;
6906 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6907 smalluint cond_code = 0;
6909 enum { cond_code = 0 };
6912 smallint rword; /* RES_foo */
6913 smallint last_rword; /* ditto */
6916 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6919 #if ENABLE_HUSH_LOOPS
6920 /* Check syntax for "for" */
6921 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6922 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6924 /* current word is FOR or IN (BOLD in comments below) */
6925 if (cpipe->next == NULL) {
6926 syntax_error("malformed for");
6928 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6931 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6932 if (cpipe->next->res_word == RES_DO)
6934 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6935 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6936 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6938 syntax_error("malformed for");
6940 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6946 /* Past this point, all code paths should jump to ret: label
6947 * in order to return, no direct "return" statements please.
6948 * This helps to ensure that no memory is leaked. */
6956 last_rword = RES_XXXX;
6958 last_followup = PIPE_SEQ;
6959 rcode = G.last_exitcode;
6961 /* Go through list of pipes, (maybe) executing them. */
6962 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6966 IF_HAS_KEYWORDS(rword = pi->res_word;)
6967 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6968 rword, cond_code, last_rword);
6969 #if ENABLE_HUSH_LOOPS
6970 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6971 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6973 /* start of a loop: remember where loop starts */
6978 /* Still in the same "if...", "then..." or "do..." branch? */
6979 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6980 if ((rcode == 0 && last_followup == PIPE_OR)
6981 || (rcode != 0 && last_followup == PIPE_AND)
6983 /* It is "<true> || CMD" or "<false> && CMD"
6984 * and we should not execute CMD */
6985 debug_printf_exec("skipped cmd because of || or &&\n");
6986 last_followup = pi->followup;
6990 last_followup = pi->followup;
6991 IF_HAS_KEYWORDS(last_rword = rword;)
6994 if (rword == RES_THEN) {
6995 /* if false; then ... fi has exitcode 0! */
6996 G.last_exitcode = rcode = EXIT_SUCCESS;
6997 /* "if <false> THEN cmd": skip cmd */
7001 if (rword == RES_ELSE || rword == RES_ELIF) {
7002 /* "if <true> then ... ELSE/ELIF cmd":
7003 * skip cmd and all following ones */
7008 #if ENABLE_HUSH_LOOPS
7009 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7011 /* first loop through for */
7013 static const char encoded_dollar_at[] ALIGN1 = {
7014 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7015 }; /* encoded representation of "$@" */
7016 static const char *const encoded_dollar_at_argv[] = {
7017 encoded_dollar_at, NULL
7018 }; /* argv list with one element: "$@" */
7021 vals = (char**)encoded_dollar_at_argv;
7022 if (pi->next->res_word == RES_IN) {
7023 /* if no variable values after "in" we skip "for" */
7024 if (!pi->next->cmds[0].argv) {
7025 G.last_exitcode = rcode = EXIT_SUCCESS;
7026 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7029 vals = pi->next->cmds[0].argv;
7030 } /* else: "for var; do..." -> assume "$@" list */
7031 /* create list of variable values */
7032 debug_print_strings("for_list made from", vals);
7033 for_list = expand_strvec_to_strvec(vals);
7034 for_lcur = for_list;
7035 debug_print_strings("for_list", for_list);
7038 /* "for" loop is over, clean up */
7044 /* Insert next value from for_lcur */
7045 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7046 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7049 if (rword == RES_IN) {
7050 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7052 if (rword == RES_DONE) {
7053 continue; /* "done" has no cmds too */
7056 #if ENABLE_HUSH_CASE
7057 if (rword == RES_CASE) {
7058 case_word = expand_strvec_to_string(pi->cmds->argv);
7061 if (rword == RES_MATCH) {
7064 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7066 /* all prev words didn't match, does this one match? */
7067 argv = pi->cmds->argv;
7069 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7070 /* TODO: which FNM_xxx flags to use? */
7071 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7073 if (cond_code == 0) { /* match! we will execute this branch */
7074 free(case_word); /* make future "word)" stop */
7082 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7084 continue; /* not matched yet, skip this pipe */
7087 /* Just pressing <enter> in shell should check for jobs.
7088 * OTOH, in non-interactive shell this is useless
7089 * and only leads to extra job checks */
7090 if (pi->num_cmds == 0) {
7091 if (G_interactive_fd)
7092 goto check_jobs_and_continue;
7096 /* After analyzing all keywords and conditions, we decided
7097 * to execute this pipe. NB: have to do checkjobs(NULL)
7098 * after run_pipe to collect any background children,
7099 * even if list execution is to be stopped. */
7100 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7103 #if ENABLE_HUSH_LOOPS
7104 G.flag_break_continue = 0;
7106 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7108 /* We ran a builtin, function, or group.
7109 * rcode is already known
7110 * and we don't need to wait for anything. */
7111 G.last_exitcode = rcode;
7112 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7113 check_and_run_traps(0);
7114 #if ENABLE_HUSH_LOOPS
7115 /* Was it "break" or "continue"? */
7116 if (G.flag_break_continue) {
7117 smallint fbc = G.flag_break_continue;
7118 /* We might fall into outer *loop*,
7119 * don't want to break it too */
7121 G.depth_break_continue--;
7122 if (G.depth_break_continue == 0)
7123 G.flag_break_continue = 0;
7124 /* else: e.g. "continue 2" should *break* once, *then* continue */
7125 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7126 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7127 goto check_jobs_and_break;
7128 /* "continue": simulate end of loop */
7133 #if ENABLE_HUSH_FUNCTIONS
7134 if (G.flag_return_in_progress == 1) {
7135 /* same as "goto check_jobs_and_break" */
7140 } else if (pi->followup == PIPE_BG) {
7141 /* What does bash do with attempts to background builtins? */
7142 /* even bash 3.2 doesn't do that well with nested bg:
7143 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7144 * I'm NOT treating inner &'s as jobs */
7145 check_and_run_traps(0);
7147 if (G.run_list_level == 1)
7150 /* Last command's pid goes to $! */
7151 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7152 G.last_exitcode = rcode = EXIT_SUCCESS;
7153 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7156 if (G.run_list_level == 1 && G_interactive_fd) {
7157 /* Waits for completion, then fg's main shell */
7158 rcode = checkjobs_and_fg_shell(pi);
7159 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7160 check_and_run_traps(0);
7163 { /* This one just waits for completion */
7164 rcode = checkjobs(pi);
7165 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7166 check_and_run_traps(0);
7168 G.last_exitcode = rcode;
7172 /* Analyze how result affects subsequent commands */
7174 if (rword == RES_IF || rword == RES_ELIF)
7177 #if ENABLE_HUSH_LOOPS
7178 /* Beware of "while false; true; do ..."! */
7179 if (pi->next && pi->next->res_word == RES_DO) {
7180 if (rword == RES_WHILE) {
7182 /* "while false; do...done" - exitcode 0 */
7183 G.last_exitcode = rcode = EXIT_SUCCESS;
7184 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7185 goto check_jobs_and_break;
7188 if (rword == RES_UNTIL) {
7190 debug_printf_exec(": until expr is true: breaking\n");
7191 check_jobs_and_break:
7199 check_jobs_and_continue:
7206 #if ENABLE_HUSH_LOOPS
7211 #if ENABLE_HUSH_CASE
7215 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7219 /* Select which version we will use */
7220 static int run_and_free_list(struct pipe *pi)
7223 debug_printf_exec("run_and_free_list entered\n");
7225 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7226 rcode = run_list(pi);
7228 /* free_pipe_list has the side effect of clearing memory.
7229 * In the long run that function can be merged with run_list,
7230 * but doing that now would hobble the debugging effort. */
7232 debug_printf_exec("run_and_free_list return %d\n", rcode);
7237 /* Called a few times only (or even once if "sh -c") */
7238 static void init_sigmasks(void)
7242 sigset_t old_blocked_set;
7244 if (!G.inherited_set_is_saved) {
7245 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7246 G.inherited_set = G.blocked_set;
7248 old_blocked_set = G.blocked_set;
7250 mask = (1 << SIGQUIT);
7251 if (G_interactive_fd) {
7252 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7253 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7254 mask |= SPECIAL_JOB_SIGS;
7256 G.non_DFL_mask = mask;
7261 sigaddset(&G.blocked_set, sig);
7265 sigdelset(&G.blocked_set, SIGCHLD);
7267 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7268 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7270 /* POSIX allows shell to re-enable SIGCHLD
7271 * even if it was SIG_IGN on entry */
7272 #if ENABLE_HUSH_FAST
7273 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7274 if (!G.inherited_set_is_saved)
7275 signal(SIGCHLD, SIGCHLD_handler);
7277 if (!G.inherited_set_is_saved)
7278 signal(SIGCHLD, SIG_DFL);
7281 G.inherited_set_is_saved = 1;
7286 static void maybe_set_to_sigexit(int sig)
7288 void (*handler)(int);
7289 /* non_DFL_mask'ed signals are, well, masked,
7290 * no need to set handler for them.
7292 if (!((G.non_DFL_mask >> sig) & 1)) {
7293 handler = signal(sig, sigexit);
7294 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7295 signal(sig, handler);
7298 /* Set handlers to restore tty pgrp and exit */
7299 static void set_fatal_handlers(void)
7301 /* We _must_ restore tty pgrp on fatal signals */
7303 maybe_set_to_sigexit(SIGILL );
7304 maybe_set_to_sigexit(SIGFPE );
7305 maybe_set_to_sigexit(SIGBUS );
7306 maybe_set_to_sigexit(SIGSEGV);
7307 maybe_set_to_sigexit(SIGTRAP);
7308 } /* else: hush is perfect. what SEGV? */
7309 maybe_set_to_sigexit(SIGABRT);
7310 /* bash 3.2 seems to handle these just like 'fatal' ones */
7311 maybe_set_to_sigexit(SIGPIPE);
7312 maybe_set_to_sigexit(SIGALRM);
7313 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7314 * if we aren't interactive... but in this case
7315 * we never want to restore pgrp on exit, and this fn is not called */
7316 /*maybe_set_to_sigexit(SIGHUP );*/
7317 /*maybe_set_to_sigexit(SIGTERM);*/
7318 /*maybe_set_to_sigexit(SIGINT );*/
7322 static int set_mode(const char cstate, const char mode)
7324 int state = (cstate == '-' ? 1 : 0);
7326 case 'n': G.n_mode = state; break;
7327 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7328 default: return EXIT_FAILURE;
7330 return EXIT_SUCCESS;
7333 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7334 int hush_main(int argc, char **argv)
7337 unsigned builtin_argc;
7339 struct variable *cur_var;
7342 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7343 G.last_exitcode = EXIT_SUCCESS;
7345 G.argv0_for_re_execing = argv[0];
7347 /* Deal with HUSH_VERSION */
7348 G.shell_ver.flg_export = 1;
7349 G.shell_ver.flg_read_only = 1;
7350 /* Code which handles ${var<op>...} needs writable values for all variables,
7351 * therefore we xstrdup: */
7352 G.shell_ver.varstr = xstrdup(hush_version_str),
7353 G.top_var = &G.shell_ver;
7354 /* Create shell local variables from the values
7355 * currently living in the environment */
7356 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7357 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7358 cur_var = G.top_var;
7361 char *value = strchr(*e, '=');
7362 if (value) { /* paranoia */
7363 cur_var->next = xzalloc(sizeof(*cur_var));
7364 cur_var = cur_var->next;
7365 cur_var->varstr = *e;
7366 cur_var->max_len = strlen(*e);
7367 cur_var->flg_export = 1;
7371 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7372 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7373 putenv(G.shell_ver.varstr);
7376 set_pwd_var(/*exp:*/ 1);
7377 /* bash also exports SHLVL and _,
7378 * and sets (but doesn't export) the following variables:
7380 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7381 * BASH_VERSION='3.2.0(1)-release'
7383 * MACHTYPE=i386-pc-linux-gnu
7385 * HOSTNAME=<xxxxxxxxxx>
7386 * PPID=<NNNNN> - we also do it elsewhere
7397 * PIPESTATUS=([0]="0")
7398 * HISTFILE=/<xxx>/.bash_history
7402 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7404 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7414 #if ENABLE_FEATURE_EDITING
7415 G.line_input_state = new_line_input_t(FOR_SHELL);
7416 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7418 const char *hp = get_local_var_value("HISTFILE");
7420 hp = get_local_var_value("HOME");
7422 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7423 //set_local_var(xasprintf("HISTFILE=%s", ...));
7430 G.global_argc = argc;
7431 G.global_argv = argv;
7432 /* Initialize some more globals to non-zero values */
7433 cmdedit_update_prompt();
7435 if (setjmp(die_jmp)) {
7436 /* xfunc has failed! die die die */
7437 /* no EXIT traps, this is an escape hatch! */
7439 hush_exit(xfunc_error_retval);
7442 /* Shell is non-interactive at first. We need to call
7443 * init_sigmasks() if we are going to execute "sh <script>",
7444 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7445 * If we later decide that we are interactive, we run init_sigmasks()
7446 * in order to intercept (more) signals.
7450 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7453 opt = getopt(argc, argv, "+c:xins"
7456 # if ENABLE_HUSH_FUNCTIONS
7466 * sh ... -c 'script'
7467 * sh ... -c 'script' ARG0 [ARG1...]
7468 * On NOMMU, if builtin_argc != 0,
7469 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7470 * "" needs to be replaced with NULL
7471 * and BARGV vector fed to builtin function.
7472 * Note: the form without ARG0 never happens:
7473 * sh ... -c 'builtin' BARGV... ""
7476 G.root_pid = getpid();
7477 G.root_ppid = getppid();
7479 G.global_argv = argv + optind;
7480 G.global_argc = argc - optind;
7482 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7483 const struct built_in_command *x;
7486 x = find_builtin(optarg);
7487 if (x) { /* paranoia */
7488 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7489 G.global_argv += builtin_argc;
7490 G.global_argv[-1] = NULL; /* replace "" */
7491 G.last_exitcode = x->b_function(argv + optind - 1);
7495 if (!G.global_argv[0]) {
7496 /* -c 'script' (no params): prevent empty $0 */
7497 G.global_argv--; /* points to argv[i] of 'script' */
7498 G.global_argv[0] = argv[0];
7500 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7502 parse_and_run_string(optarg);
7505 /* Well, we cannot just declare interactiveness,
7506 * we have to have some stuff (ctty, etc) */
7507 /* G_interactive_fd++; */
7510 /* "-s" means "read from stdin", but this is how we always
7511 * operate, so simply do nothing here. */
7514 case '<': /* "big heredoc" support */
7515 full_write1_str(optarg);
7518 unsigned long long empty_trap_mask;
7520 G.root_pid = bb_strtou(optarg, &optarg, 16);
7522 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7524 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7526 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7528 builtin_argc = bb_strtou(optarg, &optarg, 16);
7530 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7531 if (empty_trap_mask != 0) {
7534 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7535 for (sig = 1; sig < NSIG; sig++) {
7536 if (empty_trap_mask & (1LL << sig)) {
7537 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7538 sigaddset(&G.blocked_set, sig);
7541 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7543 # if ENABLE_HUSH_LOOPS
7545 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7551 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7553 # if ENABLE_HUSH_FUNCTIONS
7555 struct function *funcp = new_function(optarg);
7556 /* funcp->name is already set to optarg */
7557 /* funcp->body is set to NULL. It's a special case. */
7558 funcp->body_as_string = argv[optind];
7566 if (set_mode('-', opt) == 0) /* no error */
7570 fprintf(stderr, "Usage: sh [FILE]...\n"
7571 " or: sh -c command [args]...\n\n");
7577 } /* option parsing loop */
7580 G.root_pid = getpid();
7581 G.root_ppid = getppid();
7584 /* If we are login shell... */
7585 if (argv[0] && argv[0][0] == '-') {
7587 debug_printf("sourcing /etc/profile\n");
7588 input = fopen_for_read("/etc/profile");
7589 if (input != NULL) {
7590 close_on_exec_on(fileno(input));
7592 parse_and_run_file(input);
7595 /* bash: after sourcing /etc/profile,
7596 * tries to source (in the given order):
7597 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7598 * stopping on first found. --noprofile turns this off.
7599 * bash also sources ~/.bash_logout on exit.
7600 * If called as sh, skips .bash_XXX files.
7607 * "bash <script>" (which is never interactive (unless -i?))
7608 * sources $BASH_ENV here (without scanning $PATH).
7609 * If called as sh, does the same but with $ENV.
7611 debug_printf("running script '%s'\n", argv[optind]);
7612 G.global_argv = argv + optind;
7613 G.global_argc = argc - optind;
7614 input = xfopen_for_read(argv[optind]);
7615 close_on_exec_on(fileno(input));
7617 parse_and_run_file(input);
7618 #if ENABLE_FEATURE_CLEAN_UP
7624 /* Up to here, shell was non-interactive. Now it may become one.
7625 * NB: don't forget to (re)run init_sigmasks() as needed.
7628 /* A shell is interactive if the '-i' flag was given,
7629 * or if all of the following conditions are met:
7631 * no arguments remaining or the -s flag given
7632 * standard input is a terminal
7633 * standard output is a terminal
7634 * Refer to Posix.2, the description of the 'sh' utility.
7637 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7638 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7639 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7640 if (G_saved_tty_pgrp < 0)
7641 G_saved_tty_pgrp = 0;
7643 /* try to dup stdin to high fd#, >= 255 */
7644 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7645 if (G_interactive_fd < 0) {
7646 /* try to dup to any fd */
7647 G_interactive_fd = dup(STDIN_FILENO);
7648 if (G_interactive_fd < 0) {
7650 G_interactive_fd = 0;
7651 G_saved_tty_pgrp = 0;
7654 // TODO: track & disallow any attempts of user
7655 // to (inadvertently) close/redirect G_interactive_fd
7657 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7658 if (G_interactive_fd) {
7659 close_on_exec_on(G_interactive_fd);
7661 if (G_saved_tty_pgrp) {
7662 /* If we were run as 'hush &', sleep until we are
7663 * in the foreground (tty pgrp == our pgrp).
7664 * If we get started under a job aware app (like bash),
7665 * make sure we are now in charge so we don't fight over
7666 * who gets the foreground */
7668 pid_t shell_pgrp = getpgrp();
7669 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7670 if (G_saved_tty_pgrp == shell_pgrp)
7672 /* send TTIN to ourself (should stop us) */
7673 kill(- shell_pgrp, SIGTTIN);
7677 /* Block some signals */
7680 if (G_saved_tty_pgrp) {
7681 /* Set other signals to restore saved_tty_pgrp */
7682 set_fatal_handlers();
7683 /* Put ourselves in our own process group
7684 * (bash, too, does this only if ctty is available) */
7685 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7686 /* Grab control of the terminal */
7687 tcsetpgrp(G_interactive_fd, getpid());
7689 /* -1 is special - makes xfuncs longjmp, not exit
7690 * (we reset die_sleep = 0 whereever we [v]fork) */
7691 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7695 #elif ENABLE_HUSH_INTERACTIVE
7696 /* No job control compiled in, only prompt/line editing */
7697 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7698 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7699 if (G_interactive_fd < 0) {
7700 /* try to dup to any fd */
7701 G_interactive_fd = dup(STDIN_FILENO);
7702 if (G_interactive_fd < 0)
7704 G_interactive_fd = 0;
7707 if (G_interactive_fd) {
7708 close_on_exec_on(G_interactive_fd);
7712 /* We have interactiveness code disabled */
7716 * if interactive but not a login shell, sources ~/.bashrc
7717 * (--norc turns this off, --rcfile <file> overrides)
7720 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7721 /* note: ash and hush share this string */
7722 printf("\n\n%s %s\n"
7723 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7726 "hush - the humble shell"
7730 parse_and_run_file(stdin);
7733 #if ENABLE_FEATURE_CLEAN_UP
7734 if (G.cwd != bb_msg_unknown)
7736 cur_var = G.top_var->next;
7738 struct variable *tmp = cur_var;
7739 if (!cur_var->max_len)
7740 free(cur_var->varstr);
7741 cur_var = cur_var->next;
7745 hush_exit(G.last_exitcode);
7750 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7751 int msh_main(int argc, char **argv)
7753 //bb_error_msg("msh is deprecated, please use hush instead");
7754 return hush_main(argc, argv);
7762 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7767 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7774 return applet_main_func(argc, argv - argc);
7777 static int FAST_FUNC builtin_test(char **argv)
7779 return run_applet_main(argv, test_main);
7782 static int FAST_FUNC builtin_echo(char **argv)
7784 return run_applet_main(argv, echo_main);
7788 static int FAST_FUNC builtin_printf(char **argv)
7790 return run_applet_main(argv, printf_main);
7794 static char **skip_dash_dash(char **argv)
7797 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7802 static int FAST_FUNC builtin_eval(char **argv)
7804 int rcode = EXIT_SUCCESS;
7806 argv = skip_dash_dash(argv);
7808 char *str = expand_strvec_to_string(argv);
7810 * eval "echo Hi; done" ("done" is syntax error):
7811 * "echo Hi" will not execute too.
7813 parse_and_run_string(str);
7815 rcode = G.last_exitcode;
7820 static int FAST_FUNC builtin_cd(char **argv)
7824 argv = skip_dash_dash(argv);
7826 if (newdir == NULL) {
7827 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7828 * bash says "bash: cd: HOME not set" and does nothing
7831 const char *home = get_local_var_value("HOME");
7832 newdir = home ? home : "/";
7834 if (chdir(newdir)) {
7835 /* Mimic bash message exactly */
7836 bb_perror_msg("cd: %s", newdir);
7837 return EXIT_FAILURE;
7839 /* Read current dir (get_cwd(1) is inside) and set PWD.
7840 * Note: do not enforce exporting. If PWD was unset or unexported,
7841 * set it again, but do not export. bash does the same.
7843 set_pwd_var(/*exp:*/ 0);
7844 return EXIT_SUCCESS;
7847 static int FAST_FUNC builtin_exec(char **argv)
7849 argv = skip_dash_dash(argv);
7850 if (argv[0] == NULL)
7851 return EXIT_SUCCESS; /* bash does this */
7853 /* Careful: we can end up here after [v]fork. Do not restore
7854 * tty pgrp then, only top-level shell process does that */
7855 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7856 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7858 /* TODO: if exec fails, bash does NOT exit! We do.
7859 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7860 * and tcsetpgrp, and this is inherently racy.
7862 execvp_or_die(argv);
7865 static int FAST_FUNC builtin_exit(char **argv)
7867 debug_printf_exec("%s()\n", __func__);
7869 /* interactive bash:
7870 * # trap "echo EEE" EXIT
7873 * There are stopped jobs.
7874 * (if there are _stopped_ jobs, running ones don't count)
7877 # EEE (then bash exits)
7879 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
7882 /* note: EXIT trap is run by hush_exit */
7883 argv = skip_dash_dash(argv);
7884 if (argv[0] == NULL)
7885 hush_exit(G.last_exitcode);
7886 /* mimic bash: exit 123abc == exit 255 + error msg */
7887 xfunc_error_retval = 255;
7888 /* bash: exit -2 == exit 254, no error msg */
7889 hush_exit(xatoi(argv[0]) & 0xff);
7892 static void print_escaped(const char *s)
7897 const char *p = strchrnul(s, '\'');
7898 /* print 'xxxx', possibly just '' */
7899 printf("'%.*s'", (int)(p - s), s);
7904 /* s points to '; print "'''...'''" */
7906 do putchar('\''); while (*++s == '\'');
7911 #if !ENABLE_HUSH_LOCAL
7912 #define helper_export_local(argv, exp, lvl) \
7913 helper_export_local(argv, exp)
7915 static void helper_export_local(char **argv, int exp, int lvl)
7919 char *name_end = strchrnul(name, '=');
7921 /* So far we do not check that name is valid (TODO?) */
7923 if (*name_end == '\0') {
7924 struct variable *var, **vpp;
7926 vpp = get_ptr_to_local_var(name, name_end - name);
7927 var = vpp ? *vpp : NULL;
7929 if (exp == -1) { /* unexporting? */
7930 /* export -n NAME (without =VALUE) */
7932 var->flg_export = 0;
7933 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7935 } /* else: export -n NOT_EXISTING_VAR: no-op */
7938 if (exp == 1) { /* exporting? */
7939 /* export NAME (without =VALUE) */
7941 var->flg_export = 1;
7942 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7943 putenv(var->varstr);
7947 /* Exporting non-existing variable.
7948 * bash does not put it in environment,
7949 * but remembers that it is exported,
7950 * and does put it in env when it is set later.
7951 * We just set it to "" and export. */
7952 /* Or, it's "local NAME" (without =VALUE).
7953 * bash sets the value to "". */
7954 name = xasprintf("%s=", name);
7956 /* (Un)exporting/making local NAME=VALUE */
7957 name = xstrdup(name);
7959 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7963 static int FAST_FUNC builtin_export(char **argv)
7965 unsigned opt_unexport;
7967 #if ENABLE_HUSH_EXPORT_N
7968 /* "!": do not abort on errors */
7969 opt_unexport = getopt32(argv, "!n");
7970 if (opt_unexport == (uint32_t)-1)
7971 return EXIT_FAILURE;
7978 if (argv[0] == NULL) {
7985 /* ash emits: export VAR='VAL'
7986 * bash: declare -x VAR="VAL"
7987 * we follow ash example */
7988 const char *s = *e++;
7989 const char *p = strchr(s, '=');
7991 if (!p) /* wtf? take next variable */
7994 printf("export %.*s", (int)(p - s) + 1, s);
7995 print_escaped(p + 1);
7999 /*fflush_all(); - done after each builtin anyway */
8001 return EXIT_SUCCESS;
8004 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8006 return EXIT_SUCCESS;
8009 #if ENABLE_HUSH_LOCAL
8010 static int FAST_FUNC builtin_local(char **argv)
8012 if (G.func_nest_level == 0) {
8013 bb_error_msg("%s: not in a function", argv[0]);
8014 return EXIT_FAILURE; /* bash compat */
8016 helper_export_local(argv, 0, G.func_nest_level);
8017 return EXIT_SUCCESS;
8021 static int FAST_FUNC builtin_trap(char **argv)
8027 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8032 /* No args: print all trapped */
8033 for (i = 0; i < NSIG; ++i) {
8036 print_escaped(G.traps[i]);
8037 /* note: bash adds "SIG", but only if invoked
8038 * as "bash". If called as "sh", or if set -o posix,
8039 * then it prints short signal names.
8040 * We are printing short names: */
8041 printf(" %s\n", get_signame(i));
8044 /*fflush_all(); - done after each builtin anyway */
8045 return EXIT_SUCCESS;
8049 /* If first arg is a number: reset all specified signals */
8050 sig = bb_strtou(*argv, NULL, 10);
8056 sig = get_signum(*argv++);
8057 if (sig < 0 || sig >= NSIG) {
8059 /* Mimic bash message exactly */
8060 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8065 G.traps[sig] = xstrdup(new_cmd);
8067 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8068 get_signame(sig), sig, G.traps[sig]);
8070 /* There is no signal for 0 (EXIT) */
8075 sigaddset(&G.blocked_set, sig);
8077 /* There was a trap handler, we are removing it
8078 * (if sig has non-DFL handling,
8079 * we don't need to do anything) */
8080 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8082 sigdelset(&G.blocked_set, sig);
8085 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8089 if (!argv[1]) { /* no second arg */
8090 bb_error_msg("trap: invalid arguments");
8091 return EXIT_FAILURE;
8094 /* First arg is "-": reset all specified to default */
8095 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8096 /* Everything else: set arg as signal handler
8097 * (includes "" case, which ignores signal) */
8098 if (argv[0][0] == '-') {
8099 if (argv[0][1] == '\0') { /* "-" */
8100 /* new_cmd remains NULL: "reset these sigs" */
8103 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8106 /* else: "-something", no special meaning */
8111 goto process_sig_list;
8114 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8115 static int FAST_FUNC builtin_type(char **argv)
8117 int ret = EXIT_SUCCESS;
8123 if (0) {} /* make conditional compile easier below */
8124 /*else if (find_alias(*argv))
8125 type = "an alias";*/
8126 #if ENABLE_HUSH_FUNCTIONS
8127 else if (find_function(*argv))
8128 type = "a function";
8130 else if (find_builtin(*argv))
8131 type = "a shell builtin";
8132 else if ((path = find_in_path(*argv)) != NULL)
8135 bb_error_msg("type: %s: not found", *argv);
8140 printf("%s is %s\n", *argv, type);
8148 /* built-in 'fg' and 'bg' handler */
8149 static int FAST_FUNC builtin_fg_bg(char **argv)
8154 if (!G_interactive_fd)
8155 return EXIT_FAILURE;
8157 /* If they gave us no args, assume they want the last backgrounded task */
8159 for (pi = G.job_list; pi; pi = pi->next) {
8160 if (pi->jobid == G.last_jobid) {
8164 bb_error_msg("%s: no current job", argv[0]);
8165 return EXIT_FAILURE;
8167 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8168 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8169 return EXIT_FAILURE;
8171 for (pi = G.job_list; pi; pi = pi->next) {
8172 if (pi->jobid == jobnum) {
8176 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8177 return EXIT_FAILURE;
8179 /* TODO: bash prints a string representation
8180 * of job being foregrounded (like "sleep 1 | cat") */
8181 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8182 /* Put the job into the foreground. */
8183 tcsetpgrp(G_interactive_fd, pi->pgrp);
8186 /* Restart the processes in the job */
8187 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8188 for (i = 0; i < pi->num_cmds; i++) {
8189 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8190 pi->cmds[i].is_stopped = 0;
8192 pi->stopped_cmds = 0;
8194 i = kill(- pi->pgrp, SIGCONT);
8196 if (errno == ESRCH) {
8197 delete_finished_bg_job(pi);
8198 return EXIT_SUCCESS;
8200 bb_perror_msg("kill (SIGCONT)");
8203 if (argv[0][0] == 'f') {
8205 return checkjobs_and_fg_shell(pi);
8207 return EXIT_SUCCESS;
8211 #if ENABLE_HUSH_HELP
8212 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8214 const struct built_in_command *x;
8217 "Built-in commands:\n"
8218 "------------------\n");
8219 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8221 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8224 return EXIT_SUCCESS;
8229 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8232 const char *status_string;
8234 for (job = G.job_list; job; job = job->next) {
8235 if (job->alive_cmds == job->stopped_cmds)
8236 status_string = "Stopped";
8238 status_string = "Running";
8240 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8242 return EXIT_SUCCESS;
8247 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8252 # ifdef M_TRIM_THRESHOLD
8253 /* Optional. Reduces probability of false positives */
8256 /* Crude attempt to find where "free memory" starts,
8257 * sans fragmentation. */
8259 l = (unsigned long)p;
8262 if (l < (unsigned long)p) l = (unsigned long)p;
8265 if (!G.memleak_value)
8266 G.memleak_value = l;
8268 l -= G.memleak_value;
8275 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8280 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8283 return EXIT_SUCCESS;
8286 static int FAST_FUNC builtin_read(char **argv)
8295 /* "!": do not abort on errors.
8296 * Option string must start with "sr" to match BUILTIN_READ_xxx
8298 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8299 if (read_flags == (uint32_t)-1)
8300 return EXIT_FAILURE;
8303 r = shell_builtin_read(set_local_var_from_halves,
8305 get_local_var_value("IFS"), /* can be NULL */
8313 if ((uintptr_t)r > 1) {
8314 bb_error_msg("%s", r);
8315 r = (char*)(uintptr_t)1;
8318 return (uintptr_t)r;
8321 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8322 * built-in 'set' handler
8324 * set [-abCefhmnuvx] [-o option] [argument...]
8325 * set [+abCefhmnuvx] [+o option] [argument...]
8326 * set -- [argument...]
8329 * Implementations shall support the options in both their hyphen and
8330 * plus-sign forms. These options can also be specified as options to sh.
8332 * Write out all variables and their values: set
8333 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8334 * Turn on the -x and -v options: set -xv
8335 * Unset all positional parameters: set --
8336 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8337 * Set the positional parameters to the expansion of x, even if x expands
8338 * with a leading '-' or '+': set -- $x
8340 * So far, we only support "set -- [argument...]" and some of the short names.
8342 static int FAST_FUNC builtin_set(char **argv)
8345 char **pp, **g_argv;
8346 char *arg = *++argv;
8350 for (e = G.top_var; e; e = e->next)
8352 return EXIT_SUCCESS;
8356 if (!strcmp(arg, "--")) {
8360 if (arg[0] != '+' && arg[0] != '-')
8362 for (n = 1; arg[n]; ++n)
8363 if (set_mode(arg[0], arg[n]))
8365 } while ((arg = *++argv) != NULL);
8366 /* Now argv[0] is 1st argument */
8369 return EXIT_SUCCESS;
8372 /* NB: G.global_argv[0] ($0) is never freed/changed */
8373 g_argv = G.global_argv;
8374 if (G.global_args_malloced) {
8380 G.global_args_malloced = 1;
8381 pp = xzalloc(sizeof(pp[0]) * 2);
8382 pp[0] = g_argv[0]; /* retain $0 */
8385 /* This realloc's G.global_argv */
8386 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8393 return EXIT_SUCCESS;
8395 /* Nothing known, so abort */
8397 bb_error_msg("set: %s: invalid option", arg);
8398 return EXIT_FAILURE;
8401 static int FAST_FUNC builtin_shift(char **argv)
8404 argv = skip_dash_dash(argv);
8408 if (n >= 0 && n < G.global_argc) {
8409 if (G.global_args_malloced) {
8412 free(G.global_argv[m++]);
8415 memmove(&G.global_argv[1], &G.global_argv[n+1],
8416 G.global_argc * sizeof(G.global_argv[0]));
8417 return EXIT_SUCCESS;
8419 return EXIT_FAILURE;
8422 static int FAST_FUNC builtin_source(char **argv)
8424 char *arg_path, *filename;
8427 #if ENABLE_HUSH_FUNCTIONS
8431 argv = skip_dash_dash(argv);
8434 /* bash says: "bash: .: filename argument required" */
8435 return 2; /* bash compat */
8438 if (!strchr(filename, '/')) {
8439 arg_path = find_in_path(filename);
8441 filename = arg_path;
8443 input = fopen_or_warn(filename, "r");
8446 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8447 return EXIT_FAILURE;
8449 close_on_exec_on(fileno(input));
8451 #if ENABLE_HUSH_FUNCTIONS
8452 sv_flg = G.flag_return_in_progress;
8453 /* "we are inside sourced file, ok to use return" */
8454 G.flag_return_in_progress = -1;
8456 save_and_replace_G_args(&sv, argv);
8458 parse_and_run_file(input);
8461 restore_G_args(&sv, argv);
8462 #if ENABLE_HUSH_FUNCTIONS
8463 G.flag_return_in_progress = sv_flg;
8466 return G.last_exitcode;
8469 static int FAST_FUNC builtin_umask(char **argv)
8475 argv = skip_dash_dash(argv);
8477 mode_t old_mask = mask;
8480 rc = bb_parse_mode(argv[0], &mask);
8485 * bash: umask: 'q': invalid symbolic mode operator
8486 * bash: umask: 999: octal number out of range
8488 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8493 printf("%04o\n", (unsigned) mask);
8494 /* fall through and restore mask which we set to 0 */
8498 return !rc; /* rc != 0 - success */
8501 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8502 static int FAST_FUNC builtin_unset(char **argv)
8507 /* "!": do not abort on errors */
8508 /* "+": stop at 1st non-option */
8509 opts = getopt32(argv, "!+vf");
8510 if (opts == (unsigned)-1)
8511 return EXIT_FAILURE;
8513 bb_error_msg("unset: -v and -f are exclusive");
8514 return EXIT_FAILURE;
8520 if (!(opts & 2)) { /* not -f */
8521 if (unset_local_var(*argv)) {
8522 /* unset <nonexistent_var> doesn't fail.
8523 * Error is when one tries to unset RO var.
8524 * Message was printed by unset_local_var. */
8528 #if ENABLE_HUSH_FUNCTIONS
8538 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8539 static int FAST_FUNC builtin_wait(char **argv)
8541 int ret = EXIT_SUCCESS;
8544 argv = skip_dash_dash(argv);
8545 if (argv[0] == NULL) {
8546 /* Don't care about wait results */
8547 /* Note 1: must wait until there are no more children */
8548 /* Note 2: must be interruptible */
8550 * $ sleep 3 & sleep 6 & wait
8555 * $ sleep 3 & sleep 6 & wait
8559 * ^C <-- after ~4 sec from keyboard
8562 sigaddset(&G.blocked_set, SIGCHLD);
8563 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8566 if (errno == ECHILD)
8568 /* Wait for SIGCHLD or any other signal of interest */
8569 /* sigtimedwait with infinite timeout: */
8570 sig = sigwaitinfo(&G.blocked_set, NULL);
8572 sig = check_and_run_traps(sig);
8573 if (sig && sig != SIGCHLD) { /* see note 2 */
8579 sigdelset(&G.blocked_set, SIGCHLD);
8580 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8584 /* This is probably buggy wrt interruptible-ness */
8586 pid_t pid = bb_strtou(*argv, NULL, 10);
8588 /* mimic bash message */
8589 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8590 return EXIT_FAILURE;
8592 if (waitpid(pid, &status, 0) == pid) {
8593 if (WIFSIGNALED(status))
8594 ret = 128 + WTERMSIG(status);
8595 else if (WIFEXITED(status))
8596 ret = WEXITSTATUS(status);
8600 bb_perror_msg("wait %s", *argv);
8609 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8610 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8613 def = bb_strtou(argv[1], NULL, 10);
8614 if (errno || def < def_min || argv[2]) {
8615 bb_error_msg("%s: bad arguments", argv[0]);
8623 #if ENABLE_HUSH_LOOPS
8624 static int FAST_FUNC builtin_break(char **argv)
8627 if (G.depth_of_loop == 0) {
8628 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8629 return EXIT_SUCCESS; /* bash compat */
8631 G.flag_break_continue++; /* BC_BREAK = 1 */
8633 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8634 if (depth == UINT_MAX)
8635 G.flag_break_continue = BC_BREAK;
8636 if (G.depth_of_loop < depth)
8637 G.depth_break_continue = G.depth_of_loop;
8639 return EXIT_SUCCESS;
8642 static int FAST_FUNC builtin_continue(char **argv)
8644 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8645 return builtin_break(argv);
8649 #if ENABLE_HUSH_FUNCTIONS
8650 static int FAST_FUNC builtin_return(char **argv)
8654 if (G.flag_return_in_progress != -1) {
8655 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8656 return EXIT_FAILURE; /* bash compat */
8659 G.flag_return_in_progress = 1;
8662 * out of range: wraps around at 256, does not error out
8663 * non-numeric param:
8664 * f() { false; return qwe; }; f; echo $?
8665 * bash: return: qwe: numeric argument required <== we do this
8666 * 255 <== we also do this
8668 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);