1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112 //config: bool "hush"
115 //config: hush is a small shell (25k). It handles the normal flow control
116 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117 //config: case/esac. Redirections, here documents, $((arithmetic))
118 //config: and functions are supported.
120 //config: It will compile and work on no-mmu systems.
122 //config: It does not handle select, aliases, brace expansion,
123 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
125 //config:config HUSH_BASH_COMPAT
126 //config: bool "bash-compatible extensions"
128 //config: depends on HUSH
130 //config: Enable bash-compatible extensions.
132 //config:config HUSH_BRACE_EXPANSION
133 //config: bool "Brace expansion"
135 //config: depends on HUSH_BASH_COMPAT
137 //config: Enable {abc,def} extension.
139 //config:config HUSH_HELP
140 //config: bool "help builtin"
142 //config: depends on HUSH
144 //config: Enable help builtin in hush. Code size + ~1 kbyte.
146 //config:config HUSH_INTERACTIVE
147 //config: bool "Interactive mode"
149 //config: depends on HUSH
151 //config: Enable interactive mode (prompt and command editing).
152 //config: Without this, hush simply reads and executes commands
153 //config: from stdin just like a shell script from a file.
154 //config: No prompt, no PS1/PS2 magic shell variables.
156 //config:config HUSH_SAVEHISTORY
157 //config: bool "Save command history to .hush_history"
159 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
161 //config: Enable history saving in hush.
163 //config:config HUSH_JOB
164 //config: bool "Job control"
166 //config: depends on HUSH_INTERACTIVE
168 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
169 //config: command (not entire shell), fg/bg builtins work. Without this option,
170 //config: "cmd &" still works by simply spawning a process and immediately
171 //config: prompting for next command (or executing next command in a script),
172 //config: but no separate process group is formed.
174 //config:config HUSH_TICK
175 //config: bool "Process substitution"
177 //config: depends on HUSH
179 //config: Enable process substitution `command` and $(command) in hush.
181 //config:config HUSH_IF
182 //config: bool "Support if/then/elif/else/fi"
184 //config: depends on HUSH
186 //config: Enable if/then/elif/else/fi in hush.
188 //config:config HUSH_LOOPS
189 //config: bool "Support for, while and until loops"
191 //config: depends on HUSH
193 //config: Enable for, while and until loops in hush.
195 //config:config HUSH_CASE
196 //config: bool "Support case ... esac statement"
198 //config: depends on HUSH
200 //config: Enable case ... esac statement in hush. +400 bytes.
202 //config:config HUSH_FUNCTIONS
203 //config: bool "Support funcname() { commands; } syntax"
205 //config: depends on HUSH
207 //config: Enable support for shell functions in hush. +800 bytes.
209 //config:config HUSH_LOCAL
210 //config: bool "Support local builtin"
212 //config: depends on HUSH_FUNCTIONS
214 //config: Enable support for local variables in functions.
216 //config:config HUSH_RANDOM_SUPPORT
217 //config: bool "Pseudorandom generator and $RANDOM variable"
219 //config: depends on HUSH
221 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
222 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
224 //config:config HUSH_EXPORT_N
225 //config: bool "Support 'export -n' option"
227 //config: depends on HUSH
229 //config: export -n unexports variables. It is a bash extension.
231 //config:config HUSH_MODE_X
232 //config: bool "Support 'hush -x' option and 'set -x' command"
234 //config: depends on HUSH
236 //config: This instructs hush to print commands before execution.
237 //config: Adds ~300 bytes.
240 //config: bool "msh (deprecated: aliased to hush)"
242 //config: select HUSH
244 //config: msh is deprecated and will be removed, please migrate to hush.
247 //usage:#define hush_trivial_usage NOUSAGE_STR
248 //usage:#define hush_full_usage ""
249 //usage:#define msh_trivial_usage NOUSAGE_STR
250 //usage:#define msh_full_usage ""
251 //usage:#define sh_trivial_usage NOUSAGE_STR
252 //usage:#define sh_full_usage ""
253 //usage:#define bash_trivial_usage NOUSAGE_STR
254 //usage:#define bash_full_usage ""
258 #define LEAK_HUNTING 0
259 #define BUILD_AS_NOMMU 0
260 /* Enable/disable sanity checks. Ok to enable in production,
261 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
262 * Keeping 1 for now even in released versions.
265 /* Slightly bigger (+200 bytes), but faster hush.
266 * So far it only enables a trick with counting SIGCHLDs and forks,
267 * which allows us to do fewer waitpid's.
268 * (we can detect a case where neither forks were done nor SIGCHLDs happened
269 * and therefore waitpid will return the same result as last time)
271 #define ENABLE_HUSH_FAST 0
272 /* TODO: implement simplified code for users which do not need ${var%...} ops
273 * So far ${var%...} ops are always enabled:
275 #define ENABLE_HUSH_DOLLAR_OPS 1
280 # undef USE_FOR_NOMMU
283 # define USE_FOR_NOMMU(...) __VA_ARGS__
284 # define USE_FOR_MMU(...)
287 #include "NUM_APPLETS.h"
289 /* STANDALONE does not make sense, and won't compile */
290 # undef CONFIG_FEATURE_SH_STANDALONE
291 # undef ENABLE_FEATURE_SH_STANDALONE
292 # undef IF_FEATURE_SH_STANDALONE
293 # undef IF_NOT_FEATURE_SH_STANDALONE
294 # define ENABLE_FEATURE_SH_STANDALONE 0
295 # define IF_FEATURE_SH_STANDALONE(...)
296 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
299 #if !ENABLE_HUSH_INTERACTIVE
300 # undef ENABLE_FEATURE_EDITING
301 # define ENABLE_FEATURE_EDITING 0
302 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
303 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
306 /* Do we support ANY keywords? */
307 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
308 # define HAS_KEYWORDS 1
309 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
310 # define IF_HAS_NO_KEYWORDS(...)
312 # define HAS_KEYWORDS 0
313 # define IF_HAS_KEYWORDS(...)
314 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
317 /* If you comment out one of these below, it will be #defined later
318 * to perform debug printfs to stderr: */
319 #define debug_printf(...) do {} while (0)
320 /* Finer-grained debug switches */
321 #define debug_printf_parse(...) do {} while (0)
322 #define debug_print_tree(a, b) do {} while (0)
323 #define debug_printf_exec(...) do {} while (0)
324 #define debug_printf_env(...) do {} while (0)
325 #define debug_printf_jobs(...) do {} while (0)
326 #define debug_printf_expand(...) do {} while (0)
327 #define debug_printf_varexp(...) do {} while (0)
328 #define debug_printf_glob(...) do {} while (0)
329 #define debug_printf_list(...) do {} while (0)
330 #define debug_printf_subst(...) do {} while (0)
331 #define debug_printf_clean(...) do {} while (0)
333 #define ERR_PTR ((void*)(long)1)
335 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
337 #define _SPECIAL_VARS_STR "_*@$!?#"
338 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
339 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
340 #if ENABLE_HUSH_BASH_COMPAT
341 /* Support / and // replace ops */
342 /* Note that // is stored as \ in "encoded" string representation */
343 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
344 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
345 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
347 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
348 # define VAR_SUBST_OPS "%#:-=+?"
349 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
352 #define SPECIAL_VAR_SYMBOL 3
356 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
358 /* This supports saving pointers malloced in vfork child,
359 * to be freed in the parent.
362 typedef struct nommu_save_t {
364 struct variable *old_vars;
366 char **argv_from_re_execing;
379 #if ENABLE_HUSH_LOOPS
386 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
391 /* three pseudo-keywords support contrived "case" syntax: */
392 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
393 RES_MATCH , /* "word)" */
394 RES_CASE_BODY, /* "this command is inside CASE" */
401 typedef struct o_string {
403 int length; /* position where data is appended */
406 /* At least some part of the string was inside '' or "",
407 * possibly empty one: word"", wo''rd etc. */
408 smallint has_quoted_part;
409 smallint has_empty_slot;
410 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
413 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
415 /* Protect newly added chars against globbing
416 * by prepending \ to *, ?, [, \ */
417 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
420 MAYBE_ASSIGNMENT = 0,
421 DEFINITELY_ASSIGNMENT = 1,
423 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
426 /* Used for initialization: o_string foo = NULL_O_STRING; */
427 #define NULL_O_STRING { NULL }
429 /* I can almost use ordinary FILE*. Is open_memstream() universally
430 * available? Where is it documented? */
431 typedef struct in_str {
433 /* eof_flag=1: last char in ->p is really an EOF */
434 char eof_flag; /* meaningless if ->p == NULL */
436 #if ENABLE_HUSH_INTERACTIVE
438 smallint promptmode; /* 0: PS1, 1: PS2 */
441 int (*get) (struct in_str *) FAST_FUNC;
442 int (*peek) (struct in_str *) FAST_FUNC;
444 #define i_getch(input) ((input)->get(input))
445 #define i_peek(input) ((input)->peek(input))
447 /* The descrip member of this structure is only used to make
448 * debugging output pretty */
449 static const struct {
451 signed char default_fd;
454 { O_RDONLY, 0, "<" },
455 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
456 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
457 { O_CREAT|O_RDWR, 1, "<>" },
458 { O_RDONLY, 0, "<<" },
459 /* Should not be needed. Bogus default_fd helps in debugging */
460 /* { O_RDONLY, 77, "<<" }, */
463 struct redir_struct {
464 struct redir_struct *next;
465 char *rd_filename; /* filename */
466 int rd_fd; /* fd to redirect */
467 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
469 smallint rd_type; /* (enum redir_type) */
470 /* note: for heredocs, rd_filename contains heredoc delimiter,
471 * and subsequently heredoc itself; and rd_dup is a bitmask:
472 * bit 0: do we need to trim leading tabs?
473 * bit 1: is heredoc quoted (<<'delim' syntax) ?
476 typedef enum redir_type {
478 REDIRECT_OVERWRITE = 1,
481 REDIRECT_HEREDOC = 4,
482 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
485 REDIRFD_SYNTAX_ERR = -2,
486 REDIRFD_TO_FILE = -1,
487 /* otherwise, rd_fd is redirected to rd_dup */
489 HEREDOC_SKIPTABS = 1,
495 pid_t pid; /* 0 if exited */
496 int assignment_cnt; /* how many argv[i] are assignments? */
497 smallint is_stopped; /* is the command currently running? */
498 smallint cmd_type; /* CMD_xxx */
500 #define CMD_SUBSHELL 1
501 #if ENABLE_HUSH_BASH_COMPAT
502 /* used for "[[ EXPR ]]" */
503 # define CMD_SINGLEWORD_NOGLOB 2
505 #if ENABLE_HUSH_FUNCTIONS
506 # define CMD_FUNCDEF 3
509 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
512 char *group_as_string;
514 #if ENABLE_HUSH_FUNCTIONS
515 struct function *child_func;
516 /* This field is used to prevent a bug here:
517 * while...do f1() {a;}; f1; f1() {b;}; f1; done
518 * When we execute "f1() {a;}" cmd, we create new function and clear
519 * cmd->group, cmd->group_as_string, cmd->argv[0].
520 * When we execute "f1() {b;}", we notice that f1 exists,
521 * and that its "parent cmd" struct is still "alive",
522 * we put those fields back into cmd->xxx
523 * (struct function has ->parent_cmd ptr to facilitate that).
524 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
525 * Without this trick, loop would execute a;b;b;b;...
526 * instead of correct sequence a;b;a;b;...
527 * When command is freed, it severs the link
528 * (sets ->child_func->parent_cmd to NULL).
531 char **argv; /* command name and arguments */
532 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
533 * and on execution these are substituted with their values.
534 * Substitution can make _several_ words out of one argv[n]!
535 * Example: argv[0]=='.^C*^C.' here: echo .$*.
536 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
538 struct redir_struct *redirects; /* I/O redirections */
540 /* Is there anything in this command at all? */
541 #define IS_NULL_CMD(cmd) \
542 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
547 int num_cmds; /* total number of commands in pipe */
548 int alive_cmds; /* number of commands running (not exited) */
549 int stopped_cmds; /* number of commands alive, but stopped */
551 int jobid; /* job number */
552 pid_t pgrp; /* process group ID for the job */
553 char *cmdtext; /* name of job */
555 struct command *cmds; /* array of commands in pipe */
556 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
557 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
558 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
560 typedef enum pipe_style {
566 /* Is there anything in this pipe at all? */
567 #define IS_NULL_PIPE(pi) \
568 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
570 /* This holds pointers to the various results of parsing */
571 struct parse_context {
572 /* linked list of pipes */
573 struct pipe *list_head;
574 /* last pipe (being constructed right now) */
576 /* last command in pipe (being constructed right now) */
577 struct command *command;
578 /* last redirect in command->redirects list */
579 struct redir_struct *pending_redirect;
585 smallint ctx_inverted; /* "! cmd | cmd" */
587 smallint ctx_dsemicolon; /* ";;" seen */
589 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
591 /* group we are enclosed in:
592 * example: "if pipe1; pipe2; then pipe3; fi"
593 * when we see "if" or "then", we malloc and copy current context,
594 * and make ->stack point to it. then we parse pipeN.
595 * when closing "then" / fi" / whatever is found,
596 * we move list_head into ->stack->command->group,
597 * copy ->stack into current context, and delete ->stack.
598 * (parsing of { list } and ( list ) doesn't use this method)
600 struct parse_context *stack;
604 /* On program start, environ points to initial environment.
605 * putenv adds new pointers into it, unsetenv removes them.
606 * Neither of these (de)allocates the strings.
607 * setenv allocates new strings in malloc space and does putenv,
608 * and thus setenv is unusable (leaky) for shell's purposes */
609 #define setenv(...) setenv_is_leaky_dont_use()
611 struct variable *next;
612 char *varstr; /* points to "name=" portion */
613 #if ENABLE_HUSH_LOCAL
614 unsigned func_nest_level;
616 int max_len; /* if > 0, name is part of initial env; else name is malloced */
617 smallint flg_export; /* putenv should be done on this var */
618 smallint flg_read_only;
626 #if ENABLE_HUSH_FUNCTIONS
628 struct function *next;
630 struct command *parent_cmd;
633 char *body_as_string;
639 /* "Globals" within this file */
640 /* Sorted roughly by size (smaller offsets == smaller code) */
642 /* interactive_fd != 0 means we are an interactive shell.
643 * If we are, then saved_tty_pgrp can also be != 0, meaning
644 * that controlling tty is available. With saved_tty_pgrp == 0,
645 * job control still works, but terminal signals
646 * (^C, ^Z, ^Y, ^\) won't work at all, and background
647 * process groups can only be created with "cmd &".
648 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
649 * to give tty to the foreground process group,
650 * and will take it back when the group is stopped (^Z)
653 #if ENABLE_HUSH_INTERACTIVE
654 /* 'interactive_fd' is a fd# open to ctty, if we have one
655 * _AND_ if we decided to act interactively */
659 # define G_interactive_fd (G.interactive_fd)
661 # define G_interactive_fd 0
663 #if ENABLE_FEATURE_EDITING
664 line_input_t *line_input_state;
669 #if ENABLE_HUSH_RANDOM_SUPPORT
675 pid_t saved_tty_pgrp;
676 struct pipe *job_list;
677 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
679 # define G_saved_tty_pgrp 0
681 smallint flag_SIGINT;
682 #if ENABLE_HUSH_LOOPS
683 smallint flag_break_continue;
685 #if ENABLE_HUSH_FUNCTIONS
686 /* 0: outside of a function (or sourced file)
687 * -1: inside of a function, ok to use return builtin
688 * 1: return is invoked, skip all till end of func
690 smallint flag_return_in_progress;
693 #if ENABLE_HUSH_MODE_X
695 # define G_x_mode (G.x_mode)
699 smallint exiting; /* used to prevent EXIT trap recursion */
700 /* These four support $?, $#, and $1 */
701 smalluint last_exitcode;
702 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
703 smalluint global_args_malloced;
704 smalluint inherited_set_is_saved;
705 /* how many non-NULL argv's we have. NB: $# + 1 */
709 char *argv0_for_re_execing;
711 #if ENABLE_HUSH_LOOPS
712 unsigned depth_break_continue;
713 unsigned depth_of_loop;
717 struct variable *top_var;
718 char **expanded_assignments;
719 #if ENABLE_HUSH_FUNCTIONS
720 struct function *top_func;
721 # if ENABLE_HUSH_LOCAL
722 struct variable **shadowed_vars_pp;
723 unsigned func_nest_level;
726 /* Signal and trap handling */
728 unsigned count_SIGCHLD;
729 unsigned handled_SIGCHLD;
730 smallint we_have_children;
732 /* which signals have non-DFL handler (even with no traps set)? */
733 unsigned non_DFL_mask;
734 char **traps; /* char *traps[NSIG] */
735 sigset_t blocked_set;
736 sigset_t inherited_set;
738 unsigned long memleak_value;
741 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
743 #define G (*ptr_to_globals)
744 /* Not #defining name to G.name - this quickly gets unwieldy
745 * (too many defines). Also, I actually prefer to see when a variable
746 * is global, thus "G." prefix is a useful hint */
747 #define INIT_G() do { \
748 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
752 /* Function prototypes for builtins */
753 static int builtin_cd(char **argv) FAST_FUNC;
754 static int builtin_echo(char **argv) FAST_FUNC;
755 static int builtin_eval(char **argv) FAST_FUNC;
756 static int builtin_exec(char **argv) FAST_FUNC;
757 static int builtin_exit(char **argv) FAST_FUNC;
758 static int builtin_export(char **argv) FAST_FUNC;
760 static int builtin_fg_bg(char **argv) FAST_FUNC;
761 static int builtin_jobs(char **argv) FAST_FUNC;
764 static int builtin_help(char **argv) FAST_FUNC;
766 #if ENABLE_HUSH_LOCAL
767 static int builtin_local(char **argv) FAST_FUNC;
770 static int builtin_memleak(char **argv) FAST_FUNC;
773 static int builtin_printf(char **argv) FAST_FUNC;
775 static int builtin_pwd(char **argv) FAST_FUNC;
776 static int builtin_read(char **argv) FAST_FUNC;
777 static int builtin_set(char **argv) FAST_FUNC;
778 static int builtin_shift(char **argv) FAST_FUNC;
779 static int builtin_source(char **argv) FAST_FUNC;
780 static int builtin_test(char **argv) FAST_FUNC;
781 static int builtin_trap(char **argv) FAST_FUNC;
782 static int builtin_type(char **argv) FAST_FUNC;
783 static int builtin_true(char **argv) FAST_FUNC;
784 static int builtin_umask(char **argv) FAST_FUNC;
785 static int builtin_unset(char **argv) FAST_FUNC;
786 static int builtin_wait(char **argv) FAST_FUNC;
787 #if ENABLE_HUSH_LOOPS
788 static int builtin_break(char **argv) FAST_FUNC;
789 static int builtin_continue(char **argv) FAST_FUNC;
791 #if ENABLE_HUSH_FUNCTIONS
792 static int builtin_return(char **argv) FAST_FUNC;
795 /* Table of built-in functions. They can be forked or not, depending on
796 * context: within pipes, they fork. As simple commands, they do not.
797 * When used in non-forking context, they can change global variables
798 * in the parent shell process. If forked, of course they cannot.
799 * For example, 'unset foo | whatever' will parse and run, but foo will
800 * still be set at the end. */
801 struct built_in_command {
803 int (*b_function)(char **argv) FAST_FUNC;
806 # define BLTIN(cmd, func, help) { cmd, func, help }
808 # define BLTIN(cmd, func, help) { cmd, func }
812 static const struct built_in_command bltins1[] = {
813 BLTIN("." , builtin_source , "Run commands in a file"),
814 BLTIN(":" , builtin_true , NULL),
816 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
818 #if ENABLE_HUSH_LOOPS
819 BLTIN("break" , builtin_break , "Exit from a loop"),
821 BLTIN("cd" , builtin_cd , "Change directory"),
822 #if ENABLE_HUSH_LOOPS
823 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
825 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
826 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
827 BLTIN("exit" , builtin_exit , "Exit"),
828 BLTIN("export" , builtin_export , "Set environment variables"),
830 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
833 BLTIN("help" , builtin_help , NULL),
836 BLTIN("jobs" , builtin_jobs , "List jobs"),
838 #if ENABLE_HUSH_LOCAL
839 BLTIN("local" , builtin_local , "Set local variables"),
842 BLTIN("memleak" , builtin_memleak , NULL),
844 BLTIN("read" , builtin_read , "Input into variable"),
845 #if ENABLE_HUSH_FUNCTIONS
846 BLTIN("return" , builtin_return , "Return from a function"),
848 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
849 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
850 #if ENABLE_HUSH_BASH_COMPAT
851 BLTIN("source" , builtin_source , "Run commands in a file"),
853 BLTIN("trap" , builtin_trap , "Trap signals"),
854 BLTIN("type" , builtin_type , "Show command type"),
855 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
856 BLTIN("umask" , builtin_umask , "Set file creation mask"),
857 BLTIN("unset" , builtin_unset , "Unset variables"),
858 BLTIN("wait" , builtin_wait , "Wait for process"),
860 /* For now, echo and test are unconditionally enabled.
861 * Maybe make it configurable? */
862 static const struct built_in_command bltins2[] = {
863 BLTIN("[" , builtin_test , NULL),
864 BLTIN("echo" , builtin_echo , NULL),
866 BLTIN("printf" , builtin_printf , NULL),
868 BLTIN("pwd" , builtin_pwd , NULL),
869 BLTIN("test" , builtin_test , NULL),
876 /* prevent disasters with G.debug_indent < 0 */
877 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
878 # define debug_enter() (G.debug_indent++)
879 # define debug_leave() (G.debug_indent--)
881 # define indent() ((void)0)
882 # define debug_enter() ((void)0)
883 # define debug_leave() ((void)0)
887 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
890 #ifndef debug_printf_parse
891 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
894 #ifndef debug_printf_exec
895 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
898 #ifndef debug_printf_env
899 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
902 #ifndef debug_printf_jobs
903 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
904 # define DEBUG_JOBS 1
906 # define DEBUG_JOBS 0
909 #ifndef debug_printf_expand
910 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
911 # define DEBUG_EXPAND 1
913 # define DEBUG_EXPAND 0
916 #ifndef debug_printf_varexp
917 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 #ifndef debug_printf_glob
921 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
922 # define DEBUG_GLOB 1
924 # define DEBUG_GLOB 0
927 #ifndef debug_printf_list
928 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
931 #ifndef debug_printf_subst
932 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
935 #ifndef debug_printf_clean
936 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
937 # define DEBUG_CLEAN 1
939 # define DEBUG_CLEAN 0
943 static void debug_print_strings(const char *prefix, char **vv)
946 fprintf(stderr, "%s:\n", prefix);
948 fprintf(stderr, " '%s'\n", *vv++);
951 # define debug_print_strings(prefix, vv) ((void)0)
955 /* Leak hunting. Use hush_leaktool.sh for post-processing.
958 static void *xxmalloc(int lineno, size_t size)
960 void *ptr = xmalloc((size + 0xff) & ~0xff);
961 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
964 static void *xxrealloc(int lineno, void *ptr, size_t size)
966 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
967 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
970 static char *xxstrdup(int lineno, const char *str)
972 char *ptr = xstrdup(str);
973 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
976 static void xxfree(void *ptr)
978 fdprintf(2, "free %p\n", ptr);
981 # define xmalloc(s) xxmalloc(__LINE__, s)
982 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
983 # define xstrdup(s) xxstrdup(__LINE__, s)
984 # define free(p) xxfree(p)
988 /* Syntax and runtime errors. They always abort scripts.
989 * In interactive use they usually discard unparsed and/or unexecuted commands
990 * and return to the prompt.
991 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
994 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
995 # define syntax_error(lineno, msg) syntax_error(msg)
996 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
997 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
998 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
999 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1002 static void die_if_script(unsigned lineno, const char *fmt, ...)
1007 bb_error_msg("hush.c:%u", lineno);
1010 bb_verror_msg(fmt, p, NULL);
1012 if (!G_interactive_fd)
1016 static void syntax_error(unsigned lineno, const char *msg)
1019 die_if_script(lineno, "syntax error: %s", msg);
1021 die_if_script(lineno, "syntax error", NULL);
1024 static void syntax_error_at(unsigned lineno, const char *msg)
1026 die_if_script(lineno, "syntax error at '%s'", msg);
1029 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1031 die_if_script(lineno, "syntax error: unterminated %s", s);
1034 /* It so happens that all such cases are totally fatal
1035 * even if shell is interactive: EOF while looking for closing
1036 * delimiter. There is nowhere to read stuff from after that,
1037 * it's EOF! The only choice is to terminate.
1039 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1040 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1042 char msg[2] = { ch, '\0' };
1043 syntax_error_unterm_str(lineno, msg);
1047 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1052 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1056 # undef die_if_script
1057 # undef syntax_error
1058 # undef syntax_error_at
1059 # undef syntax_error_unterm_ch
1060 # undef syntax_error_unterm_str
1061 # undef syntax_error_unexpected_ch
1063 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1064 # define syntax_error(msg) syntax_error(__LINE__, msg)
1065 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1066 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1067 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1068 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1072 #if ENABLE_HUSH_INTERACTIVE
1073 static void cmdedit_update_prompt(void);
1075 # define cmdedit_update_prompt() ((void)0)
1079 /* Utility functions
1081 /* Replace each \x with x in place, return ptr past NUL. */
1082 static char *unbackslash(char *src)
1084 char *dst = src = strchrnul(src, '\\');
1088 if ((*dst++ = *src++) == '\0')
1094 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1115 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1116 v[count1 + count2] = NULL;
1119 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1123 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1125 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1126 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1129 #define add_strings_to_strings(strings, add, need_to_dup) \
1130 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1133 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1134 static char **add_string_to_strings(char **strings, char *add)
1139 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1142 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1144 char **ptr = add_string_to_strings(strings, add);
1145 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1148 #define add_string_to_strings(strings, add) \
1149 xx_add_string_to_strings(__LINE__, strings, add)
1152 static void free_strings(char **strings)
1167 /* Helpers for setting new $n and restoring them back
1169 typedef struct save_arg_t {
1173 smallint sv_g_malloced;
1176 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1180 sv->sv_argv0 = argv[0];
1181 sv->sv_g_argv = G.global_argv;
1182 sv->sv_g_argc = G.global_argc;
1183 sv->sv_g_malloced = G.global_args_malloced;
1185 argv[0] = G.global_argv[0]; /* retain $0 */
1186 G.global_argv = argv;
1187 G.global_args_malloced = 0;
1195 static void restore_G_args(save_arg_t *sv, char **argv)
1199 if (G.global_args_malloced) {
1200 /* someone ran "set -- arg1 arg2 ...", undo */
1202 while (*++pp) /* note: does not free $0 */
1204 free(G.global_argv);
1206 argv[0] = sv->sv_argv0;
1207 G.global_argv = sv->sv_g_argv;
1208 G.global_argc = sv->sv_g_argc;
1209 G.global_args_malloced = sv->sv_g_malloced;
1213 /* Basic theory of signal handling in shell
1214 * ========================================
1215 * This does not describe what hush does, rather, it is current understanding
1216 * what it _should_ do. If it doesn't, it's a bug.
1217 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1219 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1220 * is finished or backgrounded. It is the same in interactive and
1221 * non-interactive shells, and is the same regardless of whether
1222 * a user trap handler is installed or a shell special one is in effect.
1223 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1224 * backgrounds (i.e. stops) or kills all members of currently running
1227 * Wait builtin in interruptible by signals for which user trap is set
1228 * or by SIGINT in interactive shell.
1230 * Trap handlers will execute even within trap handlers. (right?)
1232 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1233 * except for handlers set to '' (empty string).
1235 * If job control is off, backgrounded commands ("cmd &")
1236 * have SIGINT, SIGQUIT set to SIG_IGN.
1238 * Commands which are run in command substitution ("`cmd`")
1239 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1241 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1242 * by the shell from its parent.
1244 * Signals which differ from SIG_DFL action
1245 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1248 * SIGTERM (interactive): ignore
1249 * SIGHUP (interactive):
1250 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1251 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1252 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1253 * that all pipe members are stopped. Try this in bash:
1254 * while :; do :; done - ^Z does not background it
1255 * (while :; do :; done) - ^Z backgrounds it
1256 * SIGINT (interactive): wait for last pipe, ignore the rest
1257 * of the command line, show prompt. NB: ^C does not send SIGINT
1258 * to interactive shell while shell is waiting for a pipe,
1259 * since shell is bg'ed (is not in foreground process group).
1260 * Example 1: this waits 5 sec, but does not execute ls:
1261 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1262 * Example 2: this does not wait and does not execute ls:
1263 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1264 * Example 3: this does not wait 5 sec, but executes ls:
1265 * "sleep 5; ls -l" + press ^C
1267 * (What happens to signals which are IGN on shell start?)
1268 * (What happens with signal mask on shell start?)
1270 * Implementation in hush
1271 * ======================
1272 * We use in-kernel pending signal mask to determine which signals were sent.
1273 * We block all signals which we don't want to take action immediately,
1274 * i.e. we block all signals which need to have special handling as described
1275 * above, and all signals which have traps set.
1276 * After each pipe execution, we extract any pending signals via sigtimedwait()
1279 * unsigned non_DFL_mask: a mask of such "special" signals
1280 * sigset_t blocked_set: current blocked signal set
1283 * clear bit in blocked_set unless it is also in non_DFL_mask
1284 * "trap 'cmd' SIGxxx":
1285 * set bit in blocked_set (even if 'cmd' is '')
1286 * after [v]fork, if we plan to be a shell:
1287 * unblock signals with special interactive handling
1288 * (child shell is not interactive),
1289 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1290 * after [v]fork, if we plan to exec:
1291 * POSIX says fork clears pending signal mask in child - no need to clear it.
1292 * Restore blocked signal set to one inherited by shell just prior to exec.
1294 * Note: as a result, we do not use signal handlers much. The only uses
1295 * are to count SIGCHLDs
1296 * and to restore tty pgrp on signal-induced exit.
1299 * Standard says "When a subshell is entered, traps that are not being ignored
1300 * are set to the default actions". bash interprets it so that traps which
1301 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1304 SPECIAL_INTERACTIVE_SIGS = 0
1309 SPECIAL_JOB_SIGS = 0
1317 #if ENABLE_HUSH_FAST
1318 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1321 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1327 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1328 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1329 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1330 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1332 /* Restores tty foreground process group, and exits.
1333 * May be called as signal handler for fatal signal
1334 * (will resend signal to itself, producing correct exit state)
1335 * or called directly with -EXITCODE.
1336 * We also call it if xfunc is exiting. */
1337 static void sigexit(int sig) NORETURN;
1338 static void sigexit(int sig)
1340 /* Disable all signals: job control, SIGPIPE, etc. */
1341 sigprocmask_allsigs(SIG_BLOCK);
1343 /* Careful: we can end up here after [v]fork. Do not restore
1344 * tty pgrp then, only top-level shell process does that */
1345 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1346 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1348 /* Not a signal, just exit */
1352 kill_myself_with_sig(sig); /* does not return */
1356 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1357 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1361 /* Restores tty foreground process group, and exits. */
1362 static void hush_exit(int exitcode) NORETURN;
1363 static void hush_exit(int exitcode)
1365 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1366 /* Prevent recursion:
1367 * trap "echo Hi; exit" EXIT; exit
1370 /* argv[0] is unused */
1371 argv[1] = G.traps[0];
1373 G.exiting = 1; /* prevent EXIT trap recursion */
1374 /* Note: G.traps[0] is not cleared!
1375 * "trap" will still show it, if executed
1382 sigexit(- (exitcode & 0xff));
1389 static int check_and_run_traps(int sig)
1391 /* I want it in rodata, not in bss.
1392 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1393 * initializer. But other compilers may still use bss.
1394 * TODO: find more portable solution.
1396 static const struct timespec zero_timespec = { 0, 0 };
1397 smalluint save_rcode;
1403 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1408 if (G.traps && G.traps[sig]) {
1409 if (G.traps[sig][0]) {
1410 /* We have user-defined handler */
1412 /* argv[0] is unused */
1413 argv[1] = G.traps[sig];
1415 save_rcode = G.last_exitcode;
1417 G.last_exitcode = save_rcode;
1418 } /* else: "" trap, ignoring signal */
1421 /* not a trap: special action */
1423 #if ENABLE_HUSH_FAST
1426 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1430 /* Builtin was ^C'ed, make it look prettier: */
1437 /* bash is observed to signal whole process groups,
1438 * not individual processes */
1439 for (job = G.job_list; job; job = job->next) {
1442 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1443 if (kill(- job->pgrp, SIGHUP) == 0)
1444 kill(- job->pgrp, SIGCONT);
1449 default: /* ignored: */
1450 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1458 static const char *get_cwd(int force)
1460 if (force || G.cwd == NULL) {
1461 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1462 * we must not try to free(bb_msg_unknown) */
1463 if (G.cwd == bb_msg_unknown)
1465 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1467 G.cwd = bb_msg_unknown;
1474 * Shell and environment variable support
1476 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1478 struct variable **pp;
1479 struct variable *cur;
1482 while ((cur = *pp) != NULL) {
1483 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1490 static const char* FAST_FUNC get_local_var_value(const char *name)
1492 struct variable **vpp;
1493 unsigned len = strlen(name);
1495 if (G.expanded_assignments) {
1496 char **cpp = G.expanded_assignments;
1499 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1500 return cp + len + 1;
1505 vpp = get_ptr_to_local_var(name, len);
1507 return (*vpp)->varstr + len + 1;
1509 if (strcmp(name, "PPID") == 0)
1510 return utoa(G.root_ppid);
1511 // bash compat: UID? EUID?
1512 #if ENABLE_HUSH_RANDOM_SUPPORT
1513 if (strcmp(name, "RANDOM") == 0)
1514 return utoa(next_random(&G.random_gen));
1519 /* str holds "NAME=VAL" and is expected to be malloced.
1520 * We take ownership of it.
1522 * 0: do not change export flag
1523 * (if creating new variable, flag will be 0)
1524 * 1: set export flag and putenv the variable
1525 * -1: clear export flag and unsetenv the variable
1526 * flg_read_only is set only when we handle -R var=val
1528 #if !BB_MMU && ENABLE_HUSH_LOCAL
1529 /* all params are used */
1530 #elif BB_MMU && ENABLE_HUSH_LOCAL
1531 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export, local_lvl)
1533 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1534 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1535 set_local_var(str, flg_export)
1536 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1537 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1538 set_local_var(str, flg_export, flg_read_only)
1540 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1542 struct variable **var_pp;
1543 struct variable *cur;
1547 eq_sign = strchr(str, '=');
1548 if (!eq_sign) { /* not expected to ever happen? */
1553 name_len = eq_sign - str + 1; /* including '=' */
1554 var_pp = &G.top_var;
1555 while ((cur = *var_pp) != NULL) {
1556 if (strncmp(cur->varstr, str, name_len) != 0) {
1557 var_pp = &cur->next;
1560 /* We found an existing var with this name */
1561 if (cur->flg_read_only) {
1565 bb_error_msg("%s: readonly variable", str);
1569 if (flg_export == -1) { // "&& cur->flg_export" ?
1570 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1575 #if ENABLE_HUSH_LOCAL
1576 if (cur->func_nest_level < local_lvl) {
1577 /* New variable is declared as local,
1578 * and existing one is global, or local
1579 * from enclosing function.
1580 * Remove and save old one: */
1581 *var_pp = cur->next;
1582 cur->next = *G.shadowed_vars_pp;
1583 *G.shadowed_vars_pp = cur;
1584 /* bash 3.2.33(1) and exported vars:
1586 * # f() { local z=a; env | grep ^z; }
1592 if (cur->flg_export)
1597 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1602 if (cur->max_len != 0) {
1603 if (cur->max_len >= strlen(str)) {
1604 /* This one is from startup env, reuse space */
1605 strcpy(cur->varstr, str);
1609 /* max_len == 0 signifies "malloced" var, which we can
1610 * (and has to) free */
1614 goto set_str_and_exp;
1617 /* Not found - create new variable struct */
1618 cur = xzalloc(sizeof(*cur));
1619 #if ENABLE_HUSH_LOCAL
1620 cur->func_nest_level = local_lvl;
1622 cur->next = *var_pp;
1628 cur->flg_read_only = flg_read_only;
1631 if (flg_export == 1)
1632 cur->flg_export = 1;
1633 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1634 cmdedit_update_prompt();
1635 if (cur->flg_export) {
1636 if (flg_export == -1) {
1637 cur->flg_export = 0;
1638 /* unsetenv was already done */
1640 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1641 return putenv(cur->varstr);
1647 /* Used at startup and after each cd */
1648 static void set_pwd_var(int exp)
1650 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1651 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1654 static int unset_local_var_len(const char *name, int name_len)
1656 struct variable *cur;
1657 struct variable **var_pp;
1660 return EXIT_SUCCESS;
1661 var_pp = &G.top_var;
1662 while ((cur = *var_pp) != NULL) {
1663 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1664 if (cur->flg_read_only) {
1665 bb_error_msg("%s: readonly variable", name);
1666 return EXIT_FAILURE;
1668 *var_pp = cur->next;
1669 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1670 bb_unsetenv(cur->varstr);
1671 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1672 cmdedit_update_prompt();
1676 return EXIT_SUCCESS;
1678 var_pp = &cur->next;
1680 return EXIT_SUCCESS;
1683 static int unset_local_var(const char *name)
1685 return unset_local_var_len(name, strlen(name));
1688 static void unset_vars(char **strings)
1696 const char *eq = strchrnul(*v, '=');
1697 unset_local_var_len(*v, (int)(eq - *v));
1703 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1705 char *var = xasprintf("%s=%s", name, val);
1706 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1711 * Helpers for "var1=val1 var2=val2 cmd" feature
1713 static void add_vars(struct variable *var)
1715 struct variable *next;
1719 var->next = G.top_var;
1721 if (var->flg_export) {
1722 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1723 putenv(var->varstr);
1725 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1731 static struct variable *set_vars_and_save_old(char **strings)
1734 struct variable *old = NULL;
1740 struct variable *var_p;
1741 struct variable **var_pp;
1744 eq = strchr(*s, '=');
1746 var_pp = get_ptr_to_local_var(*s, eq - *s);
1748 /* Remove variable from global linked list */
1750 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1751 *var_pp = var_p->next;
1752 /* Add it to returned list */
1756 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1767 static int FAST_FUNC static_get(struct in_str *i)
1777 static int FAST_FUNC static_peek(struct in_str *i)
1782 #if ENABLE_HUSH_INTERACTIVE
1784 static void cmdedit_update_prompt(void)
1786 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1787 G.PS1 = get_local_var_value("PS1");
1790 G.PS2 = get_local_var_value("PS2");
1798 static const char *setup_prompt_string(int promptmode)
1800 const char *prompt_str;
1801 debug_printf("setup_prompt_string %d ", promptmode);
1802 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1803 /* Set up the prompt */
1804 if (promptmode == 0) { /* PS1 */
1806 /* bash uses $PWD value, even if it is set by user.
1807 * It uses current dir only if PWD is unset.
1808 * We always use current dir. */
1809 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1814 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1815 debug_printf("result '%s'\n", prompt_str);
1819 static void get_user_input(struct in_str *i)
1822 const char *prompt_str;
1824 prompt_str = setup_prompt_string(i->promptmode);
1825 # if ENABLE_FEATURE_EDITING
1826 /* Enable command line editing only while a command line
1827 * is actually being read */
1830 /* buglet: SIGINT will not make new prompt to appear _at once_,
1831 * only after <Enter>. (^C will work) */
1832 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1833 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1834 check_and_run_traps(0);
1835 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1836 i->eof_flag = (r < 0);
1837 if (i->eof_flag) { /* EOF/error detected */
1838 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1839 G.user_input_buf[1] = '\0';
1844 fputs(prompt_str, stdout);
1846 G.user_input_buf[0] = r = fgetc(i->file);
1847 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1848 //do we need check_and_run_traps(0)? (maybe only if stdin)
1849 } while (G.flag_SIGINT);
1850 i->eof_flag = (r == EOF);
1852 i->p = G.user_input_buf;
1855 #endif /* INTERACTIVE */
1857 /* This is the magic location that prints prompts
1858 * and gets data back from the user */
1859 static int FAST_FUNC file_get(struct in_str *i)
1863 /* If there is data waiting, eat it up */
1864 if (i->p && *i->p) {
1865 #if ENABLE_HUSH_INTERACTIVE
1869 if (i->eof_flag && !*i->p)
1871 /* note: ch is never NUL */
1873 /* need to double check i->file because we might be doing something
1874 * more complicated by now, like sourcing or substituting. */
1875 #if ENABLE_HUSH_INTERACTIVE
1876 if (G_interactive_fd && i->promptme && i->file == stdin) {
1879 } while (!*i->p); /* need non-empty line */
1880 i->promptmode = 1; /* PS2 */
1885 do ch = fgetc(i->file); while (ch == '\0');
1887 debug_printf("file_get: got '%c' %d\n", ch, ch);
1888 #if ENABLE_HUSH_INTERACTIVE
1895 /* All callers guarantee this routine will never
1896 * be used right after a newline, so prompting is not needed.
1898 static int FAST_FUNC file_peek(struct in_str *i)
1901 if (i->p && *i->p) {
1902 if (i->eof_flag && !i->p[1])
1905 /* note: ch is never NUL */
1907 do ch = fgetc(i->file); while (ch == '\0');
1908 i->eof_flag = (ch == EOF);
1909 i->peek_buf[0] = ch;
1910 i->peek_buf[1] = '\0';
1912 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1916 static void setup_file_in_str(struct in_str *i, FILE *f)
1918 i->peek = file_peek;
1920 #if ENABLE_HUSH_INTERACTIVE
1922 i->promptmode = 0; /* PS1 */
1928 static void setup_string_in_str(struct in_str *i, const char *s)
1930 i->peek = static_peek;
1931 i->get = static_get;
1932 #if ENABLE_HUSH_INTERACTIVE
1934 i->promptmode = 0; /* PS1 */
1944 #define B_CHUNK (32 * sizeof(char*))
1946 static void o_reset_to_empty_unquoted(o_string *o)
1949 o->has_quoted_part = 0;
1954 static void o_free(o_string *o)
1957 memset(o, 0, sizeof(*o));
1960 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1965 static void o_grow_by(o_string *o, int len)
1967 if (o->length + len > o->maxlen) {
1968 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1969 o->data = xrealloc(o->data, 1 + o->maxlen);
1973 static void o_addchr(o_string *o, int ch)
1975 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1977 o->data[o->length] = ch;
1979 o->data[o->length] = '\0';
1982 static void o_addblock(o_string *o, const char *str, int len)
1985 memcpy(&o->data[o->length], str, len);
1987 o->data[o->length] = '\0';
1990 static void o_addstr(o_string *o, const char *str)
1992 o_addblock(o, str, strlen(str));
1996 static void nommu_addchr(o_string *o, int ch)
2002 # define nommu_addchr(o, str) ((void)0)
2005 static void o_addstr_with_NUL(o_string *o, const char *str)
2007 o_addblock(o, str, strlen(str) + 1);
2011 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2012 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2013 * Apparently, on unquoted $v bash still does globbing
2014 * ("v='*.txt'; echo $v" prints all .txt files),
2015 * but NOT brace expansion! Thus, there should be TWO independent
2016 * quoting mechanisms on $v expansion side: one protects
2017 * $v from brace expansion, and other additionally protects "$v" against globbing.
2018 * We have only second one.
2021 #if ENABLE_HUSH_BRACE_EXPANSION
2022 # define MAYBE_BRACES "{}"
2024 # define MAYBE_BRACES ""
2027 /* My analysis of quoting semantics tells me that state information
2028 * is associated with a destination, not a source.
2030 static void o_addqchr(o_string *o, int ch)
2033 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2038 o->data[o->length] = '\\';
2041 o->data[o->length] = ch;
2043 o->data[o->length] = '\0';
2046 static void o_addQchr(o_string *o, int ch)
2049 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2050 && strchr("*?[\\" MAYBE_BRACES, ch)
2053 o->data[o->length] = '\\';
2057 o->data[o->length] = ch;
2059 o->data[o->length] = '\0';
2062 static void o_addqblock(o_string *o, const char *str, int len)
2067 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2068 if (ordinary_cnt > len) /* paranoia */
2070 o_addblock(o, str, ordinary_cnt);
2071 if (ordinary_cnt == len)
2073 str += ordinary_cnt;
2074 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2078 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2080 o->data[o->length] = '\\';
2084 o->data[o->length] = ch;
2086 o->data[o->length] = '\0';
2090 static void o_addQblock(o_string *o, const char *str, int len)
2092 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2093 o_addblock(o, str, len);
2096 o_addqblock(o, str, len);
2099 static void o_addQstr(o_string *o, const char *str)
2101 o_addQblock(o, str, strlen(str));
2104 /* A special kind of o_string for $VAR and `cmd` expansion.
2105 * It contains char* list[] at the beginning, which is grown in 16 element
2106 * increments. Actual string data starts at the next multiple of 16 * (char*).
2107 * list[i] contains an INDEX (int!) into this string data.
2108 * It means that if list[] needs to grow, data needs to be moved higher up
2109 * but list[i]'s need not be modified.
2110 * NB: remembering how many list[i]'s you have there is crucial.
2111 * o_finalize_list() operation post-processes this structure - calculates
2112 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2114 #if DEBUG_EXPAND || DEBUG_GLOB
2115 static void debug_print_list(const char *prefix, o_string *o, int n)
2117 char **list = (char**)o->data;
2118 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2122 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2123 prefix, list, n, string_start, o->length, o->maxlen,
2124 !!(o->o_expflags & EXP_FLAG_GLOB),
2126 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2129 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2130 o->data + (int)list[i] + string_start,
2131 o->data + (int)list[i] + string_start);
2135 const char *p = o->data + (int)list[n - 1] + string_start;
2137 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2141 # define debug_print_list(prefix, o, n) ((void)0)
2144 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2145 * in list[n] so that it points past last stored byte so far.
2146 * It returns n+1. */
2147 static int o_save_ptr_helper(o_string *o, int n)
2149 char **list = (char**)o->data;
2153 if (!o->has_empty_slot) {
2154 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2155 string_len = o->length - string_start;
2156 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2157 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2158 /* list[n] points to string_start, make space for 16 more pointers */
2159 o->maxlen += 0x10 * sizeof(list[0]);
2160 o->data = xrealloc(o->data, o->maxlen + 1);
2161 list = (char**)o->data;
2162 memmove(list + n + 0x10, list + n, string_len);
2163 o->length += 0x10 * sizeof(list[0]);
2165 debug_printf_list("list[%d]=%d string_start=%d\n",
2166 n, string_len, string_start);
2169 /* We have empty slot at list[n], reuse without growth */
2170 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2171 string_len = o->length - string_start;
2172 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2173 n, string_len, string_start);
2174 o->has_empty_slot = 0;
2176 list[n] = (char*)(uintptr_t)string_len;
2180 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2181 static int o_get_last_ptr(o_string *o, int n)
2183 char **list = (char**)o->data;
2184 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2186 return ((int)(uintptr_t)list[n-1]) + string_start;
2189 #if ENABLE_HUSH_BRACE_EXPANSION
2190 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2191 * first, it processes even {a} (no commas), second,
2192 * I didn't manage to make it return strings when they don't match
2193 * existing files. Need to re-implement it.
2197 static int glob_needed(const char *s)
2206 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2212 /* Return pointer to next closing brace or to comma */
2213 static const char *next_brace_sub(const char *cp)
2217 while (*cp != '\0') {
2224 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2230 return *cp != '\0' ? cp : NULL;
2232 /* Recursive brace globber. Note: may garble pattern[]. */
2233 static int glob_brace(char *pattern, o_string *o, int n)
2235 char *new_pattern_buf;
2242 debug_printf_glob("glob_brace('%s')\n", pattern);
2248 if (*begin == '{') {
2249 /* Find the first sub-pattern and at the same time
2250 * find the rest after the closing brace */
2251 next = next_brace_sub(begin);
2253 /* An illegal expression */
2257 /* "{abc}" with no commas - illegal
2258 * brace expr, disregard and skip it */
2264 if (*begin == '\\' && begin[1] != '\0')
2268 debug_printf_glob("begin:%s\n", begin);
2269 debug_printf_glob("next:%s\n", next);
2271 /* Now find the end of the whole brace expression */
2273 while (*rest != '}') {
2274 rest = next_brace_sub(rest);
2276 /* An illegal expression */
2279 debug_printf_glob("rest:%s\n", rest);
2281 rest_len = strlen(++rest) + 1;
2283 /* We are sure the brace expression is well-formed */
2285 /* Allocate working buffer large enough for our work */
2286 new_pattern_buf = xmalloc(strlen(pattern));
2288 /* We have a brace expression. BEGIN points to the opening {,
2289 * NEXT points past the terminator of the first element, and REST
2290 * points past the final }. We will accumulate result names from
2291 * recursive runs for each brace alternative in the buffer using
2296 /* Construct the new glob expression */
2299 mempcpy(new_pattern_buf,
2300 /* We know the prefix for all sub-patterns */
2301 pattern, begin - pattern),
2305 /* Note: glob_brace() may garble new_pattern_buf[].
2306 * That's why we re-copy prefix every time (1st memcpy above).
2308 n = glob_brace(new_pattern_buf, o, n);
2310 /* We saw the last entry */
2314 next = next_brace_sub(next);
2316 free(new_pattern_buf);
2324 memset(&globdata, 0, sizeof(globdata));
2325 gr = glob(pattern, 0, NULL, &globdata);
2326 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2328 if (gr == GLOB_NOMATCH) {
2329 globfree(&globdata);
2330 /* NB: garbles parameter */
2331 unbackslash(pattern);
2332 o_addstr_with_NUL(o, pattern);
2333 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2334 return o_save_ptr_helper(o, n);
2336 if (gr == GLOB_NOSPACE)
2337 bb_error_msg_and_die(bb_msg_memory_exhausted);
2338 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2339 * but we didn't specify it. Paranoia again. */
2340 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2342 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2343 char **argv = globdata.gl_pathv;
2345 o_addstr_with_NUL(o, *argv);
2346 n = o_save_ptr_helper(o, n);
2352 globfree(&globdata);
2356 /* Performs globbing on last list[],
2357 * saving each result as a new list[].
2359 static int perform_glob(o_string *o, int n)
2361 char *pattern, *copy;
2363 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2365 return o_save_ptr_helper(o, n);
2366 pattern = o->data + o_get_last_ptr(o, n);
2367 debug_printf_glob("glob pattern '%s'\n", pattern);
2368 if (!glob_needed(pattern)) {
2369 /* unbackslash last string in o in place, fix length */
2370 o->length = unbackslash(pattern) - o->data;
2371 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2372 return o_save_ptr_helper(o, n);
2375 copy = xstrdup(pattern);
2376 /* "forget" pattern in o */
2377 o->length = pattern - o->data;
2378 n = glob_brace(copy, o, n);
2381 debug_print_list("perform_glob returning", o, n);
2385 #else /* !HUSH_BRACE_EXPANSION */
2388 static int glob_needed(const char *s)
2397 if (*s == '*' || *s == '[' || *s == '?')
2403 /* Performs globbing on last list[],
2404 * saving each result as a new list[].
2406 static int perform_glob(o_string *o, int n)
2412 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2414 return o_save_ptr_helper(o, n);
2415 pattern = o->data + o_get_last_ptr(o, n);
2416 debug_printf_glob("glob pattern '%s'\n", pattern);
2417 if (!glob_needed(pattern)) {
2419 /* unbackslash last string in o in place, fix length */
2420 o->length = unbackslash(pattern) - o->data;
2421 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2422 return o_save_ptr_helper(o, n);
2425 memset(&globdata, 0, sizeof(globdata));
2426 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2427 * If we glob "*.\*" and don't find anything, we need
2428 * to fall back to using literal "*.*", but GLOB_NOCHECK
2429 * will return "*.\*"!
2431 gr = glob(pattern, 0, NULL, &globdata);
2432 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2434 if (gr == GLOB_NOMATCH) {
2435 globfree(&globdata);
2438 if (gr == GLOB_NOSPACE)
2439 bb_error_msg_and_die(bb_msg_memory_exhausted);
2440 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2441 * but we didn't specify it. Paranoia again. */
2442 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2444 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2445 char **argv = globdata.gl_pathv;
2446 /* "forget" pattern in o */
2447 o->length = pattern - o->data;
2449 o_addstr_with_NUL(o, *argv);
2450 n = o_save_ptr_helper(o, n);
2456 globfree(&globdata);
2458 debug_print_list("perform_glob returning", o, n);
2462 #endif /* !HUSH_BRACE_EXPANSION */
2464 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2465 * Otherwise, just finish current list[] and start new */
2466 static int o_save_ptr(o_string *o, int n)
2468 if (o->o_expflags & EXP_FLAG_GLOB) {
2469 /* If o->has_empty_slot, list[n] was already globbed
2470 * (if it was requested back then when it was filled)
2471 * so don't do that again! */
2472 if (!o->has_empty_slot)
2473 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2475 return o_save_ptr_helper(o, n);
2478 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2479 static char **o_finalize_list(o_string *o, int n)
2484 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2486 debug_print_list("finalized", o, n);
2487 debug_printf_expand("finalized n:%d\n", n);
2488 list = (char**)o->data;
2489 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2493 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2498 static void free_pipe_list(struct pipe *pi);
2500 /* Returns pi->next - next pipe in the list */
2501 static struct pipe *free_pipe(struct pipe *pi)
2506 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2507 for (i = 0; i < pi->num_cmds; i++) {
2508 struct command *command;
2509 struct redir_struct *r, *rnext;
2511 command = &pi->cmds[i];
2512 debug_printf_clean(" command %d:\n", i);
2513 if (command->argv) {
2517 for (a = 0, p = command->argv; *p; a++, p++) {
2518 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2521 free_strings(command->argv);
2522 //command->argv = NULL;
2524 /* not "else if": on syntax error, we may have both! */
2525 if (command->group) {
2526 debug_printf_clean(" begin group (cmd_type:%d)\n",
2528 free_pipe_list(command->group);
2529 debug_printf_clean(" end group\n");
2530 //command->group = NULL;
2532 /* else is crucial here.
2533 * If group != NULL, child_func is meaningless */
2534 #if ENABLE_HUSH_FUNCTIONS
2535 else if (command->child_func) {
2536 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2537 command->child_func->parent_cmd = NULL;
2541 free(command->group_as_string);
2542 //command->group_as_string = NULL;
2544 for (r = command->redirects; r; r = rnext) {
2545 debug_printf_clean(" redirect %d%s",
2546 r->rd_fd, redir_table[r->rd_type].descrip);
2547 /* guard against the case >$FOO, where foo is unset or blank */
2548 if (r->rd_filename) {
2549 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2550 free(r->rd_filename);
2551 //r->rd_filename = NULL;
2553 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2557 //command->redirects = NULL;
2559 free(pi->cmds); /* children are an array, they get freed all at once */
2563 //pi->cmdtext = NULL;
2571 static void free_pipe_list(struct pipe *pi)
2575 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2577 debug_printf_clean("pipe followup code %d\n", pi->followup);
2583 /*** Parsing routines ***/
2585 static struct pipe *new_pipe(void)
2588 pi = xzalloc(sizeof(struct pipe));
2589 /*pi->followup = 0; - deliberately invalid value */
2590 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2594 /* Command (member of a pipe) is complete, or we start a new pipe
2595 * if ctx->command is NULL.
2596 * No errors possible here.
2598 static int done_command(struct parse_context *ctx)
2600 /* The command is really already in the pipe structure, so
2601 * advance the pipe counter and make a new, null command. */
2602 struct pipe *pi = ctx->pipe;
2603 struct command *command = ctx->command;
2606 if (IS_NULL_CMD(command)) {
2607 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2611 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2612 //debug_print_tree(ctx->list_head, 20);
2614 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2617 /* Only real trickiness here is that the uncommitted
2618 * command structure is not counted in pi->num_cmds. */
2619 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2620 ctx->command = command = &pi->cmds[pi->num_cmds];
2622 memset(command, 0, sizeof(*command));
2623 return pi->num_cmds; /* used only for 0/nonzero check */
2626 static void done_pipe(struct parse_context *ctx, pipe_style type)
2630 debug_printf_parse("done_pipe entered, followup %d\n", type);
2631 /* Close previous command */
2632 not_null = done_command(ctx);
2633 ctx->pipe->followup = type;
2635 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2636 ctx->ctx_inverted = 0;
2637 ctx->pipe->res_word = ctx->ctx_res_w;
2640 /* Without this check, even just <enter> on command line generates
2641 * tree of three NOPs (!). Which is harmless but annoying.
2642 * IOW: it is safe to do it unconditionally. */
2645 || ctx->ctx_res_w == RES_FI
2647 #if ENABLE_HUSH_LOOPS
2648 || ctx->ctx_res_w == RES_DONE
2649 || ctx->ctx_res_w == RES_FOR
2650 || ctx->ctx_res_w == RES_IN
2652 #if ENABLE_HUSH_CASE
2653 || ctx->ctx_res_w == RES_ESAC
2657 debug_printf_parse("done_pipe: adding new pipe: "
2658 "not_null:%d ctx->ctx_res_w:%d\n",
2659 not_null, ctx->ctx_res_w);
2661 ctx->pipe->next = new_p;
2663 /* RES_THEN, RES_DO etc are "sticky" -
2664 * they remain set for pipes inside if/while.
2665 * This is used to control execution.
2666 * RES_FOR and RES_IN are NOT sticky (needed to support
2667 * cases where variable or value happens to match a keyword):
2669 #if ENABLE_HUSH_LOOPS
2670 if (ctx->ctx_res_w == RES_FOR
2671 || ctx->ctx_res_w == RES_IN)
2672 ctx->ctx_res_w = RES_NONE;
2674 #if ENABLE_HUSH_CASE
2675 if (ctx->ctx_res_w == RES_MATCH)
2676 ctx->ctx_res_w = RES_CASE_BODY;
2677 if (ctx->ctx_res_w == RES_CASE)
2678 ctx->ctx_res_w = RES_CASE_IN;
2680 ctx->command = NULL; /* trick done_command below */
2681 /* Create the memory for command, roughly:
2682 * ctx->pipe->cmds = new struct command;
2683 * ctx->command = &ctx->pipe->cmds[0];
2686 //debug_print_tree(ctx->list_head, 10);
2688 debug_printf_parse("done_pipe return\n");
2691 static void initialize_context(struct parse_context *ctx)
2693 memset(ctx, 0, sizeof(*ctx));
2694 ctx->pipe = ctx->list_head = new_pipe();
2695 /* Create the memory for command, roughly:
2696 * ctx->pipe->cmds = new struct command;
2697 * ctx->command = &ctx->pipe->cmds[0];
2702 /* If a reserved word is found and processed, parse context is modified
2703 * and 1 is returned.
2706 struct reserved_combo {
2709 unsigned char assignment_flag;
2713 FLAG_END = (1 << RES_NONE ),
2715 FLAG_IF = (1 << RES_IF ),
2716 FLAG_THEN = (1 << RES_THEN ),
2717 FLAG_ELIF = (1 << RES_ELIF ),
2718 FLAG_ELSE = (1 << RES_ELSE ),
2719 FLAG_FI = (1 << RES_FI ),
2721 # if ENABLE_HUSH_LOOPS
2722 FLAG_FOR = (1 << RES_FOR ),
2723 FLAG_WHILE = (1 << RES_WHILE),
2724 FLAG_UNTIL = (1 << RES_UNTIL),
2725 FLAG_DO = (1 << RES_DO ),
2726 FLAG_DONE = (1 << RES_DONE ),
2727 FLAG_IN = (1 << RES_IN ),
2729 # if ENABLE_HUSH_CASE
2730 FLAG_MATCH = (1 << RES_MATCH),
2731 FLAG_ESAC = (1 << RES_ESAC ),
2733 FLAG_START = (1 << RES_XXXX ),
2736 static const struct reserved_combo* match_reserved_word(o_string *word)
2738 /* Mostly a list of accepted follow-up reserved words.
2739 * FLAG_END means we are done with the sequence, and are ready
2740 * to turn the compound list into a command.
2741 * FLAG_START means the word must start a new compound list.
2743 static const struct reserved_combo reserved_list[] = {
2745 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2746 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2747 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2748 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2749 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2750 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2752 # if ENABLE_HUSH_LOOPS
2753 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2754 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2755 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2756 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2757 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2758 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2760 # if ENABLE_HUSH_CASE
2761 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2762 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2765 const struct reserved_combo *r;
2767 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2768 if (strcmp(word->data, r->literal) == 0)
2773 /* Return 0: not a keyword, 1: keyword
2775 static int reserved_word(o_string *word, struct parse_context *ctx)
2777 # if ENABLE_HUSH_CASE
2778 static const struct reserved_combo reserved_match = {
2779 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2782 const struct reserved_combo *r;
2784 if (word->has_quoted_part)
2786 r = match_reserved_word(word);
2790 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2791 # if ENABLE_HUSH_CASE
2792 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2793 /* "case word IN ..." - IN part starts first MATCH part */
2794 r = &reserved_match;
2797 if (r->flag == 0) { /* '!' */
2798 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2799 syntax_error("! ! command");
2800 ctx->ctx_res_w = RES_SNTX;
2802 ctx->ctx_inverted = 1;
2805 if (r->flag & FLAG_START) {
2806 struct parse_context *old;
2808 old = xmalloc(sizeof(*old));
2809 debug_printf_parse("push stack %p\n", old);
2810 *old = *ctx; /* physical copy */
2811 initialize_context(ctx);
2813 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2814 syntax_error_at(word->data);
2815 ctx->ctx_res_w = RES_SNTX;
2818 /* "{...} fi" is ok. "{...} if" is not
2820 * if { echo foo; } then { echo bar; } fi */
2821 if (ctx->command->group)
2822 done_pipe(ctx, PIPE_SEQ);
2825 ctx->ctx_res_w = r->res;
2826 ctx->old_flag = r->flag;
2827 word->o_assignment = r->assignment_flag;
2829 if (ctx->old_flag & FLAG_END) {
2830 struct parse_context *old;
2832 done_pipe(ctx, PIPE_SEQ);
2833 debug_printf_parse("pop stack %p\n", ctx->stack);
2835 old->command->group = ctx->list_head;
2836 old->command->cmd_type = CMD_NORMAL;
2838 o_addstr(&old->as_string, ctx->as_string.data);
2839 o_free_unsafe(&ctx->as_string);
2840 old->command->group_as_string = xstrdup(old->as_string.data);
2841 debug_printf_parse("pop, remembering as:'%s'\n",
2842 old->command->group_as_string);
2844 *ctx = *old; /* physical copy */
2849 #endif /* HAS_KEYWORDS */
2851 /* Word is complete, look at it and update parsing context.
2852 * Normal return is 0. Syntax errors return 1.
2853 * Note: on return, word is reset, but not o_free'd!
2855 static int done_word(o_string *word, struct parse_context *ctx)
2857 struct command *command = ctx->command;
2859 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2860 if (word->length == 0 && !word->has_quoted_part) {
2861 debug_printf_parse("done_word return 0: true null, ignored\n");
2865 if (ctx->pending_redirect) {
2866 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2867 * only if run as "bash", not "sh" */
2868 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2870 * ...the word that follows the redirection operator
2871 * shall be subjected to tilde expansion, parameter expansion,
2872 * command substitution, arithmetic expansion, and quote
2873 * removal. Pathname expansion shall not be performed
2874 * on the word by a non-interactive shell; an interactive
2875 * shell may perform it, but shall do so only when
2876 * the expansion would result in one word."
2878 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2879 /* Cater for >\file case:
2880 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2881 * Same with heredocs:
2882 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2884 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2885 unbackslash(ctx->pending_redirect->rd_filename);
2886 /* Is it <<"HEREDOC"? */
2887 if (word->has_quoted_part) {
2888 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2891 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2892 ctx->pending_redirect = NULL;
2894 /* If this word wasn't an assignment, next ones definitely
2895 * can't be assignments. Even if they look like ones. */
2896 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2897 && word->o_assignment != WORD_IS_KEYWORD
2899 word->o_assignment = NOT_ASSIGNMENT;
2901 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2902 command->assignment_cnt++;
2903 word->o_assignment = MAYBE_ASSIGNMENT;
2907 # if ENABLE_HUSH_CASE
2908 if (ctx->ctx_dsemicolon
2909 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2911 /* already done when ctx_dsemicolon was set to 1: */
2912 /* ctx->ctx_res_w = RES_MATCH; */
2913 ctx->ctx_dsemicolon = 0;
2916 if (!command->argv /* if it's the first word... */
2917 # if ENABLE_HUSH_LOOPS
2918 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2919 && ctx->ctx_res_w != RES_IN
2921 # if ENABLE_HUSH_CASE
2922 && ctx->ctx_res_w != RES_CASE
2925 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2926 if (reserved_word(word, ctx)) {
2927 o_reset_to_empty_unquoted(word);
2928 debug_printf_parse("done_word return %d\n",
2929 (ctx->ctx_res_w == RES_SNTX));
2930 return (ctx->ctx_res_w == RES_SNTX);
2932 # if ENABLE_HUSH_BASH_COMPAT
2933 if (strcmp(word->data, "[[") == 0) {
2934 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2940 if (command->group) {
2941 /* "{ echo foo; } echo bar" - bad */
2942 syntax_error_at(word->data);
2943 debug_printf_parse("done_word return 1: syntax error, "
2944 "groups and arglists don't mix\n");
2947 if (word->has_quoted_part
2948 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2949 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2950 /* (otherwise it's known to be not empty and is already safe) */
2952 /* exclude "$@" - it can expand to no word despite "" */
2953 char *p = word->data;
2954 while (p[0] == SPECIAL_VAR_SYMBOL
2955 && (p[1] & 0x7f) == '@'
2956 && p[2] == SPECIAL_VAR_SYMBOL
2960 if (p == word->data || p[0] != '\0') {
2961 /* saw no "$@", or not only "$@" but some
2962 * real text is there too */
2963 /* insert "empty variable" reference, this makes
2964 * e.g. "", $empty"" etc to not disappear */
2965 o_addchr(word, SPECIAL_VAR_SYMBOL);
2966 o_addchr(word, SPECIAL_VAR_SYMBOL);
2969 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2970 debug_print_strings("word appended to argv", command->argv);
2973 #if ENABLE_HUSH_LOOPS
2974 if (ctx->ctx_res_w == RES_FOR) {
2975 if (word->has_quoted_part
2976 || !is_well_formed_var_name(command->argv[0], '\0')
2978 /* bash says just "not a valid identifier" */
2979 syntax_error("not a valid identifier in for");
2982 /* Force FOR to have just one word (variable name) */
2983 /* NB: basically, this makes hush see "for v in ..."
2984 * syntax as if it is "for v; in ...". FOR and IN become
2985 * two pipe structs in parse tree. */
2986 done_pipe(ctx, PIPE_SEQ);
2989 #if ENABLE_HUSH_CASE
2990 /* Force CASE to have just one word */
2991 if (ctx->ctx_res_w == RES_CASE) {
2992 done_pipe(ctx, PIPE_SEQ);
2996 o_reset_to_empty_unquoted(word);
2998 debug_printf_parse("done_word return 0\n");
3003 /* Peek ahead in the input to find out if we have a "&n" construct,
3004 * as in "2>&1", that represents duplicating a file descriptor.
3006 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3007 * REDIRFD_SYNTAX_ERR if syntax error,
3008 * REDIRFD_TO_FILE if no & was seen,
3009 * or the number found.
3012 #define parse_redir_right_fd(as_string, input) \
3013 parse_redir_right_fd(input)
3015 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3021 return REDIRFD_TO_FILE;
3023 ch = i_getch(input); /* get the & */
3024 nommu_addchr(as_string, ch);
3027 ch = i_getch(input);
3028 nommu_addchr(as_string, ch);
3029 return REDIRFD_CLOSE;
3033 while (ch != EOF && isdigit(ch)) {
3034 d = d*10 + (ch-'0');
3036 ch = i_getch(input);
3037 nommu_addchr(as_string, ch);
3042 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3044 bb_error_msg("ambiguous redirect");
3045 return REDIRFD_SYNTAX_ERR;
3048 /* Return code is 0 normal, 1 if a syntax error is detected
3050 static int parse_redirect(struct parse_context *ctx,
3053 struct in_str *input)
3055 struct command *command = ctx->command;
3056 struct redir_struct *redir;
3057 struct redir_struct **redirp;
3060 dup_num = REDIRFD_TO_FILE;
3061 if (style != REDIRECT_HEREDOC) {
3062 /* Check for a '>&1' type redirect */
3063 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3064 if (dup_num == REDIRFD_SYNTAX_ERR)
3067 int ch = i_peek(input);
3068 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3069 if (dup_num) { /* <<-... */
3070 ch = i_getch(input);
3071 nommu_addchr(&ctx->as_string, ch);
3076 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3077 int ch = i_peek(input);
3079 /* >|FILE redirect ("clobbering" >).
3080 * Since we do not support "set -o noclobber" yet,
3081 * >| and > are the same for now. Just eat |.
3083 ch = i_getch(input);
3084 nommu_addchr(&ctx->as_string, ch);
3088 /* Create a new redir_struct and append it to the linked list */
3089 redirp = &command->redirects;
3090 while ((redir = *redirp) != NULL) {
3091 redirp = &(redir->next);
3093 *redirp = redir = xzalloc(sizeof(*redir));
3094 /* redir->next = NULL; */
3095 /* redir->rd_filename = NULL; */
3096 redir->rd_type = style;
3097 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3099 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3100 redir_table[style].descrip);
3102 redir->rd_dup = dup_num;
3103 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3104 /* Erik had a check here that the file descriptor in question
3105 * is legit; I postpone that to "run time"
3106 * A "-" representation of "close me" shows up as a -3 here */
3107 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3108 redir->rd_fd, redir->rd_dup);
3110 /* Set ctx->pending_redirect, so we know what to do at the
3111 * end of the next parsed word. */
3112 ctx->pending_redirect = redir;
3117 /* If a redirect is immediately preceded by a number, that number is
3118 * supposed to tell which file descriptor to redirect. This routine
3119 * looks for such preceding numbers. In an ideal world this routine
3120 * needs to handle all the following classes of redirects...
3121 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3122 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3123 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3124 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3126 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3128 * ... If n is quoted, the number shall not be recognized as part of
3129 * the redirection expression. For example:
3131 * writes the character 2 into file a"
3132 * We are getting it right by setting ->has_quoted_part on any \<char>
3134 * A -1 return means no valid number was found,
3135 * the caller should use the appropriate default for this redirection.
3137 static int redirect_opt_num(o_string *o)
3141 if (o->data == NULL)
3143 num = bb_strtou(o->data, NULL, 10);
3144 if (errno || num < 0)
3146 o_reset_to_empty_unquoted(o);
3151 #define fetch_till_str(as_string, input, word, skip_tabs) \
3152 fetch_till_str(input, word, skip_tabs)
3154 static char *fetch_till_str(o_string *as_string,
3155 struct in_str *input,
3159 o_string heredoc = NULL_O_STRING;
3161 int prev = 0; /* not \ */
3166 ch = i_getch(input);
3168 nommu_addchr(as_string, ch);
3169 if ((ch == '\n' || ch == EOF)
3170 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3172 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3173 heredoc.data[past_EOL] = '\0';
3174 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3175 return heredoc.data;
3177 while (ch == '\n') {
3178 o_addchr(&heredoc, ch);
3181 past_EOL = heredoc.length;
3183 ch = i_getch(input);
3185 nommu_addchr(as_string, ch);
3186 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3190 o_free_unsafe(&heredoc);
3193 o_addchr(&heredoc, ch);
3194 nommu_addchr(as_string, ch);
3195 if (prev == '\\' && ch == '\\')
3196 /* Correctly handle foo\\<eol> (not a line cont.) */
3197 prev = 0; /* not \ */
3203 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3204 * and load them all. There should be exactly heredoc_cnt of them.
3206 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3208 struct pipe *pi = ctx->list_head;
3210 while (pi && heredoc_cnt) {
3212 struct command *cmd = pi->cmds;
3214 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3216 cmd->argv ? cmd->argv[0] : "NONE");
3217 for (i = 0; i < pi->num_cmds; i++) {
3218 struct redir_struct *redir = cmd->redirects;
3220 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3221 i, cmd->argv ? cmd->argv[0] : "NONE");
3223 if (redir->rd_type == REDIRECT_HEREDOC) {
3226 redir->rd_type = REDIRECT_HEREDOC2;
3227 /* redir->rd_dup is (ab)used to indicate <<- */
3228 p = fetch_till_str(&ctx->as_string, input,
3229 redir->rd_filename, redir->rd_dup);
3231 syntax_error("unexpected EOF in here document");
3234 free(redir->rd_filename);
3235 redir->rd_filename = p;
3238 redir = redir->next;
3245 /* Should be 0. If it isn't, it's a parse error */
3247 bb_error_msg_and_die("heredoc BUG 2");
3253 static int run_list(struct pipe *pi);
3255 #define parse_stream(pstring, input, end_trigger) \
3256 parse_stream(input, end_trigger)
3258 static struct pipe *parse_stream(char **pstring,
3259 struct in_str *input,
3263 #if !ENABLE_HUSH_FUNCTIONS
3264 #define parse_group(dest, ctx, input, ch) \
3265 parse_group(ctx, input, ch)
3267 static int parse_group(o_string *dest, struct parse_context *ctx,
3268 struct in_str *input, int ch)
3270 /* dest contains characters seen prior to ( or {.
3271 * Typically it's empty, but for function defs,
3272 * it contains function name (without '()'). */
3273 struct pipe *pipe_list;
3275 struct command *command = ctx->command;
3277 debug_printf_parse("parse_group entered\n");
3278 #if ENABLE_HUSH_FUNCTIONS
3279 if (ch == '(' && !dest->has_quoted_part) {
3281 if (done_word(dest, ctx))
3284 goto skip; /* (... */
3285 if (command->argv[1]) { /* word word ... (... */
3286 syntax_error_unexpected_ch('(');
3289 /* it is "word(..." or "word (..." */
3291 ch = i_getch(input);
3292 while (ch == ' ' || ch == '\t');
3294 syntax_error_unexpected_ch(ch);
3297 nommu_addchr(&ctx->as_string, ch);
3299 ch = i_getch(input);
3300 while (ch == ' ' || ch == '\t' || ch == '\n');
3302 syntax_error_unexpected_ch(ch);
3305 nommu_addchr(&ctx->as_string, ch);
3306 command->cmd_type = CMD_FUNCDEF;
3311 #if 0 /* Prevented by caller */
3312 if (command->argv /* word [word]{... */
3313 || dest->length /* word{... */
3314 || dest->has_quoted_part /* ""{... */
3317 debug_printf_parse("parse_group return 1: "
3318 "syntax error, groups and arglists don't mix\n");
3323 #if ENABLE_HUSH_FUNCTIONS
3329 command->cmd_type = CMD_SUBSHELL;
3331 /* bash does not allow "{echo...", requires whitespace */
3332 ch = i_getch(input);
3333 if (ch != ' ' && ch != '\t' && ch != '\n') {
3334 syntax_error_unexpected_ch(ch);
3337 nommu_addchr(&ctx->as_string, ch);
3342 # define as_string NULL
3344 char *as_string = NULL;
3346 pipe_list = parse_stream(&as_string, input, endch);
3349 o_addstr(&ctx->as_string, as_string);
3351 /* empty ()/{} or parse error? */
3352 if (!pipe_list || pipe_list == ERR_PTR) {
3353 /* parse_stream already emitted error msg */
3356 debug_printf_parse("parse_group return 1: "
3357 "parse_stream returned %p\n", pipe_list);
3360 command->group = pipe_list;
3362 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3363 command->group_as_string = as_string;
3364 debug_printf_parse("end of group, remembering as:'%s'\n",
3365 command->group_as_string);
3369 debug_printf_parse("parse_group return 0\n");
3371 /* command remains "open", available for possible redirects */
3374 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3375 /* Subroutines for copying $(...) and `...` things */
3376 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3378 static void add_till_single_quote(o_string *dest, struct in_str *input)
3381 int ch = i_getch(input);
3383 syntax_error_unterm_ch('\'');
3384 /*xfunc_die(); - redundant */
3391 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3392 static void add_till_double_quote(o_string *dest, struct in_str *input)
3395 int ch = i_getch(input);
3397 syntax_error_unterm_ch('"');
3398 /*xfunc_die(); - redundant */
3402 if (ch == '\\') { /* \x. Copy both chars. */
3404 ch = i_getch(input);
3408 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3412 //if (ch == '$') ...
3415 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3417 * "Within the backquoted style of command substitution, backslash
3418 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3419 * The search for the matching backquote shall be satisfied by the first
3420 * backquote found without a preceding backslash; during this search,
3421 * if a non-escaped backquote is encountered within a shell comment,
3422 * a here-document, an embedded command substitution of the $(command)
3423 * form, or a quoted string, undefined results occur. A single-quoted
3424 * or double-quoted string that begins, but does not end, within the
3425 * "`...`" sequence produces undefined results."
3427 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3429 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3432 int ch = i_getch(input);
3436 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3437 ch = i_getch(input);
3441 && (!in_dquote || ch != '"')
3443 o_addchr(dest, '\\');
3447 syntax_error_unterm_ch('`');
3448 /*xfunc_die(); - redundant */
3453 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3454 * quoting and nested ()s.
3455 * "With the $(command) style of command substitution, all characters
3456 * following the open parenthesis to the matching closing parenthesis
3457 * constitute the command. Any valid shell script can be used for command,
3458 * except a script consisting solely of redirections which produces
3459 * unspecified results."
3461 * echo $(echo '(TEST)' BEST) (TEST) BEST
3462 * echo $(echo 'TEST)' BEST) TEST) BEST
3463 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3465 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3466 * can contain arbitrary constructs, just like $(cmd).
3467 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3468 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3470 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3471 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3474 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3475 # if ENABLE_HUSH_BASH_COMPAT
3476 char end_char2 = end_ch >> 8;
3478 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3481 ch = i_getch(input);
3483 syntax_error_unterm_ch(end_ch);
3484 /*xfunc_die(); - redundant */
3486 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3489 /* we look for closing )) of $((EXPR)) */
3490 if (i_peek(input) == end_ch) {
3491 i_getch(input); /* eat second ')' */
3496 if (ch == '(' || ch == '{') {
3497 ch = (ch == '(' ? ')' : '}');
3498 add_till_closing_bracket(dest, input, ch);
3503 add_till_single_quote(dest, input);
3508 add_till_double_quote(dest, input);
3513 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3518 /* \x. Copy verbatim. Important for \(, \) */
3519 ch = i_getch(input);
3521 syntax_error_unterm_ch(')');
3522 /*xfunc_die(); - redundant */
3530 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3532 /* Return code: 0 for OK, 1 for syntax error */
3534 #define parse_dollar(as_string, dest, input, quote_mask) \
3535 parse_dollar(dest, input, quote_mask)
3536 #define as_string NULL
3538 static int parse_dollar(o_string *as_string,
3540 struct in_str *input, unsigned char quote_mask)
3542 int ch = i_peek(input); /* first character after the $ */
3544 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3546 ch = i_getch(input);
3547 nommu_addchr(as_string, ch);
3549 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3551 debug_printf_parse(": '%c'\n", ch);
3552 o_addchr(dest, ch | quote_mask);
3555 if (!isalnum(ch) && ch != '_')
3557 ch = i_getch(input);
3558 nommu_addchr(as_string, ch);
3560 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3561 } else if (isdigit(ch)) {
3563 ch = i_getch(input);
3564 nommu_addchr(as_string, ch);
3565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3566 debug_printf_parse(": '%c'\n", ch);
3567 o_addchr(dest, ch | quote_mask);
3568 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3569 } else switch (ch) {
3571 case '!': /* last bg pid */
3572 case '?': /* last exit code */
3573 case '#': /* number of args */
3574 case '*': /* args */
3575 case '@': /* args */
3576 goto make_one_char_var;
3578 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3580 ch = i_getch(input); /* eat '{' */
3581 nommu_addchr(as_string, ch);
3583 ch = i_getch(input); /* first char after '{' */
3584 /* It should be ${?}, or ${#var},
3585 * or even ${?+subst} - operator acting on a special variable,
3586 * or the beginning of variable name.
3589 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3592 syntax_error_unterm_str("${name}");
3593 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3596 nommu_addchr(as_string, ch);
3599 /* It's possible to just call add_till_closing_bracket() at this point.
3600 * However, this regresses some of our testsuite cases
3601 * which check invalid constructs like ${%}.
3602 * Oh well... let's check that the var name part is fine... */
3608 debug_printf_parse(": '%c'\n", ch);
3610 ch = i_getch(input);
3611 nommu_addchr(as_string, ch);
3615 if (!isalnum(ch) && ch != '_') {
3617 unsigned char last_ch;
3618 /* handle parameter expansions
3619 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3621 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3622 goto bad_dollar_syntax;
3624 /* Eat everything until closing '}' (or ':') */
3626 if (ENABLE_HUSH_BASH_COMPAT
3628 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3630 /* It's ${var:N[:M]} thing */
3631 end_ch = '}' * 0x100 + ':';
3633 if (ENABLE_HUSH_BASH_COMPAT
3636 /* It's ${var/[/]pattern[/repl]} thing */
3637 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3639 nommu_addchr(as_string, '/');
3642 end_ch = '}' * 0x100 + '/';
3648 #if ENABLE_HUSH_DOLLAR_OPS
3649 last_ch = add_till_closing_bracket(dest, input, end_ch);
3651 #error Simple code to only allow ${var} is not implemented
3654 o_addstr(as_string, dest->data + pos);
3655 o_addchr(as_string, last_ch);
3658 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3659 /* close the first block: */
3660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3661 /* while parsing N from ${var:N[:M]}
3662 * or pattern from ${var/[/]pattern[/repl]} */
3663 if ((end_ch & 0xff) == last_ch) {
3664 /* got ':' or '/'- parse the rest */
3669 if (end_ch == '}' * 0x100 + ':') {
3670 /* it's ${var:N} - emulate :999999999 */
3671 o_addstr(dest, "999999999");
3672 } /* else: it's ${var/[/]pattern} */
3677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3680 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3684 ch = i_getch(input);
3685 nommu_addchr(as_string, ch);
3686 # if ENABLE_SH_MATH_SUPPORT
3687 if (i_peek(input) == '(') {
3688 ch = i_getch(input);
3689 nommu_addchr(as_string, ch);
3690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691 o_addchr(dest, /*quote_mask |*/ '+');
3694 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3696 o_addstr(as_string, dest->data + pos);
3697 o_addchr(as_string, ')');
3698 o_addchr(as_string, ')');
3700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3704 # if ENABLE_HUSH_TICK
3705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3706 o_addchr(dest, quote_mask | '`');
3709 add_till_closing_bracket(dest, input, ')');
3711 o_addstr(as_string, dest->data + pos);
3712 o_addchr(as_string, ')');
3714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720 ch = i_getch(input);
3721 nommu_addchr(as_string, ch);
3723 if (isalnum(ch)) { /* it's $_name or $_123 */
3728 /* TODO: $_ and $-: */
3729 /* $_ Shell or shell script name; or last argument of last command
3730 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3731 * but in command's env, set to full pathname used to invoke it */
3732 /* $- Option flags set by set builtin or shell options (-i etc) */
3734 o_addQchr(dest, '$');
3736 debug_printf_parse("parse_dollar return 0\n");
3742 # if ENABLE_HUSH_BASH_COMPAT
3743 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3744 encode_string(dest, input, dquote_end, process_bkslash)
3746 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3747 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3748 encode_string(dest, input, dquote_end)
3750 #define as_string NULL
3754 # if ENABLE_HUSH_BASH_COMPAT
3755 /* all parameters are needed, no macro tricks */
3757 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3758 encode_string(as_string, dest, input, dquote_end)
3761 static int encode_string(o_string *as_string,
3763 struct in_str *input,
3765 int process_bkslash)
3767 #if !ENABLE_HUSH_BASH_COMPAT
3768 const int process_bkslash = 1;
3774 ch = i_getch(input);
3776 nommu_addchr(as_string, ch);
3777 if (ch == dquote_end) { /* may be only '"' or EOF */
3778 debug_printf_parse("encode_string return 0\n");
3781 /* note: can't move it above ch == dquote_end check! */
3783 syntax_error_unterm_ch('"');
3784 /*xfunc_die(); - redundant */
3788 next = i_peek(input);
3790 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3791 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3792 if (process_bkslash && ch == '\\') {
3794 syntax_error("\\<eof>");
3798 * "The backslash retains its special meaning [in "..."]
3799 * only when followed by one of the following characters:
3800 * $, `, ", \, or <newline>. A double quote may be quoted
3801 * within double quotes by preceding it with a backslash."
3802 * NB: in (unquoted) heredoc, above does not apply to ",
3803 * therefore we check for it by "next == dquote_end" cond.
3805 if (next == dquote_end || strchr("$`\\\n", next)) {
3806 ch = i_getch(input); /* eat next */
3808 goto again; /* skip \<newline> */
3809 } /* else: ch remains == '\\', and we double it below: */
3810 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3811 nommu_addchr(as_string, ch);
3815 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3816 debug_printf_parse("encode_string return 1: "
3817 "parse_dollar returned non-0\n");
3822 #if ENABLE_HUSH_TICK
3824 //unsigned pos = dest->length;
3825 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3826 o_addchr(dest, 0x80 | '`');
3827 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3828 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3829 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3833 o_addQchr(dest, ch);
3839 * Scan input until EOF or end_trigger char.
3840 * Return a list of pipes to execute, or NULL on EOF
3841 * or if end_trigger character is met.
3842 * On syntax error, exit is shell is not interactive,
3843 * reset parsing machinery and start parsing anew,
3844 * or return ERR_PTR.
3846 static struct pipe *parse_stream(char **pstring,
3847 struct in_str *input,
3850 struct parse_context ctx;
3851 o_string dest = NULL_O_STRING;
3854 /* Single-quote triggers a bypass of the main loop until its mate is
3855 * found. When recursing, quote state is passed in via dest->o_expflags.
3857 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3858 end_trigger ? end_trigger : 'X');
3861 /* If very first arg is "" or '', dest.data may end up NULL.
3862 * Preventing this: */
3863 o_addchr(&dest, '\0');
3866 /* We used to separate words on $IFS here. This was wrong.
3867 * $IFS is used only for word splitting when $var is expanded,
3868 * here we should use blank chars as separators, not $IFS
3871 reset: /* we come back here only on syntax errors in interactive shell */
3873 #if ENABLE_HUSH_INTERACTIVE
3874 input->promptmode = 0; /* PS1 */
3876 if (MAYBE_ASSIGNMENT != 0)
3877 dest.o_assignment = MAYBE_ASSIGNMENT;
3878 initialize_context(&ctx);
3881 const char *is_blank;
3882 const char *is_special;
3886 redir_type redir_style;
3888 ch = i_getch(input);
3889 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3890 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3895 syntax_error_unterm_str("here document");
3898 /* end_trigger == '}' case errors out earlier,
3899 * checking only ')' */
3900 if (end_trigger == ')') {
3901 syntax_error_unterm_ch('('); /* exits */
3902 /* goto parse_error; */
3905 if (done_word(&dest, &ctx)) {
3909 done_pipe(&ctx, PIPE_SEQ);
3911 /* If we got nothing... */
3912 /* (this makes bare "&" cmd a no-op.
3913 * bash says: "syntax error near unexpected token '&'") */
3914 if (pi->num_cmds == 0
3915 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3921 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3923 *pstring = ctx.as_string.data;
3925 o_free_unsafe(&ctx.as_string);
3928 debug_printf_parse("parse_stream return %p\n", pi);
3931 nommu_addchr(&ctx.as_string, ch);
3935 next = i_peek(input);
3937 is_special = "{}<>;&|()#'" /* special outside of "str" */
3938 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3939 /* Are { and } special here? */
3940 if (ctx.command->argv /* word [word]{... - non-special */
3941 || dest.length /* word{... - non-special */
3942 || dest.has_quoted_part /* ""{... - non-special */
3943 || (next != ';' /* }; - special */
3944 && next != ')' /* }) - special */
3945 && next != '&' /* }& and }&& ... - special */
3946 && next != '|' /* }|| ... - special */
3947 && !strchr(defifs, next) /* {word - non-special */
3950 /* They are not special, skip "{}" */
3953 is_special = strchr(is_special, ch);
3954 is_blank = strchr(defifs, ch);
3956 if (!is_special && !is_blank) { /* ordinary char */
3958 o_addQchr(&dest, ch);
3959 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3960 || dest.o_assignment == WORD_IS_KEYWORD)
3962 && is_well_formed_var_name(dest.data, '=')
3964 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3970 if (done_word(&dest, &ctx)) {
3974 #if ENABLE_HUSH_CASE
3975 /* "case ... in <newline> word) ..." -
3976 * newlines are ignored (but ';' wouldn't be) */
3977 if (ctx.command->argv == NULL
3978 && ctx.ctx_res_w == RES_MATCH
3983 /* Treat newline as a command separator. */
3984 done_pipe(&ctx, PIPE_SEQ);
3985 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3987 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3992 dest.o_assignment = MAYBE_ASSIGNMENT;
3994 /* note: if (is_blank) continue;
3995 * will still trigger for us */
3999 /* "cmd}" or "cmd }..." without semicolon or &:
4000 * } is an ordinary char in this case, even inside { cmd; }
4001 * Pathological example: { ""}; } should exec "}" cmd
4004 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4005 || dest.length != 0 /* word} */
4006 || dest.has_quoted_part /* ""} */
4010 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4011 goto skip_end_trigger;
4012 /* else: } does terminate a group */
4015 if (end_trigger && end_trigger == ch
4016 && (ch != ';' || heredoc_cnt == 0)
4017 #if ENABLE_HUSH_CASE
4019 || ctx.ctx_res_w != RES_MATCH
4020 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4025 /* This is technically valid:
4026 * { cat <<HERE; }; echo Ok
4030 * but we don't support this.
4031 * We require heredoc to be in enclosing {}/(),
4034 syntax_error_unterm_str("here document");
4037 if (done_word(&dest, &ctx)) {
4040 done_pipe(&ctx, PIPE_SEQ);
4041 dest.o_assignment = MAYBE_ASSIGNMENT;
4042 /* Do we sit outside of any if's, loops or case's? */
4044 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4048 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4050 *pstring = ctx.as_string.data;
4052 o_free_unsafe(&ctx.as_string);
4055 debug_printf_parse("parse_stream return %p: "
4056 "end_trigger char found\n",
4058 return ctx.list_head;
4065 /* Catch <, > before deciding whether this word is
4066 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4069 redir_fd = redirect_opt_num(&dest);
4070 if (done_word(&dest, &ctx)) {
4073 redir_style = REDIRECT_OVERWRITE;
4075 redir_style = REDIRECT_APPEND;
4076 ch = i_getch(input);
4077 nommu_addchr(&ctx.as_string, ch);
4080 else if (next == '(') {
4081 syntax_error(">(process) not supported");
4085 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4087 continue; /* back to top of while (1) */
4089 redir_fd = redirect_opt_num(&dest);
4090 if (done_word(&dest, &ctx)) {
4093 redir_style = REDIRECT_INPUT;
4095 redir_style = REDIRECT_HEREDOC;
4097 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4098 ch = i_getch(input);
4099 nommu_addchr(&ctx.as_string, ch);
4100 } else if (next == '>') {
4101 redir_style = REDIRECT_IO;
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4106 else if (next == '(') {
4107 syntax_error("<(process) not supported");
4111 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4113 continue; /* back to top of while (1) */
4116 if (dest.o_assignment == MAYBE_ASSIGNMENT
4117 /* check that we are not in word in "a=1 2>word b=1": */
4118 && !ctx.pending_redirect
4120 /* ch is a special char and thus this word
4121 * cannot be an assignment */
4122 dest.o_assignment = NOT_ASSIGNMENT;
4125 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4129 if (dest.length == 0) {
4132 if (ch == EOF || ch == '\n')
4135 /* note: we do not add it to &ctx.as_string */
4137 nommu_addchr(&ctx.as_string, '\n');
4139 o_addQchr(&dest, ch);
4144 syntax_error("\\<eof>");
4147 ch = i_getch(input);
4149 o_addchr(&dest, '\\');
4150 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4151 o_addchr(&dest, ch);
4152 nommu_addchr(&ctx.as_string, ch);
4153 /* Example: echo Hello \2>file
4154 * we need to know that word 2 is quoted */
4155 dest.has_quoted_part = 1;
4159 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4160 ctx.as_string.data[--ctx.as_string.length] = '\0';
4165 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4166 debug_printf_parse("parse_stream parse error: "
4167 "parse_dollar returned non-0\n");
4172 dest.has_quoted_part = 1;
4174 ch = i_getch(input);
4176 syntax_error_unterm_ch('\'');
4177 /*xfunc_die(); - redundant */
4179 nommu_addchr(&ctx.as_string, ch);
4182 o_addqchr(&dest, ch);
4186 dest.has_quoted_part = 1;
4187 if (dest.o_assignment == NOT_ASSIGNMENT)
4188 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4189 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4191 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4193 #if ENABLE_HUSH_TICK
4197 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4198 o_addchr(&dest, '`');
4200 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4202 o_addstr(&ctx.as_string, dest.data + pos);
4203 o_addchr(&ctx.as_string, '`');
4205 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4206 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4211 #if ENABLE_HUSH_CASE
4214 if (done_word(&dest, &ctx)) {
4217 done_pipe(&ctx, PIPE_SEQ);
4218 #if ENABLE_HUSH_CASE
4219 /* Eat multiple semicolons, detect
4220 * whether it means something special */
4225 ch = i_getch(input);
4226 nommu_addchr(&ctx.as_string, ch);
4227 if (ctx.ctx_res_w == RES_CASE_BODY) {
4228 ctx.ctx_dsemicolon = 1;
4229 ctx.ctx_res_w = RES_MATCH;
4235 /* We just finished a cmd. New one may start
4236 * with an assignment */
4237 dest.o_assignment = MAYBE_ASSIGNMENT;
4240 if (done_word(&dest, &ctx)) {
4244 ch = i_getch(input);
4245 nommu_addchr(&ctx.as_string, ch);
4246 done_pipe(&ctx, PIPE_AND);
4248 done_pipe(&ctx, PIPE_BG);
4252 if (done_word(&dest, &ctx)) {
4255 #if ENABLE_HUSH_CASE
4256 if (ctx.ctx_res_w == RES_MATCH)
4257 break; /* we are in case's "word | word)" */
4259 if (next == '|') { /* || */
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4262 done_pipe(&ctx, PIPE_OR);
4264 /* we could pick up a file descriptor choice here
4265 * with redirect_opt_num(), but bash doesn't do it.
4266 * "echo foo 2| cat" yields "foo 2". */
4269 o_reset_to_empty_unquoted(&ctx.as_string);
4274 #if ENABLE_HUSH_CASE
4275 /* "case... in [(]word)..." - skip '(' */
4276 if (ctx.ctx_res_w == RES_MATCH
4277 && ctx.command->argv == NULL /* not (word|(... */
4278 && dest.length == 0 /* not word(... */
4279 && dest.has_quoted_part == 0 /* not ""(... */
4285 if (parse_group(&dest, &ctx, input, ch) != 0) {
4290 #if ENABLE_HUSH_CASE
4291 if (ctx.ctx_res_w == RES_MATCH)
4295 /* proper use of this character is caught by end_trigger:
4296 * if we see {, we call parse_group(..., end_trigger='}')
4297 * and it will match } earlier (not here). */
4298 syntax_error_unexpected_ch(ch);
4302 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4308 struct parse_context *pctx;
4309 IF_HAS_KEYWORDS(struct parse_context *p2;)
4311 /* Clean up allocated tree.
4312 * Sample for finding leaks on syntax error recovery path.
4313 * Run it from interactive shell, watch pmap `pidof hush`.
4314 * while if false; then false; fi; do break; fi
4315 * Samples to catch leaks at execution:
4316 * while if (true | {true;}); then echo ok; fi; do break; done
4317 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4321 /* Update pipe/command counts,
4322 * otherwise freeing may miss some */
4323 done_pipe(pctx, PIPE_SEQ);
4324 debug_printf_clean("freeing list %p from ctx %p\n",
4325 pctx->list_head, pctx);
4326 debug_print_tree(pctx->list_head, 0);
4327 free_pipe_list(pctx->list_head);
4328 debug_printf_clean("freed list %p\n", pctx->list_head);
4330 o_free_unsafe(&pctx->as_string);
4332 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4336 IF_HAS_KEYWORDS(pctx = p2;)
4337 } while (HAS_KEYWORDS && pctx);
4338 /* Free text, clear all dest fields */
4340 /* If we are not in top-level parse, we return,
4341 * our caller will propagate error.
4343 if (end_trigger != ';') {
4351 /* Discard cached input, force prompt */
4353 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4359 /*** Execution routines ***/
4361 /* Expansion can recurse, need forward decls: */
4362 #if !ENABLE_HUSH_BASH_COMPAT
4363 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4364 #define expand_string_to_string(str, do_unbackslash) \
4365 expand_string_to_string(str)
4367 static char *expand_string_to_string(const char *str, int do_unbackslash);
4368 static int process_command_subs(o_string *dest, const char *s);
4370 /* expand_strvec_to_strvec() takes a list of strings, expands
4371 * all variable references within and returns a pointer to
4372 * a list of expanded strings, possibly with larger number
4373 * of strings. (Think VAR="a b"; echo $VAR).
4374 * This new list is allocated as a single malloc block.
4375 * NULL-terminated list of char* pointers is at the beginning of it,
4376 * followed by strings themselves.
4377 * Caller can deallocate entire list by single free(list). */
4379 /* A horde of its helpers come first: */
4381 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4383 while (--len >= 0) {
4386 #if ENABLE_HUSH_BRACE_EXPANSION
4387 if (c == '{' || c == '}') {
4388 /* { -> \{, } -> \} */
4390 /* And now we want to add { or } and continue:
4393 * luckily, just falling throught achieves this.
4399 /* \z -> \\\z; \<eol> -> \\<eol> */
4404 o_addchr(o, *str++);
4410 /* Store given string, finalizing the word and starting new one whenever
4411 * we encounter IFS char(s). This is used for expanding variable values.
4412 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4413 static int expand_on_ifs(o_string *output, int n, const char *str)
4416 int word_len = strcspn(str, G.ifs);
4418 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4419 o_addblock(output, str, word_len);
4421 /* Protect backslashes against globbing up :)
4422 * Example: "v='\*'; echo b$v" prints "b\*"
4423 * (and does not try to glob on "*")
4425 o_addblock_duplicate_backslash(output, str, word_len);
4426 /*/ Why can't we do it easier? */
4427 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4428 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4432 if (!*str) /* EOL - do not finalize word */
4434 o_addchr(output, '\0');
4435 debug_print_list("expand_on_ifs", output, n);
4436 n = o_save_ptr(output, n);
4437 str += strspn(str, G.ifs); /* skip ifs chars */
4439 debug_print_list("expand_on_ifs[1]", output, n);
4443 /* Helper to expand $((...)) and heredoc body. These act as if
4444 * they are in double quotes, with the exception that they are not :).
4445 * Just the rules are similar: "expand only $var and `cmd`"
4447 * Returns malloced string.
4448 * As an optimization, we return NULL if expansion is not needed.
4450 #if !ENABLE_HUSH_BASH_COMPAT
4451 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4452 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4453 encode_then_expand_string(str)
4455 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4458 struct in_str input;
4459 o_string dest = NULL_O_STRING;
4461 if (!strchr(str, '$')
4462 && !strchr(str, '\\')
4463 #if ENABLE_HUSH_TICK
4464 && !strchr(str, '`')
4470 /* We need to expand. Example:
4471 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4473 setup_string_in_str(&input, str);
4474 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4475 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4476 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4477 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4478 o_free_unsafe(&dest);
4482 #if ENABLE_SH_MATH_SUPPORT
4483 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4485 arith_state_t math_state;
4489 math_state.lookupvar = get_local_var_value;
4490 math_state.setvar = set_local_var_from_halves;
4491 //math_state.endofname = endofname;
4492 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4493 res = arith(&math_state, exp_str ? exp_str : arg);
4496 *errmsg_p = math_state.errmsg;
4497 if (math_state.errmsg)
4498 die_if_script(math_state.errmsg);
4503 #if ENABLE_HUSH_BASH_COMPAT
4504 /* ${var/[/]pattern[/repl]} helpers */
4505 static char *strstr_pattern(char *val, const char *pattern, int *size)
4508 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4509 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4516 /* Optimization: if "*pat" did not match the start of "string",
4517 * we know that "tring", "ring" etc will not match too:
4519 if (pattern[0] == '*')
4524 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4526 char *result = NULL;
4527 unsigned res_len = 0;
4528 unsigned repl_len = strlen(repl);
4532 char *s = strstr_pattern(val, pattern, &size);
4536 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4537 memcpy(result + res_len, val, s - val);
4539 strcpy(result + res_len, repl);
4540 res_len += repl_len;
4541 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4547 if (val[0] && result) {
4548 result = xrealloc(result, res_len + strlen(val) + 1);
4549 strcpy(result + res_len, val);
4550 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4552 debug_printf_varexp("result:'%s'\n", result);
4558 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4560 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4562 const char *val = NULL;
4563 char *to_be_freed = NULL;
4568 char exp_save = exp_save; /* for compiler */
4569 char *exp_saveptr; /* points to expansion operator */
4570 char *exp_word = exp_word; /* for compiler */
4573 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4575 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4577 first_char = arg[0] = arg0 & 0x7f;
4580 if (first_char == '#' /* ${#... */
4581 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4583 /* It must be length operator: ${#var} */
4587 /* Maybe handle parameter expansion */
4588 if (exp_saveptr /* if 2nd char is one of expansion operators */
4589 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4591 /* ${?:0}, ${#[:]%0} etc */
4592 exp_saveptr = var + 1;
4594 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4595 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4597 exp_op = exp_save = *exp_saveptr;
4599 exp_word = exp_saveptr + 1;
4600 if (exp_op == ':') {
4601 exp_op = *exp_word++;
4602 //TODO: try ${var:} and ${var:bogus} in non-bash config
4603 if (ENABLE_HUSH_BASH_COMPAT
4604 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4606 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4611 *exp_saveptr = '\0';
4612 } /* else: it's not an expansion op, but bare ${var} */
4615 /* Look up the variable in question */
4616 if (isdigit(var[0])) {
4617 /* parse_dollar should have vetted var for us */
4618 int n = xatoi_positive(var);
4619 if (n < G.global_argc)
4620 val = G.global_argv[n];
4621 /* else val remains NULL: $N with too big N */
4625 val = utoa(G.root_pid);
4627 case '!': /* bg pid */
4628 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4630 case '?': /* exitcode */
4631 val = utoa(G.last_exitcode);
4633 case '#': /* argc */
4634 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4637 val = get_local_var_value(var);
4641 /* Handle any expansions */
4642 if (exp_op == 'L') {
4643 debug_printf_expand("expand: length(%s)=", val);
4644 val = utoa(val ? strlen(val) : 0);
4645 debug_printf_expand("%s\n", val);
4646 } else if (exp_op) {
4647 if (exp_op == '%' || exp_op == '#') {
4648 /* Standard-mandated substring removal ops:
4649 * ${parameter%word} - remove smallest suffix pattern
4650 * ${parameter%%word} - remove largest suffix pattern
4651 * ${parameter#word} - remove smallest prefix pattern
4652 * ${parameter##word} - remove largest prefix pattern
4654 * Word is expanded to produce a glob pattern.
4655 * Then var's value is matched to it and matching part removed.
4657 if (val && val[0]) {
4661 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4662 if (exp_op == *exp_word) /* ## or %% */
4664 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4666 exp_word = exp_exp_word;
4667 /* HACK ALERT. We depend here on the fact that
4668 * G.global_argv and results of utoa and get_local_var_value
4669 * are actually in writable memory:
4670 * scan_and_match momentarily stores NULs there. */
4672 loc = scan_and_match(t, exp_word, scan_flags);
4673 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4674 // exp_op, t, exp_word, loc);
4676 if (loc) { /* match was found */
4677 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4678 val = loc; /* take right part */
4680 val = to_be_freed = xstrndup(val, loc - val); /* left */
4684 #if ENABLE_HUSH_BASH_COMPAT
4685 else if (exp_op == '/' || exp_op == '\\') {
4686 /* It's ${var/[/]pattern[/repl]} thing.
4687 * Note that in encoded form it has TWO parts:
4688 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4689 * and if // is used, it is encoded as \:
4690 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4692 /* Empty variable always gives nothing: */
4693 // "v=''; echo ${v/*/w}" prints "", not "w"
4694 if (val && val[0]) {
4695 /* pattern uses non-standard expansion.
4696 * repl should be unbackslashed and globbed
4697 * by the usual expansion rules:
4699 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4700 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4701 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4702 * v='a bz'; echo ${v/a*z/\z} prints "z"
4703 * (note that a*z _pattern_ is never globbed!)
4705 char *pattern, *repl, *t;
4706 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4708 pattern = xstrdup(exp_word);
4709 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4710 *p++ = SPECIAL_VAR_SYMBOL;
4712 p = strchr(p, SPECIAL_VAR_SYMBOL);
4714 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4715 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4716 /* HACK ALERT. We depend here on the fact that
4717 * G.global_argv and results of utoa and get_local_var_value
4718 * are actually in writable memory:
4719 * replace_pattern momentarily stores NULs there. */
4721 to_be_freed = replace_pattern(t,
4723 (repl ? repl : exp_word),
4725 if (to_be_freed) /* at least one replace happened */
4732 else if (exp_op == ':') {
4733 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4734 /* It's ${var:N[:M]} bashism.
4735 * Note that in encoded form it has TWO parts:
4736 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4741 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4744 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4745 *p++ = SPECIAL_VAR_SYMBOL;
4747 p = strchr(p, SPECIAL_VAR_SYMBOL);
4749 len = expand_and_evaluate_arith(exp_word, &errmsg);
4752 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4753 if (len >= 0) { /* bash compat: len < 0 is illegal */
4754 if (beg < 0) /* bash compat */
4756 debug_printf_varexp("from val:'%s'\n", val);
4757 if (len == 0 || !val || beg >= strlen(val)) {
4761 /* Paranoia. What if user entered 9999999999999
4762 * which fits in arith_t but not int? */
4765 val = to_be_freed = xstrndup(val + beg, len);
4767 debug_printf_varexp("val:'%s'\n", val);
4771 die_if_script("malformed ${%s:...}", var);
4774 } else { /* one of "-=+?" */
4775 /* Standard-mandated substitution ops:
4776 * ${var?word} - indicate error if unset
4777 * If var is unset, word (or a message indicating it is unset
4778 * if word is null) is written to standard error
4779 * and the shell exits with a non-zero exit status.
4780 * Otherwise, the value of var is substituted.
4781 * ${var-word} - use default value
4782 * If var is unset, word is substituted.
4783 * ${var=word} - assign and use default value
4784 * If var is unset, word is assigned to var.
4785 * In all cases, final value of var is substituted.
4786 * ${var+word} - use alternative value
4787 * If var is unset, null is substituted.
4788 * Otherwise, word is substituted.
4790 * Word is subjected to tilde expansion, parameter expansion,
4791 * command substitution, and arithmetic expansion.
4792 * If word is not needed, it is not expanded.
4794 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4795 * but also treat null var as if it is unset.
4797 int use_word = (!val || ((exp_save == ':') && !val[0]));
4799 use_word = !use_word;
4800 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4801 (exp_save == ':') ? "true" : "false", use_word);
4803 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4805 exp_word = to_be_freed;
4806 if (exp_op == '?') {
4807 /* mimic bash message */
4808 die_if_script("%s: %s",
4810 exp_word[0] ? exp_word : "parameter null or not set"
4812 //TODO: how interactive bash aborts expansion mid-command?
4817 if (exp_op == '=') {
4818 /* ${var=[word]} or ${var:=[word]} */
4819 if (isdigit(var[0]) || var[0] == '#') {
4820 /* mimic bash message */
4821 die_if_script("$%s: cannot assign in this way", var);
4824 char *new_var = xasprintf("%s=%s", var, val);
4825 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4829 } /* one of "-=+?" */
4831 *exp_saveptr = exp_save;
4837 *to_be_freed_pp = to_be_freed;
4841 /* Expand all variable references in given string, adding words to list[]
4842 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4843 * to be filled). This routine is extremely tricky: has to deal with
4844 * variables/parameters with whitespace, $* and $@, and constructs like
4845 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4846 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4848 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4849 * expansion of right-hand side of assignment == 1-element expand.
4851 char cant_be_null = 0; /* only bit 0x80 matters */
4854 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4855 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4856 debug_print_list("expand_vars_to_list", output, n);
4857 n = o_save_ptr(output, n);
4858 debug_print_list("expand_vars_to_list[0]", output, n);
4860 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4862 char *to_be_freed = NULL;
4863 const char *val = NULL;
4864 #if ENABLE_HUSH_TICK
4865 o_string subst_result = NULL_O_STRING;
4867 #if ENABLE_SH_MATH_SUPPORT
4868 char arith_buf[sizeof(arith_t)*3 + 2];
4870 o_addblock(output, arg, p - arg);
4871 debug_print_list("expand_vars_to_list[1]", output, n);
4873 p = strchr(p, SPECIAL_VAR_SYMBOL);
4875 /* Fetch special var name (if it is indeed one of them)
4876 * and quote bit, force the bit on if singleword expansion -
4877 * important for not getting v=$@ expand to many words. */
4878 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4880 /* Is this variable quoted and thus expansion can't be null?
4881 * "$@" is special. Even if quoted, it can still
4882 * expand to nothing (not even an empty string),
4883 * thus it is excluded. */
4884 if ((first_ch & 0x7f) != '@')
4885 cant_be_null |= first_ch;
4887 switch (first_ch & 0x7f) {
4888 /* Highest bit in first_ch indicates that var is double-quoted */
4892 if (!G.global_argv[1])
4895 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4896 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4897 while (G.global_argv[i]) {
4898 n = expand_on_ifs(output, n, G.global_argv[i]);
4899 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4900 if (G.global_argv[i++][0] && G.global_argv[i]) {
4901 /* this argv[] is not empty and not last:
4902 * put terminating NUL, start new word */
4903 o_addchr(output, '\0');
4904 debug_print_list("expand_vars_to_list[2]", output, n);
4905 n = o_save_ptr(output, n);
4906 debug_print_list("expand_vars_to_list[3]", output, n);
4910 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4911 * and in this case should treat it like '$*' - see 'else...' below */
4912 if (first_ch == ('@'|0x80) /* quoted $@ */
4913 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4916 o_addQstr(output, G.global_argv[i]);
4917 if (++i >= G.global_argc)
4919 o_addchr(output, '\0');
4920 debug_print_list("expand_vars_to_list[4]", output, n);
4921 n = o_save_ptr(output, n);
4923 } else { /* quoted $* (or v="$@" case): add as one word */
4925 o_addQstr(output, G.global_argv[i]);
4926 if (!G.global_argv[++i])
4929 o_addchr(output, G.ifs[0]);
4934 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4935 /* "Empty variable", used to make "" etc to not disappear */
4937 cant_be_null = 0x80;
4939 #if ENABLE_HUSH_TICK
4940 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4941 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4943 /* Can't just stuff it into output o_string,
4944 * expanded result may need to be globbed
4945 * and $IFS-splitted */
4946 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4947 G.last_exitcode = process_command_subs(&subst_result, arg);
4948 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4949 val = subst_result.data;
4952 #if ENABLE_SH_MATH_SUPPORT
4953 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4956 arg++; /* skip '+' */
4957 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4958 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4959 res = expand_and_evaluate_arith(arg, NULL);
4960 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
4961 sprintf(arith_buf, ARITH_FMT, res);
4967 val = expand_one_var(&to_be_freed, arg, &p);
4968 IF_HUSH_TICK(store_val:)
4969 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4970 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4971 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4972 if (val && val[0]) {
4973 n = expand_on_ifs(output, n, val);
4976 } else { /* quoted $VAR, val will be appended below */
4977 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4978 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4982 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4984 if (val && val[0]) {
4985 o_addQstr(output, val);
4989 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4990 * Do the check to avoid writing to a const string. */
4991 if (*p != SPECIAL_VAR_SYMBOL)
4992 *p = SPECIAL_VAR_SYMBOL;
4994 #if ENABLE_HUSH_TICK
4995 o_free(&subst_result);
4998 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5001 debug_print_list("expand_vars_to_list[a]", output, n);
5002 /* this part is literal, and it was already pre-quoted
5003 * if needed (much earlier), do not use o_addQstr here! */
5004 o_addstr_with_NUL(output, arg);
5005 debug_print_list("expand_vars_to_list[b]", output, n);
5006 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5007 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5010 /* allow to reuse list[n] later without re-growth */
5011 output->has_empty_slot = 1;
5013 o_addchr(output, '\0');
5019 static char **expand_variables(char **argv, unsigned expflags)
5023 o_string output = NULL_O_STRING;
5025 output.o_expflags = expflags;
5029 n = expand_vars_to_list(&output, n, *argv);
5032 debug_print_list("expand_variables", &output, n);
5034 /* output.data (malloced in one block) gets returned in "list" */
5035 list = o_finalize_list(&output, n);
5036 debug_print_strings("expand_variables[1]", list);
5040 static char **expand_strvec_to_strvec(char **argv)
5042 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5045 #if ENABLE_HUSH_BASH_COMPAT
5046 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5048 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5052 /* Used for expansion of right hand of assignments,
5053 * $((...)), heredocs, variable espansion parts.
5055 * NB: should NOT do globbing!
5056 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5058 static char *expand_string_to_string(const char *str, int do_unbackslash)
5060 #if !ENABLE_HUSH_BASH_COMPAT
5061 const int do_unbackslash = 1;
5063 char *argv[2], **list;
5065 debug_printf_expand("string_to_string<='%s'\n", str);
5066 /* This is generally an optimization, but it also
5067 * handles "", which otherwise trips over !list[0] check below.
5068 * (is this ever happens that we actually get str="" here?)
5070 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5071 //TODO: Can use on strings with \ too, just unbackslash() them?
5072 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5073 return xstrdup(str);
5076 argv[0] = (char*)str;
5078 list = expand_variables(argv, do_unbackslash
5079 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5080 : EXP_FLAG_SINGLEWORD
5083 if (!list[0] || list[1])
5084 bb_error_msg_and_die("BUG in varexp2");
5085 /* actually, just move string 2*sizeof(char*) bytes back */
5086 overlapping_strcpy((char*)list, list[0]);
5088 unbackslash((char*)list);
5089 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5093 /* Used for "eval" builtin */
5094 static char* expand_strvec_to_string(char **argv)
5098 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5099 /* Convert all NULs to spaces */
5104 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5105 bb_error_msg_and_die("BUG in varexp3");
5106 /* bash uses ' ' regardless of $IFS contents */
5111 overlapping_strcpy((char*)list, list[0]);
5112 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5116 static char **expand_assignments(char **argv, int count)
5121 G.expanded_assignments = p = NULL;
5122 /* Expand assignments into one string each */
5123 for (i = 0; i < count; i++) {
5124 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5126 G.expanded_assignments = NULL;
5133 void re_execute_shell(char ***to_free, const char *s,
5134 char *g_argv0, char **g_argv,
5135 char **builtin_argv) NORETURN;
5137 static void reset_traps_to_defaults(void)
5139 /* This function is always called in a child shell
5140 * after fork (not vfork, NOMMU doesn't use this function).
5145 /* Child shells are not interactive.
5146 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5147 * Testcase: (while :; do :; done) + ^Z should background.
5148 * Same goes for SIGTERM, SIGHUP, SIGINT.
5150 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5151 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5153 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5154 * Stupid. It can be done with *single* &= op, but we can't use
5155 * the fact that G.blocked_set is implemented as a bitmask
5157 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5161 /* Careful. Only if no trap or trap is not "" */
5162 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5163 sigdelset(&G.blocked_set, sig);
5170 /* Our homegrown sig mask is saner to work with :) */
5171 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5173 /* Resetting all traps to default except empty ones */
5174 mask = G.non_DFL_mask;
5175 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5176 if (!G.traps[sig] || !G.traps[sig][0])
5179 G.traps[sig] = NULL;
5180 /* There is no signal for 0 (EXIT) */
5183 /* There was a trap handler, we just removed it.
5184 * But if sig still has non-DFL handling,
5185 * we should not unblock the sig. */
5188 sigdelset(&G.blocked_set, sig);
5190 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5195 static void re_execute_shell(char ***to_free, const char *s,
5196 char *g_argv0, char **g_argv,
5197 char **builtin_argv) NORETURN;
5198 static void re_execute_shell(char ***to_free, const char *s,
5199 char *g_argv0, char **g_argv,
5200 char **builtin_argv)
5202 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5203 /* delims + 2 * (number of bytes in printed hex numbers) */
5204 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5205 char *heredoc_argv[4];
5206 struct variable *cur;
5207 # if ENABLE_HUSH_FUNCTIONS
5208 struct function *funcp;
5212 unsigned long long empty_trap_mask;
5214 if (!g_argv0) { /* heredoc */
5215 argv = heredoc_argv;
5216 argv[0] = (char *) G.argv0_for_re_execing;
5217 argv[1] = (char *) "-<";
5218 argv[2] = (char *) s;
5220 pp = &argv[3]; /* used as pointer to empty environment */
5226 if (pp) while (*pp++)
5229 empty_trap_mask = 0;
5232 for (sig = 1; sig < NSIG; sig++) {
5233 if (G.traps[sig] && !G.traps[sig][0])
5234 empty_trap_mask |= 1LL << sig;
5238 sprintf(param_buf, NOMMU_HACK_FMT
5239 , (unsigned) G.root_pid
5240 , (unsigned) G.root_ppid
5241 , (unsigned) G.last_bg_pid
5242 , (unsigned) G.last_exitcode
5245 IF_HUSH_LOOPS(, G.depth_of_loop)
5247 # undef NOMMU_HACK_FMT
5248 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5249 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5252 for (cur = G.top_var; cur; cur = cur->next) {
5253 if (!cur->flg_export || cur->flg_read_only)
5256 # if ENABLE_HUSH_FUNCTIONS
5257 for (funcp = G.top_func; funcp; funcp = funcp->next)
5263 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5264 *pp++ = (char *) G.argv0_for_re_execing;
5266 for (cur = G.top_var; cur; cur = cur->next) {
5267 if (strcmp(cur->varstr, hush_version_str) == 0)
5269 if (cur->flg_read_only) {
5270 *pp++ = (char *) "-R";
5271 *pp++ = cur->varstr;
5272 } else if (!cur->flg_export) {
5273 *pp++ = (char *) "-V";
5274 *pp++ = cur->varstr;
5277 # if ENABLE_HUSH_FUNCTIONS
5278 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5279 *pp++ = (char *) "-F";
5280 *pp++ = funcp->name;
5281 *pp++ = funcp->body_as_string;
5284 /* We can pass activated traps here. Say, -Tnn:trap_string
5286 * However, POSIX says that subshells reset signals with traps
5288 * I tested bash-3.2 and it not only does that with true subshells
5289 * of the form ( list ), but with any forked children shells.
5290 * I set trap "echo W" WINCH; and then tried:
5292 * { echo 1; sleep 20; echo 2; } &
5293 * while true; do echo 1; sleep 20; echo 2; break; done &
5294 * true | { echo 1; sleep 20; echo 2; } | cat
5296 * In all these cases sending SIGWINCH to the child shell
5297 * did not run the trap. If I add trap "echo V" WINCH;
5298 * _inside_ group (just before echo 1), it works.
5300 * I conclude it means we don't need to pass active traps here.
5301 * Even if we would use signal handlers instead of signal masking
5302 * in order to implement trap handling,
5303 * exec syscall below resets signals to SIG_DFL for us.
5305 *pp++ = (char *) "-c";
5308 while (*++builtin_argv)
5309 *pp++ = *builtin_argv;
5310 *pp++ = (char *) "";
5315 /* *pp = NULL; - is already there */
5319 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5320 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5321 execve(bb_busybox_exec_path, argv, pp);
5322 /* Fallback. Useful for init=/bin/hush usage etc */
5323 if (argv[0][0] == '/')
5324 execve(argv[0], argv, pp);
5325 xfunc_error_retval = 127;
5326 bb_error_msg_and_die("can't re-execute the shell");
5328 #endif /* !BB_MMU */
5331 static int run_and_free_list(struct pipe *pi);
5333 /* Executing from string: eval, sh -c '...'
5334 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5335 * end_trigger controls how often we stop parsing
5336 * NUL: parse all, execute, return
5337 * ';': parse till ';' or newline, execute, repeat till EOF
5339 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5341 /* Why we need empty flag?
5342 * An obscure corner case "false; ``; echo $?":
5343 * empty command in `` should still set $? to 0.
5344 * But we can't just set $? to 0 at the start,
5345 * this breaks "false; echo `echo $?`" case.
5349 struct pipe *pipe_list;
5351 pipe_list = parse_stream(NULL, inp, end_trigger);
5352 if (!pipe_list) { /* EOF */
5354 G.last_exitcode = 0;
5357 debug_print_tree(pipe_list, 0);
5358 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5359 run_and_free_list(pipe_list);
5364 static void parse_and_run_string(const char *s)
5366 struct in_str input;
5367 setup_string_in_str(&input, s);
5368 parse_and_run_stream(&input, '\0');
5371 static void parse_and_run_file(FILE *f)
5373 struct in_str input;
5374 setup_file_in_str(&input, f);
5375 parse_and_run_stream(&input, ';');
5378 #if ENABLE_HUSH_TICK
5379 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5384 char **to_free = NULL;
5388 pid = BB_MMU ? xfork() : xvfork();
5389 if (pid == 0) { /* child */
5390 disable_restore_tty_pgrp_on_exit();
5391 /* Process substitution is not considered to be usual
5392 * 'command execution'.
5393 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5400 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5401 close(channel[0]); /* NB: close _first_, then move fd! */
5402 xmove_fd(channel[1], 1);
5403 /* Prevent it from trying to handle ctrl-z etc */
5404 IF_HUSH_JOB(G.run_list_level = 1;)
5405 /* Awful hack for `trap` or $(trap).
5407 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5408 * contains an example where "trap" is executed in a subshell:
5410 * save_traps=$(trap)
5412 * eval "$save_traps"
5414 * Standard does not say that "trap" in subshell shall print
5415 * parent shell's traps. It only says that its output
5416 * must have suitable form, but then, in the above example
5417 * (which is not supposed to be normative), it implies that.
5419 * bash (and probably other shell) does implement it
5420 * (traps are reset to defaults, but "trap" still shows them),
5421 * but as a result, "trap" logic is hopelessly messed up:
5424 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5425 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5426 * # true | trap <--- trap is in subshell - no output (ditto)
5427 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5428 * trap -- 'echo Ho' SIGWINCH
5429 * # echo `(trap)` <--- in subshell in subshell - output
5430 * trap -- 'echo Ho' SIGWINCH
5431 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5432 * trap -- 'echo Ho' SIGWINCH
5434 * The rules when to forget and when to not forget traps
5435 * get really complex and nonsensical.
5437 * Our solution: ONLY bare $(trap) or `trap` is special.
5439 s = skip_whitespace(s);
5440 if (strncmp(s, "trap", 4) == 0
5441 && skip_whitespace(s + 4)[0] == '\0'
5443 static const char *const argv[] = { NULL, NULL };
5444 builtin_trap((char**)argv);
5445 exit(0); /* not _exit() - we need to fflush */
5448 reset_traps_to_defaults();
5449 parse_and_run_string(s);
5450 _exit(G.last_exitcode);
5452 /* We re-execute after vfork on NOMMU. This makes this script safe:
5453 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5454 * huge=`cat BIG` # was blocking here forever
5457 re_execute_shell(&to_free,
5467 # if ENABLE_HUSH_FAST
5469 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5470 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5471 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5473 enable_restore_tty_pgrp_on_exit();
5478 close_on_exec_on(channel[0]);
5479 return xfdopen_for_read(channel[0]);
5482 /* Return code is exit status of the process that is run. */
5483 static int process_command_subs(o_string *dest, const char *s)
5486 struct in_str pipe_str;
5488 int status, ch, eol_cnt;
5490 fp = generate_stream_from_string(s, &pid);
5492 /* Now send results of command back into original context */
5493 setup_file_in_str(&pipe_str, fp);
5495 while ((ch = i_getch(&pipe_str)) != EOF) {
5501 o_addchr(dest, '\n');
5504 o_addQchr(dest, ch);
5507 debug_printf("done reading from `cmd` pipe, closing it\n");
5509 /* We need to extract exitcode. Test case
5510 * "true; echo `sleep 1; false` $?"
5512 safe_waitpid(pid, &status, 0);
5513 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5514 return WEXITSTATUS(status);
5516 #endif /* ENABLE_HUSH_TICK */
5519 static void setup_heredoc(struct redir_struct *redir)
5521 struct fd_pair pair;
5524 /* the _body_ of heredoc (misleading field name) */
5525 const char *heredoc = redir->rd_filename;
5532 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5533 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5537 len = strlen(heredoc);
5539 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5541 xmove_fd(pair.rd, redir->rd_fd);
5543 /* Try writing without forking. Newer kernels have
5544 * dynamically growing pipes. Must use non-blocking write! */
5547 written = write(pair.wr, heredoc, len);
5558 ndelay_off(pair.wr);
5560 /* Okay, pipe buffer was not big enough */
5561 /* Note: we must not create a stray child (bastard? :)
5562 * for the unsuspecting parent process. Child creates a grandchild
5563 * and exits before parent execs the process which consumes heredoc
5564 * (that exec happens after we return from this function) */
5571 disable_restore_tty_pgrp_on_exit();
5572 pid = BB_MMU ? xfork() : xvfork();
5576 close(redir->rd_fd); /* read side of the pipe */
5578 full_write(pair.wr, heredoc, len); /* may loop or block */
5581 /* Delegate blocking writes to another process */
5582 xmove_fd(pair.wr, STDOUT_FILENO);
5583 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5587 #if ENABLE_HUSH_FAST
5589 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5591 enable_restore_tty_pgrp_on_exit();
5597 wait(NULL); /* wait till child has died */
5600 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5601 * and stderr if they are redirected. */
5602 static int setup_redirects(struct command *prog, int squirrel[])
5605 struct redir_struct *redir;
5607 for (redir = prog->redirects; redir; redir = redir->next) {
5608 if (redir->rd_type == REDIRECT_HEREDOC2) {
5609 /* rd_fd<<HERE case */
5610 if (squirrel && redir->rd_fd < 3
5611 && squirrel[redir->rd_fd] < 0
5613 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5615 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5617 debug_printf_parse("set heredoc '%s'\n",
5618 redir->rd_filename);
5619 setup_heredoc(redir);
5623 if (redir->rd_dup == REDIRFD_TO_FILE) {
5624 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5626 if (redir->rd_filename == NULL) {
5627 /* Something went wrong in the parse.
5628 * Pretend it didn't happen */
5629 bb_error_msg("bug in redirect parse");
5632 mode = redir_table[redir->rd_type].mode;
5633 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5634 openfd = open_or_warn(p, mode);
5637 /* this could get lost if stderr has been redirected, but
5638 * bash and ash both lose it as well (though zsh doesn't!) */
5639 //what the above comment tries to say?
5643 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5644 openfd = redir->rd_dup;
5647 if (openfd != redir->rd_fd) {
5648 if (squirrel && redir->rd_fd < 3
5649 && squirrel[redir->rd_fd] < 0
5651 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5653 if (openfd == REDIRFD_CLOSE) {
5654 /* "n>-" means "close me" */
5655 close(redir->rd_fd);
5657 xdup2(openfd, redir->rd_fd);
5658 if (redir->rd_dup == REDIRFD_TO_FILE)
5666 static void restore_redirects(int squirrel[])
5669 for (i = 0; i < 3; i++) {
5672 /* We simply die on error */
5678 static char *find_in_path(const char *arg)
5681 const char *PATH = get_local_var_value("PATH");
5687 const char *end = strchrnul(PATH, ':');
5688 int sz = end - PATH; /* must be int! */
5692 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5694 /* We have xxx::yyyy in $PATH,
5695 * it means "use current dir" */
5698 if (access(ret, F_OK) == 0)
5711 static const struct built_in_command *find_builtin_helper(const char *name,
5712 const struct built_in_command *x,
5713 const struct built_in_command *end)
5716 if (strcmp(name, x->b_cmd) != 0) {
5720 debug_printf_exec("found builtin '%s'\n", name);
5725 static const struct built_in_command *find_builtin1(const char *name)
5727 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5729 static const struct built_in_command *find_builtin(const char *name)
5731 const struct built_in_command *x = find_builtin1(name);
5734 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5737 #if ENABLE_HUSH_FUNCTIONS
5738 static struct function **find_function_slot(const char *name)
5740 struct function **funcpp = &G.top_func;
5742 if (strcmp(name, (*funcpp)->name) == 0) {
5745 funcpp = &(*funcpp)->next;
5750 static const struct function *find_function(const char *name)
5752 const struct function *funcp = *find_function_slot(name);
5754 debug_printf_exec("found function '%s'\n", name);
5758 /* Note: takes ownership on name ptr */
5759 static struct function *new_function(char *name)
5761 struct function **funcpp = find_function_slot(name);
5762 struct function *funcp = *funcpp;
5764 if (funcp != NULL) {
5765 struct command *cmd = funcp->parent_cmd;
5766 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5768 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5770 /* Note: if !funcp->body, do not free body_as_string!
5771 * This is a special case of "-F name body" function:
5772 * body_as_string was not malloced! */
5774 free_pipe_list(funcp->body);
5776 free(funcp->body_as_string);
5780 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5781 cmd->argv[0] = funcp->name;
5782 cmd->group = funcp->body;
5784 cmd->group_as_string = funcp->body_as_string;
5788 debug_printf_exec("remembering new function '%s'\n", name);
5789 funcp = *funcpp = xzalloc(sizeof(*funcp));
5790 /*funcp->next = NULL;*/
5797 static void unset_func(const char *name)
5799 struct function **funcpp = find_function_slot(name);
5800 struct function *funcp = *funcpp;
5802 if (funcp != NULL) {
5803 debug_printf_exec("freeing function '%s'\n", funcp->name);
5804 *funcpp = funcp->next;
5805 /* funcp is unlinked now, deleting it.
5806 * Note: if !funcp->body, the function was created by
5807 * "-F name body", do not free ->body_as_string
5808 * and ->name as they were not malloced. */
5810 free_pipe_list(funcp->body);
5813 free(funcp->body_as_string);
5821 #define exec_function(to_free, funcp, argv) \
5822 exec_function(funcp, argv)
5824 static void exec_function(char ***to_free,
5825 const struct function *funcp,
5826 char **argv) NORETURN;
5827 static void exec_function(char ***to_free,
5828 const struct function *funcp,
5834 argv[0] = G.global_argv[0];
5835 G.global_argv = argv;
5839 /* On MMU, funcp->body is always non-NULL */
5840 n = run_list(funcp->body);
5844 re_execute_shell(to_free,
5845 funcp->body_as_string,
5852 static int run_function(const struct function *funcp, char **argv)
5858 save_and_replace_G_args(&sv, argv);
5860 /* "we are in function, ok to use return" */
5861 sv_flg = G.flag_return_in_progress;
5862 G.flag_return_in_progress = -1;
5863 # if ENABLE_HUSH_LOCAL
5864 G.func_nest_level++;
5867 /* On MMU, funcp->body is always non-NULL */
5870 /* Function defined by -F */
5871 parse_and_run_string(funcp->body_as_string);
5872 rc = G.last_exitcode;
5876 rc = run_list(funcp->body);
5879 # if ENABLE_HUSH_LOCAL
5881 struct variable *var;
5882 struct variable **var_pp;
5884 var_pp = &G.top_var;
5885 while ((var = *var_pp) != NULL) {
5886 if (var->func_nest_level < G.func_nest_level) {
5887 var_pp = &var->next;
5891 if (var->flg_export)
5892 bb_unsetenv(var->varstr);
5893 /* Remove from global list */
5894 *var_pp = var->next;
5900 G.func_nest_level--;
5903 G.flag_return_in_progress = sv_flg;
5905 restore_G_args(&sv, argv);
5909 #endif /* ENABLE_HUSH_FUNCTIONS */
5913 #define exec_builtin(to_free, x, argv) \
5914 exec_builtin(x, argv)
5916 #define exec_builtin(to_free, x, argv) \
5917 exec_builtin(to_free, argv)
5919 static void exec_builtin(char ***to_free,
5920 const struct built_in_command *x,
5921 char **argv) NORETURN;
5922 static void exec_builtin(char ***to_free,
5923 const struct built_in_command *x,
5927 int rcode = x->b_function(argv);
5931 /* On NOMMU, we must never block!
5932 * Example: { sleep 99 | read line; } & echo Ok
5934 re_execute_shell(to_free,
5943 static void execvp_or_die(char **argv) NORETURN;
5944 static void execvp_or_die(char **argv)
5946 debug_printf_exec("execing '%s'\n", argv[0]);
5947 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5948 execvp(argv[0], argv);
5949 bb_perror_msg("can't execute '%s'", argv[0]);
5950 _exit(127); /* bash compat */
5953 #if ENABLE_HUSH_MODE_X
5954 static void dump_cmd_in_x_mode(char **argv)
5956 if (G_x_mode && argv) {
5957 /* We want to output the line in one write op */
5965 len += strlen(argv[n++]) + 1;
5971 p += sprintf(p, " %s", argv[n++]);
5979 # define dump_cmd_in_x_mode(argv) ((void)0)
5983 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5984 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5985 #define pseudo_exec(nommu_save, command, argv_expanded) \
5986 pseudo_exec(command, argv_expanded)
5989 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5991 * Don't exit() here. If you don't exec, use _exit instead.
5992 * The at_exit handlers apparently confuse the calling process,
5993 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5994 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5995 char **argv, int assignment_cnt,
5996 char **argv_expanded) NORETURN;
5997 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5998 char **argv, int assignment_cnt,
5999 char **argv_expanded)
6003 new_env = expand_assignments(argv, assignment_cnt);
6004 dump_cmd_in_x_mode(new_env);
6006 if (!argv[assignment_cnt]) {
6007 /* Case when we are here: ... | var=val | ...
6008 * (note that we do not exit early, i.e., do not optimize out
6009 * expand_assignments(): think about ... | var=`sleep 1` | ...
6011 free_strings(new_env);
6012 _exit(EXIT_SUCCESS);
6016 set_vars_and_save_old(new_env);
6017 free(new_env); /* optional */
6018 /* we can also destroy set_vars_and_save_old's return value,
6021 nommu_save->new_env = new_env;
6022 nommu_save->old_vars = set_vars_and_save_old(new_env);
6025 if (argv_expanded) {
6026 argv = argv_expanded;
6028 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6030 nommu_save->argv = argv;
6033 dump_cmd_in_x_mode(argv);
6035 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6036 if (strchr(argv[0], '/') != NULL)
6040 /* Check if the command matches any of the builtins.
6041 * Depending on context, this might be redundant. But it's
6042 * easier to waste a few CPU cycles than it is to figure out
6043 * if this is one of those cases.
6046 /* On NOMMU, it is more expensive to re-execute shell
6047 * just in order to run echo or test builtin.
6048 * It's better to skip it here and run corresponding
6049 * non-builtin later. */
6050 const struct built_in_command *x;
6051 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6053 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6056 #if ENABLE_HUSH_FUNCTIONS
6057 /* Check if the command matches any functions */
6059 const struct function *funcp = find_function(argv[0]);
6061 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6066 #if ENABLE_FEATURE_SH_STANDALONE
6067 /* Check if the command matches any busybox applets */
6069 int a = find_applet_by_name(argv[0]);
6071 # if BB_MMU /* see above why on NOMMU it is not allowed */
6072 if (APPLET_IS_NOEXEC(a)) {
6073 debug_printf_exec("running applet '%s'\n", argv[0]);
6074 run_applet_no_and_exit(a, argv);
6077 /* Re-exec ourselves */
6078 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6079 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6080 execv(bb_busybox_exec_path, argv);
6081 /* If they called chroot or otherwise made the binary no longer
6082 * executable, fall through */
6087 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6090 execvp_or_die(argv);
6093 /* Called after [v]fork() in run_pipe
6095 static void pseudo_exec(nommu_save_t *nommu_save,
6096 struct command *command,
6097 char **argv_expanded) NORETURN;
6098 static void pseudo_exec(nommu_save_t *nommu_save,
6099 struct command *command,
6100 char **argv_expanded)
6102 if (command->argv) {
6103 pseudo_exec_argv(nommu_save, command->argv,
6104 command->assignment_cnt, argv_expanded);
6107 if (command->group) {
6108 /* Cases when we are here:
6111 * ... | ( list ) | ...
6112 * ... | { list } | ...
6116 debug_printf_exec("pseudo_exec: run_list\n");
6117 reset_traps_to_defaults();
6118 rcode = run_list(command->group);
6119 /* OK to leak memory by not calling free_pipe_list,
6120 * since this process is about to exit */
6123 re_execute_shell(&nommu_save->argv_from_re_execing,
6124 command->group_as_string,
6131 /* Case when we are here: ... | >file */
6132 debug_printf_exec("pseudo_exec'ed null command\n");
6133 _exit(EXIT_SUCCESS);
6137 static const char *get_cmdtext(struct pipe *pi)
6143 /* This is subtle. ->cmdtext is created only on first backgrounding.
6144 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6145 * On subsequent bg argv is trashed, but we won't use it */
6148 argv = pi->cmds[0].argv;
6149 if (!argv || !argv[0]) {
6150 pi->cmdtext = xzalloc(1);
6156 len += strlen(*argv) + 1;
6160 argv = pi->cmds[0].argv;
6162 len = strlen(*argv);
6163 memcpy(p, *argv, len);
6171 static void insert_bg_job(struct pipe *pi)
6173 struct pipe *job, **jobp;
6176 /* Linear search for the ID of the job to use */
6178 for (job = G.job_list; job; job = job->next)
6179 if (job->jobid >= pi->jobid)
6180 pi->jobid = job->jobid + 1;
6182 /* Add job to the list of running jobs */
6184 while ((job = *jobp) != NULL)
6186 job = *jobp = xmalloc(sizeof(*job));
6188 *job = *pi; /* physical copy */
6190 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6191 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6192 for (i = 0; i < pi->num_cmds; i++) {
6193 job->cmds[i].pid = pi->cmds[i].pid;
6194 /* all other fields are not used and stay zero */
6196 job->cmdtext = xstrdup(get_cmdtext(pi));
6198 if (G_interactive_fd)
6199 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6200 G.last_jobid = job->jobid;
6203 static void remove_bg_job(struct pipe *pi)
6205 struct pipe *prev_pipe;
6207 if (pi == G.job_list) {
6208 G.job_list = pi->next;
6210 prev_pipe = G.job_list;
6211 while (prev_pipe->next != pi)
6212 prev_pipe = prev_pipe->next;
6213 prev_pipe->next = pi->next;
6216 G.last_jobid = G.job_list->jobid;
6221 /* Remove a backgrounded job */
6222 static void delete_finished_bg_job(struct pipe *pi)
6229 /* Check to see if any processes have exited -- if they
6230 * have, figure out why and see if a job has completed */
6231 static int checkjobs(struct pipe *fg_pipe)
6241 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6243 attributes = WUNTRACED;
6244 if (fg_pipe == NULL)
6245 attributes |= WNOHANG;
6248 #if ENABLE_HUSH_FAST
6249 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6250 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6251 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6252 /* There was neither fork nor SIGCHLD since last waitpid */
6253 /* Avoid doing waitpid syscall if possible */
6254 if (!G.we_have_children) {
6258 if (fg_pipe == NULL) { /* is WNOHANG set? */
6259 /* We have children, but they did not exit
6260 * or stop yet (we saw no SIGCHLD) */
6263 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6267 /* Do we do this right?
6268 * bash-3.00# sleep 20 | false
6270 * [3]+ Stopped sleep 20 | false
6271 * bash-3.00# echo $?
6272 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6273 * [hush 1.14.0: yes we do it right]
6280 #if ENABLE_HUSH_FAST
6281 i = G.count_SIGCHLD;
6283 childpid = waitpid(-1, &status, attributes);
6284 if (childpid <= 0) {
6285 if (childpid && errno != ECHILD)
6286 bb_perror_msg("waitpid");
6287 #if ENABLE_HUSH_FAST
6288 else { /* Until next SIGCHLD, waitpid's are useless */
6289 G.we_have_children = (childpid == 0);
6290 G.handled_SIGCHLD = i;
6291 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6296 dead = WIFEXITED(status) || WIFSIGNALED(status);
6299 if (WIFSTOPPED(status))
6300 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6301 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6302 if (WIFSIGNALED(status))
6303 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6304 childpid, WTERMSIG(status), WEXITSTATUS(status));
6305 if (WIFEXITED(status))
6306 debug_printf_jobs("pid %d exited, exitcode %d\n",
6307 childpid, WEXITSTATUS(status));
6309 /* Were we asked to wait for fg pipe? */
6311 for (i = 0; i < fg_pipe->num_cmds; i++) {
6312 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6313 if (fg_pipe->cmds[i].pid != childpid)
6316 fg_pipe->cmds[i].pid = 0;
6317 fg_pipe->alive_cmds--;
6318 if (i == fg_pipe->num_cmds - 1) {
6319 /* last process gives overall exitstatus */
6320 rcode = WEXITSTATUS(status);
6321 /* bash prints killer signal's name for *last*
6322 * process in pipe (prints just newline for SIGINT).
6323 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6325 if (WIFSIGNALED(status)) {
6326 int sig = WTERMSIG(status);
6327 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6328 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6329 * Maybe we need to use sig | 128? */
6332 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6335 fg_pipe->cmds[i].is_stopped = 1;
6336 fg_pipe->stopped_cmds++;
6338 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6339 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6340 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6341 /* All processes in fg pipe have exited or stopped */
6342 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6343 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6344 * and "killall -STOP cat" */
6345 if (G_interactive_fd) {
6347 if (fg_pipe->alive_cmds)
6348 insert_bg_job(fg_pipe);
6352 if (!fg_pipe->alive_cmds)
6355 /* There are still running processes in the fg pipe */
6356 goto wait_more; /* do waitpid again */
6358 /* it wasnt fg_pipe, look for process in bg pipes */
6362 /* We asked to wait for bg or orphaned children */
6363 /* No need to remember exitcode in this case */
6364 for (pi = G.job_list; pi; pi = pi->next) {
6365 for (i = 0; i < pi->num_cmds; i++) {
6366 if (pi->cmds[i].pid == childpid)
6367 goto found_pi_and_prognum;
6370 /* Happens when shell is used as init process (init=/bin/sh) */
6371 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6372 continue; /* do waitpid again */
6374 found_pi_and_prognum:
6377 pi->cmds[i].pid = 0;
6379 if (!pi->alive_cmds) {
6380 if (G_interactive_fd)
6381 printf(JOB_STATUS_FORMAT, pi->jobid,
6382 "Done", pi->cmdtext);
6383 delete_finished_bg_job(pi);
6387 pi->cmds[i].is_stopped = 1;
6391 } /* while (waitpid succeeds)... */
6397 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6400 int rcode = checkjobs(fg_pipe);
6401 if (G_saved_tty_pgrp) {
6402 /* Job finished, move the shell to the foreground */
6403 p = getpgrp(); /* our process group id */
6404 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6405 tcsetpgrp(G_interactive_fd, p);
6411 /* Start all the jobs, but don't wait for anything to finish.
6414 * Return code is normally -1, when the caller has to wait for children
6415 * to finish to determine the exit status of the pipe. If the pipe
6416 * is a simple builtin command, however, the action is done by the
6417 * time run_pipe returns, and the exit code is provided as the
6420 * Returns -1 only if started some children. IOW: we have to
6421 * mask out retvals of builtins etc with 0xff!
6423 * The only case when we do not need to [v]fork is when the pipe
6424 * is single, non-backgrounded, non-subshell command. Examples:
6425 * cmd ; ... { list } ; ...
6426 * cmd && ... { list } && ...
6427 * cmd || ... { list } || ...
6428 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6429 * or (if SH_STANDALONE) an applet, and we can run the { list }
6430 * with run_list. If it isn't one of these, we fork and exec cmd.
6432 * Cases when we must fork:
6433 * non-single: cmd | cmd
6434 * backgrounded: cmd & { list } &
6435 * subshell: ( list ) [&]
6437 #if !ENABLE_HUSH_MODE_X
6438 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6439 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6441 static int redirect_and_varexp_helper(char ***new_env_p,
6442 struct variable **old_vars_p,
6443 struct command *command,
6445 char **argv_expanded)
6447 /* setup_redirects acts on file descriptors, not FILEs.
6448 * This is perfect for work that comes after exec().
6449 * Is it really safe for inline use? Experimentally,
6450 * things seem to work. */
6451 int rcode = setup_redirects(command, squirrel);
6453 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6454 *new_env_p = new_env;
6455 dump_cmd_in_x_mode(new_env);
6456 dump_cmd_in_x_mode(argv_expanded);
6458 *old_vars_p = set_vars_and_save_old(new_env);
6462 static NOINLINE int run_pipe(struct pipe *pi)
6464 static const char *const null_ptr = NULL;
6468 struct command *command;
6469 char **argv_expanded;
6471 /* it is not always needed, but we aim to smaller code */
6472 int squirrel[] = { -1, -1, -1 };
6475 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6478 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6479 * Result should be 3 lines: q w e, qwe, q w e
6481 G.ifs = get_local_var_value("IFS");
6485 IF_HUSH_JOB(pi->pgrp = -1;)
6486 pi->stopped_cmds = 0;
6487 command = &pi->cmds[0];
6488 argv_expanded = NULL;
6490 if (pi->num_cmds != 1
6491 || pi->followup == PIPE_BG
6492 || command->cmd_type == CMD_SUBSHELL
6499 debug_printf_exec(": group:%p argv:'%s'\n",
6500 command->group, command->argv ? command->argv[0] : "NONE");
6502 if (command->group) {
6503 #if ENABLE_HUSH_FUNCTIONS
6504 if (command->cmd_type == CMD_FUNCDEF) {
6505 /* "executing" func () { list } */
6506 struct function *funcp;
6508 funcp = new_function(command->argv[0]);
6509 /* funcp->name is already set to argv[0] */
6510 funcp->body = command->group;
6512 funcp->body_as_string = command->group_as_string;
6513 command->group_as_string = NULL;
6515 command->group = NULL;
6516 command->argv[0] = NULL;
6517 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6518 funcp->parent_cmd = command;
6519 command->child_func = funcp;
6521 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6523 return EXIT_SUCCESS;
6527 debug_printf("non-subshell group\n");
6528 rcode = 1; /* exitcode if redir failed */
6529 if (setup_redirects(command, squirrel) == 0) {
6530 debug_printf_exec(": run_list\n");
6531 rcode = run_list(command->group) & 0xff;
6533 restore_redirects(squirrel);
6534 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6536 debug_printf_exec("run_pipe: return %d\n", rcode);
6540 argv = command->argv ? command->argv : (char **) &null_ptr;
6542 const struct built_in_command *x;
6543 #if ENABLE_HUSH_FUNCTIONS
6544 const struct function *funcp;
6548 char **new_env = NULL;
6549 struct variable *old_vars = NULL;
6551 if (argv[command->assignment_cnt] == NULL) {
6552 /* Assignments, but no command */
6553 /* Ensure redirects take effect (that is, create files).
6554 * Try "a=t >file" */
6555 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6556 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6557 /* Set shell variables */
6561 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6562 /* Do we need to flag set_local_var() errors?
6563 * "assignment to readonly var" and "putenv error"
6568 /* Redirect error sets $? to 1. Otherwise,
6569 * if evaluating assignment value set $?, retain it.
6570 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6572 rcode = G.last_exitcode;
6573 /* Exit, _skipping_ variable restoring code: */
6574 goto clean_up_and_ret0;
6576 #else /* Older, bigger, but more correct code */
6578 rcode = setup_redirects(command, squirrel);
6579 restore_redirects(squirrel);
6580 /* Set shell variables */
6582 bb_putchar_stderr('+');
6584 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6586 fprintf(stderr, " %s", p);
6587 debug_printf_exec("set shell var:'%s'->'%s'\n",
6589 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6590 /* Do we need to flag set_local_var() errors?
6591 * "assignment to readonly var" and "putenv error"
6596 bb_putchar_stderr('\n');
6597 /* Redirect error sets $? to 1. Otherwise,
6598 * if evaluating assignment value set $?, retain it.
6599 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6601 rcode = G.last_exitcode;
6602 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6604 debug_printf_exec("run_pipe: return %d\n", rcode);
6609 /* Expand the rest into (possibly) many strings each */
6611 #if ENABLE_HUSH_BASH_COMPAT
6612 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6613 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6617 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6620 /* if someone gives us an empty string: `cmd with empty output` */
6621 if (!argv_expanded[0]) {
6622 free(argv_expanded);
6624 return G.last_exitcode;
6627 x = find_builtin(argv_expanded[0]);
6628 #if ENABLE_HUSH_FUNCTIONS
6631 funcp = find_function(argv_expanded[0]);
6635 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6636 debug_printf("exec with redirects only\n");
6637 rcode = setup_redirects(command, NULL);
6638 goto clean_up_and_ret1;
6641 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6644 debug_printf_exec(": builtin '%s' '%s'...\n",
6645 x->b_cmd, argv_expanded[1]);
6646 rcode = x->b_function(argv_expanded) & 0xff;
6649 #if ENABLE_HUSH_FUNCTIONS
6651 # if ENABLE_HUSH_LOCAL
6652 struct variable **sv;
6653 sv = G.shadowed_vars_pp;
6654 G.shadowed_vars_pp = &old_vars;
6656 debug_printf_exec(": function '%s' '%s'...\n",
6657 funcp->name, argv_expanded[1]);
6658 rcode = run_function(funcp, argv_expanded) & 0xff;
6659 # if ENABLE_HUSH_LOCAL
6660 G.shadowed_vars_pp = sv;
6666 unset_vars(new_env);
6668 /* clean_up_and_ret0: */
6669 restore_redirects(squirrel);
6671 free(argv_expanded);
6672 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6674 debug_printf_exec("run_pipe return %d\n", rcode);
6678 if (ENABLE_FEATURE_SH_STANDALONE) {
6679 int n = find_applet_by_name(argv_expanded[0]);
6680 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6681 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6683 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6684 argv_expanded[0], argv_expanded[1]);
6685 rcode = run_nofork_applet(n, argv_expanded);
6687 goto clean_up_and_ret;
6690 /* It is neither builtin nor applet. We must fork. */
6694 /* NB: argv_expanded may already be created, and that
6695 * might include `cmd` runs! Do not rerun it! We *must*
6696 * use argv_expanded if it's non-NULL */
6698 /* Going to fork a child per each pipe member */
6703 while (cmd_no < pi->num_cmds) {
6704 struct fd_pair pipefds;
6706 volatile nommu_save_t nommu_save;
6707 nommu_save.new_env = NULL;
6708 nommu_save.old_vars = NULL;
6709 nommu_save.argv = NULL;
6710 nommu_save.argv_from_re_execing = NULL;
6712 command = &pi->cmds[cmd_no];
6714 if (command->argv) {
6715 debug_printf_exec(": pipe member '%s' '%s'...\n",
6716 command->argv[0], command->argv[1]);
6718 debug_printf_exec(": pipe member with no argv\n");
6721 /* pipes are inserted between pairs of commands */
6724 if (cmd_no < pi->num_cmds)
6725 xpiped_pair(pipefds);
6727 command->pid = BB_MMU ? fork() : vfork();
6728 if (!command->pid) { /* child */
6730 disable_restore_tty_pgrp_on_exit();
6731 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6733 /* Every child adds itself to new process group
6734 * with pgid == pid_of_first_child_in_pipe */
6735 if (G.run_list_level == 1 && G_interactive_fd) {
6738 if (pgrp < 0) /* true for 1st process only */
6740 if (setpgid(0, pgrp) == 0
6741 && pi->followup != PIPE_BG
6742 && G_saved_tty_pgrp /* we have ctty */
6744 /* We do it in *every* child, not just first,
6746 tcsetpgrp(G_interactive_fd, pgrp);
6750 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6751 /* 1st cmd in backgrounded pipe
6752 * should have its stdin /dev/null'ed */
6754 if (open(bb_dev_null, O_RDONLY))
6755 xopen("/", O_RDONLY);
6757 xmove_fd(next_infd, 0);
6759 xmove_fd(pipefds.wr, 1);
6762 /* Like bash, explicit redirects override pipes,
6763 * and the pipe fd is available for dup'ing. */
6764 if (setup_redirects(command, NULL))
6767 /* Restore default handlers just prior to exec */
6768 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6770 /* Stores to nommu_save list of env vars putenv'ed
6771 * (NOMMU, on MMU we don't need that) */
6772 /* cast away volatility... */
6773 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6774 /* pseudo_exec() does not return */
6777 /* parent or error */
6778 #if ENABLE_HUSH_FAST
6780 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6782 enable_restore_tty_pgrp_on_exit();
6784 /* Clean up after vforked child */
6785 free(nommu_save.argv);
6786 free(nommu_save.argv_from_re_execing);
6787 unset_vars(nommu_save.new_env);
6788 add_vars(nommu_save.old_vars);
6790 free(argv_expanded);
6791 argv_expanded = NULL;
6792 if (command->pid < 0) { /* [v]fork failed */
6793 /* Clearly indicate, was it fork or vfork */
6794 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6798 /* Second and next children need to know pid of first one */
6800 pi->pgrp = command->pid;
6806 if (cmd_no < pi->num_cmds)
6808 /* Pass read (output) pipe end to next iteration */
6809 next_infd = pipefds.rd;
6812 if (!pi->alive_cmds) {
6814 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6819 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6823 #ifndef debug_print_tree
6824 static void debug_print_tree(struct pipe *pi, int lvl)
6826 static const char *const PIPE[] = {
6832 static const char *RES[] = {
6833 [RES_NONE ] = "NONE" ,
6836 [RES_THEN ] = "THEN" ,
6837 [RES_ELIF ] = "ELIF" ,
6838 [RES_ELSE ] = "ELSE" ,
6841 # if ENABLE_HUSH_LOOPS
6842 [RES_FOR ] = "FOR" ,
6843 [RES_WHILE] = "WHILE",
6844 [RES_UNTIL] = "UNTIL",
6846 [RES_DONE ] = "DONE" ,
6848 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6851 # if ENABLE_HUSH_CASE
6852 [RES_CASE ] = "CASE" ,
6853 [RES_CASE_IN ] = "CASE_IN" ,
6854 [RES_MATCH] = "MATCH",
6855 [RES_CASE_BODY] = "CASE_BODY",
6856 [RES_ESAC ] = "ESAC" ,
6858 [RES_XXXX ] = "XXXX" ,
6859 [RES_SNTX ] = "SNTX" ,
6861 static const char *const CMDTYPE[] = {
6865 # if ENABLE_HUSH_FUNCTIONS
6874 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6875 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6877 while (prn < pi->num_cmds) {
6878 struct command *command = &pi->cmds[prn];
6879 char **argv = command->argv;
6881 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6883 command->assignment_cnt);
6884 if (command->group) {
6885 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6886 CMDTYPE[command->cmd_type],
6889 , " group_as_string:", command->group_as_string
6894 debug_print_tree(command->group, lvl+1);
6898 if (argv) while (*argv) {
6899 fprintf(stderr, " '%s'", *argv);
6902 fprintf(stderr, "\n");
6909 #endif /* debug_print_tree */
6911 /* NB: called by pseudo_exec, and therefore must not modify any
6912 * global data until exec/_exit (we can be a child after vfork!) */
6913 static int run_list(struct pipe *pi)
6915 #if ENABLE_HUSH_CASE
6916 char *case_word = NULL;
6918 #if ENABLE_HUSH_LOOPS
6919 struct pipe *loop_top = NULL;
6920 char **for_lcur = NULL;
6921 char **for_list = NULL;
6923 smallint last_followup;
6925 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6926 smalluint cond_code = 0;
6928 enum { cond_code = 0 };
6931 smallint rword; /* RES_foo */
6932 smallint last_rword; /* ditto */
6935 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6938 #if ENABLE_HUSH_LOOPS
6939 /* Check syntax for "for" */
6940 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6941 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6943 /* current word is FOR or IN (BOLD in comments below) */
6944 if (cpipe->next == NULL) {
6945 syntax_error("malformed for");
6947 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6950 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6951 if (cpipe->next->res_word == RES_DO)
6953 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6954 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6955 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6957 syntax_error("malformed for");
6959 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6965 /* Past this point, all code paths should jump to ret: label
6966 * in order to return, no direct "return" statements please.
6967 * This helps to ensure that no memory is leaked. */
6975 last_rword = RES_XXXX;
6977 last_followup = PIPE_SEQ;
6978 rcode = G.last_exitcode;
6980 /* Go through list of pipes, (maybe) executing them. */
6981 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6985 IF_HAS_KEYWORDS(rword = pi->res_word;)
6986 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6987 rword, cond_code, last_rword);
6988 #if ENABLE_HUSH_LOOPS
6989 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6990 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6992 /* start of a loop: remember where loop starts */
6997 /* Still in the same "if...", "then..." or "do..." branch? */
6998 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6999 if ((rcode == 0 && last_followup == PIPE_OR)
7000 || (rcode != 0 && last_followup == PIPE_AND)
7002 /* It is "<true> || CMD" or "<false> && CMD"
7003 * and we should not execute CMD */
7004 debug_printf_exec("skipped cmd because of || or &&\n");
7005 last_followup = pi->followup;
7009 last_followup = pi->followup;
7010 IF_HAS_KEYWORDS(last_rword = rword;)
7013 if (rword == RES_THEN) {
7014 /* if false; then ... fi has exitcode 0! */
7015 G.last_exitcode = rcode = EXIT_SUCCESS;
7016 /* "if <false> THEN cmd": skip cmd */
7020 if (rword == RES_ELSE || rword == RES_ELIF) {
7021 /* "if <true> then ... ELSE/ELIF cmd":
7022 * skip cmd and all following ones */
7027 #if ENABLE_HUSH_LOOPS
7028 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7030 /* first loop through for */
7032 static const char encoded_dollar_at[] ALIGN1 = {
7033 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7034 }; /* encoded representation of "$@" */
7035 static const char *const encoded_dollar_at_argv[] = {
7036 encoded_dollar_at, NULL
7037 }; /* argv list with one element: "$@" */
7040 vals = (char**)encoded_dollar_at_argv;
7041 if (pi->next->res_word == RES_IN) {
7042 /* if no variable values after "in" we skip "for" */
7043 if (!pi->next->cmds[0].argv) {
7044 G.last_exitcode = rcode = EXIT_SUCCESS;
7045 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7048 vals = pi->next->cmds[0].argv;
7049 } /* else: "for var; do..." -> assume "$@" list */
7050 /* create list of variable values */
7051 debug_print_strings("for_list made from", vals);
7052 for_list = expand_strvec_to_strvec(vals);
7053 for_lcur = for_list;
7054 debug_print_strings("for_list", for_list);
7057 /* "for" loop is over, clean up */
7063 /* Insert next value from for_lcur */
7064 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7065 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7068 if (rword == RES_IN) {
7069 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7071 if (rword == RES_DONE) {
7072 continue; /* "done" has no cmds too */
7075 #if ENABLE_HUSH_CASE
7076 if (rword == RES_CASE) {
7077 case_word = expand_strvec_to_string(pi->cmds->argv);
7080 if (rword == RES_MATCH) {
7083 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7085 /* all prev words didn't match, does this one match? */
7086 argv = pi->cmds->argv;
7088 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7089 /* TODO: which FNM_xxx flags to use? */
7090 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7092 if (cond_code == 0) { /* match! we will execute this branch */
7093 free(case_word); /* make future "word)" stop */
7101 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7103 continue; /* not matched yet, skip this pipe */
7106 /* Just pressing <enter> in shell should check for jobs.
7107 * OTOH, in non-interactive shell this is useless
7108 * and only leads to extra job checks */
7109 if (pi->num_cmds == 0) {
7110 if (G_interactive_fd)
7111 goto check_jobs_and_continue;
7115 /* After analyzing all keywords and conditions, we decided
7116 * to execute this pipe. NB: have to do checkjobs(NULL)
7117 * after run_pipe to collect any background children,
7118 * even if list execution is to be stopped. */
7119 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7122 #if ENABLE_HUSH_LOOPS
7123 G.flag_break_continue = 0;
7125 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7127 /* We ran a builtin, function, or group.
7128 * rcode is already known
7129 * and we don't need to wait for anything. */
7130 G.last_exitcode = rcode;
7131 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7132 check_and_run_traps(0);
7133 #if ENABLE_HUSH_LOOPS
7134 /* Was it "break" or "continue"? */
7135 if (G.flag_break_continue) {
7136 smallint fbc = G.flag_break_continue;
7137 /* We might fall into outer *loop*,
7138 * don't want to break it too */
7140 G.depth_break_continue--;
7141 if (G.depth_break_continue == 0)
7142 G.flag_break_continue = 0;
7143 /* else: e.g. "continue 2" should *break* once, *then* continue */
7144 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7145 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7146 goto check_jobs_and_break;
7147 /* "continue": simulate end of loop */
7152 #if ENABLE_HUSH_FUNCTIONS
7153 if (G.flag_return_in_progress == 1) {
7154 /* same as "goto check_jobs_and_break" */
7159 } else if (pi->followup == PIPE_BG) {
7160 /* What does bash do with attempts to background builtins? */
7161 /* even bash 3.2 doesn't do that well with nested bg:
7162 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7163 * I'm NOT treating inner &'s as jobs */
7164 check_and_run_traps(0);
7166 if (G.run_list_level == 1)
7169 /* Last command's pid goes to $! */
7170 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7171 G.last_exitcode = rcode = EXIT_SUCCESS;
7172 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7175 if (G.run_list_level == 1 && G_interactive_fd) {
7176 /* Waits for completion, then fg's main shell */
7177 rcode = checkjobs_and_fg_shell(pi);
7178 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7179 check_and_run_traps(0);
7182 { /* This one just waits for completion */
7183 rcode = checkjobs(pi);
7184 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7185 check_and_run_traps(0);
7187 G.last_exitcode = rcode;
7191 /* Analyze how result affects subsequent commands */
7193 if (rword == RES_IF || rword == RES_ELIF)
7196 #if ENABLE_HUSH_LOOPS
7197 /* Beware of "while false; true; do ..."! */
7198 if (pi->next && pi->next->res_word == RES_DO) {
7199 if (rword == RES_WHILE) {
7201 /* "while false; do...done" - exitcode 0 */
7202 G.last_exitcode = rcode = EXIT_SUCCESS;
7203 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7204 goto check_jobs_and_break;
7207 if (rword == RES_UNTIL) {
7209 debug_printf_exec(": until expr is true: breaking\n");
7210 check_jobs_and_break:
7218 check_jobs_and_continue:
7225 #if ENABLE_HUSH_LOOPS
7230 #if ENABLE_HUSH_CASE
7234 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7238 /* Select which version we will use */
7239 static int run_and_free_list(struct pipe *pi)
7242 debug_printf_exec("run_and_free_list entered\n");
7244 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7245 rcode = run_list(pi);
7247 /* free_pipe_list has the side effect of clearing memory.
7248 * In the long run that function can be merged with run_list,
7249 * but doing that now would hobble the debugging effort. */
7251 debug_printf_exec("run_and_free_list return %d\n", rcode);
7256 /* Called a few times only (or even once if "sh -c") */
7257 static void init_sigmasks(void)
7261 sigset_t old_blocked_set;
7263 if (!G.inherited_set_is_saved) {
7264 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7265 G.inherited_set = G.blocked_set;
7267 old_blocked_set = G.blocked_set;
7269 mask = (1 << SIGQUIT);
7270 if (G_interactive_fd) {
7271 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7272 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7273 mask |= SPECIAL_JOB_SIGS;
7275 G.non_DFL_mask = mask;
7280 sigaddset(&G.blocked_set, sig);
7284 sigdelset(&G.blocked_set, SIGCHLD);
7286 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7287 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7289 /* POSIX allows shell to re-enable SIGCHLD
7290 * even if it was SIG_IGN on entry */
7291 #if ENABLE_HUSH_FAST
7292 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7293 if (!G.inherited_set_is_saved)
7294 signal(SIGCHLD, SIGCHLD_handler);
7296 if (!G.inherited_set_is_saved)
7297 signal(SIGCHLD, SIG_DFL);
7300 G.inherited_set_is_saved = 1;
7305 static void maybe_set_to_sigexit(int sig)
7307 void (*handler)(int);
7308 /* non_DFL_mask'ed signals are, well, masked,
7309 * no need to set handler for them.
7311 if (!((G.non_DFL_mask >> sig) & 1)) {
7312 handler = signal(sig, sigexit);
7313 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7314 signal(sig, handler);
7317 /* Set handlers to restore tty pgrp and exit */
7318 static void set_fatal_handlers(void)
7320 /* We _must_ restore tty pgrp on fatal signals */
7322 maybe_set_to_sigexit(SIGILL );
7323 maybe_set_to_sigexit(SIGFPE );
7324 maybe_set_to_sigexit(SIGBUS );
7325 maybe_set_to_sigexit(SIGSEGV);
7326 maybe_set_to_sigexit(SIGTRAP);
7327 } /* else: hush is perfect. what SEGV? */
7328 maybe_set_to_sigexit(SIGABRT);
7329 /* bash 3.2 seems to handle these just like 'fatal' ones */
7330 maybe_set_to_sigexit(SIGPIPE);
7331 maybe_set_to_sigexit(SIGALRM);
7332 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7333 * if we aren't interactive... but in this case
7334 * we never want to restore pgrp on exit, and this fn is not called */
7335 /*maybe_set_to_sigexit(SIGHUP );*/
7336 /*maybe_set_to_sigexit(SIGTERM);*/
7337 /*maybe_set_to_sigexit(SIGINT );*/
7341 static int set_mode(const char cstate, const char mode)
7343 int state = (cstate == '-' ? 1 : 0);
7345 case 'n': G.n_mode = state; break;
7346 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7347 default: return EXIT_FAILURE;
7349 return EXIT_SUCCESS;
7352 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7353 int hush_main(int argc, char **argv)
7356 unsigned builtin_argc;
7358 struct variable *cur_var;
7359 struct variable shell_ver;
7362 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7363 G.last_exitcode = EXIT_SUCCESS;
7365 G.argv0_for_re_execing = argv[0];
7367 /* Deal with HUSH_VERSION */
7368 memset(&shell_ver, 0, sizeof(shell_ver));
7369 shell_ver.flg_export = 1;
7370 shell_ver.flg_read_only = 1;
7371 /* Code which handles ${var<op>...} needs writable values for all variables,
7372 * therefore we xstrdup: */
7373 shell_ver.varstr = xstrdup(hush_version_str),
7374 G.top_var = &shell_ver;
7375 /* Create shell local variables from the values
7376 * currently living in the environment */
7377 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7378 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7379 cur_var = G.top_var;
7382 char *value = strchr(*e, '=');
7383 if (value) { /* paranoia */
7384 cur_var->next = xzalloc(sizeof(*cur_var));
7385 cur_var = cur_var->next;
7386 cur_var->varstr = *e;
7387 cur_var->max_len = strlen(*e);
7388 cur_var->flg_export = 1;
7392 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7393 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7394 putenv(shell_ver.varstr);
7397 set_pwd_var(/*exp:*/ 1);
7398 /* bash also exports SHLVL and _,
7399 * and sets (but doesn't export) the following variables:
7401 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7402 * BASH_VERSION='3.2.0(1)-release'
7404 * MACHTYPE=i386-pc-linux-gnu
7406 * HOSTNAME=<xxxxxxxxxx>
7407 * PPID=<NNNNN> - we also do it elsewhere
7418 * PIPESTATUS=([0]="0")
7419 * HISTFILE=/<xxx>/.bash_history
7423 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7425 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7435 #if ENABLE_FEATURE_EDITING
7436 G.line_input_state = new_line_input_t(FOR_SHELL);
7437 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7439 const char *hp = get_local_var_value("HISTFILE");
7441 hp = get_local_var_value("HOME");
7443 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7444 //set_local_var(xasprintf("HISTFILE=%s", ...));
7451 G.global_argc = argc;
7452 G.global_argv = argv;
7453 /* Initialize some more globals to non-zero values */
7454 cmdedit_update_prompt();
7456 if (setjmp(die_jmp)) {
7457 /* xfunc has failed! die die die */
7458 /* no EXIT traps, this is an escape hatch! */
7460 hush_exit(xfunc_error_retval);
7463 /* Shell is non-interactive at first. We need to call
7464 * init_sigmasks() if we are going to execute "sh <script>",
7465 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7466 * If we later decide that we are interactive, we run init_sigmasks()
7467 * in order to intercept (more) signals.
7471 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7474 opt = getopt(argc, argv, "+c:xins"
7477 # if ENABLE_HUSH_FUNCTIONS
7487 * sh ... -c 'script'
7488 * sh ... -c 'script' ARG0 [ARG1...]
7489 * On NOMMU, if builtin_argc != 0,
7490 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7491 * "" needs to be replaced with NULL
7492 * and BARGV vector fed to builtin function.
7493 * Note: the form without ARG0 never happens:
7494 * sh ... -c 'builtin' BARGV... ""
7497 G.root_pid = getpid();
7498 G.root_ppid = getppid();
7500 G.global_argv = argv + optind;
7501 G.global_argc = argc - optind;
7503 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7504 const struct built_in_command *x;
7507 x = find_builtin(optarg);
7508 if (x) { /* paranoia */
7509 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7510 G.global_argv += builtin_argc;
7511 G.global_argv[-1] = NULL; /* replace "" */
7512 G.last_exitcode = x->b_function(argv + optind - 1);
7516 if (!G.global_argv[0]) {
7517 /* -c 'script' (no params): prevent empty $0 */
7518 G.global_argv--; /* points to argv[i] of 'script' */
7519 G.global_argv[0] = argv[0];
7521 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7523 parse_and_run_string(optarg);
7526 /* Well, we cannot just declare interactiveness,
7527 * we have to have some stuff (ctty, etc) */
7528 /* G_interactive_fd++; */
7531 /* "-s" means "read from stdin", but this is how we always
7532 * operate, so simply do nothing here. */
7535 case '<': /* "big heredoc" support */
7536 full_write1_str(optarg);
7539 unsigned long long empty_trap_mask;
7541 G.root_pid = bb_strtou(optarg, &optarg, 16);
7543 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7545 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7547 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7549 builtin_argc = bb_strtou(optarg, &optarg, 16);
7551 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7552 if (empty_trap_mask != 0) {
7555 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7556 for (sig = 1; sig < NSIG; sig++) {
7557 if (empty_trap_mask & (1LL << sig)) {
7558 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7559 sigaddset(&G.blocked_set, sig);
7562 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7564 # if ENABLE_HUSH_LOOPS
7566 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7572 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7574 # if ENABLE_HUSH_FUNCTIONS
7576 struct function *funcp = new_function(optarg);
7577 /* funcp->name is already set to optarg */
7578 /* funcp->body is set to NULL. It's a special case. */
7579 funcp->body_as_string = argv[optind];
7587 if (set_mode('-', opt) == 0) /* no error */
7591 fprintf(stderr, "Usage: sh [FILE]...\n"
7592 " or: sh -c command [args]...\n\n");
7598 } /* option parsing loop */
7601 G.root_pid = getpid();
7602 G.root_ppid = getppid();
7605 /* If we are login shell... */
7606 if (argv[0] && argv[0][0] == '-') {
7608 debug_printf("sourcing /etc/profile\n");
7609 input = fopen_for_read("/etc/profile");
7610 if (input != NULL) {
7611 close_on_exec_on(fileno(input));
7613 parse_and_run_file(input);
7616 /* bash: after sourcing /etc/profile,
7617 * tries to source (in the given order):
7618 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7619 * stopping on first found. --noprofile turns this off.
7620 * bash also sources ~/.bash_logout on exit.
7621 * If called as sh, skips .bash_XXX files.
7628 * "bash <script>" (which is never interactive (unless -i?))
7629 * sources $BASH_ENV here (without scanning $PATH).
7630 * If called as sh, does the same but with $ENV.
7632 debug_printf("running script '%s'\n", argv[optind]);
7633 G.global_argv = argv + optind;
7634 G.global_argc = argc - optind;
7635 input = xfopen_for_read(argv[optind]);
7636 close_on_exec_on(fileno(input));
7638 parse_and_run_file(input);
7639 #if ENABLE_FEATURE_CLEAN_UP
7645 /* Up to here, shell was non-interactive. Now it may become one.
7646 * NB: don't forget to (re)run init_sigmasks() as needed.
7649 /* A shell is interactive if the '-i' flag was given,
7650 * or if all of the following conditions are met:
7652 * no arguments remaining or the -s flag given
7653 * standard input is a terminal
7654 * standard output is a terminal
7655 * Refer to Posix.2, the description of the 'sh' utility.
7658 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7659 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7660 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7661 if (G_saved_tty_pgrp < 0)
7662 G_saved_tty_pgrp = 0;
7664 /* try to dup stdin to high fd#, >= 255 */
7665 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7666 if (G_interactive_fd < 0) {
7667 /* try to dup to any fd */
7668 G_interactive_fd = dup(STDIN_FILENO);
7669 if (G_interactive_fd < 0) {
7671 G_interactive_fd = 0;
7672 G_saved_tty_pgrp = 0;
7675 // TODO: track & disallow any attempts of user
7676 // to (inadvertently) close/redirect G_interactive_fd
7678 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7679 if (G_interactive_fd) {
7680 close_on_exec_on(G_interactive_fd);
7682 if (G_saved_tty_pgrp) {
7683 /* If we were run as 'hush &', sleep until we are
7684 * in the foreground (tty pgrp == our pgrp).
7685 * If we get started under a job aware app (like bash),
7686 * make sure we are now in charge so we don't fight over
7687 * who gets the foreground */
7689 pid_t shell_pgrp = getpgrp();
7690 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7691 if (G_saved_tty_pgrp == shell_pgrp)
7693 /* send TTIN to ourself (should stop us) */
7694 kill(- shell_pgrp, SIGTTIN);
7698 /* Block some signals */
7701 if (G_saved_tty_pgrp) {
7702 /* Set other signals to restore saved_tty_pgrp */
7703 set_fatal_handlers();
7704 /* Put ourselves in our own process group
7705 * (bash, too, does this only if ctty is available) */
7706 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7707 /* Grab control of the terminal */
7708 tcsetpgrp(G_interactive_fd, getpid());
7710 /* -1 is special - makes xfuncs longjmp, not exit
7711 * (we reset die_sleep = 0 whereever we [v]fork) */
7712 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7716 #elif ENABLE_HUSH_INTERACTIVE
7717 /* No job control compiled in, only prompt/line editing */
7718 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7719 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7720 if (G_interactive_fd < 0) {
7721 /* try to dup to any fd */
7722 G_interactive_fd = dup(STDIN_FILENO);
7723 if (G_interactive_fd < 0)
7725 G_interactive_fd = 0;
7728 if (G_interactive_fd) {
7729 close_on_exec_on(G_interactive_fd);
7733 /* We have interactiveness code disabled */
7737 * if interactive but not a login shell, sources ~/.bashrc
7738 * (--norc turns this off, --rcfile <file> overrides)
7741 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7742 /* note: ash and hush share this string */
7743 printf("\n\n%s %s\n"
7744 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7747 "hush - the humble shell"
7751 parse_and_run_file(stdin);
7754 #if ENABLE_FEATURE_CLEAN_UP
7755 if (G.cwd != bb_msg_unknown)
7757 cur_var = G.top_var->next;
7759 struct variable *tmp = cur_var;
7760 if (!cur_var->max_len)
7761 free(cur_var->varstr);
7762 cur_var = cur_var->next;
7766 hush_exit(G.last_exitcode);
7771 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7772 int msh_main(int argc, char **argv)
7774 //bb_error_msg("msh is deprecated, please use hush instead");
7775 return hush_main(argc, argv);
7783 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7788 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7795 return applet_main_func(argc, argv - argc);
7798 static int FAST_FUNC builtin_test(char **argv)
7800 return run_applet_main(argv, test_main);
7803 static int FAST_FUNC builtin_echo(char **argv)
7805 return run_applet_main(argv, echo_main);
7809 static int FAST_FUNC builtin_printf(char **argv)
7811 return run_applet_main(argv, printf_main);
7815 static char **skip_dash_dash(char **argv)
7818 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7823 static int FAST_FUNC builtin_eval(char **argv)
7825 int rcode = EXIT_SUCCESS;
7827 argv = skip_dash_dash(argv);
7829 char *str = expand_strvec_to_string(argv);
7831 * eval "echo Hi; done" ("done" is syntax error):
7832 * "echo Hi" will not execute too.
7834 parse_and_run_string(str);
7836 rcode = G.last_exitcode;
7841 static int FAST_FUNC builtin_cd(char **argv)
7845 argv = skip_dash_dash(argv);
7847 if (newdir == NULL) {
7848 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7849 * bash says "bash: cd: HOME not set" and does nothing
7852 const char *home = get_local_var_value("HOME");
7853 newdir = home ? home : "/";
7855 if (chdir(newdir)) {
7856 /* Mimic bash message exactly */
7857 bb_perror_msg("cd: %s", newdir);
7858 return EXIT_FAILURE;
7860 /* Read current dir (get_cwd(1) is inside) and set PWD.
7861 * Note: do not enforce exporting. If PWD was unset or unexported,
7862 * set it again, but do not export. bash does the same.
7864 set_pwd_var(/*exp:*/ 0);
7865 return EXIT_SUCCESS;
7868 static int FAST_FUNC builtin_exec(char **argv)
7870 argv = skip_dash_dash(argv);
7871 if (argv[0] == NULL)
7872 return EXIT_SUCCESS; /* bash does this */
7874 /* Careful: we can end up here after [v]fork. Do not restore
7875 * tty pgrp then, only top-level shell process does that */
7876 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7877 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7879 /* TODO: if exec fails, bash does NOT exit! We do.
7880 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7881 * and tcsetpgrp, and this is inherently racy.
7883 execvp_or_die(argv);
7886 static int FAST_FUNC builtin_exit(char **argv)
7888 debug_printf_exec("%s()\n", __func__);
7890 /* interactive bash:
7891 * # trap "echo EEE" EXIT
7894 * There are stopped jobs.
7895 * (if there are _stopped_ jobs, running ones don't count)
7898 # EEE (then bash exits)
7900 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
7903 /* note: EXIT trap is run by hush_exit */
7904 argv = skip_dash_dash(argv);
7905 if (argv[0] == NULL)
7906 hush_exit(G.last_exitcode);
7907 /* mimic bash: exit 123abc == exit 255 + error msg */
7908 xfunc_error_retval = 255;
7909 /* bash: exit -2 == exit 254, no error msg */
7910 hush_exit(xatoi(argv[0]) & 0xff);
7913 static void print_escaped(const char *s)
7918 const char *p = strchrnul(s, '\'');
7919 /* print 'xxxx', possibly just '' */
7920 printf("'%.*s'", (int)(p - s), s);
7925 /* s points to '; print "'''...'''" */
7927 do putchar('\''); while (*++s == '\'');
7932 #if !ENABLE_HUSH_LOCAL
7933 #define helper_export_local(argv, exp, lvl) \
7934 helper_export_local(argv, exp)
7936 static void helper_export_local(char **argv, int exp, int lvl)
7940 char *name_end = strchrnul(name, '=');
7942 /* So far we do not check that name is valid (TODO?) */
7944 if (*name_end == '\0') {
7945 struct variable *var, **vpp;
7947 vpp = get_ptr_to_local_var(name, name_end - name);
7948 var = vpp ? *vpp : NULL;
7950 if (exp == -1) { /* unexporting? */
7951 /* export -n NAME (without =VALUE) */
7953 var->flg_export = 0;
7954 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7956 } /* else: export -n NOT_EXISTING_VAR: no-op */
7959 if (exp == 1) { /* exporting? */
7960 /* export NAME (without =VALUE) */
7962 var->flg_export = 1;
7963 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7964 putenv(var->varstr);
7968 /* Exporting non-existing variable.
7969 * bash does not put it in environment,
7970 * but remembers that it is exported,
7971 * and does put it in env when it is set later.
7972 * We just set it to "" and export. */
7973 /* Or, it's "local NAME" (without =VALUE).
7974 * bash sets the value to "". */
7975 name = xasprintf("%s=", name);
7977 /* (Un)exporting/making local NAME=VALUE */
7978 name = xstrdup(name);
7980 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7984 static int FAST_FUNC builtin_export(char **argv)
7986 unsigned opt_unexport;
7988 #if ENABLE_HUSH_EXPORT_N
7989 /* "!": do not abort on errors */
7990 opt_unexport = getopt32(argv, "!n");
7991 if (opt_unexport == (uint32_t)-1)
7992 return EXIT_FAILURE;
7999 if (argv[0] == NULL) {
8006 /* ash emits: export VAR='VAL'
8007 * bash: declare -x VAR="VAL"
8008 * we follow ash example */
8009 const char *s = *e++;
8010 const char *p = strchr(s, '=');
8012 if (!p) /* wtf? take next variable */
8015 printf("export %.*s", (int)(p - s) + 1, s);
8016 print_escaped(p + 1);
8020 /*fflush_all(); - done after each builtin anyway */
8022 return EXIT_SUCCESS;
8025 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8027 return EXIT_SUCCESS;
8030 #if ENABLE_HUSH_LOCAL
8031 static int FAST_FUNC builtin_local(char **argv)
8033 if (G.func_nest_level == 0) {
8034 bb_error_msg("%s: not in a function", argv[0]);
8035 return EXIT_FAILURE; /* bash compat */
8037 helper_export_local(argv, 0, G.func_nest_level);
8038 return EXIT_SUCCESS;
8042 static int FAST_FUNC builtin_trap(char **argv)
8048 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8053 /* No args: print all trapped */
8054 for (i = 0; i < NSIG; ++i) {
8057 print_escaped(G.traps[i]);
8058 /* note: bash adds "SIG", but only if invoked
8059 * as "bash". If called as "sh", or if set -o posix,
8060 * then it prints short signal names.
8061 * We are printing short names: */
8062 printf(" %s\n", get_signame(i));
8065 /*fflush_all(); - done after each builtin anyway */
8066 return EXIT_SUCCESS;
8070 /* If first arg is a number: reset all specified signals */
8071 sig = bb_strtou(*argv, NULL, 10);
8077 sig = get_signum(*argv++);
8078 if (sig < 0 || sig >= NSIG) {
8080 /* Mimic bash message exactly */
8081 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8086 G.traps[sig] = xstrdup(new_cmd);
8088 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8089 get_signame(sig), sig, G.traps[sig]);
8091 /* There is no signal for 0 (EXIT) */
8096 sigaddset(&G.blocked_set, sig);
8098 /* There was a trap handler, we are removing it
8099 * (if sig has non-DFL handling,
8100 * we don't need to do anything) */
8101 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8103 sigdelset(&G.blocked_set, sig);
8106 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8110 if (!argv[1]) { /* no second arg */
8111 bb_error_msg("trap: invalid arguments");
8112 return EXIT_FAILURE;
8115 /* First arg is "-": reset all specified to default */
8116 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8117 /* Everything else: set arg as signal handler
8118 * (includes "" case, which ignores signal) */
8119 if (argv[0][0] == '-') {
8120 if (argv[0][1] == '\0') { /* "-" */
8121 /* new_cmd remains NULL: "reset these sigs" */
8124 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8127 /* else: "-something", no special meaning */
8132 goto process_sig_list;
8135 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8136 static int FAST_FUNC builtin_type(char **argv)
8138 int ret = EXIT_SUCCESS;
8144 if (0) {} /* make conditional compile easier below */
8145 /*else if (find_alias(*argv))
8146 type = "an alias";*/
8147 #if ENABLE_HUSH_FUNCTIONS
8148 else if (find_function(*argv))
8149 type = "a function";
8151 else if (find_builtin(*argv))
8152 type = "a shell builtin";
8153 else if ((path = find_in_path(*argv)) != NULL)
8156 bb_error_msg("type: %s: not found", *argv);
8161 printf("%s is %s\n", *argv, type);
8169 /* built-in 'fg' and 'bg' handler */
8170 static int FAST_FUNC builtin_fg_bg(char **argv)
8175 if (!G_interactive_fd)
8176 return EXIT_FAILURE;
8178 /* If they gave us no args, assume they want the last backgrounded task */
8180 for (pi = G.job_list; pi; pi = pi->next) {
8181 if (pi->jobid == G.last_jobid) {
8185 bb_error_msg("%s: no current job", argv[0]);
8186 return EXIT_FAILURE;
8188 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8189 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8190 return EXIT_FAILURE;
8192 for (pi = G.job_list; pi; pi = pi->next) {
8193 if (pi->jobid == jobnum) {
8197 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8198 return EXIT_FAILURE;
8200 /* TODO: bash prints a string representation
8201 * of job being foregrounded (like "sleep 1 | cat") */
8202 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8203 /* Put the job into the foreground. */
8204 tcsetpgrp(G_interactive_fd, pi->pgrp);
8207 /* Restart the processes in the job */
8208 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8209 for (i = 0; i < pi->num_cmds; i++) {
8210 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8211 pi->cmds[i].is_stopped = 0;
8213 pi->stopped_cmds = 0;
8215 i = kill(- pi->pgrp, SIGCONT);
8217 if (errno == ESRCH) {
8218 delete_finished_bg_job(pi);
8219 return EXIT_SUCCESS;
8221 bb_perror_msg("kill (SIGCONT)");
8224 if (argv[0][0] == 'f') {
8226 return checkjobs_and_fg_shell(pi);
8228 return EXIT_SUCCESS;
8232 #if ENABLE_HUSH_HELP
8233 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8235 const struct built_in_command *x;
8238 "Built-in commands:\n"
8239 "------------------\n");
8240 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8242 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8245 return EXIT_SUCCESS;
8250 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8253 const char *status_string;
8255 for (job = G.job_list; job; job = job->next) {
8256 if (job->alive_cmds == job->stopped_cmds)
8257 status_string = "Stopped";
8259 status_string = "Running";
8261 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8263 return EXIT_SUCCESS;
8268 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8273 # ifdef M_TRIM_THRESHOLD
8274 /* Optional. Reduces probability of false positives */
8277 /* Crude attempt to find where "free memory" starts,
8278 * sans fragmentation. */
8280 l = (unsigned long)p;
8283 if (l < (unsigned long)p) l = (unsigned long)p;
8286 if (!G.memleak_value)
8287 G.memleak_value = l;
8289 l -= G.memleak_value;
8296 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8301 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8304 return EXIT_SUCCESS;
8307 static int FAST_FUNC builtin_read(char **argv)
8316 /* "!": do not abort on errors.
8317 * Option string must start with "sr" to match BUILTIN_READ_xxx
8319 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8320 if (read_flags == (uint32_t)-1)
8321 return EXIT_FAILURE;
8324 r = shell_builtin_read(set_local_var_from_halves,
8326 get_local_var_value("IFS"), /* can be NULL */
8334 if ((uintptr_t)r > 1) {
8335 bb_error_msg("%s", r);
8336 r = (char*)(uintptr_t)1;
8339 return (uintptr_t)r;
8342 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8343 * built-in 'set' handler
8345 * set [-abCefhmnuvx] [-o option] [argument...]
8346 * set [+abCefhmnuvx] [+o option] [argument...]
8347 * set -- [argument...]
8350 * Implementations shall support the options in both their hyphen and
8351 * plus-sign forms. These options can also be specified as options to sh.
8353 * Write out all variables and their values: set
8354 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8355 * Turn on the -x and -v options: set -xv
8356 * Unset all positional parameters: set --
8357 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8358 * Set the positional parameters to the expansion of x, even if x expands
8359 * with a leading '-' or '+': set -- $x
8361 * So far, we only support "set -- [argument...]" and some of the short names.
8363 static int FAST_FUNC builtin_set(char **argv)
8366 char **pp, **g_argv;
8367 char *arg = *++argv;
8371 for (e = G.top_var; e; e = e->next)
8373 return EXIT_SUCCESS;
8377 if (!strcmp(arg, "--")) {
8381 if (arg[0] != '+' && arg[0] != '-')
8383 for (n = 1; arg[n]; ++n)
8384 if (set_mode(arg[0], arg[n]))
8386 } while ((arg = *++argv) != NULL);
8387 /* Now argv[0] is 1st argument */
8390 return EXIT_SUCCESS;
8393 /* NB: G.global_argv[0] ($0) is never freed/changed */
8394 g_argv = G.global_argv;
8395 if (G.global_args_malloced) {
8401 G.global_args_malloced = 1;
8402 pp = xzalloc(sizeof(pp[0]) * 2);
8403 pp[0] = g_argv[0]; /* retain $0 */
8406 /* This realloc's G.global_argv */
8407 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8414 return EXIT_SUCCESS;
8416 /* Nothing known, so abort */
8418 bb_error_msg("set: %s: invalid option", arg);
8419 return EXIT_FAILURE;
8422 static int FAST_FUNC builtin_shift(char **argv)
8425 argv = skip_dash_dash(argv);
8429 if (n >= 0 && n < G.global_argc) {
8430 if (G.global_args_malloced) {
8433 free(G.global_argv[m++]);
8436 memmove(&G.global_argv[1], &G.global_argv[n+1],
8437 G.global_argc * sizeof(G.global_argv[0]));
8438 return EXIT_SUCCESS;
8440 return EXIT_FAILURE;
8443 static int FAST_FUNC builtin_source(char **argv)
8445 char *arg_path, *filename;
8448 #if ENABLE_HUSH_FUNCTIONS
8452 argv = skip_dash_dash(argv);
8455 /* bash says: "bash: .: filename argument required" */
8456 return 2; /* bash compat */
8459 if (!strchr(filename, '/')) {
8460 arg_path = find_in_path(filename);
8462 filename = arg_path;
8464 input = fopen_or_warn(filename, "r");
8467 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8468 return EXIT_FAILURE;
8470 close_on_exec_on(fileno(input));
8472 #if ENABLE_HUSH_FUNCTIONS
8473 sv_flg = G.flag_return_in_progress;
8474 /* "we are inside sourced file, ok to use return" */
8475 G.flag_return_in_progress = -1;
8477 save_and_replace_G_args(&sv, argv);
8479 parse_and_run_file(input);
8482 restore_G_args(&sv, argv);
8483 #if ENABLE_HUSH_FUNCTIONS
8484 G.flag_return_in_progress = sv_flg;
8487 return G.last_exitcode;
8490 static int FAST_FUNC builtin_umask(char **argv)
8496 argv = skip_dash_dash(argv);
8498 mode_t old_mask = mask;
8501 rc = bb_parse_mode(argv[0], &mask);
8506 * bash: umask: 'q': invalid symbolic mode operator
8507 * bash: umask: 999: octal number out of range
8509 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8514 printf("%04o\n", (unsigned) mask);
8515 /* fall through and restore mask which we set to 0 */
8519 return !rc; /* rc != 0 - success */
8522 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8523 static int FAST_FUNC builtin_unset(char **argv)
8528 /* "!": do not abort on errors */
8529 /* "+": stop at 1st non-option */
8530 opts = getopt32(argv, "!+vf");
8531 if (opts == (unsigned)-1)
8532 return EXIT_FAILURE;
8534 bb_error_msg("unset: -v and -f are exclusive");
8535 return EXIT_FAILURE;
8541 if (!(opts & 2)) { /* not -f */
8542 if (unset_local_var(*argv)) {
8543 /* unset <nonexistent_var> doesn't fail.
8544 * Error is when one tries to unset RO var.
8545 * Message was printed by unset_local_var. */
8549 #if ENABLE_HUSH_FUNCTIONS
8559 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8560 static int FAST_FUNC builtin_wait(char **argv)
8562 int ret = EXIT_SUCCESS;
8565 argv = skip_dash_dash(argv);
8566 if (argv[0] == NULL) {
8567 /* Don't care about wait results */
8568 /* Note 1: must wait until there are no more children */
8569 /* Note 2: must be interruptible */
8571 * $ sleep 3 & sleep 6 & wait
8576 * $ sleep 3 & sleep 6 & wait
8580 * ^C <-- after ~4 sec from keyboard
8583 sigaddset(&G.blocked_set, SIGCHLD);
8584 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8587 if (errno == ECHILD)
8589 /* Wait for SIGCHLD or any other signal of interest */
8590 /* sigtimedwait with infinite timeout: */
8591 sig = sigwaitinfo(&G.blocked_set, NULL);
8593 sig = check_and_run_traps(sig);
8594 if (sig && sig != SIGCHLD) { /* see note 2 */
8600 sigdelset(&G.blocked_set, SIGCHLD);
8601 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8605 /* This is probably buggy wrt interruptible-ness */
8607 pid_t pid = bb_strtou(*argv, NULL, 10);
8609 /* mimic bash message */
8610 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8611 return EXIT_FAILURE;
8613 if (waitpid(pid, &status, 0) == pid) {
8614 if (WIFSIGNALED(status))
8615 ret = 128 + WTERMSIG(status);
8616 else if (WIFEXITED(status))
8617 ret = WEXITSTATUS(status);
8621 bb_perror_msg("wait %s", *argv);
8630 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8631 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8634 def = bb_strtou(argv[1], NULL, 10);
8635 if (errno || def < def_min || argv[2]) {
8636 bb_error_msg("%s: bad arguments", argv[0]);
8644 #if ENABLE_HUSH_LOOPS
8645 static int FAST_FUNC builtin_break(char **argv)
8648 if (G.depth_of_loop == 0) {
8649 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8650 return EXIT_SUCCESS; /* bash compat */
8652 G.flag_break_continue++; /* BC_BREAK = 1 */
8654 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8655 if (depth == UINT_MAX)
8656 G.flag_break_continue = BC_BREAK;
8657 if (G.depth_of_loop < depth)
8658 G.depth_break_continue = G.depth_of_loop;
8660 return EXIT_SUCCESS;
8663 static int FAST_FUNC builtin_continue(char **argv)
8665 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8666 return builtin_break(argv);
8670 #if ENABLE_HUSH_FUNCTIONS
8671 static int FAST_FUNC builtin_return(char **argv)
8675 if (G.flag_return_in_progress != -1) {
8676 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8677 return EXIT_FAILURE; /* bash compat */
8680 G.flag_return_in_progress = 1;
8683 * out of range: wraps around at 256, does not error out
8684 * non-numeric param:
8685 * f() { false; return qwe; }; f; echo $?
8686 * bash: return: qwe: numeric argument required <== we do this
8687 * 255 <== we also do this
8689 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);