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>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #include <malloc.h> /* for malloc_trim */
87 /* #include <dmalloc.h> */
92 #include "shell_common.h"
95 #if ENABLE_HUSH_RANDOM_SUPPORT
98 # define CLEAR_RANDOM_T(rnd) ((void)0)
101 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
104 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
106 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
107 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
109 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
110 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
113 //config: bool "hush"
116 //config: hush is a small shell (25k). It handles the normal flow control
117 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
118 //config: case/esac. Redirections, here documents, $((arithmetic))
119 //config: and functions are supported.
121 //config: It will compile and work on no-mmu systems.
123 //config: It does not handle select, aliases, tilde expansion,
124 //config: &>file and >&file redirection of stdout+stderr.
126 //config:config HUSH_BASH_COMPAT
127 //config: bool "bash-compatible extensions"
129 //config: depends on HUSH
131 //config: Enable bash-compatible extensions.
133 //config:config HUSH_BRACE_EXPANSION
134 //config: bool "Brace expansion"
136 //config: depends on HUSH_BASH_COMPAT
138 //config: Enable {abc,def} extension.
140 //config:config HUSH_HELP
141 //config: bool "help builtin"
143 //config: depends on HUSH
145 //config: Enable help builtin in hush. Code size + ~1 kbyte.
147 //config:config HUSH_INTERACTIVE
148 //config: bool "Interactive mode"
150 //config: depends on HUSH
152 //config: Enable interactive mode (prompt and command editing).
153 //config: Without this, hush simply reads and executes commands
154 //config: from stdin just like a shell script from a file.
155 //config: No prompt, no PS1/PS2 magic shell variables.
157 //config:config HUSH_SAVEHISTORY
158 //config: bool "Save command history to .hush_history"
160 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162 //config: Enable history saving in hush.
164 //config:config HUSH_JOB
165 //config: bool "Job control"
167 //config: depends on HUSH_INTERACTIVE
169 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
170 //config: command (not entire shell), fg/bg builtins work. Without this option,
171 //config: "cmd &" still works by simply spawning a process and immediately
172 //config: prompting for next command (or executing next command in a script),
173 //config: but no separate process group is formed.
175 //config:config HUSH_TICK
176 //config: bool "Process substitution"
178 //config: depends on HUSH
180 //config: Enable process substitution `command` and $(command) in hush.
182 //config:config HUSH_IF
183 //config: bool "Support if/then/elif/else/fi"
185 //config: depends on HUSH
187 //config: Enable if/then/elif/else/fi in hush.
189 //config:config HUSH_LOOPS
190 //config: bool "Support for, while and until loops"
192 //config: depends on HUSH
194 //config: Enable for, while and until loops in hush.
196 //config:config HUSH_CASE
197 //config: bool "Support case ... esac statement"
199 //config: depends on HUSH
201 //config: Enable case ... esac statement in hush. +400 bytes.
203 //config:config HUSH_FUNCTIONS
204 //config: bool "Support funcname() { commands; } syntax"
206 //config: depends on HUSH
208 //config: Enable support for shell functions in hush. +800 bytes.
210 //config:config HUSH_LOCAL
211 //config: bool "Support local builtin"
213 //config: depends on HUSH_FUNCTIONS
215 //config: Enable support for local variables in functions.
217 //config:config HUSH_RANDOM_SUPPORT
218 //config: bool "Pseudorandom generator and $RANDOM variable"
220 //config: depends on HUSH
222 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
223 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
225 //config:config HUSH_EXPORT_N
226 //config: bool "Support 'export -n' option"
228 //config: depends on HUSH
230 //config: export -n unexports variables. It is a bash extension.
232 //config:config HUSH_MODE_X
233 //config: bool "Support 'hush -x' option and 'set -x' command"
235 //config: depends on HUSH
237 //config: This instructs hush to print commands before execution.
238 //config: Adds ~300 bytes.
241 //config: bool "msh (deprecated: aliased to hush)"
243 //config: select HUSH
245 //config: msh is deprecated and will be removed, please migrate to hush.
248 //usage:#define hush_trivial_usage NOUSAGE_STR
249 //usage:#define hush_full_usage ""
250 //usage:#define msh_trivial_usage NOUSAGE_STR
251 //usage:#define msh_full_usage ""
252 //usage:#define sh_trivial_usage NOUSAGE_STR
253 //usage:#define sh_full_usage ""
254 //usage:#define bash_trivial_usage NOUSAGE_STR
255 //usage:#define bash_full_usage ""
259 #define LEAK_HUNTING 0
260 #define BUILD_AS_NOMMU 0
261 /* Enable/disable sanity checks. Ok to enable in production,
262 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
263 * Keeping 1 for now even in released versions.
266 /* Slightly bigger (+200 bytes), but faster hush.
267 * So far it only enables a trick with counting SIGCHLDs and forks,
268 * which allows us to do fewer waitpid's.
269 * (we can detect a case where neither forks were done nor SIGCHLDs happened
270 * and therefore waitpid will return the same result as last time)
272 #define ENABLE_HUSH_FAST 0
273 /* TODO: implement simplified code for users which do not need ${var%...} ops
274 * So far ${var%...} ops are always enabled:
276 #define ENABLE_HUSH_DOLLAR_OPS 1
281 # undef USE_FOR_NOMMU
284 # define USE_FOR_NOMMU(...) __VA_ARGS__
285 # define USE_FOR_MMU(...)
288 #include "NUM_APPLETS.h"
290 /* STANDALONE does not make sense, and won't compile */
291 # undef CONFIG_FEATURE_SH_STANDALONE
292 # undef ENABLE_FEATURE_SH_STANDALONE
293 # undef IF_FEATURE_SH_STANDALONE
294 # undef IF_NOT_FEATURE_SH_STANDALONE
295 # define ENABLE_FEATURE_SH_STANDALONE 0
296 # define IF_FEATURE_SH_STANDALONE(...)
297 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
300 #if !ENABLE_HUSH_INTERACTIVE
301 # undef ENABLE_FEATURE_EDITING
302 # define ENABLE_FEATURE_EDITING 0
303 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
304 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
307 /* Do we support ANY keywords? */
308 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
309 # define HAS_KEYWORDS 1
310 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
311 # define IF_HAS_NO_KEYWORDS(...)
313 # define HAS_KEYWORDS 0
314 # define IF_HAS_KEYWORDS(...)
315 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
318 /* If you comment out one of these below, it will be #defined later
319 * to perform debug printfs to stderr: */
320 #define debug_printf(...) do {} while (0)
321 /* Finer-grained debug switches */
322 #define debug_printf_parse(...) do {} while (0)
323 #define debug_print_tree(a, b) do {} while (0)
324 #define debug_printf_exec(...) do {} while (0)
325 #define debug_printf_env(...) do {} while (0)
326 #define debug_printf_jobs(...) do {} while (0)
327 #define debug_printf_expand(...) do {} while (0)
328 #define debug_printf_varexp(...) do {} while (0)
329 #define debug_printf_glob(...) do {} while (0)
330 #define debug_printf_list(...) do {} while (0)
331 #define debug_printf_subst(...) do {} while (0)
332 #define debug_printf_clean(...) do {} while (0)
334 #define ERR_PTR ((void*)(long)1)
336 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
338 #define _SPECIAL_VARS_STR "_*@$!?#"
339 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
340 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
341 #if ENABLE_HUSH_BASH_COMPAT
342 /* Support / and // replace ops */
343 /* Note that // is stored as \ in "encoded" string representation */
344 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
345 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
346 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
348 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
349 # define VAR_SUBST_OPS "%#:-=+?"
350 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
353 #define SPECIAL_VAR_SYMBOL 3
357 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
359 /* This supports saving pointers malloced in vfork child,
360 * to be freed in the parent.
363 typedef struct nommu_save_t {
365 struct variable *old_vars;
367 char **argv_from_re_execing;
380 #if ENABLE_HUSH_LOOPS
387 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
392 /* three pseudo-keywords support contrived "case" syntax: */
393 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
394 RES_MATCH , /* "word)" */
395 RES_CASE_BODY, /* "this command is inside CASE" */
402 typedef struct o_string {
404 int length; /* position where data is appended */
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 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
416 /* Protect newly added chars against globbing
417 * by prepending \ to *, ?, [, \ */
418 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
421 MAYBE_ASSIGNMENT = 0,
422 DEFINITELY_ASSIGNMENT = 1,
424 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
427 /* Used for initialization: o_string foo = NULL_O_STRING; */
428 #define NULL_O_STRING { NULL }
430 /* I can almost use ordinary FILE*. Is open_memstream() universally
431 * available? Where is it documented? */
432 typedef struct in_str {
434 /* eof_flag=1: last char in ->p is really an EOF */
435 char eof_flag; /* meaningless if ->p == NULL */
437 #if ENABLE_HUSH_INTERACTIVE
439 smallint promptmode; /* 0: PS1, 1: PS2 */
442 int (*get) (struct in_str *) FAST_FUNC;
443 int (*peek) (struct in_str *) FAST_FUNC;
445 #define i_getch(input) ((input)->get(input))
446 #define i_peek(input) ((input)->peek(input))
448 /* The descrip member of this structure is only used to make
449 * debugging output pretty */
450 static const struct {
452 signed char default_fd;
455 { O_RDONLY, 0, "<" },
456 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
457 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
458 { O_CREAT|O_RDWR, 1, "<>" },
459 { O_RDONLY, 0, "<<" },
460 /* Should not be needed. Bogus default_fd helps in debugging */
461 /* { O_RDONLY, 77, "<<" }, */
464 struct redir_struct {
465 struct redir_struct *next;
466 char *rd_filename; /* filename */
467 int rd_fd; /* fd to redirect */
468 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
470 smallint rd_type; /* (enum redir_type) */
471 /* note: for heredocs, rd_filename contains heredoc delimiter,
472 * and subsequently heredoc itself; and rd_dup is a bitmask:
473 * bit 0: do we need to trim leading tabs?
474 * bit 1: is heredoc quoted (<<'delim' syntax) ?
477 typedef enum redir_type {
479 REDIRECT_OVERWRITE = 1,
482 REDIRECT_HEREDOC = 4,
483 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
486 REDIRFD_SYNTAX_ERR = -2,
487 REDIRFD_TO_FILE = -1,
488 /* otherwise, rd_fd is redirected to rd_dup */
490 HEREDOC_SKIPTABS = 1,
496 pid_t pid; /* 0 if exited */
497 int assignment_cnt; /* how many argv[i] are assignments? */
498 smallint is_stopped; /* is the command currently running? */
499 smallint cmd_type; /* CMD_xxx */
501 #define CMD_SUBSHELL 1
502 #if ENABLE_HUSH_BASH_COMPAT
503 /* used for "[[ EXPR ]]" */
504 # define CMD_SINGLEWORD_NOGLOB 2
506 #if ENABLE_HUSH_FUNCTIONS
507 # define CMD_FUNCDEF 3
510 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
513 char *group_as_string;
515 #if ENABLE_HUSH_FUNCTIONS
516 struct function *child_func;
517 /* This field is used to prevent a bug here:
518 * while...do f1() {a;}; f1; f1() {b;}; f1; done
519 * When we execute "f1() {a;}" cmd, we create new function and clear
520 * cmd->group, cmd->group_as_string, cmd->argv[0].
521 * When we execute "f1() {b;}", we notice that f1 exists,
522 * and that its "parent cmd" struct is still "alive",
523 * we put those fields back into cmd->xxx
524 * (struct function has ->parent_cmd ptr to facilitate that).
525 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
526 * Without this trick, loop would execute a;b;b;b;...
527 * instead of correct sequence a;b;a;b;...
528 * When command is freed, it severs the link
529 * (sets ->child_func->parent_cmd to NULL).
532 char **argv; /* command name and arguments */
533 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
534 * and on execution these are substituted with their values.
535 * Substitution can make _several_ words out of one argv[n]!
536 * Example: argv[0]=='.^C*^C.' here: echo .$*.
537 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
539 struct redir_struct *redirects; /* I/O redirections */
541 /* Is there anything in this command at all? */
542 #define IS_NULL_CMD(cmd) \
543 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
548 int num_cmds; /* total number of commands in pipe */
549 int alive_cmds; /* number of commands running (not exited) */
550 int stopped_cmds; /* number of commands alive, but stopped */
552 int jobid; /* job number */
553 pid_t pgrp; /* process group ID for the job */
554 char *cmdtext; /* name of job */
556 struct command *cmds; /* array of commands in pipe */
557 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
558 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
559 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
561 typedef enum pipe_style {
567 /* Is there anything in this pipe at all? */
568 #define IS_NULL_PIPE(pi) \
569 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
571 /* This holds pointers to the various results of parsing */
572 struct parse_context {
573 /* linked list of pipes */
574 struct pipe *list_head;
575 /* last pipe (being constructed right now) */
577 /* last command in pipe (being constructed right now) */
578 struct command *command;
579 /* last redirect in command->redirects list */
580 struct redir_struct *pending_redirect;
586 smallint ctx_inverted; /* "! cmd | cmd" */
588 smallint ctx_dsemicolon; /* ";;" seen */
590 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
592 /* group we are enclosed in:
593 * example: "if pipe1; pipe2; then pipe3; fi"
594 * when we see "if" or "then", we malloc and copy current context,
595 * and make ->stack point to it. then we parse pipeN.
596 * when closing "then" / fi" / whatever is found,
597 * we move list_head into ->stack->command->group,
598 * copy ->stack into current context, and delete ->stack.
599 * (parsing of { list } and ( list ) doesn't use this method)
601 struct parse_context *stack;
605 /* On program start, environ points to initial environment.
606 * putenv adds new pointers into it, unsetenv removes them.
607 * Neither of these (de)allocates the strings.
608 * setenv allocates new strings in malloc space and does putenv,
609 * and thus setenv is unusable (leaky) for shell's purposes */
610 #define setenv(...) setenv_is_leaky_dont_use()
612 struct variable *next;
613 char *varstr; /* points to "name=" portion */
614 #if ENABLE_HUSH_LOCAL
615 unsigned func_nest_level;
617 int max_len; /* if > 0, name is part of initial env; else name is malloced */
618 smallint flg_export; /* putenv should be done on this var */
619 smallint flg_read_only;
627 #if ENABLE_HUSH_FUNCTIONS
629 struct function *next;
631 struct command *parent_cmd;
634 char *body_as_string;
640 /* "Globals" within this file */
641 /* Sorted roughly by size (smaller offsets == smaller code) */
643 /* interactive_fd != 0 means we are an interactive shell.
644 * If we are, then saved_tty_pgrp can also be != 0, meaning
645 * that controlling tty is available. With saved_tty_pgrp == 0,
646 * job control still works, but terminal signals
647 * (^C, ^Z, ^Y, ^\) won't work at all, and background
648 * process groups can only be created with "cmd &".
649 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
650 * to give tty to the foreground process group,
651 * and will take it back when the group is stopped (^Z)
654 #if ENABLE_HUSH_INTERACTIVE
655 /* 'interactive_fd' is a fd# open to ctty, if we have one
656 * _AND_ if we decided to act interactively */
660 # define G_interactive_fd (G.interactive_fd)
662 # define G_interactive_fd 0
664 #if ENABLE_FEATURE_EDITING
665 line_input_t *line_input_state;
670 #if ENABLE_HUSH_RANDOM_SUPPORT
676 pid_t saved_tty_pgrp;
677 struct pipe *job_list;
678 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
680 # define G_saved_tty_pgrp 0
682 smallint flag_SIGINT;
683 #if ENABLE_HUSH_LOOPS
684 smallint flag_break_continue;
686 #if ENABLE_HUSH_FUNCTIONS
687 /* 0: outside of a function (or sourced file)
688 * -1: inside of a function, ok to use return builtin
689 * 1: return is invoked, skip all till end of func
691 smallint flag_return_in_progress;
694 #if ENABLE_HUSH_MODE_X
696 # define G_x_mode (G.x_mode)
700 smallint exiting; /* used to prevent EXIT trap recursion */
701 /* These four support $?, $#, and $1 */
702 smalluint last_exitcode;
703 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
704 smalluint global_args_malloced;
705 smalluint inherited_set_is_saved;
706 /* how many non-NULL argv's we have. NB: $# + 1 */
710 char *argv0_for_re_execing;
712 #if ENABLE_HUSH_LOOPS
713 unsigned depth_break_continue;
714 unsigned depth_of_loop;
718 struct variable *top_var;
719 char **expanded_assignments;
720 #if ENABLE_HUSH_FUNCTIONS
721 struct function *top_func;
722 # if ENABLE_HUSH_LOCAL
723 struct variable **shadowed_vars_pp;
724 unsigned func_nest_level;
727 /* Signal and trap handling */
729 unsigned count_SIGCHLD;
730 unsigned handled_SIGCHLD;
731 smallint we_have_children;
733 /* which signals have non-DFL handler (even with no traps set)? */
734 unsigned non_DFL_mask;
735 char **traps; /* char *traps[NSIG] */
736 sigset_t blocked_set;
737 sigset_t inherited_set;
739 unsigned long memleak_value;
742 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
744 #define G (*ptr_to_globals)
745 /* Not #defining name to G.name - this quickly gets unwieldy
746 * (too many defines). Also, I actually prefer to see when a variable
747 * is global, thus "G." prefix is a useful hint */
748 #define INIT_G() do { \
749 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
753 /* Function prototypes for builtins */
754 static int builtin_cd(char **argv) FAST_FUNC;
755 static int builtin_echo(char **argv) FAST_FUNC;
756 static int builtin_eval(char **argv) FAST_FUNC;
757 static int builtin_exec(char **argv) FAST_FUNC;
758 static int builtin_exit(char **argv) FAST_FUNC;
759 static int builtin_export(char **argv) FAST_FUNC;
761 static int builtin_fg_bg(char **argv) FAST_FUNC;
762 static int builtin_jobs(char **argv) FAST_FUNC;
765 static int builtin_help(char **argv) FAST_FUNC;
767 #if ENABLE_HUSH_LOCAL
768 static int builtin_local(char **argv) FAST_FUNC;
771 static int builtin_memleak(char **argv) FAST_FUNC;
774 static int builtin_printf(char **argv) FAST_FUNC;
776 static int builtin_pwd(char **argv) FAST_FUNC;
777 static int builtin_read(char **argv) FAST_FUNC;
778 static int builtin_set(char **argv) FAST_FUNC;
779 static int builtin_shift(char **argv) FAST_FUNC;
780 static int builtin_source(char **argv) FAST_FUNC;
781 static int builtin_test(char **argv) FAST_FUNC;
782 static int builtin_trap(char **argv) FAST_FUNC;
783 static int builtin_type(char **argv) FAST_FUNC;
784 static int builtin_true(char **argv) FAST_FUNC;
785 static int builtin_umask(char **argv) FAST_FUNC;
786 static int builtin_unset(char **argv) FAST_FUNC;
787 static int builtin_wait(char **argv) FAST_FUNC;
788 #if ENABLE_HUSH_LOOPS
789 static int builtin_break(char **argv) FAST_FUNC;
790 static int builtin_continue(char **argv) FAST_FUNC;
792 #if ENABLE_HUSH_FUNCTIONS
793 static int builtin_return(char **argv) FAST_FUNC;
796 /* Table of built-in functions. They can be forked or not, depending on
797 * context: within pipes, they fork. As simple commands, they do not.
798 * When used in non-forking context, they can change global variables
799 * in the parent shell process. If forked, of course they cannot.
800 * For example, 'unset foo | whatever' will parse and run, but foo will
801 * still be set at the end. */
802 struct built_in_command {
804 int (*b_function)(char **argv) FAST_FUNC;
807 # define BLTIN(cmd, func, help) { cmd, func, help }
809 # define BLTIN(cmd, func, help) { cmd, func }
813 static const struct built_in_command bltins1[] = {
814 BLTIN("." , builtin_source , "Run commands in a file"),
815 BLTIN(":" , builtin_true , NULL),
817 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
819 #if ENABLE_HUSH_LOOPS
820 BLTIN("break" , builtin_break , "Exit from a loop"),
822 BLTIN("cd" , builtin_cd , "Change directory"),
823 #if ENABLE_HUSH_LOOPS
824 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
826 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
827 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
828 BLTIN("exit" , builtin_exit , "Exit"),
829 BLTIN("export" , builtin_export , "Set environment variables"),
831 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
834 BLTIN("help" , builtin_help , NULL),
837 BLTIN("jobs" , builtin_jobs , "List jobs"),
839 #if ENABLE_HUSH_LOCAL
840 BLTIN("local" , builtin_local , "Set local variables"),
843 BLTIN("memleak" , builtin_memleak , NULL),
845 BLTIN("read" , builtin_read , "Input into variable"),
846 #if ENABLE_HUSH_FUNCTIONS
847 BLTIN("return" , builtin_return , "Return from a function"),
849 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
850 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
851 #if ENABLE_HUSH_BASH_COMPAT
852 BLTIN("source" , builtin_source , "Run commands in a file"),
854 BLTIN("trap" , builtin_trap , "Trap signals"),
855 BLTIN("type" , builtin_type , "Show command type"),
856 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
857 BLTIN("umask" , builtin_umask , "Set file creation mask"),
858 BLTIN("unset" , builtin_unset , "Unset variables"),
859 BLTIN("wait" , builtin_wait , "Wait for process"),
861 /* For now, echo and test are unconditionally enabled.
862 * Maybe make it configurable? */
863 static const struct built_in_command bltins2[] = {
864 BLTIN("[" , builtin_test , NULL),
865 BLTIN("echo" , builtin_echo , NULL),
867 BLTIN("printf" , builtin_printf , NULL),
869 BLTIN("pwd" , builtin_pwd , NULL),
870 BLTIN("test" , builtin_test , NULL),
877 /* prevent disasters with G.debug_indent < 0 */
878 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
879 # define debug_enter() (G.debug_indent++)
880 # define debug_leave() (G.debug_indent--)
882 # define indent() ((void)0)
883 # define debug_enter() ((void)0)
884 # define debug_leave() ((void)0)
888 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
891 #ifndef debug_printf_parse
892 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
895 #ifndef debug_printf_exec
896 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
899 #ifndef debug_printf_env
900 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
903 #ifndef debug_printf_jobs
904 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
905 # define DEBUG_JOBS 1
907 # define DEBUG_JOBS 0
910 #ifndef debug_printf_expand
911 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
912 # define DEBUG_EXPAND 1
914 # define DEBUG_EXPAND 0
917 #ifndef debug_printf_varexp
918 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
921 #ifndef debug_printf_glob
922 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
923 # define DEBUG_GLOB 1
925 # define DEBUG_GLOB 0
928 #ifndef debug_printf_list
929 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
932 #ifndef debug_printf_subst
933 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
936 #ifndef debug_printf_clean
937 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
938 # define DEBUG_CLEAN 1
940 # define DEBUG_CLEAN 0
944 static void debug_print_strings(const char *prefix, char **vv)
947 fprintf(stderr, "%s:\n", prefix);
949 fprintf(stderr, " '%s'\n", *vv++);
952 # define debug_print_strings(prefix, vv) ((void)0)
956 /* Leak hunting. Use hush_leaktool.sh for post-processing.
959 static void *xxmalloc(int lineno, size_t size)
961 void *ptr = xmalloc((size + 0xff) & ~0xff);
962 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
965 static void *xxrealloc(int lineno, void *ptr, size_t size)
967 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
968 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
971 static char *xxstrdup(int lineno, const char *str)
973 char *ptr = xstrdup(str);
974 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
977 static void xxfree(void *ptr)
979 fdprintf(2, "free %p\n", ptr);
982 # define xmalloc(s) xxmalloc(__LINE__, s)
983 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
984 # define xstrdup(s) xxstrdup(__LINE__, s)
985 # define free(p) xxfree(p)
989 /* Syntax and runtime errors. They always abort scripts.
990 * In interactive use they usually discard unparsed and/or unexecuted commands
991 * and return to the prompt.
992 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
995 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
996 # define syntax_error(lineno, msg) syntax_error(msg)
997 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
998 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
999 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1000 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1003 static void die_if_script(unsigned lineno, const char *fmt, ...)
1008 bb_error_msg("hush.c:%u", lineno);
1011 bb_verror_msg(fmt, p, NULL);
1013 if (!G_interactive_fd)
1017 static void syntax_error(unsigned lineno, const char *msg)
1020 die_if_script(lineno, "syntax error: %s", msg);
1022 die_if_script(lineno, "syntax error", NULL);
1025 static void syntax_error_at(unsigned lineno, const char *msg)
1027 die_if_script(lineno, "syntax error at '%s'", msg);
1030 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1032 die_if_script(lineno, "syntax error: unterminated %s", s);
1035 /* It so happens that all such cases are totally fatal
1036 * even if shell is interactive: EOF while looking for closing
1037 * delimiter. There is nowhere to read stuff from after that,
1038 * it's EOF! The only choice is to terminate.
1040 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1041 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1043 char msg[2] = { ch, '\0' };
1044 syntax_error_unterm_str(lineno, msg);
1048 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1053 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1057 # undef die_if_script
1058 # undef syntax_error
1059 # undef syntax_error_at
1060 # undef syntax_error_unterm_ch
1061 # undef syntax_error_unterm_str
1062 # undef syntax_error_unexpected_ch
1064 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1065 # define syntax_error(msg) syntax_error(__LINE__, msg)
1066 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1067 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1068 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1069 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1073 #if ENABLE_HUSH_INTERACTIVE
1074 static void cmdedit_update_prompt(void);
1076 # define cmdedit_update_prompt() ((void)0)
1080 /* Utility functions
1082 /* Replace each \x with x in place, return ptr past NUL. */
1083 static char *unbackslash(char *src)
1085 char *dst = src = strchrnul(src, '\\');
1089 if ((*dst++ = *src++) == '\0')
1095 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1116 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1117 v[count1 + count2] = NULL;
1120 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1124 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1126 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1127 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1130 #define add_strings_to_strings(strings, add, need_to_dup) \
1131 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1134 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1135 static char **add_string_to_strings(char **strings, char *add)
1140 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1143 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1145 char **ptr = add_string_to_strings(strings, add);
1146 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1149 #define add_string_to_strings(strings, add) \
1150 xx_add_string_to_strings(__LINE__, strings, add)
1153 static void free_strings(char **strings)
1168 /* Helpers for setting new $n and restoring them back
1170 typedef struct save_arg_t {
1174 smallint sv_g_malloced;
1177 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1181 sv->sv_argv0 = argv[0];
1182 sv->sv_g_argv = G.global_argv;
1183 sv->sv_g_argc = G.global_argc;
1184 sv->sv_g_malloced = G.global_args_malloced;
1186 argv[0] = G.global_argv[0]; /* retain $0 */
1187 G.global_argv = argv;
1188 G.global_args_malloced = 0;
1196 static void restore_G_args(save_arg_t *sv, char **argv)
1200 if (G.global_args_malloced) {
1201 /* someone ran "set -- arg1 arg2 ...", undo */
1203 while (*++pp) /* note: does not free $0 */
1205 free(G.global_argv);
1207 argv[0] = sv->sv_argv0;
1208 G.global_argv = sv->sv_g_argv;
1209 G.global_argc = sv->sv_g_argc;
1210 G.global_args_malloced = sv->sv_g_malloced;
1214 /* Basic theory of signal handling in shell
1215 * ========================================
1216 * This does not describe what hush does, rather, it is current understanding
1217 * what it _should_ do. If it doesn't, it's a bug.
1218 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1220 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1221 * is finished or backgrounded. It is the same in interactive and
1222 * non-interactive shells, and is the same regardless of whether
1223 * a user trap handler is installed or a shell special one is in effect.
1224 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1225 * backgrounds (i.e. stops) or kills all members of currently running
1228 * Wait builtin in interruptible by signals for which user trap is set
1229 * or by SIGINT in interactive shell.
1231 * Trap handlers will execute even within trap handlers. (right?)
1233 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1234 * except for handlers set to '' (empty string).
1236 * If job control is off, backgrounded commands ("cmd &")
1237 * have SIGINT, SIGQUIT set to SIG_IGN.
1239 * Commands which are run in command substitution ("`cmd`")
1240 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1242 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1243 * by the shell from its parent.
1245 * Signals which differ from SIG_DFL action
1246 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1249 * SIGTERM (interactive): ignore
1250 * SIGHUP (interactive):
1251 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1252 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1253 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1254 * that all pipe members are stopped. Try this in bash:
1255 * while :; do :; done - ^Z does not background it
1256 * (while :; do :; done) - ^Z backgrounds it
1257 * SIGINT (interactive): wait for last pipe, ignore the rest
1258 * of the command line, show prompt. NB: ^C does not send SIGINT
1259 * to interactive shell while shell is waiting for a pipe,
1260 * since shell is bg'ed (is not in foreground process group).
1261 * Example 1: this waits 5 sec, but does not execute ls:
1262 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1263 * Example 2: this does not wait and does not execute ls:
1264 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1265 * Example 3: this does not wait 5 sec, but executes ls:
1266 * "sleep 5; ls -l" + press ^C
1268 * (What happens to signals which are IGN on shell start?)
1269 * (What happens with signal mask on shell start?)
1271 * Implementation in hush
1272 * ======================
1273 * We use in-kernel pending signal mask to determine which signals were sent.
1274 * We block all signals which we don't want to take action immediately,
1275 * i.e. we block all signals which need to have special handling as described
1276 * above, and all signals which have traps set.
1277 * After each pipe execution, we extract any pending signals via sigtimedwait()
1280 * unsigned non_DFL_mask: a mask of such "special" signals
1281 * sigset_t blocked_set: current blocked signal set
1284 * clear bit in blocked_set unless it is also in non_DFL_mask
1285 * "trap 'cmd' SIGxxx":
1286 * set bit in blocked_set (even if 'cmd' is '')
1287 * after [v]fork, if we plan to be a shell:
1288 * unblock signals with special interactive handling
1289 * (child shell is not interactive),
1290 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1291 * after [v]fork, if we plan to exec:
1292 * POSIX says fork clears pending signal mask in child - no need to clear it.
1293 * Restore blocked signal set to one inherited by shell just prior to exec.
1295 * Note: as a result, we do not use signal handlers much. The only uses
1296 * are to count SIGCHLDs
1297 * and to restore tty pgrp on signal-induced exit.
1300 * Standard says "When a subshell is entered, traps that are not being ignored
1301 * are set to the default actions". bash interprets it so that traps which
1302 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1305 SPECIAL_INTERACTIVE_SIGS = 0
1310 SPECIAL_JOB_SIGS = 0
1318 #if ENABLE_HUSH_FAST
1319 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1322 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1328 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1329 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1330 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1331 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1333 /* Restores tty foreground process group, and exits.
1334 * May be called as signal handler for fatal signal
1335 * (will resend signal to itself, producing correct exit state)
1336 * or called directly with -EXITCODE.
1337 * We also call it if xfunc is exiting. */
1338 static void sigexit(int sig) NORETURN;
1339 static void sigexit(int sig)
1341 /* Disable all signals: job control, SIGPIPE, etc. */
1342 sigprocmask_allsigs(SIG_BLOCK);
1344 /* Careful: we can end up here after [v]fork. Do not restore
1345 * tty pgrp then, only top-level shell process does that */
1346 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1347 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1349 /* Not a signal, just exit */
1353 kill_myself_with_sig(sig); /* does not return */
1357 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1358 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1362 /* Restores tty foreground process group, and exits. */
1363 static void hush_exit(int exitcode) NORETURN;
1364 static void hush_exit(int exitcode)
1366 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1367 /* Prevent recursion:
1368 * trap "echo Hi; exit" EXIT; exit
1371 /* argv[0] is unused */
1372 argv[1] = G.traps[0];
1374 G.exiting = 1; /* prevent EXIT trap recursion */
1375 /* Note: G.traps[0] is not cleared!
1376 * "trap" will still show it, if executed
1383 sigexit(- (exitcode & 0xff));
1390 static int check_and_run_traps(int sig)
1392 /* I want it in rodata, not in bss.
1393 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1394 * initializer. But other compilers may still use bss.
1395 * TODO: find more portable solution.
1397 static const struct timespec zero_timespec = { 0, 0 };
1398 smalluint save_rcode;
1404 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1409 if (G.traps && G.traps[sig]) {
1410 if (G.traps[sig][0]) {
1411 /* We have user-defined handler */
1413 /* argv[0] is unused */
1414 argv[1] = G.traps[sig];
1416 save_rcode = G.last_exitcode;
1418 G.last_exitcode = save_rcode;
1419 } /* else: "" trap, ignoring signal */
1422 /* not a trap: special action */
1424 #if ENABLE_HUSH_FAST
1427 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1431 /* Builtin was ^C'ed, make it look prettier: */
1438 /* bash is observed to signal whole process groups,
1439 * not individual processes */
1440 for (job = G.job_list; job; job = job->next) {
1443 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1444 if (kill(- job->pgrp, SIGHUP) == 0)
1445 kill(- job->pgrp, SIGCONT);
1450 default: /* ignored: */
1451 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1459 static const char *get_cwd(int force)
1461 if (force || G.cwd == NULL) {
1462 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1463 * we must not try to free(bb_msg_unknown) */
1464 if (G.cwd == bb_msg_unknown)
1466 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1468 G.cwd = bb_msg_unknown;
1475 * Shell and environment variable support
1477 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1479 struct variable **pp;
1480 struct variable *cur;
1483 while ((cur = *pp) != NULL) {
1484 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1491 static const char* FAST_FUNC get_local_var_value(const char *name)
1493 struct variable **vpp;
1494 unsigned len = strlen(name);
1496 if (G.expanded_assignments) {
1497 char **cpp = G.expanded_assignments;
1500 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1501 return cp + len + 1;
1506 vpp = get_ptr_to_local_var(name, len);
1508 return (*vpp)->varstr + len + 1;
1510 if (strcmp(name, "PPID") == 0)
1511 return utoa(G.root_ppid);
1512 // bash compat: UID? EUID?
1513 #if ENABLE_HUSH_RANDOM_SUPPORT
1514 if (strcmp(name, "RANDOM") == 0)
1515 return utoa(next_random(&G.random_gen));
1520 /* str holds "NAME=VAL" and is expected to be malloced.
1521 * We take ownership of it.
1523 * 0: do not change export flag
1524 * (if creating new variable, flag will be 0)
1525 * 1: set export flag and putenv the variable
1526 * -1: clear export flag and unsetenv the variable
1527 * flg_read_only is set only when we handle -R var=val
1529 #if !BB_MMU && ENABLE_HUSH_LOCAL
1530 /* all params are used */
1531 #elif BB_MMU && ENABLE_HUSH_LOCAL
1532 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1533 set_local_var(str, flg_export, local_lvl)
1534 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1535 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1536 set_local_var(str, flg_export)
1537 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1538 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1539 set_local_var(str, flg_export, flg_read_only)
1541 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1543 struct variable **var_pp;
1544 struct variable *cur;
1548 eq_sign = strchr(str, '=');
1549 if (!eq_sign) { /* not expected to ever happen? */
1554 name_len = eq_sign - str + 1; /* including '=' */
1555 var_pp = &G.top_var;
1556 while ((cur = *var_pp) != NULL) {
1557 if (strncmp(cur->varstr, str, name_len) != 0) {
1558 var_pp = &cur->next;
1561 /* We found an existing var with this name */
1562 if (cur->flg_read_only) {
1566 bb_error_msg("%s: readonly variable", str);
1570 if (flg_export == -1) { // "&& cur->flg_export" ?
1571 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1576 #if ENABLE_HUSH_LOCAL
1577 if (cur->func_nest_level < local_lvl) {
1578 /* New variable is declared as local,
1579 * and existing one is global, or local
1580 * from enclosing function.
1581 * Remove and save old one: */
1582 *var_pp = cur->next;
1583 cur->next = *G.shadowed_vars_pp;
1584 *G.shadowed_vars_pp = cur;
1585 /* bash 3.2.33(1) and exported vars:
1587 * # f() { local z=a; env | grep ^z; }
1593 if (cur->flg_export)
1598 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1603 if (cur->max_len != 0) {
1604 if (cur->max_len >= strlen(str)) {
1605 /* This one is from startup env, reuse space */
1606 strcpy(cur->varstr, str);
1610 /* max_len == 0 signifies "malloced" var, which we can
1611 * (and has to) free */
1615 goto set_str_and_exp;
1618 /* Not found - create new variable struct */
1619 cur = xzalloc(sizeof(*cur));
1620 #if ENABLE_HUSH_LOCAL
1621 cur->func_nest_level = local_lvl;
1623 cur->next = *var_pp;
1629 cur->flg_read_only = flg_read_only;
1632 if (flg_export == 1)
1633 cur->flg_export = 1;
1634 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1635 cmdedit_update_prompt();
1636 if (cur->flg_export) {
1637 if (flg_export == -1) {
1638 cur->flg_export = 0;
1639 /* unsetenv was already done */
1641 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1642 return putenv(cur->varstr);
1648 /* Used at startup and after each cd */
1649 static void set_pwd_var(int exp)
1651 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1652 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1655 static int unset_local_var_len(const char *name, int name_len)
1657 struct variable *cur;
1658 struct variable **var_pp;
1661 return EXIT_SUCCESS;
1662 var_pp = &G.top_var;
1663 while ((cur = *var_pp) != NULL) {
1664 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1665 if (cur->flg_read_only) {
1666 bb_error_msg("%s: readonly variable", name);
1667 return EXIT_FAILURE;
1669 *var_pp = cur->next;
1670 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1671 bb_unsetenv(cur->varstr);
1672 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1673 cmdedit_update_prompt();
1677 return EXIT_SUCCESS;
1679 var_pp = &cur->next;
1681 return EXIT_SUCCESS;
1684 static int unset_local_var(const char *name)
1686 return unset_local_var_len(name, strlen(name));
1689 static void unset_vars(char **strings)
1697 const char *eq = strchrnul(*v, '=');
1698 unset_local_var_len(*v, (int)(eq - *v));
1704 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1706 char *var = xasprintf("%s=%s", name, val);
1707 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1712 * Helpers for "var1=val1 var2=val2 cmd" feature
1714 static void add_vars(struct variable *var)
1716 struct variable *next;
1720 var->next = G.top_var;
1722 if (var->flg_export) {
1723 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1724 putenv(var->varstr);
1726 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1732 static struct variable *set_vars_and_save_old(char **strings)
1735 struct variable *old = NULL;
1741 struct variable *var_p;
1742 struct variable **var_pp;
1745 eq = strchr(*s, '=');
1747 var_pp = get_ptr_to_local_var(*s, eq - *s);
1749 /* Remove variable from global linked list */
1751 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1752 *var_pp = var_p->next;
1753 /* Add it to returned list */
1757 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1768 static int FAST_FUNC static_get(struct in_str *i)
1778 static int FAST_FUNC static_peek(struct in_str *i)
1783 #if ENABLE_HUSH_INTERACTIVE
1785 static void cmdedit_update_prompt(void)
1787 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1788 G.PS1 = get_local_var_value("PS1");
1791 G.PS2 = get_local_var_value("PS2");
1799 static const char *setup_prompt_string(int promptmode)
1801 const char *prompt_str;
1802 debug_printf("setup_prompt_string %d ", promptmode);
1803 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1804 /* Set up the prompt */
1805 if (promptmode == 0) { /* PS1 */
1807 /* bash uses $PWD value, even if it is set by user.
1808 * It uses current dir only if PWD is unset.
1809 * We always use current dir. */
1810 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1815 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1816 debug_printf("result '%s'\n", prompt_str);
1820 static void get_user_input(struct in_str *i)
1823 const char *prompt_str;
1825 prompt_str = setup_prompt_string(i->promptmode);
1826 # if ENABLE_FEATURE_EDITING
1827 /* Enable command line editing only while a command line
1828 * is actually being read */
1831 /* buglet: SIGINT will not make new prompt to appear _at once_,
1832 * only after <Enter>. (^C will work) */
1833 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1834 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1835 check_and_run_traps(0);
1836 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1837 i->eof_flag = (r < 0);
1838 if (i->eof_flag) { /* EOF/error detected */
1839 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1840 G.user_input_buf[1] = '\0';
1845 fputs(prompt_str, stdout);
1847 G.user_input_buf[0] = r = fgetc(i->file);
1848 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1849 //do we need check_and_run_traps(0)? (maybe only if stdin)
1850 } while (G.flag_SIGINT);
1851 i->eof_flag = (r == EOF);
1853 i->p = G.user_input_buf;
1856 #endif /* INTERACTIVE */
1858 /* This is the magic location that prints prompts
1859 * and gets data back from the user */
1860 static int FAST_FUNC file_get(struct in_str *i)
1864 /* If there is data waiting, eat it up */
1865 if (i->p && *i->p) {
1866 #if ENABLE_HUSH_INTERACTIVE
1870 if (i->eof_flag && !*i->p)
1872 /* note: ch is never NUL */
1874 /* need to double check i->file because we might be doing something
1875 * more complicated by now, like sourcing or substituting. */
1876 #if ENABLE_HUSH_INTERACTIVE
1877 if (G_interactive_fd && i->promptme && i->file == stdin) {
1880 } while (!*i->p); /* need non-empty line */
1881 i->promptmode = 1; /* PS2 */
1886 do ch = fgetc(i->file); while (ch == '\0');
1888 debug_printf("file_get: got '%c' %d\n", ch, ch);
1889 #if ENABLE_HUSH_INTERACTIVE
1896 /* All callers guarantee this routine will never
1897 * be used right after a newline, so prompting is not needed.
1899 static int FAST_FUNC file_peek(struct in_str *i)
1902 if (i->p && *i->p) {
1903 if (i->eof_flag && !i->p[1])
1906 /* note: ch is never NUL */
1908 do ch = fgetc(i->file); while (ch == '\0');
1909 i->eof_flag = (ch == EOF);
1910 i->peek_buf[0] = ch;
1911 i->peek_buf[1] = '\0';
1913 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1917 static void setup_file_in_str(struct in_str *i, FILE *f)
1919 i->peek = file_peek;
1921 #if ENABLE_HUSH_INTERACTIVE
1923 i->promptmode = 0; /* PS1 */
1929 static void setup_string_in_str(struct in_str *i, const char *s)
1931 i->peek = static_peek;
1932 i->get = static_get;
1933 #if ENABLE_HUSH_INTERACTIVE
1935 i->promptmode = 0; /* PS1 */
1945 #define B_CHUNK (32 * sizeof(char*))
1947 static void o_reset_to_empty_unquoted(o_string *o)
1950 o->has_quoted_part = 0;
1955 static void o_free(o_string *o)
1958 memset(o, 0, sizeof(*o));
1961 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1966 static void o_grow_by(o_string *o, int len)
1968 if (o->length + len > o->maxlen) {
1969 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1970 o->data = xrealloc(o->data, 1 + o->maxlen);
1974 static void o_addchr(o_string *o, int ch)
1976 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1978 o->data[o->length] = ch;
1980 o->data[o->length] = '\0';
1983 static void o_addblock(o_string *o, const char *str, int len)
1986 memcpy(&o->data[o->length], str, len);
1988 o->data[o->length] = '\0';
1991 static void o_addstr(o_string *o, const char *str)
1993 o_addblock(o, str, strlen(str));
1997 static void nommu_addchr(o_string *o, int ch)
2003 # define nommu_addchr(o, str) ((void)0)
2006 static void o_addstr_with_NUL(o_string *o, const char *str)
2008 o_addblock(o, str, strlen(str) + 1);
2012 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2013 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2014 * Apparently, on unquoted $v bash still does globbing
2015 * ("v='*.txt'; echo $v" prints all .txt files),
2016 * but NOT brace expansion! Thus, there should be TWO independent
2017 * quoting mechanisms on $v expansion side: one protects
2018 * $v from brace expansion, and other additionally protects "$v" against globbing.
2019 * We have only second one.
2022 #if ENABLE_HUSH_BRACE_EXPANSION
2023 # define MAYBE_BRACES "{}"
2025 # define MAYBE_BRACES ""
2028 /* My analysis of quoting semantics tells me that state information
2029 * is associated with a destination, not a source.
2031 static void o_addqchr(o_string *o, int ch)
2034 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2039 o->data[o->length] = '\\';
2042 o->data[o->length] = ch;
2044 o->data[o->length] = '\0';
2047 static void o_addQchr(o_string *o, int ch)
2050 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2051 && strchr("*?[\\" MAYBE_BRACES, ch)
2054 o->data[o->length] = '\\';
2058 o->data[o->length] = ch;
2060 o->data[o->length] = '\0';
2063 static void o_addqblock(o_string *o, const char *str, int len)
2068 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2069 if (ordinary_cnt > len) /* paranoia */
2071 o_addblock(o, str, ordinary_cnt);
2072 if (ordinary_cnt == len)
2074 str += ordinary_cnt;
2075 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2079 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2081 o->data[o->length] = '\\';
2085 o->data[o->length] = ch;
2087 o->data[o->length] = '\0';
2091 static void o_addQblock(o_string *o, const char *str, int len)
2093 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2094 o_addblock(o, str, len);
2097 o_addqblock(o, str, len);
2100 static void o_addQstr(o_string *o, const char *str)
2102 o_addQblock(o, str, strlen(str));
2105 /* A special kind of o_string for $VAR and `cmd` expansion.
2106 * It contains char* list[] at the beginning, which is grown in 16 element
2107 * increments. Actual string data starts at the next multiple of 16 * (char*).
2108 * list[i] contains an INDEX (int!) into this string data.
2109 * It means that if list[] needs to grow, data needs to be moved higher up
2110 * but list[i]'s need not be modified.
2111 * NB: remembering how many list[i]'s you have there is crucial.
2112 * o_finalize_list() operation post-processes this structure - calculates
2113 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2115 #if DEBUG_EXPAND || DEBUG_GLOB
2116 static void debug_print_list(const char *prefix, o_string *o, int n)
2118 char **list = (char**)o->data;
2119 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2123 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2124 prefix, list, n, string_start, o->length, o->maxlen,
2125 !!(o->o_expflags & EXP_FLAG_GLOB),
2127 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2130 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2131 o->data + (int)list[i] + string_start,
2132 o->data + (int)list[i] + string_start);
2136 const char *p = o->data + (int)list[n - 1] + string_start;
2138 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2142 # define debug_print_list(prefix, o, n) ((void)0)
2145 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2146 * in list[n] so that it points past last stored byte so far.
2147 * It returns n+1. */
2148 static int o_save_ptr_helper(o_string *o, int n)
2150 char **list = (char**)o->data;
2154 if (!o->has_empty_slot) {
2155 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2156 string_len = o->length - string_start;
2157 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2158 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2159 /* list[n] points to string_start, make space for 16 more pointers */
2160 o->maxlen += 0x10 * sizeof(list[0]);
2161 o->data = xrealloc(o->data, o->maxlen + 1);
2162 list = (char**)o->data;
2163 memmove(list + n + 0x10, list + n, string_len);
2164 o->length += 0x10 * sizeof(list[0]);
2166 debug_printf_list("list[%d]=%d string_start=%d\n",
2167 n, string_len, string_start);
2170 /* We have empty slot at list[n], reuse without growth */
2171 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2172 string_len = o->length - string_start;
2173 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2174 n, string_len, string_start);
2175 o->has_empty_slot = 0;
2177 list[n] = (char*)(uintptr_t)string_len;
2181 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2182 static int o_get_last_ptr(o_string *o, int n)
2184 char **list = (char**)o->data;
2185 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2187 return ((int)(uintptr_t)list[n-1]) + string_start;
2190 #if ENABLE_HUSH_BRACE_EXPANSION
2191 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2192 * first, it processes even {a} (no commas), second,
2193 * I didn't manage to make it return strings when they don't match
2194 * existing files. Need to re-implement it.
2198 static int glob_needed(const char *s)
2207 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2213 /* Return pointer to next closing brace or to comma */
2214 static const char *next_brace_sub(const char *cp)
2218 while (*cp != '\0') {
2225 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2231 return *cp != '\0' ? cp : NULL;
2233 /* Recursive brace globber. Note: may garble pattern[]. */
2234 static int glob_brace(char *pattern, o_string *o, int n)
2236 char *new_pattern_buf;
2243 debug_printf_glob("glob_brace('%s')\n", pattern);
2249 if (*begin == '{') {
2250 /* Find the first sub-pattern and at the same time
2251 * find the rest after the closing brace */
2252 next = next_brace_sub(begin);
2254 /* An illegal expression */
2258 /* "{abc}" with no commas - illegal
2259 * brace expr, disregard and skip it */
2265 if (*begin == '\\' && begin[1] != '\0')
2269 debug_printf_glob("begin:%s\n", begin);
2270 debug_printf_glob("next:%s\n", next);
2272 /* Now find the end of the whole brace expression */
2274 while (*rest != '}') {
2275 rest = next_brace_sub(rest);
2277 /* An illegal expression */
2280 debug_printf_glob("rest:%s\n", rest);
2282 rest_len = strlen(++rest) + 1;
2284 /* We are sure the brace expression is well-formed */
2286 /* Allocate working buffer large enough for our work */
2287 new_pattern_buf = xmalloc(strlen(pattern));
2289 /* We have a brace expression. BEGIN points to the opening {,
2290 * NEXT points past the terminator of the first element, and REST
2291 * points past the final }. We will accumulate result names from
2292 * recursive runs for each brace alternative in the buffer using
2297 /* Construct the new glob expression */
2300 mempcpy(new_pattern_buf,
2301 /* We know the prefix for all sub-patterns */
2302 pattern, begin - pattern),
2306 /* Note: glob_brace() may garble new_pattern_buf[].
2307 * That's why we re-copy prefix every time (1st memcpy above).
2309 n = glob_brace(new_pattern_buf, o, n);
2311 /* We saw the last entry */
2315 next = next_brace_sub(next);
2317 free(new_pattern_buf);
2325 memset(&globdata, 0, sizeof(globdata));
2326 gr = glob(pattern, 0, NULL, &globdata);
2327 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2329 if (gr == GLOB_NOMATCH) {
2330 globfree(&globdata);
2331 /* NB: garbles parameter */
2332 unbackslash(pattern);
2333 o_addstr_with_NUL(o, pattern);
2334 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2335 return o_save_ptr_helper(o, n);
2337 if (gr == GLOB_NOSPACE)
2338 bb_error_msg_and_die(bb_msg_memory_exhausted);
2339 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2340 * but we didn't specify it. Paranoia again. */
2341 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2343 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2344 char **argv = globdata.gl_pathv;
2346 o_addstr_with_NUL(o, *argv);
2347 n = o_save_ptr_helper(o, n);
2353 globfree(&globdata);
2357 /* Performs globbing on last list[],
2358 * saving each result as a new list[].
2360 static int perform_glob(o_string *o, int n)
2362 char *pattern, *copy;
2364 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2366 return o_save_ptr_helper(o, n);
2367 pattern = o->data + o_get_last_ptr(o, n);
2368 debug_printf_glob("glob pattern '%s'\n", pattern);
2369 if (!glob_needed(pattern)) {
2370 /* unbackslash last string in o in place, fix length */
2371 o->length = unbackslash(pattern) - o->data;
2372 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2373 return o_save_ptr_helper(o, n);
2376 copy = xstrdup(pattern);
2377 /* "forget" pattern in o */
2378 o->length = pattern - o->data;
2379 n = glob_brace(copy, o, n);
2382 debug_print_list("perform_glob returning", o, n);
2386 #else /* !HUSH_BRACE_EXPANSION */
2389 static int glob_needed(const char *s)
2398 if (*s == '*' || *s == '[' || *s == '?')
2404 /* Performs globbing on last list[],
2405 * saving each result as a new list[].
2407 static int perform_glob(o_string *o, int n)
2413 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2415 return o_save_ptr_helper(o, n);
2416 pattern = o->data + o_get_last_ptr(o, n);
2417 debug_printf_glob("glob pattern '%s'\n", pattern);
2418 if (!glob_needed(pattern)) {
2420 /* unbackslash last string in o in place, fix length */
2421 o->length = unbackslash(pattern) - o->data;
2422 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2423 return o_save_ptr_helper(o, n);
2426 memset(&globdata, 0, sizeof(globdata));
2427 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2428 * If we glob "*.\*" and don't find anything, we need
2429 * to fall back to using literal "*.*", but GLOB_NOCHECK
2430 * will return "*.\*"!
2432 gr = glob(pattern, 0, NULL, &globdata);
2433 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2435 if (gr == GLOB_NOMATCH) {
2436 globfree(&globdata);
2439 if (gr == GLOB_NOSPACE)
2440 bb_error_msg_and_die(bb_msg_memory_exhausted);
2441 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2442 * but we didn't specify it. Paranoia again. */
2443 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2445 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2446 char **argv = globdata.gl_pathv;
2447 /* "forget" pattern in o */
2448 o->length = pattern - o->data;
2450 o_addstr_with_NUL(o, *argv);
2451 n = o_save_ptr_helper(o, n);
2457 globfree(&globdata);
2459 debug_print_list("perform_glob returning", o, n);
2463 #endif /* !HUSH_BRACE_EXPANSION */
2465 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2466 * Otherwise, just finish current list[] and start new */
2467 static int o_save_ptr(o_string *o, int n)
2469 if (o->o_expflags & EXP_FLAG_GLOB) {
2470 /* If o->has_empty_slot, list[n] was already globbed
2471 * (if it was requested back then when it was filled)
2472 * so don't do that again! */
2473 if (!o->has_empty_slot)
2474 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2476 return o_save_ptr_helper(o, n);
2479 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2480 static char **o_finalize_list(o_string *o, int n)
2485 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2487 debug_print_list("finalized", o, n);
2488 debug_printf_expand("finalized n:%d\n", n);
2489 list = (char**)o->data;
2490 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2494 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2499 static void free_pipe_list(struct pipe *pi);
2501 /* Returns pi->next - next pipe in the list */
2502 static struct pipe *free_pipe(struct pipe *pi)
2507 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2508 for (i = 0; i < pi->num_cmds; i++) {
2509 struct command *command;
2510 struct redir_struct *r, *rnext;
2512 command = &pi->cmds[i];
2513 debug_printf_clean(" command %d:\n", i);
2514 if (command->argv) {
2518 for (a = 0, p = command->argv; *p; a++, p++) {
2519 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2522 free_strings(command->argv);
2523 //command->argv = NULL;
2525 /* not "else if": on syntax error, we may have both! */
2526 if (command->group) {
2527 debug_printf_clean(" begin group (cmd_type:%d)\n",
2529 free_pipe_list(command->group);
2530 debug_printf_clean(" end group\n");
2531 //command->group = NULL;
2533 /* else is crucial here.
2534 * If group != NULL, child_func is meaningless */
2535 #if ENABLE_HUSH_FUNCTIONS
2536 else if (command->child_func) {
2537 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2538 command->child_func->parent_cmd = NULL;
2542 free(command->group_as_string);
2543 //command->group_as_string = NULL;
2545 for (r = command->redirects; r; r = rnext) {
2546 debug_printf_clean(" redirect %d%s",
2547 r->rd_fd, redir_table[r->rd_type].descrip);
2548 /* guard against the case >$FOO, where foo is unset or blank */
2549 if (r->rd_filename) {
2550 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2551 free(r->rd_filename);
2552 //r->rd_filename = NULL;
2554 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2558 //command->redirects = NULL;
2560 free(pi->cmds); /* children are an array, they get freed all at once */
2564 //pi->cmdtext = NULL;
2572 static void free_pipe_list(struct pipe *pi)
2576 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2578 debug_printf_clean("pipe followup code %d\n", pi->followup);
2584 /*** Parsing routines ***/
2586 static struct pipe *new_pipe(void)
2589 pi = xzalloc(sizeof(struct pipe));
2590 /*pi->followup = 0; - deliberately invalid value */
2591 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2595 /* Command (member of a pipe) is complete, or we start a new pipe
2596 * if ctx->command is NULL.
2597 * No errors possible here.
2599 static int done_command(struct parse_context *ctx)
2601 /* The command is really already in the pipe structure, so
2602 * advance the pipe counter and make a new, null command. */
2603 struct pipe *pi = ctx->pipe;
2604 struct command *command = ctx->command;
2607 if (IS_NULL_CMD(command)) {
2608 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2612 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2613 //debug_print_tree(ctx->list_head, 20);
2615 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2618 /* Only real trickiness here is that the uncommitted
2619 * command structure is not counted in pi->num_cmds. */
2620 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2621 ctx->command = command = &pi->cmds[pi->num_cmds];
2623 memset(command, 0, sizeof(*command));
2624 return pi->num_cmds; /* used only for 0/nonzero check */
2627 static void done_pipe(struct parse_context *ctx, pipe_style type)
2631 debug_printf_parse("done_pipe entered, followup %d\n", type);
2632 /* Close previous command */
2633 not_null = done_command(ctx);
2634 ctx->pipe->followup = type;
2636 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2637 ctx->ctx_inverted = 0;
2638 ctx->pipe->res_word = ctx->ctx_res_w;
2641 /* Without this check, even just <enter> on command line generates
2642 * tree of three NOPs (!). Which is harmless but annoying.
2643 * IOW: it is safe to do it unconditionally. */
2646 || ctx->ctx_res_w == RES_FI
2648 #if ENABLE_HUSH_LOOPS
2649 || ctx->ctx_res_w == RES_DONE
2650 || ctx->ctx_res_w == RES_FOR
2651 || ctx->ctx_res_w == RES_IN
2653 #if ENABLE_HUSH_CASE
2654 || ctx->ctx_res_w == RES_ESAC
2658 debug_printf_parse("done_pipe: adding new pipe: "
2659 "not_null:%d ctx->ctx_res_w:%d\n",
2660 not_null, ctx->ctx_res_w);
2662 ctx->pipe->next = new_p;
2664 /* RES_THEN, RES_DO etc are "sticky" -
2665 * they remain set for pipes inside if/while.
2666 * This is used to control execution.
2667 * RES_FOR and RES_IN are NOT sticky (needed to support
2668 * cases where variable or value happens to match a keyword):
2670 #if ENABLE_HUSH_LOOPS
2671 if (ctx->ctx_res_w == RES_FOR
2672 || ctx->ctx_res_w == RES_IN)
2673 ctx->ctx_res_w = RES_NONE;
2675 #if ENABLE_HUSH_CASE
2676 if (ctx->ctx_res_w == RES_MATCH)
2677 ctx->ctx_res_w = RES_CASE_BODY;
2678 if (ctx->ctx_res_w == RES_CASE)
2679 ctx->ctx_res_w = RES_CASE_IN;
2681 ctx->command = NULL; /* trick done_command below */
2682 /* Create the memory for command, roughly:
2683 * ctx->pipe->cmds = new struct command;
2684 * ctx->command = &ctx->pipe->cmds[0];
2687 //debug_print_tree(ctx->list_head, 10);
2689 debug_printf_parse("done_pipe return\n");
2692 static void initialize_context(struct parse_context *ctx)
2694 memset(ctx, 0, sizeof(*ctx));
2695 ctx->pipe = ctx->list_head = new_pipe();
2696 /* Create the memory for command, roughly:
2697 * ctx->pipe->cmds = new struct command;
2698 * ctx->command = &ctx->pipe->cmds[0];
2703 /* If a reserved word is found and processed, parse context is modified
2704 * and 1 is returned.
2707 struct reserved_combo {
2710 unsigned char assignment_flag;
2714 FLAG_END = (1 << RES_NONE ),
2716 FLAG_IF = (1 << RES_IF ),
2717 FLAG_THEN = (1 << RES_THEN ),
2718 FLAG_ELIF = (1 << RES_ELIF ),
2719 FLAG_ELSE = (1 << RES_ELSE ),
2720 FLAG_FI = (1 << RES_FI ),
2722 # if ENABLE_HUSH_LOOPS
2723 FLAG_FOR = (1 << RES_FOR ),
2724 FLAG_WHILE = (1 << RES_WHILE),
2725 FLAG_UNTIL = (1 << RES_UNTIL),
2726 FLAG_DO = (1 << RES_DO ),
2727 FLAG_DONE = (1 << RES_DONE ),
2728 FLAG_IN = (1 << RES_IN ),
2730 # if ENABLE_HUSH_CASE
2731 FLAG_MATCH = (1 << RES_MATCH),
2732 FLAG_ESAC = (1 << RES_ESAC ),
2734 FLAG_START = (1 << RES_XXXX ),
2737 static const struct reserved_combo* match_reserved_word(o_string *word)
2739 /* Mostly a list of accepted follow-up reserved words.
2740 * FLAG_END means we are done with the sequence, and are ready
2741 * to turn the compound list into a command.
2742 * FLAG_START means the word must start a new compound list.
2744 static const struct reserved_combo reserved_list[] = {
2746 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2747 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2748 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2749 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2750 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2751 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2753 # if ENABLE_HUSH_LOOPS
2754 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2755 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2756 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2757 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2758 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2759 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2761 # if ENABLE_HUSH_CASE
2762 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2763 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2766 const struct reserved_combo *r;
2768 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2769 if (strcmp(word->data, r->literal) == 0)
2774 /* Return 0: not a keyword, 1: keyword
2776 static int reserved_word(o_string *word, struct parse_context *ctx)
2778 # if ENABLE_HUSH_CASE
2779 static const struct reserved_combo reserved_match = {
2780 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2783 const struct reserved_combo *r;
2785 if (word->has_quoted_part)
2787 r = match_reserved_word(word);
2791 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2792 # if ENABLE_HUSH_CASE
2793 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2794 /* "case word IN ..." - IN part starts first MATCH part */
2795 r = &reserved_match;
2798 if (r->flag == 0) { /* '!' */
2799 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2800 syntax_error("! ! command");
2801 ctx->ctx_res_w = RES_SNTX;
2803 ctx->ctx_inverted = 1;
2806 if (r->flag & FLAG_START) {
2807 struct parse_context *old;
2809 old = xmalloc(sizeof(*old));
2810 debug_printf_parse("push stack %p\n", old);
2811 *old = *ctx; /* physical copy */
2812 initialize_context(ctx);
2814 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2815 syntax_error_at(word->data);
2816 ctx->ctx_res_w = RES_SNTX;
2819 /* "{...} fi" is ok. "{...} if" is not
2821 * if { echo foo; } then { echo bar; } fi */
2822 if (ctx->command->group)
2823 done_pipe(ctx, PIPE_SEQ);
2826 ctx->ctx_res_w = r->res;
2827 ctx->old_flag = r->flag;
2828 word->o_assignment = r->assignment_flag;
2830 if (ctx->old_flag & FLAG_END) {
2831 struct parse_context *old;
2833 done_pipe(ctx, PIPE_SEQ);
2834 debug_printf_parse("pop stack %p\n", ctx->stack);
2836 old->command->group = ctx->list_head;
2837 old->command->cmd_type = CMD_NORMAL;
2839 o_addstr(&old->as_string, ctx->as_string.data);
2840 o_free_unsafe(&ctx->as_string);
2841 old->command->group_as_string = xstrdup(old->as_string.data);
2842 debug_printf_parse("pop, remembering as:'%s'\n",
2843 old->command->group_as_string);
2845 *ctx = *old; /* physical copy */
2850 #endif /* HAS_KEYWORDS */
2852 /* Word is complete, look at it and update parsing context.
2853 * Normal return is 0. Syntax errors return 1.
2854 * Note: on return, word is reset, but not o_free'd!
2856 static int done_word(o_string *word, struct parse_context *ctx)
2858 struct command *command = ctx->command;
2860 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2861 if (word->length == 0 && !word->has_quoted_part) {
2862 debug_printf_parse("done_word return 0: true null, ignored\n");
2866 if (ctx->pending_redirect) {
2867 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2868 * only if run as "bash", not "sh" */
2869 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2871 * ...the word that follows the redirection operator
2872 * shall be subjected to tilde expansion, parameter expansion,
2873 * command substitution, arithmetic expansion, and quote
2874 * removal. Pathname expansion shall not be performed
2875 * on the word by a non-interactive shell; an interactive
2876 * shell may perform it, but shall do so only when
2877 * the expansion would result in one word."
2879 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2880 /* Cater for >\file case:
2881 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2882 * Same with heredocs:
2883 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2885 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2886 unbackslash(ctx->pending_redirect->rd_filename);
2887 /* Is it <<"HEREDOC"? */
2888 if (word->has_quoted_part) {
2889 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2892 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2893 ctx->pending_redirect = NULL;
2895 /* If this word wasn't an assignment, next ones definitely
2896 * can't be assignments. Even if they look like ones. */
2897 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2898 && word->o_assignment != WORD_IS_KEYWORD
2900 word->o_assignment = NOT_ASSIGNMENT;
2902 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2903 command->assignment_cnt++;
2904 word->o_assignment = MAYBE_ASSIGNMENT;
2908 # if ENABLE_HUSH_CASE
2909 if (ctx->ctx_dsemicolon
2910 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2912 /* already done when ctx_dsemicolon was set to 1: */
2913 /* ctx->ctx_res_w = RES_MATCH; */
2914 ctx->ctx_dsemicolon = 0;
2917 if (!command->argv /* if it's the first word... */
2918 # if ENABLE_HUSH_LOOPS
2919 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2920 && ctx->ctx_res_w != RES_IN
2922 # if ENABLE_HUSH_CASE
2923 && ctx->ctx_res_w != RES_CASE
2926 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2927 if (reserved_word(word, ctx)) {
2928 o_reset_to_empty_unquoted(word);
2929 debug_printf_parse("done_word return %d\n",
2930 (ctx->ctx_res_w == RES_SNTX));
2931 return (ctx->ctx_res_w == RES_SNTX);
2933 # if ENABLE_HUSH_BASH_COMPAT
2934 if (strcmp(word->data, "[[") == 0) {
2935 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2941 if (command->group) {
2942 /* "{ echo foo; } echo bar" - bad */
2943 syntax_error_at(word->data);
2944 debug_printf_parse("done_word return 1: syntax error, "
2945 "groups and arglists don't mix\n");
2948 if (word->has_quoted_part
2949 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2950 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2951 /* (otherwise it's known to be not empty and is already safe) */
2953 /* exclude "$@" - it can expand to no word despite "" */
2954 char *p = word->data;
2955 while (p[0] == SPECIAL_VAR_SYMBOL
2956 && (p[1] & 0x7f) == '@'
2957 && p[2] == SPECIAL_VAR_SYMBOL
2961 if (p == word->data || p[0] != '\0') {
2962 /* saw no "$@", or not only "$@" but some
2963 * real text is there too */
2964 /* insert "empty variable" reference, this makes
2965 * e.g. "", $empty"" etc to not disappear */
2966 o_addchr(word, SPECIAL_VAR_SYMBOL);
2967 o_addchr(word, SPECIAL_VAR_SYMBOL);
2970 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2971 debug_print_strings("word appended to argv", command->argv);
2974 #if ENABLE_HUSH_LOOPS
2975 if (ctx->ctx_res_w == RES_FOR) {
2976 if (word->has_quoted_part
2977 || !is_well_formed_var_name(command->argv[0], '\0')
2979 /* bash says just "not a valid identifier" */
2980 syntax_error("not a valid identifier in for");
2983 /* Force FOR to have just one word (variable name) */
2984 /* NB: basically, this makes hush see "for v in ..."
2985 * syntax as if it is "for v; in ...". FOR and IN become
2986 * two pipe structs in parse tree. */
2987 done_pipe(ctx, PIPE_SEQ);
2990 #if ENABLE_HUSH_CASE
2991 /* Force CASE to have just one word */
2992 if (ctx->ctx_res_w == RES_CASE) {
2993 done_pipe(ctx, PIPE_SEQ);
2997 o_reset_to_empty_unquoted(word);
2999 debug_printf_parse("done_word return 0\n");
3004 /* Peek ahead in the input to find out if we have a "&n" construct,
3005 * as in "2>&1", that represents duplicating a file descriptor.
3007 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3008 * REDIRFD_SYNTAX_ERR if syntax error,
3009 * REDIRFD_TO_FILE if no & was seen,
3010 * or the number found.
3013 #define parse_redir_right_fd(as_string, input) \
3014 parse_redir_right_fd(input)
3016 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3022 return REDIRFD_TO_FILE;
3024 ch = i_getch(input); /* get the & */
3025 nommu_addchr(as_string, ch);
3028 ch = i_getch(input);
3029 nommu_addchr(as_string, ch);
3030 return REDIRFD_CLOSE;
3034 while (ch != EOF && isdigit(ch)) {
3035 d = d*10 + (ch-'0');
3037 ch = i_getch(input);
3038 nommu_addchr(as_string, ch);
3043 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3045 bb_error_msg("ambiguous redirect");
3046 return REDIRFD_SYNTAX_ERR;
3049 /* Return code is 0 normal, 1 if a syntax error is detected
3051 static int parse_redirect(struct parse_context *ctx,
3054 struct in_str *input)
3056 struct command *command = ctx->command;
3057 struct redir_struct *redir;
3058 struct redir_struct **redirp;
3061 dup_num = REDIRFD_TO_FILE;
3062 if (style != REDIRECT_HEREDOC) {
3063 /* Check for a '>&1' type redirect */
3064 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3065 if (dup_num == REDIRFD_SYNTAX_ERR)
3068 int ch = i_peek(input);
3069 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3070 if (dup_num) { /* <<-... */
3071 ch = i_getch(input);
3072 nommu_addchr(&ctx->as_string, ch);
3077 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3078 int ch = i_peek(input);
3080 /* >|FILE redirect ("clobbering" >).
3081 * Since we do not support "set -o noclobber" yet,
3082 * >| and > are the same for now. Just eat |.
3084 ch = i_getch(input);
3085 nommu_addchr(&ctx->as_string, ch);
3089 /* Create a new redir_struct and append it to the linked list */
3090 redirp = &command->redirects;
3091 while ((redir = *redirp) != NULL) {
3092 redirp = &(redir->next);
3094 *redirp = redir = xzalloc(sizeof(*redir));
3095 /* redir->next = NULL; */
3096 /* redir->rd_filename = NULL; */
3097 redir->rd_type = style;
3098 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3100 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3101 redir_table[style].descrip);
3103 redir->rd_dup = dup_num;
3104 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3105 /* Erik had a check here that the file descriptor in question
3106 * is legit; I postpone that to "run time"
3107 * A "-" representation of "close me" shows up as a -3 here */
3108 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3109 redir->rd_fd, redir->rd_dup);
3111 /* Set ctx->pending_redirect, so we know what to do at the
3112 * end of the next parsed word. */
3113 ctx->pending_redirect = redir;
3118 /* If a redirect is immediately preceded by a number, that number is
3119 * supposed to tell which file descriptor to redirect. This routine
3120 * looks for such preceding numbers. In an ideal world this routine
3121 * needs to handle all the following classes of redirects...
3122 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3123 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3124 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3125 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3127 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3129 * ... If n is quoted, the number shall not be recognized as part of
3130 * the redirection expression. For example:
3132 * writes the character 2 into file a"
3133 * We are getting it right by setting ->has_quoted_part on any \<char>
3135 * A -1 return means no valid number was found,
3136 * the caller should use the appropriate default for this redirection.
3138 static int redirect_opt_num(o_string *o)
3142 if (o->data == NULL)
3144 num = bb_strtou(o->data, NULL, 10);
3145 if (errno || num < 0)
3147 o_reset_to_empty_unquoted(o);
3152 #define fetch_till_str(as_string, input, word, skip_tabs) \
3153 fetch_till_str(input, word, skip_tabs)
3155 static char *fetch_till_str(o_string *as_string,
3156 struct in_str *input,
3160 o_string heredoc = NULL_O_STRING;
3162 int prev = 0; /* not \ */
3167 ch = i_getch(input);
3169 nommu_addchr(as_string, ch);
3170 if ((ch == '\n' || ch == EOF)
3171 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3173 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3174 heredoc.data[past_EOL] = '\0';
3175 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3176 return heredoc.data;
3178 while (ch == '\n') {
3179 o_addchr(&heredoc, ch);
3182 past_EOL = heredoc.length;
3184 ch = i_getch(input);
3186 nommu_addchr(as_string, ch);
3187 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3191 o_free_unsafe(&heredoc);
3194 o_addchr(&heredoc, ch);
3195 nommu_addchr(as_string, ch);
3196 if (prev == '\\' && ch == '\\')
3197 /* Correctly handle foo\\<eol> (not a line cont.) */
3198 prev = 0; /* not \ */
3204 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3205 * and load them all. There should be exactly heredoc_cnt of them.
3207 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3209 struct pipe *pi = ctx->list_head;
3211 while (pi && heredoc_cnt) {
3213 struct command *cmd = pi->cmds;
3215 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3217 cmd->argv ? cmd->argv[0] : "NONE");
3218 for (i = 0; i < pi->num_cmds; i++) {
3219 struct redir_struct *redir = cmd->redirects;
3221 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3222 i, cmd->argv ? cmd->argv[0] : "NONE");
3224 if (redir->rd_type == REDIRECT_HEREDOC) {
3227 redir->rd_type = REDIRECT_HEREDOC2;
3228 /* redir->rd_dup is (ab)used to indicate <<- */
3229 p = fetch_till_str(&ctx->as_string, input,
3230 redir->rd_filename, redir->rd_dup);
3232 syntax_error("unexpected EOF in here document");
3235 free(redir->rd_filename);
3236 redir->rd_filename = p;
3239 redir = redir->next;
3246 /* Should be 0. If it isn't, it's a parse error */
3248 bb_error_msg_and_die("heredoc BUG 2");
3254 static int run_list(struct pipe *pi);
3256 #define parse_stream(pstring, input, end_trigger) \
3257 parse_stream(input, end_trigger)
3259 static struct pipe *parse_stream(char **pstring,
3260 struct in_str *input,
3264 #if !ENABLE_HUSH_FUNCTIONS
3265 #define parse_group(dest, ctx, input, ch) \
3266 parse_group(ctx, input, ch)
3268 static int parse_group(o_string *dest, struct parse_context *ctx,
3269 struct in_str *input, int ch)
3271 /* dest contains characters seen prior to ( or {.
3272 * Typically it's empty, but for function defs,
3273 * it contains function name (without '()'). */
3274 struct pipe *pipe_list;
3276 struct command *command = ctx->command;
3278 debug_printf_parse("parse_group entered\n");
3279 #if ENABLE_HUSH_FUNCTIONS
3280 if (ch == '(' && !dest->has_quoted_part) {
3282 if (done_word(dest, ctx))
3285 goto skip; /* (... */
3286 if (command->argv[1]) { /* word word ... (... */
3287 syntax_error_unexpected_ch('(');
3290 /* it is "word(..." or "word (..." */
3292 ch = i_getch(input);
3293 while (ch == ' ' || ch == '\t');
3295 syntax_error_unexpected_ch(ch);
3298 nommu_addchr(&ctx->as_string, ch);
3300 ch = i_getch(input);
3301 while (ch == ' ' || ch == '\t' || ch == '\n');
3303 syntax_error_unexpected_ch(ch);
3306 nommu_addchr(&ctx->as_string, ch);
3307 command->cmd_type = CMD_FUNCDEF;
3312 #if 0 /* Prevented by caller */
3313 if (command->argv /* word [word]{... */
3314 || dest->length /* word{... */
3315 || dest->has_quoted_part /* ""{... */
3318 debug_printf_parse("parse_group return 1: "
3319 "syntax error, groups and arglists don't mix\n");
3324 #if ENABLE_HUSH_FUNCTIONS
3330 command->cmd_type = CMD_SUBSHELL;
3332 /* bash does not allow "{echo...", requires whitespace */
3333 ch = i_getch(input);
3334 if (ch != ' ' && ch != '\t' && ch != '\n') {
3335 syntax_error_unexpected_ch(ch);
3338 nommu_addchr(&ctx->as_string, ch);
3343 # define as_string NULL
3345 char *as_string = NULL;
3347 pipe_list = parse_stream(&as_string, input, endch);
3350 o_addstr(&ctx->as_string, as_string);
3352 /* empty ()/{} or parse error? */
3353 if (!pipe_list || pipe_list == ERR_PTR) {
3354 /* parse_stream already emitted error msg */
3357 debug_printf_parse("parse_group return 1: "
3358 "parse_stream returned %p\n", pipe_list);
3361 command->group = pipe_list;
3363 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3364 command->group_as_string = as_string;
3365 debug_printf_parse("end of group, remembering as:'%s'\n",
3366 command->group_as_string);
3370 debug_printf_parse("parse_group return 0\n");
3372 /* command remains "open", available for possible redirects */
3375 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3376 /* Subroutines for copying $(...) and `...` things */
3377 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3379 static void add_till_single_quote(o_string *dest, struct in_str *input)
3382 int ch = i_getch(input);
3384 syntax_error_unterm_ch('\'');
3385 /*xfunc_die(); - redundant */
3392 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3393 static void add_till_double_quote(o_string *dest, struct in_str *input)
3396 int ch = i_getch(input);
3398 syntax_error_unterm_ch('"');
3399 /*xfunc_die(); - redundant */
3403 if (ch == '\\') { /* \x. Copy both chars. */
3405 ch = i_getch(input);
3409 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3413 //if (ch == '$') ...
3416 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3418 * "Within the backquoted style of command substitution, backslash
3419 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3420 * The search for the matching backquote shall be satisfied by the first
3421 * backquote found without a preceding backslash; during this search,
3422 * if a non-escaped backquote is encountered within a shell comment,
3423 * a here-document, an embedded command substitution of the $(command)
3424 * form, or a quoted string, undefined results occur. A single-quoted
3425 * or double-quoted string that begins, but does not end, within the
3426 * "`...`" sequence produces undefined results."
3428 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3430 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3433 int ch = i_getch(input);
3437 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3438 ch = i_getch(input);
3442 && (!in_dquote || ch != '"')
3444 o_addchr(dest, '\\');
3448 syntax_error_unterm_ch('`');
3449 /*xfunc_die(); - redundant */
3454 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3455 * quoting and nested ()s.
3456 * "With the $(command) style of command substitution, all characters
3457 * following the open parenthesis to the matching closing parenthesis
3458 * constitute the command. Any valid shell script can be used for command,
3459 * except a script consisting solely of redirections which produces
3460 * unspecified results."
3462 * echo $(echo '(TEST)' BEST) (TEST) BEST
3463 * echo $(echo 'TEST)' BEST) TEST) BEST
3464 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3466 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3467 * can contain arbitrary constructs, just like $(cmd).
3468 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3469 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3471 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3472 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3475 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3476 # if ENABLE_HUSH_BASH_COMPAT
3477 char end_char2 = end_ch >> 8;
3479 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3482 ch = i_getch(input);
3484 syntax_error_unterm_ch(end_ch);
3485 /*xfunc_die(); - redundant */
3487 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3490 /* we look for closing )) of $((EXPR)) */
3491 if (i_peek(input) == end_ch) {
3492 i_getch(input); /* eat second ')' */
3497 if (ch == '(' || ch == '{') {
3498 ch = (ch == '(' ? ')' : '}');
3499 add_till_closing_bracket(dest, input, ch);
3504 add_till_single_quote(dest, input);
3509 add_till_double_quote(dest, input);
3514 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3519 /* \x. Copy verbatim. Important for \(, \) */
3520 ch = i_getch(input);
3522 syntax_error_unterm_ch(')');
3523 /*xfunc_die(); - redundant */
3531 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3533 /* Return code: 0 for OK, 1 for syntax error */
3535 #define parse_dollar(as_string, dest, input, quote_mask) \
3536 parse_dollar(dest, input, quote_mask)
3537 #define as_string NULL
3539 static int parse_dollar(o_string *as_string,
3541 struct in_str *input, unsigned char quote_mask)
3543 int ch = i_peek(input); /* first character after the $ */
3545 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3547 ch = i_getch(input);
3548 nommu_addchr(as_string, ch);
3550 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3552 debug_printf_parse(": '%c'\n", ch);
3553 o_addchr(dest, ch | quote_mask);
3556 if (!isalnum(ch) && ch != '_')
3558 ch = i_getch(input);
3559 nommu_addchr(as_string, ch);
3561 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3562 } else if (isdigit(ch)) {
3564 ch = i_getch(input);
3565 nommu_addchr(as_string, ch);
3566 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3567 debug_printf_parse(": '%c'\n", ch);
3568 o_addchr(dest, ch | quote_mask);
3569 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3570 } else switch (ch) {
3572 case '!': /* last bg pid */
3573 case '?': /* last exit code */
3574 case '#': /* number of args */
3575 case '*': /* args */
3576 case '@': /* args */
3577 goto make_one_char_var;
3579 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3581 ch = i_getch(input); /* eat '{' */
3582 nommu_addchr(as_string, ch);
3584 ch = i_getch(input); /* first char after '{' */
3585 /* It should be ${?}, or ${#var},
3586 * or even ${?+subst} - operator acting on a special variable,
3587 * or the beginning of variable name.
3590 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3593 syntax_error_unterm_str("${name}");
3594 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3597 nommu_addchr(as_string, ch);
3600 /* It's possible to just call add_till_closing_bracket() at this point.
3601 * However, this regresses some of our testsuite cases
3602 * which check invalid constructs like ${%}.
3603 * Oh well... let's check that the var name part is fine... */
3609 debug_printf_parse(": '%c'\n", ch);
3611 ch = i_getch(input);
3612 nommu_addchr(as_string, ch);
3616 if (!isalnum(ch) && ch != '_') {
3618 unsigned char last_ch;
3619 /* handle parameter expansions
3620 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3622 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3623 goto bad_dollar_syntax;
3625 /* Eat everything until closing '}' (or ':') */
3627 if (ENABLE_HUSH_BASH_COMPAT
3629 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3631 /* It's ${var:N[:M]} thing */
3632 end_ch = '}' * 0x100 + ':';
3634 if (ENABLE_HUSH_BASH_COMPAT
3637 /* It's ${var/[/]pattern[/repl]} thing */
3638 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3640 nommu_addchr(as_string, '/');
3643 end_ch = '}' * 0x100 + '/';
3649 #if ENABLE_HUSH_DOLLAR_OPS
3650 last_ch = add_till_closing_bracket(dest, input, end_ch);
3652 #error Simple code to only allow ${var} is not implemented
3655 o_addstr(as_string, dest->data + pos);
3656 o_addchr(as_string, last_ch);
3659 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3660 /* close the first block: */
3661 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3662 /* while parsing N from ${var:N[:M]}
3663 * or pattern from ${var/[/]pattern[/repl]} */
3664 if ((end_ch & 0xff) == last_ch) {
3665 /* got ':' or '/'- parse the rest */
3670 if (end_ch == '}' * 0x100 + ':') {
3671 /* it's ${var:N} - emulate :999999999 */
3672 o_addstr(dest, "999999999");
3673 } /* else: it's ${var/[/]pattern} */
3678 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3681 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3685 ch = i_getch(input);
3686 nommu_addchr(as_string, ch);
3687 # if ENABLE_SH_MATH_SUPPORT
3688 if (i_peek(input) == '(') {
3689 ch = i_getch(input);
3690 nommu_addchr(as_string, ch);
3691 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3692 o_addchr(dest, /*quote_mask |*/ '+');
3695 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3697 o_addstr(as_string, dest->data + pos);
3698 o_addchr(as_string, ')');
3699 o_addchr(as_string, ')');
3701 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3705 # if ENABLE_HUSH_TICK
3706 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3707 o_addchr(dest, quote_mask | '`');
3710 add_till_closing_bracket(dest, input, ')');
3712 o_addstr(as_string, dest->data + pos);
3713 o_addchr(as_string, ')');
3715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3721 ch = i_getch(input);
3722 nommu_addchr(as_string, ch);
3724 if (isalnum(ch)) { /* it's $_name or $_123 */
3729 /* TODO: $_ and $-: */
3730 /* $_ Shell or shell script name; or last argument of last command
3731 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3732 * but in command's env, set to full pathname used to invoke it */
3733 /* $- Option flags set by set builtin or shell options (-i etc) */
3735 o_addQchr(dest, '$');
3737 debug_printf_parse("parse_dollar return 0\n");
3743 # if ENABLE_HUSH_BASH_COMPAT
3744 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3745 encode_string(dest, input, dquote_end, process_bkslash)
3747 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3748 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3749 encode_string(dest, input, dquote_end)
3751 #define as_string NULL
3755 # if ENABLE_HUSH_BASH_COMPAT
3756 /* all parameters are needed, no macro tricks */
3758 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3759 encode_string(as_string, dest, input, dquote_end)
3762 static int encode_string(o_string *as_string,
3764 struct in_str *input,
3766 int process_bkslash)
3768 #if !ENABLE_HUSH_BASH_COMPAT
3769 const int process_bkslash = 1;
3775 ch = i_getch(input);
3777 nommu_addchr(as_string, ch);
3778 if (ch == dquote_end) { /* may be only '"' or EOF */
3779 debug_printf_parse("encode_string return 0\n");
3782 /* note: can't move it above ch == dquote_end check! */
3784 syntax_error_unterm_ch('"');
3785 /*xfunc_die(); - redundant */
3789 next = i_peek(input);
3791 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3792 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3793 if (process_bkslash && ch == '\\') {
3795 syntax_error("\\<eof>");
3799 * "The backslash retains its special meaning [in "..."]
3800 * only when followed by one of the following characters:
3801 * $, `, ", \, or <newline>. A double quote may be quoted
3802 * within double quotes by preceding it with a backslash."
3803 * NB: in (unquoted) heredoc, above does not apply to ",
3804 * therefore we check for it by "next == dquote_end" cond.
3806 if (next == dquote_end || strchr("$`\\\n", next)) {
3807 ch = i_getch(input); /* eat next */
3809 goto again; /* skip \<newline> */
3810 } /* else: ch remains == '\\', and we double it below: */
3811 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3812 nommu_addchr(as_string, ch);
3816 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3817 debug_printf_parse("encode_string return 1: "
3818 "parse_dollar returned non-0\n");
3823 #if ENABLE_HUSH_TICK
3825 //unsigned pos = dest->length;
3826 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3827 o_addchr(dest, 0x80 | '`');
3828 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3829 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3830 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3834 o_addQchr(dest, ch);
3840 * Scan input until EOF or end_trigger char.
3841 * Return a list of pipes to execute, or NULL on EOF
3842 * or if end_trigger character is met.
3843 * On syntax error, exit is shell is not interactive,
3844 * reset parsing machinery and start parsing anew,
3845 * or return ERR_PTR.
3847 static struct pipe *parse_stream(char **pstring,
3848 struct in_str *input,
3851 struct parse_context ctx;
3852 o_string dest = NULL_O_STRING;
3855 /* Single-quote triggers a bypass of the main loop until its mate is
3856 * found. When recursing, quote state is passed in via dest->o_expflags.
3858 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3859 end_trigger ? end_trigger : 'X');
3862 /* If very first arg is "" or '', dest.data may end up NULL.
3863 * Preventing this: */
3864 o_addchr(&dest, '\0');
3867 /* We used to separate words on $IFS here. This was wrong.
3868 * $IFS is used only for word splitting when $var is expanded,
3869 * here we should use blank chars as separators, not $IFS
3872 reset: /* we come back here only on syntax errors in interactive shell */
3874 #if ENABLE_HUSH_INTERACTIVE
3875 input->promptmode = 0; /* PS1 */
3877 if (MAYBE_ASSIGNMENT != 0)
3878 dest.o_assignment = MAYBE_ASSIGNMENT;
3879 initialize_context(&ctx);
3882 const char *is_blank;
3883 const char *is_special;
3887 redir_type redir_style;
3889 ch = i_getch(input);
3890 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3891 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3896 syntax_error_unterm_str("here document");
3899 /* end_trigger == '}' case errors out earlier,
3900 * checking only ')' */
3901 if (end_trigger == ')') {
3902 syntax_error_unterm_ch('('); /* exits */
3903 /* goto parse_error; */
3906 if (done_word(&dest, &ctx)) {
3910 done_pipe(&ctx, PIPE_SEQ);
3912 /* If we got nothing... */
3913 /* (this makes bare "&" cmd a no-op.
3914 * bash says: "syntax error near unexpected token '&'") */
3915 if (pi->num_cmds == 0
3916 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3922 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3924 *pstring = ctx.as_string.data;
3926 o_free_unsafe(&ctx.as_string);
3929 debug_printf_parse("parse_stream return %p\n", pi);
3932 nommu_addchr(&ctx.as_string, ch);
3936 next = i_peek(input);
3938 is_special = "{}<>;&|()#'" /* special outside of "str" */
3939 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3940 /* Are { and } special here? */
3941 if (ctx.command->argv /* word [word]{... - non-special */
3942 || dest.length /* word{... - non-special */
3943 || dest.has_quoted_part /* ""{... - non-special */
3944 || (next != ';' /* }; - special */
3945 && next != ')' /* }) - special */
3946 && next != '&' /* }& and }&& ... - special */
3947 && next != '|' /* }|| ... - special */
3948 && !strchr(defifs, next) /* {word - non-special */
3951 /* They are not special, skip "{}" */
3954 is_special = strchr(is_special, ch);
3955 is_blank = strchr(defifs, ch);
3957 if (!is_special && !is_blank) { /* ordinary char */
3959 o_addQchr(&dest, ch);
3960 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3961 || dest.o_assignment == WORD_IS_KEYWORD)
3963 && is_well_formed_var_name(dest.data, '=')
3965 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3971 if (done_word(&dest, &ctx)) {
3975 #if ENABLE_HUSH_CASE
3976 /* "case ... in <newline> word) ..." -
3977 * newlines are ignored (but ';' wouldn't be) */
3978 if (ctx.command->argv == NULL
3979 && ctx.ctx_res_w == RES_MATCH
3984 /* Treat newline as a command separator. */
3985 done_pipe(&ctx, PIPE_SEQ);
3986 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3988 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3993 dest.o_assignment = MAYBE_ASSIGNMENT;
3995 /* note: if (is_blank) continue;
3996 * will still trigger for us */
4000 /* "cmd}" or "cmd }..." without semicolon or &:
4001 * } is an ordinary char in this case, even inside { cmd; }
4002 * Pathological example: { ""}; } should exec "}" cmd
4005 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4006 || dest.length != 0 /* word} */
4007 || dest.has_quoted_part /* ""} */
4011 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4012 goto skip_end_trigger;
4013 /* else: } does terminate a group */
4016 if (end_trigger && end_trigger == ch
4017 && (ch != ';' || heredoc_cnt == 0)
4018 #if ENABLE_HUSH_CASE
4020 || ctx.ctx_res_w != RES_MATCH
4021 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4026 /* This is technically valid:
4027 * { cat <<HERE; }; echo Ok
4031 * but we don't support this.
4032 * We require heredoc to be in enclosing {}/(),
4035 syntax_error_unterm_str("here document");
4038 if (done_word(&dest, &ctx)) {
4041 done_pipe(&ctx, PIPE_SEQ);
4042 dest.o_assignment = MAYBE_ASSIGNMENT;
4043 /* Do we sit outside of any if's, loops or case's? */
4045 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4049 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4051 *pstring = ctx.as_string.data;
4053 o_free_unsafe(&ctx.as_string);
4056 debug_printf_parse("parse_stream return %p: "
4057 "end_trigger char found\n",
4059 return ctx.list_head;
4066 /* Catch <, > before deciding whether this word is
4067 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4070 redir_fd = redirect_opt_num(&dest);
4071 if (done_word(&dest, &ctx)) {
4074 redir_style = REDIRECT_OVERWRITE;
4076 redir_style = REDIRECT_APPEND;
4077 ch = i_getch(input);
4078 nommu_addchr(&ctx.as_string, ch);
4081 else if (next == '(') {
4082 syntax_error(">(process) not supported");
4086 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4088 continue; /* back to top of while (1) */
4090 redir_fd = redirect_opt_num(&dest);
4091 if (done_word(&dest, &ctx)) {
4094 redir_style = REDIRECT_INPUT;
4096 redir_style = REDIRECT_HEREDOC;
4098 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4099 ch = i_getch(input);
4100 nommu_addchr(&ctx.as_string, ch);
4101 } else if (next == '>') {
4102 redir_style = REDIRECT_IO;
4103 ch = i_getch(input);
4104 nommu_addchr(&ctx.as_string, ch);
4107 else if (next == '(') {
4108 syntax_error("<(process) not supported");
4112 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4114 continue; /* back to top of while (1) */
4117 if (dest.o_assignment == MAYBE_ASSIGNMENT
4118 /* check that we are not in word in "a=1 2>word b=1": */
4119 && !ctx.pending_redirect
4121 /* ch is a special char and thus this word
4122 * cannot be an assignment */
4123 dest.o_assignment = NOT_ASSIGNMENT;
4126 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4130 if (dest.length == 0) {
4133 if (ch == EOF || ch == '\n')
4136 /* note: we do not add it to &ctx.as_string */
4138 nommu_addchr(&ctx.as_string, '\n');
4140 o_addQchr(&dest, ch);
4145 syntax_error("\\<eof>");
4148 ch = i_getch(input);
4150 o_addchr(&dest, '\\');
4151 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4152 o_addchr(&dest, ch);
4153 nommu_addchr(&ctx.as_string, ch);
4154 /* Example: echo Hello \2>file
4155 * we need to know that word 2 is quoted */
4156 dest.has_quoted_part = 1;
4160 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4161 ctx.as_string.data[--ctx.as_string.length] = '\0';
4166 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4167 debug_printf_parse("parse_stream parse error: "
4168 "parse_dollar returned non-0\n");
4173 dest.has_quoted_part = 1;
4175 ch = i_getch(input);
4177 syntax_error_unterm_ch('\'');
4178 /*xfunc_die(); - redundant */
4180 nommu_addchr(&ctx.as_string, ch);
4183 o_addqchr(&dest, ch);
4187 dest.has_quoted_part = 1;
4188 if (dest.o_assignment == NOT_ASSIGNMENT)
4189 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4190 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4192 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4194 #if ENABLE_HUSH_TICK
4198 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4199 o_addchr(&dest, '`');
4201 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4203 o_addstr(&ctx.as_string, dest.data + pos);
4204 o_addchr(&ctx.as_string, '`');
4206 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4207 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4212 #if ENABLE_HUSH_CASE
4215 if (done_word(&dest, &ctx)) {
4218 done_pipe(&ctx, PIPE_SEQ);
4219 #if ENABLE_HUSH_CASE
4220 /* Eat multiple semicolons, detect
4221 * whether it means something special */
4226 ch = i_getch(input);
4227 nommu_addchr(&ctx.as_string, ch);
4228 if (ctx.ctx_res_w == RES_CASE_BODY) {
4229 ctx.ctx_dsemicolon = 1;
4230 ctx.ctx_res_w = RES_MATCH;
4236 /* We just finished a cmd. New one may start
4237 * with an assignment */
4238 dest.o_assignment = MAYBE_ASSIGNMENT;
4241 if (done_word(&dest, &ctx)) {
4245 ch = i_getch(input);
4246 nommu_addchr(&ctx.as_string, ch);
4247 done_pipe(&ctx, PIPE_AND);
4249 done_pipe(&ctx, PIPE_BG);
4253 if (done_word(&dest, &ctx)) {
4256 #if ENABLE_HUSH_CASE
4257 if (ctx.ctx_res_w == RES_MATCH)
4258 break; /* we are in case's "word | word)" */
4260 if (next == '|') { /* || */
4261 ch = i_getch(input);
4262 nommu_addchr(&ctx.as_string, ch);
4263 done_pipe(&ctx, PIPE_OR);
4265 /* we could pick up a file descriptor choice here
4266 * with redirect_opt_num(), but bash doesn't do it.
4267 * "echo foo 2| cat" yields "foo 2". */
4270 o_reset_to_empty_unquoted(&ctx.as_string);
4275 #if ENABLE_HUSH_CASE
4276 /* "case... in [(]word)..." - skip '(' */
4277 if (ctx.ctx_res_w == RES_MATCH
4278 && ctx.command->argv == NULL /* not (word|(... */
4279 && dest.length == 0 /* not word(... */
4280 && dest.has_quoted_part == 0 /* not ""(... */
4286 if (parse_group(&dest, &ctx, input, ch) != 0) {
4291 #if ENABLE_HUSH_CASE
4292 if (ctx.ctx_res_w == RES_MATCH)
4296 /* proper use of this character is caught by end_trigger:
4297 * if we see {, we call parse_group(..., end_trigger='}')
4298 * and it will match } earlier (not here). */
4299 syntax_error_unexpected_ch(ch);
4303 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4309 struct parse_context *pctx;
4310 IF_HAS_KEYWORDS(struct parse_context *p2;)
4312 /* Clean up allocated tree.
4313 * Sample for finding leaks on syntax error recovery path.
4314 * Run it from interactive shell, watch pmap `pidof hush`.
4315 * while if false; then false; fi; do break; fi
4316 * Samples to catch leaks at execution:
4317 * while if (true | {true;}); then echo ok; fi; do break; done
4318 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4322 /* Update pipe/command counts,
4323 * otherwise freeing may miss some */
4324 done_pipe(pctx, PIPE_SEQ);
4325 debug_printf_clean("freeing list %p from ctx %p\n",
4326 pctx->list_head, pctx);
4327 debug_print_tree(pctx->list_head, 0);
4328 free_pipe_list(pctx->list_head);
4329 debug_printf_clean("freed list %p\n", pctx->list_head);
4331 o_free_unsafe(&pctx->as_string);
4333 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4337 IF_HAS_KEYWORDS(pctx = p2;)
4338 } while (HAS_KEYWORDS && pctx);
4339 /* Free text, clear all dest fields */
4341 /* If we are not in top-level parse, we return,
4342 * our caller will propagate error.
4344 if (end_trigger != ';') {
4352 /* Discard cached input, force prompt */
4354 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4360 /*** Execution routines ***/
4362 /* Expansion can recurse, need forward decls: */
4363 #if !ENABLE_HUSH_BASH_COMPAT
4364 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4365 #define expand_string_to_string(str, do_unbackslash) \
4366 expand_string_to_string(str)
4368 static char *expand_string_to_string(const char *str, int do_unbackslash);
4369 static int process_command_subs(o_string *dest, const char *s);
4371 /* expand_strvec_to_strvec() takes a list of strings, expands
4372 * all variable references within and returns a pointer to
4373 * a list of expanded strings, possibly with larger number
4374 * of strings. (Think VAR="a b"; echo $VAR).
4375 * This new list is allocated as a single malloc block.
4376 * NULL-terminated list of char* pointers is at the beginning of it,
4377 * followed by strings themselves.
4378 * Caller can deallocate entire list by single free(list). */
4380 /* A horde of its helpers come first: */
4382 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4384 while (--len >= 0) {
4387 #if ENABLE_HUSH_BRACE_EXPANSION
4388 if (c == '{' || c == '}') {
4389 /* { -> \{, } -> \} */
4391 /* And now we want to add { or } and continue:
4394 * luckily, just falling throught achieves this.
4400 /* \z -> \\\z; \<eol> -> \\<eol> */
4405 o_addchr(o, *str++);
4411 /* Store given string, finalizing the word and starting new one whenever
4412 * we encounter IFS char(s). This is used for expanding variable values.
4413 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4414 static int expand_on_ifs(o_string *output, int n, const char *str)
4417 int word_len = strcspn(str, G.ifs);
4419 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4420 o_addblock(output, str, word_len);
4422 /* Protect backslashes against globbing up :)
4423 * Example: "v='\*'; echo b$v" prints "b\*"
4424 * (and does not try to glob on "*")
4426 o_addblock_duplicate_backslash(output, str, word_len);
4427 /*/ Why can't we do it easier? */
4428 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4429 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4433 if (!*str) /* EOL - do not finalize word */
4435 o_addchr(output, '\0');
4436 debug_print_list("expand_on_ifs", output, n);
4437 n = o_save_ptr(output, n);
4438 str += strspn(str, G.ifs); /* skip ifs chars */
4440 debug_print_list("expand_on_ifs[1]", output, n);
4444 /* Helper to expand $((...)) and heredoc body. These act as if
4445 * they are in double quotes, with the exception that they are not :).
4446 * Just the rules are similar: "expand only $var and `cmd`"
4448 * Returns malloced string.
4449 * As an optimization, we return NULL if expansion is not needed.
4451 #if !ENABLE_HUSH_BASH_COMPAT
4452 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4453 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4454 encode_then_expand_string(str)
4456 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4459 struct in_str input;
4460 o_string dest = NULL_O_STRING;
4462 if (!strchr(str, '$')
4463 && !strchr(str, '\\')
4464 #if ENABLE_HUSH_TICK
4465 && !strchr(str, '`')
4471 /* We need to expand. Example:
4472 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4474 setup_string_in_str(&input, str);
4475 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4476 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4477 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4478 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4479 o_free_unsafe(&dest);
4483 #if ENABLE_SH_MATH_SUPPORT
4484 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4486 arith_state_t math_state;
4490 math_state.lookupvar = get_local_var_value;
4491 math_state.setvar = set_local_var_from_halves;
4492 //math_state.endofname = endofname;
4493 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4494 res = arith(&math_state, exp_str ? exp_str : arg);
4497 *errmsg_p = math_state.errmsg;
4498 if (math_state.errmsg)
4499 die_if_script(math_state.errmsg);
4504 #if ENABLE_HUSH_BASH_COMPAT
4505 /* ${var/[/]pattern[/repl]} helpers */
4506 static char *strstr_pattern(char *val, const char *pattern, int *size)
4509 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4510 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4517 /* Optimization: if "*pat" did not match the start of "string",
4518 * we know that "tring", "ring" etc will not match too:
4520 if (pattern[0] == '*')
4525 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4527 char *result = NULL;
4528 unsigned res_len = 0;
4529 unsigned repl_len = strlen(repl);
4533 char *s = strstr_pattern(val, pattern, &size);
4537 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4538 memcpy(result + res_len, val, s - val);
4540 strcpy(result + res_len, repl);
4541 res_len += repl_len;
4542 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4548 if (val[0] && result) {
4549 result = xrealloc(result, res_len + strlen(val) + 1);
4550 strcpy(result + res_len, val);
4551 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4553 debug_printf_varexp("result:'%s'\n", result);
4559 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4561 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4563 const char *val = NULL;
4564 char *to_be_freed = NULL;
4569 char exp_save = exp_save; /* for compiler */
4570 char *exp_saveptr; /* points to expansion operator */
4571 char *exp_word = exp_word; /* for compiler */
4574 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4576 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4578 first_char = arg[0] = arg0 & 0x7f;
4581 if (first_char == '#' /* ${#... */
4582 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4584 /* It must be length operator: ${#var} */
4588 /* Maybe handle parameter expansion */
4589 if (exp_saveptr /* if 2nd char is one of expansion operators */
4590 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4592 /* ${?:0}, ${#[:]%0} etc */
4593 exp_saveptr = var + 1;
4595 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4596 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4598 exp_op = exp_save = *exp_saveptr;
4600 exp_word = exp_saveptr + 1;
4601 if (exp_op == ':') {
4602 exp_op = *exp_word++;
4603 //TODO: try ${var:} and ${var:bogus} in non-bash config
4604 if (ENABLE_HUSH_BASH_COMPAT
4605 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4607 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4612 *exp_saveptr = '\0';
4613 } /* else: it's not an expansion op, but bare ${var} */
4616 /* Look up the variable in question */
4617 if (isdigit(var[0])) {
4618 /* parse_dollar should have vetted var for us */
4619 int n = xatoi_positive(var);
4620 if (n < G.global_argc)
4621 val = G.global_argv[n];
4622 /* else val remains NULL: $N with too big N */
4626 val = utoa(G.root_pid);
4628 case '!': /* bg pid */
4629 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4631 case '?': /* exitcode */
4632 val = utoa(G.last_exitcode);
4634 case '#': /* argc */
4635 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4638 val = get_local_var_value(var);
4642 /* Handle any expansions */
4643 if (exp_op == 'L') {
4644 debug_printf_expand("expand: length(%s)=", val);
4645 val = utoa(val ? strlen(val) : 0);
4646 debug_printf_expand("%s\n", val);
4647 } else if (exp_op) {
4648 if (exp_op == '%' || exp_op == '#') {
4649 /* Standard-mandated substring removal ops:
4650 * ${parameter%word} - remove smallest suffix pattern
4651 * ${parameter%%word} - remove largest suffix pattern
4652 * ${parameter#word} - remove smallest prefix pattern
4653 * ${parameter##word} - remove largest prefix pattern
4655 * Word is expanded to produce a glob pattern.
4656 * Then var's value is matched to it and matching part removed.
4658 if (val && val[0]) {
4662 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4663 if (exp_op == *exp_word) /* ## or %% */
4665 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4667 exp_word = exp_exp_word;
4668 /* HACK ALERT. We depend here on the fact that
4669 * G.global_argv and results of utoa and get_local_var_value
4670 * are actually in writable memory:
4671 * scan_and_match momentarily stores NULs there. */
4673 loc = scan_and_match(t, exp_word, scan_flags);
4674 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4675 // exp_op, t, exp_word, loc);
4677 if (loc) { /* match was found */
4678 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4679 val = loc; /* take right part */
4681 val = to_be_freed = xstrndup(val, loc - val); /* left */
4685 #if ENABLE_HUSH_BASH_COMPAT
4686 else if (exp_op == '/' || exp_op == '\\') {
4687 /* It's ${var/[/]pattern[/repl]} thing.
4688 * Note that in encoded form it has TWO parts:
4689 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4690 * and if // is used, it is encoded as \:
4691 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4693 /* Empty variable always gives nothing: */
4694 // "v=''; echo ${v/*/w}" prints "", not "w"
4695 if (val && val[0]) {
4696 /* pattern uses non-standard expansion.
4697 * repl should be unbackslashed and globbed
4698 * by the usual expansion rules:
4700 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4701 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4702 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4703 * v='a bz'; echo ${v/a*z/\z} prints "z"
4704 * (note that a*z _pattern_ is never globbed!)
4706 char *pattern, *repl, *t;
4707 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4709 pattern = xstrdup(exp_word);
4710 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4711 *p++ = SPECIAL_VAR_SYMBOL;
4713 p = strchr(p, SPECIAL_VAR_SYMBOL);
4715 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4716 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4717 /* HACK ALERT. We depend here on the fact that
4718 * G.global_argv and results of utoa and get_local_var_value
4719 * are actually in writable memory:
4720 * replace_pattern momentarily stores NULs there. */
4722 to_be_freed = replace_pattern(t,
4724 (repl ? repl : exp_word),
4726 if (to_be_freed) /* at least one replace happened */
4733 else if (exp_op == ':') {
4734 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4735 /* It's ${var:N[:M]} bashism.
4736 * Note that in encoded form it has TWO parts:
4737 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4742 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4745 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4746 *p++ = SPECIAL_VAR_SYMBOL;
4748 p = strchr(p, SPECIAL_VAR_SYMBOL);
4750 len = expand_and_evaluate_arith(exp_word, &errmsg);
4753 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4754 if (len >= 0) { /* bash compat: len < 0 is illegal */
4755 if (beg < 0) /* bash compat */
4757 debug_printf_varexp("from val:'%s'\n", val);
4758 if (len == 0 || !val || beg >= strlen(val)) {
4762 /* Paranoia. What if user entered 9999999999999
4763 * which fits in arith_t but not int? */
4766 val = to_be_freed = xstrndup(val + beg, len);
4768 debug_printf_varexp("val:'%s'\n", val);
4772 die_if_script("malformed ${%s:...}", var);
4775 } else { /* one of "-=+?" */
4776 /* Standard-mandated substitution ops:
4777 * ${var?word} - indicate error if unset
4778 * If var is unset, word (or a message indicating it is unset
4779 * if word is null) is written to standard error
4780 * and the shell exits with a non-zero exit status.
4781 * Otherwise, the value of var is substituted.
4782 * ${var-word} - use default value
4783 * If var is unset, word is substituted.
4784 * ${var=word} - assign and use default value
4785 * If var is unset, word is assigned to var.
4786 * In all cases, final value of var is substituted.
4787 * ${var+word} - use alternative value
4788 * If var is unset, null is substituted.
4789 * Otherwise, word is substituted.
4791 * Word is subjected to tilde expansion, parameter expansion,
4792 * command substitution, and arithmetic expansion.
4793 * If word is not needed, it is not expanded.
4795 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4796 * but also treat null var as if it is unset.
4798 int use_word = (!val || ((exp_save == ':') && !val[0]));
4800 use_word = !use_word;
4801 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4802 (exp_save == ':') ? "true" : "false", use_word);
4804 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4806 exp_word = to_be_freed;
4807 if (exp_op == '?') {
4808 /* mimic bash message */
4809 die_if_script("%s: %s",
4811 exp_word[0] ? exp_word : "parameter null or not set"
4813 //TODO: how interactive bash aborts expansion mid-command?
4818 if (exp_op == '=') {
4819 /* ${var=[word]} or ${var:=[word]} */
4820 if (isdigit(var[0]) || var[0] == '#') {
4821 /* mimic bash message */
4822 die_if_script("$%s: cannot assign in this way", var);
4825 char *new_var = xasprintf("%s=%s", var, val);
4826 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4830 } /* one of "-=+?" */
4832 *exp_saveptr = exp_save;
4838 *to_be_freed_pp = to_be_freed;
4842 /* Expand all variable references in given string, adding words to list[]
4843 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4844 * to be filled). This routine is extremely tricky: has to deal with
4845 * variables/parameters with whitespace, $* and $@, and constructs like
4846 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4847 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4849 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4850 * expansion of right-hand side of assignment == 1-element expand.
4852 char cant_be_null = 0; /* only bit 0x80 matters */
4855 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4856 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4857 debug_print_list("expand_vars_to_list", output, n);
4858 n = o_save_ptr(output, n);
4859 debug_print_list("expand_vars_to_list[0]", output, n);
4861 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4863 char *to_be_freed = NULL;
4864 const char *val = NULL;
4865 #if ENABLE_HUSH_TICK
4866 o_string subst_result = NULL_O_STRING;
4868 #if ENABLE_SH_MATH_SUPPORT
4869 char arith_buf[sizeof(arith_t)*3 + 2];
4871 o_addblock(output, arg, p - arg);
4872 debug_print_list("expand_vars_to_list[1]", output, n);
4874 p = strchr(p, SPECIAL_VAR_SYMBOL);
4876 /* Fetch special var name (if it is indeed one of them)
4877 * and quote bit, force the bit on if singleword expansion -
4878 * important for not getting v=$@ expand to many words. */
4879 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4881 /* Is this variable quoted and thus expansion can't be null?
4882 * "$@" is special. Even if quoted, it can still
4883 * expand to nothing (not even an empty string),
4884 * thus it is excluded. */
4885 if ((first_ch & 0x7f) != '@')
4886 cant_be_null |= first_ch;
4888 switch (first_ch & 0x7f) {
4889 /* Highest bit in first_ch indicates that var is double-quoted */
4893 if (!G.global_argv[1])
4896 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4897 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4898 while (G.global_argv[i]) {
4899 n = expand_on_ifs(output, n, G.global_argv[i]);
4900 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4901 if (G.global_argv[i++][0] && G.global_argv[i]) {
4902 /* this argv[] is not empty and not last:
4903 * put terminating NUL, start new word */
4904 o_addchr(output, '\0');
4905 debug_print_list("expand_vars_to_list[2]", output, n);
4906 n = o_save_ptr(output, n);
4907 debug_print_list("expand_vars_to_list[3]", output, n);
4911 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4912 * and in this case should treat it like '$*' - see 'else...' below */
4913 if (first_ch == ('@'|0x80) /* quoted $@ */
4914 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4917 o_addQstr(output, G.global_argv[i]);
4918 if (++i >= G.global_argc)
4920 o_addchr(output, '\0');
4921 debug_print_list("expand_vars_to_list[4]", output, n);
4922 n = o_save_ptr(output, n);
4924 } else { /* quoted $* (or v="$@" case): add as one word */
4926 o_addQstr(output, G.global_argv[i]);
4927 if (!G.global_argv[++i])
4930 o_addchr(output, G.ifs[0]);
4935 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4936 /* "Empty variable", used to make "" etc to not disappear */
4938 cant_be_null = 0x80;
4940 #if ENABLE_HUSH_TICK
4941 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4942 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4944 /* Can't just stuff it into output o_string,
4945 * expanded result may need to be globbed
4946 * and $IFS-splitted */
4947 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4948 G.last_exitcode = process_command_subs(&subst_result, arg);
4949 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4950 val = subst_result.data;
4953 #if ENABLE_SH_MATH_SUPPORT
4954 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4957 arg++; /* skip '+' */
4958 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4959 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4960 res = expand_and_evaluate_arith(arg, NULL);
4961 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
4962 sprintf(arith_buf, ARITH_FMT, res);
4968 val = expand_one_var(&to_be_freed, arg, &p);
4969 IF_HUSH_TICK(store_val:)
4970 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4971 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4972 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4973 if (val && val[0]) {
4974 n = expand_on_ifs(output, n, val);
4977 } else { /* quoted $VAR, val will be appended below */
4978 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4979 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4983 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4985 if (val && val[0]) {
4986 o_addQstr(output, val);
4990 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4991 * Do the check to avoid writing to a const string. */
4992 if (*p != SPECIAL_VAR_SYMBOL)
4993 *p = SPECIAL_VAR_SYMBOL;
4995 #if ENABLE_HUSH_TICK
4996 o_free(&subst_result);
4999 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5002 debug_print_list("expand_vars_to_list[a]", output, n);
5003 /* this part is literal, and it was already pre-quoted
5004 * if needed (much earlier), do not use o_addQstr here! */
5005 o_addstr_with_NUL(output, arg);
5006 debug_print_list("expand_vars_to_list[b]", output, n);
5007 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5008 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5011 /* allow to reuse list[n] later without re-growth */
5012 output->has_empty_slot = 1;
5014 o_addchr(output, '\0');
5020 static char **expand_variables(char **argv, unsigned expflags)
5024 o_string output = NULL_O_STRING;
5026 output.o_expflags = expflags;
5030 n = expand_vars_to_list(&output, n, *argv);
5033 debug_print_list("expand_variables", &output, n);
5035 /* output.data (malloced in one block) gets returned in "list" */
5036 list = o_finalize_list(&output, n);
5037 debug_print_strings("expand_variables[1]", list);
5041 static char **expand_strvec_to_strvec(char **argv)
5043 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5046 #if ENABLE_HUSH_BASH_COMPAT
5047 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5049 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5053 /* Used for expansion of right hand of assignments,
5054 * $((...)), heredocs, variable espansion parts.
5056 * NB: should NOT do globbing!
5057 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5059 static char *expand_string_to_string(const char *str, int do_unbackslash)
5061 #if !ENABLE_HUSH_BASH_COMPAT
5062 const int do_unbackslash = 1;
5064 char *argv[2], **list;
5066 debug_printf_expand("string_to_string<='%s'\n", str);
5067 /* This is generally an optimization, but it also
5068 * handles "", which otherwise trips over !list[0] check below.
5069 * (is this ever happens that we actually get str="" here?)
5071 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5072 //TODO: Can use on strings with \ too, just unbackslash() them?
5073 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5074 return xstrdup(str);
5077 argv[0] = (char*)str;
5079 list = expand_variables(argv, do_unbackslash
5080 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5081 : EXP_FLAG_SINGLEWORD
5084 if (!list[0] || list[1])
5085 bb_error_msg_and_die("BUG in varexp2");
5086 /* actually, just move string 2*sizeof(char*) bytes back */
5087 overlapping_strcpy((char*)list, list[0]);
5089 unbackslash((char*)list);
5090 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5094 /* Used for "eval" builtin */
5095 static char* expand_strvec_to_string(char **argv)
5099 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5100 /* Convert all NULs to spaces */
5105 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5106 bb_error_msg_and_die("BUG in varexp3");
5107 /* bash uses ' ' regardless of $IFS contents */
5112 overlapping_strcpy((char*)list, list[0]);
5113 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5117 static char **expand_assignments(char **argv, int count)
5122 G.expanded_assignments = p = NULL;
5123 /* Expand assignments into one string each */
5124 for (i = 0; i < count; i++) {
5125 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5127 G.expanded_assignments = NULL;
5134 void re_execute_shell(char ***to_free, const char *s,
5135 char *g_argv0, char **g_argv,
5136 char **builtin_argv) NORETURN;
5138 static void reset_traps_to_defaults(void)
5140 /* This function is always called in a child shell
5141 * after fork (not vfork, NOMMU doesn't use this function).
5146 /* Child shells are not interactive.
5147 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5148 * Testcase: (while :; do :; done) + ^Z should background.
5149 * Same goes for SIGTERM, SIGHUP, SIGINT.
5151 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5152 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5154 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5155 * Stupid. It can be done with *single* &= op, but we can't use
5156 * the fact that G.blocked_set is implemented as a bitmask
5158 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5162 /* Careful. Only if no trap or trap is not "" */
5163 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5164 sigdelset(&G.blocked_set, sig);
5171 /* Our homegrown sig mask is saner to work with :) */
5172 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5174 /* Resetting all traps to default except empty ones */
5175 mask = G.non_DFL_mask;
5176 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5177 if (!G.traps[sig] || !G.traps[sig][0])
5180 G.traps[sig] = NULL;
5181 /* There is no signal for 0 (EXIT) */
5184 /* There was a trap handler, we just removed it.
5185 * But if sig still has non-DFL handling,
5186 * we should not unblock the sig. */
5189 sigdelset(&G.blocked_set, sig);
5191 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5196 static void re_execute_shell(char ***to_free, const char *s,
5197 char *g_argv0, char **g_argv,
5198 char **builtin_argv) NORETURN;
5199 static void re_execute_shell(char ***to_free, const char *s,
5200 char *g_argv0, char **g_argv,
5201 char **builtin_argv)
5203 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5204 /* delims + 2 * (number of bytes in printed hex numbers) */
5205 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5206 char *heredoc_argv[4];
5207 struct variable *cur;
5208 # if ENABLE_HUSH_FUNCTIONS
5209 struct function *funcp;
5213 unsigned long long empty_trap_mask;
5215 if (!g_argv0) { /* heredoc */
5216 argv = heredoc_argv;
5217 argv[0] = (char *) G.argv0_for_re_execing;
5218 argv[1] = (char *) "-<";
5219 argv[2] = (char *) s;
5221 pp = &argv[3]; /* used as pointer to empty environment */
5227 if (pp) while (*pp++)
5230 empty_trap_mask = 0;
5233 for (sig = 1; sig < NSIG; sig++) {
5234 if (G.traps[sig] && !G.traps[sig][0])
5235 empty_trap_mask |= 1LL << sig;
5239 sprintf(param_buf, NOMMU_HACK_FMT
5240 , (unsigned) G.root_pid
5241 , (unsigned) G.root_ppid
5242 , (unsigned) G.last_bg_pid
5243 , (unsigned) G.last_exitcode
5246 IF_HUSH_LOOPS(, G.depth_of_loop)
5248 # undef NOMMU_HACK_FMT
5249 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5250 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5253 for (cur = G.top_var; cur; cur = cur->next) {
5254 if (!cur->flg_export || cur->flg_read_only)
5257 # if ENABLE_HUSH_FUNCTIONS
5258 for (funcp = G.top_func; funcp; funcp = funcp->next)
5264 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5265 *pp++ = (char *) G.argv0_for_re_execing;
5267 for (cur = G.top_var; cur; cur = cur->next) {
5268 if (strcmp(cur->varstr, hush_version_str) == 0)
5270 if (cur->flg_read_only) {
5271 *pp++ = (char *) "-R";
5272 *pp++ = cur->varstr;
5273 } else if (!cur->flg_export) {
5274 *pp++ = (char *) "-V";
5275 *pp++ = cur->varstr;
5278 # if ENABLE_HUSH_FUNCTIONS
5279 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5280 *pp++ = (char *) "-F";
5281 *pp++ = funcp->name;
5282 *pp++ = funcp->body_as_string;
5285 /* We can pass activated traps here. Say, -Tnn:trap_string
5287 * However, POSIX says that subshells reset signals with traps
5289 * I tested bash-3.2 and it not only does that with true subshells
5290 * of the form ( list ), but with any forked children shells.
5291 * I set trap "echo W" WINCH; and then tried:
5293 * { echo 1; sleep 20; echo 2; } &
5294 * while true; do echo 1; sleep 20; echo 2; break; done &
5295 * true | { echo 1; sleep 20; echo 2; } | cat
5297 * In all these cases sending SIGWINCH to the child shell
5298 * did not run the trap. If I add trap "echo V" WINCH;
5299 * _inside_ group (just before echo 1), it works.
5301 * I conclude it means we don't need to pass active traps here.
5302 * Even if we would use signal handlers instead of signal masking
5303 * in order to implement trap handling,
5304 * exec syscall below resets signals to SIG_DFL for us.
5306 *pp++ = (char *) "-c";
5309 while (*++builtin_argv)
5310 *pp++ = *builtin_argv;
5311 *pp++ = (char *) "";
5316 /* *pp = NULL; - is already there */
5320 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5321 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5322 execve(bb_busybox_exec_path, argv, pp);
5323 /* Fallback. Useful for init=/bin/hush usage etc */
5324 if (argv[0][0] == '/')
5325 execve(argv[0], argv, pp);
5326 xfunc_error_retval = 127;
5327 bb_error_msg_and_die("can't re-execute the shell");
5329 #endif /* !BB_MMU */
5332 static int run_and_free_list(struct pipe *pi);
5334 /* Executing from string: eval, sh -c '...'
5335 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5336 * end_trigger controls how often we stop parsing
5337 * NUL: parse all, execute, return
5338 * ';': parse till ';' or newline, execute, repeat till EOF
5340 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5342 /* Why we need empty flag?
5343 * An obscure corner case "false; ``; echo $?":
5344 * empty command in `` should still set $? to 0.
5345 * But we can't just set $? to 0 at the start,
5346 * this breaks "false; echo `echo $?`" case.
5350 struct pipe *pipe_list;
5352 pipe_list = parse_stream(NULL, inp, end_trigger);
5353 if (!pipe_list) { /* EOF */
5355 G.last_exitcode = 0;
5358 debug_print_tree(pipe_list, 0);
5359 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5360 run_and_free_list(pipe_list);
5365 static void parse_and_run_string(const char *s)
5367 struct in_str input;
5368 setup_string_in_str(&input, s);
5369 parse_and_run_stream(&input, '\0');
5372 static void parse_and_run_file(FILE *f)
5374 struct in_str input;
5375 setup_file_in_str(&input, f);
5376 parse_and_run_stream(&input, ';');
5379 #if ENABLE_HUSH_TICK
5380 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5385 char **to_free = NULL;
5389 pid = BB_MMU ? xfork() : xvfork();
5390 if (pid == 0) { /* child */
5391 disable_restore_tty_pgrp_on_exit();
5392 /* Process substitution is not considered to be usual
5393 * 'command execution'.
5394 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5401 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5402 close(channel[0]); /* NB: close _first_, then move fd! */
5403 xmove_fd(channel[1], 1);
5404 /* Prevent it from trying to handle ctrl-z etc */
5405 IF_HUSH_JOB(G.run_list_level = 1;)
5406 /* Awful hack for `trap` or $(trap).
5408 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5409 * contains an example where "trap" is executed in a subshell:
5411 * save_traps=$(trap)
5413 * eval "$save_traps"
5415 * Standard does not say that "trap" in subshell shall print
5416 * parent shell's traps. It only says that its output
5417 * must have suitable form, but then, in the above example
5418 * (which is not supposed to be normative), it implies that.
5420 * bash (and probably other shell) does implement it
5421 * (traps are reset to defaults, but "trap" still shows them),
5422 * but as a result, "trap" logic is hopelessly messed up:
5425 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5426 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5427 * # true | trap <--- trap is in subshell - no output (ditto)
5428 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5429 * trap -- 'echo Ho' SIGWINCH
5430 * # echo `(trap)` <--- in subshell in subshell - output
5431 * trap -- 'echo Ho' SIGWINCH
5432 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5433 * trap -- 'echo Ho' SIGWINCH
5435 * The rules when to forget and when to not forget traps
5436 * get really complex and nonsensical.
5438 * Our solution: ONLY bare $(trap) or `trap` is special.
5440 s = skip_whitespace(s);
5441 if (strncmp(s, "trap", 4) == 0
5442 && skip_whitespace(s + 4)[0] == '\0'
5444 static const char *const argv[] = { NULL, NULL };
5445 builtin_trap((char**)argv);
5446 exit(0); /* not _exit() - we need to fflush */
5449 reset_traps_to_defaults();
5450 parse_and_run_string(s);
5451 _exit(G.last_exitcode);
5453 /* We re-execute after vfork on NOMMU. This makes this script safe:
5454 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5455 * huge=`cat BIG` # was blocking here forever
5458 re_execute_shell(&to_free,
5468 # if ENABLE_HUSH_FAST
5470 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5471 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5472 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5474 enable_restore_tty_pgrp_on_exit();
5479 close_on_exec_on(channel[0]);
5480 return xfdopen_for_read(channel[0]);
5483 /* Return code is exit status of the process that is run. */
5484 static int process_command_subs(o_string *dest, const char *s)
5487 struct in_str pipe_str;
5489 int status, ch, eol_cnt;
5491 fp = generate_stream_from_string(s, &pid);
5493 /* Now send results of command back into original context */
5494 setup_file_in_str(&pipe_str, fp);
5496 while ((ch = i_getch(&pipe_str)) != EOF) {
5502 o_addchr(dest, '\n');
5505 o_addQchr(dest, ch);
5508 debug_printf("done reading from `cmd` pipe, closing it\n");
5510 /* We need to extract exitcode. Test case
5511 * "true; echo `sleep 1; false` $?"
5513 safe_waitpid(pid, &status, 0);
5514 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5515 return WEXITSTATUS(status);
5517 #endif /* ENABLE_HUSH_TICK */
5520 static void setup_heredoc(struct redir_struct *redir)
5522 struct fd_pair pair;
5525 /* the _body_ of heredoc (misleading field name) */
5526 const char *heredoc = redir->rd_filename;
5533 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5534 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5538 len = strlen(heredoc);
5540 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5542 xmove_fd(pair.rd, redir->rd_fd);
5544 /* Try writing without forking. Newer kernels have
5545 * dynamically growing pipes. Must use non-blocking write! */
5548 written = write(pair.wr, heredoc, len);
5559 ndelay_off(pair.wr);
5561 /* Okay, pipe buffer was not big enough */
5562 /* Note: we must not create a stray child (bastard? :)
5563 * for the unsuspecting parent process. Child creates a grandchild
5564 * and exits before parent execs the process which consumes heredoc
5565 * (that exec happens after we return from this function) */
5572 disable_restore_tty_pgrp_on_exit();
5573 pid = BB_MMU ? xfork() : xvfork();
5577 close(redir->rd_fd); /* read side of the pipe */
5579 full_write(pair.wr, heredoc, len); /* may loop or block */
5582 /* Delegate blocking writes to another process */
5583 xmove_fd(pair.wr, STDOUT_FILENO);
5584 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5588 #if ENABLE_HUSH_FAST
5590 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5592 enable_restore_tty_pgrp_on_exit();
5598 wait(NULL); /* wait till child has died */
5601 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5602 * and stderr if they are redirected. */
5603 static int setup_redirects(struct command *prog, int squirrel[])
5606 struct redir_struct *redir;
5608 for (redir = prog->redirects; redir; redir = redir->next) {
5609 if (redir->rd_type == REDIRECT_HEREDOC2) {
5610 /* rd_fd<<HERE case */
5611 if (squirrel && redir->rd_fd < 3
5612 && squirrel[redir->rd_fd] < 0
5614 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5616 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5618 debug_printf_parse("set heredoc '%s'\n",
5619 redir->rd_filename);
5620 setup_heredoc(redir);
5624 if (redir->rd_dup == REDIRFD_TO_FILE) {
5625 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5627 if (redir->rd_filename == NULL) {
5628 /* Something went wrong in the parse.
5629 * Pretend it didn't happen */
5630 bb_error_msg("bug in redirect parse");
5633 mode = redir_table[redir->rd_type].mode;
5634 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5635 openfd = open_or_warn(p, mode);
5638 /* this could get lost if stderr has been redirected, but
5639 * bash and ash both lose it as well (though zsh doesn't!) */
5640 //what the above comment tries to say?
5644 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5645 openfd = redir->rd_dup;
5648 if (openfd != redir->rd_fd) {
5649 if (squirrel && redir->rd_fd < 3
5650 && squirrel[redir->rd_fd] < 0
5652 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5654 if (openfd == REDIRFD_CLOSE) {
5655 /* "n>-" means "close me" */
5656 close(redir->rd_fd);
5658 xdup2(openfd, redir->rd_fd);
5659 if (redir->rd_dup == REDIRFD_TO_FILE)
5667 static void restore_redirects(int squirrel[])
5670 for (i = 0; i < 3; i++) {
5673 /* We simply die on error */
5679 static char *find_in_path(const char *arg)
5682 const char *PATH = get_local_var_value("PATH");
5688 const char *end = strchrnul(PATH, ':');
5689 int sz = end - PATH; /* must be int! */
5693 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5695 /* We have xxx::yyyy in $PATH,
5696 * it means "use current dir" */
5699 if (access(ret, F_OK) == 0)
5712 static const struct built_in_command *find_builtin_helper(const char *name,
5713 const struct built_in_command *x,
5714 const struct built_in_command *end)
5717 if (strcmp(name, x->b_cmd) != 0) {
5721 debug_printf_exec("found builtin '%s'\n", name);
5726 static const struct built_in_command *find_builtin1(const char *name)
5728 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5730 static const struct built_in_command *find_builtin(const char *name)
5732 const struct built_in_command *x = find_builtin1(name);
5735 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5738 #if ENABLE_HUSH_FUNCTIONS
5739 static struct function **find_function_slot(const char *name)
5741 struct function **funcpp = &G.top_func;
5743 if (strcmp(name, (*funcpp)->name) == 0) {
5746 funcpp = &(*funcpp)->next;
5751 static const struct function *find_function(const char *name)
5753 const struct function *funcp = *find_function_slot(name);
5755 debug_printf_exec("found function '%s'\n", name);
5759 /* Note: takes ownership on name ptr */
5760 static struct function *new_function(char *name)
5762 struct function **funcpp = find_function_slot(name);
5763 struct function *funcp = *funcpp;
5765 if (funcp != NULL) {
5766 struct command *cmd = funcp->parent_cmd;
5767 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5769 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5771 /* Note: if !funcp->body, do not free body_as_string!
5772 * This is a special case of "-F name body" function:
5773 * body_as_string was not malloced! */
5775 free_pipe_list(funcp->body);
5777 free(funcp->body_as_string);
5781 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5782 cmd->argv[0] = funcp->name;
5783 cmd->group = funcp->body;
5785 cmd->group_as_string = funcp->body_as_string;
5789 debug_printf_exec("remembering new function '%s'\n", name);
5790 funcp = *funcpp = xzalloc(sizeof(*funcp));
5791 /*funcp->next = NULL;*/
5798 static void unset_func(const char *name)
5800 struct function **funcpp = find_function_slot(name);
5801 struct function *funcp = *funcpp;
5803 if (funcp != NULL) {
5804 debug_printf_exec("freeing function '%s'\n", funcp->name);
5805 *funcpp = funcp->next;
5806 /* funcp is unlinked now, deleting it.
5807 * Note: if !funcp->body, the function was created by
5808 * "-F name body", do not free ->body_as_string
5809 * and ->name as they were not malloced. */
5811 free_pipe_list(funcp->body);
5814 free(funcp->body_as_string);
5822 #define exec_function(to_free, funcp, argv) \
5823 exec_function(funcp, argv)
5825 static void exec_function(char ***to_free,
5826 const struct function *funcp,
5827 char **argv) NORETURN;
5828 static void exec_function(char ***to_free,
5829 const struct function *funcp,
5835 argv[0] = G.global_argv[0];
5836 G.global_argv = argv;
5840 /* On MMU, funcp->body is always non-NULL */
5841 n = run_list(funcp->body);
5845 re_execute_shell(to_free,
5846 funcp->body_as_string,
5853 static int run_function(const struct function *funcp, char **argv)
5859 save_and_replace_G_args(&sv, argv);
5861 /* "we are in function, ok to use return" */
5862 sv_flg = G.flag_return_in_progress;
5863 G.flag_return_in_progress = -1;
5864 # if ENABLE_HUSH_LOCAL
5865 G.func_nest_level++;
5868 /* On MMU, funcp->body is always non-NULL */
5871 /* Function defined by -F */
5872 parse_and_run_string(funcp->body_as_string);
5873 rc = G.last_exitcode;
5877 rc = run_list(funcp->body);
5880 # if ENABLE_HUSH_LOCAL
5882 struct variable *var;
5883 struct variable **var_pp;
5885 var_pp = &G.top_var;
5886 while ((var = *var_pp) != NULL) {
5887 if (var->func_nest_level < G.func_nest_level) {
5888 var_pp = &var->next;
5892 if (var->flg_export)
5893 bb_unsetenv(var->varstr);
5894 /* Remove from global list */
5895 *var_pp = var->next;
5901 G.func_nest_level--;
5904 G.flag_return_in_progress = sv_flg;
5906 restore_G_args(&sv, argv);
5910 #endif /* ENABLE_HUSH_FUNCTIONS */
5914 #define exec_builtin(to_free, x, argv) \
5915 exec_builtin(x, argv)
5917 #define exec_builtin(to_free, x, argv) \
5918 exec_builtin(to_free, argv)
5920 static void exec_builtin(char ***to_free,
5921 const struct built_in_command *x,
5922 char **argv) NORETURN;
5923 static void exec_builtin(char ***to_free,
5924 const struct built_in_command *x,
5928 int rcode = x->b_function(argv);
5932 /* On NOMMU, we must never block!
5933 * Example: { sleep 99 | read line; } & echo Ok
5935 re_execute_shell(to_free,
5944 static void execvp_or_die(char **argv) NORETURN;
5945 static void execvp_or_die(char **argv)
5947 debug_printf_exec("execing '%s'\n", argv[0]);
5948 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5949 execvp(argv[0], argv);
5950 bb_perror_msg("can't execute '%s'", argv[0]);
5951 _exit(127); /* bash compat */
5954 #if ENABLE_HUSH_MODE_X
5955 static void dump_cmd_in_x_mode(char **argv)
5957 if (G_x_mode && argv) {
5958 /* We want to output the line in one write op */
5966 len += strlen(argv[n++]) + 1;
5972 p += sprintf(p, " %s", argv[n++]);
5980 # define dump_cmd_in_x_mode(argv) ((void)0)
5984 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5985 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5986 #define pseudo_exec(nommu_save, command, argv_expanded) \
5987 pseudo_exec(command, argv_expanded)
5990 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5992 * Don't exit() here. If you don't exec, use _exit instead.
5993 * The at_exit handlers apparently confuse the calling process,
5994 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5995 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5996 char **argv, int assignment_cnt,
5997 char **argv_expanded) NORETURN;
5998 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5999 char **argv, int assignment_cnt,
6000 char **argv_expanded)
6004 new_env = expand_assignments(argv, assignment_cnt);
6005 dump_cmd_in_x_mode(new_env);
6007 if (!argv[assignment_cnt]) {
6008 /* Case when we are here: ... | var=val | ...
6009 * (note that we do not exit early, i.e., do not optimize out
6010 * expand_assignments(): think about ... | var=`sleep 1` | ...
6012 free_strings(new_env);
6013 _exit(EXIT_SUCCESS);
6017 set_vars_and_save_old(new_env);
6018 free(new_env); /* optional */
6019 /* we can also destroy set_vars_and_save_old's return value,
6022 nommu_save->new_env = new_env;
6023 nommu_save->old_vars = set_vars_and_save_old(new_env);
6026 if (argv_expanded) {
6027 argv = argv_expanded;
6029 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6031 nommu_save->argv = argv;
6034 dump_cmd_in_x_mode(argv);
6036 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6037 if (strchr(argv[0], '/') != NULL)
6041 /* Check if the command matches any of the builtins.
6042 * Depending on context, this might be redundant. But it's
6043 * easier to waste a few CPU cycles than it is to figure out
6044 * if this is one of those cases.
6047 /* On NOMMU, it is more expensive to re-execute shell
6048 * just in order to run echo or test builtin.
6049 * It's better to skip it here and run corresponding
6050 * non-builtin later. */
6051 const struct built_in_command *x;
6052 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6054 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6057 #if ENABLE_HUSH_FUNCTIONS
6058 /* Check if the command matches any functions */
6060 const struct function *funcp = find_function(argv[0]);
6062 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6067 #if ENABLE_FEATURE_SH_STANDALONE
6068 /* Check if the command matches any busybox applets */
6070 int a = find_applet_by_name(argv[0]);
6072 # if BB_MMU /* see above why on NOMMU it is not allowed */
6073 if (APPLET_IS_NOEXEC(a)) {
6074 debug_printf_exec("running applet '%s'\n", argv[0]);
6075 run_applet_no_and_exit(a, argv);
6078 /* Re-exec ourselves */
6079 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6080 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6081 execv(bb_busybox_exec_path, argv);
6082 /* If they called chroot or otherwise made the binary no longer
6083 * executable, fall through */
6088 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6091 execvp_or_die(argv);
6094 /* Called after [v]fork() in run_pipe
6096 static void pseudo_exec(nommu_save_t *nommu_save,
6097 struct command *command,
6098 char **argv_expanded) NORETURN;
6099 static void pseudo_exec(nommu_save_t *nommu_save,
6100 struct command *command,
6101 char **argv_expanded)
6103 if (command->argv) {
6104 pseudo_exec_argv(nommu_save, command->argv,
6105 command->assignment_cnt, argv_expanded);
6108 if (command->group) {
6109 /* Cases when we are here:
6112 * ... | ( list ) | ...
6113 * ... | { list } | ...
6117 debug_printf_exec("pseudo_exec: run_list\n");
6118 reset_traps_to_defaults();
6119 rcode = run_list(command->group);
6120 /* OK to leak memory by not calling free_pipe_list,
6121 * since this process is about to exit */
6124 re_execute_shell(&nommu_save->argv_from_re_execing,
6125 command->group_as_string,
6132 /* Case when we are here: ... | >file */
6133 debug_printf_exec("pseudo_exec'ed null command\n");
6134 _exit(EXIT_SUCCESS);
6138 static const char *get_cmdtext(struct pipe *pi)
6144 /* This is subtle. ->cmdtext is created only on first backgrounding.
6145 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6146 * On subsequent bg argv is trashed, but we won't use it */
6149 argv = pi->cmds[0].argv;
6150 if (!argv || !argv[0]) {
6151 pi->cmdtext = xzalloc(1);
6157 len += strlen(*argv) + 1;
6161 argv = pi->cmds[0].argv;
6163 len = strlen(*argv);
6164 memcpy(p, *argv, len);
6172 static void insert_bg_job(struct pipe *pi)
6174 struct pipe *job, **jobp;
6177 /* Linear search for the ID of the job to use */
6179 for (job = G.job_list; job; job = job->next)
6180 if (job->jobid >= pi->jobid)
6181 pi->jobid = job->jobid + 1;
6183 /* Add job to the list of running jobs */
6185 while ((job = *jobp) != NULL)
6187 job = *jobp = xmalloc(sizeof(*job));
6189 *job = *pi; /* physical copy */
6191 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6192 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6193 for (i = 0; i < pi->num_cmds; i++) {
6194 job->cmds[i].pid = pi->cmds[i].pid;
6195 /* all other fields are not used and stay zero */
6197 job->cmdtext = xstrdup(get_cmdtext(pi));
6199 if (G_interactive_fd)
6200 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6201 G.last_jobid = job->jobid;
6204 static void remove_bg_job(struct pipe *pi)
6206 struct pipe *prev_pipe;
6208 if (pi == G.job_list) {
6209 G.job_list = pi->next;
6211 prev_pipe = G.job_list;
6212 while (prev_pipe->next != pi)
6213 prev_pipe = prev_pipe->next;
6214 prev_pipe->next = pi->next;
6217 G.last_jobid = G.job_list->jobid;
6222 /* Remove a backgrounded job */
6223 static void delete_finished_bg_job(struct pipe *pi)
6230 /* Check to see if any processes have exited -- if they
6231 * have, figure out why and see if a job has completed */
6232 static int checkjobs(struct pipe *fg_pipe)
6242 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6244 attributes = WUNTRACED;
6245 if (fg_pipe == NULL)
6246 attributes |= WNOHANG;
6249 #if ENABLE_HUSH_FAST
6250 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6251 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6252 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6253 /* There was neither fork nor SIGCHLD since last waitpid */
6254 /* Avoid doing waitpid syscall if possible */
6255 if (!G.we_have_children) {
6259 if (fg_pipe == NULL) { /* is WNOHANG set? */
6260 /* We have children, but they did not exit
6261 * or stop yet (we saw no SIGCHLD) */
6264 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6268 /* Do we do this right?
6269 * bash-3.00# sleep 20 | false
6271 * [3]+ Stopped sleep 20 | false
6272 * bash-3.00# echo $?
6273 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6274 * [hush 1.14.0: yes we do it right]
6281 #if ENABLE_HUSH_FAST
6282 i = G.count_SIGCHLD;
6284 childpid = waitpid(-1, &status, attributes);
6285 if (childpid <= 0) {
6286 if (childpid && errno != ECHILD)
6287 bb_perror_msg("waitpid");
6288 #if ENABLE_HUSH_FAST
6289 else { /* Until next SIGCHLD, waitpid's are useless */
6290 G.we_have_children = (childpid == 0);
6291 G.handled_SIGCHLD = i;
6292 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6297 dead = WIFEXITED(status) || WIFSIGNALED(status);
6300 if (WIFSTOPPED(status))
6301 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6302 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6303 if (WIFSIGNALED(status))
6304 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6305 childpid, WTERMSIG(status), WEXITSTATUS(status));
6306 if (WIFEXITED(status))
6307 debug_printf_jobs("pid %d exited, exitcode %d\n",
6308 childpid, WEXITSTATUS(status));
6310 /* Were we asked to wait for fg pipe? */
6312 i = fg_pipe->num_cmds;
6314 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6315 if (fg_pipe->cmds[i].pid != childpid)
6318 fg_pipe->cmds[i].pid = 0;
6319 fg_pipe->alive_cmds--;
6320 if (i == fg_pipe->num_cmds - 1) {
6321 /* last process gives overall exitstatus */
6322 rcode = WEXITSTATUS(status);
6323 /* bash prints killer signal's name for *last*
6324 * process in pipe (prints just newline for SIGINT).
6325 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6327 if (WIFSIGNALED(status)) {
6328 int sig = WTERMSIG(status);
6329 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6330 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6331 * Maybe we need to use sig | 128? */
6334 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6337 fg_pipe->cmds[i].is_stopped = 1;
6338 fg_pipe->stopped_cmds++;
6340 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6341 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6342 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6343 /* All processes in fg pipe have exited or stopped */
6344 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6345 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6346 * and "killall -STOP cat" */
6347 if (G_interactive_fd) {
6349 if (fg_pipe->alive_cmds != 0)
6350 insert_bg_job(fg_pipe);
6354 if (fg_pipe->alive_cmds == 0)
6357 /* There are still running processes in the fg pipe */
6358 goto wait_more; /* do waitpid again */
6360 /* it wasnt fg_pipe, look for process in bg pipes */
6364 /* We asked to wait for bg or orphaned children */
6365 /* No need to remember exitcode in this case */
6366 for (pi = G.job_list; pi; pi = pi->next) {
6367 for (i = 0; i < pi->num_cmds; i++) {
6368 if (pi->cmds[i].pid == childpid)
6369 goto found_pi_and_prognum;
6372 /* Happens when shell is used as init process (init=/bin/sh) */
6373 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6374 continue; /* do waitpid again */
6376 found_pi_and_prognum:
6379 pi->cmds[i].pid = 0;
6381 if (!pi->alive_cmds) {
6382 if (G_interactive_fd)
6383 printf(JOB_STATUS_FORMAT, pi->jobid,
6384 "Done", pi->cmdtext);
6385 delete_finished_bg_job(pi);
6389 pi->cmds[i].is_stopped = 1;
6393 } /* while (waitpid succeeds)... */
6399 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6402 int rcode = checkjobs(fg_pipe);
6403 if (G_saved_tty_pgrp) {
6404 /* Job finished, move the shell to the foreground */
6405 p = getpgrp(); /* our process group id */
6406 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6407 tcsetpgrp(G_interactive_fd, p);
6413 /* Start all the jobs, but don't wait for anything to finish.
6416 * Return code is normally -1, when the caller has to wait for children
6417 * to finish to determine the exit status of the pipe. If the pipe
6418 * is a simple builtin command, however, the action is done by the
6419 * time run_pipe returns, and the exit code is provided as the
6422 * Returns -1 only if started some children. IOW: we have to
6423 * mask out retvals of builtins etc with 0xff!
6425 * The only case when we do not need to [v]fork is when the pipe
6426 * is single, non-backgrounded, non-subshell command. Examples:
6427 * cmd ; ... { list } ; ...
6428 * cmd && ... { list } && ...
6429 * cmd || ... { list } || ...
6430 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6431 * or (if SH_STANDALONE) an applet, and we can run the { list }
6432 * with run_list. If it isn't one of these, we fork and exec cmd.
6434 * Cases when we must fork:
6435 * non-single: cmd | cmd
6436 * backgrounded: cmd & { list } &
6437 * subshell: ( list ) [&]
6439 #if !ENABLE_HUSH_MODE_X
6440 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6441 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6443 static int redirect_and_varexp_helper(char ***new_env_p,
6444 struct variable **old_vars_p,
6445 struct command *command,
6447 char **argv_expanded)
6449 /* setup_redirects acts on file descriptors, not FILEs.
6450 * This is perfect for work that comes after exec().
6451 * Is it really safe for inline use? Experimentally,
6452 * things seem to work. */
6453 int rcode = setup_redirects(command, squirrel);
6455 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6456 *new_env_p = new_env;
6457 dump_cmd_in_x_mode(new_env);
6458 dump_cmd_in_x_mode(argv_expanded);
6460 *old_vars_p = set_vars_and_save_old(new_env);
6464 static NOINLINE int run_pipe(struct pipe *pi)
6466 static const char *const null_ptr = NULL;
6470 struct command *command;
6471 char **argv_expanded;
6473 /* it is not always needed, but we aim to smaller code */
6474 int squirrel[] = { -1, -1, -1 };
6477 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6480 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6481 * Result should be 3 lines: q w e, qwe, q w e
6483 G.ifs = get_local_var_value("IFS");
6487 IF_HUSH_JOB(pi->pgrp = -1;)
6488 pi->stopped_cmds = 0;
6489 command = &pi->cmds[0];
6490 argv_expanded = NULL;
6492 if (pi->num_cmds != 1
6493 || pi->followup == PIPE_BG
6494 || command->cmd_type == CMD_SUBSHELL
6501 debug_printf_exec(": group:%p argv:'%s'\n",
6502 command->group, command->argv ? command->argv[0] : "NONE");
6504 if (command->group) {
6505 #if ENABLE_HUSH_FUNCTIONS
6506 if (command->cmd_type == CMD_FUNCDEF) {
6507 /* "executing" func () { list } */
6508 struct function *funcp;
6510 funcp = new_function(command->argv[0]);
6511 /* funcp->name is already set to argv[0] */
6512 funcp->body = command->group;
6514 funcp->body_as_string = command->group_as_string;
6515 command->group_as_string = NULL;
6517 command->group = NULL;
6518 command->argv[0] = NULL;
6519 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6520 funcp->parent_cmd = command;
6521 command->child_func = funcp;
6523 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6525 return EXIT_SUCCESS;
6529 debug_printf("non-subshell group\n");
6530 rcode = 1; /* exitcode if redir failed */
6531 if (setup_redirects(command, squirrel) == 0) {
6532 debug_printf_exec(": run_list\n");
6533 rcode = run_list(command->group) & 0xff;
6535 restore_redirects(squirrel);
6536 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6538 debug_printf_exec("run_pipe: return %d\n", rcode);
6542 argv = command->argv ? command->argv : (char **) &null_ptr;
6544 const struct built_in_command *x;
6545 #if ENABLE_HUSH_FUNCTIONS
6546 const struct function *funcp;
6550 char **new_env = NULL;
6551 struct variable *old_vars = NULL;
6553 if (argv[command->assignment_cnt] == NULL) {
6554 /* Assignments, but no command */
6555 /* Ensure redirects take effect (that is, create files).
6556 * Try "a=t >file" */
6557 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6558 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6559 /* Set shell variables */
6563 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6564 /* Do we need to flag set_local_var() errors?
6565 * "assignment to readonly var" and "putenv error"
6570 /* Redirect error sets $? to 1. Otherwise,
6571 * if evaluating assignment value set $?, retain it.
6572 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6574 rcode = G.last_exitcode;
6575 /* Exit, _skipping_ variable restoring code: */
6576 goto clean_up_and_ret0;
6578 #else /* Older, bigger, but more correct code */
6580 rcode = setup_redirects(command, squirrel);
6581 restore_redirects(squirrel);
6582 /* Set shell variables */
6584 bb_putchar_stderr('+');
6586 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6588 fprintf(stderr, " %s", p);
6589 debug_printf_exec("set shell var:'%s'->'%s'\n",
6591 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6592 /* Do we need to flag set_local_var() errors?
6593 * "assignment to readonly var" and "putenv error"
6598 bb_putchar_stderr('\n');
6599 /* Redirect error sets $? to 1. Otherwise,
6600 * if evaluating assignment value set $?, retain it.
6601 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6603 rcode = G.last_exitcode;
6604 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6606 debug_printf_exec("run_pipe: return %d\n", rcode);
6611 /* Expand the rest into (possibly) many strings each */
6613 #if ENABLE_HUSH_BASH_COMPAT
6614 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6615 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6619 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6622 /* if someone gives us an empty string: `cmd with empty output` */
6623 if (!argv_expanded[0]) {
6624 free(argv_expanded);
6626 return G.last_exitcode;
6629 x = find_builtin(argv_expanded[0]);
6630 #if ENABLE_HUSH_FUNCTIONS
6633 funcp = find_function(argv_expanded[0]);
6637 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6638 debug_printf("exec with redirects only\n");
6639 rcode = setup_redirects(command, NULL);
6640 goto clean_up_and_ret1;
6643 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6646 debug_printf_exec(": builtin '%s' '%s'...\n",
6647 x->b_cmd, argv_expanded[1]);
6648 rcode = x->b_function(argv_expanded) & 0xff;
6651 #if ENABLE_HUSH_FUNCTIONS
6653 # if ENABLE_HUSH_LOCAL
6654 struct variable **sv;
6655 sv = G.shadowed_vars_pp;
6656 G.shadowed_vars_pp = &old_vars;
6658 debug_printf_exec(": function '%s' '%s'...\n",
6659 funcp->name, argv_expanded[1]);
6660 rcode = run_function(funcp, argv_expanded) & 0xff;
6661 # if ENABLE_HUSH_LOCAL
6662 G.shadowed_vars_pp = sv;
6668 unset_vars(new_env);
6670 /* clean_up_and_ret0: */
6671 restore_redirects(squirrel);
6673 free(argv_expanded);
6674 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6676 debug_printf_exec("run_pipe return %d\n", rcode);
6680 if (ENABLE_FEATURE_SH_STANDALONE) {
6681 int n = find_applet_by_name(argv_expanded[0]);
6682 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6683 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6685 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6686 argv_expanded[0], argv_expanded[1]);
6687 rcode = run_nofork_applet(n, argv_expanded);
6689 goto clean_up_and_ret;
6692 /* It is neither builtin nor applet. We must fork. */
6696 /* NB: argv_expanded may already be created, and that
6697 * might include `cmd` runs! Do not rerun it! We *must*
6698 * use argv_expanded if it's non-NULL */
6700 /* Going to fork a child per each pipe member */
6705 while (cmd_no < pi->num_cmds) {
6706 struct fd_pair pipefds;
6708 volatile nommu_save_t nommu_save;
6709 nommu_save.new_env = NULL;
6710 nommu_save.old_vars = NULL;
6711 nommu_save.argv = NULL;
6712 nommu_save.argv_from_re_execing = NULL;
6714 command = &pi->cmds[cmd_no];
6716 if (command->argv) {
6717 debug_printf_exec(": pipe member '%s' '%s'...\n",
6718 command->argv[0], command->argv[1]);
6720 debug_printf_exec(": pipe member with no argv\n");
6723 /* pipes are inserted between pairs of commands */
6726 if (cmd_no < pi->num_cmds)
6727 xpiped_pair(pipefds);
6729 command->pid = BB_MMU ? fork() : vfork();
6730 if (!command->pid) { /* child */
6732 disable_restore_tty_pgrp_on_exit();
6733 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6735 /* Every child adds itself to new process group
6736 * with pgid == pid_of_first_child_in_pipe */
6737 if (G.run_list_level == 1 && G_interactive_fd) {
6740 if (pgrp < 0) /* true for 1st process only */
6742 if (setpgid(0, pgrp) == 0
6743 && pi->followup != PIPE_BG
6744 && G_saved_tty_pgrp /* we have ctty */
6746 /* We do it in *every* child, not just first,
6748 tcsetpgrp(G_interactive_fd, pgrp);
6752 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6753 /* 1st cmd in backgrounded pipe
6754 * should have its stdin /dev/null'ed */
6756 if (open(bb_dev_null, O_RDONLY))
6757 xopen("/", O_RDONLY);
6759 xmove_fd(next_infd, 0);
6761 xmove_fd(pipefds.wr, 1);
6764 /* Like bash, explicit redirects override pipes,
6765 * and the pipe fd is available for dup'ing. */
6766 if (setup_redirects(command, NULL))
6769 /* Restore default handlers just prior to exec */
6770 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6772 /* Stores to nommu_save list of env vars putenv'ed
6773 * (NOMMU, on MMU we don't need that) */
6774 /* cast away volatility... */
6775 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6776 /* pseudo_exec() does not return */
6779 /* parent or error */
6780 #if ENABLE_HUSH_FAST
6782 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6784 enable_restore_tty_pgrp_on_exit();
6786 /* Clean up after vforked child */
6787 free(nommu_save.argv);
6788 free(nommu_save.argv_from_re_execing);
6789 unset_vars(nommu_save.new_env);
6790 add_vars(nommu_save.old_vars);
6792 free(argv_expanded);
6793 argv_expanded = NULL;
6794 if (command->pid < 0) { /* [v]fork failed */
6795 /* Clearly indicate, was it fork or vfork */
6796 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6800 /* Second and next children need to know pid of first one */
6802 pi->pgrp = command->pid;
6808 if (cmd_no < pi->num_cmds)
6810 /* Pass read (output) pipe end to next iteration */
6811 next_infd = pipefds.rd;
6814 if (!pi->alive_cmds) {
6816 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6821 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6825 #ifndef debug_print_tree
6826 static void debug_print_tree(struct pipe *pi, int lvl)
6828 static const char *const PIPE[] = {
6834 static const char *RES[] = {
6835 [RES_NONE ] = "NONE" ,
6838 [RES_THEN ] = "THEN" ,
6839 [RES_ELIF ] = "ELIF" ,
6840 [RES_ELSE ] = "ELSE" ,
6843 # if ENABLE_HUSH_LOOPS
6844 [RES_FOR ] = "FOR" ,
6845 [RES_WHILE] = "WHILE",
6846 [RES_UNTIL] = "UNTIL",
6848 [RES_DONE ] = "DONE" ,
6850 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6853 # if ENABLE_HUSH_CASE
6854 [RES_CASE ] = "CASE" ,
6855 [RES_CASE_IN ] = "CASE_IN" ,
6856 [RES_MATCH] = "MATCH",
6857 [RES_CASE_BODY] = "CASE_BODY",
6858 [RES_ESAC ] = "ESAC" ,
6860 [RES_XXXX ] = "XXXX" ,
6861 [RES_SNTX ] = "SNTX" ,
6863 static const char *const CMDTYPE[] = {
6867 # if ENABLE_HUSH_FUNCTIONS
6876 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6877 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6879 while (prn < pi->num_cmds) {
6880 struct command *command = &pi->cmds[prn];
6881 char **argv = command->argv;
6883 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6885 command->assignment_cnt);
6886 if (command->group) {
6887 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6888 CMDTYPE[command->cmd_type],
6891 , " group_as_string:", command->group_as_string
6896 debug_print_tree(command->group, lvl+1);
6900 if (argv) while (*argv) {
6901 fprintf(stderr, " '%s'", *argv);
6904 fprintf(stderr, "\n");
6911 #endif /* debug_print_tree */
6913 /* NB: called by pseudo_exec, and therefore must not modify any
6914 * global data until exec/_exit (we can be a child after vfork!) */
6915 static int run_list(struct pipe *pi)
6917 #if ENABLE_HUSH_CASE
6918 char *case_word = NULL;
6920 #if ENABLE_HUSH_LOOPS
6921 struct pipe *loop_top = NULL;
6922 char **for_lcur = NULL;
6923 char **for_list = NULL;
6925 smallint last_followup;
6927 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6928 smalluint cond_code = 0;
6930 enum { cond_code = 0 };
6933 smallint rword; /* RES_foo */
6934 smallint last_rword; /* ditto */
6937 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6940 #if ENABLE_HUSH_LOOPS
6941 /* Check syntax for "for" */
6942 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6943 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6945 /* current word is FOR or IN (BOLD in comments below) */
6946 if (cpipe->next == NULL) {
6947 syntax_error("malformed for");
6949 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6952 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6953 if (cpipe->next->res_word == RES_DO)
6955 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6956 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6957 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6959 syntax_error("malformed for");
6961 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6967 /* Past this point, all code paths should jump to ret: label
6968 * in order to return, no direct "return" statements please.
6969 * This helps to ensure that no memory is leaked. */
6977 last_rword = RES_XXXX;
6979 last_followup = PIPE_SEQ;
6980 rcode = G.last_exitcode;
6982 /* Go through list of pipes, (maybe) executing them. */
6983 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6987 IF_HAS_KEYWORDS(rword = pi->res_word;)
6988 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6989 rword, cond_code, last_rword);
6990 #if ENABLE_HUSH_LOOPS
6991 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6992 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6994 /* start of a loop: remember where loop starts */
6999 /* Still in the same "if...", "then..." or "do..." branch? */
7000 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7001 if ((rcode == 0 && last_followup == PIPE_OR)
7002 || (rcode != 0 && last_followup == PIPE_AND)
7004 /* It is "<true> || CMD" or "<false> && CMD"
7005 * and we should not execute CMD */
7006 debug_printf_exec("skipped cmd because of || or &&\n");
7007 last_followup = pi->followup;
7011 last_followup = pi->followup;
7012 IF_HAS_KEYWORDS(last_rword = rword;)
7015 if (rword == RES_THEN) {
7016 /* if false; then ... fi has exitcode 0! */
7017 G.last_exitcode = rcode = EXIT_SUCCESS;
7018 /* "if <false> THEN cmd": skip cmd */
7022 if (rword == RES_ELSE || rword == RES_ELIF) {
7023 /* "if <true> then ... ELSE/ELIF cmd":
7024 * skip cmd and all following ones */
7029 #if ENABLE_HUSH_LOOPS
7030 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7032 /* first loop through for */
7034 static const char encoded_dollar_at[] ALIGN1 = {
7035 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7036 }; /* encoded representation of "$@" */
7037 static const char *const encoded_dollar_at_argv[] = {
7038 encoded_dollar_at, NULL
7039 }; /* argv list with one element: "$@" */
7042 vals = (char**)encoded_dollar_at_argv;
7043 if (pi->next->res_word == RES_IN) {
7044 /* if no variable values after "in" we skip "for" */
7045 if (!pi->next->cmds[0].argv) {
7046 G.last_exitcode = rcode = EXIT_SUCCESS;
7047 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7050 vals = pi->next->cmds[0].argv;
7051 } /* else: "for var; do..." -> assume "$@" list */
7052 /* create list of variable values */
7053 debug_print_strings("for_list made from", vals);
7054 for_list = expand_strvec_to_strvec(vals);
7055 for_lcur = for_list;
7056 debug_print_strings("for_list", for_list);
7059 /* "for" loop is over, clean up */
7065 /* Insert next value from for_lcur */
7066 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7067 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7070 if (rword == RES_IN) {
7071 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7073 if (rword == RES_DONE) {
7074 continue; /* "done" has no cmds too */
7077 #if ENABLE_HUSH_CASE
7078 if (rword == RES_CASE) {
7079 case_word = expand_strvec_to_string(pi->cmds->argv);
7082 if (rword == RES_MATCH) {
7085 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7087 /* all prev words didn't match, does this one match? */
7088 argv = pi->cmds->argv;
7090 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7091 /* TODO: which FNM_xxx flags to use? */
7092 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7094 if (cond_code == 0) { /* match! we will execute this branch */
7095 free(case_word); /* make future "word)" stop */
7103 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7105 continue; /* not matched yet, skip this pipe */
7108 /* Just pressing <enter> in shell should check for jobs.
7109 * OTOH, in non-interactive shell this is useless
7110 * and only leads to extra job checks */
7111 if (pi->num_cmds == 0) {
7112 if (G_interactive_fd)
7113 goto check_jobs_and_continue;
7117 /* After analyzing all keywords and conditions, we decided
7118 * to execute this pipe. NB: have to do checkjobs(NULL)
7119 * after run_pipe to collect any background children,
7120 * even if list execution is to be stopped. */
7121 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7124 #if ENABLE_HUSH_LOOPS
7125 G.flag_break_continue = 0;
7127 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7129 /* We ran a builtin, function, or group.
7130 * rcode is already known
7131 * and we don't need to wait for anything. */
7132 G.last_exitcode = rcode;
7133 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7134 check_and_run_traps(0);
7135 #if ENABLE_HUSH_LOOPS
7136 /* Was it "break" or "continue"? */
7137 if (G.flag_break_continue) {
7138 smallint fbc = G.flag_break_continue;
7139 /* We might fall into outer *loop*,
7140 * don't want to break it too */
7142 G.depth_break_continue--;
7143 if (G.depth_break_continue == 0)
7144 G.flag_break_continue = 0;
7145 /* else: e.g. "continue 2" should *break* once, *then* continue */
7146 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7147 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7148 goto check_jobs_and_break;
7149 /* "continue": simulate end of loop */
7154 #if ENABLE_HUSH_FUNCTIONS
7155 if (G.flag_return_in_progress == 1) {
7156 /* same as "goto check_jobs_and_break" */
7161 } else if (pi->followup == PIPE_BG) {
7162 /* What does bash do with attempts to background builtins? */
7163 /* even bash 3.2 doesn't do that well with nested bg:
7164 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7165 * I'm NOT treating inner &'s as jobs */
7166 check_and_run_traps(0);
7168 if (G.run_list_level == 1)
7171 /* Last command's pid goes to $! */
7172 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7173 G.last_exitcode = rcode = EXIT_SUCCESS;
7174 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7177 if (G.run_list_level == 1 && G_interactive_fd) {
7178 /* Waits for completion, then fg's main shell */
7179 rcode = checkjobs_and_fg_shell(pi);
7180 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7181 check_and_run_traps(0);
7184 { /* This one just waits for completion */
7185 rcode = checkjobs(pi);
7186 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7187 check_and_run_traps(0);
7189 G.last_exitcode = rcode;
7193 /* Analyze how result affects subsequent commands */
7195 if (rword == RES_IF || rword == RES_ELIF)
7198 #if ENABLE_HUSH_LOOPS
7199 /* Beware of "while false; true; do ..."! */
7200 if (pi->next && pi->next->res_word == RES_DO) {
7201 if (rword == RES_WHILE) {
7203 /* "while false; do...done" - exitcode 0 */
7204 G.last_exitcode = rcode = EXIT_SUCCESS;
7205 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7206 goto check_jobs_and_break;
7209 if (rword == RES_UNTIL) {
7211 debug_printf_exec(": until expr is true: breaking\n");
7212 check_jobs_and_break:
7220 check_jobs_and_continue:
7227 #if ENABLE_HUSH_LOOPS
7232 #if ENABLE_HUSH_CASE
7236 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7240 /* Select which version we will use */
7241 static int run_and_free_list(struct pipe *pi)
7244 debug_printf_exec("run_and_free_list entered\n");
7246 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7247 rcode = run_list(pi);
7249 /* free_pipe_list has the side effect of clearing memory.
7250 * In the long run that function can be merged with run_list,
7251 * but doing that now would hobble the debugging effort. */
7253 debug_printf_exec("run_and_free_list return %d\n", rcode);
7258 /* Called a few times only (or even once if "sh -c") */
7259 static void init_sigmasks(void)
7263 sigset_t old_blocked_set;
7265 if (!G.inherited_set_is_saved) {
7266 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7267 G.inherited_set = G.blocked_set;
7269 old_blocked_set = G.blocked_set;
7271 mask = (1 << SIGQUIT);
7272 if (G_interactive_fd) {
7273 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7274 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7275 mask |= SPECIAL_JOB_SIGS;
7277 G.non_DFL_mask = mask;
7282 sigaddset(&G.blocked_set, sig);
7286 sigdelset(&G.blocked_set, SIGCHLD);
7288 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7289 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7291 /* POSIX allows shell to re-enable SIGCHLD
7292 * even if it was SIG_IGN on entry */
7293 #if ENABLE_HUSH_FAST
7294 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7295 if (!G.inherited_set_is_saved)
7296 signal(SIGCHLD, SIGCHLD_handler);
7298 if (!G.inherited_set_is_saved)
7299 signal(SIGCHLD, SIG_DFL);
7302 G.inherited_set_is_saved = 1;
7307 static void maybe_set_to_sigexit(int sig)
7309 void (*handler)(int);
7310 /* non_DFL_mask'ed signals are, well, masked,
7311 * no need to set handler for them.
7313 if (!((G.non_DFL_mask >> sig) & 1)) {
7314 handler = signal(sig, sigexit);
7315 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7316 signal(sig, handler);
7319 /* Set handlers to restore tty pgrp and exit */
7320 static void set_fatal_handlers(void)
7322 /* We _must_ restore tty pgrp on fatal signals */
7324 maybe_set_to_sigexit(SIGILL );
7325 maybe_set_to_sigexit(SIGFPE );
7326 maybe_set_to_sigexit(SIGBUS );
7327 maybe_set_to_sigexit(SIGSEGV);
7328 maybe_set_to_sigexit(SIGTRAP);
7329 } /* else: hush is perfect. what SEGV? */
7330 maybe_set_to_sigexit(SIGABRT);
7331 /* bash 3.2 seems to handle these just like 'fatal' ones */
7332 maybe_set_to_sigexit(SIGPIPE);
7333 maybe_set_to_sigexit(SIGALRM);
7334 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7335 * if we aren't interactive... but in this case
7336 * we never want to restore pgrp on exit, and this fn is not called */
7337 /*maybe_set_to_sigexit(SIGHUP );*/
7338 /*maybe_set_to_sigexit(SIGTERM);*/
7339 /*maybe_set_to_sigexit(SIGINT );*/
7343 static int set_mode(const char cstate, const char mode)
7345 int state = (cstate == '-' ? 1 : 0);
7347 case 'n': G.n_mode = state; break;
7348 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7349 default: return EXIT_FAILURE;
7351 return EXIT_SUCCESS;
7354 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7355 int hush_main(int argc, char **argv)
7358 unsigned builtin_argc;
7360 struct variable *cur_var;
7361 struct variable shell_ver;
7364 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7365 G.last_exitcode = EXIT_SUCCESS;
7367 G.argv0_for_re_execing = argv[0];
7369 /* Deal with HUSH_VERSION */
7370 memset(&shell_ver, 0, sizeof(shell_ver));
7371 shell_ver.flg_export = 1;
7372 shell_ver.flg_read_only = 1;
7373 /* Code which handles ${var<op>...} needs writable values for all variables,
7374 * therefore we xstrdup: */
7375 shell_ver.varstr = xstrdup(hush_version_str),
7376 G.top_var = &shell_ver;
7377 /* Create shell local variables from the values
7378 * currently living in the environment */
7379 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7380 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7381 cur_var = G.top_var;
7384 char *value = strchr(*e, '=');
7385 if (value) { /* paranoia */
7386 cur_var->next = xzalloc(sizeof(*cur_var));
7387 cur_var = cur_var->next;
7388 cur_var->varstr = *e;
7389 cur_var->max_len = strlen(*e);
7390 cur_var->flg_export = 1;
7394 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7395 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7396 putenv(shell_ver.varstr);
7399 set_pwd_var(/*exp:*/ 1);
7400 /* bash also exports SHLVL and _,
7401 * and sets (but doesn't export) the following variables:
7403 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7404 * BASH_VERSION='3.2.0(1)-release'
7406 * MACHTYPE=i386-pc-linux-gnu
7408 * HOSTNAME=<xxxxxxxxxx>
7409 * PPID=<NNNNN> - we also do it elsewhere
7420 * PIPESTATUS=([0]="0")
7421 * HISTFILE=/<xxx>/.bash_history
7425 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7427 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7437 #if ENABLE_FEATURE_EDITING
7438 G.line_input_state = new_line_input_t(FOR_SHELL);
7439 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7441 const char *hp = get_local_var_value("HISTFILE");
7443 hp = get_local_var_value("HOME");
7445 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7446 //set_local_var(xasprintf("HISTFILE=%s", ...));
7453 G.global_argc = argc;
7454 G.global_argv = argv;
7455 /* Initialize some more globals to non-zero values */
7456 cmdedit_update_prompt();
7458 if (setjmp(die_jmp)) {
7459 /* xfunc has failed! die die die */
7460 /* no EXIT traps, this is an escape hatch! */
7462 hush_exit(xfunc_error_retval);
7465 /* Shell is non-interactive at first. We need to call
7466 * init_sigmasks() if we are going to execute "sh <script>",
7467 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7468 * If we later decide that we are interactive, we run init_sigmasks()
7469 * in order to intercept (more) signals.
7473 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7476 opt = getopt(argc, argv, "+c:xins"
7479 # if ENABLE_HUSH_FUNCTIONS
7489 * sh ... -c 'script'
7490 * sh ... -c 'script' ARG0 [ARG1...]
7491 * On NOMMU, if builtin_argc != 0,
7492 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7493 * "" needs to be replaced with NULL
7494 * and BARGV vector fed to builtin function.
7495 * Note: the form without ARG0 never happens:
7496 * sh ... -c 'builtin' BARGV... ""
7499 G.root_pid = getpid();
7500 G.root_ppid = getppid();
7502 G.global_argv = argv + optind;
7503 G.global_argc = argc - optind;
7505 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7506 const struct built_in_command *x;
7509 x = find_builtin(optarg);
7510 if (x) { /* paranoia */
7511 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7512 G.global_argv += builtin_argc;
7513 G.global_argv[-1] = NULL; /* replace "" */
7514 G.last_exitcode = x->b_function(argv + optind - 1);
7518 if (!G.global_argv[0]) {
7519 /* -c 'script' (no params): prevent empty $0 */
7520 G.global_argv--; /* points to argv[i] of 'script' */
7521 G.global_argv[0] = argv[0];
7523 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7525 parse_and_run_string(optarg);
7528 /* Well, we cannot just declare interactiveness,
7529 * we have to have some stuff (ctty, etc) */
7530 /* G_interactive_fd++; */
7533 /* "-s" means "read from stdin", but this is how we always
7534 * operate, so simply do nothing here. */
7537 case '<': /* "big heredoc" support */
7538 full_write1_str(optarg);
7541 unsigned long long empty_trap_mask;
7543 G.root_pid = bb_strtou(optarg, &optarg, 16);
7545 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7547 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7549 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7551 builtin_argc = bb_strtou(optarg, &optarg, 16);
7553 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7554 if (empty_trap_mask != 0) {
7557 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7558 for (sig = 1; sig < NSIG; sig++) {
7559 if (empty_trap_mask & (1LL << sig)) {
7560 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7561 sigaddset(&G.blocked_set, sig);
7564 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7566 # if ENABLE_HUSH_LOOPS
7568 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7574 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7576 # if ENABLE_HUSH_FUNCTIONS
7578 struct function *funcp = new_function(optarg);
7579 /* funcp->name is already set to optarg */
7580 /* funcp->body is set to NULL. It's a special case. */
7581 funcp->body_as_string = argv[optind];
7589 if (set_mode('-', opt) == 0) /* no error */
7593 fprintf(stderr, "Usage: sh [FILE]...\n"
7594 " or: sh -c command [args]...\n\n");
7600 } /* option parsing loop */
7603 G.root_pid = getpid();
7604 G.root_ppid = getppid();
7607 /* If we are login shell... */
7608 if (argv[0] && argv[0][0] == '-') {
7610 debug_printf("sourcing /etc/profile\n");
7611 input = fopen_for_read("/etc/profile");
7612 if (input != NULL) {
7613 close_on_exec_on(fileno(input));
7615 parse_and_run_file(input);
7618 /* bash: after sourcing /etc/profile,
7619 * tries to source (in the given order):
7620 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7621 * stopping on first found. --noprofile turns this off.
7622 * bash also sources ~/.bash_logout on exit.
7623 * If called as sh, skips .bash_XXX files.
7630 * "bash <script>" (which is never interactive (unless -i?))
7631 * sources $BASH_ENV here (without scanning $PATH).
7632 * If called as sh, does the same but with $ENV.
7634 debug_printf("running script '%s'\n", argv[optind]);
7635 G.global_argv = argv + optind;
7636 G.global_argc = argc - optind;
7637 input = xfopen_for_read(argv[optind]);
7638 close_on_exec_on(fileno(input));
7640 parse_and_run_file(input);
7641 #if ENABLE_FEATURE_CLEAN_UP
7647 /* Up to here, shell was non-interactive. Now it may become one.
7648 * NB: don't forget to (re)run init_sigmasks() as needed.
7651 /* A shell is interactive if the '-i' flag was given,
7652 * or if all of the following conditions are met:
7654 * no arguments remaining or the -s flag given
7655 * standard input is a terminal
7656 * standard output is a terminal
7657 * Refer to Posix.2, the description of the 'sh' utility.
7660 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7661 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7662 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7663 if (G_saved_tty_pgrp < 0)
7664 G_saved_tty_pgrp = 0;
7666 /* try to dup stdin to high fd#, >= 255 */
7667 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7668 if (G_interactive_fd < 0) {
7669 /* try to dup to any fd */
7670 G_interactive_fd = dup(STDIN_FILENO);
7671 if (G_interactive_fd < 0) {
7673 G_interactive_fd = 0;
7674 G_saved_tty_pgrp = 0;
7677 // TODO: track & disallow any attempts of user
7678 // to (inadvertently) close/redirect G_interactive_fd
7680 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7681 if (G_interactive_fd) {
7682 close_on_exec_on(G_interactive_fd);
7684 if (G_saved_tty_pgrp) {
7685 /* If we were run as 'hush &', sleep until we are
7686 * in the foreground (tty pgrp == our pgrp).
7687 * If we get started under a job aware app (like bash),
7688 * make sure we are now in charge so we don't fight over
7689 * who gets the foreground */
7691 pid_t shell_pgrp = getpgrp();
7692 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7693 if (G_saved_tty_pgrp == shell_pgrp)
7695 /* send TTIN to ourself (should stop us) */
7696 kill(- shell_pgrp, SIGTTIN);
7700 /* Block some signals */
7703 if (G_saved_tty_pgrp) {
7704 /* Set other signals to restore saved_tty_pgrp */
7705 set_fatal_handlers();
7706 /* Put ourselves in our own process group
7707 * (bash, too, does this only if ctty is available) */
7708 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7709 /* Grab control of the terminal */
7710 tcsetpgrp(G_interactive_fd, getpid());
7712 /* -1 is special - makes xfuncs longjmp, not exit
7713 * (we reset die_sleep = 0 whereever we [v]fork) */
7714 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7718 #elif ENABLE_HUSH_INTERACTIVE
7719 /* No job control compiled in, only prompt/line editing */
7720 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7721 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7722 if (G_interactive_fd < 0) {
7723 /* try to dup to any fd */
7724 G_interactive_fd = dup(STDIN_FILENO);
7725 if (G_interactive_fd < 0)
7727 G_interactive_fd = 0;
7730 if (G_interactive_fd) {
7731 close_on_exec_on(G_interactive_fd);
7735 /* We have interactiveness code disabled */
7739 * if interactive but not a login shell, sources ~/.bashrc
7740 * (--norc turns this off, --rcfile <file> overrides)
7743 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7744 /* note: ash and hush share this string */
7745 printf("\n\n%s %s\n"
7746 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7749 "hush - the humble shell"
7753 parse_and_run_file(stdin);
7756 #if ENABLE_FEATURE_CLEAN_UP
7757 if (G.cwd != bb_msg_unknown)
7759 cur_var = G.top_var->next;
7761 struct variable *tmp = cur_var;
7762 if (!cur_var->max_len)
7763 free(cur_var->varstr);
7764 cur_var = cur_var->next;
7768 hush_exit(G.last_exitcode);
7773 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7774 int msh_main(int argc, char **argv)
7776 //bb_error_msg("msh is deprecated, please use hush instead");
7777 return hush_main(argc, argv);
7785 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7790 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7797 return applet_main_func(argc, argv - argc);
7800 static int FAST_FUNC builtin_test(char **argv)
7802 return run_applet_main(argv, test_main);
7805 static int FAST_FUNC builtin_echo(char **argv)
7807 return run_applet_main(argv, echo_main);
7811 static int FAST_FUNC builtin_printf(char **argv)
7813 return run_applet_main(argv, printf_main);
7817 static char **skip_dash_dash(char **argv)
7820 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7825 static int FAST_FUNC builtin_eval(char **argv)
7827 int rcode = EXIT_SUCCESS;
7829 argv = skip_dash_dash(argv);
7831 char *str = expand_strvec_to_string(argv);
7833 * eval "echo Hi; done" ("done" is syntax error):
7834 * "echo Hi" will not execute too.
7836 parse_and_run_string(str);
7838 rcode = G.last_exitcode;
7843 static int FAST_FUNC builtin_cd(char **argv)
7847 argv = skip_dash_dash(argv);
7849 if (newdir == NULL) {
7850 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7851 * bash says "bash: cd: HOME not set" and does nothing
7854 const char *home = get_local_var_value("HOME");
7855 newdir = home ? home : "/";
7857 if (chdir(newdir)) {
7858 /* Mimic bash message exactly */
7859 bb_perror_msg("cd: %s", newdir);
7860 return EXIT_FAILURE;
7862 /* Read current dir (get_cwd(1) is inside) and set PWD.
7863 * Note: do not enforce exporting. If PWD was unset or unexported,
7864 * set it again, but do not export. bash does the same.
7866 set_pwd_var(/*exp:*/ 0);
7867 return EXIT_SUCCESS;
7870 static int FAST_FUNC builtin_exec(char **argv)
7872 argv = skip_dash_dash(argv);
7873 if (argv[0] == NULL)
7874 return EXIT_SUCCESS; /* bash does this */
7876 /* Careful: we can end up here after [v]fork. Do not restore
7877 * tty pgrp then, only top-level shell process does that */
7878 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7879 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7881 /* TODO: if exec fails, bash does NOT exit! We do.
7882 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7883 * and tcsetpgrp, and this is inherently racy.
7885 execvp_or_die(argv);
7888 static int FAST_FUNC builtin_exit(char **argv)
7890 debug_printf_exec("%s()\n", __func__);
7892 /* interactive bash:
7893 * # trap "echo EEE" EXIT
7896 * There are stopped jobs.
7897 * (if there are _stopped_ jobs, running ones don't count)
7900 # EEE (then bash exits)
7902 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
7905 /* note: EXIT trap is run by hush_exit */
7906 argv = skip_dash_dash(argv);
7907 if (argv[0] == NULL)
7908 hush_exit(G.last_exitcode);
7909 /* mimic bash: exit 123abc == exit 255 + error msg */
7910 xfunc_error_retval = 255;
7911 /* bash: exit -2 == exit 254, no error msg */
7912 hush_exit(xatoi(argv[0]) & 0xff);
7915 static void print_escaped(const char *s)
7920 const char *p = strchrnul(s, '\'');
7921 /* print 'xxxx', possibly just '' */
7922 printf("'%.*s'", (int)(p - s), s);
7927 /* s points to '; print "'''...'''" */
7929 do putchar('\''); while (*++s == '\'');
7934 #if !ENABLE_HUSH_LOCAL
7935 #define helper_export_local(argv, exp, lvl) \
7936 helper_export_local(argv, exp)
7938 static void helper_export_local(char **argv, int exp, int lvl)
7942 char *name_end = strchrnul(name, '=');
7944 /* So far we do not check that name is valid (TODO?) */
7946 if (*name_end == '\0') {
7947 struct variable *var, **vpp;
7949 vpp = get_ptr_to_local_var(name, name_end - name);
7950 var = vpp ? *vpp : NULL;
7952 if (exp == -1) { /* unexporting? */
7953 /* export -n NAME (without =VALUE) */
7955 var->flg_export = 0;
7956 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7958 } /* else: export -n NOT_EXISTING_VAR: no-op */
7961 if (exp == 1) { /* exporting? */
7962 /* export NAME (without =VALUE) */
7964 var->flg_export = 1;
7965 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7966 putenv(var->varstr);
7970 /* Exporting non-existing variable.
7971 * bash does not put it in environment,
7972 * but remembers that it is exported,
7973 * and does put it in env when it is set later.
7974 * We just set it to "" and export. */
7975 /* Or, it's "local NAME" (without =VALUE).
7976 * bash sets the value to "". */
7977 name = xasprintf("%s=", name);
7979 /* (Un)exporting/making local NAME=VALUE */
7980 name = xstrdup(name);
7982 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7986 static int FAST_FUNC builtin_export(char **argv)
7988 unsigned opt_unexport;
7990 #if ENABLE_HUSH_EXPORT_N
7991 /* "!": do not abort on errors */
7992 opt_unexport = getopt32(argv, "!n");
7993 if (opt_unexport == (uint32_t)-1)
7994 return EXIT_FAILURE;
8001 if (argv[0] == NULL) {
8008 /* ash emits: export VAR='VAL'
8009 * bash: declare -x VAR="VAL"
8010 * we follow ash example */
8011 const char *s = *e++;
8012 const char *p = strchr(s, '=');
8014 if (!p) /* wtf? take next variable */
8017 printf("export %.*s", (int)(p - s) + 1, s);
8018 print_escaped(p + 1);
8022 /*fflush_all(); - done after each builtin anyway */
8024 return EXIT_SUCCESS;
8027 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8029 return EXIT_SUCCESS;
8032 #if ENABLE_HUSH_LOCAL
8033 static int FAST_FUNC builtin_local(char **argv)
8035 if (G.func_nest_level == 0) {
8036 bb_error_msg("%s: not in a function", argv[0]);
8037 return EXIT_FAILURE; /* bash compat */
8039 helper_export_local(argv, 0, G.func_nest_level);
8040 return EXIT_SUCCESS;
8044 static int FAST_FUNC builtin_trap(char **argv)
8050 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8055 /* No args: print all trapped */
8056 for (i = 0; i < NSIG; ++i) {
8059 print_escaped(G.traps[i]);
8060 /* note: bash adds "SIG", but only if invoked
8061 * as "bash". If called as "sh", or if set -o posix,
8062 * then it prints short signal names.
8063 * We are printing short names: */
8064 printf(" %s\n", get_signame(i));
8067 /*fflush_all(); - done after each builtin anyway */
8068 return EXIT_SUCCESS;
8072 /* If first arg is a number: reset all specified signals */
8073 sig = bb_strtou(*argv, NULL, 10);
8079 sig = get_signum(*argv++);
8080 if (sig < 0 || sig >= NSIG) {
8082 /* Mimic bash message exactly */
8083 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8088 G.traps[sig] = xstrdup(new_cmd);
8090 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8091 get_signame(sig), sig, G.traps[sig]);
8093 /* There is no signal for 0 (EXIT) */
8098 sigaddset(&G.blocked_set, sig);
8100 /* There was a trap handler, we are removing it
8101 * (if sig has non-DFL handling,
8102 * we don't need to do anything) */
8103 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8105 sigdelset(&G.blocked_set, sig);
8108 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8112 if (!argv[1]) { /* no second arg */
8113 bb_error_msg("trap: invalid arguments");
8114 return EXIT_FAILURE;
8117 /* First arg is "-": reset all specified to default */
8118 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8119 /* Everything else: set arg as signal handler
8120 * (includes "" case, which ignores signal) */
8121 if (argv[0][0] == '-') {
8122 if (argv[0][1] == '\0') { /* "-" */
8123 /* new_cmd remains NULL: "reset these sigs" */
8126 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8129 /* else: "-something", no special meaning */
8134 goto process_sig_list;
8137 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8138 static int FAST_FUNC builtin_type(char **argv)
8140 int ret = EXIT_SUCCESS;
8146 if (0) {} /* make conditional compile easier below */
8147 /*else if (find_alias(*argv))
8148 type = "an alias";*/
8149 #if ENABLE_HUSH_FUNCTIONS
8150 else if (find_function(*argv))
8151 type = "a function";
8153 else if (find_builtin(*argv))
8154 type = "a shell builtin";
8155 else if ((path = find_in_path(*argv)) != NULL)
8158 bb_error_msg("type: %s: not found", *argv);
8163 printf("%s is %s\n", *argv, type);
8171 /* built-in 'fg' and 'bg' handler */
8172 static int FAST_FUNC builtin_fg_bg(char **argv)
8177 if (!G_interactive_fd)
8178 return EXIT_FAILURE;
8180 /* If they gave us no args, assume they want the last backgrounded task */
8182 for (pi = G.job_list; pi; pi = pi->next) {
8183 if (pi->jobid == G.last_jobid) {
8187 bb_error_msg("%s: no current job", argv[0]);
8188 return EXIT_FAILURE;
8190 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8191 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8192 return EXIT_FAILURE;
8194 for (pi = G.job_list; pi; pi = pi->next) {
8195 if (pi->jobid == jobnum) {
8199 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8200 return EXIT_FAILURE;
8202 /* TODO: bash prints a string representation
8203 * of job being foregrounded (like "sleep 1 | cat") */
8204 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8205 /* Put the job into the foreground. */
8206 tcsetpgrp(G_interactive_fd, pi->pgrp);
8209 /* Restart the processes in the job */
8210 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8211 for (i = 0; i < pi->num_cmds; i++) {
8212 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8213 pi->cmds[i].is_stopped = 0;
8215 pi->stopped_cmds = 0;
8217 i = kill(- pi->pgrp, SIGCONT);
8219 if (errno == ESRCH) {
8220 delete_finished_bg_job(pi);
8221 return EXIT_SUCCESS;
8223 bb_perror_msg("kill (SIGCONT)");
8226 if (argv[0][0] == 'f') {
8228 return checkjobs_and_fg_shell(pi);
8230 return EXIT_SUCCESS;
8234 #if ENABLE_HUSH_HELP
8235 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8237 const struct built_in_command *x;
8240 "Built-in commands:\n"
8241 "------------------\n");
8242 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8244 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8247 return EXIT_SUCCESS;
8252 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8255 const char *status_string;
8257 for (job = G.job_list; job; job = job->next) {
8258 if (job->alive_cmds == job->stopped_cmds)
8259 status_string = "Stopped";
8261 status_string = "Running";
8263 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8265 return EXIT_SUCCESS;
8270 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8275 # ifdef M_TRIM_THRESHOLD
8276 /* Optional. Reduces probability of false positives */
8279 /* Crude attempt to find where "free memory" starts,
8280 * sans fragmentation. */
8282 l = (unsigned long)p;
8285 if (l < (unsigned long)p) l = (unsigned long)p;
8288 if (!G.memleak_value)
8289 G.memleak_value = l;
8291 l -= G.memleak_value;
8298 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8303 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8306 return EXIT_SUCCESS;
8309 static int FAST_FUNC builtin_read(char **argv)
8318 /* "!": do not abort on errors.
8319 * Option string must start with "sr" to match BUILTIN_READ_xxx
8321 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8322 if (read_flags == (uint32_t)-1)
8323 return EXIT_FAILURE;
8326 r = shell_builtin_read(set_local_var_from_halves,
8328 get_local_var_value("IFS"), /* can be NULL */
8336 if ((uintptr_t)r > 1) {
8337 bb_error_msg("%s", r);
8338 r = (char*)(uintptr_t)1;
8341 return (uintptr_t)r;
8344 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8345 * built-in 'set' handler
8347 * set [-abCefhmnuvx] [-o option] [argument...]
8348 * set [+abCefhmnuvx] [+o option] [argument...]
8349 * set -- [argument...]
8352 * Implementations shall support the options in both their hyphen and
8353 * plus-sign forms. These options can also be specified as options to sh.
8355 * Write out all variables and their values: set
8356 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8357 * Turn on the -x and -v options: set -xv
8358 * Unset all positional parameters: set --
8359 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8360 * Set the positional parameters to the expansion of x, even if x expands
8361 * with a leading '-' or '+': set -- $x
8363 * So far, we only support "set -- [argument...]" and some of the short names.
8365 static int FAST_FUNC builtin_set(char **argv)
8368 char **pp, **g_argv;
8369 char *arg = *++argv;
8373 for (e = G.top_var; e; e = e->next)
8375 return EXIT_SUCCESS;
8379 if (!strcmp(arg, "--")) {
8383 if (arg[0] != '+' && arg[0] != '-')
8385 for (n = 1; arg[n]; ++n)
8386 if (set_mode(arg[0], arg[n]))
8388 } while ((arg = *++argv) != NULL);
8389 /* Now argv[0] is 1st argument */
8392 return EXIT_SUCCESS;
8395 /* NB: G.global_argv[0] ($0) is never freed/changed */
8396 g_argv = G.global_argv;
8397 if (G.global_args_malloced) {
8403 G.global_args_malloced = 1;
8404 pp = xzalloc(sizeof(pp[0]) * 2);
8405 pp[0] = g_argv[0]; /* retain $0 */
8408 /* This realloc's G.global_argv */
8409 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8416 return EXIT_SUCCESS;
8418 /* Nothing known, so abort */
8420 bb_error_msg("set: %s: invalid option", arg);
8421 return EXIT_FAILURE;
8424 static int FAST_FUNC builtin_shift(char **argv)
8427 argv = skip_dash_dash(argv);
8431 if (n >= 0 && n < G.global_argc) {
8432 if (G.global_args_malloced) {
8435 free(G.global_argv[m++]);
8438 memmove(&G.global_argv[1], &G.global_argv[n+1],
8439 G.global_argc * sizeof(G.global_argv[0]));
8440 return EXIT_SUCCESS;
8442 return EXIT_FAILURE;
8445 static int FAST_FUNC builtin_source(char **argv)
8447 char *arg_path, *filename;
8450 #if ENABLE_HUSH_FUNCTIONS
8454 argv = skip_dash_dash(argv);
8457 /* bash says: "bash: .: filename argument required" */
8458 return 2; /* bash compat */
8461 if (!strchr(filename, '/')) {
8462 arg_path = find_in_path(filename);
8464 filename = arg_path;
8466 input = fopen_or_warn(filename, "r");
8469 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8470 return EXIT_FAILURE;
8472 close_on_exec_on(fileno(input));
8474 #if ENABLE_HUSH_FUNCTIONS
8475 sv_flg = G.flag_return_in_progress;
8476 /* "we are inside sourced file, ok to use return" */
8477 G.flag_return_in_progress = -1;
8479 save_and_replace_G_args(&sv, argv);
8481 parse_and_run_file(input);
8484 restore_G_args(&sv, argv);
8485 #if ENABLE_HUSH_FUNCTIONS
8486 G.flag_return_in_progress = sv_flg;
8489 return G.last_exitcode;
8492 static int FAST_FUNC builtin_umask(char **argv)
8498 argv = skip_dash_dash(argv);
8500 mode_t old_mask = mask;
8503 rc = bb_parse_mode(argv[0], &mask);
8508 * bash: umask: 'q': invalid symbolic mode operator
8509 * bash: umask: 999: octal number out of range
8511 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8516 printf("%04o\n", (unsigned) mask);
8517 /* fall through and restore mask which we set to 0 */
8521 return !rc; /* rc != 0 - success */
8524 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8525 static int FAST_FUNC builtin_unset(char **argv)
8530 /* "!": do not abort on errors */
8531 /* "+": stop at 1st non-option */
8532 opts = getopt32(argv, "!+vf");
8533 if (opts == (unsigned)-1)
8534 return EXIT_FAILURE;
8536 bb_error_msg("unset: -v and -f are exclusive");
8537 return EXIT_FAILURE;
8543 if (!(opts & 2)) { /* not -f */
8544 if (unset_local_var(*argv)) {
8545 /* unset <nonexistent_var> doesn't fail.
8546 * Error is when one tries to unset RO var.
8547 * Message was printed by unset_local_var. */
8551 #if ENABLE_HUSH_FUNCTIONS
8561 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8562 static int FAST_FUNC builtin_wait(char **argv)
8564 int ret = EXIT_SUCCESS;
8567 argv = skip_dash_dash(argv);
8568 if (argv[0] == NULL) {
8569 /* Don't care about wait results */
8570 /* Note 1: must wait until there are no more children */
8571 /* Note 2: must be interruptible */
8573 * $ sleep 3 & sleep 6 & wait
8578 * $ sleep 3 & sleep 6 & wait
8582 * ^C <-- after ~4 sec from keyboard
8585 sigaddset(&G.blocked_set, SIGCHLD);
8586 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8589 if (errno == ECHILD)
8591 /* Wait for SIGCHLD or any other signal of interest */
8592 /* sigtimedwait with infinite timeout: */
8593 sig = sigwaitinfo(&G.blocked_set, NULL);
8595 sig = check_and_run_traps(sig);
8596 if (sig && sig != SIGCHLD) { /* see note 2 */
8602 sigdelset(&G.blocked_set, SIGCHLD);
8603 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8607 /* This is probably buggy wrt interruptible-ness */
8609 pid_t pid = bb_strtou(*argv, NULL, 10);
8611 /* mimic bash message */
8612 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8613 return EXIT_FAILURE;
8615 if (waitpid(pid, &status, 0) == pid) {
8616 if (WIFSIGNALED(status))
8617 ret = 128 + WTERMSIG(status);
8618 else if (WIFEXITED(status))
8619 ret = WEXITSTATUS(status);
8623 bb_perror_msg("wait %s", *argv);
8632 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8633 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8636 def = bb_strtou(argv[1], NULL, 10);
8637 if (errno || def < def_min || argv[2]) {
8638 bb_error_msg("%s: bad arguments", argv[0]);
8646 #if ENABLE_HUSH_LOOPS
8647 static int FAST_FUNC builtin_break(char **argv)
8650 if (G.depth_of_loop == 0) {
8651 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8652 return EXIT_SUCCESS; /* bash compat */
8654 G.flag_break_continue++; /* BC_BREAK = 1 */
8656 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8657 if (depth == UINT_MAX)
8658 G.flag_break_continue = BC_BREAK;
8659 if (G.depth_of_loop < depth)
8660 G.depth_break_continue = G.depth_of_loop;
8662 return EXIT_SUCCESS;
8665 static int FAST_FUNC builtin_continue(char **argv)
8667 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8668 return builtin_break(argv);
8672 #if ENABLE_HUSH_FUNCTIONS
8673 static int FAST_FUNC builtin_return(char **argv)
8677 if (G.flag_return_in_progress != -1) {
8678 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8679 return EXIT_FAILURE; /* bash compat */
8682 G.flag_return_in_progress = 1;
8685 * out of range: wraps around at 256, does not error out
8686 * non-numeric param:
8687 * f() { false; return qwe; }; f; echo $?
8688 * bash: return: qwe: numeric argument required <== we do this
8689 * 255 <== we also do this
8691 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);