1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112 //config: bool "hush"
115 //config: hush is a small shell (25k). It handles the normal flow control
116 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117 //config: case/esac. Redirections, here documents, $((arithmetic))
118 //config: and functions are supported.
120 //config: It will compile and work on no-mmu systems.
122 //config: It does not handle select, aliases, brace expansion,
123 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
125 //config:config HUSH_BASH_COMPAT
126 //config: bool "bash-compatible extensions"
128 //config: depends on HUSH
130 //config: Enable bash-compatible extensions.
132 //config:config HUSH_HELP
133 //config: bool "help builtin"
135 //config: depends on HUSH
137 //config: Enable help builtin in hush. Code size + ~1 kbyte.
139 //config:config HUSH_INTERACTIVE
140 //config: bool "Interactive mode"
142 //config: depends on HUSH
144 //config: Enable interactive mode (prompt and command editing).
145 //config: Without this, hush simply reads and executes commands
146 //config: from stdin just like a shell script from a file.
147 //config: No prompt, no PS1/PS2 magic shell variables.
149 //config:config HUSH_JOB
150 //config: bool "Job control"
152 //config: depends on HUSH_INTERACTIVE
154 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
155 //config: command (not entire shell), fg/bg builtins work. Without this option,
156 //config: "cmd &" still works by simply spawning a process and immediately
157 //config: prompting for next command (or executing next command in a script),
158 //config: but no separate process group is formed.
160 //config:config HUSH_TICK
161 //config: bool "Process substitution"
163 //config: depends on HUSH
165 //config: Enable process substitution `command` and $(command) in hush.
167 //config:config HUSH_IF
168 //config: bool "Support if/then/elif/else/fi"
170 //config: depends on HUSH
172 //config: Enable if/then/elif/else/fi in hush.
174 //config:config HUSH_LOOPS
175 //config: bool "Support for, while and until loops"
177 //config: depends on HUSH
179 //config: Enable for, while and until loops in hush.
181 //config:config HUSH_CASE
182 //config: bool "Support case ... esac statement"
184 //config: depends on HUSH
186 //config: Enable case ... esac statement in hush. +400 bytes.
188 //config:config HUSH_FUNCTIONS
189 //config: bool "Support funcname() { commands; } syntax"
191 //config: depends on HUSH
193 //config: Enable support for shell functions in hush. +800 bytes.
195 //config:config HUSH_LOCAL
196 //config: bool "Support local builtin"
198 //config: depends on HUSH_FUNCTIONS
200 //config: Enable support for local variables in functions.
202 //config:config HUSH_RANDOM_SUPPORT
203 //config: bool "Pseudorandom generator and $RANDOM variable"
205 //config: depends on HUSH
207 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
208 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
210 //config:config HUSH_EXPORT_N
211 //config: bool "Support 'export -n' option"
213 //config: depends on HUSH
215 //config: export -n unexports variables. It is a bash extension.
217 //config:config HUSH_MODE_X
218 //config: bool "Support 'hush -x' option and 'set -x' command"
220 //config: depends on HUSH
222 //config: This instructs hush to print commands before execution.
223 //config: Adds ~300 bytes.
226 //config: bool "msh (deprecated: aliased to hush)"
228 //config: select HUSH
230 //config: msh is deprecated and will be removed, please migrate to hush.
233 //usage:#define hush_trivial_usage NOUSAGE_STR
234 //usage:#define hush_full_usage ""
235 //usage:#define msh_trivial_usage NOUSAGE_STR
236 //usage:#define msh_full_usage ""
240 #define LEAK_HUNTING 0
241 #define BUILD_AS_NOMMU 0
242 /* Enable/disable sanity checks. Ok to enable in production,
243 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
244 * Keeping 1 for now even in released versions.
247 /* Slightly bigger (+200 bytes), but faster hush.
248 * So far it only enables a trick with counting SIGCHLDs and forks,
249 * which allows us to do fewer waitpid's.
250 * (we can detect a case where neither forks were done nor SIGCHLDs happened
251 * and therefore waitpid will return the same result as last time)
253 #define ENABLE_HUSH_FAST 0
254 /* TODO: implement simplified code for users which do not need ${var%...} ops
255 * So far ${var%...} ops are always enabled:
257 #define ENABLE_HUSH_DOLLAR_OPS 1
262 # undef USE_FOR_NOMMU
265 # define USE_FOR_NOMMU(...) __VA_ARGS__
266 # define USE_FOR_MMU(...)
269 #include "NUM_APPLETS.h"
271 /* STANDALONE does not make sense, and won't compile */
272 # undef CONFIG_FEATURE_SH_STANDALONE
273 # undef ENABLE_FEATURE_SH_STANDALONE
274 # undef IF_FEATURE_SH_STANDALONE
275 # undef IF_NOT_FEATURE_SH_STANDALONE
276 # define ENABLE_FEATURE_SH_STANDALONE 0
277 # define IF_FEATURE_SH_STANDALONE(...)
278 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
281 #if !ENABLE_HUSH_INTERACTIVE
282 # undef ENABLE_FEATURE_EDITING
283 # define ENABLE_FEATURE_EDITING 0
284 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
285 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
288 /* Do we support ANY keywords? */
289 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
290 # define HAS_KEYWORDS 1
291 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
292 # define IF_HAS_NO_KEYWORDS(...)
294 # define HAS_KEYWORDS 0
295 # define IF_HAS_KEYWORDS(...)
296 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
299 /* If you comment out one of these below, it will be #defined later
300 * to perform debug printfs to stderr: */
301 #define debug_printf(...) do {} while (0)
302 /* Finer-grained debug switches */
303 #define debug_printf_parse(...) do {} while (0)
304 #define debug_print_tree(a, b) do {} while (0)
305 #define debug_printf_exec(...) do {} while (0)
306 #define debug_printf_env(...) do {} while (0)
307 #define debug_printf_jobs(...) do {} while (0)
308 #define debug_printf_expand(...) do {} while (0)
309 #define debug_printf_varexp(...) do {} while (0)
310 #define debug_printf_glob(...) do {} while (0)
311 #define debug_printf_list(...) do {} while (0)
312 #define debug_printf_subst(...) do {} while (0)
313 #define debug_printf_clean(...) do {} while (0)
315 #define ERR_PTR ((void*)(long)1)
317 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
319 #define _SPECIAL_VARS_STR "_*@$!?#"
320 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
321 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
322 #if ENABLE_HUSH_BASH_COMPAT
323 /* Support / and // replace ops */
324 /* Note that // is stored as \ in "encoded" string representation */
325 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
326 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
327 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
329 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
330 # define VAR_SUBST_OPS "%#:-=+?"
331 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
334 #define SPECIAL_VAR_SYMBOL 3
338 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
340 /* This supports saving pointers malloced in vfork child,
341 * to be freed in the parent.
344 typedef struct nommu_save_t {
346 struct variable *old_vars;
348 char **argv_from_re_execing;
361 #if ENABLE_HUSH_LOOPS
368 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
373 /* three pseudo-keywords support contrived "case" syntax: */
374 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
375 RES_MATCH , /* "word)" */
376 RES_CASE_BODY, /* "this command is inside CASE" */
384 EXP_FLAG_GLOB = 0x200,
385 EXP_FLAG_ESC_GLOB_CHARS = 0x100,
386 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
389 typedef struct o_string {
391 int length; /* position where data is appended */
393 /* Protect newly added chars against globbing
394 * (by prepending \ to *, ?, [, \) */
396 /* At least some part of the string was inside '' or "",
397 * possibly empty one: word"", wo''rd etc. */
398 smallint has_quoted_part;
399 smallint has_empty_slot;
400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
408 /* Used for initialization: o_string foo = NULL_O_STRING; */
409 #define NULL_O_STRING { NULL }
411 /* I can almost use ordinary FILE*. Is open_memstream() universally
412 * available? Where is it documented? */
413 typedef struct in_str {
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
418 #if ENABLE_HUSH_INTERACTIVE
420 smallint promptmode; /* 0: PS1, 1: PS2 */
423 int (*get) (struct in_str *) FAST_FUNC;
424 int (*peek) (struct in_str *) FAST_FUNC;
426 #define i_getch(input) ((input)->get(input))
427 #define i_peek(input) ((input)->peek(input))
429 /* The descrip member of this structure is only used to make
430 * debugging output pretty */
431 static const struct {
433 signed char default_fd;
436 { O_RDONLY, 0, "<" },
437 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
438 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
439 { O_CREAT|O_RDWR, 1, "<>" },
440 { O_RDONLY, 0, "<<" },
441 /* Should not be needed. Bogus default_fd helps in debugging */
442 /* { O_RDONLY, 77, "<<" }, */
445 struct redir_struct {
446 struct redir_struct *next;
447 char *rd_filename; /* filename */
448 int rd_fd; /* fd to redirect */
449 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
451 smallint rd_type; /* (enum redir_type) */
452 /* note: for heredocs, rd_filename contains heredoc delimiter,
453 * and subsequently heredoc itself; and rd_dup is a bitmask:
454 * bit 0: do we need to trim leading tabs?
455 * bit 1: is heredoc quoted (<<'delim' syntax) ?
458 typedef enum redir_type {
460 REDIRECT_OVERWRITE = 1,
463 REDIRECT_HEREDOC = 4,
464 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
467 REDIRFD_SYNTAX_ERR = -2,
468 REDIRFD_TO_FILE = -1,
469 /* otherwise, rd_fd is redirected to rd_dup */
471 HEREDOC_SKIPTABS = 1,
477 pid_t pid; /* 0 if exited */
478 int assignment_cnt; /* how many argv[i] are assignments? */
479 smallint is_stopped; /* is the command currently running? */
480 smallint cmd_type; /* CMD_xxx */
482 #define CMD_SUBSHELL 1
483 #if ENABLE_HUSH_BASH_COMPAT
484 /* used for "[[ EXPR ]]" */
485 # define CMD_SINGLEWORD_NOGLOB 2
487 #if ENABLE_HUSH_FUNCTIONS
488 # define CMD_FUNCDEF 3
491 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
494 char *group_as_string;
496 #if ENABLE_HUSH_FUNCTIONS
497 struct function *child_func;
498 /* This field is used to prevent a bug here:
499 * while...do f1() {a;}; f1; f1() {b;}; f1; done
500 * When we execute "f1() {a;}" cmd, we create new function and clear
501 * cmd->group, cmd->group_as_string, cmd->argv[0].
502 * When we execute "f1() {b;}", we notice that f1 exists,
503 * and that its "parent cmd" struct is still "alive",
504 * we put those fields back into cmd->xxx
505 * (struct function has ->parent_cmd ptr to facilitate that).
506 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
507 * Without this trick, loop would execute a;b;b;b;...
508 * instead of correct sequence a;b;a;b;...
509 * When command is freed, it severs the link
510 * (sets ->child_func->parent_cmd to NULL).
513 char **argv; /* command name and arguments */
514 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
515 * and on execution these are substituted with their values.
516 * Substitution can make _several_ words out of one argv[n]!
517 * Example: argv[0]=='.^C*^C.' here: echo .$*.
518 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
520 struct redir_struct *redirects; /* I/O redirections */
522 /* Is there anything in this command at all? */
523 #define IS_NULL_CMD(cmd) \
524 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
529 int num_cmds; /* total number of commands in pipe */
530 int alive_cmds; /* number of commands running (not exited) */
531 int stopped_cmds; /* number of commands alive, but stopped */
533 int jobid; /* job number */
534 pid_t pgrp; /* process group ID for the job */
535 char *cmdtext; /* name of job */
537 struct command *cmds; /* array of commands in pipe */
538 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
539 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
540 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
542 typedef enum pipe_style {
548 /* Is there anything in this pipe at all? */
549 #define IS_NULL_PIPE(pi) \
550 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
552 /* This holds pointers to the various results of parsing */
553 struct parse_context {
554 /* linked list of pipes */
555 struct pipe *list_head;
556 /* last pipe (being constructed right now) */
558 /* last command in pipe (being constructed right now) */
559 struct command *command;
560 /* last redirect in command->redirects list */
561 struct redir_struct *pending_redirect;
567 smallint ctx_inverted; /* "! cmd | cmd" */
569 smallint ctx_dsemicolon; /* ";;" seen */
571 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
573 /* group we are enclosed in:
574 * example: "if pipe1; pipe2; then pipe3; fi"
575 * when we see "if" or "then", we malloc and copy current context,
576 * and make ->stack point to it. then we parse pipeN.
577 * when closing "then" / fi" / whatever is found,
578 * we move list_head into ->stack->command->group,
579 * copy ->stack into current context, and delete ->stack.
580 * (parsing of { list } and ( list ) doesn't use this method)
582 struct parse_context *stack;
586 /* On program start, environ points to initial environment.
587 * putenv adds new pointers into it, unsetenv removes them.
588 * Neither of these (de)allocates the strings.
589 * setenv allocates new strings in malloc space and does putenv,
590 * and thus setenv is unusable (leaky) for shell's purposes */
591 #define setenv(...) setenv_is_leaky_dont_use()
593 struct variable *next;
594 char *varstr; /* points to "name=" portion */
595 #if ENABLE_HUSH_LOCAL
596 unsigned func_nest_level;
598 int max_len; /* if > 0, name is part of initial env; else name is malloced */
599 smallint flg_export; /* putenv should be done on this var */
600 smallint flg_read_only;
608 #if ENABLE_HUSH_FUNCTIONS
610 struct function *next;
612 struct command *parent_cmd;
615 char *body_as_string;
621 /* "Globals" within this file */
622 /* Sorted roughly by size (smaller offsets == smaller code) */
624 /* interactive_fd != 0 means we are an interactive shell.
625 * If we are, then saved_tty_pgrp can also be != 0, meaning
626 * that controlling tty is available. With saved_tty_pgrp == 0,
627 * job control still works, but terminal signals
628 * (^C, ^Z, ^Y, ^\) won't work at all, and background
629 * process groups can only be created with "cmd &".
630 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
631 * to give tty to the foreground process group,
632 * and will take it back when the group is stopped (^Z)
635 #if ENABLE_HUSH_INTERACTIVE
636 /* 'interactive_fd' is a fd# open to ctty, if we have one
637 * _AND_ if we decided to act interactively */
641 # define G_interactive_fd (G.interactive_fd)
643 # define G_interactive_fd 0
645 #if ENABLE_FEATURE_EDITING
646 line_input_t *line_input_state;
651 #if ENABLE_HUSH_RANDOM_SUPPORT
657 pid_t saved_tty_pgrp;
658 struct pipe *job_list;
659 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
661 # define G_saved_tty_pgrp 0
663 smallint flag_SIGINT;
664 #if ENABLE_HUSH_LOOPS
665 smallint flag_break_continue;
667 #if ENABLE_HUSH_FUNCTIONS
668 /* 0: outside of a function (or sourced file)
669 * -1: inside of a function, ok to use return builtin
670 * 1: return is invoked, skip all till end of func
672 smallint flag_return_in_progress;
675 #if ENABLE_HUSH_MODE_X
677 # define G_x_mode (G.x_mode)
681 smallint exiting; /* used to prevent EXIT trap recursion */
682 /* These four support $?, $#, and $1 */
683 smalluint last_exitcode;
684 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
685 smalluint global_args_malloced;
686 smalluint inherited_set_is_saved;
687 /* how many non-NULL argv's we have. NB: $# + 1 */
691 char *argv0_for_re_execing;
693 #if ENABLE_HUSH_LOOPS
694 unsigned depth_break_continue;
695 unsigned depth_of_loop;
699 struct variable *top_var; /* = &G.shell_ver (set in main()) */
700 struct variable shell_ver;
701 char **expanded_assignments;
702 #if ENABLE_HUSH_FUNCTIONS
703 struct function *top_func;
704 # if ENABLE_HUSH_LOCAL
705 struct variable **shadowed_vars_pp;
706 unsigned func_nest_level;
709 /* Signal and trap handling */
711 unsigned count_SIGCHLD;
712 unsigned handled_SIGCHLD;
713 smallint we_have_children;
715 /* which signals have non-DFL handler (even with no traps set)? */
716 unsigned non_DFL_mask;
717 char **traps; /* char *traps[NSIG] */
718 sigset_t blocked_set;
719 sigset_t inherited_set;
721 unsigned long memleak_value;
724 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
726 #define G (*ptr_to_globals)
727 /* Not #defining name to G.name - this quickly gets unwieldy
728 * (too many defines). Also, I actually prefer to see when a variable
729 * is global, thus "G." prefix is a useful hint */
730 #define INIT_G() do { \
731 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
735 /* Function prototypes for builtins */
736 static int builtin_cd(char **argv) FAST_FUNC;
737 static int builtin_echo(char **argv) FAST_FUNC;
738 static int builtin_eval(char **argv) FAST_FUNC;
739 static int builtin_exec(char **argv) FAST_FUNC;
740 static int builtin_exit(char **argv) FAST_FUNC;
741 static int builtin_export(char **argv) FAST_FUNC;
743 static int builtin_fg_bg(char **argv) FAST_FUNC;
744 static int builtin_jobs(char **argv) FAST_FUNC;
747 static int builtin_help(char **argv) FAST_FUNC;
749 #if ENABLE_HUSH_LOCAL
750 static int builtin_local(char **argv) FAST_FUNC;
753 static int builtin_memleak(char **argv) FAST_FUNC;
756 static int builtin_printf(char **argv) FAST_FUNC;
758 static int builtin_pwd(char **argv) FAST_FUNC;
759 static int builtin_read(char **argv) FAST_FUNC;
760 static int builtin_set(char **argv) FAST_FUNC;
761 static int builtin_shift(char **argv) FAST_FUNC;
762 static int builtin_source(char **argv) FAST_FUNC;
763 static int builtin_test(char **argv) FAST_FUNC;
764 static int builtin_trap(char **argv) FAST_FUNC;
765 static int builtin_type(char **argv) FAST_FUNC;
766 static int builtin_true(char **argv) FAST_FUNC;
767 static int builtin_umask(char **argv) FAST_FUNC;
768 static int builtin_unset(char **argv) FAST_FUNC;
769 static int builtin_wait(char **argv) FAST_FUNC;
770 #if ENABLE_HUSH_LOOPS
771 static int builtin_break(char **argv) FAST_FUNC;
772 static int builtin_continue(char **argv) FAST_FUNC;
774 #if ENABLE_HUSH_FUNCTIONS
775 static int builtin_return(char **argv) FAST_FUNC;
778 /* Table of built-in functions. They can be forked or not, depending on
779 * context: within pipes, they fork. As simple commands, they do not.
780 * When used in non-forking context, they can change global variables
781 * in the parent shell process. If forked, of course they cannot.
782 * For example, 'unset foo | whatever' will parse and run, but foo will
783 * still be set at the end. */
784 struct built_in_command {
786 int (*b_function)(char **argv) FAST_FUNC;
789 # define BLTIN(cmd, func, help) { cmd, func, help }
791 # define BLTIN(cmd, func, help) { cmd, func }
795 static const struct built_in_command bltins1[] = {
796 BLTIN("." , builtin_source , "Run commands in a file"),
797 BLTIN(":" , builtin_true , NULL),
799 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
801 #if ENABLE_HUSH_LOOPS
802 BLTIN("break" , builtin_break , "Exit from a loop"),
804 BLTIN("cd" , builtin_cd , "Change directory"),
805 #if ENABLE_HUSH_LOOPS
806 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
808 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
809 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
810 BLTIN("exit" , builtin_exit , "Exit"),
811 BLTIN("export" , builtin_export , "Set environment variables"),
813 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
816 BLTIN("help" , builtin_help , NULL),
819 BLTIN("jobs" , builtin_jobs , "List jobs"),
821 #if ENABLE_HUSH_LOCAL
822 BLTIN("local" , builtin_local , "Set local variables"),
825 BLTIN("memleak" , builtin_memleak , NULL),
827 BLTIN("read" , builtin_read , "Input into variable"),
828 #if ENABLE_HUSH_FUNCTIONS
829 BLTIN("return" , builtin_return , "Return from a function"),
831 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
832 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
833 #if ENABLE_HUSH_BASH_COMPAT
834 BLTIN("source" , builtin_source , "Run commands in a file"),
836 BLTIN("trap" , builtin_trap , "Trap signals"),
837 BLTIN("type" , builtin_type , "Show command type"),
838 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
839 BLTIN("umask" , builtin_umask , "Set file creation mask"),
840 BLTIN("unset" , builtin_unset , "Unset variables"),
841 BLTIN("wait" , builtin_wait , "Wait for process"),
843 /* For now, echo and test are unconditionally enabled.
844 * Maybe make it configurable? */
845 static const struct built_in_command bltins2[] = {
846 BLTIN("[" , builtin_test , NULL),
847 BLTIN("echo" , builtin_echo , NULL),
849 BLTIN("printf" , builtin_printf , NULL),
851 BLTIN("pwd" , builtin_pwd , NULL),
852 BLTIN("test" , builtin_test , NULL),
859 /* prevent disasters with G.debug_indent < 0 */
860 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
861 # define debug_enter() (G.debug_indent++)
862 # define debug_leave() (G.debug_indent--)
864 # define indent() ((void)0)
865 # define debug_enter() ((void)0)
866 # define debug_leave() ((void)0)
870 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
873 #ifndef debug_printf_parse
874 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
877 #ifndef debug_printf_exec
878 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
881 #ifndef debug_printf_env
882 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
885 #ifndef debug_printf_jobs
886 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
887 # define DEBUG_JOBS 1
889 # define DEBUG_JOBS 0
892 #ifndef debug_printf_expand
893 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
894 # define DEBUG_EXPAND 1
896 # define DEBUG_EXPAND 0
899 #ifndef debug_printf_varexp
900 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
903 #ifndef debug_printf_glob
904 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
905 # define DEBUG_GLOB 1
907 # define DEBUG_GLOB 0
910 #ifndef debug_printf_list
911 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
914 #ifndef debug_printf_subst
915 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
918 #ifndef debug_printf_clean
919 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 # define DEBUG_CLEAN 1
922 # define DEBUG_CLEAN 0
926 static void debug_print_strings(const char *prefix, char **vv)
929 fprintf(stderr, "%s:\n", prefix);
931 fprintf(stderr, " '%s'\n", *vv++);
934 # define debug_print_strings(prefix, vv) ((void)0)
938 /* Leak hunting. Use hush_leaktool.sh for post-processing.
941 static void *xxmalloc(int lineno, size_t size)
943 void *ptr = xmalloc((size + 0xff) & ~0xff);
944 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
947 static void *xxrealloc(int lineno, void *ptr, size_t size)
949 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
950 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
953 static char *xxstrdup(int lineno, const char *str)
955 char *ptr = xstrdup(str);
956 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
959 static void xxfree(void *ptr)
961 fdprintf(2, "free %p\n", ptr);
964 # define xmalloc(s) xxmalloc(__LINE__, s)
965 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
966 # define xstrdup(s) xxstrdup(__LINE__, s)
967 # define free(p) xxfree(p)
971 /* Syntax and runtime errors. They always abort scripts.
972 * In interactive use they usually discard unparsed and/or unexecuted commands
973 * and return to the prompt.
974 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
977 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
978 # define syntax_error(lineno, msg) syntax_error(msg)
979 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
980 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
981 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
982 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
985 static void die_if_script(unsigned lineno, const char *fmt, ...)
990 bb_error_msg("hush.c:%u", lineno);
993 bb_verror_msg(fmt, p, NULL);
995 if (!G_interactive_fd)
999 static void syntax_error(unsigned lineno, const char *msg)
1002 die_if_script(lineno, "syntax error: %s", msg);
1004 die_if_script(lineno, "syntax error", NULL);
1007 static void syntax_error_at(unsigned lineno, const char *msg)
1009 die_if_script(lineno, "syntax error at '%s'", msg);
1012 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1014 die_if_script(lineno, "syntax error: unterminated %s", s);
1017 /* It so happens that all such cases are totally fatal
1018 * even if shell is interactive: EOF while looking for closing
1019 * delimiter. There is nowhere to read stuff from after that,
1020 * it's EOF! The only choice is to terminate.
1022 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1023 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1025 char msg[2] = { ch, '\0' };
1026 syntax_error_unterm_str(lineno, msg);
1030 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1035 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1039 # undef die_if_script
1040 # undef syntax_error
1041 # undef syntax_error_at
1042 # undef syntax_error_unterm_ch
1043 # undef syntax_error_unterm_str
1044 # undef syntax_error_unexpected_ch
1046 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1047 # define syntax_error(msg) syntax_error(__LINE__, msg)
1048 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1049 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1050 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1051 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1055 #if ENABLE_HUSH_INTERACTIVE
1056 static void cmdedit_update_prompt(void);
1058 # define cmdedit_update_prompt() ((void)0)
1062 /* Utility functions
1064 /* Replace each \x with x in place, return ptr past NUL. */
1065 static char *unbackslash(char *src)
1067 char *dst = src = strchrnul(src, '\\');
1071 if ((*dst++ = *src++) == '\0')
1077 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1098 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1099 v[count1 + count2] = NULL;
1102 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1106 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1108 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1109 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1112 #define add_strings_to_strings(strings, add, need_to_dup) \
1113 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1116 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1117 static char **add_string_to_strings(char **strings, char *add)
1122 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1125 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1127 char **ptr = add_string_to_strings(strings, add);
1128 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1131 #define add_string_to_strings(strings, add) \
1132 xx_add_string_to_strings(__LINE__, strings, add)
1135 static void free_strings(char **strings)
1150 /* Helpers for setting new $n and restoring them back
1152 typedef struct save_arg_t {
1156 smallint sv_g_malloced;
1159 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1163 sv->sv_argv0 = argv[0];
1164 sv->sv_g_argv = G.global_argv;
1165 sv->sv_g_argc = G.global_argc;
1166 sv->sv_g_malloced = G.global_args_malloced;
1168 argv[0] = G.global_argv[0]; /* retain $0 */
1169 G.global_argv = argv;
1170 G.global_args_malloced = 0;
1178 static void restore_G_args(save_arg_t *sv, char **argv)
1182 if (G.global_args_malloced) {
1183 /* someone ran "set -- arg1 arg2 ...", undo */
1185 while (*++pp) /* note: does not free $0 */
1187 free(G.global_argv);
1189 argv[0] = sv->sv_argv0;
1190 G.global_argv = sv->sv_g_argv;
1191 G.global_argc = sv->sv_g_argc;
1192 G.global_args_malloced = sv->sv_g_malloced;
1196 /* Basic theory of signal handling in shell
1197 * ========================================
1198 * This does not describe what hush does, rather, it is current understanding
1199 * what it _should_ do. If it doesn't, it's a bug.
1200 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1202 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1203 * is finished or backgrounded. It is the same in interactive and
1204 * non-interactive shells, and is the same regardless of whether
1205 * a user trap handler is installed or a shell special one is in effect.
1206 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1207 * backgrounds (i.e. stops) or kills all members of currently running
1210 * Wait builtin in interruptible by signals for which user trap is set
1211 * or by SIGINT in interactive shell.
1213 * Trap handlers will execute even within trap handlers. (right?)
1215 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1216 * except for handlers set to '' (empty string).
1218 * If job control is off, backgrounded commands ("cmd &")
1219 * have SIGINT, SIGQUIT set to SIG_IGN.
1221 * Commands which are run in command substitution ("`cmd`")
1222 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1224 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1225 * by the shell from its parent.
1227 * Signals which differ from SIG_DFL action
1228 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1231 * SIGTERM (interactive): ignore
1232 * SIGHUP (interactive):
1233 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1234 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1235 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1236 * that all pipe members are stopped. Try this in bash:
1237 * while :; do :; done - ^Z does not background it
1238 * (while :; do :; done) - ^Z backgrounds it
1239 * SIGINT (interactive): wait for last pipe, ignore the rest
1240 * of the command line, show prompt. NB: ^C does not send SIGINT
1241 * to interactive shell while shell is waiting for a pipe,
1242 * since shell is bg'ed (is not in foreground process group).
1243 * Example 1: this waits 5 sec, but does not execute ls:
1244 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1245 * Example 2: this does not wait and does not execute ls:
1246 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1247 * Example 3: this does not wait 5 sec, but executes ls:
1248 * "sleep 5; ls -l" + press ^C
1250 * (What happens to signals which are IGN on shell start?)
1251 * (What happens with signal mask on shell start?)
1253 * Implementation in hush
1254 * ======================
1255 * We use in-kernel pending signal mask to determine which signals were sent.
1256 * We block all signals which we don't want to take action immediately,
1257 * i.e. we block all signals which need to have special handling as described
1258 * above, and all signals which have traps set.
1259 * After each pipe execution, we extract any pending signals via sigtimedwait()
1262 * unsigned non_DFL_mask: a mask of such "special" signals
1263 * sigset_t blocked_set: current blocked signal set
1266 * clear bit in blocked_set unless it is also in non_DFL_mask
1267 * "trap 'cmd' SIGxxx":
1268 * set bit in blocked_set (even if 'cmd' is '')
1269 * after [v]fork, if we plan to be a shell:
1270 * unblock signals with special interactive handling
1271 * (child shell is not interactive),
1272 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1273 * after [v]fork, if we plan to exec:
1274 * POSIX says fork clears pending signal mask in child - no need to clear it.
1275 * Restore blocked signal set to one inherited by shell just prior to exec.
1277 * Note: as a result, we do not use signal handlers much. The only uses
1278 * are to count SIGCHLDs
1279 * and to restore tty pgrp on signal-induced exit.
1282 * Standard says "When a subshell is entered, traps that are not being ignored
1283 * are set to the default actions". bash interprets it so that traps which
1284 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1287 SPECIAL_INTERACTIVE_SIGS = 0
1292 SPECIAL_JOB_SIGS = 0
1300 #if ENABLE_HUSH_FAST
1301 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1304 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1310 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1311 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1312 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1313 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1315 /* Restores tty foreground process group, and exits.
1316 * May be called as signal handler for fatal signal
1317 * (will resend signal to itself, producing correct exit state)
1318 * or called directly with -EXITCODE.
1319 * We also call it if xfunc is exiting. */
1320 static void sigexit(int sig) NORETURN;
1321 static void sigexit(int sig)
1323 /* Disable all signals: job control, SIGPIPE, etc. */
1324 sigprocmask_allsigs(SIG_BLOCK);
1326 /* Careful: we can end up here after [v]fork. Do not restore
1327 * tty pgrp then, only top-level shell process does that */
1328 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1329 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1331 /* Not a signal, just exit */
1335 kill_myself_with_sig(sig); /* does not return */
1339 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1340 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1344 /* Restores tty foreground process group, and exits. */
1345 static void hush_exit(int exitcode) NORETURN;
1346 static void hush_exit(int exitcode)
1348 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1349 /* Prevent recursion:
1350 * trap "echo Hi; exit" EXIT; exit
1353 /* argv[0] is unused */
1354 argv[1] = G.traps[0];
1359 /* free(argv[1]); - why bother */
1364 sigexit(- (exitcode & 0xff));
1370 static int check_and_run_traps(int sig)
1372 static const struct timespec zero_timespec;
1373 smalluint save_rcode;
1379 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1384 if (G.traps && G.traps[sig]) {
1385 if (G.traps[sig][0]) {
1386 /* We have user-defined handler */
1388 /* argv[0] is unused */
1389 argv[1] = G.traps[sig];
1391 save_rcode = G.last_exitcode;
1393 G.last_exitcode = save_rcode;
1394 } /* else: "" trap, ignoring signal */
1397 /* not a trap: special action */
1399 #if ENABLE_HUSH_FAST
1402 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1406 /* Builtin was ^C'ed, make it look prettier: */
1413 /* bash is observed to signal whole process groups,
1414 * not individual processes */
1415 for (job = G.job_list; job; job = job->next) {
1418 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1419 if (kill(- job->pgrp, SIGHUP) == 0)
1420 kill(- job->pgrp, SIGCONT);
1425 default: /* ignored: */
1426 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1434 static const char *get_cwd(int force)
1436 if (force || G.cwd == NULL) {
1437 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1438 * we must not try to free(bb_msg_unknown) */
1439 if (G.cwd == bb_msg_unknown)
1441 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1443 G.cwd = bb_msg_unknown;
1450 * Shell and environment variable support
1452 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1454 struct variable **pp;
1455 struct variable *cur;
1458 while ((cur = *pp) != NULL) {
1459 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1466 static const char* FAST_FUNC get_local_var_value(const char *name)
1468 struct variable **vpp;
1469 unsigned len = strlen(name);
1471 if (G.expanded_assignments) {
1472 char **cpp = G.expanded_assignments;
1475 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1476 return cp + len + 1;
1481 vpp = get_ptr_to_local_var(name, len);
1483 return (*vpp)->varstr + len + 1;
1485 if (strcmp(name, "PPID") == 0)
1486 return utoa(G.root_ppid);
1487 // bash compat: UID? EUID?
1488 #if ENABLE_HUSH_RANDOM_SUPPORT
1489 if (strcmp(name, "RANDOM") == 0)
1490 return utoa(next_random(&G.random_gen));
1495 /* str holds "NAME=VAL" and is expected to be malloced.
1496 * We take ownership of it.
1498 * 0: do not change export flag
1499 * (if creating new variable, flag will be 0)
1500 * 1: set export flag and putenv the variable
1501 * -1: clear export flag and unsetenv the variable
1502 * flg_read_only is set only when we handle -R var=val
1504 #if !BB_MMU && ENABLE_HUSH_LOCAL
1505 /* all params are used */
1506 #elif BB_MMU && ENABLE_HUSH_LOCAL
1507 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1508 set_local_var(str, flg_export, local_lvl)
1509 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1510 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1511 set_local_var(str, flg_export)
1512 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1513 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1514 set_local_var(str, flg_export, flg_read_only)
1516 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1518 struct variable **var_pp;
1519 struct variable *cur;
1523 eq_sign = strchr(str, '=');
1524 if (!eq_sign) { /* not expected to ever happen? */
1529 name_len = eq_sign - str + 1; /* including '=' */
1530 var_pp = &G.top_var;
1531 while ((cur = *var_pp) != NULL) {
1532 if (strncmp(cur->varstr, str, name_len) != 0) {
1533 var_pp = &cur->next;
1536 /* We found an existing var with this name */
1537 if (cur->flg_read_only) {
1541 bb_error_msg("%s: readonly variable", str);
1545 if (flg_export == -1) { // "&& cur->flg_export" ?
1546 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1551 #if ENABLE_HUSH_LOCAL
1552 if (cur->func_nest_level < local_lvl) {
1553 /* New variable is declared as local,
1554 * and existing one is global, or local
1555 * from enclosing function.
1556 * Remove and save old one: */
1557 *var_pp = cur->next;
1558 cur->next = *G.shadowed_vars_pp;
1559 *G.shadowed_vars_pp = cur;
1560 /* bash 3.2.33(1) and exported vars:
1562 * # f() { local z=a; env | grep ^z; }
1568 if (cur->flg_export)
1573 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1578 if (cur->max_len != 0) {
1579 if (cur->max_len >= strlen(str)) {
1580 /* This one is from startup env, reuse space */
1581 strcpy(cur->varstr, str);
1585 /* max_len == 0 signifies "malloced" var, which we can
1586 * (and has to) free */
1590 goto set_str_and_exp;
1593 /* Not found - create new variable struct */
1594 cur = xzalloc(sizeof(*cur));
1595 #if ENABLE_HUSH_LOCAL
1596 cur->func_nest_level = local_lvl;
1598 cur->next = *var_pp;
1604 cur->flg_read_only = flg_read_only;
1607 if (flg_export == 1)
1608 cur->flg_export = 1;
1609 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1610 cmdedit_update_prompt();
1611 if (cur->flg_export) {
1612 if (flg_export == -1) {
1613 cur->flg_export = 0;
1614 /* unsetenv was already done */
1616 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1617 return putenv(cur->varstr);
1623 /* Used at startup and after each cd */
1624 static void set_pwd_var(int exp)
1626 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1627 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1630 static int unset_local_var_len(const char *name, int name_len)
1632 struct variable *cur;
1633 struct variable **var_pp;
1636 return EXIT_SUCCESS;
1637 var_pp = &G.top_var;
1638 while ((cur = *var_pp) != NULL) {
1639 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1640 if (cur->flg_read_only) {
1641 bb_error_msg("%s: readonly variable", name);
1642 return EXIT_FAILURE;
1644 *var_pp = cur->next;
1645 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1646 bb_unsetenv(cur->varstr);
1647 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1648 cmdedit_update_prompt();
1652 return EXIT_SUCCESS;
1654 var_pp = &cur->next;
1656 return EXIT_SUCCESS;
1659 static int unset_local_var(const char *name)
1661 return unset_local_var_len(name, strlen(name));
1664 static void unset_vars(char **strings)
1672 const char *eq = strchrnul(*v, '=');
1673 unset_local_var_len(*v, (int)(eq - *v));
1679 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1681 char *var = xasprintf("%s=%s", name, val);
1682 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1687 * Helpers for "var1=val1 var2=val2 cmd" feature
1689 static void add_vars(struct variable *var)
1691 struct variable *next;
1695 var->next = G.top_var;
1697 if (var->flg_export) {
1698 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1699 putenv(var->varstr);
1701 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1707 static struct variable *set_vars_and_save_old(char **strings)
1710 struct variable *old = NULL;
1716 struct variable *var_p;
1717 struct variable **var_pp;
1720 eq = strchr(*s, '=');
1722 var_pp = get_ptr_to_local_var(*s, eq - *s);
1724 /* Remove variable from global linked list */
1726 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1727 *var_pp = var_p->next;
1728 /* Add it to returned list */
1732 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1743 static int FAST_FUNC static_get(struct in_str *i)
1753 static int FAST_FUNC static_peek(struct in_str *i)
1758 #if ENABLE_HUSH_INTERACTIVE
1760 static void cmdedit_update_prompt(void)
1762 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1763 G.PS1 = get_local_var_value("PS1");
1766 G.PS2 = get_local_var_value("PS2");
1774 static const char *setup_prompt_string(int promptmode)
1776 const char *prompt_str;
1777 debug_printf("setup_prompt_string %d ", promptmode);
1778 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1779 /* Set up the prompt */
1780 if (promptmode == 0) { /* PS1 */
1782 /* bash uses $PWD value, even if it is set by user.
1783 * It uses current dir only if PWD is unset.
1784 * We always use current dir. */
1785 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1790 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1791 debug_printf("result '%s'\n", prompt_str);
1795 static void get_user_input(struct in_str *i)
1798 const char *prompt_str;
1800 prompt_str = setup_prompt_string(i->promptmode);
1801 # if ENABLE_FEATURE_EDITING
1802 /* Enable command line editing only while a command line
1803 * is actually being read */
1806 /* buglet: SIGINT will not make new prompt to appear _at once_,
1807 * only after <Enter>. (^C will work) */
1808 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1809 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1810 check_and_run_traps(0);
1811 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1812 i->eof_flag = (r < 0);
1813 if (i->eof_flag) { /* EOF/error detected */
1814 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1815 G.user_input_buf[1] = '\0';
1820 fputs(prompt_str, stdout);
1822 G.user_input_buf[0] = r = fgetc(i->file);
1823 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1824 //do we need check_and_run_traps(0)? (maybe only if stdin)
1825 } while (G.flag_SIGINT);
1826 i->eof_flag = (r == EOF);
1828 i->p = G.user_input_buf;
1831 #endif /* INTERACTIVE */
1833 /* This is the magic location that prints prompts
1834 * and gets data back from the user */
1835 static int FAST_FUNC file_get(struct in_str *i)
1839 /* If there is data waiting, eat it up */
1840 if (i->p && *i->p) {
1841 #if ENABLE_HUSH_INTERACTIVE
1845 if (i->eof_flag && !*i->p)
1847 /* note: ch is never NUL */
1849 /* need to double check i->file because we might be doing something
1850 * more complicated by now, like sourcing or substituting. */
1851 #if ENABLE_HUSH_INTERACTIVE
1852 if (G_interactive_fd && i->promptme && i->file == stdin) {
1855 } while (!*i->p); /* need non-empty line */
1856 i->promptmode = 1; /* PS2 */
1861 do ch = fgetc(i->file); while (ch == '\0');
1863 debug_printf("file_get: got '%c' %d\n", ch, ch);
1864 #if ENABLE_HUSH_INTERACTIVE
1871 /* All callers guarantee this routine will never
1872 * be used right after a newline, so prompting is not needed.
1874 static int FAST_FUNC file_peek(struct in_str *i)
1877 if (i->p && *i->p) {
1878 if (i->eof_flag && !i->p[1])
1881 /* note: ch is never NUL */
1883 do ch = fgetc(i->file); while (ch == '\0');
1884 i->eof_flag = (ch == EOF);
1885 i->peek_buf[0] = ch;
1886 i->peek_buf[1] = '\0';
1888 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1892 static void setup_file_in_str(struct in_str *i, FILE *f)
1894 i->peek = file_peek;
1896 #if ENABLE_HUSH_INTERACTIVE
1898 i->promptmode = 0; /* PS1 */
1904 static void setup_string_in_str(struct in_str *i, const char *s)
1906 i->peek = static_peek;
1907 i->get = static_get;
1908 #if ENABLE_HUSH_INTERACTIVE
1910 i->promptmode = 0; /* PS1 */
1920 #define B_CHUNK (32 * sizeof(char*))
1922 static void o_reset_to_empty_unquoted(o_string *o)
1925 o->has_quoted_part = 0;
1930 static void o_free(o_string *o)
1933 memset(o, 0, sizeof(*o));
1936 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1941 static void o_grow_by(o_string *o, int len)
1943 if (o->length + len > o->maxlen) {
1944 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1945 o->data = xrealloc(o->data, 1 + o->maxlen);
1949 static void o_addchr(o_string *o, int ch)
1951 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1953 o->data[o->length] = ch;
1955 o->data[o->length] = '\0';
1958 static void o_addblock(o_string *o, const char *str, int len)
1961 memcpy(&o->data[o->length], str, len);
1963 o->data[o->length] = '\0';
1966 static void o_addstr(o_string *o, const char *str)
1968 o_addblock(o, str, strlen(str));
1972 static void nommu_addchr(o_string *o, int ch)
1978 # define nommu_addchr(o, str) ((void)0)
1981 static void o_addstr_with_NUL(o_string *o, const char *str)
1983 o_addblock(o, str, strlen(str) + 1);
1986 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1991 if (*str++ == '\\') {
1992 /* \z -> \\\z; \<eol> -> \\<eol> */
1997 o_addchr(o, *str++);
2003 #undef HUSH_BRACE_EXP
2005 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2006 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2007 * Apparently, on unquoted $v bash still does globbing
2008 * ("v='*.txt'; echo $v" prints all .txt files),
2009 * but NOT brace expansion! Thus, there should be TWO independent
2010 * quoting mechanisms on $v expansion side: one protects
2011 * $v from brace expansion, and other additionally protects "$v" against globbing.
2012 * We have only second one.
2015 #ifdef HUSH_BRACE_EXP
2016 # define MAYBE_BRACES "{}"
2018 # define MAYBE_BRACES ""
2021 /* My analysis of quoting semantics tells me that state information
2022 * is associated with a destination, not a source.
2024 static void o_addqchr(o_string *o, int ch)
2027 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2032 o->data[o->length] = '\\';
2035 o->data[o->length] = ch;
2037 o->data[o->length] = '\0';
2040 static void o_addQchr(o_string *o, int ch)
2043 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2044 && strchr("*?[\\" MAYBE_BRACES, ch)
2047 o->data[o->length] = '\\';
2051 o->data[o->length] = ch;
2053 o->data[o->length] = '\0';
2056 static void o_addqblock(o_string *o, const char *str, int len)
2061 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2062 if (ordinary_cnt > len) /* paranoia */
2064 o_addblock(o, str, ordinary_cnt);
2065 if (ordinary_cnt == len)
2067 str += ordinary_cnt;
2068 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2072 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2074 o->data[o->length] = '\\';
2078 o->data[o->length] = ch;
2080 o->data[o->length] = '\0';
2084 static void o_addQblock(o_string *o, const char *str, int len)
2086 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2087 o_addblock(o, str, len);
2090 o_addqblock(o, str, len);
2093 static void o_addQstr(o_string *o, const char *str)
2095 o_addQblock(o, str, strlen(str));
2098 /* A special kind of o_string for $VAR and `cmd` expansion.
2099 * It contains char* list[] at the beginning, which is grown in 16 element
2100 * increments. Actual string data starts at the next multiple of 16 * (char*).
2101 * list[i] contains an INDEX (int!) into this string data.
2102 * It means that if list[] needs to grow, data needs to be moved higher up
2103 * but list[i]'s need not be modified.
2104 * NB: remembering how many list[i]'s you have there is crucial.
2105 * o_finalize_list() operation post-processes this structure - calculates
2106 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2108 #if DEBUG_EXPAND || DEBUG_GLOB
2109 static void debug_print_list(const char *prefix, o_string *o, int n)
2111 char **list = (char**)o->data;
2112 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2116 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2117 prefix, list, n, string_start, o->length, o->maxlen,
2118 !!(o->o_expflags & EXP_FLAG_GLOB),
2120 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2123 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2124 o->data + (int)list[i] + string_start,
2125 o->data + (int)list[i] + string_start);
2129 const char *p = o->data + (int)list[n - 1] + string_start;
2131 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2135 # define debug_print_list(prefix, o, n) ((void)0)
2138 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2139 * in list[n] so that it points past last stored byte so far.
2140 * It returns n+1. */
2141 static int o_save_ptr_helper(o_string *o, int n)
2143 char **list = (char**)o->data;
2147 if (!o->has_empty_slot) {
2148 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2149 string_len = o->length - string_start;
2150 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2151 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2152 /* list[n] points to string_start, make space for 16 more pointers */
2153 o->maxlen += 0x10 * sizeof(list[0]);
2154 o->data = xrealloc(o->data, o->maxlen + 1);
2155 list = (char**)o->data;
2156 memmove(list + n + 0x10, list + n, string_len);
2157 o->length += 0x10 * sizeof(list[0]);
2159 debug_printf_list("list[%d]=%d string_start=%d\n",
2160 n, string_len, string_start);
2163 /* We have empty slot at list[n], reuse without growth */
2164 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2165 string_len = o->length - string_start;
2166 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2167 n, string_len, string_start);
2168 o->has_empty_slot = 0;
2170 list[n] = (char*)(uintptr_t)string_len;
2174 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2175 static int o_get_last_ptr(o_string *o, int n)
2177 char **list = (char**)o->data;
2178 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2180 return ((int)(uintptr_t)list[n-1]) + string_start;
2183 #ifdef HUSH_BRACE_EXP
2184 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2185 * first, it processes even {a} (no commas), second,
2186 * I didn't manage to make it return strings when they don't match
2187 * existing files. Need to re-implement it.
2191 static int glob_needed(const char *s)
2200 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2206 /* Return pointer to next closing brace or to comma */
2207 static const char *next_brace_sub(const char *cp)
2211 while (*cp != '\0') {
2218 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2224 return *cp != '\0' ? cp : NULL;
2226 /* Recursive brace globber. Note: may garble pattern[]. */
2227 static int glob_brace(char *pattern, o_string *o, int n)
2229 char *new_pattern_buf;
2236 debug_printf_glob("glob_brace('%s')\n", pattern);
2242 if (*begin == '{') {
2243 /* Find the first sub-pattern and at the same time
2244 * find the rest after the closing brace */
2245 next = next_brace_sub(begin);
2247 /* An illegal expression */
2251 /* "{abc}" with no commas - illegal
2252 * brace expr, disregard and skip it */
2258 if (*begin == '\\' && begin[1] != '\0')
2262 debug_printf_glob("begin:%s\n", begin);
2263 debug_printf_glob("next:%s\n", next);
2265 /* Now find the end of the whole brace expression */
2267 while (*rest != '}') {
2268 rest = next_brace_sub(rest);
2270 /* An illegal expression */
2273 debug_printf_glob("rest:%s\n", rest);
2275 rest_len = strlen(++rest) + 1;
2277 /* We are sure the brace expression is well-formed */
2279 /* Allocate working buffer large enough for our work */
2280 new_pattern_buf = xmalloc(strlen(pattern));
2282 /* We have a brace expression. BEGIN points to the opening {,
2283 * NEXT points past the terminator of the first element, and REST
2284 * points past the final }. We will accumulate result names from
2285 * recursive runs for each brace alternative in the buffer using
2290 /* Construct the new glob expression */
2293 mempcpy(new_pattern_buf,
2294 /* We know the prefix for all sub-patterns */
2295 pattern, begin - pattern),
2299 /* Note: glob_brace() may garble new_pattern_buf[].
2300 * That's why we re-copy prefix every time (1st memcpy above).
2302 n = glob_brace(new_pattern_buf, o, n);
2304 /* We saw the last entry */
2308 next = next_brace_sub(next);
2310 free(new_pattern_buf);
2318 memset(&globdata, 0, sizeof(globdata));
2319 gr = glob(pattern, 0, NULL, &globdata);
2320 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2322 if (gr == GLOB_NOMATCH) {
2323 globfree(&globdata);
2324 /* NB: garbles parameter */
2325 unbackslash(pattern);
2326 o_addstr_with_NUL(o, pattern);
2327 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2328 return o_save_ptr_helper(o, n);
2330 if (gr == GLOB_NOSPACE)
2331 bb_error_msg_and_die(bb_msg_memory_exhausted);
2332 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2333 * but we didn't specify it. Paranoia again. */
2334 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2336 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2337 char **argv = globdata.gl_pathv;
2339 o_addstr_with_NUL(o, *argv);
2340 n = o_save_ptr_helper(o, n);
2346 globfree(&globdata);
2350 /* Performs globbing on last list[],
2351 * saving each result as a new list[].
2353 static int perform_glob(o_string *o, int n)
2355 char *pattern, *copy;
2357 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2359 return o_save_ptr_helper(o, n);
2360 pattern = o->data + o_get_last_ptr(o, n);
2361 debug_printf_glob("glob pattern '%s'\n", pattern);
2362 if (!glob_needed(pattern)) {
2363 /* unbackslash last string in o in place, fix length */
2364 o->length = unbackslash(pattern) - o->data;
2365 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2366 return o_save_ptr_helper(o, n);
2369 copy = xstrdup(pattern);
2370 /* "forget" pattern in o */
2371 o->length = pattern - o->data;
2372 n = glob_brace(copy, o, n);
2375 debug_print_list("perform_glob returning", o, n);
2379 #else /* !HUSH_BRACE_EXP */
2382 static int glob_needed(const char *s)
2391 if (*s == '*' || *s == '[' || *s == '?')
2397 /* Performs globbing on last list[],
2398 * saving each result as a new list[].
2400 static int perform_glob(o_string *o, int n)
2406 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2408 return o_save_ptr_helper(o, n);
2409 pattern = o->data + o_get_last_ptr(o, n);
2410 debug_printf_glob("glob pattern '%s'\n", pattern);
2411 if (!glob_needed(pattern)) {
2413 /* unbackslash last string in o in place, fix length */
2414 o->length = unbackslash(pattern) - o->data;
2415 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2416 return o_save_ptr_helper(o, n);
2419 memset(&globdata, 0, sizeof(globdata));
2420 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2421 * If we glob "*.\*" and don't find anything, we need
2422 * to fall back to using literal "*.*", but GLOB_NOCHECK
2423 * will return "*.\*"!
2425 gr = glob(pattern, 0, NULL, &globdata);
2426 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2428 if (gr == GLOB_NOMATCH) {
2429 globfree(&globdata);
2432 if (gr == GLOB_NOSPACE)
2433 bb_error_msg_and_die(bb_msg_memory_exhausted);
2434 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2435 * but we didn't specify it. Paranoia again. */
2436 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2438 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2439 char **argv = globdata.gl_pathv;
2440 /* "forget" pattern in o */
2441 o->length = pattern - o->data;
2443 o_addstr_with_NUL(o, *argv);
2444 n = o_save_ptr_helper(o, n);
2450 globfree(&globdata);
2452 debug_print_list("perform_glob returning", o, n);
2456 #endif /* !HUSH_BRACE_EXP */
2458 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2459 * Otherwise, just finish current list[] and start new */
2460 static int o_save_ptr(o_string *o, int n)
2462 if (o->o_expflags & EXP_FLAG_GLOB) {
2463 /* If o->has_empty_slot, list[n] was already globbed
2464 * (if it was requested back then when it was filled)
2465 * so don't do that again! */
2466 if (!o->has_empty_slot)
2467 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2469 return o_save_ptr_helper(o, n);
2472 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2473 static char **o_finalize_list(o_string *o, int n)
2478 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2480 debug_print_list("finalized", o, n);
2481 debug_printf_expand("finalized n:%d\n", n);
2482 list = (char**)o->data;
2483 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2487 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2492 static void free_pipe_list(struct pipe *pi);
2494 /* Returns pi->next - next pipe in the list */
2495 static struct pipe *free_pipe(struct pipe *pi)
2500 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2501 for (i = 0; i < pi->num_cmds; i++) {
2502 struct command *command;
2503 struct redir_struct *r, *rnext;
2505 command = &pi->cmds[i];
2506 debug_printf_clean(" command %d:\n", i);
2507 if (command->argv) {
2511 for (a = 0, p = command->argv; *p; a++, p++) {
2512 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2515 free_strings(command->argv);
2516 //command->argv = NULL;
2518 /* not "else if": on syntax error, we may have both! */
2519 if (command->group) {
2520 debug_printf_clean(" begin group (cmd_type:%d)\n",
2522 free_pipe_list(command->group);
2523 debug_printf_clean(" end group\n");
2524 //command->group = NULL;
2526 /* else is crucial here.
2527 * If group != NULL, child_func is meaningless */
2528 #if ENABLE_HUSH_FUNCTIONS
2529 else if (command->child_func) {
2530 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2531 command->child_func->parent_cmd = NULL;
2535 free(command->group_as_string);
2536 //command->group_as_string = NULL;
2538 for (r = command->redirects; r; r = rnext) {
2539 debug_printf_clean(" redirect %d%s",
2540 r->rd_fd, redir_table[r->rd_type].descrip);
2541 /* guard against the case >$FOO, where foo is unset or blank */
2542 if (r->rd_filename) {
2543 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2544 free(r->rd_filename);
2545 //r->rd_filename = NULL;
2547 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2551 //command->redirects = NULL;
2553 free(pi->cmds); /* children are an array, they get freed all at once */
2557 //pi->cmdtext = NULL;
2565 static void free_pipe_list(struct pipe *pi)
2569 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2571 debug_printf_clean("pipe followup code %d\n", pi->followup);
2577 /*** Parsing routines ***/
2579 static struct pipe *new_pipe(void)
2582 pi = xzalloc(sizeof(struct pipe));
2583 /*pi->followup = 0; - deliberately invalid value */
2584 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2588 /* Command (member of a pipe) is complete, or we start a new pipe
2589 * if ctx->command is NULL.
2590 * No errors possible here.
2592 static int done_command(struct parse_context *ctx)
2594 /* The command is really already in the pipe structure, so
2595 * advance the pipe counter and make a new, null command. */
2596 struct pipe *pi = ctx->pipe;
2597 struct command *command = ctx->command;
2600 if (IS_NULL_CMD(command)) {
2601 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2605 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2606 //debug_print_tree(ctx->list_head, 20);
2608 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2611 /* Only real trickiness here is that the uncommitted
2612 * command structure is not counted in pi->num_cmds. */
2613 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2614 ctx->command = command = &pi->cmds[pi->num_cmds];
2616 memset(command, 0, sizeof(*command));
2617 return pi->num_cmds; /* used only for 0/nonzero check */
2620 static void done_pipe(struct parse_context *ctx, pipe_style type)
2624 debug_printf_parse("done_pipe entered, followup %d\n", type);
2625 /* Close previous command */
2626 not_null = done_command(ctx);
2627 ctx->pipe->followup = type;
2629 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2630 ctx->ctx_inverted = 0;
2631 ctx->pipe->res_word = ctx->ctx_res_w;
2634 /* Without this check, even just <enter> on command line generates
2635 * tree of three NOPs (!). Which is harmless but annoying.
2636 * IOW: it is safe to do it unconditionally. */
2639 || ctx->ctx_res_w == RES_FI
2641 #if ENABLE_HUSH_LOOPS
2642 || ctx->ctx_res_w == RES_DONE
2643 || ctx->ctx_res_w == RES_FOR
2644 || ctx->ctx_res_w == RES_IN
2646 #if ENABLE_HUSH_CASE
2647 || ctx->ctx_res_w == RES_ESAC
2651 debug_printf_parse("done_pipe: adding new pipe: "
2652 "not_null:%d ctx->ctx_res_w:%d\n",
2653 not_null, ctx->ctx_res_w);
2655 ctx->pipe->next = new_p;
2657 /* RES_THEN, RES_DO etc are "sticky" -
2658 * they remain set for pipes inside if/while.
2659 * This is used to control execution.
2660 * RES_FOR and RES_IN are NOT sticky (needed to support
2661 * cases where variable or value happens to match a keyword):
2663 #if ENABLE_HUSH_LOOPS
2664 if (ctx->ctx_res_w == RES_FOR
2665 || ctx->ctx_res_w == RES_IN)
2666 ctx->ctx_res_w = RES_NONE;
2668 #if ENABLE_HUSH_CASE
2669 if (ctx->ctx_res_w == RES_MATCH)
2670 ctx->ctx_res_w = RES_CASE_BODY;
2671 if (ctx->ctx_res_w == RES_CASE)
2672 ctx->ctx_res_w = RES_CASE_IN;
2674 ctx->command = NULL; /* trick done_command below */
2675 /* Create the memory for command, roughly:
2676 * ctx->pipe->cmds = new struct command;
2677 * ctx->command = &ctx->pipe->cmds[0];
2680 //debug_print_tree(ctx->list_head, 10);
2682 debug_printf_parse("done_pipe return\n");
2685 static void initialize_context(struct parse_context *ctx)
2687 memset(ctx, 0, sizeof(*ctx));
2688 ctx->pipe = ctx->list_head = new_pipe();
2689 /* Create the memory for command, roughly:
2690 * ctx->pipe->cmds = new struct command;
2691 * ctx->command = &ctx->pipe->cmds[0];
2696 /* If a reserved word is found and processed, parse context is modified
2697 * and 1 is returned.
2700 struct reserved_combo {
2703 unsigned char assignment_flag;
2707 FLAG_END = (1 << RES_NONE ),
2709 FLAG_IF = (1 << RES_IF ),
2710 FLAG_THEN = (1 << RES_THEN ),
2711 FLAG_ELIF = (1 << RES_ELIF ),
2712 FLAG_ELSE = (1 << RES_ELSE ),
2713 FLAG_FI = (1 << RES_FI ),
2715 # if ENABLE_HUSH_LOOPS
2716 FLAG_FOR = (1 << RES_FOR ),
2717 FLAG_WHILE = (1 << RES_WHILE),
2718 FLAG_UNTIL = (1 << RES_UNTIL),
2719 FLAG_DO = (1 << RES_DO ),
2720 FLAG_DONE = (1 << RES_DONE ),
2721 FLAG_IN = (1 << RES_IN ),
2723 # if ENABLE_HUSH_CASE
2724 FLAG_MATCH = (1 << RES_MATCH),
2725 FLAG_ESAC = (1 << RES_ESAC ),
2727 FLAG_START = (1 << RES_XXXX ),
2730 static const struct reserved_combo* match_reserved_word(o_string *word)
2732 /* Mostly a list of accepted follow-up reserved words.
2733 * FLAG_END means we are done with the sequence, and are ready
2734 * to turn the compound list into a command.
2735 * FLAG_START means the word must start a new compound list.
2737 static const struct reserved_combo reserved_list[] = {
2739 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2740 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2741 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2742 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2743 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2744 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2746 # if ENABLE_HUSH_LOOPS
2747 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2748 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2749 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2750 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2751 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2752 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2754 # if ENABLE_HUSH_CASE
2755 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2756 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2759 const struct reserved_combo *r;
2761 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2762 if (strcmp(word->data, r->literal) == 0)
2767 /* Return 0: not a keyword, 1: keyword
2769 static int reserved_word(o_string *word, struct parse_context *ctx)
2771 # if ENABLE_HUSH_CASE
2772 static const struct reserved_combo reserved_match = {
2773 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2776 const struct reserved_combo *r;
2778 if (word->has_quoted_part)
2780 r = match_reserved_word(word);
2784 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2785 # if ENABLE_HUSH_CASE
2786 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2787 /* "case word IN ..." - IN part starts first MATCH part */
2788 r = &reserved_match;
2791 if (r->flag == 0) { /* '!' */
2792 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2793 syntax_error("! ! command");
2794 ctx->ctx_res_w = RES_SNTX;
2796 ctx->ctx_inverted = 1;
2799 if (r->flag & FLAG_START) {
2800 struct parse_context *old;
2802 old = xmalloc(sizeof(*old));
2803 debug_printf_parse("push stack %p\n", old);
2804 *old = *ctx; /* physical copy */
2805 initialize_context(ctx);
2807 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2808 syntax_error_at(word->data);
2809 ctx->ctx_res_w = RES_SNTX;
2812 /* "{...} fi" is ok. "{...} if" is not
2814 * if { echo foo; } then { echo bar; } fi */
2815 if (ctx->command->group)
2816 done_pipe(ctx, PIPE_SEQ);
2819 ctx->ctx_res_w = r->res;
2820 ctx->old_flag = r->flag;
2821 word->o_assignment = r->assignment_flag;
2823 if (ctx->old_flag & FLAG_END) {
2824 struct parse_context *old;
2826 done_pipe(ctx, PIPE_SEQ);
2827 debug_printf_parse("pop stack %p\n", ctx->stack);
2829 old->command->group = ctx->list_head;
2830 old->command->cmd_type = CMD_NORMAL;
2832 o_addstr(&old->as_string, ctx->as_string.data);
2833 o_free_unsafe(&ctx->as_string);
2834 old->command->group_as_string = xstrdup(old->as_string.data);
2835 debug_printf_parse("pop, remembering as:'%s'\n",
2836 old->command->group_as_string);
2838 *ctx = *old; /* physical copy */
2843 #endif /* HAS_KEYWORDS */
2845 /* Word is complete, look at it and update parsing context.
2846 * Normal return is 0. Syntax errors return 1.
2847 * Note: on return, word is reset, but not o_free'd!
2849 static int done_word(o_string *word, struct parse_context *ctx)
2851 struct command *command = ctx->command;
2853 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2854 if (word->length == 0 && !word->has_quoted_part) {
2855 debug_printf_parse("done_word return 0: true null, ignored\n");
2859 if (ctx->pending_redirect) {
2860 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2861 * only if run as "bash", not "sh" */
2862 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2864 * ...the word that follows the redirection operator
2865 * shall be subjected to tilde expansion, parameter expansion,
2866 * command substitution, arithmetic expansion, and quote
2867 * removal. Pathname expansion shall not be performed
2868 * on the word by a non-interactive shell; an interactive
2869 * shell may perform it, but shall do so only when
2870 * the expansion would result in one word."
2872 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2873 /* Cater for >\file case:
2874 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2875 * Same with heredocs:
2876 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2878 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2879 unbackslash(ctx->pending_redirect->rd_filename);
2880 /* Is it <<"HEREDOC"? */
2881 if (word->has_quoted_part) {
2882 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2885 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2886 ctx->pending_redirect = NULL;
2888 /* If this word wasn't an assignment, next ones definitely
2889 * can't be assignments. Even if they look like ones. */
2890 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2891 && word->o_assignment != WORD_IS_KEYWORD
2893 word->o_assignment = NOT_ASSIGNMENT;
2895 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2896 command->assignment_cnt++;
2897 word->o_assignment = MAYBE_ASSIGNMENT;
2901 # if ENABLE_HUSH_CASE
2902 if (ctx->ctx_dsemicolon
2903 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2905 /* already done when ctx_dsemicolon was set to 1: */
2906 /* ctx->ctx_res_w = RES_MATCH; */
2907 ctx->ctx_dsemicolon = 0;
2910 if (!command->argv /* if it's the first word... */
2911 # if ENABLE_HUSH_LOOPS
2912 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2913 && ctx->ctx_res_w != RES_IN
2915 # if ENABLE_HUSH_CASE
2916 && ctx->ctx_res_w != RES_CASE
2919 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2920 if (reserved_word(word, ctx)) {
2921 o_reset_to_empty_unquoted(word);
2922 debug_printf_parse("done_word return %d\n",
2923 (ctx->ctx_res_w == RES_SNTX));
2924 return (ctx->ctx_res_w == RES_SNTX);
2926 # if ENABLE_HUSH_BASH_COMPAT
2927 if (strcmp(word->data, "[[") == 0) {
2928 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2934 if (command->group) {
2935 /* "{ echo foo; } echo bar" - bad */
2936 syntax_error_at(word->data);
2937 debug_printf_parse("done_word return 1: syntax error, "
2938 "groups and arglists don't mix\n");
2941 if (word->has_quoted_part
2942 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2943 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2944 /* (otherwise it's known to be not empty and is already safe) */
2946 /* exclude "$@" - it can expand to no word despite "" */
2947 char *p = word->data;
2948 while (p[0] == SPECIAL_VAR_SYMBOL
2949 && (p[1] & 0x7f) == '@'
2950 && p[2] == SPECIAL_VAR_SYMBOL
2954 if (p == word->data || p[0] != '\0') {
2955 /* saw no "$@", or not only "$@" but some
2956 * real text is there too */
2957 /* insert "empty variable" reference, this makes
2958 * e.g. "", $empty"" etc to not disappear */
2959 o_addchr(word, SPECIAL_VAR_SYMBOL);
2960 o_addchr(word, SPECIAL_VAR_SYMBOL);
2963 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2964 debug_print_strings("word appended to argv", command->argv);
2967 #if ENABLE_HUSH_LOOPS
2968 if (ctx->ctx_res_w == RES_FOR) {
2969 if (word->has_quoted_part
2970 || !is_well_formed_var_name(command->argv[0], '\0')
2972 /* bash says just "not a valid identifier" */
2973 syntax_error("not a valid identifier in for");
2976 /* Force FOR to have just one word (variable name) */
2977 /* NB: basically, this makes hush see "for v in ..."
2978 * syntax as if it is "for v; in ...". FOR and IN become
2979 * two pipe structs in parse tree. */
2980 done_pipe(ctx, PIPE_SEQ);
2983 #if ENABLE_HUSH_CASE
2984 /* Force CASE to have just one word */
2985 if (ctx->ctx_res_w == RES_CASE) {
2986 done_pipe(ctx, PIPE_SEQ);
2990 o_reset_to_empty_unquoted(word);
2992 debug_printf_parse("done_word return 0\n");
2997 /* Peek ahead in the input to find out if we have a "&n" construct,
2998 * as in "2>&1", that represents duplicating a file descriptor.
3000 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3001 * REDIRFD_SYNTAX_ERR if syntax error,
3002 * REDIRFD_TO_FILE if no & was seen,
3003 * or the number found.
3006 #define parse_redir_right_fd(as_string, input) \
3007 parse_redir_right_fd(input)
3009 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3015 return REDIRFD_TO_FILE;
3017 ch = i_getch(input); /* get the & */
3018 nommu_addchr(as_string, ch);
3021 ch = i_getch(input);
3022 nommu_addchr(as_string, ch);
3023 return REDIRFD_CLOSE;
3027 while (ch != EOF && isdigit(ch)) {
3028 d = d*10 + (ch-'0');
3030 ch = i_getch(input);
3031 nommu_addchr(as_string, ch);
3036 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3038 bb_error_msg("ambiguous redirect");
3039 return REDIRFD_SYNTAX_ERR;
3042 /* Return code is 0 normal, 1 if a syntax error is detected
3044 static int parse_redirect(struct parse_context *ctx,
3047 struct in_str *input)
3049 struct command *command = ctx->command;
3050 struct redir_struct *redir;
3051 struct redir_struct **redirp;
3054 dup_num = REDIRFD_TO_FILE;
3055 if (style != REDIRECT_HEREDOC) {
3056 /* Check for a '>&1' type redirect */
3057 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3058 if (dup_num == REDIRFD_SYNTAX_ERR)
3061 int ch = i_peek(input);
3062 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3063 if (dup_num) { /* <<-... */
3064 ch = i_getch(input);
3065 nommu_addchr(&ctx->as_string, ch);
3070 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3071 int ch = i_peek(input);
3073 /* >|FILE redirect ("clobbering" >).
3074 * Since we do not support "set -o noclobber" yet,
3075 * >| and > are the same for now. Just eat |.
3077 ch = i_getch(input);
3078 nommu_addchr(&ctx->as_string, ch);
3082 /* Create a new redir_struct and append it to the linked list */
3083 redirp = &command->redirects;
3084 while ((redir = *redirp) != NULL) {
3085 redirp = &(redir->next);
3087 *redirp = redir = xzalloc(sizeof(*redir));
3088 /* redir->next = NULL; */
3089 /* redir->rd_filename = NULL; */
3090 redir->rd_type = style;
3091 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3093 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3094 redir_table[style].descrip);
3096 redir->rd_dup = dup_num;
3097 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3098 /* Erik had a check here that the file descriptor in question
3099 * is legit; I postpone that to "run time"
3100 * A "-" representation of "close me" shows up as a -3 here */
3101 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3102 redir->rd_fd, redir->rd_dup);
3104 /* Set ctx->pending_redirect, so we know what to do at the
3105 * end of the next parsed word. */
3106 ctx->pending_redirect = redir;
3111 /* If a redirect is immediately preceded by a number, that number is
3112 * supposed to tell which file descriptor to redirect. This routine
3113 * looks for such preceding numbers. In an ideal world this routine
3114 * needs to handle all the following classes of redirects...
3115 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3116 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3117 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3118 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3120 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3122 * ... If n is quoted, the number shall not be recognized as part of
3123 * the redirection expression. For example:
3125 * writes the character 2 into file a"
3126 * We are getting it right by setting ->has_quoted_part on any \<char>
3128 * A -1 return means no valid number was found,
3129 * the caller should use the appropriate default for this redirection.
3131 static int redirect_opt_num(o_string *o)
3135 if (o->data == NULL)
3137 num = bb_strtou(o->data, NULL, 10);
3138 if (errno || num < 0)
3140 o_reset_to_empty_unquoted(o);
3145 #define fetch_till_str(as_string, input, word, skip_tabs) \
3146 fetch_till_str(input, word, skip_tabs)
3148 static char *fetch_till_str(o_string *as_string,
3149 struct in_str *input,
3153 o_string heredoc = NULL_O_STRING;
3155 int prev = 0; /* not \ */
3160 ch = i_getch(input);
3162 nommu_addchr(as_string, ch);
3163 if ((ch == '\n' || ch == EOF)
3164 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3166 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3167 heredoc.data[past_EOL] = '\0';
3168 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3169 return heredoc.data;
3171 while (ch == '\n') {
3172 o_addchr(&heredoc, ch);
3175 past_EOL = heredoc.length;
3177 ch = i_getch(input);
3179 nommu_addchr(as_string, ch);
3180 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3184 o_free_unsafe(&heredoc);
3187 o_addchr(&heredoc, ch);
3188 nommu_addchr(as_string, ch);
3189 if (prev == '\\' && ch == '\\')
3190 /* Correctly handle foo\\<eol> (not a line cont.) */
3191 prev = 0; /* not \ */
3197 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3198 * and load them all. There should be exactly heredoc_cnt of them.
3200 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3202 struct pipe *pi = ctx->list_head;
3204 while (pi && heredoc_cnt) {
3206 struct command *cmd = pi->cmds;
3208 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3210 cmd->argv ? cmd->argv[0] : "NONE");
3211 for (i = 0; i < pi->num_cmds; i++) {
3212 struct redir_struct *redir = cmd->redirects;
3214 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3215 i, cmd->argv ? cmd->argv[0] : "NONE");
3217 if (redir->rd_type == REDIRECT_HEREDOC) {
3220 redir->rd_type = REDIRECT_HEREDOC2;
3221 /* redir->rd_dup is (ab)used to indicate <<- */
3222 p = fetch_till_str(&ctx->as_string, input,
3223 redir->rd_filename, redir->rd_dup);
3225 syntax_error("unexpected EOF in here document");
3228 free(redir->rd_filename);
3229 redir->rd_filename = p;
3232 redir = redir->next;
3239 /* Should be 0. If it isn't, it's a parse error */
3241 bb_error_msg_and_die("heredoc BUG 2");
3247 static int run_list(struct pipe *pi);
3249 #define parse_stream(pstring, input, end_trigger) \
3250 parse_stream(input, end_trigger)
3252 static struct pipe *parse_stream(char **pstring,
3253 struct in_str *input,
3257 #if !ENABLE_HUSH_FUNCTIONS
3258 #define parse_group(dest, ctx, input, ch) \
3259 parse_group(ctx, input, ch)
3261 static int parse_group(o_string *dest, struct parse_context *ctx,
3262 struct in_str *input, int ch)
3264 /* dest contains characters seen prior to ( or {.
3265 * Typically it's empty, but for function defs,
3266 * it contains function name (without '()'). */
3267 struct pipe *pipe_list;
3269 struct command *command = ctx->command;
3271 debug_printf_parse("parse_group entered\n");
3272 #if ENABLE_HUSH_FUNCTIONS
3273 if (ch == '(' && !dest->has_quoted_part) {
3275 if (done_word(dest, ctx))
3278 goto skip; /* (... */
3279 if (command->argv[1]) { /* word word ... (... */
3280 syntax_error_unexpected_ch('(');
3283 /* it is "word(..." or "word (..." */
3285 ch = i_getch(input);
3286 while (ch == ' ' || ch == '\t');
3288 syntax_error_unexpected_ch(ch);
3291 nommu_addchr(&ctx->as_string, ch);
3293 ch = i_getch(input);
3294 while (ch == ' ' || ch == '\t' || ch == '\n');
3296 syntax_error_unexpected_ch(ch);
3299 nommu_addchr(&ctx->as_string, ch);
3300 command->cmd_type = CMD_FUNCDEF;
3305 #if 0 /* Prevented by caller */
3306 if (command->argv /* word [word]{... */
3307 || dest->length /* word{... */
3308 || dest->has_quoted_part /* ""{... */
3311 debug_printf_parse("parse_group return 1: "
3312 "syntax error, groups and arglists don't mix\n");
3317 #if ENABLE_HUSH_FUNCTIONS
3323 command->cmd_type = CMD_SUBSHELL;
3325 /* bash does not allow "{echo...", requires whitespace */
3326 ch = i_getch(input);
3327 if (ch != ' ' && ch != '\t' && ch != '\n') {
3328 syntax_error_unexpected_ch(ch);
3331 nommu_addchr(&ctx->as_string, ch);
3336 # define as_string NULL
3338 char *as_string = NULL;
3340 pipe_list = parse_stream(&as_string, input, endch);
3343 o_addstr(&ctx->as_string, as_string);
3345 /* empty ()/{} or parse error? */
3346 if (!pipe_list || pipe_list == ERR_PTR) {
3347 /* parse_stream already emitted error msg */
3350 debug_printf_parse("parse_group return 1: "
3351 "parse_stream returned %p\n", pipe_list);
3354 command->group = pipe_list;
3356 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3357 command->group_as_string = as_string;
3358 debug_printf_parse("end of group, remembering as:'%s'\n",
3359 command->group_as_string);
3363 debug_printf_parse("parse_group return 0\n");
3365 /* command remains "open", available for possible redirects */
3368 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3369 /* Subroutines for copying $(...) and `...` things */
3370 static void add_till_backquote(o_string *dest, struct in_str *input);
3372 static void add_till_single_quote(o_string *dest, struct in_str *input)
3375 int ch = i_getch(input);
3377 syntax_error_unterm_ch('\'');
3378 /*xfunc_die(); - redundant */
3385 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3386 static void add_till_double_quote(o_string *dest, struct in_str *input)
3389 int ch = i_getch(input);
3391 syntax_error_unterm_ch('"');
3392 /*xfunc_die(); - redundant */
3396 if (ch == '\\') { /* \x. Copy both chars. */
3398 ch = i_getch(input);
3402 add_till_backquote(dest, input);
3406 //if (ch == '$') ...
3409 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3411 * "Within the backquoted style of command substitution, backslash
3412 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3413 * The search for the matching backquote shall be satisfied by the first
3414 * backquote found without a preceding backslash; during this search,
3415 * if a non-escaped backquote is encountered within a shell comment,
3416 * a here-document, an embedded command substitution of the $(command)
3417 * form, or a quoted string, undefined results occur. A single-quoted
3418 * or double-quoted string that begins, but does not end, within the
3419 * "`...`" sequence produces undefined results."
3421 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3423 static void add_till_backquote(o_string *dest, struct in_str *input)
3426 int ch = i_getch(input);
3428 syntax_error_unterm_ch('`');
3429 /*xfunc_die(); - redundant */
3434 /* \x. Copy both chars unless it is \` */
3435 int ch2 = i_getch(input);
3437 syntax_error_unterm_ch('`');
3438 /*xfunc_die(); - redundant */
3440 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3447 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3448 * quoting and nested ()s.
3449 * "With the $(command) style of command substitution, all characters
3450 * following the open parenthesis to the matching closing parenthesis
3451 * constitute the command. Any valid shell script can be used for command,
3452 * except a script consisting solely of redirections which produces
3453 * unspecified results."
3455 * echo $(echo '(TEST)' BEST) (TEST) BEST
3456 * echo $(echo 'TEST)' BEST) TEST) BEST
3457 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3459 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3460 * can contain arbitrary constructs, just like $(cmd).
3461 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3462 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3464 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3465 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3468 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3469 # if ENABLE_HUSH_BASH_COMPAT
3470 char end_char2 = end_ch >> 8;
3472 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3475 ch = i_getch(input);
3477 syntax_error_unterm_ch(end_ch);
3478 /*xfunc_die(); - redundant */
3480 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3483 /* we look for closing )) of $((EXPR)) */
3484 if (i_peek(input) == end_ch) {
3485 i_getch(input); /* eat second ')' */
3490 if (ch == '(' || ch == '{') {
3491 ch = (ch == '(' ? ')' : '}');
3492 add_till_closing_bracket(dest, input, ch);
3497 add_till_single_quote(dest, input);
3502 add_till_double_quote(dest, input);
3507 add_till_backquote(dest, input);
3512 /* \x. Copy verbatim. Important for \(, \) */
3513 ch = i_getch(input);
3515 syntax_error_unterm_ch(')');
3516 /*xfunc_die(); - redundant */
3524 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3526 /* Return code: 0 for OK, 1 for syntax error */
3528 #define parse_dollar(as_string, dest, input, quote_mask) \
3529 parse_dollar(dest, input, quote_mask)
3530 #define as_string NULL
3532 static int parse_dollar(o_string *as_string,
3534 struct in_str *input, unsigned char quote_mask)
3536 int ch = i_peek(input); /* first character after the $ */
3538 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3540 ch = i_getch(input);
3541 nommu_addchr(as_string, ch);
3543 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3545 debug_printf_parse(": '%c'\n", ch);
3546 o_addchr(dest, ch | quote_mask);
3549 if (!isalnum(ch) && ch != '_')
3551 ch = i_getch(input);
3552 nommu_addchr(as_string, ch);
3554 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3555 } else if (isdigit(ch)) {
3557 ch = i_getch(input);
3558 nommu_addchr(as_string, ch);
3559 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3560 debug_printf_parse(": '%c'\n", ch);
3561 o_addchr(dest, ch | quote_mask);
3562 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3563 } else switch (ch) {
3565 case '!': /* last bg pid */
3566 case '?': /* last exit code */
3567 case '#': /* number of args */
3568 case '*': /* args */
3569 case '@': /* args */
3570 goto make_one_char_var;
3572 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3574 ch = i_getch(input); /* eat '{' */
3575 nommu_addchr(as_string, ch);
3577 ch = i_getch(input); /* first char after '{' */
3578 /* It should be ${?}, or ${#var},
3579 * or even ${?+subst} - operator acting on a special variable,
3580 * or the beginning of variable name.
3583 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3586 syntax_error_unterm_str("${name}");
3587 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3590 nommu_addchr(as_string, ch);
3593 /* It's possible to just call add_till_closing_bracket() at this point.
3594 * However, this regresses some of our testsuite cases
3595 * which check invalid constructs like ${%}.
3596 * Oh well... let's check that the var name part is fine... */
3602 debug_printf_parse(": '%c'\n", ch);
3604 ch = i_getch(input);
3605 nommu_addchr(as_string, ch);
3609 if (!isalnum(ch) && ch != '_') {
3611 unsigned char last_ch;
3612 /* handle parameter expansions
3613 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3615 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3616 goto bad_dollar_syntax;
3618 /* Eat everything until closing '}' (or ':') */
3620 if (ENABLE_HUSH_BASH_COMPAT
3622 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3624 /* It's ${var:N[:M]} thing */
3625 end_ch = '}' * 0x100 + ':';
3627 if (ENABLE_HUSH_BASH_COMPAT
3630 /* It's ${var/[/]pattern[/repl]} thing */
3631 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3633 nommu_addchr(as_string, '/');
3636 end_ch = '}' * 0x100 + '/';
3642 #if ENABLE_HUSH_DOLLAR_OPS
3643 last_ch = add_till_closing_bracket(dest, input, end_ch);
3645 #error Simple code to only allow ${var} is not implemented
3648 o_addstr(as_string, dest->data + pos);
3649 o_addchr(as_string, last_ch);
3652 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3653 /* close the first block: */
3654 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3655 /* while parsing N from ${var:N[:M]}
3656 * or pattern from ${var/[/]pattern[/repl]} */
3657 if ((end_ch & 0xff) == last_ch) {
3658 /* got ':' or '/'- parse the rest */
3663 if (end_ch == '}' * 0x100 + ':') {
3664 /* it's ${var:N} - emulate :999999999 */
3665 o_addstr(dest, "999999999");
3666 } /* else: it's ${var/[/]pattern} */
3671 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3674 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3678 ch = i_getch(input);
3679 nommu_addchr(as_string, ch);
3680 # if ENABLE_SH_MATH_SUPPORT
3681 if (i_peek(input) == '(') {
3682 ch = i_getch(input);
3683 nommu_addchr(as_string, ch);
3684 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3685 o_addchr(dest, /*quote_mask |*/ '+');
3688 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3690 o_addstr(as_string, dest->data + pos);
3691 o_addchr(as_string, ')');
3692 o_addchr(as_string, ')');
3694 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3698 # if ENABLE_HUSH_TICK
3699 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3700 o_addchr(dest, quote_mask | '`');
3703 add_till_closing_bracket(dest, input, ')');
3705 o_addstr(as_string, dest->data + pos);
3706 o_addchr(as_string, ')');
3708 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3714 ch = i_getch(input);
3715 nommu_addchr(as_string, ch);
3717 if (isalnum(ch)) { /* it's $_name or $_123 */
3722 /* TODO: $_ and $-: */
3723 /* $_ Shell or shell script name; or last argument of last command
3724 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3725 * but in command's env, set to full pathname used to invoke it */
3726 /* $- Option flags set by set builtin or shell options (-i etc) */
3728 o_addQchr(dest, '$');
3730 debug_printf_parse("parse_dollar return 0\n");
3736 # if ENABLE_HUSH_BASH_COMPAT
3737 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3738 encode_string(dest, input, dquote_end, process_bkslash)
3740 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3741 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3742 encode_string(dest, input, dquote_end)
3744 #define as_string NULL
3748 # if ENABLE_HUSH_BASH_COMPAT
3749 /* all parameters are needed, no macro tricks */
3751 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3752 encode_string(as_string, dest, input, dquote_end)
3755 static int encode_string(o_string *as_string,
3757 struct in_str *input,
3759 int process_bkslash)
3761 #if !ENABLE_HUSH_BASH_COMPAT
3762 const int process_bkslash = 1;
3768 ch = i_getch(input);
3770 nommu_addchr(as_string, ch);
3771 if (ch == dquote_end) { /* may be only '"' or EOF */
3772 debug_printf_parse("encode_string return 0\n");
3775 /* note: can't move it above ch == dquote_end check! */
3777 syntax_error_unterm_ch('"');
3778 /*xfunc_die(); - redundant */
3782 next = i_peek(input);
3784 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3785 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3786 if (process_bkslash && ch == '\\') {
3788 syntax_error("\\<eof>");
3792 * "The backslash retains its special meaning [in "..."]
3793 * only when followed by one of the following characters:
3794 * $, `, ", \, or <newline>. A double quote may be quoted
3795 * within double quotes by preceding it with a backslash."
3796 * NB: in (unquoted) heredoc, above does not apply to ",
3797 * therefore we check for it by "next == dquote_end" cond.
3799 if (next == dquote_end || strchr("$`\\\n", next)) {
3800 ch = i_getch(input); /* eat next */
3802 goto again; /* skip \<newline> */
3803 } /* else: ch remains == '\\', and we double it below: */
3804 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3805 nommu_addchr(as_string, ch);
3809 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3810 debug_printf_parse("encode_string return 1: "
3811 "parse_dollar returned non-0\n");
3816 #if ENABLE_HUSH_TICK
3818 //unsigned pos = dest->length;
3819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3820 o_addchr(dest, 0x80 | '`');
3821 add_till_backquote(dest, input);
3822 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3823 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3827 o_addQchr(dest, ch);
3833 * Scan input until EOF or end_trigger char.
3834 * Return a list of pipes to execute, or NULL on EOF
3835 * or if end_trigger character is met.
3836 * On syntax error, exit is shell is not interactive,
3837 * reset parsing machinery and start parsing anew,
3838 * or return ERR_PTR.
3840 static struct pipe *parse_stream(char **pstring,
3841 struct in_str *input,
3844 struct parse_context ctx;
3845 o_string dest = NULL_O_STRING;
3848 /* Single-quote triggers a bypass of the main loop until its mate is
3849 * found. When recursing, quote state is passed in via dest->o_expflags.
3851 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3852 end_trigger ? end_trigger : 'X');
3855 /* If very first arg is "" or '', dest.data may end up NULL.
3856 * Preventing this: */
3857 o_addchr(&dest, '\0');
3860 /* We used to separate words on $IFS here. This was wrong.
3861 * $IFS is used only for word splitting when $var is expanded,
3862 * here we should use blank chars as separators, not $IFS
3865 reset: /* we come back here only on syntax errors in interactive shell */
3867 #if ENABLE_HUSH_INTERACTIVE
3868 input->promptmode = 0; /* PS1 */
3870 if (MAYBE_ASSIGNMENT != 0)
3871 dest.o_assignment = MAYBE_ASSIGNMENT;
3872 initialize_context(&ctx);
3875 const char *is_blank;
3876 const char *is_special;
3880 redir_type redir_style;
3882 ch = i_getch(input);
3883 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3884 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3889 syntax_error_unterm_str("here document");
3892 /* end_trigger == '}' case errors out earlier,
3893 * checking only ')' */
3894 if (end_trigger == ')') {
3895 syntax_error_unterm_ch('('); /* exits */
3896 /* goto parse_error; */
3899 if (done_word(&dest, &ctx)) {
3903 done_pipe(&ctx, PIPE_SEQ);
3905 /* If we got nothing... */
3906 /* (this makes bare "&" cmd a no-op.
3907 * bash says: "syntax error near unexpected token '&'") */
3908 if (pi->num_cmds == 0
3909 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3915 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3917 *pstring = ctx.as_string.data;
3919 o_free_unsafe(&ctx.as_string);
3922 debug_printf_parse("parse_stream return %p\n", pi);
3925 nommu_addchr(&ctx.as_string, ch);
3929 next = i_peek(input);
3931 is_special = "{}<>;&|()#'" /* special outside of "str" */
3932 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3933 /* Are { and } special here? */
3934 if (ctx.command->argv /* word [word]{... - non-special */
3935 || dest.length /* word{... - non-special */
3936 || dest.has_quoted_part /* ""{... - non-special */
3937 || (next != ';' /* }; - special */
3938 && next != ')' /* }) - special */
3939 && next != '&' /* }& and }&& ... - special */
3940 && next != '|' /* }|| ... - special */
3941 && !strchr(defifs, next) /* {word - non-special */
3944 /* They are not special, skip "{}" */
3947 is_special = strchr(is_special, ch);
3948 is_blank = strchr(defifs, ch);
3950 if (!is_special && !is_blank) { /* ordinary char */
3952 o_addQchr(&dest, ch);
3953 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3954 || dest.o_assignment == WORD_IS_KEYWORD)
3956 && is_well_formed_var_name(dest.data, '=')
3958 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3964 if (done_word(&dest, &ctx)) {
3968 #if ENABLE_HUSH_CASE
3969 /* "case ... in <newline> word) ..." -
3970 * newlines are ignored (but ';' wouldn't be) */
3971 if (ctx.command->argv == NULL
3972 && ctx.ctx_res_w == RES_MATCH
3977 /* Treat newline as a command separator. */
3978 done_pipe(&ctx, PIPE_SEQ);
3979 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3981 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3986 dest.o_assignment = MAYBE_ASSIGNMENT;
3988 /* note: if (is_blank) continue;
3989 * will still trigger for us */
3993 /* "cmd}" or "cmd }..." without semicolon or &:
3994 * } is an ordinary char in this case, even inside { cmd; }
3995 * Pathological example: { ""}; } should exec "}" cmd
3998 if (!IS_NULL_CMD(ctx.command) /* cmd } */
3999 || dest.length != 0 /* word} */
4000 || dest.has_quoted_part /* ""} */
4004 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4005 goto skip_end_trigger;
4006 /* else: } does terminate a group */
4009 if (end_trigger && end_trigger == ch
4010 && (ch != ';' || heredoc_cnt == 0)
4011 #if ENABLE_HUSH_CASE
4013 || ctx.ctx_res_w != RES_MATCH
4014 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4019 /* This is technically valid:
4020 * { cat <<HERE; }; echo Ok
4024 * but we don't support this.
4025 * We require heredoc to be in enclosing {}/(),
4028 syntax_error_unterm_str("here document");
4031 if (done_word(&dest, &ctx)) {
4034 done_pipe(&ctx, PIPE_SEQ);
4035 dest.o_assignment = MAYBE_ASSIGNMENT;
4036 /* Do we sit outside of any if's, loops or case's? */
4038 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4042 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4044 *pstring = ctx.as_string.data;
4046 o_free_unsafe(&ctx.as_string);
4049 debug_printf_parse("parse_stream return %p: "
4050 "end_trigger char found\n",
4052 return ctx.list_head;
4059 /* Catch <, > before deciding whether this word is
4060 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4063 redir_fd = redirect_opt_num(&dest);
4064 if (done_word(&dest, &ctx)) {
4067 redir_style = REDIRECT_OVERWRITE;
4069 redir_style = REDIRECT_APPEND;
4070 ch = i_getch(input);
4071 nommu_addchr(&ctx.as_string, ch);
4074 else if (next == '(') {
4075 syntax_error(">(process) not supported");
4079 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4081 continue; /* back to top of while (1) */
4083 redir_fd = redirect_opt_num(&dest);
4084 if (done_word(&dest, &ctx)) {
4087 redir_style = REDIRECT_INPUT;
4089 redir_style = REDIRECT_HEREDOC;
4091 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4092 ch = i_getch(input);
4093 nommu_addchr(&ctx.as_string, ch);
4094 } else if (next == '>') {
4095 redir_style = REDIRECT_IO;
4096 ch = i_getch(input);
4097 nommu_addchr(&ctx.as_string, ch);
4100 else if (next == '(') {
4101 syntax_error("<(process) not supported");
4105 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4107 continue; /* back to top of while (1) */
4110 if (dest.o_assignment == MAYBE_ASSIGNMENT
4111 /* check that we are not in word in "a=1 2>word b=1": */
4112 && !ctx.pending_redirect
4114 /* ch is a special char and thus this word
4115 * cannot be an assignment */
4116 dest.o_assignment = NOT_ASSIGNMENT;
4119 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4123 if (dest.length == 0) {
4126 if (ch == EOF || ch == '\n')
4129 /* note: we do not add it to &ctx.as_string */
4131 nommu_addchr(&ctx.as_string, '\n');
4133 o_addQchr(&dest, ch);
4138 syntax_error("\\<eof>");
4141 ch = i_getch(input);
4143 o_addchr(&dest, '\\');
4144 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4145 o_addchr(&dest, ch);
4146 nommu_addchr(&ctx.as_string, ch);
4147 /* Example: echo Hello \2>file
4148 * we need to know that word 2 is quoted */
4149 dest.has_quoted_part = 1;
4153 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4154 ctx.as_string.data[--ctx.as_string.length] = '\0';
4159 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4160 debug_printf_parse("parse_stream parse error: "
4161 "parse_dollar returned non-0\n");
4166 dest.has_quoted_part = 1;
4168 ch = i_getch(input);
4170 syntax_error_unterm_ch('\'');
4171 /*xfunc_die(); - redundant */
4173 nommu_addchr(&ctx.as_string, ch);
4176 o_addqchr(&dest, ch);
4180 dest.has_quoted_part = 1;
4181 if (dest.o_assignment == NOT_ASSIGNMENT)
4182 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4183 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4185 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4187 #if ENABLE_HUSH_TICK
4191 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4192 o_addchr(&dest, '`');
4194 add_till_backquote(&dest, input);
4196 o_addstr(&ctx.as_string, dest.data + pos);
4197 o_addchr(&ctx.as_string, '`');
4199 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4200 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4205 #if ENABLE_HUSH_CASE
4208 if (done_word(&dest, &ctx)) {
4211 done_pipe(&ctx, PIPE_SEQ);
4212 #if ENABLE_HUSH_CASE
4213 /* Eat multiple semicolons, detect
4214 * whether it means something special */
4219 ch = i_getch(input);
4220 nommu_addchr(&ctx.as_string, ch);
4221 if (ctx.ctx_res_w == RES_CASE_BODY) {
4222 ctx.ctx_dsemicolon = 1;
4223 ctx.ctx_res_w = RES_MATCH;
4229 /* We just finished a cmd. New one may start
4230 * with an assignment */
4231 dest.o_assignment = MAYBE_ASSIGNMENT;
4234 if (done_word(&dest, &ctx)) {
4238 ch = i_getch(input);
4239 nommu_addchr(&ctx.as_string, ch);
4240 done_pipe(&ctx, PIPE_AND);
4242 done_pipe(&ctx, PIPE_BG);
4246 if (done_word(&dest, &ctx)) {
4249 #if ENABLE_HUSH_CASE
4250 if (ctx.ctx_res_w == RES_MATCH)
4251 break; /* we are in case's "word | word)" */
4253 if (next == '|') { /* || */
4254 ch = i_getch(input);
4255 nommu_addchr(&ctx.as_string, ch);
4256 done_pipe(&ctx, PIPE_OR);
4258 /* we could pick up a file descriptor choice here
4259 * with redirect_opt_num(), but bash doesn't do it.
4260 * "echo foo 2| cat" yields "foo 2". */
4263 o_reset_to_empty_unquoted(&ctx.as_string);
4268 #if ENABLE_HUSH_CASE
4269 /* "case... in [(]word)..." - skip '(' */
4270 if (ctx.ctx_res_w == RES_MATCH
4271 && ctx.command->argv == NULL /* not (word|(... */
4272 && dest.length == 0 /* not word(... */
4273 && dest.has_quoted_part == 0 /* not ""(... */
4279 if (parse_group(&dest, &ctx, input, ch) != 0) {
4284 #if ENABLE_HUSH_CASE
4285 if (ctx.ctx_res_w == RES_MATCH)
4289 /* proper use of this character is caught by end_trigger:
4290 * if we see {, we call parse_group(..., end_trigger='}')
4291 * and it will match } earlier (not here). */
4292 syntax_error_unexpected_ch(ch);
4296 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4302 struct parse_context *pctx;
4303 IF_HAS_KEYWORDS(struct parse_context *p2;)
4305 /* Clean up allocated tree.
4306 * Sample for finding leaks on syntax error recovery path.
4307 * Run it from interactive shell, watch pmap `pidof hush`.
4308 * while if false; then false; fi; do break; fi
4309 * Samples to catch leaks at execution:
4310 * while if (true | {true;}); then echo ok; fi; do break; done
4311 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4315 /* Update pipe/command counts,
4316 * otherwise freeing may miss some */
4317 done_pipe(pctx, PIPE_SEQ);
4318 debug_printf_clean("freeing list %p from ctx %p\n",
4319 pctx->list_head, pctx);
4320 debug_print_tree(pctx->list_head, 0);
4321 free_pipe_list(pctx->list_head);
4322 debug_printf_clean("freed list %p\n", pctx->list_head);
4324 o_free_unsafe(&pctx->as_string);
4326 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4330 IF_HAS_KEYWORDS(pctx = p2;)
4331 } while (HAS_KEYWORDS && pctx);
4332 /* Free text, clear all dest fields */
4334 /* If we are not in top-level parse, we return,
4335 * our caller will propagate error.
4337 if (end_trigger != ';') {
4345 /* Discard cached input, force prompt */
4347 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4353 /*** Execution routines ***/
4355 /* Expansion can recurse, need forward decls: */
4356 #if !ENABLE_HUSH_BASH_COMPAT
4357 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4358 #define expand_string_to_string(str, do_unbackslash) \
4359 expand_string_to_string(str)
4361 static char *expand_string_to_string(const char *str, int do_unbackslash);
4362 static int process_command_subs(o_string *dest, const char *s);
4364 /* expand_strvec_to_strvec() takes a list of strings, expands
4365 * all variable references within and returns a pointer to
4366 * a list of expanded strings, possibly with larger number
4367 * of strings. (Think VAR="a b"; echo $VAR).
4368 * This new list is allocated as a single malloc block.
4369 * NULL-terminated list of char* pointers is at the beginning of it,
4370 * followed by strings themselves.
4371 * Caller can deallocate entire list by single free(list). */
4373 /* Store given string, finalizing the word and starting new one whenever
4374 * we encounter IFS char(s). This is used for expanding variable values.
4375 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4376 static int expand_on_ifs(o_string *output, int n, const char *str)
4379 int word_len = strcspn(str, G.ifs);
4381 if (!(output->o_expflags & EXP_FLAG_GLOB))
4382 o_addblock(output, str, word_len);
4384 /* Protect backslashes against globbing up :)
4385 * Example: "v='\*'; echo b$v" prints "b\*"
4386 * (and does not try to glob on "*")
4388 o_addblock_duplicate_backslash(output, str, word_len);
4389 /*/ Why can't we do it easier? */
4390 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4391 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4395 if (!*str) /* EOL - do not finalize word */
4397 o_addchr(output, '\0');
4398 debug_print_list("expand_on_ifs", output, n);
4399 n = o_save_ptr(output, n);
4400 str += strspn(str, G.ifs); /* skip ifs chars */
4402 debug_print_list("expand_on_ifs[1]", output, n);
4406 /* Helper to expand $((...)) and heredoc body. These act as if
4407 * they are in double quotes, with the exception that they are not :).
4408 * Just the rules are similar: "expand only $var and `cmd`"
4410 * Returns malloced string.
4411 * As an optimization, we return NULL if expansion is not needed.
4413 #if !ENABLE_HUSH_BASH_COMPAT
4414 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4415 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4416 encode_then_expand_string(str)
4418 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4421 struct in_str input;
4422 o_string dest = NULL_O_STRING;
4424 if (!strchr(str, '$')
4425 && !strchr(str, '\\')
4426 #if ENABLE_HUSH_TICK
4427 && !strchr(str, '`')
4433 /* We need to expand. Example:
4434 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4436 setup_string_in_str(&input, str);
4437 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4438 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4439 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4440 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4441 o_free_unsafe(&dest);
4445 #if ENABLE_SH_MATH_SUPPORT
4446 static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
4448 arith_eval_hooks_t hooks;
4452 hooks.lookupvar = get_local_var_value;
4453 hooks.setvar = set_local_var_from_halves;
4454 //hooks.endofname = endofname;
4455 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4456 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
4462 #if ENABLE_HUSH_BASH_COMPAT
4463 /* ${var/[/]pattern[/repl]} helpers */
4464 static char *strstr_pattern(char *val, const char *pattern, int *size)
4467 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4468 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4475 /* Optimization: if "*pat" did not match the start of "string",
4476 * we know that "tring", "ring" etc will not match too:
4478 if (pattern[0] == '*')
4483 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4485 char *result = NULL;
4486 unsigned res_len = 0;
4487 unsigned repl_len = strlen(repl);
4491 char *s = strstr_pattern(val, pattern, &size);
4495 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4496 memcpy(result + res_len, val, s - val);
4498 strcpy(result + res_len, repl);
4499 res_len += repl_len;
4500 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4506 if (val[0] && result) {
4507 result = xrealloc(result, res_len + strlen(val) + 1);
4508 strcpy(result + res_len, val);
4509 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4511 debug_printf_varexp("result:'%s'\n", result);
4517 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4519 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4521 const char *val = NULL;
4522 char *to_be_freed = NULL;
4527 char exp_save = exp_save; /* for compiler */
4528 char *exp_saveptr; /* points to expansion operator */
4529 char *exp_word = exp_word; /* for compiler */
4532 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4534 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4536 first_char = arg[0] = arg0 & 0x7f;
4539 if (first_char == '#' /* ${#... */
4540 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4542 /* It must be length operator: ${#var} */
4546 /* Maybe handle parameter expansion */
4547 if (exp_saveptr /* if 2nd char is one of expansion operators */
4548 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4550 /* ${?:0}, ${#[:]%0} etc */
4551 exp_saveptr = var + 1;
4553 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4554 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4556 exp_op = exp_save = *exp_saveptr;
4558 exp_word = exp_saveptr + 1;
4559 if (exp_op == ':') {
4560 exp_op = *exp_word++;
4561 //TODO: try ${var:} and ${var:bogus} in non-bash config
4562 if (ENABLE_HUSH_BASH_COMPAT
4563 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4565 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4570 *exp_saveptr = '\0';
4571 } /* else: it's not an expansion op, but bare ${var} */
4574 /* Look up the variable in question */
4575 if (isdigit(var[0])) {
4576 /* parse_dollar should have vetted var for us */
4577 int n = xatoi_positive(var);
4578 if (n < G.global_argc)
4579 val = G.global_argv[n];
4580 /* else val remains NULL: $N with too big N */
4584 val = utoa(G.root_pid);
4586 case '!': /* bg pid */
4587 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4589 case '?': /* exitcode */
4590 val = utoa(G.last_exitcode);
4592 case '#': /* argc */
4593 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4596 val = get_local_var_value(var);
4600 /* Handle any expansions */
4601 if (exp_op == 'L') {
4602 debug_printf_expand("expand: length(%s)=", val);
4603 val = utoa(val ? strlen(val) : 0);
4604 debug_printf_expand("%s\n", val);
4605 } else if (exp_op) {
4606 if (exp_op == '%' || exp_op == '#') {
4607 /* Standard-mandated substring removal ops:
4608 * ${parameter%word} - remove smallest suffix pattern
4609 * ${parameter%%word} - remove largest suffix pattern
4610 * ${parameter#word} - remove smallest prefix pattern
4611 * ${parameter##word} - remove largest prefix pattern
4613 * Word is expanded to produce a glob pattern.
4614 * Then var's value is matched to it and matching part removed.
4616 if (val && val[0]) {
4620 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4621 if (exp_op == *exp_word) /* ## or %% */
4623 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4625 exp_word = exp_exp_word;
4626 /* HACK ALERT. We depend here on the fact that
4627 * G.global_argv and results of utoa and get_local_var_value
4628 * are actually in writable memory:
4629 * scan_and_match momentarily stores NULs there. */
4631 loc = scan_and_match(t, exp_word, scan_flags);
4632 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4633 // exp_op, t, exp_word, loc);
4635 if (loc) { /* match was found */
4636 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4637 val = loc; /* take right part */
4639 val = to_be_freed = xstrndup(val, loc - val); /* left */
4643 #if ENABLE_HUSH_BASH_COMPAT
4644 else if (exp_op == '/' || exp_op == '\\') {
4645 /* It's ${var/[/]pattern[/repl]} thing.
4646 * Note that in encoded form it has TWO parts:
4647 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4648 * and if // is used, it is encoded as \:
4649 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4651 /* Empty variable always gives nothing: */
4652 // "v=''; echo ${v/*/w}" prints "", not "w"
4653 if (val && val[0]) {
4654 /* pattern uses non-standard expansion.
4655 * repl should be unbackslashed and globbed
4656 * by the usual expansion rules:
4658 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4659 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4660 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4661 * v='a bz'; echo ${v/a*z/\z} prints "z"
4662 * (note that a*z _pattern_ is never globbed!)
4664 char *pattern, *repl, *t;
4665 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4667 pattern = xstrdup(exp_word);
4668 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4669 *p++ = SPECIAL_VAR_SYMBOL;
4671 p = strchr(p, SPECIAL_VAR_SYMBOL);
4673 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4674 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4675 /* HACK ALERT. We depend here on the fact that
4676 * G.global_argv and results of utoa and get_local_var_value
4677 * are actually in writable memory:
4678 * replace_pattern momentarily stores NULs there. */
4680 to_be_freed = replace_pattern(t,
4682 (repl ? repl : exp_word),
4684 if (to_be_freed) /* at least one replace happened */
4691 else if (exp_op == ':') {
4692 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4693 /* It's ${var:N[:M]} bashism.
4694 * Note that in encoded form it has TWO parts:
4695 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4700 beg = expand_and_evaluate_arith(exp_word, &errcode);
4701 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4702 *p++ = SPECIAL_VAR_SYMBOL;
4704 p = strchr(p, SPECIAL_VAR_SYMBOL);
4706 len = expand_and_evaluate_arith(exp_word, &errcode);
4707 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4709 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
4710 if (beg < 0) /* bash compat */
4712 debug_printf_varexp("from val:'%s'\n", val);
4713 if (len == 0 || !val || beg >= strlen(val))
4716 /* Paranoia. What if user entered 9999999999999
4717 * which fits in arith_t but not int? */
4720 val = to_be_freed = xstrndup(val + beg, len);
4722 debug_printf_varexp("val:'%s'\n", val);
4726 die_if_script("malformed ${%s:...}", var);
4729 } else { /* one of "-=+?" */
4730 /* Standard-mandated substitution ops:
4731 * ${var?word} - indicate error if unset
4732 * If var is unset, word (or a message indicating it is unset
4733 * if word is null) is written to standard error
4734 * and the shell exits with a non-zero exit status.
4735 * Otherwise, the value of var is substituted.
4736 * ${var-word} - use default value
4737 * If var is unset, word is substituted.
4738 * ${var=word} - assign and use default value
4739 * If var is unset, word is assigned to var.
4740 * In all cases, final value of var is substituted.
4741 * ${var+word} - use alternative value
4742 * If var is unset, null is substituted.
4743 * Otherwise, word is substituted.
4745 * Word is subjected to tilde expansion, parameter expansion,
4746 * command substitution, and arithmetic expansion.
4747 * If word is not needed, it is not expanded.
4749 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4750 * but also treat null var as if it is unset.
4752 int use_word = (!val || ((exp_save == ':') && !val[0]));
4754 use_word = !use_word;
4755 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4756 (exp_save == ':') ? "true" : "false", use_word);
4758 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4760 exp_word = to_be_freed;
4761 if (exp_op == '?') {
4762 /* mimic bash message */
4763 die_if_script("%s: %s",
4765 exp_word[0] ? exp_word : "parameter null or not set"
4767 //TODO: how interactive bash aborts expansion mid-command?
4772 if (exp_op == '=') {
4773 /* ${var=[word]} or ${var:=[word]} */
4774 if (isdigit(var[0]) || var[0] == '#') {
4775 /* mimic bash message */
4776 die_if_script("$%s: cannot assign in this way", var);
4779 char *new_var = xasprintf("%s=%s", var, val);
4780 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4784 } /* one of "-=+?" */
4786 *exp_saveptr = exp_save;
4792 *to_be_freed_pp = to_be_freed;
4796 /* Expand all variable references in given string, adding words to list[]
4797 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4798 * to be filled). This routine is extremely tricky: has to deal with
4799 * variables/parameters with whitespace, $* and $@, and constructs like
4800 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4801 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4803 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4804 * expansion of right-hand side of assignment == 1-element expand.
4806 char cant_be_null = 0; /* only bit 0x80 matters */
4809 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4810 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4811 debug_print_list("expand_vars_to_list", output, n);
4812 n = o_save_ptr(output, n);
4813 debug_print_list("expand_vars_to_list[0]", output, n);
4815 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4817 char *to_be_freed = NULL;
4818 const char *val = NULL;
4819 #if ENABLE_HUSH_TICK
4820 o_string subst_result = NULL_O_STRING;
4822 #if ENABLE_SH_MATH_SUPPORT
4823 char arith_buf[sizeof(arith_t)*3 + 2];
4825 o_addblock(output, arg, p - arg);
4826 debug_print_list("expand_vars_to_list[1]", output, n);
4828 p = strchr(p, SPECIAL_VAR_SYMBOL);
4830 /* Fetch special var name (if it is indeed one of them)
4831 * and quote bit, force the bit on if singleword expansion -
4832 * important for not getting v=$@ expand to many words. */
4833 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4835 /* Is this variable quoted and thus expansion can't be null?
4836 * "$@" is special. Even if quoted, it can still
4837 * expand to nothing (not even an empty string),
4838 * thus it is excluded. */
4839 if ((first_ch & 0x7f) != '@')
4840 cant_be_null |= first_ch;
4842 switch (first_ch & 0x7f) {
4843 /* Highest bit in first_ch indicates that var is double-quoted */
4847 if (!G.global_argv[1])
4850 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4851 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4852 while (G.global_argv[i]) {
4853 n = expand_on_ifs(output, n, G.global_argv[i]);
4854 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4855 if (G.global_argv[i++][0] && G.global_argv[i]) {
4856 /* this argv[] is not empty and not last:
4857 * put terminating NUL, start new word */
4858 o_addchr(output, '\0');
4859 debug_print_list("expand_vars_to_list[2]", output, n);
4860 n = o_save_ptr(output, n);
4861 debug_print_list("expand_vars_to_list[3]", output, n);
4865 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4866 * and in this case should treat it like '$*' - see 'else...' below */
4867 if (first_ch == ('@'|0x80) /* quoted $@ */
4868 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4871 o_addQstr(output, G.global_argv[i]);
4872 if (++i >= G.global_argc)
4874 o_addchr(output, '\0');
4875 debug_print_list("expand_vars_to_list[4]", output, n);
4876 n = o_save_ptr(output, n);
4878 } else { /* quoted $* (or v="$@" case): add as one word */
4880 o_addQstr(output, G.global_argv[i]);
4881 if (!G.global_argv[++i])
4884 o_addchr(output, G.ifs[0]);
4889 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4890 /* "Empty variable", used to make "" etc to not disappear */
4892 cant_be_null = 0x80;
4894 #if ENABLE_HUSH_TICK
4895 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4896 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4898 /* Can't just stuff it into output o_string,
4899 * expanded result may need to be globbed
4900 * and $IFS-splitted */
4901 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4902 G.last_exitcode = process_command_subs(&subst_result, arg);
4903 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4904 val = subst_result.data;
4907 #if ENABLE_SH_MATH_SUPPORT
4908 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4912 arg++; /* skip '+' */
4913 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4914 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4915 res = expand_and_evaluate_arith(arg, &errcode);
4918 const char *msg = "error in arithmetic";
4921 msg = "exponent less than 0";
4924 msg = "divide by 0";
4927 msg = "expression recursion loop detected";
4932 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
4933 sprintf(arith_buf, arith_t_fmt, res);
4939 val = expand_one_var(&to_be_freed, arg, &p);
4940 IF_HUSH_TICK(store_val:)
4941 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4942 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4943 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4944 if (val && val[0]) {
4945 n = expand_on_ifs(output, n, val);
4948 } else { /* quoted $VAR, val will be appended below */
4949 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4950 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4954 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4956 if (val && val[0]) {
4957 o_addQstr(output, val);
4961 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4962 * Do the check to avoid writing to a const string. */
4963 if (*p != SPECIAL_VAR_SYMBOL)
4964 *p = SPECIAL_VAR_SYMBOL;
4966 #if ENABLE_HUSH_TICK
4967 o_free(&subst_result);
4970 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4973 debug_print_list("expand_vars_to_list[a]", output, n);
4974 /* this part is literal, and it was already pre-quoted
4975 * if needed (much earlier), do not use o_addQstr here! */
4976 o_addstr_with_NUL(output, arg);
4977 debug_print_list("expand_vars_to_list[b]", output, n);
4978 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
4979 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
4982 /* allow to reuse list[n] later without re-growth */
4983 output->has_empty_slot = 1;
4985 o_addchr(output, '\0');
4991 static char **expand_variables(char **argv, unsigned expflags)
4995 o_string output = NULL_O_STRING;
4997 output.o_expflags = expflags;
5001 n = expand_vars_to_list(&output, n, *argv);
5004 debug_print_list("expand_variables", &output, n);
5006 /* output.data (malloced in one block) gets returned in "list" */
5007 list = o_finalize_list(&output, n);
5008 debug_print_strings("expand_variables[1]", list);
5012 static char **expand_strvec_to_strvec(char **argv)
5014 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5017 #if ENABLE_HUSH_BASH_COMPAT
5018 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5020 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5024 /* Used for expansion of right hand of assignments,
5025 * $((...)), heredocs, variable espansion parts.
5027 * NB: should NOT do globbing!
5028 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5030 static char *expand_string_to_string(const char *str, int do_unbackslash)
5032 #if !ENABLE_HUSH_BASH_COMPAT
5033 const int do_unbackslash = 1;
5035 char *argv[2], **list;
5037 debug_printf_expand("string_to_string<='%s'\n", str);
5038 /* This is generally an optimization, but it also
5039 * handles "", which otherwise trips over !list[0] check below.
5040 * (is this ever happens that we actually get str="" here?)
5042 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5043 //TODO: Can use on strings with \ too, just unbackslash() them?
5044 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5045 return xstrdup(str);
5048 argv[0] = (char*)str;
5050 list = expand_variables(argv, do_unbackslash
5051 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5052 : EXP_FLAG_SINGLEWORD
5055 if (!list[0] || list[1])
5056 bb_error_msg_and_die("BUG in varexp2");
5057 /* actually, just move string 2*sizeof(char*) bytes back */
5058 overlapping_strcpy((char*)list, list[0]);
5060 unbackslash((char*)list);
5061 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5065 /* Used for "eval" builtin */
5066 static char* expand_strvec_to_string(char **argv)
5070 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5071 /* Convert all NULs to spaces */
5076 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5077 bb_error_msg_and_die("BUG in varexp3");
5078 /* bash uses ' ' regardless of $IFS contents */
5083 overlapping_strcpy((char*)list, list[0]);
5084 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5088 static char **expand_assignments(char **argv, int count)
5093 G.expanded_assignments = p = NULL;
5094 /* Expand assignments into one string each */
5095 for (i = 0; i < count; i++) {
5096 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5098 G.expanded_assignments = NULL;
5105 void re_execute_shell(char ***to_free, const char *s,
5106 char *g_argv0, char **g_argv,
5107 char **builtin_argv) NORETURN;
5109 static void reset_traps_to_defaults(void)
5111 /* This function is always called in a child shell
5112 * after fork (not vfork, NOMMU doesn't use this function).
5117 /* Child shells are not interactive.
5118 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5119 * Testcase: (while :; do :; done) + ^Z should background.
5120 * Same goes for SIGTERM, SIGHUP, SIGINT.
5122 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5123 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5125 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5126 * Stupid. It can be done with *single* &= op, but we can't use
5127 * the fact that G.blocked_set is implemented as a bitmask
5129 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5133 /* Careful. Only if no trap or trap is not "" */
5134 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5135 sigdelset(&G.blocked_set, sig);
5142 /* Our homegrown sig mask is saner to work with :) */
5143 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5145 /* Resetting all traps to default except empty ones */
5146 mask = G.non_DFL_mask;
5147 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5148 if (!G.traps[sig] || !G.traps[sig][0])
5151 G.traps[sig] = NULL;
5152 /* There is no signal for 0 (EXIT) */
5155 /* There was a trap handler, we just removed it.
5156 * But if sig still has non-DFL handling,
5157 * we should not unblock the sig. */
5160 sigdelset(&G.blocked_set, sig);
5162 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5167 static void re_execute_shell(char ***to_free, const char *s,
5168 char *g_argv0, char **g_argv,
5169 char **builtin_argv) NORETURN;
5170 static void re_execute_shell(char ***to_free, const char *s,
5171 char *g_argv0, char **g_argv,
5172 char **builtin_argv)
5174 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5175 /* delims + 2 * (number of bytes in printed hex numbers) */
5176 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5177 char *heredoc_argv[4];
5178 struct variable *cur;
5179 # if ENABLE_HUSH_FUNCTIONS
5180 struct function *funcp;
5184 unsigned long long empty_trap_mask;
5186 if (!g_argv0) { /* heredoc */
5187 argv = heredoc_argv;
5188 argv[0] = (char *) G.argv0_for_re_execing;
5189 argv[1] = (char *) "-<";
5190 argv[2] = (char *) s;
5192 pp = &argv[3]; /* used as pointer to empty environment */
5198 if (pp) while (*pp++)
5201 empty_trap_mask = 0;
5204 for (sig = 1; sig < NSIG; sig++) {
5205 if (G.traps[sig] && !G.traps[sig][0])
5206 empty_trap_mask |= 1LL << sig;
5210 sprintf(param_buf, NOMMU_HACK_FMT
5211 , (unsigned) G.root_pid
5212 , (unsigned) G.root_ppid
5213 , (unsigned) G.last_bg_pid
5214 , (unsigned) G.last_exitcode
5217 IF_HUSH_LOOPS(, G.depth_of_loop)
5219 # undef NOMMU_HACK_FMT
5220 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5221 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5224 for (cur = G.top_var; cur; cur = cur->next) {
5225 if (!cur->flg_export || cur->flg_read_only)
5228 # if ENABLE_HUSH_FUNCTIONS
5229 for (funcp = G.top_func; funcp; funcp = funcp->next)
5235 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5236 *pp++ = (char *) G.argv0_for_re_execing;
5238 for (cur = G.top_var; cur; cur = cur->next) {
5239 if (strcmp(cur->varstr, hush_version_str) == 0)
5241 if (cur->flg_read_only) {
5242 *pp++ = (char *) "-R";
5243 *pp++ = cur->varstr;
5244 } else if (!cur->flg_export) {
5245 *pp++ = (char *) "-V";
5246 *pp++ = cur->varstr;
5249 # if ENABLE_HUSH_FUNCTIONS
5250 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5251 *pp++ = (char *) "-F";
5252 *pp++ = funcp->name;
5253 *pp++ = funcp->body_as_string;
5256 /* We can pass activated traps here. Say, -Tnn:trap_string
5258 * However, POSIX says that subshells reset signals with traps
5260 * I tested bash-3.2 and it not only does that with true subshells
5261 * of the form ( list ), but with any forked children shells.
5262 * I set trap "echo W" WINCH; and then tried:
5264 * { echo 1; sleep 20; echo 2; } &
5265 * while true; do echo 1; sleep 20; echo 2; break; done &
5266 * true | { echo 1; sleep 20; echo 2; } | cat
5268 * In all these cases sending SIGWINCH to the child shell
5269 * did not run the trap. If I add trap "echo V" WINCH;
5270 * _inside_ group (just before echo 1), it works.
5272 * I conclude it means we don't need to pass active traps here.
5273 * Even if we would use signal handlers instead of signal masking
5274 * in order to implement trap handling,
5275 * exec syscall below resets signals to SIG_DFL for us.
5277 *pp++ = (char *) "-c";
5280 while (*++builtin_argv)
5281 *pp++ = *builtin_argv;
5282 *pp++ = (char *) "";
5287 /* *pp = NULL; - is already there */
5291 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5292 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5293 execve(bb_busybox_exec_path, argv, pp);
5294 /* Fallback. Useful for init=/bin/hush usage etc */
5295 if (argv[0][0] == '/')
5296 execve(argv[0], argv, pp);
5297 xfunc_error_retval = 127;
5298 bb_error_msg_and_die("can't re-execute the shell");
5300 #endif /* !BB_MMU */
5303 static int run_and_free_list(struct pipe *pi);
5305 /* Executing from string: eval, sh -c '...'
5306 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5307 * end_trigger controls how often we stop parsing
5308 * NUL: parse all, execute, return
5309 * ';': parse till ';' or newline, execute, repeat till EOF
5311 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5313 /* Why we need empty flag?
5314 * An obscure corner case "false; ``; echo $?":
5315 * empty command in `` should still set $? to 0.
5316 * But we can't just set $? to 0 at the start,
5317 * this breaks "false; echo `echo $?`" case.
5321 struct pipe *pipe_list;
5323 pipe_list = parse_stream(NULL, inp, end_trigger);
5324 if (!pipe_list) { /* EOF */
5326 G.last_exitcode = 0;
5329 debug_print_tree(pipe_list, 0);
5330 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5331 run_and_free_list(pipe_list);
5336 static void parse_and_run_string(const char *s)
5338 struct in_str input;
5339 setup_string_in_str(&input, s);
5340 parse_and_run_stream(&input, '\0');
5343 static void parse_and_run_file(FILE *f)
5345 struct in_str input;
5346 setup_file_in_str(&input, f);
5347 parse_and_run_stream(&input, ';');
5350 #if ENABLE_HUSH_TICK
5351 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5356 char **to_free = NULL;
5360 pid = BB_MMU ? xfork() : xvfork();
5361 if (pid == 0) { /* child */
5362 disable_restore_tty_pgrp_on_exit();
5363 /* Process substitution is not considered to be usual
5364 * 'command execution'.
5365 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5372 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5373 close(channel[0]); /* NB: close _first_, then move fd! */
5374 xmove_fd(channel[1], 1);
5375 /* Prevent it from trying to handle ctrl-z etc */
5376 IF_HUSH_JOB(G.run_list_level = 1;)
5377 /* Awful hack for `trap` or $(trap).
5379 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5380 * contains an example where "trap" is executed in a subshell:
5382 * save_traps=$(trap)
5384 * eval "$save_traps"
5386 * Standard does not say that "trap" in subshell shall print
5387 * parent shell's traps. It only says that its output
5388 * must have suitable form, but then, in the above example
5389 * (which is not supposed to be normative), it implies that.
5391 * bash (and probably other shell) does implement it
5392 * (traps are reset to defaults, but "trap" still shows them),
5393 * but as a result, "trap" logic is hopelessly messed up:
5396 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5397 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5398 * # true | trap <--- trap is in subshell - no output (ditto)
5399 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5400 * trap -- 'echo Ho' SIGWINCH
5401 * # echo `(trap)` <--- in subshell in subshell - output
5402 * trap -- 'echo Ho' SIGWINCH
5403 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5404 * trap -- 'echo Ho' SIGWINCH
5406 * The rules when to forget and when to not forget traps
5407 * get really complex and nonsensical.
5409 * Our solution: ONLY bare $(trap) or `trap` is special.
5411 s = skip_whitespace(s);
5412 if (strncmp(s, "trap", 4) == 0
5413 && skip_whitespace(s + 4)[0] == '\0'
5415 static const char *const argv[] = { NULL, NULL };
5416 builtin_trap((char**)argv);
5417 exit(0); /* not _exit() - we need to fflush */
5420 reset_traps_to_defaults();
5421 parse_and_run_string(s);
5422 _exit(G.last_exitcode);
5424 /* We re-execute after vfork on NOMMU. This makes this script safe:
5425 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5426 * huge=`cat BIG` # was blocking here forever
5429 re_execute_shell(&to_free,
5439 # if ENABLE_HUSH_FAST
5441 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5442 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5443 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5445 enable_restore_tty_pgrp_on_exit();
5450 close_on_exec_on(channel[0]);
5451 return xfdopen_for_read(channel[0]);
5454 /* Return code is exit status of the process that is run. */
5455 static int process_command_subs(o_string *dest, const char *s)
5458 struct in_str pipe_str;
5460 int status, ch, eol_cnt;
5462 fp = generate_stream_from_string(s, &pid);
5464 /* Now send results of command back into original context */
5465 setup_file_in_str(&pipe_str, fp);
5467 while ((ch = i_getch(&pipe_str)) != EOF) {
5473 o_addchr(dest, '\n');
5476 o_addQchr(dest, ch);
5479 debug_printf("done reading from `cmd` pipe, closing it\n");
5481 /* We need to extract exitcode. Test case
5482 * "true; echo `sleep 1; false` $?"
5484 safe_waitpid(pid, &status, 0);
5485 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5486 return WEXITSTATUS(status);
5488 #endif /* ENABLE_HUSH_TICK */
5491 static void setup_heredoc(struct redir_struct *redir)
5493 struct fd_pair pair;
5496 /* the _body_ of heredoc (misleading field name) */
5497 const char *heredoc = redir->rd_filename;
5504 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5505 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5509 len = strlen(heredoc);
5511 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5513 xmove_fd(pair.rd, redir->rd_fd);
5515 /* Try writing without forking. Newer kernels have
5516 * dynamically growing pipes. Must use non-blocking write! */
5519 written = write(pair.wr, heredoc, len);
5530 ndelay_off(pair.wr);
5532 /* Okay, pipe buffer was not big enough */
5533 /* Note: we must not create a stray child (bastard? :)
5534 * for the unsuspecting parent process. Child creates a grandchild
5535 * and exits before parent execs the process which consumes heredoc
5536 * (that exec happens after we return from this function) */
5543 disable_restore_tty_pgrp_on_exit();
5544 pid = BB_MMU ? xfork() : xvfork();
5548 close(redir->rd_fd); /* read side of the pipe */
5550 full_write(pair.wr, heredoc, len); /* may loop or block */
5553 /* Delegate blocking writes to another process */
5554 xmove_fd(pair.wr, STDOUT_FILENO);
5555 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5559 #if ENABLE_HUSH_FAST
5561 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5563 enable_restore_tty_pgrp_on_exit();
5569 wait(NULL); /* wait till child has died */
5572 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5573 * and stderr if they are redirected. */
5574 static int setup_redirects(struct command *prog, int squirrel[])
5577 struct redir_struct *redir;
5579 for (redir = prog->redirects; redir; redir = redir->next) {
5580 if (redir->rd_type == REDIRECT_HEREDOC2) {
5581 /* rd_fd<<HERE case */
5582 if (squirrel && redir->rd_fd < 3
5583 && squirrel[redir->rd_fd] < 0
5585 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5587 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5589 debug_printf_parse("set heredoc '%s'\n",
5590 redir->rd_filename);
5591 setup_heredoc(redir);
5595 if (redir->rd_dup == REDIRFD_TO_FILE) {
5596 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5598 if (redir->rd_filename == NULL) {
5599 /* Something went wrong in the parse.
5600 * Pretend it didn't happen */
5601 bb_error_msg("bug in redirect parse");
5604 mode = redir_table[redir->rd_type].mode;
5605 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5606 openfd = open_or_warn(p, mode);
5609 /* this could get lost if stderr has been redirected, but
5610 * bash and ash both lose it as well (though zsh doesn't!) */
5611 //what the above comment tries to say?
5615 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5616 openfd = redir->rd_dup;
5619 if (openfd != redir->rd_fd) {
5620 if (squirrel && redir->rd_fd < 3
5621 && squirrel[redir->rd_fd] < 0
5623 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5625 if (openfd == REDIRFD_CLOSE) {
5626 /* "n>-" means "close me" */
5627 close(redir->rd_fd);
5629 xdup2(openfd, redir->rd_fd);
5630 if (redir->rd_dup == REDIRFD_TO_FILE)
5638 static void restore_redirects(int squirrel[])
5641 for (i = 0; i < 3; i++) {
5644 /* We simply die on error */
5650 static char *find_in_path(const char *arg)
5653 const char *PATH = get_local_var_value("PATH");
5659 const char *end = strchrnul(PATH, ':');
5660 int sz = end - PATH; /* must be int! */
5664 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5666 /* We have xxx::yyyy in $PATH,
5667 * it means "use current dir" */
5670 if (access(ret, F_OK) == 0)
5683 static const struct built_in_command *find_builtin_helper(const char *name,
5684 const struct built_in_command *x,
5685 const struct built_in_command *end)
5688 if (strcmp(name, x->b_cmd) != 0) {
5692 debug_printf_exec("found builtin '%s'\n", name);
5697 static const struct built_in_command *find_builtin1(const char *name)
5699 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5701 static const struct built_in_command *find_builtin(const char *name)
5703 const struct built_in_command *x = find_builtin1(name);
5706 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5709 #if ENABLE_HUSH_FUNCTIONS
5710 static struct function **find_function_slot(const char *name)
5712 struct function **funcpp = &G.top_func;
5714 if (strcmp(name, (*funcpp)->name) == 0) {
5717 funcpp = &(*funcpp)->next;
5722 static const struct function *find_function(const char *name)
5724 const struct function *funcp = *find_function_slot(name);
5726 debug_printf_exec("found function '%s'\n", name);
5730 /* Note: takes ownership on name ptr */
5731 static struct function *new_function(char *name)
5733 struct function **funcpp = find_function_slot(name);
5734 struct function *funcp = *funcpp;
5736 if (funcp != NULL) {
5737 struct command *cmd = funcp->parent_cmd;
5738 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5740 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5742 /* Note: if !funcp->body, do not free body_as_string!
5743 * This is a special case of "-F name body" function:
5744 * body_as_string was not malloced! */
5746 free_pipe_list(funcp->body);
5748 free(funcp->body_as_string);
5752 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5753 cmd->argv[0] = funcp->name;
5754 cmd->group = funcp->body;
5756 cmd->group_as_string = funcp->body_as_string;
5760 debug_printf_exec("remembering new function '%s'\n", name);
5761 funcp = *funcpp = xzalloc(sizeof(*funcp));
5762 /*funcp->next = NULL;*/
5769 static void unset_func(const char *name)
5771 struct function **funcpp = find_function_slot(name);
5772 struct function *funcp = *funcpp;
5774 if (funcp != NULL) {
5775 debug_printf_exec("freeing function '%s'\n", funcp->name);
5776 *funcpp = funcp->next;
5777 /* funcp is unlinked now, deleting it.
5778 * Note: if !funcp->body, the function was created by
5779 * "-F name body", do not free ->body_as_string
5780 * and ->name as they were not malloced. */
5782 free_pipe_list(funcp->body);
5785 free(funcp->body_as_string);
5793 #define exec_function(to_free, funcp, argv) \
5794 exec_function(funcp, argv)
5796 static void exec_function(char ***to_free,
5797 const struct function *funcp,
5798 char **argv) NORETURN;
5799 static void exec_function(char ***to_free,
5800 const struct function *funcp,
5806 argv[0] = G.global_argv[0];
5807 G.global_argv = argv;
5811 /* On MMU, funcp->body is always non-NULL */
5812 n = run_list(funcp->body);
5816 re_execute_shell(to_free,
5817 funcp->body_as_string,
5824 static int run_function(const struct function *funcp, char **argv)
5830 save_and_replace_G_args(&sv, argv);
5832 /* "we are in function, ok to use return" */
5833 sv_flg = G.flag_return_in_progress;
5834 G.flag_return_in_progress = -1;
5835 # if ENABLE_HUSH_LOCAL
5836 G.func_nest_level++;
5839 /* On MMU, funcp->body is always non-NULL */
5842 /* Function defined by -F */
5843 parse_and_run_string(funcp->body_as_string);
5844 rc = G.last_exitcode;
5848 rc = run_list(funcp->body);
5851 # if ENABLE_HUSH_LOCAL
5853 struct variable *var;
5854 struct variable **var_pp;
5856 var_pp = &G.top_var;
5857 while ((var = *var_pp) != NULL) {
5858 if (var->func_nest_level < G.func_nest_level) {
5859 var_pp = &var->next;
5863 if (var->flg_export)
5864 bb_unsetenv(var->varstr);
5865 /* Remove from global list */
5866 *var_pp = var->next;
5872 G.func_nest_level--;
5875 G.flag_return_in_progress = sv_flg;
5877 restore_G_args(&sv, argv);
5881 #endif /* ENABLE_HUSH_FUNCTIONS */
5885 #define exec_builtin(to_free, x, argv) \
5886 exec_builtin(x, argv)
5888 #define exec_builtin(to_free, x, argv) \
5889 exec_builtin(to_free, argv)
5891 static void exec_builtin(char ***to_free,
5892 const struct built_in_command *x,
5893 char **argv) NORETURN;
5894 static void exec_builtin(char ***to_free,
5895 const struct built_in_command *x,
5899 int rcode = x->b_function(argv);
5903 /* On NOMMU, we must never block!
5904 * Example: { sleep 99 | read line; } & echo Ok
5906 re_execute_shell(to_free,
5915 static void execvp_or_die(char **argv) NORETURN;
5916 static void execvp_or_die(char **argv)
5918 debug_printf_exec("execing '%s'\n", argv[0]);
5919 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5920 execvp(argv[0], argv);
5921 bb_perror_msg("can't execute '%s'", argv[0]);
5922 _exit(127); /* bash compat */
5925 #if ENABLE_HUSH_MODE_X
5926 static void dump_cmd_in_x_mode(char **argv)
5928 if (G_x_mode && argv) {
5929 /* We want to output the line in one write op */
5937 len += strlen(argv[n++]) + 1;
5943 p += sprintf(p, " %s", argv[n++]);
5951 # define dump_cmd_in_x_mode(argv) ((void)0)
5955 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5956 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5957 #define pseudo_exec(nommu_save, command, argv_expanded) \
5958 pseudo_exec(command, argv_expanded)
5961 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5963 * Don't exit() here. If you don't exec, use _exit instead.
5964 * The at_exit handlers apparently confuse the calling process,
5965 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5966 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5967 char **argv, int assignment_cnt,
5968 char **argv_expanded) NORETURN;
5969 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5970 char **argv, int assignment_cnt,
5971 char **argv_expanded)
5975 new_env = expand_assignments(argv, assignment_cnt);
5976 dump_cmd_in_x_mode(new_env);
5978 if (!argv[assignment_cnt]) {
5979 /* Case when we are here: ... | var=val | ...
5980 * (note that we do not exit early, i.e., do not optimize out
5981 * expand_assignments(): think about ... | var=`sleep 1` | ...
5983 free_strings(new_env);
5984 _exit(EXIT_SUCCESS);
5988 set_vars_and_save_old(new_env);
5989 free(new_env); /* optional */
5990 /* we can also destroy set_vars_and_save_old's return value,
5993 nommu_save->new_env = new_env;
5994 nommu_save->old_vars = set_vars_and_save_old(new_env);
5997 if (argv_expanded) {
5998 argv = argv_expanded;
6000 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6002 nommu_save->argv = argv;
6005 dump_cmd_in_x_mode(argv);
6007 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6008 if (strchr(argv[0], '/') != NULL)
6012 /* Check if the command matches any of the builtins.
6013 * Depending on context, this might be redundant. But it's
6014 * easier to waste a few CPU cycles than it is to figure out
6015 * if this is one of those cases.
6018 /* On NOMMU, it is more expensive to re-execute shell
6019 * just in order to run echo or test builtin.
6020 * It's better to skip it here and run corresponding
6021 * non-builtin later. */
6022 const struct built_in_command *x;
6023 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6025 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6028 #if ENABLE_HUSH_FUNCTIONS
6029 /* Check if the command matches any functions */
6031 const struct function *funcp = find_function(argv[0]);
6033 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6038 #if ENABLE_FEATURE_SH_STANDALONE
6039 /* Check if the command matches any busybox applets */
6041 int a = find_applet_by_name(argv[0]);
6043 # if BB_MMU /* see above why on NOMMU it is not allowed */
6044 if (APPLET_IS_NOEXEC(a)) {
6045 debug_printf_exec("running applet '%s'\n", argv[0]);
6046 run_applet_no_and_exit(a, argv);
6049 /* Re-exec ourselves */
6050 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6051 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6052 execv(bb_busybox_exec_path, argv);
6053 /* If they called chroot or otherwise made the binary no longer
6054 * executable, fall through */
6059 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6062 execvp_or_die(argv);
6065 /* Called after [v]fork() in run_pipe
6067 static void pseudo_exec(nommu_save_t *nommu_save,
6068 struct command *command,
6069 char **argv_expanded) NORETURN;
6070 static void pseudo_exec(nommu_save_t *nommu_save,
6071 struct command *command,
6072 char **argv_expanded)
6074 if (command->argv) {
6075 pseudo_exec_argv(nommu_save, command->argv,
6076 command->assignment_cnt, argv_expanded);
6079 if (command->group) {
6080 /* Cases when we are here:
6083 * ... | ( list ) | ...
6084 * ... | { list } | ...
6088 debug_printf_exec("pseudo_exec: run_list\n");
6089 reset_traps_to_defaults();
6090 rcode = run_list(command->group);
6091 /* OK to leak memory by not calling free_pipe_list,
6092 * since this process is about to exit */
6095 re_execute_shell(&nommu_save->argv_from_re_execing,
6096 command->group_as_string,
6103 /* Case when we are here: ... | >file */
6104 debug_printf_exec("pseudo_exec'ed null command\n");
6105 _exit(EXIT_SUCCESS);
6109 static const char *get_cmdtext(struct pipe *pi)
6115 /* This is subtle. ->cmdtext is created only on first backgrounding.
6116 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6117 * On subsequent bg argv is trashed, but we won't use it */
6120 argv = pi->cmds[0].argv;
6121 if (!argv || !argv[0]) {
6122 pi->cmdtext = xzalloc(1);
6128 len += strlen(*argv) + 1;
6132 argv = pi->cmds[0].argv;
6134 len = strlen(*argv);
6135 memcpy(p, *argv, len);
6143 static void insert_bg_job(struct pipe *pi)
6145 struct pipe *job, **jobp;
6148 /* Linear search for the ID of the job to use */
6150 for (job = G.job_list; job; job = job->next)
6151 if (job->jobid >= pi->jobid)
6152 pi->jobid = job->jobid + 1;
6154 /* Add job to the list of running jobs */
6156 while ((job = *jobp) != NULL)
6158 job = *jobp = xmalloc(sizeof(*job));
6160 *job = *pi; /* physical copy */
6162 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6163 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6164 for (i = 0; i < pi->num_cmds; i++) {
6165 job->cmds[i].pid = pi->cmds[i].pid;
6166 /* all other fields are not used and stay zero */
6168 job->cmdtext = xstrdup(get_cmdtext(pi));
6170 if (G_interactive_fd)
6171 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6172 G.last_jobid = job->jobid;
6175 static void remove_bg_job(struct pipe *pi)
6177 struct pipe *prev_pipe;
6179 if (pi == G.job_list) {
6180 G.job_list = pi->next;
6182 prev_pipe = G.job_list;
6183 while (prev_pipe->next != pi)
6184 prev_pipe = prev_pipe->next;
6185 prev_pipe->next = pi->next;
6188 G.last_jobid = G.job_list->jobid;
6193 /* Remove a backgrounded job */
6194 static void delete_finished_bg_job(struct pipe *pi)
6201 /* Check to see if any processes have exited -- if they
6202 * have, figure out why and see if a job has completed */
6203 static int checkjobs(struct pipe *fg_pipe)
6213 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6215 attributes = WUNTRACED;
6216 if (fg_pipe == NULL)
6217 attributes |= WNOHANG;
6220 #if ENABLE_HUSH_FAST
6221 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6222 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6223 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6224 /* There was neither fork nor SIGCHLD since last waitpid */
6225 /* Avoid doing waitpid syscall if possible */
6226 if (!G.we_have_children) {
6230 if (fg_pipe == NULL) { /* is WNOHANG set? */
6231 /* We have children, but they did not exit
6232 * or stop yet (we saw no SIGCHLD) */
6235 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6239 /* Do we do this right?
6240 * bash-3.00# sleep 20 | false
6242 * [3]+ Stopped sleep 20 | false
6243 * bash-3.00# echo $?
6244 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6245 * [hush 1.14.0: yes we do it right]
6252 #if ENABLE_HUSH_FAST
6253 i = G.count_SIGCHLD;
6255 childpid = waitpid(-1, &status, attributes);
6256 if (childpid <= 0) {
6257 if (childpid && errno != ECHILD)
6258 bb_perror_msg("waitpid");
6259 #if ENABLE_HUSH_FAST
6260 else { /* Until next SIGCHLD, waitpid's are useless */
6261 G.we_have_children = (childpid == 0);
6262 G.handled_SIGCHLD = i;
6263 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6268 dead = WIFEXITED(status) || WIFSIGNALED(status);
6271 if (WIFSTOPPED(status))
6272 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6273 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6274 if (WIFSIGNALED(status))
6275 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6276 childpid, WTERMSIG(status), WEXITSTATUS(status));
6277 if (WIFEXITED(status))
6278 debug_printf_jobs("pid %d exited, exitcode %d\n",
6279 childpid, WEXITSTATUS(status));
6281 /* Were we asked to wait for fg pipe? */
6283 for (i = 0; i < fg_pipe->num_cmds; i++) {
6284 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6285 if (fg_pipe->cmds[i].pid != childpid)
6288 fg_pipe->cmds[i].pid = 0;
6289 fg_pipe->alive_cmds--;
6290 if (i == fg_pipe->num_cmds - 1) {
6291 /* last process gives overall exitstatus */
6292 rcode = WEXITSTATUS(status);
6293 /* bash prints killer signal's name for *last*
6294 * process in pipe (prints just newline for SIGINT).
6295 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6297 if (WIFSIGNALED(status)) {
6298 int sig = WTERMSIG(status);
6299 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6300 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6301 * Maybe we need to use sig | 128? */
6304 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6307 fg_pipe->cmds[i].is_stopped = 1;
6308 fg_pipe->stopped_cmds++;
6310 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6311 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6312 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6313 /* All processes in fg pipe have exited or stopped */
6314 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6315 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6316 * and "killall -STOP cat" */
6317 if (G_interactive_fd) {
6319 if (fg_pipe->alive_cmds)
6320 insert_bg_job(fg_pipe);
6324 if (!fg_pipe->alive_cmds)
6327 /* There are still running processes in the fg pipe */
6328 goto wait_more; /* do waitpid again */
6330 /* it wasnt fg_pipe, look for process in bg pipes */
6334 /* We asked to wait for bg or orphaned children */
6335 /* No need to remember exitcode in this case */
6336 for (pi = G.job_list; pi; pi = pi->next) {
6337 for (i = 0; i < pi->num_cmds; i++) {
6338 if (pi->cmds[i].pid == childpid)
6339 goto found_pi_and_prognum;
6342 /* Happens when shell is used as init process (init=/bin/sh) */
6343 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6344 continue; /* do waitpid again */
6346 found_pi_and_prognum:
6349 pi->cmds[i].pid = 0;
6351 if (!pi->alive_cmds) {
6352 if (G_interactive_fd)
6353 printf(JOB_STATUS_FORMAT, pi->jobid,
6354 "Done", pi->cmdtext);
6355 delete_finished_bg_job(pi);
6359 pi->cmds[i].is_stopped = 1;
6363 } /* while (waitpid succeeds)... */
6369 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6372 int rcode = checkjobs(fg_pipe);
6373 if (G_saved_tty_pgrp) {
6374 /* Job finished, move the shell to the foreground */
6375 p = getpgrp(); /* our process group id */
6376 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6377 tcsetpgrp(G_interactive_fd, p);
6383 /* Start all the jobs, but don't wait for anything to finish.
6386 * Return code is normally -1, when the caller has to wait for children
6387 * to finish to determine the exit status of the pipe. If the pipe
6388 * is a simple builtin command, however, the action is done by the
6389 * time run_pipe returns, and the exit code is provided as the
6392 * Returns -1 only if started some children. IOW: we have to
6393 * mask out retvals of builtins etc with 0xff!
6395 * The only case when we do not need to [v]fork is when the pipe
6396 * is single, non-backgrounded, non-subshell command. Examples:
6397 * cmd ; ... { list } ; ...
6398 * cmd && ... { list } && ...
6399 * cmd || ... { list } || ...
6400 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6401 * or (if SH_STANDALONE) an applet, and we can run the { list }
6402 * with run_list. If it isn't one of these, we fork and exec cmd.
6404 * Cases when we must fork:
6405 * non-single: cmd | cmd
6406 * backgrounded: cmd & { list } &
6407 * subshell: ( list ) [&]
6409 #if !ENABLE_HUSH_MODE_X
6410 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6411 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6413 static int redirect_and_varexp_helper(char ***new_env_p,
6414 struct variable **old_vars_p,
6415 struct command *command,
6417 char **argv_expanded)
6419 /* setup_redirects acts on file descriptors, not FILEs.
6420 * This is perfect for work that comes after exec().
6421 * Is it really safe for inline use? Experimentally,
6422 * things seem to work. */
6423 int rcode = setup_redirects(command, squirrel);
6425 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6426 *new_env_p = new_env;
6427 dump_cmd_in_x_mode(new_env);
6428 dump_cmd_in_x_mode(argv_expanded);
6430 *old_vars_p = set_vars_and_save_old(new_env);
6434 static NOINLINE int run_pipe(struct pipe *pi)
6436 static const char *const null_ptr = NULL;
6440 struct command *command;
6441 char **argv_expanded;
6443 /* it is not always needed, but we aim to smaller code */
6444 int squirrel[] = { -1, -1, -1 };
6447 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6450 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6451 * Result should be 3 lines: q w e, qwe, q w e
6453 G.ifs = get_local_var_value("IFS");
6457 IF_HUSH_JOB(pi->pgrp = -1;)
6458 pi->stopped_cmds = 0;
6459 command = &pi->cmds[0];
6460 argv_expanded = NULL;
6462 if (pi->num_cmds != 1
6463 || pi->followup == PIPE_BG
6464 || command->cmd_type == CMD_SUBSHELL
6471 debug_printf_exec(": group:%p argv:'%s'\n",
6472 command->group, command->argv ? command->argv[0] : "NONE");
6474 if (command->group) {
6475 #if ENABLE_HUSH_FUNCTIONS
6476 if (command->cmd_type == CMD_FUNCDEF) {
6477 /* "executing" func () { list } */
6478 struct function *funcp;
6480 funcp = new_function(command->argv[0]);
6481 /* funcp->name is already set to argv[0] */
6482 funcp->body = command->group;
6484 funcp->body_as_string = command->group_as_string;
6485 command->group_as_string = NULL;
6487 command->group = NULL;
6488 command->argv[0] = NULL;
6489 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6490 funcp->parent_cmd = command;
6491 command->child_func = funcp;
6493 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6495 return EXIT_SUCCESS;
6499 debug_printf("non-subshell group\n");
6500 rcode = 1; /* exitcode if redir failed */
6501 if (setup_redirects(command, squirrel) == 0) {
6502 debug_printf_exec(": run_list\n");
6503 rcode = run_list(command->group) & 0xff;
6505 restore_redirects(squirrel);
6506 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6508 debug_printf_exec("run_pipe: return %d\n", rcode);
6512 argv = command->argv ? command->argv : (char **) &null_ptr;
6514 const struct built_in_command *x;
6515 #if ENABLE_HUSH_FUNCTIONS
6516 const struct function *funcp;
6520 char **new_env = NULL;
6521 struct variable *old_vars = NULL;
6523 if (argv[command->assignment_cnt] == NULL) {
6524 /* Assignments, but no command */
6525 /* Ensure redirects take effect (that is, create files).
6526 * Try "a=t >file" */
6527 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6528 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6529 /* Set shell variables */
6533 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6534 /* Do we need to flag set_local_var() errors?
6535 * "assignment to readonly var" and "putenv error"
6540 /* Redirect error sets $? to 1. Otherwise,
6541 * if evaluating assignment value set $?, retain it.
6542 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6544 rcode = G.last_exitcode;
6545 /* Exit, _skipping_ variable restoring code: */
6546 goto clean_up_and_ret0;
6548 #else /* Older, bigger, but more correct code */
6550 rcode = setup_redirects(command, squirrel);
6551 restore_redirects(squirrel);
6552 /* Set shell variables */
6554 bb_putchar_stderr('+');
6556 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6558 fprintf(stderr, " %s", p);
6559 debug_printf_exec("set shell var:'%s'->'%s'\n",
6561 set_local_var(p, /*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 bb_putchar_stderr('\n');
6569 /* Redirect error sets $? to 1. Otherwise,
6570 * if evaluating assignment value set $?, retain it.
6571 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6573 rcode = G.last_exitcode;
6574 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6576 debug_printf_exec("run_pipe: return %d\n", rcode);
6581 /* Expand the rest into (possibly) many strings each */
6583 #if ENABLE_HUSH_BASH_COMPAT
6584 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6585 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6589 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6592 /* if someone gives us an empty string: `cmd with empty output` */
6593 if (!argv_expanded[0]) {
6594 free(argv_expanded);
6596 return G.last_exitcode;
6599 x = find_builtin(argv_expanded[0]);
6600 #if ENABLE_HUSH_FUNCTIONS
6603 funcp = find_function(argv_expanded[0]);
6607 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6608 debug_printf("exec with redirects only\n");
6609 rcode = setup_redirects(command, NULL);
6610 goto clean_up_and_ret1;
6613 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6616 debug_printf_exec(": builtin '%s' '%s'...\n",
6617 x->b_cmd, argv_expanded[1]);
6618 rcode = x->b_function(argv_expanded) & 0xff;
6621 #if ENABLE_HUSH_FUNCTIONS
6623 # if ENABLE_HUSH_LOCAL
6624 struct variable **sv;
6625 sv = G.shadowed_vars_pp;
6626 G.shadowed_vars_pp = &old_vars;
6628 debug_printf_exec(": function '%s' '%s'...\n",
6629 funcp->name, argv_expanded[1]);
6630 rcode = run_function(funcp, argv_expanded) & 0xff;
6631 # if ENABLE_HUSH_LOCAL
6632 G.shadowed_vars_pp = sv;
6638 unset_vars(new_env);
6640 /* clean_up_and_ret0: */
6641 restore_redirects(squirrel);
6643 free(argv_expanded);
6644 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6646 debug_printf_exec("run_pipe return %d\n", rcode);
6650 if (ENABLE_FEATURE_SH_STANDALONE) {
6651 int n = find_applet_by_name(argv_expanded[0]);
6652 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6653 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6655 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6656 argv_expanded[0], argv_expanded[1]);
6657 rcode = run_nofork_applet(n, argv_expanded);
6659 goto clean_up_and_ret;
6662 /* It is neither builtin nor applet. We must fork. */
6666 /* NB: argv_expanded may already be created, and that
6667 * might include `cmd` runs! Do not rerun it! We *must*
6668 * use argv_expanded if it's non-NULL */
6670 /* Going to fork a child per each pipe member */
6675 while (cmd_no < pi->num_cmds) {
6676 struct fd_pair pipefds;
6678 volatile nommu_save_t nommu_save;
6679 nommu_save.new_env = NULL;
6680 nommu_save.old_vars = NULL;
6681 nommu_save.argv = NULL;
6682 nommu_save.argv_from_re_execing = NULL;
6684 command = &pi->cmds[cmd_no];
6686 if (command->argv) {
6687 debug_printf_exec(": pipe member '%s' '%s'...\n",
6688 command->argv[0], command->argv[1]);
6690 debug_printf_exec(": pipe member with no argv\n");
6693 /* pipes are inserted between pairs of commands */
6696 if (cmd_no < pi->num_cmds)
6697 xpiped_pair(pipefds);
6699 command->pid = BB_MMU ? fork() : vfork();
6700 if (!command->pid) { /* child */
6702 disable_restore_tty_pgrp_on_exit();
6703 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6705 /* Every child adds itself to new process group
6706 * with pgid == pid_of_first_child_in_pipe */
6707 if (G.run_list_level == 1 && G_interactive_fd) {
6710 if (pgrp < 0) /* true for 1st process only */
6712 if (setpgid(0, pgrp) == 0
6713 && pi->followup != PIPE_BG
6714 && G_saved_tty_pgrp /* we have ctty */
6716 /* We do it in *every* child, not just first,
6718 tcsetpgrp(G_interactive_fd, pgrp);
6722 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6723 /* 1st cmd in backgrounded pipe
6724 * should have its stdin /dev/null'ed */
6726 if (open(bb_dev_null, O_RDONLY))
6727 xopen("/", O_RDONLY);
6729 xmove_fd(next_infd, 0);
6731 xmove_fd(pipefds.wr, 1);
6734 /* Like bash, explicit redirects override pipes,
6735 * and the pipe fd is available for dup'ing. */
6736 if (setup_redirects(command, NULL))
6739 /* Restore default handlers just prior to exec */
6740 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6742 /* Stores to nommu_save list of env vars putenv'ed
6743 * (NOMMU, on MMU we don't need that) */
6744 /* cast away volatility... */
6745 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6746 /* pseudo_exec() does not return */
6749 /* parent or error */
6750 #if ENABLE_HUSH_FAST
6752 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6754 enable_restore_tty_pgrp_on_exit();
6756 /* Clean up after vforked child */
6757 free(nommu_save.argv);
6758 free(nommu_save.argv_from_re_execing);
6759 unset_vars(nommu_save.new_env);
6760 add_vars(nommu_save.old_vars);
6762 free(argv_expanded);
6763 argv_expanded = NULL;
6764 if (command->pid < 0) { /* [v]fork failed */
6765 /* Clearly indicate, was it fork or vfork */
6766 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6770 /* Second and next children need to know pid of first one */
6772 pi->pgrp = command->pid;
6778 if (cmd_no < pi->num_cmds)
6780 /* Pass read (output) pipe end to next iteration */
6781 next_infd = pipefds.rd;
6784 if (!pi->alive_cmds) {
6786 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6791 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6795 #ifndef debug_print_tree
6796 static void debug_print_tree(struct pipe *pi, int lvl)
6798 static const char *const PIPE[] = {
6804 static const char *RES[] = {
6805 [RES_NONE ] = "NONE" ,
6808 [RES_THEN ] = "THEN" ,
6809 [RES_ELIF ] = "ELIF" ,
6810 [RES_ELSE ] = "ELSE" ,
6813 # if ENABLE_HUSH_LOOPS
6814 [RES_FOR ] = "FOR" ,
6815 [RES_WHILE] = "WHILE",
6816 [RES_UNTIL] = "UNTIL",
6818 [RES_DONE ] = "DONE" ,
6820 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6823 # if ENABLE_HUSH_CASE
6824 [RES_CASE ] = "CASE" ,
6825 [RES_CASE_IN ] = "CASE_IN" ,
6826 [RES_MATCH] = "MATCH",
6827 [RES_CASE_BODY] = "CASE_BODY",
6828 [RES_ESAC ] = "ESAC" ,
6830 [RES_XXXX ] = "XXXX" ,
6831 [RES_SNTX ] = "SNTX" ,
6833 static const char *const CMDTYPE[] = {
6837 # if ENABLE_HUSH_FUNCTIONS
6846 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6847 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6849 while (prn < pi->num_cmds) {
6850 struct command *command = &pi->cmds[prn];
6851 char **argv = command->argv;
6853 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6855 command->assignment_cnt);
6856 if (command->group) {
6857 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6858 CMDTYPE[command->cmd_type],
6861 , " group_as_string:", command->group_as_string
6866 debug_print_tree(command->group, lvl+1);
6870 if (argv) while (*argv) {
6871 fprintf(stderr, " '%s'", *argv);
6874 fprintf(stderr, "\n");
6881 #endif /* debug_print_tree */
6883 /* NB: called by pseudo_exec, and therefore must not modify any
6884 * global data until exec/_exit (we can be a child after vfork!) */
6885 static int run_list(struct pipe *pi)
6887 #if ENABLE_HUSH_CASE
6888 char *case_word = NULL;
6890 #if ENABLE_HUSH_LOOPS
6891 struct pipe *loop_top = NULL;
6892 char **for_lcur = NULL;
6893 char **for_list = NULL;
6895 smallint last_followup;
6897 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6898 smalluint cond_code = 0;
6900 enum { cond_code = 0 };
6903 smallint rword; /* RES_foo */
6904 smallint last_rword; /* ditto */
6907 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6910 #if ENABLE_HUSH_LOOPS
6911 /* Check syntax for "for" */
6912 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6913 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6915 /* current word is FOR or IN (BOLD in comments below) */
6916 if (cpipe->next == NULL) {
6917 syntax_error("malformed for");
6919 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6922 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6923 if (cpipe->next->res_word == RES_DO)
6925 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6926 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6927 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6929 syntax_error("malformed for");
6931 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6937 /* Past this point, all code paths should jump to ret: label
6938 * in order to return, no direct "return" statements please.
6939 * This helps to ensure that no memory is leaked. */
6947 last_rword = RES_XXXX;
6949 last_followup = PIPE_SEQ;
6950 rcode = G.last_exitcode;
6952 /* Go through list of pipes, (maybe) executing them. */
6953 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6957 IF_HAS_KEYWORDS(rword = pi->res_word;)
6958 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6959 rword, cond_code, last_rword);
6960 #if ENABLE_HUSH_LOOPS
6961 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6962 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6964 /* start of a loop: remember where loop starts */
6969 /* Still in the same "if...", "then..." or "do..." branch? */
6970 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6971 if ((rcode == 0 && last_followup == PIPE_OR)
6972 || (rcode != 0 && last_followup == PIPE_AND)
6974 /* It is "<true> || CMD" or "<false> && CMD"
6975 * and we should not execute CMD */
6976 debug_printf_exec("skipped cmd because of || or &&\n");
6977 last_followup = pi->followup;
6981 last_followup = pi->followup;
6982 IF_HAS_KEYWORDS(last_rword = rword;)
6985 if (rword == RES_THEN) {
6986 /* if false; then ... fi has exitcode 0! */
6987 G.last_exitcode = rcode = EXIT_SUCCESS;
6988 /* "if <false> THEN cmd": skip cmd */
6992 if (rword == RES_ELSE || rword == RES_ELIF) {
6993 /* "if <true> then ... ELSE/ELIF cmd":
6994 * skip cmd and all following ones */
6999 #if ENABLE_HUSH_LOOPS
7000 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7002 /* first loop through for */
7004 static const char encoded_dollar_at[] ALIGN1 = {
7005 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7006 }; /* encoded representation of "$@" */
7007 static const char *const encoded_dollar_at_argv[] = {
7008 encoded_dollar_at, NULL
7009 }; /* argv list with one element: "$@" */
7012 vals = (char**)encoded_dollar_at_argv;
7013 if (pi->next->res_word == RES_IN) {
7014 /* if no variable values after "in" we skip "for" */
7015 if (!pi->next->cmds[0].argv) {
7016 G.last_exitcode = rcode = EXIT_SUCCESS;
7017 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7020 vals = pi->next->cmds[0].argv;
7021 } /* else: "for var; do..." -> assume "$@" list */
7022 /* create list of variable values */
7023 debug_print_strings("for_list made from", vals);
7024 for_list = expand_strvec_to_strvec(vals);
7025 for_lcur = for_list;
7026 debug_print_strings("for_list", for_list);
7029 /* "for" loop is over, clean up */
7035 /* Insert next value from for_lcur */
7036 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7037 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7040 if (rword == RES_IN) {
7041 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7043 if (rword == RES_DONE) {
7044 continue; /* "done" has no cmds too */
7047 #if ENABLE_HUSH_CASE
7048 if (rword == RES_CASE) {
7049 case_word = expand_strvec_to_string(pi->cmds->argv);
7052 if (rword == RES_MATCH) {
7055 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7057 /* all prev words didn't match, does this one match? */
7058 argv = pi->cmds->argv;
7060 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7061 /* TODO: which FNM_xxx flags to use? */
7062 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7064 if (cond_code == 0) { /* match! we will execute this branch */
7065 free(case_word); /* make future "word)" stop */
7073 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7075 continue; /* not matched yet, skip this pipe */
7078 /* Just pressing <enter> in shell should check for jobs.
7079 * OTOH, in non-interactive shell this is useless
7080 * and only leads to extra job checks */
7081 if (pi->num_cmds == 0) {
7082 if (G_interactive_fd)
7083 goto check_jobs_and_continue;
7087 /* After analyzing all keywords and conditions, we decided
7088 * to execute this pipe. NB: have to do checkjobs(NULL)
7089 * after run_pipe to collect any background children,
7090 * even if list execution is to be stopped. */
7091 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7094 #if ENABLE_HUSH_LOOPS
7095 G.flag_break_continue = 0;
7097 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7099 /* We ran a builtin, function, or group.
7100 * rcode is already known
7101 * and we don't need to wait for anything. */
7102 G.last_exitcode = rcode;
7103 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7104 check_and_run_traps(0);
7105 #if ENABLE_HUSH_LOOPS
7106 /* Was it "break" or "continue"? */
7107 if (G.flag_break_continue) {
7108 smallint fbc = G.flag_break_continue;
7109 /* We might fall into outer *loop*,
7110 * don't want to break it too */
7112 G.depth_break_continue--;
7113 if (G.depth_break_continue == 0)
7114 G.flag_break_continue = 0;
7115 /* else: e.g. "continue 2" should *break* once, *then* continue */
7116 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7117 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7118 goto check_jobs_and_break;
7119 /* "continue": simulate end of loop */
7124 #if ENABLE_HUSH_FUNCTIONS
7125 if (G.flag_return_in_progress == 1) {
7126 /* same as "goto check_jobs_and_break" */
7131 } else if (pi->followup == PIPE_BG) {
7132 /* What does bash do with attempts to background builtins? */
7133 /* even bash 3.2 doesn't do that well with nested bg:
7134 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7135 * I'm NOT treating inner &'s as jobs */
7136 check_and_run_traps(0);
7138 if (G.run_list_level == 1)
7141 /* Last command's pid goes to $! */
7142 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7143 G.last_exitcode = rcode = EXIT_SUCCESS;
7144 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7147 if (G.run_list_level == 1 && G_interactive_fd) {
7148 /* Waits for completion, then fg's main shell */
7149 rcode = checkjobs_and_fg_shell(pi);
7150 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7151 check_and_run_traps(0);
7154 { /* This one just waits for completion */
7155 rcode = checkjobs(pi);
7156 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7157 check_and_run_traps(0);
7159 G.last_exitcode = rcode;
7163 /* Analyze how result affects subsequent commands */
7165 if (rword == RES_IF || rword == RES_ELIF)
7168 #if ENABLE_HUSH_LOOPS
7169 /* Beware of "while false; true; do ..."! */
7170 if (pi->next && pi->next->res_word == RES_DO) {
7171 if (rword == RES_WHILE) {
7173 /* "while false; do...done" - exitcode 0 */
7174 G.last_exitcode = rcode = EXIT_SUCCESS;
7175 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7176 goto check_jobs_and_break;
7179 if (rword == RES_UNTIL) {
7181 debug_printf_exec(": until expr is true: breaking\n");
7182 check_jobs_and_break:
7190 check_jobs_and_continue:
7197 #if ENABLE_HUSH_LOOPS
7202 #if ENABLE_HUSH_CASE
7206 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7210 /* Select which version we will use */
7211 static int run_and_free_list(struct pipe *pi)
7214 debug_printf_exec("run_and_free_list entered\n");
7216 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7217 rcode = run_list(pi);
7219 /* free_pipe_list has the side effect of clearing memory.
7220 * In the long run that function can be merged with run_list,
7221 * but doing that now would hobble the debugging effort. */
7223 debug_printf_exec("run_and_free_list return %d\n", rcode);
7228 /* Called a few times only (or even once if "sh -c") */
7229 static void init_sigmasks(void)
7233 sigset_t old_blocked_set;
7235 if (!G.inherited_set_is_saved) {
7236 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7237 G.inherited_set = G.blocked_set;
7239 old_blocked_set = G.blocked_set;
7241 mask = (1 << SIGQUIT);
7242 if (G_interactive_fd) {
7243 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7244 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7245 mask |= SPECIAL_JOB_SIGS;
7247 G.non_DFL_mask = mask;
7252 sigaddset(&G.blocked_set, sig);
7256 sigdelset(&G.blocked_set, SIGCHLD);
7258 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7259 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7261 /* POSIX allows shell to re-enable SIGCHLD
7262 * even if it was SIG_IGN on entry */
7263 #if ENABLE_HUSH_FAST
7264 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7265 if (!G.inherited_set_is_saved)
7266 signal(SIGCHLD, SIGCHLD_handler);
7268 if (!G.inherited_set_is_saved)
7269 signal(SIGCHLD, SIG_DFL);
7272 G.inherited_set_is_saved = 1;
7277 static void maybe_set_to_sigexit(int sig)
7279 void (*handler)(int);
7280 /* non_DFL_mask'ed signals are, well, masked,
7281 * no need to set handler for them.
7283 if (!((G.non_DFL_mask >> sig) & 1)) {
7284 handler = signal(sig, sigexit);
7285 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7286 signal(sig, handler);
7289 /* Set handlers to restore tty pgrp and exit */
7290 static void set_fatal_handlers(void)
7292 /* We _must_ restore tty pgrp on fatal signals */
7294 maybe_set_to_sigexit(SIGILL );
7295 maybe_set_to_sigexit(SIGFPE );
7296 maybe_set_to_sigexit(SIGBUS );
7297 maybe_set_to_sigexit(SIGSEGV);
7298 maybe_set_to_sigexit(SIGTRAP);
7299 } /* else: hush is perfect. what SEGV? */
7300 maybe_set_to_sigexit(SIGABRT);
7301 /* bash 3.2 seems to handle these just like 'fatal' ones */
7302 maybe_set_to_sigexit(SIGPIPE);
7303 maybe_set_to_sigexit(SIGALRM);
7304 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7305 * if we aren't interactive... but in this case
7306 * we never want to restore pgrp on exit, and this fn is not called */
7307 /*maybe_set_to_sigexit(SIGHUP );*/
7308 /*maybe_set_to_sigexit(SIGTERM);*/
7309 /*maybe_set_to_sigexit(SIGINT );*/
7313 static int set_mode(const char cstate, const char mode)
7315 int state = (cstate == '-' ? 1 : 0);
7317 case 'n': G.n_mode = state; break;
7318 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7319 default: return EXIT_FAILURE;
7321 return EXIT_SUCCESS;
7324 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7325 int hush_main(int argc, char **argv)
7328 unsigned builtin_argc;
7330 struct variable *cur_var;
7333 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7334 G.last_exitcode = EXIT_SUCCESS;
7336 G.argv0_for_re_execing = argv[0];
7338 /* Deal with HUSH_VERSION */
7339 G.shell_ver.flg_export = 1;
7340 G.shell_ver.flg_read_only = 1;
7341 /* Code which handles ${var<op>...} needs writable values for all variables,
7342 * therefore we xstrdup: */
7343 G.shell_ver.varstr = xstrdup(hush_version_str),
7344 G.top_var = &G.shell_ver;
7345 /* Create shell local variables from the values
7346 * currently living in the environment */
7347 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7348 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7349 cur_var = G.top_var;
7352 char *value = strchr(*e, '=');
7353 if (value) { /* paranoia */
7354 cur_var->next = xzalloc(sizeof(*cur_var));
7355 cur_var = cur_var->next;
7356 cur_var->varstr = *e;
7357 cur_var->max_len = strlen(*e);
7358 cur_var->flg_export = 1;
7362 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7363 debug_printf_env("putenv '%s'\n", G.shell_ver.varstr);
7364 putenv(G.shell_ver.varstr);
7367 set_pwd_var(/*exp:*/ 1);
7368 /* bash also exports SHLVL and _,
7369 * and sets (but doesn't export) the following variables:
7371 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7372 * BASH_VERSION='3.2.0(1)-release'
7374 * MACHTYPE=i386-pc-linux-gnu
7376 * HOSTNAME=<xxxxxxxxxx>
7377 * PPID=<NNNNN> - we also do it elsewhere
7388 * PIPESTATUS=([0]="0")
7389 * HISTFILE=/<xxx>/.bash_history
7393 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7395 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7405 #if ENABLE_FEATURE_EDITING
7406 G.line_input_state = new_line_input_t(FOR_SHELL);
7408 G.global_argc = argc;
7409 G.global_argv = argv;
7410 /* Initialize some more globals to non-zero values */
7411 cmdedit_update_prompt();
7413 if (setjmp(die_jmp)) {
7414 /* xfunc has failed! die die die */
7415 /* no EXIT traps, this is an escape hatch! */
7417 hush_exit(xfunc_error_retval);
7420 /* Shell is non-interactive at first. We need to call
7421 * init_sigmasks() if we are going to execute "sh <script>",
7422 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7423 * If we later decide that we are interactive, we run init_sigmasks()
7424 * in order to intercept (more) signals.
7428 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7431 opt = getopt(argc, argv, "+c:xins"
7434 # if ENABLE_HUSH_FUNCTIONS
7444 * sh ... -c 'script'
7445 * sh ... -c 'script' ARG0 [ARG1...]
7446 * On NOMMU, if builtin_argc != 0,
7447 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7448 * "" needs to be replaced with NULL
7449 * and BARGV vector fed to builtin function.
7450 * Note: the form without ARG0 never happens:
7451 * sh ... -c 'builtin' BARGV... ""
7454 G.root_pid = getpid();
7455 G.root_ppid = getppid();
7457 G.global_argv = argv + optind;
7458 G.global_argc = argc - optind;
7460 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7461 const struct built_in_command *x;
7464 x = find_builtin(optarg);
7465 if (x) { /* paranoia */
7466 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7467 G.global_argv += builtin_argc;
7468 G.global_argv[-1] = NULL; /* replace "" */
7469 G.last_exitcode = x->b_function(argv + optind - 1);
7473 if (!G.global_argv[0]) {
7474 /* -c 'script' (no params): prevent empty $0 */
7475 G.global_argv--; /* points to argv[i] of 'script' */
7476 G.global_argv[0] = argv[0];
7478 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7480 parse_and_run_string(optarg);
7483 /* Well, we cannot just declare interactiveness,
7484 * we have to have some stuff (ctty, etc) */
7485 /* G_interactive_fd++; */
7488 /* "-s" means "read from stdin", but this is how we always
7489 * operate, so simply do nothing here. */
7492 case '<': /* "big heredoc" support */
7493 full_write1_str(optarg);
7496 unsigned long long empty_trap_mask;
7498 G.root_pid = bb_strtou(optarg, &optarg, 16);
7500 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7502 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7504 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7506 builtin_argc = bb_strtou(optarg, &optarg, 16);
7508 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7509 if (empty_trap_mask != 0) {
7512 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7513 for (sig = 1; sig < NSIG; sig++) {
7514 if (empty_trap_mask & (1LL << sig)) {
7515 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7516 sigaddset(&G.blocked_set, sig);
7519 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7521 # if ENABLE_HUSH_LOOPS
7523 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7529 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7531 # if ENABLE_HUSH_FUNCTIONS
7533 struct function *funcp = new_function(optarg);
7534 /* funcp->name is already set to optarg */
7535 /* funcp->body is set to NULL. It's a special case. */
7536 funcp->body_as_string = argv[optind];
7544 if (set_mode('-', opt) == 0) /* no error */
7548 fprintf(stderr, "Usage: sh [FILE]...\n"
7549 " or: sh -c command [args]...\n\n");
7555 } /* option parsing loop */
7558 G.root_pid = getpid();
7559 G.root_ppid = getppid();
7562 /* If we are login shell... */
7563 if (argv[0] && argv[0][0] == '-') {
7565 debug_printf("sourcing /etc/profile\n");
7566 input = fopen_for_read("/etc/profile");
7567 if (input != NULL) {
7568 close_on_exec_on(fileno(input));
7570 parse_and_run_file(input);
7573 /* bash: after sourcing /etc/profile,
7574 * tries to source (in the given order):
7575 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7576 * stopping on first found. --noprofile turns this off.
7577 * bash also sources ~/.bash_logout on exit.
7578 * If called as sh, skips .bash_XXX files.
7585 * "bash <script>" (which is never interactive (unless -i?))
7586 * sources $BASH_ENV here (without scanning $PATH).
7587 * If called as sh, does the same but with $ENV.
7589 debug_printf("running script '%s'\n", argv[optind]);
7590 G.global_argv = argv + optind;
7591 G.global_argc = argc - optind;
7592 input = xfopen_for_read(argv[optind]);
7593 close_on_exec_on(fileno(input));
7595 parse_and_run_file(input);
7596 #if ENABLE_FEATURE_CLEAN_UP
7602 /* Up to here, shell was non-interactive. Now it may become one.
7603 * NB: don't forget to (re)run init_sigmasks() as needed.
7606 /* A shell is interactive if the '-i' flag was given,
7607 * or if all of the following conditions are met:
7609 * no arguments remaining or the -s flag given
7610 * standard input is a terminal
7611 * standard output is a terminal
7612 * Refer to Posix.2, the description of the 'sh' utility.
7615 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7616 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7617 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7618 if (G_saved_tty_pgrp < 0)
7619 G_saved_tty_pgrp = 0;
7621 /* try to dup stdin to high fd#, >= 255 */
7622 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7623 if (G_interactive_fd < 0) {
7624 /* try to dup to any fd */
7625 G_interactive_fd = dup(STDIN_FILENO);
7626 if (G_interactive_fd < 0) {
7628 G_interactive_fd = 0;
7629 G_saved_tty_pgrp = 0;
7632 // TODO: track & disallow any attempts of user
7633 // to (inadvertently) close/redirect G_interactive_fd
7635 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7636 if (G_interactive_fd) {
7637 close_on_exec_on(G_interactive_fd);
7639 if (G_saved_tty_pgrp) {
7640 /* If we were run as 'hush &', sleep until we are
7641 * in the foreground (tty pgrp == our pgrp).
7642 * If we get started under a job aware app (like bash),
7643 * make sure we are now in charge so we don't fight over
7644 * who gets the foreground */
7646 pid_t shell_pgrp = getpgrp();
7647 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7648 if (G_saved_tty_pgrp == shell_pgrp)
7650 /* send TTIN to ourself (should stop us) */
7651 kill(- shell_pgrp, SIGTTIN);
7655 /* Block some signals */
7658 if (G_saved_tty_pgrp) {
7659 /* Set other signals to restore saved_tty_pgrp */
7660 set_fatal_handlers();
7661 /* Put ourselves in our own process group
7662 * (bash, too, does this only if ctty is available) */
7663 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7664 /* Grab control of the terminal */
7665 tcsetpgrp(G_interactive_fd, getpid());
7667 /* -1 is special - makes xfuncs longjmp, not exit
7668 * (we reset die_sleep = 0 whereever we [v]fork) */
7669 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7673 #elif ENABLE_HUSH_INTERACTIVE
7674 /* No job control compiled in, only prompt/line editing */
7675 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7676 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7677 if (G_interactive_fd < 0) {
7678 /* try to dup to any fd */
7679 G_interactive_fd = dup(STDIN_FILENO);
7680 if (G_interactive_fd < 0)
7682 G_interactive_fd = 0;
7685 if (G_interactive_fd) {
7686 close_on_exec_on(G_interactive_fd);
7690 /* We have interactiveness code disabled */
7694 * if interactive but not a login shell, sources ~/.bashrc
7695 * (--norc turns this off, --rcfile <file> overrides)
7698 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7699 /* note: ash and hush share this string */
7700 printf("\n\n%s %s\n"
7701 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7704 "hush - the humble shell"
7708 parse_and_run_file(stdin);
7711 #if ENABLE_FEATURE_CLEAN_UP
7712 if (G.cwd != bb_msg_unknown)
7714 cur_var = G.top_var->next;
7716 struct variable *tmp = cur_var;
7717 if (!cur_var->max_len)
7718 free(cur_var->varstr);
7719 cur_var = cur_var->next;
7723 hush_exit(G.last_exitcode);
7728 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7729 int msh_main(int argc, char **argv)
7731 //bb_error_msg("msh is deprecated, please use hush instead");
7732 return hush_main(argc, argv);
7740 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7745 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7752 return applet_main_func(argc, argv - argc);
7755 static int FAST_FUNC builtin_test(char **argv)
7757 return run_applet_main(argv, test_main);
7760 static int FAST_FUNC builtin_echo(char **argv)
7762 return run_applet_main(argv, echo_main);
7766 static int FAST_FUNC builtin_printf(char **argv)
7768 return run_applet_main(argv, printf_main);
7772 static char **skip_dash_dash(char **argv)
7775 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7780 static int FAST_FUNC builtin_eval(char **argv)
7782 int rcode = EXIT_SUCCESS;
7784 argv = skip_dash_dash(argv);
7786 char *str = expand_strvec_to_string(argv);
7788 * eval "echo Hi; done" ("done" is syntax error):
7789 * "echo Hi" will not execute too.
7791 parse_and_run_string(str);
7793 rcode = G.last_exitcode;
7798 static int FAST_FUNC builtin_cd(char **argv)
7802 argv = skip_dash_dash(argv);
7804 if (newdir == NULL) {
7805 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7806 * bash says "bash: cd: HOME not set" and does nothing
7809 const char *home = get_local_var_value("HOME");
7810 newdir = home ? home : "/";
7812 if (chdir(newdir)) {
7813 /* Mimic bash message exactly */
7814 bb_perror_msg("cd: %s", newdir);
7815 return EXIT_FAILURE;
7817 /* Read current dir (get_cwd(1) is inside) and set PWD.
7818 * Note: do not enforce exporting. If PWD was unset or unexported,
7819 * set it again, but do not export. bash does the same.
7821 set_pwd_var(/*exp:*/ 0);
7822 return EXIT_SUCCESS;
7825 static int FAST_FUNC builtin_exec(char **argv)
7827 argv = skip_dash_dash(argv);
7828 if (argv[0] == NULL)
7829 return EXIT_SUCCESS; /* bash does this */
7831 /* Careful: we can end up here after [v]fork. Do not restore
7832 * tty pgrp then, only top-level shell process does that */
7833 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7834 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7836 /* TODO: if exec fails, bash does NOT exit! We do.
7837 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7838 * and tcsetpgrp, and this is inherently racy.
7840 execvp_or_die(argv);
7843 static int FAST_FUNC builtin_exit(char **argv)
7845 debug_printf_exec("%s()\n", __func__);
7847 /* interactive bash:
7848 * # trap "echo EEE" EXIT
7851 * There are stopped jobs.
7852 * (if there are _stopped_ jobs, running ones don't count)
7855 # EEE (then bash exits)
7857 * we can use G.exiting = -1 as indicator "last cmd was exit"
7860 /* note: EXIT trap is run by hush_exit */
7861 argv = skip_dash_dash(argv);
7862 if (argv[0] == NULL)
7863 hush_exit(G.last_exitcode);
7864 /* mimic bash: exit 123abc == exit 255 + error msg */
7865 xfunc_error_retval = 255;
7866 /* bash: exit -2 == exit 254, no error msg */
7867 hush_exit(xatoi(argv[0]) & 0xff);
7870 static void print_escaped(const char *s)
7875 const char *p = strchrnul(s, '\'');
7876 /* print 'xxxx', possibly just '' */
7877 printf("'%.*s'", (int)(p - s), s);
7882 /* s points to '; print "'''...'''" */
7884 do putchar('\''); while (*++s == '\'');
7889 #if !ENABLE_HUSH_LOCAL
7890 #define helper_export_local(argv, exp, lvl) \
7891 helper_export_local(argv, exp)
7893 static void helper_export_local(char **argv, int exp, int lvl)
7897 char *name_end = strchrnul(name, '=');
7899 /* So far we do not check that name is valid (TODO?) */
7901 if (*name_end == '\0') {
7902 struct variable *var, **vpp;
7904 vpp = get_ptr_to_local_var(name, name_end - name);
7905 var = vpp ? *vpp : NULL;
7907 if (exp == -1) { /* unexporting? */
7908 /* export -n NAME (without =VALUE) */
7910 var->flg_export = 0;
7911 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7913 } /* else: export -n NOT_EXISTING_VAR: no-op */
7916 if (exp == 1) { /* exporting? */
7917 /* export NAME (without =VALUE) */
7919 var->flg_export = 1;
7920 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7921 putenv(var->varstr);
7925 /* Exporting non-existing variable.
7926 * bash does not put it in environment,
7927 * but remembers that it is exported,
7928 * and does put it in env when it is set later.
7929 * We just set it to "" and export. */
7930 /* Or, it's "local NAME" (without =VALUE).
7931 * bash sets the value to "". */
7932 name = xasprintf("%s=", name);
7934 /* (Un)exporting/making local NAME=VALUE */
7935 name = xstrdup(name);
7937 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7941 static int FAST_FUNC builtin_export(char **argv)
7943 unsigned opt_unexport;
7945 #if ENABLE_HUSH_EXPORT_N
7946 /* "!": do not abort on errors */
7947 opt_unexport = getopt32(argv, "!n");
7948 if (opt_unexport == (uint32_t)-1)
7949 return EXIT_FAILURE;
7956 if (argv[0] == NULL) {
7963 /* ash emits: export VAR='VAL'
7964 * bash: declare -x VAR="VAL"
7965 * we follow ash example */
7966 const char *s = *e++;
7967 const char *p = strchr(s, '=');
7969 if (!p) /* wtf? take next variable */
7972 printf("export %.*s", (int)(p - s) + 1, s);
7973 print_escaped(p + 1);
7977 /*fflush_all(); - done after each builtin anyway */
7979 return EXIT_SUCCESS;
7982 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
7984 return EXIT_SUCCESS;
7987 #if ENABLE_HUSH_LOCAL
7988 static int FAST_FUNC builtin_local(char **argv)
7990 if (G.func_nest_level == 0) {
7991 bb_error_msg("%s: not in a function", argv[0]);
7992 return EXIT_FAILURE; /* bash compat */
7994 helper_export_local(argv, 0, G.func_nest_level);
7995 return EXIT_SUCCESS;
7999 static int FAST_FUNC builtin_trap(char **argv)
8005 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8010 /* No args: print all trapped */
8011 for (i = 0; i < NSIG; ++i) {
8014 print_escaped(G.traps[i]);
8015 /* note: bash adds "SIG", but only if invoked
8016 * as "bash". If called as "sh", or if set -o posix,
8017 * then it prints short signal names.
8018 * We are printing short names: */
8019 printf(" %s\n", get_signame(i));
8022 /*fflush_all(); - done after each builtin anyway */
8023 return EXIT_SUCCESS;
8027 /* If first arg is a number: reset all specified signals */
8028 sig = bb_strtou(*argv, NULL, 10);
8034 sig = get_signum(*argv++);
8035 if (sig < 0 || sig >= NSIG) {
8037 /* Mimic bash message exactly */
8038 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8043 G.traps[sig] = xstrdup(new_cmd);
8045 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8046 get_signame(sig), sig, G.traps[sig]);
8048 /* There is no signal for 0 (EXIT) */
8053 sigaddset(&G.blocked_set, sig);
8055 /* There was a trap handler, we are removing it
8056 * (if sig has non-DFL handling,
8057 * we don't need to do anything) */
8058 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8060 sigdelset(&G.blocked_set, sig);
8063 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8067 if (!argv[1]) { /* no second arg */
8068 bb_error_msg("trap: invalid arguments");
8069 return EXIT_FAILURE;
8072 /* First arg is "-": reset all specified to default */
8073 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8074 /* Everything else: set arg as signal handler
8075 * (includes "" case, which ignores signal) */
8076 if (argv[0][0] == '-') {
8077 if (argv[0][1] == '\0') { /* "-" */
8078 /* new_cmd remains NULL: "reset these sigs" */
8081 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8084 /* else: "-something", no special meaning */
8089 goto process_sig_list;
8092 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8093 static int FAST_FUNC builtin_type(char **argv)
8095 int ret = EXIT_SUCCESS;
8101 if (0) {} /* make conditional compile easier below */
8102 /*else if (find_alias(*argv))
8103 type = "an alias";*/
8104 #if ENABLE_HUSH_FUNCTIONS
8105 else if (find_function(*argv))
8106 type = "a function";
8108 else if (find_builtin(*argv))
8109 type = "a shell builtin";
8110 else if ((path = find_in_path(*argv)) != NULL)
8113 bb_error_msg("type: %s: not found", *argv);
8118 printf("%s is %s\n", *argv, type);
8126 /* built-in 'fg' and 'bg' handler */
8127 static int FAST_FUNC builtin_fg_bg(char **argv)
8132 if (!G_interactive_fd)
8133 return EXIT_FAILURE;
8135 /* If they gave us no args, assume they want the last backgrounded task */
8137 for (pi = G.job_list; pi; pi = pi->next) {
8138 if (pi->jobid == G.last_jobid) {
8142 bb_error_msg("%s: no current job", argv[0]);
8143 return EXIT_FAILURE;
8145 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8146 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8147 return EXIT_FAILURE;
8149 for (pi = G.job_list; pi; pi = pi->next) {
8150 if (pi->jobid == jobnum) {
8154 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8155 return EXIT_FAILURE;
8157 /* TODO: bash prints a string representation
8158 * of job being foregrounded (like "sleep 1 | cat") */
8159 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8160 /* Put the job into the foreground. */
8161 tcsetpgrp(G_interactive_fd, pi->pgrp);
8164 /* Restart the processes in the job */
8165 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8166 for (i = 0; i < pi->num_cmds; i++) {
8167 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8168 pi->cmds[i].is_stopped = 0;
8170 pi->stopped_cmds = 0;
8172 i = kill(- pi->pgrp, SIGCONT);
8174 if (errno == ESRCH) {
8175 delete_finished_bg_job(pi);
8176 return EXIT_SUCCESS;
8178 bb_perror_msg("kill (SIGCONT)");
8181 if (argv[0][0] == 'f') {
8183 return checkjobs_and_fg_shell(pi);
8185 return EXIT_SUCCESS;
8189 #if ENABLE_HUSH_HELP
8190 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8192 const struct built_in_command *x;
8195 "Built-in commands:\n"
8196 "------------------\n");
8197 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8199 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8202 return EXIT_SUCCESS;
8207 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8210 const char *status_string;
8212 for (job = G.job_list; job; job = job->next) {
8213 if (job->alive_cmds == job->stopped_cmds)
8214 status_string = "Stopped";
8216 status_string = "Running";
8218 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8220 return EXIT_SUCCESS;
8225 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8230 # ifdef M_TRIM_THRESHOLD
8231 /* Optional. Reduces probability of false positives */
8234 /* Crude attempt to find where "free memory" starts,
8235 * sans fragmentation. */
8237 l = (unsigned long)p;
8240 if (l < (unsigned long)p) l = (unsigned long)p;
8243 if (!G.memleak_value)
8244 G.memleak_value = l;
8246 l -= G.memleak_value;
8253 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8258 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8261 return EXIT_SUCCESS;
8264 static int FAST_FUNC builtin_read(char **argv)
8273 /* "!": do not abort on errors.
8274 * Option string must start with "sr" to match BUILTIN_READ_xxx
8276 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8277 if (read_flags == (uint32_t)-1)
8278 return EXIT_FAILURE;
8281 r = shell_builtin_read(set_local_var_from_halves,
8283 get_local_var_value("IFS"), /* can be NULL */
8291 if ((uintptr_t)r > 1) {
8292 bb_error_msg("%s", r);
8293 r = (char*)(uintptr_t)1;
8296 return (uintptr_t)r;
8299 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8300 * built-in 'set' handler
8302 * set [-abCefhmnuvx] [-o option] [argument...]
8303 * set [+abCefhmnuvx] [+o option] [argument...]
8304 * set -- [argument...]
8307 * Implementations shall support the options in both their hyphen and
8308 * plus-sign forms. These options can also be specified as options to sh.
8310 * Write out all variables and their values: set
8311 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8312 * Turn on the -x and -v options: set -xv
8313 * Unset all positional parameters: set --
8314 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8315 * Set the positional parameters to the expansion of x, even if x expands
8316 * with a leading '-' or '+': set -- $x
8318 * So far, we only support "set -- [argument...]" and some of the short names.
8320 static int FAST_FUNC builtin_set(char **argv)
8323 char **pp, **g_argv;
8324 char *arg = *++argv;
8328 for (e = G.top_var; e; e = e->next)
8330 return EXIT_SUCCESS;
8334 if (!strcmp(arg, "--")) {
8338 if (arg[0] != '+' && arg[0] != '-')
8340 for (n = 1; arg[n]; ++n)
8341 if (set_mode(arg[0], arg[n]))
8343 } while ((arg = *++argv) != NULL);
8344 /* Now argv[0] is 1st argument */
8347 return EXIT_SUCCESS;
8350 /* NB: G.global_argv[0] ($0) is never freed/changed */
8351 g_argv = G.global_argv;
8352 if (G.global_args_malloced) {
8358 G.global_args_malloced = 1;
8359 pp = xzalloc(sizeof(pp[0]) * 2);
8360 pp[0] = g_argv[0]; /* retain $0 */
8363 /* This realloc's G.global_argv */
8364 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8371 return EXIT_SUCCESS;
8373 /* Nothing known, so abort */
8375 bb_error_msg("set: %s: invalid option", arg);
8376 return EXIT_FAILURE;
8379 static int FAST_FUNC builtin_shift(char **argv)
8382 argv = skip_dash_dash(argv);
8386 if (n >= 0 && n < G.global_argc) {
8387 if (G.global_args_malloced) {
8390 free(G.global_argv[m++]);
8393 memmove(&G.global_argv[1], &G.global_argv[n+1],
8394 G.global_argc * sizeof(G.global_argv[0]));
8395 return EXIT_SUCCESS;
8397 return EXIT_FAILURE;
8400 static int FAST_FUNC builtin_source(char **argv)
8402 char *arg_path, *filename;
8405 #if ENABLE_HUSH_FUNCTIONS
8409 argv = skip_dash_dash(argv);
8412 /* bash says: "bash: .: filename argument required" */
8413 return 2; /* bash compat */
8416 if (!strchr(filename, '/')) {
8417 arg_path = find_in_path(filename);
8419 filename = arg_path;
8421 input = fopen_or_warn(filename, "r");
8424 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8425 return EXIT_FAILURE;
8427 close_on_exec_on(fileno(input));
8429 #if ENABLE_HUSH_FUNCTIONS
8430 sv_flg = G.flag_return_in_progress;
8431 /* "we are inside sourced file, ok to use return" */
8432 G.flag_return_in_progress = -1;
8434 save_and_replace_G_args(&sv, argv);
8436 parse_and_run_file(input);
8439 restore_G_args(&sv, argv);
8440 #if ENABLE_HUSH_FUNCTIONS
8441 G.flag_return_in_progress = sv_flg;
8444 return G.last_exitcode;
8447 static int FAST_FUNC builtin_umask(char **argv)
8453 argv = skip_dash_dash(argv);
8455 mode_t old_mask = mask;
8458 rc = bb_parse_mode(argv[0], &mask);
8463 * bash: umask: 'q': invalid symbolic mode operator
8464 * bash: umask: 999: octal number out of range
8466 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8471 printf("%04o\n", (unsigned) mask);
8472 /* fall through and restore mask which we set to 0 */
8476 return !rc; /* rc != 0 - success */
8479 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8480 static int FAST_FUNC builtin_unset(char **argv)
8485 /* "!": do not abort on errors */
8486 /* "+": stop at 1st non-option */
8487 opts = getopt32(argv, "!+vf");
8488 if (opts == (unsigned)-1)
8489 return EXIT_FAILURE;
8491 bb_error_msg("unset: -v and -f are exclusive");
8492 return EXIT_FAILURE;
8498 if (!(opts & 2)) { /* not -f */
8499 if (unset_local_var(*argv)) {
8500 /* unset <nonexistent_var> doesn't fail.
8501 * Error is when one tries to unset RO var.
8502 * Message was printed by unset_local_var. */
8506 #if ENABLE_HUSH_FUNCTIONS
8516 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8517 static int FAST_FUNC builtin_wait(char **argv)
8519 int ret = EXIT_SUCCESS;
8522 argv = skip_dash_dash(argv);
8523 if (argv[0] == NULL) {
8524 /* Don't care about wait results */
8525 /* Note 1: must wait until there are no more children */
8526 /* Note 2: must be interruptible */
8528 * $ sleep 3 & sleep 6 & wait
8533 * $ sleep 3 & sleep 6 & wait
8537 * ^C <-- after ~4 sec from keyboard
8540 sigaddset(&G.blocked_set, SIGCHLD);
8541 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8544 if (errno == ECHILD)
8546 /* Wait for SIGCHLD or any other signal of interest */
8547 /* sigtimedwait with infinite timeout: */
8548 sig = sigwaitinfo(&G.blocked_set, NULL);
8550 sig = check_and_run_traps(sig);
8551 if (sig && sig != SIGCHLD) { /* see note 2 */
8557 sigdelset(&G.blocked_set, SIGCHLD);
8558 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8562 /* This is probably buggy wrt interruptible-ness */
8564 pid_t pid = bb_strtou(*argv, NULL, 10);
8566 /* mimic bash message */
8567 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8568 return EXIT_FAILURE;
8570 if (waitpid(pid, &status, 0) == pid) {
8571 if (WIFSIGNALED(status))
8572 ret = 128 + WTERMSIG(status);
8573 else if (WIFEXITED(status))
8574 ret = WEXITSTATUS(status);
8578 bb_perror_msg("wait %s", *argv);
8587 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8588 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8591 def = bb_strtou(argv[1], NULL, 10);
8592 if (errno || def < def_min || argv[2]) {
8593 bb_error_msg("%s: bad arguments", argv[0]);
8601 #if ENABLE_HUSH_LOOPS
8602 static int FAST_FUNC builtin_break(char **argv)
8605 if (G.depth_of_loop == 0) {
8606 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8607 return EXIT_SUCCESS; /* bash compat */
8609 G.flag_break_continue++; /* BC_BREAK = 1 */
8611 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8612 if (depth == UINT_MAX)
8613 G.flag_break_continue = BC_BREAK;
8614 if (G.depth_of_loop < depth)
8615 G.depth_break_continue = G.depth_of_loop;
8617 return EXIT_SUCCESS;
8620 static int FAST_FUNC builtin_continue(char **argv)
8622 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8623 return builtin_break(argv);
8627 #if ENABLE_HUSH_FUNCTIONS
8628 static int FAST_FUNC builtin_return(char **argv)
8632 if (G.flag_return_in_progress != -1) {
8633 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8634 return EXIT_FAILURE; /* bash compat */
8637 G.flag_return_in_progress = 1;
8640 * out of range: wraps around at 256, does not error out
8641 * non-numeric param:
8642 * f() { false; return qwe; }; f; echo $?
8643 * bash: return: qwe: numeric argument required <== we do this
8644 * 255 <== we also do this
8646 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);