1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * parse_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
45 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
48 * make complex ${var%...} constructs support optional
49 * make here documents optional
52 * redirection of stdout+stderr: &> and >&
53 * brace expansion: one/{two,three,four}
54 * reserved words: function select
55 * advanced test: [[ ]]
56 * process substitution: <(list) and >(list)
59 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
60 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
61 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
64 * This is exactly equivalent to let "EXPR".
65 * $[EXPR]: synonym for $((EXPR))
66 * export builtin should be special, its arguments are assignments
67 * and therefore expansion of them should be "one-word" expansion:
68 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
71 * ls: cannot access i=a: No such file or directory
72 * ls: cannot access b: No such file or directory
73 * Note1: same applies to local builtin.
74 * Note2: bash 3.2.33(1) does this only if export word itself
76 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
81 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
83 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
84 #include <malloc.h> /* for malloc_trim */
86 /* #include <dmalloc.h> */
91 #include "shell_common.h"
94 #if ENABLE_HUSH_RANDOM_SUPPORT
97 # define CLEAR_RANDOM_T(rnd) ((void)0)
100 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
103 //applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
104 //applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
105 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
106 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
109 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112 //config: bool "hush"
115 //config: hush is a small shell (25k). It handles the normal flow control
116 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
117 //config: case/esac. Redirections, here documents, $((arithmetic))
118 //config: and functions are supported.
120 //config: It will compile and work on no-mmu systems.
122 //config: It does not handle select, aliases, brace expansion,
123 //config: tilde expansion, &>file and >&file redirection of stdout+stderr.
125 //config:config HUSH_BASH_COMPAT
126 //config: bool "bash-compatible extensions"
128 //config: depends on HUSH
130 //config: Enable bash-compatible extensions.
132 //config:config HUSH_BRACE_EXPANSION
133 //config: bool "Brace expansion"
135 //config: depends on HUSH_BASH_COMPAT
137 //config: Enable {abc,def} extension.
139 //config:config HUSH_HELP
140 //config: bool "help builtin"
142 //config: depends on HUSH
144 //config: Enable help builtin in hush. Code size + ~1 kbyte.
146 //config:config HUSH_INTERACTIVE
147 //config: bool "Interactive mode"
149 //config: depends on HUSH
151 //config: Enable interactive mode (prompt and command editing).
152 //config: Without this, hush simply reads and executes commands
153 //config: from stdin just like a shell script from a file.
154 //config: No prompt, no PS1/PS2 magic shell variables.
156 //config:config HUSH_SAVEHISTORY
157 //config: bool "Save command history to .hush_history"
159 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
161 //config: Enable history saving in hush.
163 //config:config HUSH_JOB
164 //config: bool "Job control"
166 //config: depends on HUSH_INTERACTIVE
168 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
169 //config: command (not entire shell), fg/bg builtins work. Without this option,
170 //config: "cmd &" still works by simply spawning a process and immediately
171 //config: prompting for next command (or executing next command in a script),
172 //config: but no separate process group is formed.
174 //config:config HUSH_TICK
175 //config: bool "Process substitution"
177 //config: depends on HUSH
179 //config: Enable process substitution `command` and $(command) in hush.
181 //config:config HUSH_IF
182 //config: bool "Support if/then/elif/else/fi"
184 //config: depends on HUSH
186 //config: Enable if/then/elif/else/fi in hush.
188 //config:config HUSH_LOOPS
189 //config: bool "Support for, while and until loops"
191 //config: depends on HUSH
193 //config: Enable for, while and until loops in hush.
195 //config:config HUSH_CASE
196 //config: bool "Support case ... esac statement"
198 //config: depends on HUSH
200 //config: Enable case ... esac statement in hush. +400 bytes.
202 //config:config HUSH_FUNCTIONS
203 //config: bool "Support funcname() { commands; } syntax"
205 //config: depends on HUSH
207 //config: Enable support for shell functions in hush. +800 bytes.
209 //config:config HUSH_LOCAL
210 //config: bool "Support local builtin"
212 //config: depends on HUSH_FUNCTIONS
214 //config: Enable support for local variables in functions.
216 //config:config HUSH_RANDOM_SUPPORT
217 //config: bool "Pseudorandom generator and $RANDOM variable"
219 //config: depends on HUSH
221 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
222 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
224 //config:config HUSH_EXPORT_N
225 //config: bool "Support 'export -n' option"
227 //config: depends on HUSH
229 //config: export -n unexports variables. It is a bash extension.
231 //config:config HUSH_MODE_X
232 //config: bool "Support 'hush -x' option and 'set -x' command"
234 //config: depends on HUSH
236 //config: This instructs hush to print commands before execution.
237 //config: Adds ~300 bytes.
240 //config: bool "msh (deprecated: aliased to hush)"
242 //config: select HUSH
244 //config: msh is deprecated and will be removed, please migrate to hush.
247 //usage:#define hush_trivial_usage NOUSAGE_STR
248 //usage:#define hush_full_usage ""
249 //usage:#define msh_trivial_usage NOUSAGE_STR
250 //usage:#define msh_full_usage ""
251 //usage:#define sh_trivial_usage NOUSAGE_STR
252 //usage:#define sh_full_usage ""
253 //usage:#define bash_trivial_usage NOUSAGE_STR
254 //usage:#define bash_full_usage ""
258 #define LEAK_HUNTING 0
259 #define BUILD_AS_NOMMU 0
260 /* Enable/disable sanity checks. Ok to enable in production,
261 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
262 * Keeping 1 for now even in released versions.
265 /* Slightly bigger (+200 bytes), but faster hush.
266 * So far it only enables a trick with counting SIGCHLDs and forks,
267 * which allows us to do fewer waitpid's.
268 * (we can detect a case where neither forks were done nor SIGCHLDs happened
269 * and therefore waitpid will return the same result as last time)
271 #define ENABLE_HUSH_FAST 0
272 /* TODO: implement simplified code for users which do not need ${var%...} ops
273 * So far ${var%...} ops are always enabled:
275 #define ENABLE_HUSH_DOLLAR_OPS 1
280 # undef USE_FOR_NOMMU
283 # define USE_FOR_NOMMU(...) __VA_ARGS__
284 # define USE_FOR_MMU(...)
287 #include "NUM_APPLETS.h"
289 /* STANDALONE does not make sense, and won't compile */
290 # undef CONFIG_FEATURE_SH_STANDALONE
291 # undef ENABLE_FEATURE_SH_STANDALONE
292 # undef IF_FEATURE_SH_STANDALONE
293 # undef IF_NOT_FEATURE_SH_STANDALONE
294 # define ENABLE_FEATURE_SH_STANDALONE 0
295 # define IF_FEATURE_SH_STANDALONE(...)
296 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
299 #if !ENABLE_HUSH_INTERACTIVE
300 # undef ENABLE_FEATURE_EDITING
301 # define ENABLE_FEATURE_EDITING 0
302 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
303 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
306 /* Do we support ANY keywords? */
307 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
308 # define HAS_KEYWORDS 1
309 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
310 # define IF_HAS_NO_KEYWORDS(...)
312 # define HAS_KEYWORDS 0
313 # define IF_HAS_KEYWORDS(...)
314 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
317 /* If you comment out one of these below, it will be #defined later
318 * to perform debug printfs to stderr: */
319 #define debug_printf(...) do {} while (0)
320 /* Finer-grained debug switches */
321 #define debug_printf_parse(...) do {} while (0)
322 #define debug_print_tree(a, b) do {} while (0)
323 #define debug_printf_exec(...) do {} while (0)
324 #define debug_printf_env(...) do {} while (0)
325 #define debug_printf_jobs(...) do {} while (0)
326 #define debug_printf_expand(...) do {} while (0)
327 #define debug_printf_varexp(...) do {} while (0)
328 #define debug_printf_glob(...) do {} while (0)
329 #define debug_printf_list(...) do {} while (0)
330 #define debug_printf_subst(...) do {} while (0)
331 #define debug_printf_clean(...) do {} while (0)
333 #define ERR_PTR ((void*)(long)1)
335 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
337 #define _SPECIAL_VARS_STR "_*@$!?#"
338 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
339 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
340 #if ENABLE_HUSH_BASH_COMPAT
341 /* Support / and // replace ops */
342 /* Note that // is stored as \ in "encoded" string representation */
343 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
344 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
345 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
347 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
348 # define VAR_SUBST_OPS "%#:-=+?"
349 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
352 #define SPECIAL_VAR_SYMBOL 3
356 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
358 /* This supports saving pointers malloced in vfork child,
359 * to be freed in the parent.
362 typedef struct nommu_save_t {
364 struct variable *old_vars;
366 char **argv_from_re_execing;
379 #if ENABLE_HUSH_LOOPS
386 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
391 /* three pseudo-keywords support contrived "case" syntax: */
392 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
393 RES_MATCH , /* "word)" */
394 RES_CASE_BODY, /* "this command is inside CASE" */
401 typedef struct o_string {
403 int length; /* position where data is appended */
406 /* At least some part of the string was inside '' or "",
407 * possibly empty one: word"", wo''rd etc. */
408 smallint has_quoted_part;
409 smallint has_empty_slot;
410 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
413 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
415 /* Protect newly added chars against globbing
416 * by prepending \ to *, ?, [, \ */
417 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
420 MAYBE_ASSIGNMENT = 0,
421 DEFINITELY_ASSIGNMENT = 1,
423 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
426 /* Used for initialization: o_string foo = NULL_O_STRING; */
427 #define NULL_O_STRING { NULL }
429 /* I can almost use ordinary FILE*. Is open_memstream() universally
430 * available? Where is it documented? */
431 typedef struct in_str {
433 /* eof_flag=1: last char in ->p is really an EOF */
434 char eof_flag; /* meaningless if ->p == NULL */
436 #if ENABLE_HUSH_INTERACTIVE
438 smallint promptmode; /* 0: PS1, 1: PS2 */
441 int (*get) (struct in_str *) FAST_FUNC;
442 int (*peek) (struct in_str *) FAST_FUNC;
444 #define i_getch(input) ((input)->get(input))
445 #define i_peek(input) ((input)->peek(input))
447 /* The descrip member of this structure is only used to make
448 * debugging output pretty */
449 static const struct {
451 signed char default_fd;
454 { O_RDONLY, 0, "<" },
455 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
456 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
457 { O_CREAT|O_RDWR, 1, "<>" },
458 { O_RDONLY, 0, "<<" },
459 /* Should not be needed. Bogus default_fd helps in debugging */
460 /* { O_RDONLY, 77, "<<" }, */
463 struct redir_struct {
464 struct redir_struct *next;
465 char *rd_filename; /* filename */
466 int rd_fd; /* fd to redirect */
467 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
469 smallint rd_type; /* (enum redir_type) */
470 /* note: for heredocs, rd_filename contains heredoc delimiter,
471 * and subsequently heredoc itself; and rd_dup is a bitmask:
472 * bit 0: do we need to trim leading tabs?
473 * bit 1: is heredoc quoted (<<'delim' syntax) ?
476 typedef enum redir_type {
478 REDIRECT_OVERWRITE = 1,
481 REDIRECT_HEREDOC = 4,
482 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
485 REDIRFD_SYNTAX_ERR = -2,
486 REDIRFD_TO_FILE = -1,
487 /* otherwise, rd_fd is redirected to rd_dup */
489 HEREDOC_SKIPTABS = 1,
495 pid_t pid; /* 0 if exited */
496 int assignment_cnt; /* how many argv[i] are assignments? */
497 smallint is_stopped; /* is the command currently running? */
498 smallint cmd_type; /* CMD_xxx */
500 #define CMD_SUBSHELL 1
501 #if ENABLE_HUSH_BASH_COMPAT
502 /* used for "[[ EXPR ]]" */
503 # define CMD_SINGLEWORD_NOGLOB 2
505 #if ENABLE_HUSH_FUNCTIONS
506 # define CMD_FUNCDEF 3
509 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
512 char *group_as_string;
514 #if ENABLE_HUSH_FUNCTIONS
515 struct function *child_func;
516 /* This field is used to prevent a bug here:
517 * while...do f1() {a;}; f1; f1() {b;}; f1; done
518 * When we execute "f1() {a;}" cmd, we create new function and clear
519 * cmd->group, cmd->group_as_string, cmd->argv[0].
520 * When we execute "f1() {b;}", we notice that f1 exists,
521 * and that its "parent cmd" struct is still "alive",
522 * we put those fields back into cmd->xxx
523 * (struct function has ->parent_cmd ptr to facilitate that).
524 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
525 * Without this trick, loop would execute a;b;b;b;...
526 * instead of correct sequence a;b;a;b;...
527 * When command is freed, it severs the link
528 * (sets ->child_func->parent_cmd to NULL).
531 char **argv; /* command name and arguments */
532 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
533 * and on execution these are substituted with their values.
534 * Substitution can make _several_ words out of one argv[n]!
535 * Example: argv[0]=='.^C*^C.' here: echo .$*.
536 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
538 struct redir_struct *redirects; /* I/O redirections */
540 /* Is there anything in this command at all? */
541 #define IS_NULL_CMD(cmd) \
542 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
547 int num_cmds; /* total number of commands in pipe */
548 int alive_cmds; /* number of commands running (not exited) */
549 int stopped_cmds; /* number of commands alive, but stopped */
551 int jobid; /* job number */
552 pid_t pgrp; /* process group ID for the job */
553 char *cmdtext; /* name of job */
555 struct command *cmds; /* array of commands in pipe */
556 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
557 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
558 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
560 typedef enum pipe_style {
566 /* Is there anything in this pipe at all? */
567 #define IS_NULL_PIPE(pi) \
568 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
570 /* This holds pointers to the various results of parsing */
571 struct parse_context {
572 /* linked list of pipes */
573 struct pipe *list_head;
574 /* last pipe (being constructed right now) */
576 /* last command in pipe (being constructed right now) */
577 struct command *command;
578 /* last redirect in command->redirects list */
579 struct redir_struct *pending_redirect;
585 smallint ctx_inverted; /* "! cmd | cmd" */
587 smallint ctx_dsemicolon; /* ";;" seen */
589 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
591 /* group we are enclosed in:
592 * example: "if pipe1; pipe2; then pipe3; fi"
593 * when we see "if" or "then", we malloc and copy current context,
594 * and make ->stack point to it. then we parse pipeN.
595 * when closing "then" / fi" / whatever is found,
596 * we move list_head into ->stack->command->group,
597 * copy ->stack into current context, and delete ->stack.
598 * (parsing of { list } and ( list ) doesn't use this method)
600 struct parse_context *stack;
604 /* On program start, environ points to initial environment.
605 * putenv adds new pointers into it, unsetenv removes them.
606 * Neither of these (de)allocates the strings.
607 * setenv allocates new strings in malloc space and does putenv,
608 * and thus setenv is unusable (leaky) for shell's purposes */
609 #define setenv(...) setenv_is_leaky_dont_use()
611 struct variable *next;
612 char *varstr; /* points to "name=" portion */
613 #if ENABLE_HUSH_LOCAL
614 unsigned func_nest_level;
616 int max_len; /* if > 0, name is part of initial env; else name is malloced */
617 smallint flg_export; /* putenv should be done on this var */
618 smallint flg_read_only;
626 #if ENABLE_HUSH_FUNCTIONS
628 struct function *next;
630 struct command *parent_cmd;
633 char *body_as_string;
639 /* "Globals" within this file */
640 /* Sorted roughly by size (smaller offsets == smaller code) */
642 /* interactive_fd != 0 means we are an interactive shell.
643 * If we are, then saved_tty_pgrp can also be != 0, meaning
644 * that controlling tty is available. With saved_tty_pgrp == 0,
645 * job control still works, but terminal signals
646 * (^C, ^Z, ^Y, ^\) won't work at all, and background
647 * process groups can only be created with "cmd &".
648 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
649 * to give tty to the foreground process group,
650 * and will take it back when the group is stopped (^Z)
653 #if ENABLE_HUSH_INTERACTIVE
654 /* 'interactive_fd' is a fd# open to ctty, if we have one
655 * _AND_ if we decided to act interactively */
659 # define G_interactive_fd (G.interactive_fd)
661 # define G_interactive_fd 0
663 #if ENABLE_FEATURE_EDITING
664 line_input_t *line_input_state;
669 #if ENABLE_HUSH_RANDOM_SUPPORT
675 pid_t saved_tty_pgrp;
676 struct pipe *job_list;
677 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
679 # define G_saved_tty_pgrp 0
681 smallint flag_SIGINT;
682 #if ENABLE_HUSH_LOOPS
683 smallint flag_break_continue;
685 #if ENABLE_HUSH_FUNCTIONS
686 /* 0: outside of a function (or sourced file)
687 * -1: inside of a function, ok to use return builtin
688 * 1: return is invoked, skip all till end of func
690 smallint flag_return_in_progress;
693 #if ENABLE_HUSH_MODE_X
695 # define G_x_mode (G.x_mode)
699 smallint exiting; /* used to prevent EXIT trap recursion */
700 /* These four support $?, $#, and $1 */
701 smalluint last_exitcode;
702 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
703 smalluint global_args_malloced;
704 smalluint inherited_set_is_saved;
705 /* how many non-NULL argv's we have. NB: $# + 1 */
709 char *argv0_for_re_execing;
711 #if ENABLE_HUSH_LOOPS
712 unsigned depth_break_continue;
713 unsigned depth_of_loop;
717 struct variable *top_var;
718 char **expanded_assignments;
719 #if ENABLE_HUSH_FUNCTIONS
720 struct function *top_func;
721 # if ENABLE_HUSH_LOCAL
722 struct variable **shadowed_vars_pp;
723 unsigned func_nest_level;
726 /* Signal and trap handling */
728 unsigned count_SIGCHLD;
729 unsigned handled_SIGCHLD;
730 smallint we_have_children;
732 /* which signals have non-DFL handler (even with no traps set)? */
733 unsigned non_DFL_mask;
734 char **traps; /* char *traps[NSIG] */
735 sigset_t blocked_set;
736 sigset_t inherited_set;
738 unsigned long memleak_value;
741 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
743 #define G (*ptr_to_globals)
744 /* Not #defining name to G.name - this quickly gets unwieldy
745 * (too many defines). Also, I actually prefer to see when a variable
746 * is global, thus "G." prefix is a useful hint */
747 #define INIT_G() do { \
748 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
752 /* Function prototypes for builtins */
753 static int builtin_cd(char **argv) FAST_FUNC;
754 static int builtin_echo(char **argv) FAST_FUNC;
755 static int builtin_eval(char **argv) FAST_FUNC;
756 static int builtin_exec(char **argv) FAST_FUNC;
757 static int builtin_exit(char **argv) FAST_FUNC;
758 static int builtin_export(char **argv) FAST_FUNC;
760 static int builtin_fg_bg(char **argv) FAST_FUNC;
761 static int builtin_jobs(char **argv) FAST_FUNC;
764 static int builtin_help(char **argv) FAST_FUNC;
766 #if ENABLE_HUSH_LOCAL
767 static int builtin_local(char **argv) FAST_FUNC;
770 static int builtin_memleak(char **argv) FAST_FUNC;
773 static int builtin_printf(char **argv) FAST_FUNC;
775 static int builtin_pwd(char **argv) FAST_FUNC;
776 static int builtin_read(char **argv) FAST_FUNC;
777 static int builtin_set(char **argv) FAST_FUNC;
778 static int builtin_shift(char **argv) FAST_FUNC;
779 static int builtin_source(char **argv) FAST_FUNC;
780 static int builtin_test(char **argv) FAST_FUNC;
781 static int builtin_trap(char **argv) FAST_FUNC;
782 static int builtin_type(char **argv) FAST_FUNC;
783 static int builtin_true(char **argv) FAST_FUNC;
784 static int builtin_umask(char **argv) FAST_FUNC;
785 static int builtin_unset(char **argv) FAST_FUNC;
786 static int builtin_wait(char **argv) FAST_FUNC;
787 #if ENABLE_HUSH_LOOPS
788 static int builtin_break(char **argv) FAST_FUNC;
789 static int builtin_continue(char **argv) FAST_FUNC;
791 #if ENABLE_HUSH_FUNCTIONS
792 static int builtin_return(char **argv) FAST_FUNC;
795 /* Table of built-in functions. They can be forked or not, depending on
796 * context: within pipes, they fork. As simple commands, they do not.
797 * When used in non-forking context, they can change global variables
798 * in the parent shell process. If forked, of course they cannot.
799 * For example, 'unset foo | whatever' will parse and run, but foo will
800 * still be set at the end. */
801 struct built_in_command {
803 int (*b_function)(char **argv) FAST_FUNC;
806 # define BLTIN(cmd, func, help) { cmd, func, help }
808 # define BLTIN(cmd, func, help) { cmd, func }
812 static const struct built_in_command bltins1[] = {
813 BLTIN("." , builtin_source , "Run commands in a file"),
814 BLTIN(":" , builtin_true , NULL),
816 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
818 #if ENABLE_HUSH_LOOPS
819 BLTIN("break" , builtin_break , "Exit from a loop"),
821 BLTIN("cd" , builtin_cd , "Change directory"),
822 #if ENABLE_HUSH_LOOPS
823 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
825 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
826 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
827 BLTIN("exit" , builtin_exit , "Exit"),
828 BLTIN("export" , builtin_export , "Set environment variables"),
830 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
833 BLTIN("help" , builtin_help , NULL),
836 BLTIN("jobs" , builtin_jobs , "List jobs"),
838 #if ENABLE_HUSH_LOCAL
839 BLTIN("local" , builtin_local , "Set local variables"),
842 BLTIN("memleak" , builtin_memleak , NULL),
844 BLTIN("read" , builtin_read , "Input into variable"),
845 #if ENABLE_HUSH_FUNCTIONS
846 BLTIN("return" , builtin_return , "Return from a function"),
848 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
849 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
850 #if ENABLE_HUSH_BASH_COMPAT
851 BLTIN("source" , builtin_source , "Run commands in a file"),
853 BLTIN("trap" , builtin_trap , "Trap signals"),
854 BLTIN("type" , builtin_type , "Show command type"),
855 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
856 BLTIN("umask" , builtin_umask , "Set file creation mask"),
857 BLTIN("unset" , builtin_unset , "Unset variables"),
858 BLTIN("wait" , builtin_wait , "Wait for process"),
860 /* For now, echo and test are unconditionally enabled.
861 * Maybe make it configurable? */
862 static const struct built_in_command bltins2[] = {
863 BLTIN("[" , builtin_test , NULL),
864 BLTIN("echo" , builtin_echo , NULL),
866 BLTIN("printf" , builtin_printf , NULL),
868 BLTIN("pwd" , builtin_pwd , NULL),
869 BLTIN("test" , builtin_test , NULL),
876 /* prevent disasters with G.debug_indent < 0 */
877 # define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
878 # define debug_enter() (G.debug_indent++)
879 # define debug_leave() (G.debug_indent--)
881 # define indent() ((void)0)
882 # define debug_enter() ((void)0)
883 # define debug_leave() ((void)0)
887 # define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
890 #ifndef debug_printf_parse
891 # define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
894 #ifndef debug_printf_exec
895 #define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
898 #ifndef debug_printf_env
899 # define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
902 #ifndef debug_printf_jobs
903 # define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
904 # define DEBUG_JOBS 1
906 # define DEBUG_JOBS 0
909 #ifndef debug_printf_expand
910 # define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
911 # define DEBUG_EXPAND 1
913 # define DEBUG_EXPAND 0
916 #ifndef debug_printf_varexp
917 # define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
920 #ifndef debug_printf_glob
921 # define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
922 # define DEBUG_GLOB 1
924 # define DEBUG_GLOB 0
927 #ifndef debug_printf_list
928 # define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
931 #ifndef debug_printf_subst
932 # define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
935 #ifndef debug_printf_clean
936 # define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
937 # define DEBUG_CLEAN 1
939 # define DEBUG_CLEAN 0
943 static void debug_print_strings(const char *prefix, char **vv)
946 fprintf(stderr, "%s:\n", prefix);
948 fprintf(stderr, " '%s'\n", *vv++);
951 # define debug_print_strings(prefix, vv) ((void)0)
955 /* Leak hunting. Use hush_leaktool.sh for post-processing.
958 static void *xxmalloc(int lineno, size_t size)
960 void *ptr = xmalloc((size + 0xff) & ~0xff);
961 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
964 static void *xxrealloc(int lineno, void *ptr, size_t size)
966 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
967 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
970 static char *xxstrdup(int lineno, const char *str)
972 char *ptr = xstrdup(str);
973 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
976 static void xxfree(void *ptr)
978 fdprintf(2, "free %p\n", ptr);
981 # define xmalloc(s) xxmalloc(__LINE__, s)
982 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
983 # define xstrdup(s) xxstrdup(__LINE__, s)
984 # define free(p) xxfree(p)
988 /* Syntax and runtime errors. They always abort scripts.
989 * In interactive use they usually discard unparsed and/or unexecuted commands
990 * and return to the prompt.
991 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
994 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
995 # define syntax_error(lineno, msg) syntax_error(msg)
996 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
997 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
998 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
999 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1002 static void die_if_script(unsigned lineno, const char *fmt, ...)
1007 bb_error_msg("hush.c:%u", lineno);
1010 bb_verror_msg(fmt, p, NULL);
1012 if (!G_interactive_fd)
1016 static void syntax_error(unsigned lineno, const char *msg)
1019 die_if_script(lineno, "syntax error: %s", msg);
1021 die_if_script(lineno, "syntax error", NULL);
1024 static void syntax_error_at(unsigned lineno, const char *msg)
1026 die_if_script(lineno, "syntax error at '%s'", msg);
1029 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1031 die_if_script(lineno, "syntax error: unterminated %s", s);
1034 /* It so happens that all such cases are totally fatal
1035 * even if shell is interactive: EOF while looking for closing
1036 * delimiter. There is nowhere to read stuff from after that,
1037 * it's EOF! The only choice is to terminate.
1039 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1040 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1042 char msg[2] = { ch, '\0' };
1043 syntax_error_unterm_str(lineno, msg);
1047 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1052 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1056 # undef die_if_script
1057 # undef syntax_error
1058 # undef syntax_error_at
1059 # undef syntax_error_unterm_ch
1060 # undef syntax_error_unterm_str
1061 # undef syntax_error_unexpected_ch
1063 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1064 # define syntax_error(msg) syntax_error(__LINE__, msg)
1065 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1066 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1067 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1068 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1072 #if ENABLE_HUSH_INTERACTIVE
1073 static void cmdedit_update_prompt(void);
1075 # define cmdedit_update_prompt() ((void)0)
1079 /* Utility functions
1081 /* Replace each \x with x in place, return ptr past NUL. */
1082 static char *unbackslash(char *src)
1084 char *dst = src = strchrnul(src, '\\');
1088 if ((*dst++ = *src++) == '\0')
1094 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1115 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1116 v[count1 + count2] = NULL;
1119 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1123 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1125 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1126 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1129 #define add_strings_to_strings(strings, add, need_to_dup) \
1130 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1133 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1134 static char **add_string_to_strings(char **strings, char *add)
1139 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1142 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1144 char **ptr = add_string_to_strings(strings, add);
1145 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1148 #define add_string_to_strings(strings, add) \
1149 xx_add_string_to_strings(__LINE__, strings, add)
1152 static void free_strings(char **strings)
1167 /* Helpers for setting new $n and restoring them back
1169 typedef struct save_arg_t {
1173 smallint sv_g_malloced;
1176 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1180 sv->sv_argv0 = argv[0];
1181 sv->sv_g_argv = G.global_argv;
1182 sv->sv_g_argc = G.global_argc;
1183 sv->sv_g_malloced = G.global_args_malloced;
1185 argv[0] = G.global_argv[0]; /* retain $0 */
1186 G.global_argv = argv;
1187 G.global_args_malloced = 0;
1195 static void restore_G_args(save_arg_t *sv, char **argv)
1199 if (G.global_args_malloced) {
1200 /* someone ran "set -- arg1 arg2 ...", undo */
1202 while (*++pp) /* note: does not free $0 */
1204 free(G.global_argv);
1206 argv[0] = sv->sv_argv0;
1207 G.global_argv = sv->sv_g_argv;
1208 G.global_argc = sv->sv_g_argc;
1209 G.global_args_malloced = sv->sv_g_malloced;
1213 /* Basic theory of signal handling in shell
1214 * ========================================
1215 * This does not describe what hush does, rather, it is current understanding
1216 * what it _should_ do. If it doesn't, it's a bug.
1217 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1219 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1220 * is finished or backgrounded. It is the same in interactive and
1221 * non-interactive shells, and is the same regardless of whether
1222 * a user trap handler is installed or a shell special one is in effect.
1223 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1224 * backgrounds (i.e. stops) or kills all members of currently running
1227 * Wait builtin in interruptible by signals for which user trap is set
1228 * or by SIGINT in interactive shell.
1230 * Trap handlers will execute even within trap handlers. (right?)
1232 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1233 * except for handlers set to '' (empty string).
1235 * If job control is off, backgrounded commands ("cmd &")
1236 * have SIGINT, SIGQUIT set to SIG_IGN.
1238 * Commands which are run in command substitution ("`cmd`")
1239 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1241 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1242 * by the shell from its parent.
1244 * Signals which differ from SIG_DFL action
1245 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1248 * SIGTERM (interactive): ignore
1249 * SIGHUP (interactive):
1250 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1251 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1252 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1253 * that all pipe members are stopped. Try this in bash:
1254 * while :; do :; done - ^Z does not background it
1255 * (while :; do :; done) - ^Z backgrounds it
1256 * SIGINT (interactive): wait for last pipe, ignore the rest
1257 * of the command line, show prompt. NB: ^C does not send SIGINT
1258 * to interactive shell while shell is waiting for a pipe,
1259 * since shell is bg'ed (is not in foreground process group).
1260 * Example 1: this waits 5 sec, but does not execute ls:
1261 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1262 * Example 2: this does not wait and does not execute ls:
1263 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1264 * Example 3: this does not wait 5 sec, but executes ls:
1265 * "sleep 5; ls -l" + press ^C
1267 * (What happens to signals which are IGN on shell start?)
1268 * (What happens with signal mask on shell start?)
1270 * Implementation in hush
1271 * ======================
1272 * We use in-kernel pending signal mask to determine which signals were sent.
1273 * We block all signals which we don't want to take action immediately,
1274 * i.e. we block all signals which need to have special handling as described
1275 * above, and all signals which have traps set.
1276 * After each pipe execution, we extract any pending signals via sigtimedwait()
1279 * unsigned non_DFL_mask: a mask of such "special" signals
1280 * sigset_t blocked_set: current blocked signal set
1283 * clear bit in blocked_set unless it is also in non_DFL_mask
1284 * "trap 'cmd' SIGxxx":
1285 * set bit in blocked_set (even if 'cmd' is '')
1286 * after [v]fork, if we plan to be a shell:
1287 * unblock signals with special interactive handling
1288 * (child shell is not interactive),
1289 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1290 * after [v]fork, if we plan to exec:
1291 * POSIX says fork clears pending signal mask in child - no need to clear it.
1292 * Restore blocked signal set to one inherited by shell just prior to exec.
1294 * Note: as a result, we do not use signal handlers much. The only uses
1295 * are to count SIGCHLDs
1296 * and to restore tty pgrp on signal-induced exit.
1299 * Standard says "When a subshell is entered, traps that are not being ignored
1300 * are set to the default actions". bash interprets it so that traps which
1301 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1304 SPECIAL_INTERACTIVE_SIGS = 0
1309 SPECIAL_JOB_SIGS = 0
1317 #if ENABLE_HUSH_FAST
1318 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1321 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1327 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1328 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1329 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1330 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1332 /* Restores tty foreground process group, and exits.
1333 * May be called as signal handler for fatal signal
1334 * (will resend signal to itself, producing correct exit state)
1335 * or called directly with -EXITCODE.
1336 * We also call it if xfunc is exiting. */
1337 static void sigexit(int sig) NORETURN;
1338 static void sigexit(int sig)
1340 /* Disable all signals: job control, SIGPIPE, etc. */
1341 sigprocmask_allsigs(SIG_BLOCK);
1343 /* Careful: we can end up here after [v]fork. Do not restore
1344 * tty pgrp then, only top-level shell process does that */
1345 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1346 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1348 /* Not a signal, just exit */
1352 kill_myself_with_sig(sig); /* does not return */
1356 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1357 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1361 /* Restores tty foreground process group, and exits. */
1362 static void hush_exit(int exitcode) NORETURN;
1363 static void hush_exit(int exitcode)
1365 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1366 /* Prevent recursion:
1367 * trap "echo Hi; exit" EXIT; exit
1370 /* argv[0] is unused */
1371 argv[1] = G.traps[0];
1373 G.exiting = 1; /* prevent EXIT trap recursion */
1374 /* Note: G.traps[0] is not cleared!
1375 * "trap" will still show it, if executed
1382 sigexit(- (exitcode & 0xff));
1389 static int check_and_run_traps(int sig)
1391 /* I want it in rodata, not in bss.
1392 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1393 * initializer. But other compilers may still use bss.
1394 * TODO: find more portable solution.
1396 static const struct timespec zero_timespec = { 0, 0 };
1397 smalluint save_rcode;
1403 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1408 if (G.traps && G.traps[sig]) {
1409 if (G.traps[sig][0]) {
1410 /* We have user-defined handler */
1412 /* argv[0] is unused */
1413 argv[1] = G.traps[sig];
1415 save_rcode = G.last_exitcode;
1417 G.last_exitcode = save_rcode;
1418 } /* else: "" trap, ignoring signal */
1421 /* not a trap: special action */
1423 #if ENABLE_HUSH_FAST
1426 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1430 /* Builtin was ^C'ed, make it look prettier: */
1437 /* bash is observed to signal whole process groups,
1438 * not individual processes */
1439 for (job = G.job_list; job; job = job->next) {
1442 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1443 if (kill(- job->pgrp, SIGHUP) == 0)
1444 kill(- job->pgrp, SIGCONT);
1449 default: /* ignored: */
1450 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1458 static const char *get_cwd(int force)
1460 if (force || G.cwd == NULL) {
1461 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1462 * we must not try to free(bb_msg_unknown) */
1463 if (G.cwd == bb_msg_unknown)
1465 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1467 G.cwd = bb_msg_unknown;
1474 * Shell and environment variable support
1476 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1478 struct variable **pp;
1479 struct variable *cur;
1482 while ((cur = *pp) != NULL) {
1483 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1490 static const char* FAST_FUNC get_local_var_value(const char *name)
1492 struct variable **vpp;
1493 unsigned len = strlen(name);
1495 if (G.expanded_assignments) {
1496 char **cpp = G.expanded_assignments;
1499 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1500 return cp + len + 1;
1505 vpp = get_ptr_to_local_var(name, len);
1507 return (*vpp)->varstr + len + 1;
1509 if (strcmp(name, "PPID") == 0)
1510 return utoa(G.root_ppid);
1511 // bash compat: UID? EUID?
1512 #if ENABLE_HUSH_RANDOM_SUPPORT
1513 if (strcmp(name, "RANDOM") == 0)
1514 return utoa(next_random(&G.random_gen));
1519 /* str holds "NAME=VAL" and is expected to be malloced.
1520 * We take ownership of it.
1522 * 0: do not change export flag
1523 * (if creating new variable, flag will be 0)
1524 * 1: set export flag and putenv the variable
1525 * -1: clear export flag and unsetenv the variable
1526 * flg_read_only is set only when we handle -R var=val
1528 #if !BB_MMU && ENABLE_HUSH_LOCAL
1529 /* all params are used */
1530 #elif BB_MMU && ENABLE_HUSH_LOCAL
1531 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1532 set_local_var(str, flg_export, local_lvl)
1533 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1534 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1535 set_local_var(str, flg_export)
1536 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1537 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1538 set_local_var(str, flg_export, flg_read_only)
1540 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1542 struct variable **var_pp;
1543 struct variable *cur;
1547 eq_sign = strchr(str, '=');
1548 if (!eq_sign) { /* not expected to ever happen? */
1553 name_len = eq_sign - str + 1; /* including '=' */
1554 var_pp = &G.top_var;
1555 while ((cur = *var_pp) != NULL) {
1556 if (strncmp(cur->varstr, str, name_len) != 0) {
1557 var_pp = &cur->next;
1560 /* We found an existing var with this name */
1561 if (cur->flg_read_only) {
1565 bb_error_msg("%s: readonly variable", str);
1569 if (flg_export == -1) { // "&& cur->flg_export" ?
1570 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1575 #if ENABLE_HUSH_LOCAL
1576 if (cur->func_nest_level < local_lvl) {
1577 /* New variable is declared as local,
1578 * and existing one is global, or local
1579 * from enclosing function.
1580 * Remove and save old one: */
1581 *var_pp = cur->next;
1582 cur->next = *G.shadowed_vars_pp;
1583 *G.shadowed_vars_pp = cur;
1584 /* bash 3.2.33(1) and exported vars:
1586 * # f() { local z=a; env | grep ^z; }
1592 if (cur->flg_export)
1597 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1602 if (cur->max_len != 0) {
1603 if (cur->max_len >= strlen(str)) {
1604 /* This one is from startup env, reuse space */
1605 strcpy(cur->varstr, str);
1609 /* max_len == 0 signifies "malloced" var, which we can
1610 * (and has to) free */
1614 goto set_str_and_exp;
1617 /* Not found - create new variable struct */
1618 cur = xzalloc(sizeof(*cur));
1619 #if ENABLE_HUSH_LOCAL
1620 cur->func_nest_level = local_lvl;
1622 cur->next = *var_pp;
1628 cur->flg_read_only = flg_read_only;
1631 if (flg_export == 1)
1632 cur->flg_export = 1;
1633 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1634 cmdedit_update_prompt();
1635 if (cur->flg_export) {
1636 if (flg_export == -1) {
1637 cur->flg_export = 0;
1638 /* unsetenv was already done */
1640 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1641 return putenv(cur->varstr);
1647 /* Used at startup and after each cd */
1648 static void set_pwd_var(int exp)
1650 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1651 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1654 static int unset_local_var_len(const char *name, int name_len)
1656 struct variable *cur;
1657 struct variable **var_pp;
1660 return EXIT_SUCCESS;
1661 var_pp = &G.top_var;
1662 while ((cur = *var_pp) != NULL) {
1663 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1664 if (cur->flg_read_only) {
1665 bb_error_msg("%s: readonly variable", name);
1666 return EXIT_FAILURE;
1668 *var_pp = cur->next;
1669 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1670 bb_unsetenv(cur->varstr);
1671 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1672 cmdedit_update_prompt();
1676 return EXIT_SUCCESS;
1678 var_pp = &cur->next;
1680 return EXIT_SUCCESS;
1683 static int unset_local_var(const char *name)
1685 return unset_local_var_len(name, strlen(name));
1688 static void unset_vars(char **strings)
1696 const char *eq = strchrnul(*v, '=');
1697 unset_local_var_len(*v, (int)(eq - *v));
1703 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1705 char *var = xasprintf("%s=%s", name, val);
1706 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1711 * Helpers for "var1=val1 var2=val2 cmd" feature
1713 static void add_vars(struct variable *var)
1715 struct variable *next;
1719 var->next = G.top_var;
1721 if (var->flg_export) {
1722 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1723 putenv(var->varstr);
1725 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1731 static struct variable *set_vars_and_save_old(char **strings)
1734 struct variable *old = NULL;
1740 struct variable *var_p;
1741 struct variable **var_pp;
1744 eq = strchr(*s, '=');
1746 var_pp = get_ptr_to_local_var(*s, eq - *s);
1748 /* Remove variable from global linked list */
1750 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1751 *var_pp = var_p->next;
1752 /* Add it to returned list */
1756 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1767 static int FAST_FUNC static_get(struct in_str *i)
1777 static int FAST_FUNC static_peek(struct in_str *i)
1782 #if ENABLE_HUSH_INTERACTIVE
1784 static void cmdedit_update_prompt(void)
1786 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1787 G.PS1 = get_local_var_value("PS1");
1790 G.PS2 = get_local_var_value("PS2");
1798 static const char *setup_prompt_string(int promptmode)
1800 const char *prompt_str;
1801 debug_printf("setup_prompt_string %d ", promptmode);
1802 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1803 /* Set up the prompt */
1804 if (promptmode == 0) { /* PS1 */
1806 /* bash uses $PWD value, even if it is set by user.
1807 * It uses current dir only if PWD is unset.
1808 * We always use current dir. */
1809 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1814 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1815 debug_printf("result '%s'\n", prompt_str);
1819 static void get_user_input(struct in_str *i)
1822 const char *prompt_str;
1824 prompt_str = setup_prompt_string(i->promptmode);
1825 # if ENABLE_FEATURE_EDITING
1826 /* Enable command line editing only while a command line
1827 * is actually being read */
1830 /* buglet: SIGINT will not make new prompt to appear _at once_,
1831 * only after <Enter>. (^C will work) */
1832 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
1833 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1834 check_and_run_traps(0);
1835 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1836 i->eof_flag = (r < 0);
1837 if (i->eof_flag) { /* EOF/error detected */
1838 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1839 G.user_input_buf[1] = '\0';
1844 fputs(prompt_str, stdout);
1846 G.user_input_buf[0] = r = fgetc(i->file);
1847 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1848 //do we need check_and_run_traps(0)? (maybe only if stdin)
1849 } while (G.flag_SIGINT);
1850 i->eof_flag = (r == EOF);
1852 i->p = G.user_input_buf;
1855 #endif /* INTERACTIVE */
1857 /* This is the magic location that prints prompts
1858 * and gets data back from the user */
1859 static int FAST_FUNC file_get(struct in_str *i)
1863 /* If there is data waiting, eat it up */
1864 if (i->p && *i->p) {
1865 #if ENABLE_HUSH_INTERACTIVE
1869 if (i->eof_flag && !*i->p)
1871 /* note: ch is never NUL */
1873 /* need to double check i->file because we might be doing something
1874 * more complicated by now, like sourcing or substituting. */
1875 #if ENABLE_HUSH_INTERACTIVE
1876 if (G_interactive_fd && i->promptme && i->file == stdin) {
1879 } while (!*i->p); /* need non-empty line */
1880 i->promptmode = 1; /* PS2 */
1885 do ch = fgetc(i->file); while (ch == '\0');
1887 debug_printf("file_get: got '%c' %d\n", ch, ch);
1888 #if ENABLE_HUSH_INTERACTIVE
1895 /* All callers guarantee this routine will never
1896 * be used right after a newline, so prompting is not needed.
1898 static int FAST_FUNC file_peek(struct in_str *i)
1901 if (i->p && *i->p) {
1902 if (i->eof_flag && !i->p[1])
1905 /* note: ch is never NUL */
1907 do ch = fgetc(i->file); while (ch == '\0');
1908 i->eof_flag = (ch == EOF);
1909 i->peek_buf[0] = ch;
1910 i->peek_buf[1] = '\0';
1912 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1916 static void setup_file_in_str(struct in_str *i, FILE *f)
1918 i->peek = file_peek;
1920 #if ENABLE_HUSH_INTERACTIVE
1922 i->promptmode = 0; /* PS1 */
1928 static void setup_string_in_str(struct in_str *i, const char *s)
1930 i->peek = static_peek;
1931 i->get = static_get;
1932 #if ENABLE_HUSH_INTERACTIVE
1934 i->promptmode = 0; /* PS1 */
1944 #define B_CHUNK (32 * sizeof(char*))
1946 static void o_reset_to_empty_unquoted(o_string *o)
1949 o->has_quoted_part = 0;
1954 static void o_free(o_string *o)
1957 memset(o, 0, sizeof(*o));
1960 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1965 static void o_grow_by(o_string *o, int len)
1967 if (o->length + len > o->maxlen) {
1968 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1969 o->data = xrealloc(o->data, 1 + o->maxlen);
1973 static void o_addchr(o_string *o, int ch)
1975 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1977 o->data[o->length] = ch;
1979 o->data[o->length] = '\0';
1982 static void o_addblock(o_string *o, const char *str, int len)
1985 memcpy(&o->data[o->length], str, len);
1987 o->data[o->length] = '\0';
1990 static void o_addstr(o_string *o, const char *str)
1992 o_addblock(o, str, strlen(str));
1996 static void nommu_addchr(o_string *o, int ch)
2002 # define nommu_addchr(o, str) ((void)0)
2005 static void o_addstr_with_NUL(o_string *o, const char *str)
2007 o_addblock(o, str, strlen(str) + 1);
2011 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2012 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2013 * Apparently, on unquoted $v bash still does globbing
2014 * ("v='*.txt'; echo $v" prints all .txt files),
2015 * but NOT brace expansion! Thus, there should be TWO independent
2016 * quoting mechanisms on $v expansion side: one protects
2017 * $v from brace expansion, and other additionally protects "$v" against globbing.
2018 * We have only second one.
2021 #if ENABLE_HUSH_BRACE_EXPANSION
2022 # define MAYBE_BRACES "{}"
2024 # define MAYBE_BRACES ""
2027 /* My analysis of quoting semantics tells me that state information
2028 * is associated with a destination, not a source.
2030 static void o_addqchr(o_string *o, int ch)
2033 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2038 o->data[o->length] = '\\';
2041 o->data[o->length] = ch;
2043 o->data[o->length] = '\0';
2046 static void o_addQchr(o_string *o, int ch)
2049 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2050 && strchr("*?[\\" MAYBE_BRACES, ch)
2053 o->data[o->length] = '\\';
2057 o->data[o->length] = ch;
2059 o->data[o->length] = '\0';
2062 static void o_addqblock(o_string *o, const char *str, int len)
2067 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2068 if (ordinary_cnt > len) /* paranoia */
2070 o_addblock(o, str, ordinary_cnt);
2071 if (ordinary_cnt == len)
2073 str += ordinary_cnt;
2074 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2078 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2080 o->data[o->length] = '\\';
2084 o->data[o->length] = ch;
2086 o->data[o->length] = '\0';
2090 static void o_addQblock(o_string *o, const char *str, int len)
2092 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2093 o_addblock(o, str, len);
2096 o_addqblock(o, str, len);
2099 static void o_addQstr(o_string *o, const char *str)
2101 o_addQblock(o, str, strlen(str));
2104 /* A special kind of o_string for $VAR and `cmd` expansion.
2105 * It contains char* list[] at the beginning, which is grown in 16 element
2106 * increments. Actual string data starts at the next multiple of 16 * (char*).
2107 * list[i] contains an INDEX (int!) into this string data.
2108 * It means that if list[] needs to grow, data needs to be moved higher up
2109 * but list[i]'s need not be modified.
2110 * NB: remembering how many list[i]'s you have there is crucial.
2111 * o_finalize_list() operation post-processes this structure - calculates
2112 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2114 #if DEBUG_EXPAND || DEBUG_GLOB
2115 static void debug_print_list(const char *prefix, o_string *o, int n)
2117 char **list = (char**)o->data;
2118 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2122 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2123 prefix, list, n, string_start, o->length, o->maxlen,
2124 !!(o->o_expflags & EXP_FLAG_GLOB),
2126 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2129 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2130 o->data + (int)list[i] + string_start,
2131 o->data + (int)list[i] + string_start);
2135 const char *p = o->data + (int)list[n - 1] + string_start;
2137 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2141 # define debug_print_list(prefix, o, n) ((void)0)
2144 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2145 * in list[n] so that it points past last stored byte so far.
2146 * It returns n+1. */
2147 static int o_save_ptr_helper(o_string *o, int n)
2149 char **list = (char**)o->data;
2153 if (!o->has_empty_slot) {
2154 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2155 string_len = o->length - string_start;
2156 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2157 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2158 /* list[n] points to string_start, make space for 16 more pointers */
2159 o->maxlen += 0x10 * sizeof(list[0]);
2160 o->data = xrealloc(o->data, o->maxlen + 1);
2161 list = (char**)o->data;
2162 memmove(list + n + 0x10, list + n, string_len);
2163 o->length += 0x10 * sizeof(list[0]);
2165 debug_printf_list("list[%d]=%d string_start=%d\n",
2166 n, string_len, string_start);
2169 /* We have empty slot at list[n], reuse without growth */
2170 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2171 string_len = o->length - string_start;
2172 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2173 n, string_len, string_start);
2174 o->has_empty_slot = 0;
2176 list[n] = (char*)(uintptr_t)string_len;
2180 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2181 static int o_get_last_ptr(o_string *o, int n)
2183 char **list = (char**)o->data;
2184 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2186 return ((int)(uintptr_t)list[n-1]) + string_start;
2189 #if ENABLE_HUSH_BRACE_EXPANSION
2190 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2191 * first, it processes even {a} (no commas), second,
2192 * I didn't manage to make it return strings when they don't match
2193 * existing files. Need to re-implement it.
2197 static int glob_needed(const char *s)
2206 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2212 /* Return pointer to next closing brace or to comma */
2213 static const char *next_brace_sub(const char *cp)
2217 while (*cp != '\0') {
2224 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2230 return *cp != '\0' ? cp : NULL;
2232 /* Recursive brace globber. Note: may garble pattern[]. */
2233 static int glob_brace(char *pattern, o_string *o, int n)
2235 char *new_pattern_buf;
2242 debug_printf_glob("glob_brace('%s')\n", pattern);
2248 if (*begin == '{') {
2249 /* Find the first sub-pattern and at the same time
2250 * find the rest after the closing brace */
2251 next = next_brace_sub(begin);
2253 /* An illegal expression */
2257 /* "{abc}" with no commas - illegal
2258 * brace expr, disregard and skip it */
2264 if (*begin == '\\' && begin[1] != '\0')
2268 debug_printf_glob("begin:%s\n", begin);
2269 debug_printf_glob("next:%s\n", next);
2271 /* Now find the end of the whole brace expression */
2273 while (*rest != '}') {
2274 rest = next_brace_sub(rest);
2276 /* An illegal expression */
2279 debug_printf_glob("rest:%s\n", rest);
2281 rest_len = strlen(++rest) + 1;
2283 /* We are sure the brace expression is well-formed */
2285 /* Allocate working buffer large enough for our work */
2286 new_pattern_buf = xmalloc(strlen(pattern));
2288 /* We have a brace expression. BEGIN points to the opening {,
2289 * NEXT points past the terminator of the first element, and REST
2290 * points past the final }. We will accumulate result names from
2291 * recursive runs for each brace alternative in the buffer using
2296 /* Construct the new glob expression */
2299 mempcpy(new_pattern_buf,
2300 /* We know the prefix for all sub-patterns */
2301 pattern, begin - pattern),
2305 /* Note: glob_brace() may garble new_pattern_buf[].
2306 * That's why we re-copy prefix every time (1st memcpy above).
2308 n = glob_brace(new_pattern_buf, o, n);
2310 /* We saw the last entry */
2314 next = next_brace_sub(next);
2316 free(new_pattern_buf);
2324 memset(&globdata, 0, sizeof(globdata));
2325 gr = glob(pattern, 0, NULL, &globdata);
2326 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2328 if (gr == GLOB_NOMATCH) {
2329 globfree(&globdata);
2330 /* NB: garbles parameter */
2331 unbackslash(pattern);
2332 o_addstr_with_NUL(o, pattern);
2333 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2334 return o_save_ptr_helper(o, n);
2336 if (gr == GLOB_NOSPACE)
2337 bb_error_msg_and_die(bb_msg_memory_exhausted);
2338 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2339 * but we didn't specify it. Paranoia again. */
2340 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2342 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2343 char **argv = globdata.gl_pathv;
2345 o_addstr_with_NUL(o, *argv);
2346 n = o_save_ptr_helper(o, n);
2352 globfree(&globdata);
2356 /* Performs globbing on last list[],
2357 * saving each result as a new list[].
2359 static int perform_glob(o_string *o, int n)
2361 char *pattern, *copy;
2363 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2365 return o_save_ptr_helper(o, n);
2366 pattern = o->data + o_get_last_ptr(o, n);
2367 debug_printf_glob("glob pattern '%s'\n", pattern);
2368 if (!glob_needed(pattern)) {
2369 /* unbackslash last string in o in place, fix length */
2370 o->length = unbackslash(pattern) - o->data;
2371 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2372 return o_save_ptr_helper(o, n);
2375 copy = xstrdup(pattern);
2376 /* "forget" pattern in o */
2377 o->length = pattern - o->data;
2378 n = glob_brace(copy, o, n);
2381 debug_print_list("perform_glob returning", o, n);
2385 #else /* !HUSH_BRACE_EXPANSION */
2388 static int glob_needed(const char *s)
2397 if (*s == '*' || *s == '[' || *s == '?')
2403 /* Performs globbing on last list[],
2404 * saving each result as a new list[].
2406 static int perform_glob(o_string *o, int n)
2412 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2414 return o_save_ptr_helper(o, n);
2415 pattern = o->data + o_get_last_ptr(o, n);
2416 debug_printf_glob("glob pattern '%s'\n", pattern);
2417 if (!glob_needed(pattern)) {
2419 /* unbackslash last string in o in place, fix length */
2420 o->length = unbackslash(pattern) - o->data;
2421 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2422 return o_save_ptr_helper(o, n);
2425 memset(&globdata, 0, sizeof(globdata));
2426 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2427 * If we glob "*.\*" and don't find anything, we need
2428 * to fall back to using literal "*.*", but GLOB_NOCHECK
2429 * will return "*.\*"!
2431 gr = glob(pattern, 0, NULL, &globdata);
2432 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2434 if (gr == GLOB_NOMATCH) {
2435 globfree(&globdata);
2438 if (gr == GLOB_NOSPACE)
2439 bb_error_msg_and_die(bb_msg_memory_exhausted);
2440 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2441 * but we didn't specify it. Paranoia again. */
2442 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2444 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2445 char **argv = globdata.gl_pathv;
2446 /* "forget" pattern in o */
2447 o->length = pattern - o->data;
2449 o_addstr_with_NUL(o, *argv);
2450 n = o_save_ptr_helper(o, n);
2456 globfree(&globdata);
2458 debug_print_list("perform_glob returning", o, n);
2462 #endif /* !HUSH_BRACE_EXPANSION */
2464 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2465 * Otherwise, just finish current list[] and start new */
2466 static int o_save_ptr(o_string *o, int n)
2468 if (o->o_expflags & EXP_FLAG_GLOB) {
2469 /* If o->has_empty_slot, list[n] was already globbed
2470 * (if it was requested back then when it was filled)
2471 * so don't do that again! */
2472 if (!o->has_empty_slot)
2473 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2475 return o_save_ptr_helper(o, n);
2478 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2479 static char **o_finalize_list(o_string *o, int n)
2484 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2486 debug_print_list("finalized", o, n);
2487 debug_printf_expand("finalized n:%d\n", n);
2488 list = (char**)o->data;
2489 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2493 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2498 static void free_pipe_list(struct pipe *pi);
2500 /* Returns pi->next - next pipe in the list */
2501 static struct pipe *free_pipe(struct pipe *pi)
2506 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2507 for (i = 0; i < pi->num_cmds; i++) {
2508 struct command *command;
2509 struct redir_struct *r, *rnext;
2511 command = &pi->cmds[i];
2512 debug_printf_clean(" command %d:\n", i);
2513 if (command->argv) {
2517 for (a = 0, p = command->argv; *p; a++, p++) {
2518 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2521 free_strings(command->argv);
2522 //command->argv = NULL;
2524 /* not "else if": on syntax error, we may have both! */
2525 if (command->group) {
2526 debug_printf_clean(" begin group (cmd_type:%d)\n",
2528 free_pipe_list(command->group);
2529 debug_printf_clean(" end group\n");
2530 //command->group = NULL;
2532 /* else is crucial here.
2533 * If group != NULL, child_func is meaningless */
2534 #if ENABLE_HUSH_FUNCTIONS
2535 else if (command->child_func) {
2536 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2537 command->child_func->parent_cmd = NULL;
2541 free(command->group_as_string);
2542 //command->group_as_string = NULL;
2544 for (r = command->redirects; r; r = rnext) {
2545 debug_printf_clean(" redirect %d%s",
2546 r->rd_fd, redir_table[r->rd_type].descrip);
2547 /* guard against the case >$FOO, where foo is unset or blank */
2548 if (r->rd_filename) {
2549 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2550 free(r->rd_filename);
2551 //r->rd_filename = NULL;
2553 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2557 //command->redirects = NULL;
2559 free(pi->cmds); /* children are an array, they get freed all at once */
2563 //pi->cmdtext = NULL;
2571 static void free_pipe_list(struct pipe *pi)
2575 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2577 debug_printf_clean("pipe followup code %d\n", pi->followup);
2583 /*** Parsing routines ***/
2585 static struct pipe *new_pipe(void)
2588 pi = xzalloc(sizeof(struct pipe));
2589 /*pi->followup = 0; - deliberately invalid value */
2590 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2594 /* Command (member of a pipe) is complete, or we start a new pipe
2595 * if ctx->command is NULL.
2596 * No errors possible here.
2598 static int done_command(struct parse_context *ctx)
2600 /* The command is really already in the pipe structure, so
2601 * advance the pipe counter and make a new, null command. */
2602 struct pipe *pi = ctx->pipe;
2603 struct command *command = ctx->command;
2606 if (IS_NULL_CMD(command)) {
2607 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2611 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2612 //debug_print_tree(ctx->list_head, 20);
2614 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2617 /* Only real trickiness here is that the uncommitted
2618 * command structure is not counted in pi->num_cmds. */
2619 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2620 ctx->command = command = &pi->cmds[pi->num_cmds];
2622 memset(command, 0, sizeof(*command));
2623 return pi->num_cmds; /* used only for 0/nonzero check */
2626 static void done_pipe(struct parse_context *ctx, pipe_style type)
2630 debug_printf_parse("done_pipe entered, followup %d\n", type);
2631 /* Close previous command */
2632 not_null = done_command(ctx);
2633 ctx->pipe->followup = type;
2635 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2636 ctx->ctx_inverted = 0;
2637 ctx->pipe->res_word = ctx->ctx_res_w;
2640 /* Without this check, even just <enter> on command line generates
2641 * tree of three NOPs (!). Which is harmless but annoying.
2642 * IOW: it is safe to do it unconditionally. */
2645 || ctx->ctx_res_w == RES_FI
2647 #if ENABLE_HUSH_LOOPS
2648 || ctx->ctx_res_w == RES_DONE
2649 || ctx->ctx_res_w == RES_FOR
2650 || ctx->ctx_res_w == RES_IN
2652 #if ENABLE_HUSH_CASE
2653 || ctx->ctx_res_w == RES_ESAC
2657 debug_printf_parse("done_pipe: adding new pipe: "
2658 "not_null:%d ctx->ctx_res_w:%d\n",
2659 not_null, ctx->ctx_res_w);
2661 ctx->pipe->next = new_p;
2663 /* RES_THEN, RES_DO etc are "sticky" -
2664 * they remain set for pipes inside if/while.
2665 * This is used to control execution.
2666 * RES_FOR and RES_IN are NOT sticky (needed to support
2667 * cases where variable or value happens to match a keyword):
2669 #if ENABLE_HUSH_LOOPS
2670 if (ctx->ctx_res_w == RES_FOR
2671 || ctx->ctx_res_w == RES_IN)
2672 ctx->ctx_res_w = RES_NONE;
2674 #if ENABLE_HUSH_CASE
2675 if (ctx->ctx_res_w == RES_MATCH)
2676 ctx->ctx_res_w = RES_CASE_BODY;
2677 if (ctx->ctx_res_w == RES_CASE)
2678 ctx->ctx_res_w = RES_CASE_IN;
2680 ctx->command = NULL; /* trick done_command below */
2681 /* Create the memory for command, roughly:
2682 * ctx->pipe->cmds = new struct command;
2683 * ctx->command = &ctx->pipe->cmds[0];
2686 //debug_print_tree(ctx->list_head, 10);
2688 debug_printf_parse("done_pipe return\n");
2691 static void initialize_context(struct parse_context *ctx)
2693 memset(ctx, 0, sizeof(*ctx));
2694 ctx->pipe = ctx->list_head = new_pipe();
2695 /* Create the memory for command, roughly:
2696 * ctx->pipe->cmds = new struct command;
2697 * ctx->command = &ctx->pipe->cmds[0];
2702 /* If a reserved word is found and processed, parse context is modified
2703 * and 1 is returned.
2706 struct reserved_combo {
2709 unsigned char assignment_flag;
2713 FLAG_END = (1 << RES_NONE ),
2715 FLAG_IF = (1 << RES_IF ),
2716 FLAG_THEN = (1 << RES_THEN ),
2717 FLAG_ELIF = (1 << RES_ELIF ),
2718 FLAG_ELSE = (1 << RES_ELSE ),
2719 FLAG_FI = (1 << RES_FI ),
2721 # if ENABLE_HUSH_LOOPS
2722 FLAG_FOR = (1 << RES_FOR ),
2723 FLAG_WHILE = (1 << RES_WHILE),
2724 FLAG_UNTIL = (1 << RES_UNTIL),
2725 FLAG_DO = (1 << RES_DO ),
2726 FLAG_DONE = (1 << RES_DONE ),
2727 FLAG_IN = (1 << RES_IN ),
2729 # if ENABLE_HUSH_CASE
2730 FLAG_MATCH = (1 << RES_MATCH),
2731 FLAG_ESAC = (1 << RES_ESAC ),
2733 FLAG_START = (1 << RES_XXXX ),
2736 static const struct reserved_combo* match_reserved_word(o_string *word)
2738 /* Mostly a list of accepted follow-up reserved words.
2739 * FLAG_END means we are done with the sequence, and are ready
2740 * to turn the compound list into a command.
2741 * FLAG_START means the word must start a new compound list.
2743 static const struct reserved_combo reserved_list[] = {
2745 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2746 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2747 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2748 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2749 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2750 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2752 # if ENABLE_HUSH_LOOPS
2753 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2754 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2755 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2756 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2757 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2758 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2760 # if ENABLE_HUSH_CASE
2761 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2762 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2765 const struct reserved_combo *r;
2767 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2768 if (strcmp(word->data, r->literal) == 0)
2773 /* Return 0: not a keyword, 1: keyword
2775 static int reserved_word(o_string *word, struct parse_context *ctx)
2777 # if ENABLE_HUSH_CASE
2778 static const struct reserved_combo reserved_match = {
2779 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2782 const struct reserved_combo *r;
2784 if (word->has_quoted_part)
2786 r = match_reserved_word(word);
2790 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2791 # if ENABLE_HUSH_CASE
2792 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2793 /* "case word IN ..." - IN part starts first MATCH part */
2794 r = &reserved_match;
2797 if (r->flag == 0) { /* '!' */
2798 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2799 syntax_error("! ! command");
2800 ctx->ctx_res_w = RES_SNTX;
2802 ctx->ctx_inverted = 1;
2805 if (r->flag & FLAG_START) {
2806 struct parse_context *old;
2808 old = xmalloc(sizeof(*old));
2809 debug_printf_parse("push stack %p\n", old);
2810 *old = *ctx; /* physical copy */
2811 initialize_context(ctx);
2813 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2814 syntax_error_at(word->data);
2815 ctx->ctx_res_w = RES_SNTX;
2818 /* "{...} fi" is ok. "{...} if" is not
2820 * if { echo foo; } then { echo bar; } fi */
2821 if (ctx->command->group)
2822 done_pipe(ctx, PIPE_SEQ);
2825 ctx->ctx_res_w = r->res;
2826 ctx->old_flag = r->flag;
2827 word->o_assignment = r->assignment_flag;
2829 if (ctx->old_flag & FLAG_END) {
2830 struct parse_context *old;
2832 done_pipe(ctx, PIPE_SEQ);
2833 debug_printf_parse("pop stack %p\n", ctx->stack);
2835 old->command->group = ctx->list_head;
2836 old->command->cmd_type = CMD_NORMAL;
2838 o_addstr(&old->as_string, ctx->as_string.data);
2839 o_free_unsafe(&ctx->as_string);
2840 old->command->group_as_string = xstrdup(old->as_string.data);
2841 debug_printf_parse("pop, remembering as:'%s'\n",
2842 old->command->group_as_string);
2844 *ctx = *old; /* physical copy */
2849 #endif /* HAS_KEYWORDS */
2851 /* Word is complete, look at it and update parsing context.
2852 * Normal return is 0. Syntax errors return 1.
2853 * Note: on return, word is reset, but not o_free'd!
2855 static int done_word(o_string *word, struct parse_context *ctx)
2857 struct command *command = ctx->command;
2859 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
2860 if (word->length == 0 && !word->has_quoted_part) {
2861 debug_printf_parse("done_word return 0: true null, ignored\n");
2865 if (ctx->pending_redirect) {
2866 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2867 * only if run as "bash", not "sh" */
2868 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
2870 * ...the word that follows the redirection operator
2871 * shall be subjected to tilde expansion, parameter expansion,
2872 * command substitution, arithmetic expansion, and quote
2873 * removal. Pathname expansion shall not be performed
2874 * on the word by a non-interactive shell; an interactive
2875 * shell may perform it, but shall do so only when
2876 * the expansion would result in one word."
2878 ctx->pending_redirect->rd_filename = xstrdup(word->data);
2879 /* Cater for >\file case:
2880 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
2881 * Same with heredocs:
2882 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
2884 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
2885 unbackslash(ctx->pending_redirect->rd_filename);
2886 /* Is it <<"HEREDOC"? */
2887 if (word->has_quoted_part) {
2888 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
2891 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
2892 ctx->pending_redirect = NULL;
2894 /* If this word wasn't an assignment, next ones definitely
2895 * can't be assignments. Even if they look like ones. */
2896 if (word->o_assignment != DEFINITELY_ASSIGNMENT
2897 && word->o_assignment != WORD_IS_KEYWORD
2899 word->o_assignment = NOT_ASSIGNMENT;
2901 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
2902 command->assignment_cnt++;
2903 word->o_assignment = MAYBE_ASSIGNMENT;
2907 # if ENABLE_HUSH_CASE
2908 if (ctx->ctx_dsemicolon
2909 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
2911 /* already done when ctx_dsemicolon was set to 1: */
2912 /* ctx->ctx_res_w = RES_MATCH; */
2913 ctx->ctx_dsemicolon = 0;
2916 if (!command->argv /* if it's the first word... */
2917 # if ENABLE_HUSH_LOOPS
2918 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
2919 && ctx->ctx_res_w != RES_IN
2921 # if ENABLE_HUSH_CASE
2922 && ctx->ctx_res_w != RES_CASE
2925 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
2926 if (reserved_word(word, ctx)) {
2927 o_reset_to_empty_unquoted(word);
2928 debug_printf_parse("done_word return %d\n",
2929 (ctx->ctx_res_w == RES_SNTX));
2930 return (ctx->ctx_res_w == RES_SNTX);
2932 # if ENABLE_HUSH_BASH_COMPAT
2933 if (strcmp(word->data, "[[") == 0) {
2934 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
2940 if (command->group) {
2941 /* "{ echo foo; } echo bar" - bad */
2942 syntax_error_at(word->data);
2943 debug_printf_parse("done_word return 1: syntax error, "
2944 "groups and arglists don't mix\n");
2947 if (word->has_quoted_part
2948 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2949 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2950 /* (otherwise it's known to be not empty and is already safe) */
2952 /* exclude "$@" - it can expand to no word despite "" */
2953 char *p = word->data;
2954 while (p[0] == SPECIAL_VAR_SYMBOL
2955 && (p[1] & 0x7f) == '@'
2956 && p[2] == SPECIAL_VAR_SYMBOL
2960 if (p == word->data || p[0] != '\0') {
2961 /* saw no "$@", or not only "$@" but some
2962 * real text is there too */
2963 /* insert "empty variable" reference, this makes
2964 * e.g. "", $empty"" etc to not disappear */
2965 o_addchr(word, SPECIAL_VAR_SYMBOL);
2966 o_addchr(word, SPECIAL_VAR_SYMBOL);
2969 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
2970 debug_print_strings("word appended to argv", command->argv);
2973 #if ENABLE_HUSH_LOOPS
2974 if (ctx->ctx_res_w == RES_FOR) {
2975 if (word->has_quoted_part
2976 || !is_well_formed_var_name(command->argv[0], '\0')
2978 /* bash says just "not a valid identifier" */
2979 syntax_error("not a valid identifier in for");
2982 /* Force FOR to have just one word (variable name) */
2983 /* NB: basically, this makes hush see "for v in ..."
2984 * syntax as if it is "for v; in ...". FOR and IN become
2985 * two pipe structs in parse tree. */
2986 done_pipe(ctx, PIPE_SEQ);
2989 #if ENABLE_HUSH_CASE
2990 /* Force CASE to have just one word */
2991 if (ctx->ctx_res_w == RES_CASE) {
2992 done_pipe(ctx, PIPE_SEQ);
2996 o_reset_to_empty_unquoted(word);
2998 debug_printf_parse("done_word return 0\n");
3003 /* Peek ahead in the input to find out if we have a "&n" construct,
3004 * as in "2>&1", that represents duplicating a file descriptor.
3006 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3007 * REDIRFD_SYNTAX_ERR if syntax error,
3008 * REDIRFD_TO_FILE if no & was seen,
3009 * or the number found.
3012 #define parse_redir_right_fd(as_string, input) \
3013 parse_redir_right_fd(input)
3015 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3021 return REDIRFD_TO_FILE;
3023 ch = i_getch(input); /* get the & */
3024 nommu_addchr(as_string, ch);
3027 ch = i_getch(input);
3028 nommu_addchr(as_string, ch);
3029 return REDIRFD_CLOSE;
3033 while (ch != EOF && isdigit(ch)) {
3034 d = d*10 + (ch-'0');
3036 ch = i_getch(input);
3037 nommu_addchr(as_string, ch);
3042 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3044 bb_error_msg("ambiguous redirect");
3045 return REDIRFD_SYNTAX_ERR;
3048 /* Return code is 0 normal, 1 if a syntax error is detected
3050 static int parse_redirect(struct parse_context *ctx,
3053 struct in_str *input)
3055 struct command *command = ctx->command;
3056 struct redir_struct *redir;
3057 struct redir_struct **redirp;
3060 dup_num = REDIRFD_TO_FILE;
3061 if (style != REDIRECT_HEREDOC) {
3062 /* Check for a '>&1' type redirect */
3063 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3064 if (dup_num == REDIRFD_SYNTAX_ERR)
3067 int ch = i_peek(input);
3068 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3069 if (dup_num) { /* <<-... */
3070 ch = i_getch(input);
3071 nommu_addchr(&ctx->as_string, ch);
3076 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3077 int ch = i_peek(input);
3079 /* >|FILE redirect ("clobbering" >).
3080 * Since we do not support "set -o noclobber" yet,
3081 * >| and > are the same for now. Just eat |.
3083 ch = i_getch(input);
3084 nommu_addchr(&ctx->as_string, ch);
3088 /* Create a new redir_struct and append it to the linked list */
3089 redirp = &command->redirects;
3090 while ((redir = *redirp) != NULL) {
3091 redirp = &(redir->next);
3093 *redirp = redir = xzalloc(sizeof(*redir));
3094 /* redir->next = NULL; */
3095 /* redir->rd_filename = NULL; */
3096 redir->rd_type = style;
3097 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3099 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3100 redir_table[style].descrip);
3102 redir->rd_dup = dup_num;
3103 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3104 /* Erik had a check here that the file descriptor in question
3105 * is legit; I postpone that to "run time"
3106 * A "-" representation of "close me" shows up as a -3 here */
3107 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3108 redir->rd_fd, redir->rd_dup);
3110 /* Set ctx->pending_redirect, so we know what to do at the
3111 * end of the next parsed word. */
3112 ctx->pending_redirect = redir;
3117 /* If a redirect is immediately preceded by a number, that number is
3118 * supposed to tell which file descriptor to redirect. This routine
3119 * looks for such preceding numbers. In an ideal world this routine
3120 * needs to handle all the following classes of redirects...
3121 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3122 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3123 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3124 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3126 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3128 * ... If n is quoted, the number shall not be recognized as part of
3129 * the redirection expression. For example:
3131 * writes the character 2 into file a"
3132 * We are getting it right by setting ->has_quoted_part on any \<char>
3134 * A -1 return means no valid number was found,
3135 * the caller should use the appropriate default for this redirection.
3137 static int redirect_opt_num(o_string *o)
3141 if (o->data == NULL)
3143 num = bb_strtou(o->data, NULL, 10);
3144 if (errno || num < 0)
3146 o_reset_to_empty_unquoted(o);
3151 #define fetch_till_str(as_string, input, word, skip_tabs) \
3152 fetch_till_str(input, word, skip_tabs)
3154 static char *fetch_till_str(o_string *as_string,
3155 struct in_str *input,
3159 o_string heredoc = NULL_O_STRING;
3161 int prev = 0; /* not \ */
3166 ch = i_getch(input);
3168 nommu_addchr(as_string, ch);
3169 if ((ch == '\n' || ch == EOF)
3170 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3172 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3173 heredoc.data[past_EOL] = '\0';
3174 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3175 return heredoc.data;
3177 while (ch == '\n') {
3178 o_addchr(&heredoc, ch);
3181 past_EOL = heredoc.length;
3183 ch = i_getch(input);
3185 nommu_addchr(as_string, ch);
3186 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3190 o_free_unsafe(&heredoc);
3193 o_addchr(&heredoc, ch);
3194 nommu_addchr(as_string, ch);
3195 if (prev == '\\' && ch == '\\')
3196 /* Correctly handle foo\\<eol> (not a line cont.) */
3197 prev = 0; /* not \ */
3203 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3204 * and load them all. There should be exactly heredoc_cnt of them.
3206 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3208 struct pipe *pi = ctx->list_head;
3210 while (pi && heredoc_cnt) {
3212 struct command *cmd = pi->cmds;
3214 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3216 cmd->argv ? cmd->argv[0] : "NONE");
3217 for (i = 0; i < pi->num_cmds; i++) {
3218 struct redir_struct *redir = cmd->redirects;
3220 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3221 i, cmd->argv ? cmd->argv[0] : "NONE");
3223 if (redir->rd_type == REDIRECT_HEREDOC) {
3226 redir->rd_type = REDIRECT_HEREDOC2;
3227 /* redir->rd_dup is (ab)used to indicate <<- */
3228 p = fetch_till_str(&ctx->as_string, input,
3229 redir->rd_filename, redir->rd_dup);
3231 syntax_error("unexpected EOF in here document");
3234 free(redir->rd_filename);
3235 redir->rd_filename = p;
3238 redir = redir->next;
3245 /* Should be 0. If it isn't, it's a parse error */
3247 bb_error_msg_and_die("heredoc BUG 2");
3253 static int run_list(struct pipe *pi);
3255 #define parse_stream(pstring, input, end_trigger) \
3256 parse_stream(input, end_trigger)
3258 static struct pipe *parse_stream(char **pstring,
3259 struct in_str *input,
3263 #if !ENABLE_HUSH_FUNCTIONS
3264 #define parse_group(dest, ctx, input, ch) \
3265 parse_group(ctx, input, ch)
3267 static int parse_group(o_string *dest, struct parse_context *ctx,
3268 struct in_str *input, int ch)
3270 /* dest contains characters seen prior to ( or {.
3271 * Typically it's empty, but for function defs,
3272 * it contains function name (without '()'). */
3273 struct pipe *pipe_list;
3275 struct command *command = ctx->command;
3277 debug_printf_parse("parse_group entered\n");
3278 #if ENABLE_HUSH_FUNCTIONS
3279 if (ch == '(' && !dest->has_quoted_part) {
3281 if (done_word(dest, ctx))
3284 goto skip; /* (... */
3285 if (command->argv[1]) { /* word word ... (... */
3286 syntax_error_unexpected_ch('(');
3289 /* it is "word(..." or "word (..." */
3291 ch = i_getch(input);
3292 while (ch == ' ' || ch == '\t');
3294 syntax_error_unexpected_ch(ch);
3297 nommu_addchr(&ctx->as_string, ch);
3299 ch = i_getch(input);
3300 while (ch == ' ' || ch == '\t' || ch == '\n');
3302 syntax_error_unexpected_ch(ch);
3305 nommu_addchr(&ctx->as_string, ch);
3306 command->cmd_type = CMD_FUNCDEF;
3311 #if 0 /* Prevented by caller */
3312 if (command->argv /* word [word]{... */
3313 || dest->length /* word{... */
3314 || dest->has_quoted_part /* ""{... */
3317 debug_printf_parse("parse_group return 1: "
3318 "syntax error, groups and arglists don't mix\n");
3323 #if ENABLE_HUSH_FUNCTIONS
3329 command->cmd_type = CMD_SUBSHELL;
3331 /* bash does not allow "{echo...", requires whitespace */
3332 ch = i_getch(input);
3333 if (ch != ' ' && ch != '\t' && ch != '\n') {
3334 syntax_error_unexpected_ch(ch);
3337 nommu_addchr(&ctx->as_string, ch);
3342 # define as_string NULL
3344 char *as_string = NULL;
3346 pipe_list = parse_stream(&as_string, input, endch);
3349 o_addstr(&ctx->as_string, as_string);
3351 /* empty ()/{} or parse error? */
3352 if (!pipe_list || pipe_list == ERR_PTR) {
3353 /* parse_stream already emitted error msg */
3356 debug_printf_parse("parse_group return 1: "
3357 "parse_stream returned %p\n", pipe_list);
3360 command->group = pipe_list;
3362 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3363 command->group_as_string = as_string;
3364 debug_printf_parse("end of group, remembering as:'%s'\n",
3365 command->group_as_string);
3369 debug_printf_parse("parse_group return 0\n");
3371 /* command remains "open", available for possible redirects */
3374 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3375 /* Subroutines for copying $(...) and `...` things */
3376 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3378 static void add_till_single_quote(o_string *dest, struct in_str *input)
3381 int ch = i_getch(input);
3383 syntax_error_unterm_ch('\'');
3384 /*xfunc_die(); - redundant */
3391 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3392 static void add_till_double_quote(o_string *dest, struct in_str *input)
3395 int ch = i_getch(input);
3397 syntax_error_unterm_ch('"');
3398 /*xfunc_die(); - redundant */
3402 if (ch == '\\') { /* \x. Copy both chars. */
3404 ch = i_getch(input);
3408 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3412 //if (ch == '$') ...
3415 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3417 * "Within the backquoted style of command substitution, backslash
3418 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3419 * The search for the matching backquote shall be satisfied by the first
3420 * backquote found without a preceding backslash; during this search,
3421 * if a non-escaped backquote is encountered within a shell comment,
3422 * a here-document, an embedded command substitution of the $(command)
3423 * form, or a quoted string, undefined results occur. A single-quoted
3424 * or double-quoted string that begins, but does not end, within the
3425 * "`...`" sequence produces undefined results."
3427 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3429 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3432 int ch = i_getch(input);
3436 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3437 ch = i_getch(input);
3441 && (!in_dquote || ch != '"')
3443 o_addchr(dest, '\\');
3447 syntax_error_unterm_ch('`');
3448 /*xfunc_die(); - redundant */
3453 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3454 * quoting and nested ()s.
3455 * "With the $(command) style of command substitution, all characters
3456 * following the open parenthesis to the matching closing parenthesis
3457 * constitute the command. Any valid shell script can be used for command,
3458 * except a script consisting solely of redirections which produces
3459 * unspecified results."
3461 * echo $(echo '(TEST)' BEST) (TEST) BEST
3462 * echo $(echo 'TEST)' BEST) TEST) BEST
3463 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3465 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3466 * can contain arbitrary constructs, just like $(cmd).
3467 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3468 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3470 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3471 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3474 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3475 # if ENABLE_HUSH_BASH_COMPAT
3476 char end_char2 = end_ch >> 8;
3478 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3481 ch = i_getch(input);
3483 syntax_error_unterm_ch(end_ch);
3484 /*xfunc_die(); - redundant */
3486 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3489 /* we look for closing )) of $((EXPR)) */
3490 if (i_peek(input) == end_ch) {
3491 i_getch(input); /* eat second ')' */
3496 if (ch == '(' || ch == '{') {
3497 ch = (ch == '(' ? ')' : '}');
3498 add_till_closing_bracket(dest, input, ch);
3503 add_till_single_quote(dest, input);
3508 add_till_double_quote(dest, input);
3513 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3518 /* \x. Copy verbatim. Important for \(, \) */
3519 ch = i_getch(input);
3521 syntax_error_unterm_ch(')');
3522 /*xfunc_die(); - redundant */
3530 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3532 /* Return code: 0 for OK, 1 for syntax error */
3534 #define parse_dollar(as_string, dest, input, quote_mask) \
3535 parse_dollar(dest, input, quote_mask)
3536 #define as_string NULL
3538 static int parse_dollar(o_string *as_string,
3540 struct in_str *input, unsigned char quote_mask)
3542 int ch = i_peek(input); /* first character after the $ */
3544 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3546 ch = i_getch(input);
3547 nommu_addchr(as_string, ch);
3549 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3551 debug_printf_parse(": '%c'\n", ch);
3552 o_addchr(dest, ch | quote_mask);
3555 if (!isalnum(ch) && ch != '_')
3557 ch = i_getch(input);
3558 nommu_addchr(as_string, ch);
3560 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3561 } else if (isdigit(ch)) {
3563 ch = i_getch(input);
3564 nommu_addchr(as_string, ch);
3565 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3566 debug_printf_parse(": '%c'\n", ch);
3567 o_addchr(dest, ch | quote_mask);
3568 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3569 } else switch (ch) {
3571 case '!': /* last bg pid */
3572 case '?': /* last exit code */
3573 case '#': /* number of args */
3574 case '*': /* args */
3575 case '@': /* args */
3576 goto make_one_char_var;
3578 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3580 ch = i_getch(input); /* eat '{' */
3581 nommu_addchr(as_string, ch);
3583 ch = i_getch(input); /* first char after '{' */
3584 /* It should be ${?}, or ${#var},
3585 * or even ${?+subst} - operator acting on a special variable,
3586 * or the beginning of variable name.
3589 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3592 syntax_error_unterm_str("${name}");
3593 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3596 nommu_addchr(as_string, ch);
3599 /* It's possible to just call add_till_closing_bracket() at this point.
3600 * However, this regresses some of our testsuite cases
3601 * which check invalid constructs like ${%}.
3602 * Oh well... let's check that the var name part is fine... */
3608 debug_printf_parse(": '%c'\n", ch);
3610 ch = i_getch(input);
3611 nommu_addchr(as_string, ch);
3615 if (!isalnum(ch) && ch != '_') {
3617 unsigned char last_ch;
3618 /* handle parameter expansions
3619 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3621 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3622 goto bad_dollar_syntax;
3624 /* Eat everything until closing '}' (or ':') */
3626 if (ENABLE_HUSH_BASH_COMPAT
3628 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3630 /* It's ${var:N[:M]} thing */
3631 end_ch = '}' * 0x100 + ':';
3633 if (ENABLE_HUSH_BASH_COMPAT
3636 /* It's ${var/[/]pattern[/repl]} thing */
3637 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3639 nommu_addchr(as_string, '/');
3642 end_ch = '}' * 0x100 + '/';
3648 #if ENABLE_HUSH_DOLLAR_OPS
3649 last_ch = add_till_closing_bracket(dest, input, end_ch);
3651 #error Simple code to only allow ${var} is not implemented
3654 o_addstr(as_string, dest->data + pos);
3655 o_addchr(as_string, last_ch);
3658 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3659 /* close the first block: */
3660 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3661 /* while parsing N from ${var:N[:M]}
3662 * or pattern from ${var/[/]pattern[/repl]} */
3663 if ((end_ch & 0xff) == last_ch) {
3664 /* got ':' or '/'- parse the rest */
3669 if (end_ch == '}' * 0x100 + ':') {
3670 /* it's ${var:N} - emulate :999999999 */
3671 o_addstr(dest, "999999999");
3672 } /* else: it's ${var/[/]pattern} */
3677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3680 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3684 ch = i_getch(input);
3685 nommu_addchr(as_string, ch);
3686 # if ENABLE_SH_MATH_SUPPORT
3687 if (i_peek(input) == '(') {
3688 ch = i_getch(input);
3689 nommu_addchr(as_string, ch);
3690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691 o_addchr(dest, /*quote_mask |*/ '+');
3694 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3696 o_addstr(as_string, dest->data + pos);
3697 o_addchr(as_string, ')');
3698 o_addchr(as_string, ')');
3700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3704 # if ENABLE_HUSH_TICK
3705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3706 o_addchr(dest, quote_mask | '`');
3709 add_till_closing_bracket(dest, input, ')');
3711 o_addstr(as_string, dest->data + pos);
3712 o_addchr(as_string, ')');
3714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720 ch = i_getch(input);
3721 nommu_addchr(as_string, ch);
3723 if (isalnum(ch)) { /* it's $_name or $_123 */
3728 /* TODO: $_ and $-: */
3729 /* $_ Shell or shell script name; or last argument of last command
3730 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3731 * but in command's env, set to full pathname used to invoke it */
3732 /* $- Option flags set by set builtin or shell options (-i etc) */
3734 o_addQchr(dest, '$');
3736 debug_printf_parse("parse_dollar return 0\n");
3742 # if ENABLE_HUSH_BASH_COMPAT
3743 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3744 encode_string(dest, input, dquote_end, process_bkslash)
3746 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3747 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3748 encode_string(dest, input, dquote_end)
3750 #define as_string NULL
3754 # if ENABLE_HUSH_BASH_COMPAT
3755 /* all parameters are needed, no macro tricks */
3757 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3758 encode_string(as_string, dest, input, dquote_end)
3761 static int encode_string(o_string *as_string,
3763 struct in_str *input,
3765 int process_bkslash)
3767 #if !ENABLE_HUSH_BASH_COMPAT
3768 const int process_bkslash = 1;
3774 ch = i_getch(input);
3776 nommu_addchr(as_string, ch);
3777 if (ch == dquote_end) { /* may be only '"' or EOF */
3778 debug_printf_parse("encode_string return 0\n");
3781 /* note: can't move it above ch == dquote_end check! */
3783 syntax_error_unterm_ch('"');
3784 /*xfunc_die(); - redundant */
3788 next = i_peek(input);
3790 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3791 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3792 if (process_bkslash && ch == '\\') {
3794 syntax_error("\\<eof>");
3798 * "The backslash retains its special meaning [in "..."]
3799 * only when followed by one of the following characters:
3800 * $, `, ", \, or <newline>. A double quote may be quoted
3801 * within double quotes by preceding it with a backslash."
3802 * NB: in (unquoted) heredoc, above does not apply to ",
3803 * therefore we check for it by "next == dquote_end" cond.
3805 if (next == dquote_end || strchr("$`\\\n", next)) {
3806 ch = i_getch(input); /* eat next */
3808 goto again; /* skip \<newline> */
3809 } /* else: ch remains == '\\', and we double it below: */
3810 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3811 nommu_addchr(as_string, ch);
3815 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3816 debug_printf_parse("encode_string return 1: "
3817 "parse_dollar returned non-0\n");
3822 #if ENABLE_HUSH_TICK
3824 //unsigned pos = dest->length;
3825 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3826 o_addchr(dest, 0x80 | '`');
3827 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3828 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3829 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3833 o_addQchr(dest, ch);
3839 * Scan input until EOF or end_trigger char.
3840 * Return a list of pipes to execute, or NULL on EOF
3841 * or if end_trigger character is met.
3842 * On syntax error, exit is shell is not interactive,
3843 * reset parsing machinery and start parsing anew,
3844 * or return ERR_PTR.
3846 static struct pipe *parse_stream(char **pstring,
3847 struct in_str *input,
3850 struct parse_context ctx;
3851 o_string dest = NULL_O_STRING;
3854 /* Single-quote triggers a bypass of the main loop until its mate is
3855 * found. When recursing, quote state is passed in via dest->o_expflags.
3857 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
3858 end_trigger ? end_trigger : 'X');
3861 /* If very first arg is "" or '', dest.data may end up NULL.
3862 * Preventing this: */
3863 o_addchr(&dest, '\0');
3866 /* We used to separate words on $IFS here. This was wrong.
3867 * $IFS is used only for word splitting when $var is expanded,
3868 * here we should use blank chars as separators, not $IFS
3871 reset: /* we come back here only on syntax errors in interactive shell */
3873 #if ENABLE_HUSH_INTERACTIVE
3874 input->promptmode = 0; /* PS1 */
3876 if (MAYBE_ASSIGNMENT != 0)
3877 dest.o_assignment = MAYBE_ASSIGNMENT;
3878 initialize_context(&ctx);
3881 const char *is_blank;
3882 const char *is_special;
3886 redir_type redir_style;
3888 ch = i_getch(input);
3889 debug_printf_parse(": ch=%c (%d) escape=%d\n",
3890 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3895 syntax_error_unterm_str("here document");
3898 /* end_trigger == '}' case errors out earlier,
3899 * checking only ')' */
3900 if (end_trigger == ')') {
3901 syntax_error_unterm_ch('('); /* exits */
3902 /* goto parse_error; */
3905 if (done_word(&dest, &ctx)) {
3909 done_pipe(&ctx, PIPE_SEQ);
3911 /* If we got nothing... */
3912 /* (this makes bare "&" cmd a no-op.
3913 * bash says: "syntax error near unexpected token '&'") */
3914 if (pi->num_cmds == 0
3915 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
3921 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
3923 *pstring = ctx.as_string.data;
3925 o_free_unsafe(&ctx.as_string);
3928 debug_printf_parse("parse_stream return %p\n", pi);
3931 nommu_addchr(&ctx.as_string, ch);
3935 next = i_peek(input);
3937 is_special = "{}<>;&|()#'" /* special outside of "str" */
3938 "\\$\"" IF_HUSH_TICK("`"); /* always special */
3939 /* Are { and } special here? */
3940 if (ctx.command->argv /* word [word]{... - non-special */
3941 || dest.length /* word{... - non-special */
3942 || dest.has_quoted_part /* ""{... - non-special */
3943 || (next != ';' /* }; - special */
3944 && next != ')' /* }) - special */
3945 && next != '&' /* }& and }&& ... - special */
3946 && next != '|' /* }|| ... - special */
3947 && !strchr(defifs, next) /* {word - non-special */
3950 /* They are not special, skip "{}" */
3953 is_special = strchr(is_special, ch);
3954 is_blank = strchr(defifs, ch);
3956 if (!is_special && !is_blank) { /* ordinary char */
3958 o_addQchr(&dest, ch);
3959 if ((dest.o_assignment == MAYBE_ASSIGNMENT
3960 || dest.o_assignment == WORD_IS_KEYWORD)
3962 && is_well_formed_var_name(dest.data, '=')
3964 dest.o_assignment = DEFINITELY_ASSIGNMENT;
3970 if (done_word(&dest, &ctx)) {
3974 #if ENABLE_HUSH_CASE
3975 /* "case ... in <newline> word) ..." -
3976 * newlines are ignored (but ';' wouldn't be) */
3977 if (ctx.command->argv == NULL
3978 && ctx.ctx_res_w == RES_MATCH
3983 /* Treat newline as a command separator. */
3984 done_pipe(&ctx, PIPE_SEQ);
3985 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
3987 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
3992 dest.o_assignment = MAYBE_ASSIGNMENT;
3994 /* note: if (is_blank) continue;
3995 * will still trigger for us */
3999 /* "cmd}" or "cmd }..." without semicolon or &:
4000 * } is an ordinary char in this case, even inside { cmd; }
4001 * Pathological example: { ""}; } should exec "}" cmd
4004 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4005 || dest.length != 0 /* word} */
4006 || dest.has_quoted_part /* ""} */
4010 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4011 goto skip_end_trigger;
4012 /* else: } does terminate a group */
4015 if (end_trigger && end_trigger == ch
4016 && (ch != ';' || heredoc_cnt == 0)
4017 #if ENABLE_HUSH_CASE
4019 || ctx.ctx_res_w != RES_MATCH
4020 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4025 /* This is technically valid:
4026 * { cat <<HERE; }; echo Ok
4030 * but we don't support this.
4031 * We require heredoc to be in enclosing {}/(),
4034 syntax_error_unterm_str("here document");
4037 if (done_word(&dest, &ctx)) {
4040 done_pipe(&ctx, PIPE_SEQ);
4041 dest.o_assignment = MAYBE_ASSIGNMENT;
4042 /* Do we sit outside of any if's, loops or case's? */
4044 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4048 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4050 *pstring = ctx.as_string.data;
4052 o_free_unsafe(&ctx.as_string);
4055 debug_printf_parse("parse_stream return %p: "
4056 "end_trigger char found\n",
4058 return ctx.list_head;
4065 /* Catch <, > before deciding whether this word is
4066 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4069 redir_fd = redirect_opt_num(&dest);
4070 if (done_word(&dest, &ctx)) {
4073 redir_style = REDIRECT_OVERWRITE;
4075 redir_style = REDIRECT_APPEND;
4076 ch = i_getch(input);
4077 nommu_addchr(&ctx.as_string, ch);
4080 else if (next == '(') {
4081 syntax_error(">(process) not supported");
4085 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4087 continue; /* back to top of while (1) */
4089 redir_fd = redirect_opt_num(&dest);
4090 if (done_word(&dest, &ctx)) {
4093 redir_style = REDIRECT_INPUT;
4095 redir_style = REDIRECT_HEREDOC;
4097 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4098 ch = i_getch(input);
4099 nommu_addchr(&ctx.as_string, ch);
4100 } else if (next == '>') {
4101 redir_style = REDIRECT_IO;
4102 ch = i_getch(input);
4103 nommu_addchr(&ctx.as_string, ch);
4106 else if (next == '(') {
4107 syntax_error("<(process) not supported");
4111 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4113 continue; /* back to top of while (1) */
4116 if (dest.o_assignment == MAYBE_ASSIGNMENT
4117 /* check that we are not in word in "a=1 2>word b=1": */
4118 && !ctx.pending_redirect
4120 /* ch is a special char and thus this word
4121 * cannot be an assignment */
4122 dest.o_assignment = NOT_ASSIGNMENT;
4125 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4129 if (dest.length == 0) {
4132 if (ch == EOF || ch == '\n')
4135 /* note: we do not add it to &ctx.as_string */
4137 nommu_addchr(&ctx.as_string, '\n');
4139 o_addQchr(&dest, ch);
4144 syntax_error("\\<eof>");
4147 ch = i_getch(input);
4149 o_addchr(&dest, '\\');
4150 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4151 o_addchr(&dest, ch);
4152 nommu_addchr(&ctx.as_string, ch);
4153 /* Example: echo Hello \2>file
4154 * we need to know that word 2 is quoted */
4155 dest.has_quoted_part = 1;
4159 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
4160 ctx.as_string.data[--ctx.as_string.length] = '\0';
4165 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4166 debug_printf_parse("parse_stream parse error: "
4167 "parse_dollar returned non-0\n");
4172 dest.has_quoted_part = 1;
4174 ch = i_getch(input);
4176 syntax_error_unterm_ch('\'');
4177 /*xfunc_die(); - redundant */
4179 nommu_addchr(&ctx.as_string, ch);
4182 o_addqchr(&dest, ch);
4186 dest.has_quoted_part = 1;
4187 if (dest.o_assignment == NOT_ASSIGNMENT)
4188 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4189 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4191 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4193 #if ENABLE_HUSH_TICK
4197 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4198 o_addchr(&dest, '`');
4200 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4202 o_addstr(&ctx.as_string, dest.data + pos);
4203 o_addchr(&ctx.as_string, '`');
4205 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4206 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4211 #if ENABLE_HUSH_CASE
4214 if (done_word(&dest, &ctx)) {
4217 done_pipe(&ctx, PIPE_SEQ);
4218 #if ENABLE_HUSH_CASE
4219 /* Eat multiple semicolons, detect
4220 * whether it means something special */
4225 ch = i_getch(input);
4226 nommu_addchr(&ctx.as_string, ch);
4227 if (ctx.ctx_res_w == RES_CASE_BODY) {
4228 ctx.ctx_dsemicolon = 1;
4229 ctx.ctx_res_w = RES_MATCH;
4235 /* We just finished a cmd. New one may start
4236 * with an assignment */
4237 dest.o_assignment = MAYBE_ASSIGNMENT;
4240 if (done_word(&dest, &ctx)) {
4244 ch = i_getch(input);
4245 nommu_addchr(&ctx.as_string, ch);
4246 done_pipe(&ctx, PIPE_AND);
4248 done_pipe(&ctx, PIPE_BG);
4252 if (done_word(&dest, &ctx)) {
4255 #if ENABLE_HUSH_CASE
4256 if (ctx.ctx_res_w == RES_MATCH)
4257 break; /* we are in case's "word | word)" */
4259 if (next == '|') { /* || */
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4262 done_pipe(&ctx, PIPE_OR);
4264 /* we could pick up a file descriptor choice here
4265 * with redirect_opt_num(), but bash doesn't do it.
4266 * "echo foo 2| cat" yields "foo 2". */
4269 o_reset_to_empty_unquoted(&ctx.as_string);
4274 #if ENABLE_HUSH_CASE
4275 /* "case... in [(]word)..." - skip '(' */
4276 if (ctx.ctx_res_w == RES_MATCH
4277 && ctx.command->argv == NULL /* not (word|(... */
4278 && dest.length == 0 /* not word(... */
4279 && dest.has_quoted_part == 0 /* not ""(... */
4285 if (parse_group(&dest, &ctx, input, ch) != 0) {
4290 #if ENABLE_HUSH_CASE
4291 if (ctx.ctx_res_w == RES_MATCH)
4295 /* proper use of this character is caught by end_trigger:
4296 * if we see {, we call parse_group(..., end_trigger='}')
4297 * and it will match } earlier (not here). */
4298 syntax_error_unexpected_ch(ch);
4302 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4308 struct parse_context *pctx;
4309 IF_HAS_KEYWORDS(struct parse_context *p2;)
4311 /* Clean up allocated tree.
4312 * Sample for finding leaks on syntax error recovery path.
4313 * Run it from interactive shell, watch pmap `pidof hush`.
4314 * while if false; then false; fi; do break; fi
4315 * Samples to catch leaks at execution:
4316 * while if (true | {true;}); then echo ok; fi; do break; done
4317 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4321 /* Update pipe/command counts,
4322 * otherwise freeing may miss some */
4323 done_pipe(pctx, PIPE_SEQ);
4324 debug_printf_clean("freeing list %p from ctx %p\n",
4325 pctx->list_head, pctx);
4326 debug_print_tree(pctx->list_head, 0);
4327 free_pipe_list(pctx->list_head);
4328 debug_printf_clean("freed list %p\n", pctx->list_head);
4330 o_free_unsafe(&pctx->as_string);
4332 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4336 IF_HAS_KEYWORDS(pctx = p2;)
4337 } while (HAS_KEYWORDS && pctx);
4338 /* Free text, clear all dest fields */
4340 /* If we are not in top-level parse, we return,
4341 * our caller will propagate error.
4343 if (end_trigger != ';') {
4351 /* Discard cached input, force prompt */
4353 IF_HUSH_INTERACTIVE(input->promptme = 1;)
4359 /*** Execution routines ***/
4361 /* Expansion can recurse, need forward decls: */
4362 #if !ENABLE_HUSH_BASH_COMPAT
4363 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4364 #define expand_string_to_string(str, do_unbackslash) \
4365 expand_string_to_string(str)
4367 static char *expand_string_to_string(const char *str, int do_unbackslash);
4368 static int process_command_subs(o_string *dest, const char *s);
4370 /* expand_strvec_to_strvec() takes a list of strings, expands
4371 * all variable references within and returns a pointer to
4372 * a list of expanded strings, possibly with larger number
4373 * of strings. (Think VAR="a b"; echo $VAR).
4374 * This new list is allocated as a single malloc block.
4375 * NULL-terminated list of char* pointers is at the beginning of it,
4376 * followed by strings themselves.
4377 * Caller can deallocate entire list by single free(list). */
4379 /* A horde of its helpers come first: */
4381 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4383 while (--len >= 0) {
4385 #if ENABLE_HUSH_BRACE_EXPANSION
4386 if (c == '{' || c == '}') {
4387 /* { -> \{, } -> \} */
4395 /* \z -> \\\z; \<eol> -> \\<eol> */
4400 o_addchr(o, *str++);
4406 /* Store given string, finalizing the word and starting new one whenever
4407 * we encounter IFS char(s). This is used for expanding variable values.
4408 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4409 static int expand_on_ifs(o_string *output, int n, const char *str)
4412 int word_len = strcspn(str, G.ifs);
4414 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4415 o_addblock(output, str, word_len);
4417 /* Protect backslashes against globbing up :)
4418 * Example: "v='\*'; echo b$v" prints "b\*"
4419 * (and does not try to glob on "*")
4421 o_addblock_duplicate_backslash(output, str, word_len);
4422 /*/ Why can't we do it easier? */
4423 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4424 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4428 if (!*str) /* EOL - do not finalize word */
4430 o_addchr(output, '\0');
4431 debug_print_list("expand_on_ifs", output, n);
4432 n = o_save_ptr(output, n);
4433 str += strspn(str, G.ifs); /* skip ifs chars */
4435 debug_print_list("expand_on_ifs[1]", output, n);
4439 /* Helper to expand $((...)) and heredoc body. These act as if
4440 * they are in double quotes, with the exception that they are not :).
4441 * Just the rules are similar: "expand only $var and `cmd`"
4443 * Returns malloced string.
4444 * As an optimization, we return NULL if expansion is not needed.
4446 #if !ENABLE_HUSH_BASH_COMPAT
4447 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4448 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4449 encode_then_expand_string(str)
4451 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4454 struct in_str input;
4455 o_string dest = NULL_O_STRING;
4457 if (!strchr(str, '$')
4458 && !strchr(str, '\\')
4459 #if ENABLE_HUSH_TICK
4460 && !strchr(str, '`')
4466 /* We need to expand. Example:
4467 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4469 setup_string_in_str(&input, str);
4470 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4471 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4472 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4473 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4474 o_free_unsafe(&dest);
4478 #if ENABLE_SH_MATH_SUPPORT
4479 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4481 arith_state_t math_state;
4485 math_state.lookupvar = get_local_var_value;
4486 math_state.setvar = set_local_var_from_halves;
4487 //math_state.endofname = endofname;
4488 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4489 res = arith(&math_state, exp_str ? exp_str : arg);
4492 *errmsg_p = math_state.errmsg;
4493 if (math_state.errmsg)
4494 die_if_script(math_state.errmsg);
4499 #if ENABLE_HUSH_BASH_COMPAT
4500 /* ${var/[/]pattern[/repl]} helpers */
4501 static char *strstr_pattern(char *val, const char *pattern, int *size)
4504 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4505 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4512 /* Optimization: if "*pat" did not match the start of "string",
4513 * we know that "tring", "ring" etc will not match too:
4515 if (pattern[0] == '*')
4520 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4522 char *result = NULL;
4523 unsigned res_len = 0;
4524 unsigned repl_len = strlen(repl);
4528 char *s = strstr_pattern(val, pattern, &size);
4532 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4533 memcpy(result + res_len, val, s - val);
4535 strcpy(result + res_len, repl);
4536 res_len += repl_len;
4537 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4543 if (val[0] && result) {
4544 result = xrealloc(result, res_len + strlen(val) + 1);
4545 strcpy(result + res_len, val);
4546 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4548 debug_printf_varexp("result:'%s'\n", result);
4554 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4556 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4558 const char *val = NULL;
4559 char *to_be_freed = NULL;
4564 char exp_save = exp_save; /* for compiler */
4565 char *exp_saveptr; /* points to expansion operator */
4566 char *exp_word = exp_word; /* for compiler */
4569 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4571 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4573 first_char = arg[0] = arg0 & 0x7f;
4576 if (first_char == '#' /* ${#... */
4577 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4579 /* It must be length operator: ${#var} */
4583 /* Maybe handle parameter expansion */
4584 if (exp_saveptr /* if 2nd char is one of expansion operators */
4585 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4587 /* ${?:0}, ${#[:]%0} etc */
4588 exp_saveptr = var + 1;
4590 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4591 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4593 exp_op = exp_save = *exp_saveptr;
4595 exp_word = exp_saveptr + 1;
4596 if (exp_op == ':') {
4597 exp_op = *exp_word++;
4598 //TODO: try ${var:} and ${var:bogus} in non-bash config
4599 if (ENABLE_HUSH_BASH_COMPAT
4600 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4602 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4607 *exp_saveptr = '\0';
4608 } /* else: it's not an expansion op, but bare ${var} */
4611 /* Look up the variable in question */
4612 if (isdigit(var[0])) {
4613 /* parse_dollar should have vetted var for us */
4614 int n = xatoi_positive(var);
4615 if (n < G.global_argc)
4616 val = G.global_argv[n];
4617 /* else val remains NULL: $N with too big N */
4621 val = utoa(G.root_pid);
4623 case '!': /* bg pid */
4624 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4626 case '?': /* exitcode */
4627 val = utoa(G.last_exitcode);
4629 case '#': /* argc */
4630 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4633 val = get_local_var_value(var);
4637 /* Handle any expansions */
4638 if (exp_op == 'L') {
4639 debug_printf_expand("expand: length(%s)=", val);
4640 val = utoa(val ? strlen(val) : 0);
4641 debug_printf_expand("%s\n", val);
4642 } else if (exp_op) {
4643 if (exp_op == '%' || exp_op == '#') {
4644 /* Standard-mandated substring removal ops:
4645 * ${parameter%word} - remove smallest suffix pattern
4646 * ${parameter%%word} - remove largest suffix pattern
4647 * ${parameter#word} - remove smallest prefix pattern
4648 * ${parameter##word} - remove largest prefix pattern
4650 * Word is expanded to produce a glob pattern.
4651 * Then var's value is matched to it and matching part removed.
4653 if (val && val[0]) {
4657 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4658 if (exp_op == *exp_word) /* ## or %% */
4660 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4662 exp_word = exp_exp_word;
4663 /* HACK ALERT. We depend here on the fact that
4664 * G.global_argv and results of utoa and get_local_var_value
4665 * are actually in writable memory:
4666 * scan_and_match momentarily stores NULs there. */
4668 loc = scan_and_match(t, exp_word, scan_flags);
4669 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4670 // exp_op, t, exp_word, loc);
4672 if (loc) { /* match was found */
4673 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4674 val = loc; /* take right part */
4676 val = to_be_freed = xstrndup(val, loc - val); /* left */
4680 #if ENABLE_HUSH_BASH_COMPAT
4681 else if (exp_op == '/' || exp_op == '\\') {
4682 /* It's ${var/[/]pattern[/repl]} thing.
4683 * Note that in encoded form it has TWO parts:
4684 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4685 * and if // is used, it is encoded as \:
4686 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4688 /* Empty variable always gives nothing: */
4689 // "v=''; echo ${v/*/w}" prints "", not "w"
4690 if (val && val[0]) {
4691 /* pattern uses non-standard expansion.
4692 * repl should be unbackslashed and globbed
4693 * by the usual expansion rules:
4695 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4696 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4697 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4698 * v='a bz'; echo ${v/a*z/\z} prints "z"
4699 * (note that a*z _pattern_ is never globbed!)
4701 char *pattern, *repl, *t;
4702 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4704 pattern = xstrdup(exp_word);
4705 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4706 *p++ = SPECIAL_VAR_SYMBOL;
4708 p = strchr(p, SPECIAL_VAR_SYMBOL);
4710 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4711 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4712 /* HACK ALERT. We depend here on the fact that
4713 * G.global_argv and results of utoa and get_local_var_value
4714 * are actually in writable memory:
4715 * replace_pattern momentarily stores NULs there. */
4717 to_be_freed = replace_pattern(t,
4719 (repl ? repl : exp_word),
4721 if (to_be_freed) /* at least one replace happened */
4728 else if (exp_op == ':') {
4729 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4730 /* It's ${var:N[:M]} bashism.
4731 * Note that in encoded form it has TWO parts:
4732 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4737 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4740 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4741 *p++ = SPECIAL_VAR_SYMBOL;
4743 p = strchr(p, SPECIAL_VAR_SYMBOL);
4745 len = expand_and_evaluate_arith(exp_word, &errmsg);
4748 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4749 if (len >= 0) { /* bash compat: len < 0 is illegal */
4750 if (beg < 0) /* bash compat */
4752 debug_printf_varexp("from val:'%s'\n", val);
4753 if (len == 0 || !val || beg >= strlen(val)) {
4757 /* Paranoia. What if user entered 9999999999999
4758 * which fits in arith_t but not int? */
4761 val = to_be_freed = xstrndup(val + beg, len);
4763 debug_printf_varexp("val:'%s'\n", val);
4767 die_if_script("malformed ${%s:...}", var);
4770 } else { /* one of "-=+?" */
4771 /* Standard-mandated substitution ops:
4772 * ${var?word} - indicate error if unset
4773 * If var is unset, word (or a message indicating it is unset
4774 * if word is null) is written to standard error
4775 * and the shell exits with a non-zero exit status.
4776 * Otherwise, the value of var is substituted.
4777 * ${var-word} - use default value
4778 * If var is unset, word is substituted.
4779 * ${var=word} - assign and use default value
4780 * If var is unset, word is assigned to var.
4781 * In all cases, final value of var is substituted.
4782 * ${var+word} - use alternative value
4783 * If var is unset, null is substituted.
4784 * Otherwise, word is substituted.
4786 * Word is subjected to tilde expansion, parameter expansion,
4787 * command substitution, and arithmetic expansion.
4788 * If word is not needed, it is not expanded.
4790 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4791 * but also treat null var as if it is unset.
4793 int use_word = (!val || ((exp_save == ':') && !val[0]));
4795 use_word = !use_word;
4796 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4797 (exp_save == ':') ? "true" : "false", use_word);
4799 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4801 exp_word = to_be_freed;
4802 if (exp_op == '?') {
4803 /* mimic bash message */
4804 die_if_script("%s: %s",
4806 exp_word[0] ? exp_word : "parameter null or not set"
4808 //TODO: how interactive bash aborts expansion mid-command?
4813 if (exp_op == '=') {
4814 /* ${var=[word]} or ${var:=[word]} */
4815 if (isdigit(var[0]) || var[0] == '#') {
4816 /* mimic bash message */
4817 die_if_script("$%s: cannot assign in this way", var);
4820 char *new_var = xasprintf("%s=%s", var, val);
4821 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4825 } /* one of "-=+?" */
4827 *exp_saveptr = exp_save;
4833 *to_be_freed_pp = to_be_freed;
4837 /* Expand all variable references in given string, adding words to list[]
4838 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4839 * to be filled). This routine is extremely tricky: has to deal with
4840 * variables/parameters with whitespace, $* and $@, and constructs like
4841 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
4842 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
4844 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
4845 * expansion of right-hand side of assignment == 1-element expand.
4847 char cant_be_null = 0; /* only bit 0x80 matters */
4850 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4851 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
4852 debug_print_list("expand_vars_to_list", output, n);
4853 n = o_save_ptr(output, n);
4854 debug_print_list("expand_vars_to_list[0]", output, n);
4856 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
4858 char *to_be_freed = NULL;
4859 const char *val = NULL;
4860 #if ENABLE_HUSH_TICK
4861 o_string subst_result = NULL_O_STRING;
4863 #if ENABLE_SH_MATH_SUPPORT
4864 char arith_buf[sizeof(arith_t)*3 + 2];
4866 o_addblock(output, arg, p - arg);
4867 debug_print_list("expand_vars_to_list[1]", output, n);
4869 p = strchr(p, SPECIAL_VAR_SYMBOL);
4871 /* Fetch special var name (if it is indeed one of them)
4872 * and quote bit, force the bit on if singleword expansion -
4873 * important for not getting v=$@ expand to many words. */
4874 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
4876 /* Is this variable quoted and thus expansion can't be null?
4877 * "$@" is special. Even if quoted, it can still
4878 * expand to nothing (not even an empty string),
4879 * thus it is excluded. */
4880 if ((first_ch & 0x7f) != '@')
4881 cant_be_null |= first_ch;
4883 switch (first_ch & 0x7f) {
4884 /* Highest bit in first_ch indicates that var is double-quoted */
4888 if (!G.global_argv[1])
4891 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
4892 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
4893 while (G.global_argv[i]) {
4894 n = expand_on_ifs(output, n, G.global_argv[i]);
4895 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
4896 if (G.global_argv[i++][0] && G.global_argv[i]) {
4897 /* this argv[] is not empty and not last:
4898 * put terminating NUL, start new word */
4899 o_addchr(output, '\0');
4900 debug_print_list("expand_vars_to_list[2]", output, n);
4901 n = o_save_ptr(output, n);
4902 debug_print_list("expand_vars_to_list[3]", output, n);
4906 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
4907 * and in this case should treat it like '$*' - see 'else...' below */
4908 if (first_ch == ('@'|0x80) /* quoted $@ */
4909 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
4912 o_addQstr(output, G.global_argv[i]);
4913 if (++i >= G.global_argc)
4915 o_addchr(output, '\0');
4916 debug_print_list("expand_vars_to_list[4]", output, n);
4917 n = o_save_ptr(output, n);
4919 } else { /* quoted $* (or v="$@" case): add as one word */
4921 o_addQstr(output, G.global_argv[i]);
4922 if (!G.global_argv[++i])
4925 o_addchr(output, G.ifs[0]);
4930 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
4931 /* "Empty variable", used to make "" etc to not disappear */
4933 cant_be_null = 0x80;
4935 #if ENABLE_HUSH_TICK
4936 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
4937 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4939 /* Can't just stuff it into output o_string,
4940 * expanded result may need to be globbed
4941 * and $IFS-splitted */
4942 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
4943 G.last_exitcode = process_command_subs(&subst_result, arg);
4944 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
4945 val = subst_result.data;
4948 #if ENABLE_SH_MATH_SUPPORT
4949 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
4952 arg++; /* skip '+' */
4953 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
4954 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
4955 res = expand_and_evaluate_arith(arg, NULL);
4956 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
4957 sprintf(arith_buf, ARITH_FMT, res);
4963 val = expand_one_var(&to_be_freed, arg, &p);
4964 IF_HUSH_TICK(store_val:)
4965 if (!(first_ch & 0x80)) { /* unquoted $VAR */
4966 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
4967 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4968 if (val && val[0]) {
4969 n = expand_on_ifs(output, n, val);
4972 } else { /* quoted $VAR, val will be appended below */
4973 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
4974 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4978 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
4980 if (val && val[0]) {
4981 o_addQstr(output, val);
4985 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
4986 * Do the check to avoid writing to a const string. */
4987 if (*p != SPECIAL_VAR_SYMBOL)
4988 *p = SPECIAL_VAR_SYMBOL;
4990 #if ENABLE_HUSH_TICK
4991 o_free(&subst_result);
4994 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
4997 debug_print_list("expand_vars_to_list[a]", output, n);
4998 /* this part is literal, and it was already pre-quoted
4999 * if needed (much earlier), do not use o_addQstr here! */
5000 o_addstr_with_NUL(output, arg);
5001 debug_print_list("expand_vars_to_list[b]", output, n);
5002 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5003 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5006 /* allow to reuse list[n] later without re-growth */
5007 output->has_empty_slot = 1;
5009 o_addchr(output, '\0');
5015 static char **expand_variables(char **argv, unsigned expflags)
5019 o_string output = NULL_O_STRING;
5021 output.o_expflags = expflags;
5025 n = expand_vars_to_list(&output, n, *argv);
5028 debug_print_list("expand_variables", &output, n);
5030 /* output.data (malloced in one block) gets returned in "list" */
5031 list = o_finalize_list(&output, n);
5032 debug_print_strings("expand_variables[1]", list);
5036 static char **expand_strvec_to_strvec(char **argv)
5038 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5041 #if ENABLE_HUSH_BASH_COMPAT
5042 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5044 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5048 /* Used for expansion of right hand of assignments,
5049 * $((...)), heredocs, variable espansion parts.
5051 * NB: should NOT do globbing!
5052 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5054 static char *expand_string_to_string(const char *str, int do_unbackslash)
5056 #if !ENABLE_HUSH_BASH_COMPAT
5057 const int do_unbackslash = 1;
5059 char *argv[2], **list;
5061 debug_printf_expand("string_to_string<='%s'\n", str);
5062 /* This is generally an optimization, but it also
5063 * handles "", which otherwise trips over !list[0] check below.
5064 * (is this ever happens that we actually get str="" here?)
5066 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5067 //TODO: Can use on strings with \ too, just unbackslash() them?
5068 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5069 return xstrdup(str);
5072 argv[0] = (char*)str;
5074 list = expand_variables(argv, do_unbackslash
5075 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5076 : EXP_FLAG_SINGLEWORD
5079 if (!list[0] || list[1])
5080 bb_error_msg_and_die("BUG in varexp2");
5081 /* actually, just move string 2*sizeof(char*) bytes back */
5082 overlapping_strcpy((char*)list, list[0]);
5084 unbackslash((char*)list);
5085 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5089 /* Used for "eval" builtin */
5090 static char* expand_strvec_to_string(char **argv)
5094 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5095 /* Convert all NULs to spaces */
5100 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5101 bb_error_msg_and_die("BUG in varexp3");
5102 /* bash uses ' ' regardless of $IFS contents */
5107 overlapping_strcpy((char*)list, list[0]);
5108 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5112 static char **expand_assignments(char **argv, int count)
5117 G.expanded_assignments = p = NULL;
5118 /* Expand assignments into one string each */
5119 for (i = 0; i < count; i++) {
5120 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5122 G.expanded_assignments = NULL;
5129 void re_execute_shell(char ***to_free, const char *s,
5130 char *g_argv0, char **g_argv,
5131 char **builtin_argv) NORETURN;
5133 static void reset_traps_to_defaults(void)
5135 /* This function is always called in a child shell
5136 * after fork (not vfork, NOMMU doesn't use this function).
5141 /* Child shells are not interactive.
5142 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5143 * Testcase: (while :; do :; done) + ^Z should background.
5144 * Same goes for SIGTERM, SIGHUP, SIGINT.
5146 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5147 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5149 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5150 * Stupid. It can be done with *single* &= op, but we can't use
5151 * the fact that G.blocked_set is implemented as a bitmask
5153 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5157 /* Careful. Only if no trap or trap is not "" */
5158 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5159 sigdelset(&G.blocked_set, sig);
5166 /* Our homegrown sig mask is saner to work with :) */
5167 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5169 /* Resetting all traps to default except empty ones */
5170 mask = G.non_DFL_mask;
5171 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5172 if (!G.traps[sig] || !G.traps[sig][0])
5175 G.traps[sig] = NULL;
5176 /* There is no signal for 0 (EXIT) */
5179 /* There was a trap handler, we just removed it.
5180 * But if sig still has non-DFL handling,
5181 * we should not unblock the sig. */
5184 sigdelset(&G.blocked_set, sig);
5186 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5191 static void re_execute_shell(char ***to_free, const char *s,
5192 char *g_argv0, char **g_argv,
5193 char **builtin_argv) NORETURN;
5194 static void re_execute_shell(char ***to_free, const char *s,
5195 char *g_argv0, char **g_argv,
5196 char **builtin_argv)
5198 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5199 /* delims + 2 * (number of bytes in printed hex numbers) */
5200 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5201 char *heredoc_argv[4];
5202 struct variable *cur;
5203 # if ENABLE_HUSH_FUNCTIONS
5204 struct function *funcp;
5208 unsigned long long empty_trap_mask;
5210 if (!g_argv0) { /* heredoc */
5211 argv = heredoc_argv;
5212 argv[0] = (char *) G.argv0_for_re_execing;
5213 argv[1] = (char *) "-<";
5214 argv[2] = (char *) s;
5216 pp = &argv[3]; /* used as pointer to empty environment */
5222 if (pp) while (*pp++)
5225 empty_trap_mask = 0;
5228 for (sig = 1; sig < NSIG; sig++) {
5229 if (G.traps[sig] && !G.traps[sig][0])
5230 empty_trap_mask |= 1LL << sig;
5234 sprintf(param_buf, NOMMU_HACK_FMT
5235 , (unsigned) G.root_pid
5236 , (unsigned) G.root_ppid
5237 , (unsigned) G.last_bg_pid
5238 , (unsigned) G.last_exitcode
5241 IF_HUSH_LOOPS(, G.depth_of_loop)
5243 # undef NOMMU_HACK_FMT
5244 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5245 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5248 for (cur = G.top_var; cur; cur = cur->next) {
5249 if (!cur->flg_export || cur->flg_read_only)
5252 # if ENABLE_HUSH_FUNCTIONS
5253 for (funcp = G.top_func; funcp; funcp = funcp->next)
5259 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5260 *pp++ = (char *) G.argv0_for_re_execing;
5262 for (cur = G.top_var; cur; cur = cur->next) {
5263 if (strcmp(cur->varstr, hush_version_str) == 0)
5265 if (cur->flg_read_only) {
5266 *pp++ = (char *) "-R";
5267 *pp++ = cur->varstr;
5268 } else if (!cur->flg_export) {
5269 *pp++ = (char *) "-V";
5270 *pp++ = cur->varstr;
5273 # if ENABLE_HUSH_FUNCTIONS
5274 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5275 *pp++ = (char *) "-F";
5276 *pp++ = funcp->name;
5277 *pp++ = funcp->body_as_string;
5280 /* We can pass activated traps here. Say, -Tnn:trap_string
5282 * However, POSIX says that subshells reset signals with traps
5284 * I tested bash-3.2 and it not only does that with true subshells
5285 * of the form ( list ), but with any forked children shells.
5286 * I set trap "echo W" WINCH; and then tried:
5288 * { echo 1; sleep 20; echo 2; } &
5289 * while true; do echo 1; sleep 20; echo 2; break; done &
5290 * true | { echo 1; sleep 20; echo 2; } | cat
5292 * In all these cases sending SIGWINCH to the child shell
5293 * did not run the trap. If I add trap "echo V" WINCH;
5294 * _inside_ group (just before echo 1), it works.
5296 * I conclude it means we don't need to pass active traps here.
5297 * Even if we would use signal handlers instead of signal masking
5298 * in order to implement trap handling,
5299 * exec syscall below resets signals to SIG_DFL for us.
5301 *pp++ = (char *) "-c";
5304 while (*++builtin_argv)
5305 *pp++ = *builtin_argv;
5306 *pp++ = (char *) "";
5311 /* *pp = NULL; - is already there */
5315 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5316 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5317 execve(bb_busybox_exec_path, argv, pp);
5318 /* Fallback. Useful for init=/bin/hush usage etc */
5319 if (argv[0][0] == '/')
5320 execve(argv[0], argv, pp);
5321 xfunc_error_retval = 127;
5322 bb_error_msg_and_die("can't re-execute the shell");
5324 #endif /* !BB_MMU */
5327 static int run_and_free_list(struct pipe *pi);
5329 /* Executing from string: eval, sh -c '...'
5330 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5331 * end_trigger controls how often we stop parsing
5332 * NUL: parse all, execute, return
5333 * ';': parse till ';' or newline, execute, repeat till EOF
5335 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5337 /* Why we need empty flag?
5338 * An obscure corner case "false; ``; echo $?":
5339 * empty command in `` should still set $? to 0.
5340 * But we can't just set $? to 0 at the start,
5341 * this breaks "false; echo `echo $?`" case.
5345 struct pipe *pipe_list;
5347 pipe_list = parse_stream(NULL, inp, end_trigger);
5348 if (!pipe_list) { /* EOF */
5350 G.last_exitcode = 0;
5353 debug_print_tree(pipe_list, 0);
5354 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5355 run_and_free_list(pipe_list);
5360 static void parse_and_run_string(const char *s)
5362 struct in_str input;
5363 setup_string_in_str(&input, s);
5364 parse_and_run_stream(&input, '\0');
5367 static void parse_and_run_file(FILE *f)
5369 struct in_str input;
5370 setup_file_in_str(&input, f);
5371 parse_and_run_stream(&input, ';');
5374 #if ENABLE_HUSH_TICK
5375 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5380 char **to_free = NULL;
5384 pid = BB_MMU ? xfork() : xvfork();
5385 if (pid == 0) { /* child */
5386 disable_restore_tty_pgrp_on_exit();
5387 /* Process substitution is not considered to be usual
5388 * 'command execution'.
5389 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5396 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5397 close(channel[0]); /* NB: close _first_, then move fd! */
5398 xmove_fd(channel[1], 1);
5399 /* Prevent it from trying to handle ctrl-z etc */
5400 IF_HUSH_JOB(G.run_list_level = 1;)
5401 /* Awful hack for `trap` or $(trap).
5403 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5404 * contains an example where "trap" is executed in a subshell:
5406 * save_traps=$(trap)
5408 * eval "$save_traps"
5410 * Standard does not say that "trap" in subshell shall print
5411 * parent shell's traps. It only says that its output
5412 * must have suitable form, but then, in the above example
5413 * (which is not supposed to be normative), it implies that.
5415 * bash (and probably other shell) does implement it
5416 * (traps are reset to defaults, but "trap" still shows them),
5417 * but as a result, "trap" logic is hopelessly messed up:
5420 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5421 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5422 * # true | trap <--- trap is in subshell - no output (ditto)
5423 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5424 * trap -- 'echo Ho' SIGWINCH
5425 * # echo `(trap)` <--- in subshell in subshell - output
5426 * trap -- 'echo Ho' SIGWINCH
5427 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5428 * trap -- 'echo Ho' SIGWINCH
5430 * The rules when to forget and when to not forget traps
5431 * get really complex and nonsensical.
5433 * Our solution: ONLY bare $(trap) or `trap` is special.
5435 s = skip_whitespace(s);
5436 if (strncmp(s, "trap", 4) == 0
5437 && skip_whitespace(s + 4)[0] == '\0'
5439 static const char *const argv[] = { NULL, NULL };
5440 builtin_trap((char**)argv);
5441 exit(0); /* not _exit() - we need to fflush */
5444 reset_traps_to_defaults();
5445 parse_and_run_string(s);
5446 _exit(G.last_exitcode);
5448 /* We re-execute after vfork on NOMMU. This makes this script safe:
5449 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5450 * huge=`cat BIG` # was blocking here forever
5453 re_execute_shell(&to_free,
5463 # if ENABLE_HUSH_FAST
5465 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5466 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5467 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5469 enable_restore_tty_pgrp_on_exit();
5474 close_on_exec_on(channel[0]);
5475 return xfdopen_for_read(channel[0]);
5478 /* Return code is exit status of the process that is run. */
5479 static int process_command_subs(o_string *dest, const char *s)
5482 struct in_str pipe_str;
5484 int status, ch, eol_cnt;
5486 fp = generate_stream_from_string(s, &pid);
5488 /* Now send results of command back into original context */
5489 setup_file_in_str(&pipe_str, fp);
5491 while ((ch = i_getch(&pipe_str)) != EOF) {
5497 o_addchr(dest, '\n');
5500 o_addQchr(dest, ch);
5503 debug_printf("done reading from `cmd` pipe, closing it\n");
5505 /* We need to extract exitcode. Test case
5506 * "true; echo `sleep 1; false` $?"
5508 safe_waitpid(pid, &status, 0);
5509 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5510 return WEXITSTATUS(status);
5512 #endif /* ENABLE_HUSH_TICK */
5515 static void setup_heredoc(struct redir_struct *redir)
5517 struct fd_pair pair;
5520 /* the _body_ of heredoc (misleading field name) */
5521 const char *heredoc = redir->rd_filename;
5528 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5529 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5533 len = strlen(heredoc);
5535 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5537 xmove_fd(pair.rd, redir->rd_fd);
5539 /* Try writing without forking. Newer kernels have
5540 * dynamically growing pipes. Must use non-blocking write! */
5543 written = write(pair.wr, heredoc, len);
5554 ndelay_off(pair.wr);
5556 /* Okay, pipe buffer was not big enough */
5557 /* Note: we must not create a stray child (bastard? :)
5558 * for the unsuspecting parent process. Child creates a grandchild
5559 * and exits before parent execs the process which consumes heredoc
5560 * (that exec happens after we return from this function) */
5567 disable_restore_tty_pgrp_on_exit();
5568 pid = BB_MMU ? xfork() : xvfork();
5572 close(redir->rd_fd); /* read side of the pipe */
5574 full_write(pair.wr, heredoc, len); /* may loop or block */
5577 /* Delegate blocking writes to another process */
5578 xmove_fd(pair.wr, STDOUT_FILENO);
5579 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5583 #if ENABLE_HUSH_FAST
5585 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5587 enable_restore_tty_pgrp_on_exit();
5593 wait(NULL); /* wait till child has died */
5596 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5597 * and stderr if they are redirected. */
5598 static int setup_redirects(struct command *prog, int squirrel[])
5601 struct redir_struct *redir;
5603 for (redir = prog->redirects; redir; redir = redir->next) {
5604 if (redir->rd_type == REDIRECT_HEREDOC2) {
5605 /* rd_fd<<HERE case */
5606 if (squirrel && redir->rd_fd < 3
5607 && squirrel[redir->rd_fd] < 0
5609 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5611 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5613 debug_printf_parse("set heredoc '%s'\n",
5614 redir->rd_filename);
5615 setup_heredoc(redir);
5619 if (redir->rd_dup == REDIRFD_TO_FILE) {
5620 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5622 if (redir->rd_filename == NULL) {
5623 /* Something went wrong in the parse.
5624 * Pretend it didn't happen */
5625 bb_error_msg("bug in redirect parse");
5628 mode = redir_table[redir->rd_type].mode;
5629 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5630 openfd = open_or_warn(p, mode);
5633 /* this could get lost if stderr has been redirected, but
5634 * bash and ash both lose it as well (though zsh doesn't!) */
5635 //what the above comment tries to say?
5639 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5640 openfd = redir->rd_dup;
5643 if (openfd != redir->rd_fd) {
5644 if (squirrel && redir->rd_fd < 3
5645 && squirrel[redir->rd_fd] < 0
5647 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5649 if (openfd == REDIRFD_CLOSE) {
5650 /* "n>-" means "close me" */
5651 close(redir->rd_fd);
5653 xdup2(openfd, redir->rd_fd);
5654 if (redir->rd_dup == REDIRFD_TO_FILE)
5662 static void restore_redirects(int squirrel[])
5665 for (i = 0; i < 3; i++) {
5668 /* We simply die on error */
5674 static char *find_in_path(const char *arg)
5677 const char *PATH = get_local_var_value("PATH");
5683 const char *end = strchrnul(PATH, ':');
5684 int sz = end - PATH; /* must be int! */
5688 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5690 /* We have xxx::yyyy in $PATH,
5691 * it means "use current dir" */
5694 if (access(ret, F_OK) == 0)
5707 static const struct built_in_command *find_builtin_helper(const char *name,
5708 const struct built_in_command *x,
5709 const struct built_in_command *end)
5712 if (strcmp(name, x->b_cmd) != 0) {
5716 debug_printf_exec("found builtin '%s'\n", name);
5721 static const struct built_in_command *find_builtin1(const char *name)
5723 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5725 static const struct built_in_command *find_builtin(const char *name)
5727 const struct built_in_command *x = find_builtin1(name);
5730 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5733 #if ENABLE_HUSH_FUNCTIONS
5734 static struct function **find_function_slot(const char *name)
5736 struct function **funcpp = &G.top_func;
5738 if (strcmp(name, (*funcpp)->name) == 0) {
5741 funcpp = &(*funcpp)->next;
5746 static const struct function *find_function(const char *name)
5748 const struct function *funcp = *find_function_slot(name);
5750 debug_printf_exec("found function '%s'\n", name);
5754 /* Note: takes ownership on name ptr */
5755 static struct function *new_function(char *name)
5757 struct function **funcpp = find_function_slot(name);
5758 struct function *funcp = *funcpp;
5760 if (funcp != NULL) {
5761 struct command *cmd = funcp->parent_cmd;
5762 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5764 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5766 /* Note: if !funcp->body, do not free body_as_string!
5767 * This is a special case of "-F name body" function:
5768 * body_as_string was not malloced! */
5770 free_pipe_list(funcp->body);
5772 free(funcp->body_as_string);
5776 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5777 cmd->argv[0] = funcp->name;
5778 cmd->group = funcp->body;
5780 cmd->group_as_string = funcp->body_as_string;
5784 debug_printf_exec("remembering new function '%s'\n", name);
5785 funcp = *funcpp = xzalloc(sizeof(*funcp));
5786 /*funcp->next = NULL;*/
5793 static void unset_func(const char *name)
5795 struct function **funcpp = find_function_slot(name);
5796 struct function *funcp = *funcpp;
5798 if (funcp != NULL) {
5799 debug_printf_exec("freeing function '%s'\n", funcp->name);
5800 *funcpp = funcp->next;
5801 /* funcp is unlinked now, deleting it.
5802 * Note: if !funcp->body, the function was created by
5803 * "-F name body", do not free ->body_as_string
5804 * and ->name as they were not malloced. */
5806 free_pipe_list(funcp->body);
5809 free(funcp->body_as_string);
5817 #define exec_function(to_free, funcp, argv) \
5818 exec_function(funcp, argv)
5820 static void exec_function(char ***to_free,
5821 const struct function *funcp,
5822 char **argv) NORETURN;
5823 static void exec_function(char ***to_free,
5824 const struct function *funcp,
5830 argv[0] = G.global_argv[0];
5831 G.global_argv = argv;
5835 /* On MMU, funcp->body is always non-NULL */
5836 n = run_list(funcp->body);
5840 re_execute_shell(to_free,
5841 funcp->body_as_string,
5848 static int run_function(const struct function *funcp, char **argv)
5854 save_and_replace_G_args(&sv, argv);
5856 /* "we are in function, ok to use return" */
5857 sv_flg = G.flag_return_in_progress;
5858 G.flag_return_in_progress = -1;
5859 # if ENABLE_HUSH_LOCAL
5860 G.func_nest_level++;
5863 /* On MMU, funcp->body is always non-NULL */
5866 /* Function defined by -F */
5867 parse_and_run_string(funcp->body_as_string);
5868 rc = G.last_exitcode;
5872 rc = run_list(funcp->body);
5875 # if ENABLE_HUSH_LOCAL
5877 struct variable *var;
5878 struct variable **var_pp;
5880 var_pp = &G.top_var;
5881 while ((var = *var_pp) != NULL) {
5882 if (var->func_nest_level < G.func_nest_level) {
5883 var_pp = &var->next;
5887 if (var->flg_export)
5888 bb_unsetenv(var->varstr);
5889 /* Remove from global list */
5890 *var_pp = var->next;
5896 G.func_nest_level--;
5899 G.flag_return_in_progress = sv_flg;
5901 restore_G_args(&sv, argv);
5905 #endif /* ENABLE_HUSH_FUNCTIONS */
5909 #define exec_builtin(to_free, x, argv) \
5910 exec_builtin(x, argv)
5912 #define exec_builtin(to_free, x, argv) \
5913 exec_builtin(to_free, argv)
5915 static void exec_builtin(char ***to_free,
5916 const struct built_in_command *x,
5917 char **argv) NORETURN;
5918 static void exec_builtin(char ***to_free,
5919 const struct built_in_command *x,
5923 int rcode = x->b_function(argv);
5927 /* On NOMMU, we must never block!
5928 * Example: { sleep 99 | read line; } & echo Ok
5930 re_execute_shell(to_free,
5939 static void execvp_or_die(char **argv) NORETURN;
5940 static void execvp_or_die(char **argv)
5942 debug_printf_exec("execing '%s'\n", argv[0]);
5943 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5944 execvp(argv[0], argv);
5945 bb_perror_msg("can't execute '%s'", argv[0]);
5946 _exit(127); /* bash compat */
5949 #if ENABLE_HUSH_MODE_X
5950 static void dump_cmd_in_x_mode(char **argv)
5952 if (G_x_mode && argv) {
5953 /* We want to output the line in one write op */
5961 len += strlen(argv[n++]) + 1;
5967 p += sprintf(p, " %s", argv[n++]);
5975 # define dump_cmd_in_x_mode(argv) ((void)0)
5979 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
5980 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
5981 #define pseudo_exec(nommu_save, command, argv_expanded) \
5982 pseudo_exec(command, argv_expanded)
5985 /* Called after [v]fork() in run_pipe, or from builtin_exec.
5987 * Don't exit() here. If you don't exec, use _exit instead.
5988 * The at_exit handlers apparently confuse the calling process,
5989 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
5990 static void pseudo_exec_argv(nommu_save_t *nommu_save,
5991 char **argv, int assignment_cnt,
5992 char **argv_expanded) NORETURN;
5993 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
5994 char **argv, int assignment_cnt,
5995 char **argv_expanded)
5999 new_env = expand_assignments(argv, assignment_cnt);
6000 dump_cmd_in_x_mode(new_env);
6002 if (!argv[assignment_cnt]) {
6003 /* Case when we are here: ... | var=val | ...
6004 * (note that we do not exit early, i.e., do not optimize out
6005 * expand_assignments(): think about ... | var=`sleep 1` | ...
6007 free_strings(new_env);
6008 _exit(EXIT_SUCCESS);
6012 set_vars_and_save_old(new_env);
6013 free(new_env); /* optional */
6014 /* we can also destroy set_vars_and_save_old's return value,
6017 nommu_save->new_env = new_env;
6018 nommu_save->old_vars = set_vars_and_save_old(new_env);
6021 if (argv_expanded) {
6022 argv = argv_expanded;
6024 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6026 nommu_save->argv = argv;
6029 dump_cmd_in_x_mode(argv);
6031 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6032 if (strchr(argv[0], '/') != NULL)
6036 /* Check if the command matches any of the builtins.
6037 * Depending on context, this might be redundant. But it's
6038 * easier to waste a few CPU cycles than it is to figure out
6039 * if this is one of those cases.
6042 /* On NOMMU, it is more expensive to re-execute shell
6043 * just in order to run echo or test builtin.
6044 * It's better to skip it here and run corresponding
6045 * non-builtin later. */
6046 const struct built_in_command *x;
6047 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6049 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6052 #if ENABLE_HUSH_FUNCTIONS
6053 /* Check if the command matches any functions */
6055 const struct function *funcp = find_function(argv[0]);
6057 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6062 #if ENABLE_FEATURE_SH_STANDALONE
6063 /* Check if the command matches any busybox applets */
6065 int a = find_applet_by_name(argv[0]);
6067 # if BB_MMU /* see above why on NOMMU it is not allowed */
6068 if (APPLET_IS_NOEXEC(a)) {
6069 debug_printf_exec("running applet '%s'\n", argv[0]);
6070 run_applet_no_and_exit(a, argv);
6073 /* Re-exec ourselves */
6074 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6075 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6076 execv(bb_busybox_exec_path, argv);
6077 /* If they called chroot or otherwise made the binary no longer
6078 * executable, fall through */
6083 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6086 execvp_or_die(argv);
6089 /* Called after [v]fork() in run_pipe
6091 static void pseudo_exec(nommu_save_t *nommu_save,
6092 struct command *command,
6093 char **argv_expanded) NORETURN;
6094 static void pseudo_exec(nommu_save_t *nommu_save,
6095 struct command *command,
6096 char **argv_expanded)
6098 if (command->argv) {
6099 pseudo_exec_argv(nommu_save, command->argv,
6100 command->assignment_cnt, argv_expanded);
6103 if (command->group) {
6104 /* Cases when we are here:
6107 * ... | ( list ) | ...
6108 * ... | { list } | ...
6112 debug_printf_exec("pseudo_exec: run_list\n");
6113 reset_traps_to_defaults();
6114 rcode = run_list(command->group);
6115 /* OK to leak memory by not calling free_pipe_list,
6116 * since this process is about to exit */
6119 re_execute_shell(&nommu_save->argv_from_re_execing,
6120 command->group_as_string,
6127 /* Case when we are here: ... | >file */
6128 debug_printf_exec("pseudo_exec'ed null command\n");
6129 _exit(EXIT_SUCCESS);
6133 static const char *get_cmdtext(struct pipe *pi)
6139 /* This is subtle. ->cmdtext is created only on first backgrounding.
6140 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6141 * On subsequent bg argv is trashed, but we won't use it */
6144 argv = pi->cmds[0].argv;
6145 if (!argv || !argv[0]) {
6146 pi->cmdtext = xzalloc(1);
6152 len += strlen(*argv) + 1;
6156 argv = pi->cmds[0].argv;
6158 len = strlen(*argv);
6159 memcpy(p, *argv, len);
6167 static void insert_bg_job(struct pipe *pi)
6169 struct pipe *job, **jobp;
6172 /* Linear search for the ID of the job to use */
6174 for (job = G.job_list; job; job = job->next)
6175 if (job->jobid >= pi->jobid)
6176 pi->jobid = job->jobid + 1;
6178 /* Add job to the list of running jobs */
6180 while ((job = *jobp) != NULL)
6182 job = *jobp = xmalloc(sizeof(*job));
6184 *job = *pi; /* physical copy */
6186 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6187 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6188 for (i = 0; i < pi->num_cmds; i++) {
6189 job->cmds[i].pid = pi->cmds[i].pid;
6190 /* all other fields are not used and stay zero */
6192 job->cmdtext = xstrdup(get_cmdtext(pi));
6194 if (G_interactive_fd)
6195 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6196 G.last_jobid = job->jobid;
6199 static void remove_bg_job(struct pipe *pi)
6201 struct pipe *prev_pipe;
6203 if (pi == G.job_list) {
6204 G.job_list = pi->next;
6206 prev_pipe = G.job_list;
6207 while (prev_pipe->next != pi)
6208 prev_pipe = prev_pipe->next;
6209 prev_pipe->next = pi->next;
6212 G.last_jobid = G.job_list->jobid;
6217 /* Remove a backgrounded job */
6218 static void delete_finished_bg_job(struct pipe *pi)
6225 /* Check to see if any processes have exited -- if they
6226 * have, figure out why and see if a job has completed */
6227 static int checkjobs(struct pipe *fg_pipe)
6237 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6239 attributes = WUNTRACED;
6240 if (fg_pipe == NULL)
6241 attributes |= WNOHANG;
6244 #if ENABLE_HUSH_FAST
6245 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6246 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6247 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6248 /* There was neither fork nor SIGCHLD since last waitpid */
6249 /* Avoid doing waitpid syscall if possible */
6250 if (!G.we_have_children) {
6254 if (fg_pipe == NULL) { /* is WNOHANG set? */
6255 /* We have children, but they did not exit
6256 * or stop yet (we saw no SIGCHLD) */
6259 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6263 /* Do we do this right?
6264 * bash-3.00# sleep 20 | false
6266 * [3]+ Stopped sleep 20 | false
6267 * bash-3.00# echo $?
6268 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6269 * [hush 1.14.0: yes we do it right]
6276 #if ENABLE_HUSH_FAST
6277 i = G.count_SIGCHLD;
6279 childpid = waitpid(-1, &status, attributes);
6280 if (childpid <= 0) {
6281 if (childpid && errno != ECHILD)
6282 bb_perror_msg("waitpid");
6283 #if ENABLE_HUSH_FAST
6284 else { /* Until next SIGCHLD, waitpid's are useless */
6285 G.we_have_children = (childpid == 0);
6286 G.handled_SIGCHLD = i;
6287 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6292 dead = WIFEXITED(status) || WIFSIGNALED(status);
6295 if (WIFSTOPPED(status))
6296 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6297 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6298 if (WIFSIGNALED(status))
6299 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6300 childpid, WTERMSIG(status), WEXITSTATUS(status));
6301 if (WIFEXITED(status))
6302 debug_printf_jobs("pid %d exited, exitcode %d\n",
6303 childpid, WEXITSTATUS(status));
6305 /* Were we asked to wait for fg pipe? */
6307 for (i = 0; i < fg_pipe->num_cmds; i++) {
6308 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6309 if (fg_pipe->cmds[i].pid != childpid)
6312 fg_pipe->cmds[i].pid = 0;
6313 fg_pipe->alive_cmds--;
6314 if (i == fg_pipe->num_cmds - 1) {
6315 /* last process gives overall exitstatus */
6316 rcode = WEXITSTATUS(status);
6317 /* bash prints killer signal's name for *last*
6318 * process in pipe (prints just newline for SIGINT).
6319 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6321 if (WIFSIGNALED(status)) {
6322 int sig = WTERMSIG(status);
6323 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
6324 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6325 * Maybe we need to use sig | 128? */
6328 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6331 fg_pipe->cmds[i].is_stopped = 1;
6332 fg_pipe->stopped_cmds++;
6334 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6335 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6336 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
6337 /* All processes in fg pipe have exited or stopped */
6338 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6339 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6340 * and "killall -STOP cat" */
6341 if (G_interactive_fd) {
6343 if (fg_pipe->alive_cmds)
6344 insert_bg_job(fg_pipe);
6348 if (!fg_pipe->alive_cmds)
6351 /* There are still running processes in the fg pipe */
6352 goto wait_more; /* do waitpid again */
6354 /* it wasnt fg_pipe, look for process in bg pipes */
6358 /* We asked to wait for bg or orphaned children */
6359 /* No need to remember exitcode in this case */
6360 for (pi = G.job_list; pi; pi = pi->next) {
6361 for (i = 0; i < pi->num_cmds; i++) {
6362 if (pi->cmds[i].pid == childpid)
6363 goto found_pi_and_prognum;
6366 /* Happens when shell is used as init process (init=/bin/sh) */
6367 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6368 continue; /* do waitpid again */
6370 found_pi_and_prognum:
6373 pi->cmds[i].pid = 0;
6375 if (!pi->alive_cmds) {
6376 if (G_interactive_fd)
6377 printf(JOB_STATUS_FORMAT, pi->jobid,
6378 "Done", pi->cmdtext);
6379 delete_finished_bg_job(pi);
6383 pi->cmds[i].is_stopped = 1;
6387 } /* while (waitpid succeeds)... */
6393 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6396 int rcode = checkjobs(fg_pipe);
6397 if (G_saved_tty_pgrp) {
6398 /* Job finished, move the shell to the foreground */
6399 p = getpgrp(); /* our process group id */
6400 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6401 tcsetpgrp(G_interactive_fd, p);
6407 /* Start all the jobs, but don't wait for anything to finish.
6410 * Return code is normally -1, when the caller has to wait for children
6411 * to finish to determine the exit status of the pipe. If the pipe
6412 * is a simple builtin command, however, the action is done by the
6413 * time run_pipe returns, and the exit code is provided as the
6416 * Returns -1 only if started some children. IOW: we have to
6417 * mask out retvals of builtins etc with 0xff!
6419 * The only case when we do not need to [v]fork is when the pipe
6420 * is single, non-backgrounded, non-subshell command. Examples:
6421 * cmd ; ... { list } ; ...
6422 * cmd && ... { list } && ...
6423 * cmd || ... { list } || ...
6424 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6425 * or (if SH_STANDALONE) an applet, and we can run the { list }
6426 * with run_list. If it isn't one of these, we fork and exec cmd.
6428 * Cases when we must fork:
6429 * non-single: cmd | cmd
6430 * backgrounded: cmd & { list } &
6431 * subshell: ( list ) [&]
6433 #if !ENABLE_HUSH_MODE_X
6434 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
6435 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6437 static int redirect_and_varexp_helper(char ***new_env_p,
6438 struct variable **old_vars_p,
6439 struct command *command,
6441 char **argv_expanded)
6443 /* setup_redirects acts on file descriptors, not FILEs.
6444 * This is perfect for work that comes after exec().
6445 * Is it really safe for inline use? Experimentally,
6446 * things seem to work. */
6447 int rcode = setup_redirects(command, squirrel);
6449 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6450 *new_env_p = new_env;
6451 dump_cmd_in_x_mode(new_env);
6452 dump_cmd_in_x_mode(argv_expanded);
6454 *old_vars_p = set_vars_and_save_old(new_env);
6458 static NOINLINE int run_pipe(struct pipe *pi)
6460 static const char *const null_ptr = NULL;
6464 struct command *command;
6465 char **argv_expanded;
6467 /* it is not always needed, but we aim to smaller code */
6468 int squirrel[] = { -1, -1, -1 };
6471 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6474 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6475 * Result should be 3 lines: q w e, qwe, q w e
6477 G.ifs = get_local_var_value("IFS");
6481 IF_HUSH_JOB(pi->pgrp = -1;)
6482 pi->stopped_cmds = 0;
6483 command = &pi->cmds[0];
6484 argv_expanded = NULL;
6486 if (pi->num_cmds != 1
6487 || pi->followup == PIPE_BG
6488 || command->cmd_type == CMD_SUBSHELL
6495 debug_printf_exec(": group:%p argv:'%s'\n",
6496 command->group, command->argv ? command->argv[0] : "NONE");
6498 if (command->group) {
6499 #if ENABLE_HUSH_FUNCTIONS
6500 if (command->cmd_type == CMD_FUNCDEF) {
6501 /* "executing" func () { list } */
6502 struct function *funcp;
6504 funcp = new_function(command->argv[0]);
6505 /* funcp->name is already set to argv[0] */
6506 funcp->body = command->group;
6508 funcp->body_as_string = command->group_as_string;
6509 command->group_as_string = NULL;
6511 command->group = NULL;
6512 command->argv[0] = NULL;
6513 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6514 funcp->parent_cmd = command;
6515 command->child_func = funcp;
6517 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6519 return EXIT_SUCCESS;
6523 debug_printf("non-subshell group\n");
6524 rcode = 1; /* exitcode if redir failed */
6525 if (setup_redirects(command, squirrel) == 0) {
6526 debug_printf_exec(": run_list\n");
6527 rcode = run_list(command->group) & 0xff;
6529 restore_redirects(squirrel);
6530 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6532 debug_printf_exec("run_pipe: return %d\n", rcode);
6536 argv = command->argv ? command->argv : (char **) &null_ptr;
6538 const struct built_in_command *x;
6539 #if ENABLE_HUSH_FUNCTIONS
6540 const struct function *funcp;
6544 char **new_env = NULL;
6545 struct variable *old_vars = NULL;
6547 if (argv[command->assignment_cnt] == NULL) {
6548 /* Assignments, but no command */
6549 /* Ensure redirects take effect (that is, create files).
6550 * Try "a=t >file" */
6551 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6552 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6553 /* Set shell variables */
6557 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6558 /* Do we need to flag set_local_var() errors?
6559 * "assignment to readonly var" and "putenv error"
6564 /* Redirect error sets $? to 1. Otherwise,
6565 * if evaluating assignment value set $?, retain it.
6566 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6568 rcode = G.last_exitcode;
6569 /* Exit, _skipping_ variable restoring code: */
6570 goto clean_up_and_ret0;
6572 #else /* Older, bigger, but more correct code */
6574 rcode = setup_redirects(command, squirrel);
6575 restore_redirects(squirrel);
6576 /* Set shell variables */
6578 bb_putchar_stderr('+');
6580 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6582 fprintf(stderr, " %s", p);
6583 debug_printf_exec("set shell var:'%s'->'%s'\n",
6585 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6586 /* Do we need to flag set_local_var() errors?
6587 * "assignment to readonly var" and "putenv error"
6592 bb_putchar_stderr('\n');
6593 /* Redirect error sets $? to 1. Otherwise,
6594 * if evaluating assignment value set $?, retain it.
6595 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6597 rcode = G.last_exitcode;
6598 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6600 debug_printf_exec("run_pipe: return %d\n", rcode);
6605 /* Expand the rest into (possibly) many strings each */
6607 #if ENABLE_HUSH_BASH_COMPAT
6608 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6609 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6613 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6616 /* if someone gives us an empty string: `cmd with empty output` */
6617 if (!argv_expanded[0]) {
6618 free(argv_expanded);
6620 return G.last_exitcode;
6623 x = find_builtin(argv_expanded[0]);
6624 #if ENABLE_HUSH_FUNCTIONS
6627 funcp = find_function(argv_expanded[0]);
6631 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6632 debug_printf("exec with redirects only\n");
6633 rcode = setup_redirects(command, NULL);
6634 goto clean_up_and_ret1;
6637 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6640 debug_printf_exec(": builtin '%s' '%s'...\n",
6641 x->b_cmd, argv_expanded[1]);
6642 rcode = x->b_function(argv_expanded) & 0xff;
6645 #if ENABLE_HUSH_FUNCTIONS
6647 # if ENABLE_HUSH_LOCAL
6648 struct variable **sv;
6649 sv = G.shadowed_vars_pp;
6650 G.shadowed_vars_pp = &old_vars;
6652 debug_printf_exec(": function '%s' '%s'...\n",
6653 funcp->name, argv_expanded[1]);
6654 rcode = run_function(funcp, argv_expanded) & 0xff;
6655 # if ENABLE_HUSH_LOCAL
6656 G.shadowed_vars_pp = sv;
6662 unset_vars(new_env);
6664 /* clean_up_and_ret0: */
6665 restore_redirects(squirrel);
6667 free(argv_expanded);
6668 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6670 debug_printf_exec("run_pipe return %d\n", rcode);
6674 if (ENABLE_FEATURE_SH_STANDALONE) {
6675 int n = find_applet_by_name(argv_expanded[0]);
6676 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6677 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6679 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6680 argv_expanded[0], argv_expanded[1]);
6681 rcode = run_nofork_applet(n, argv_expanded);
6683 goto clean_up_and_ret;
6686 /* It is neither builtin nor applet. We must fork. */
6690 /* NB: argv_expanded may already be created, and that
6691 * might include `cmd` runs! Do not rerun it! We *must*
6692 * use argv_expanded if it's non-NULL */
6694 /* Going to fork a child per each pipe member */
6699 while (cmd_no < pi->num_cmds) {
6700 struct fd_pair pipefds;
6702 volatile nommu_save_t nommu_save;
6703 nommu_save.new_env = NULL;
6704 nommu_save.old_vars = NULL;
6705 nommu_save.argv = NULL;
6706 nommu_save.argv_from_re_execing = NULL;
6708 command = &pi->cmds[cmd_no];
6710 if (command->argv) {
6711 debug_printf_exec(": pipe member '%s' '%s'...\n",
6712 command->argv[0], command->argv[1]);
6714 debug_printf_exec(": pipe member with no argv\n");
6717 /* pipes are inserted between pairs of commands */
6720 if (cmd_no < pi->num_cmds)
6721 xpiped_pair(pipefds);
6723 command->pid = BB_MMU ? fork() : vfork();
6724 if (!command->pid) { /* child */
6726 disable_restore_tty_pgrp_on_exit();
6727 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6729 /* Every child adds itself to new process group
6730 * with pgid == pid_of_first_child_in_pipe */
6731 if (G.run_list_level == 1 && G_interactive_fd) {
6734 if (pgrp < 0) /* true for 1st process only */
6736 if (setpgid(0, pgrp) == 0
6737 && pi->followup != PIPE_BG
6738 && G_saved_tty_pgrp /* we have ctty */
6740 /* We do it in *every* child, not just first,
6742 tcsetpgrp(G_interactive_fd, pgrp);
6746 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6747 /* 1st cmd in backgrounded pipe
6748 * should have its stdin /dev/null'ed */
6750 if (open(bb_dev_null, O_RDONLY))
6751 xopen("/", O_RDONLY);
6753 xmove_fd(next_infd, 0);
6755 xmove_fd(pipefds.wr, 1);
6758 /* Like bash, explicit redirects override pipes,
6759 * and the pipe fd is available for dup'ing. */
6760 if (setup_redirects(command, NULL))
6763 /* Restore default handlers just prior to exec */
6764 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6766 /* Stores to nommu_save list of env vars putenv'ed
6767 * (NOMMU, on MMU we don't need that) */
6768 /* cast away volatility... */
6769 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6770 /* pseudo_exec() does not return */
6773 /* parent or error */
6774 #if ENABLE_HUSH_FAST
6776 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6778 enable_restore_tty_pgrp_on_exit();
6780 /* Clean up after vforked child */
6781 free(nommu_save.argv);
6782 free(nommu_save.argv_from_re_execing);
6783 unset_vars(nommu_save.new_env);
6784 add_vars(nommu_save.old_vars);
6786 free(argv_expanded);
6787 argv_expanded = NULL;
6788 if (command->pid < 0) { /* [v]fork failed */
6789 /* Clearly indicate, was it fork or vfork */
6790 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6794 /* Second and next children need to know pid of first one */
6796 pi->pgrp = command->pid;
6802 if (cmd_no < pi->num_cmds)
6804 /* Pass read (output) pipe end to next iteration */
6805 next_infd = pipefds.rd;
6808 if (!pi->alive_cmds) {
6810 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6815 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6819 #ifndef debug_print_tree
6820 static void debug_print_tree(struct pipe *pi, int lvl)
6822 static const char *const PIPE[] = {
6828 static const char *RES[] = {
6829 [RES_NONE ] = "NONE" ,
6832 [RES_THEN ] = "THEN" ,
6833 [RES_ELIF ] = "ELIF" ,
6834 [RES_ELSE ] = "ELSE" ,
6837 # if ENABLE_HUSH_LOOPS
6838 [RES_FOR ] = "FOR" ,
6839 [RES_WHILE] = "WHILE",
6840 [RES_UNTIL] = "UNTIL",
6842 [RES_DONE ] = "DONE" ,
6844 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
6847 # if ENABLE_HUSH_CASE
6848 [RES_CASE ] = "CASE" ,
6849 [RES_CASE_IN ] = "CASE_IN" ,
6850 [RES_MATCH] = "MATCH",
6851 [RES_CASE_BODY] = "CASE_BODY",
6852 [RES_ESAC ] = "ESAC" ,
6854 [RES_XXXX ] = "XXXX" ,
6855 [RES_SNTX ] = "SNTX" ,
6857 static const char *const CMDTYPE[] = {
6861 # if ENABLE_HUSH_FUNCTIONS
6870 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
6871 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
6873 while (prn < pi->num_cmds) {
6874 struct command *command = &pi->cmds[prn];
6875 char **argv = command->argv;
6877 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
6879 command->assignment_cnt);
6880 if (command->group) {
6881 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
6882 CMDTYPE[command->cmd_type],
6885 , " group_as_string:", command->group_as_string
6890 debug_print_tree(command->group, lvl+1);
6894 if (argv) while (*argv) {
6895 fprintf(stderr, " '%s'", *argv);
6898 fprintf(stderr, "\n");
6905 #endif /* debug_print_tree */
6907 /* NB: called by pseudo_exec, and therefore must not modify any
6908 * global data until exec/_exit (we can be a child after vfork!) */
6909 static int run_list(struct pipe *pi)
6911 #if ENABLE_HUSH_CASE
6912 char *case_word = NULL;
6914 #if ENABLE_HUSH_LOOPS
6915 struct pipe *loop_top = NULL;
6916 char **for_lcur = NULL;
6917 char **for_list = NULL;
6919 smallint last_followup;
6921 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6922 smalluint cond_code = 0;
6924 enum { cond_code = 0 };
6927 smallint rword; /* RES_foo */
6928 smallint last_rword; /* ditto */
6931 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
6934 #if ENABLE_HUSH_LOOPS
6935 /* Check syntax for "for" */
6936 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
6937 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
6939 /* current word is FOR or IN (BOLD in comments below) */
6940 if (cpipe->next == NULL) {
6941 syntax_error("malformed for");
6943 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6946 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
6947 if (cpipe->next->res_word == RES_DO)
6949 /* next word is not "do". It must be "in" then ("FOR v in ...") */
6950 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
6951 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
6953 syntax_error("malformed for");
6955 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
6961 /* Past this point, all code paths should jump to ret: label
6962 * in order to return, no direct "return" statements please.
6963 * This helps to ensure that no memory is leaked. */
6971 last_rword = RES_XXXX;
6973 last_followup = PIPE_SEQ;
6974 rcode = G.last_exitcode;
6976 /* Go through list of pipes, (maybe) executing them. */
6977 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
6981 IF_HAS_KEYWORDS(rword = pi->res_word;)
6982 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
6983 rword, cond_code, last_rword);
6984 #if ENABLE_HUSH_LOOPS
6985 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
6986 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
6988 /* start of a loop: remember where loop starts */
6993 /* Still in the same "if...", "then..." or "do..." branch? */
6994 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
6995 if ((rcode == 0 && last_followup == PIPE_OR)
6996 || (rcode != 0 && last_followup == PIPE_AND)
6998 /* It is "<true> || CMD" or "<false> && CMD"
6999 * and we should not execute CMD */
7000 debug_printf_exec("skipped cmd because of || or &&\n");
7001 last_followup = pi->followup;
7005 last_followup = pi->followup;
7006 IF_HAS_KEYWORDS(last_rword = rword;)
7009 if (rword == RES_THEN) {
7010 /* if false; then ... fi has exitcode 0! */
7011 G.last_exitcode = rcode = EXIT_SUCCESS;
7012 /* "if <false> THEN cmd": skip cmd */
7016 if (rword == RES_ELSE || rword == RES_ELIF) {
7017 /* "if <true> then ... ELSE/ELIF cmd":
7018 * skip cmd and all following ones */
7023 #if ENABLE_HUSH_LOOPS
7024 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7026 /* first loop through for */
7028 static const char encoded_dollar_at[] ALIGN1 = {
7029 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7030 }; /* encoded representation of "$@" */
7031 static const char *const encoded_dollar_at_argv[] = {
7032 encoded_dollar_at, NULL
7033 }; /* argv list with one element: "$@" */
7036 vals = (char**)encoded_dollar_at_argv;
7037 if (pi->next->res_word == RES_IN) {
7038 /* if no variable values after "in" we skip "for" */
7039 if (!pi->next->cmds[0].argv) {
7040 G.last_exitcode = rcode = EXIT_SUCCESS;
7041 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7044 vals = pi->next->cmds[0].argv;
7045 } /* else: "for var; do..." -> assume "$@" list */
7046 /* create list of variable values */
7047 debug_print_strings("for_list made from", vals);
7048 for_list = expand_strvec_to_strvec(vals);
7049 for_lcur = for_list;
7050 debug_print_strings("for_list", for_list);
7053 /* "for" loop is over, clean up */
7059 /* Insert next value from for_lcur */
7060 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7061 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7064 if (rword == RES_IN) {
7065 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7067 if (rword == RES_DONE) {
7068 continue; /* "done" has no cmds too */
7071 #if ENABLE_HUSH_CASE
7072 if (rword == RES_CASE) {
7073 case_word = expand_strvec_to_string(pi->cmds->argv);
7076 if (rword == RES_MATCH) {
7079 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7081 /* all prev words didn't match, does this one match? */
7082 argv = pi->cmds->argv;
7084 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7085 /* TODO: which FNM_xxx flags to use? */
7086 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7088 if (cond_code == 0) { /* match! we will execute this branch */
7089 free(case_word); /* make future "word)" stop */
7097 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7099 continue; /* not matched yet, skip this pipe */
7102 /* Just pressing <enter> in shell should check for jobs.
7103 * OTOH, in non-interactive shell this is useless
7104 * and only leads to extra job checks */
7105 if (pi->num_cmds == 0) {
7106 if (G_interactive_fd)
7107 goto check_jobs_and_continue;
7111 /* After analyzing all keywords and conditions, we decided
7112 * to execute this pipe. NB: have to do checkjobs(NULL)
7113 * after run_pipe to collect any background children,
7114 * even if list execution is to be stopped. */
7115 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7118 #if ENABLE_HUSH_LOOPS
7119 G.flag_break_continue = 0;
7121 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7123 /* We ran a builtin, function, or group.
7124 * rcode is already known
7125 * and we don't need to wait for anything. */
7126 G.last_exitcode = rcode;
7127 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7128 check_and_run_traps(0);
7129 #if ENABLE_HUSH_LOOPS
7130 /* Was it "break" or "continue"? */
7131 if (G.flag_break_continue) {
7132 smallint fbc = G.flag_break_continue;
7133 /* We might fall into outer *loop*,
7134 * don't want to break it too */
7136 G.depth_break_continue--;
7137 if (G.depth_break_continue == 0)
7138 G.flag_break_continue = 0;
7139 /* else: e.g. "continue 2" should *break* once, *then* continue */
7140 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7141 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7142 goto check_jobs_and_break;
7143 /* "continue": simulate end of loop */
7148 #if ENABLE_HUSH_FUNCTIONS
7149 if (G.flag_return_in_progress == 1) {
7150 /* same as "goto check_jobs_and_break" */
7155 } else if (pi->followup == PIPE_BG) {
7156 /* What does bash do with attempts to background builtins? */
7157 /* even bash 3.2 doesn't do that well with nested bg:
7158 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7159 * I'm NOT treating inner &'s as jobs */
7160 check_and_run_traps(0);
7162 if (G.run_list_level == 1)
7165 /* Last command's pid goes to $! */
7166 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7167 G.last_exitcode = rcode = EXIT_SUCCESS;
7168 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7171 if (G.run_list_level == 1 && G_interactive_fd) {
7172 /* Waits for completion, then fg's main shell */
7173 rcode = checkjobs_and_fg_shell(pi);
7174 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7175 check_and_run_traps(0);
7178 { /* This one just waits for completion */
7179 rcode = checkjobs(pi);
7180 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7181 check_and_run_traps(0);
7183 G.last_exitcode = rcode;
7187 /* Analyze how result affects subsequent commands */
7189 if (rword == RES_IF || rword == RES_ELIF)
7192 #if ENABLE_HUSH_LOOPS
7193 /* Beware of "while false; true; do ..."! */
7194 if (pi->next && pi->next->res_word == RES_DO) {
7195 if (rword == RES_WHILE) {
7197 /* "while false; do...done" - exitcode 0 */
7198 G.last_exitcode = rcode = EXIT_SUCCESS;
7199 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7200 goto check_jobs_and_break;
7203 if (rword == RES_UNTIL) {
7205 debug_printf_exec(": until expr is true: breaking\n");
7206 check_jobs_and_break:
7214 check_jobs_and_continue:
7221 #if ENABLE_HUSH_LOOPS
7226 #if ENABLE_HUSH_CASE
7230 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7234 /* Select which version we will use */
7235 static int run_and_free_list(struct pipe *pi)
7238 debug_printf_exec("run_and_free_list entered\n");
7240 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7241 rcode = run_list(pi);
7243 /* free_pipe_list has the side effect of clearing memory.
7244 * In the long run that function can be merged with run_list,
7245 * but doing that now would hobble the debugging effort. */
7247 debug_printf_exec("run_and_free_list return %d\n", rcode);
7252 /* Called a few times only (or even once if "sh -c") */
7253 static void init_sigmasks(void)
7257 sigset_t old_blocked_set;
7259 if (!G.inherited_set_is_saved) {
7260 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7261 G.inherited_set = G.blocked_set;
7263 old_blocked_set = G.blocked_set;
7265 mask = (1 << SIGQUIT);
7266 if (G_interactive_fd) {
7267 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7268 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7269 mask |= SPECIAL_JOB_SIGS;
7271 G.non_DFL_mask = mask;
7276 sigaddset(&G.blocked_set, sig);
7280 sigdelset(&G.blocked_set, SIGCHLD);
7282 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7283 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7285 /* POSIX allows shell to re-enable SIGCHLD
7286 * even if it was SIG_IGN on entry */
7287 #if ENABLE_HUSH_FAST
7288 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7289 if (!G.inherited_set_is_saved)
7290 signal(SIGCHLD, SIGCHLD_handler);
7292 if (!G.inherited_set_is_saved)
7293 signal(SIGCHLD, SIG_DFL);
7296 G.inherited_set_is_saved = 1;
7301 static void maybe_set_to_sigexit(int sig)
7303 void (*handler)(int);
7304 /* non_DFL_mask'ed signals are, well, masked,
7305 * no need to set handler for them.
7307 if (!((G.non_DFL_mask >> sig) & 1)) {
7308 handler = signal(sig, sigexit);
7309 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7310 signal(sig, handler);
7313 /* Set handlers to restore tty pgrp and exit */
7314 static void set_fatal_handlers(void)
7316 /* We _must_ restore tty pgrp on fatal signals */
7318 maybe_set_to_sigexit(SIGILL );
7319 maybe_set_to_sigexit(SIGFPE );
7320 maybe_set_to_sigexit(SIGBUS );
7321 maybe_set_to_sigexit(SIGSEGV);
7322 maybe_set_to_sigexit(SIGTRAP);
7323 } /* else: hush is perfect. what SEGV? */
7324 maybe_set_to_sigexit(SIGABRT);
7325 /* bash 3.2 seems to handle these just like 'fatal' ones */
7326 maybe_set_to_sigexit(SIGPIPE);
7327 maybe_set_to_sigexit(SIGALRM);
7328 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7329 * if we aren't interactive... but in this case
7330 * we never want to restore pgrp on exit, and this fn is not called */
7331 /*maybe_set_to_sigexit(SIGHUP );*/
7332 /*maybe_set_to_sigexit(SIGTERM);*/
7333 /*maybe_set_to_sigexit(SIGINT );*/
7337 static int set_mode(const char cstate, const char mode)
7339 int state = (cstate == '-' ? 1 : 0);
7341 case 'n': G.n_mode = state; break;
7342 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
7343 default: return EXIT_FAILURE;
7345 return EXIT_SUCCESS;
7348 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7349 int hush_main(int argc, char **argv)
7352 unsigned builtin_argc;
7354 struct variable *cur_var;
7355 struct variable shell_ver;
7358 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7359 G.last_exitcode = EXIT_SUCCESS;
7361 G.argv0_for_re_execing = argv[0];
7363 /* Deal with HUSH_VERSION */
7364 memset(&shell_ver, 0, sizeof(shell_ver));
7365 shell_ver.flg_export = 1;
7366 shell_ver.flg_read_only = 1;
7367 /* Code which handles ${var<op>...} needs writable values for all variables,
7368 * therefore we xstrdup: */
7369 shell_ver.varstr = xstrdup(hush_version_str),
7370 G.top_var = &shell_ver;
7371 /* Create shell local variables from the values
7372 * currently living in the environment */
7373 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7374 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7375 cur_var = G.top_var;
7378 char *value = strchr(*e, '=');
7379 if (value) { /* paranoia */
7380 cur_var->next = xzalloc(sizeof(*cur_var));
7381 cur_var = cur_var->next;
7382 cur_var->varstr = *e;
7383 cur_var->max_len = strlen(*e);
7384 cur_var->flg_export = 1;
7388 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7389 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7390 putenv(shell_ver.varstr);
7393 set_pwd_var(/*exp:*/ 1);
7394 /* bash also exports SHLVL and _,
7395 * and sets (but doesn't export) the following variables:
7397 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7398 * BASH_VERSION='3.2.0(1)-release'
7400 * MACHTYPE=i386-pc-linux-gnu
7402 * HOSTNAME=<xxxxxxxxxx>
7403 * PPID=<NNNNN> - we also do it elsewhere
7414 * PIPESTATUS=([0]="0")
7415 * HISTFILE=/<xxx>/.bash_history
7419 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7421 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7431 #if ENABLE_FEATURE_EDITING
7432 G.line_input_state = new_line_input_t(FOR_SHELL);
7433 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7435 const char *hp = get_local_var_value("HISTFILE");
7437 hp = get_local_var_value("HOME");
7439 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7440 //set_local_var(xasprintf("HISTFILE=%s", ...));
7447 G.global_argc = argc;
7448 G.global_argv = argv;
7449 /* Initialize some more globals to non-zero values */
7450 cmdedit_update_prompt();
7452 if (setjmp(die_jmp)) {
7453 /* xfunc has failed! die die die */
7454 /* no EXIT traps, this is an escape hatch! */
7456 hush_exit(xfunc_error_retval);
7459 /* Shell is non-interactive at first. We need to call
7460 * init_sigmasks() if we are going to execute "sh <script>",
7461 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7462 * If we later decide that we are interactive, we run init_sigmasks()
7463 * in order to intercept (more) signals.
7467 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7470 opt = getopt(argc, argv, "+c:xins"
7473 # if ENABLE_HUSH_FUNCTIONS
7483 * sh ... -c 'script'
7484 * sh ... -c 'script' ARG0 [ARG1...]
7485 * On NOMMU, if builtin_argc != 0,
7486 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7487 * "" needs to be replaced with NULL
7488 * and BARGV vector fed to builtin function.
7489 * Note: the form without ARG0 never happens:
7490 * sh ... -c 'builtin' BARGV... ""
7493 G.root_pid = getpid();
7494 G.root_ppid = getppid();
7496 G.global_argv = argv + optind;
7497 G.global_argc = argc - optind;
7499 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7500 const struct built_in_command *x;
7503 x = find_builtin(optarg);
7504 if (x) { /* paranoia */
7505 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7506 G.global_argv += builtin_argc;
7507 G.global_argv[-1] = NULL; /* replace "" */
7508 G.last_exitcode = x->b_function(argv + optind - 1);
7512 if (!G.global_argv[0]) {
7513 /* -c 'script' (no params): prevent empty $0 */
7514 G.global_argv--; /* points to argv[i] of 'script' */
7515 G.global_argv[0] = argv[0];
7517 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7519 parse_and_run_string(optarg);
7522 /* Well, we cannot just declare interactiveness,
7523 * we have to have some stuff (ctty, etc) */
7524 /* G_interactive_fd++; */
7527 /* "-s" means "read from stdin", but this is how we always
7528 * operate, so simply do nothing here. */
7531 case '<': /* "big heredoc" support */
7532 full_write1_str(optarg);
7535 unsigned long long empty_trap_mask;
7537 G.root_pid = bb_strtou(optarg, &optarg, 16);
7539 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7541 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7543 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7545 builtin_argc = bb_strtou(optarg, &optarg, 16);
7547 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7548 if (empty_trap_mask != 0) {
7551 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7552 for (sig = 1; sig < NSIG; sig++) {
7553 if (empty_trap_mask & (1LL << sig)) {
7554 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7555 sigaddset(&G.blocked_set, sig);
7558 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7560 # if ENABLE_HUSH_LOOPS
7562 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7568 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7570 # if ENABLE_HUSH_FUNCTIONS
7572 struct function *funcp = new_function(optarg);
7573 /* funcp->name is already set to optarg */
7574 /* funcp->body is set to NULL. It's a special case. */
7575 funcp->body_as_string = argv[optind];
7583 if (set_mode('-', opt) == 0) /* no error */
7587 fprintf(stderr, "Usage: sh [FILE]...\n"
7588 " or: sh -c command [args]...\n\n");
7594 } /* option parsing loop */
7597 G.root_pid = getpid();
7598 G.root_ppid = getppid();
7601 /* If we are login shell... */
7602 if (argv[0] && argv[0][0] == '-') {
7604 debug_printf("sourcing /etc/profile\n");
7605 input = fopen_for_read("/etc/profile");
7606 if (input != NULL) {
7607 close_on_exec_on(fileno(input));
7609 parse_and_run_file(input);
7612 /* bash: after sourcing /etc/profile,
7613 * tries to source (in the given order):
7614 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7615 * stopping on first found. --noprofile turns this off.
7616 * bash also sources ~/.bash_logout on exit.
7617 * If called as sh, skips .bash_XXX files.
7624 * "bash <script>" (which is never interactive (unless -i?))
7625 * sources $BASH_ENV here (without scanning $PATH).
7626 * If called as sh, does the same but with $ENV.
7628 debug_printf("running script '%s'\n", argv[optind]);
7629 G.global_argv = argv + optind;
7630 G.global_argc = argc - optind;
7631 input = xfopen_for_read(argv[optind]);
7632 close_on_exec_on(fileno(input));
7634 parse_and_run_file(input);
7635 #if ENABLE_FEATURE_CLEAN_UP
7641 /* Up to here, shell was non-interactive. Now it may become one.
7642 * NB: don't forget to (re)run init_sigmasks() as needed.
7645 /* A shell is interactive if the '-i' flag was given,
7646 * or if all of the following conditions are met:
7648 * no arguments remaining or the -s flag given
7649 * standard input is a terminal
7650 * standard output is a terminal
7651 * Refer to Posix.2, the description of the 'sh' utility.
7654 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7655 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7656 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7657 if (G_saved_tty_pgrp < 0)
7658 G_saved_tty_pgrp = 0;
7660 /* try to dup stdin to high fd#, >= 255 */
7661 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7662 if (G_interactive_fd < 0) {
7663 /* try to dup to any fd */
7664 G_interactive_fd = dup(STDIN_FILENO);
7665 if (G_interactive_fd < 0) {
7667 G_interactive_fd = 0;
7668 G_saved_tty_pgrp = 0;
7671 // TODO: track & disallow any attempts of user
7672 // to (inadvertently) close/redirect G_interactive_fd
7674 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7675 if (G_interactive_fd) {
7676 close_on_exec_on(G_interactive_fd);
7678 if (G_saved_tty_pgrp) {
7679 /* If we were run as 'hush &', sleep until we are
7680 * in the foreground (tty pgrp == our pgrp).
7681 * If we get started under a job aware app (like bash),
7682 * make sure we are now in charge so we don't fight over
7683 * who gets the foreground */
7685 pid_t shell_pgrp = getpgrp();
7686 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7687 if (G_saved_tty_pgrp == shell_pgrp)
7689 /* send TTIN to ourself (should stop us) */
7690 kill(- shell_pgrp, SIGTTIN);
7694 /* Block some signals */
7697 if (G_saved_tty_pgrp) {
7698 /* Set other signals to restore saved_tty_pgrp */
7699 set_fatal_handlers();
7700 /* Put ourselves in our own process group
7701 * (bash, too, does this only if ctty is available) */
7702 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7703 /* Grab control of the terminal */
7704 tcsetpgrp(G_interactive_fd, getpid());
7706 /* -1 is special - makes xfuncs longjmp, not exit
7707 * (we reset die_sleep = 0 whereever we [v]fork) */
7708 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7712 #elif ENABLE_HUSH_INTERACTIVE
7713 /* No job control compiled in, only prompt/line editing */
7714 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7715 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7716 if (G_interactive_fd < 0) {
7717 /* try to dup to any fd */
7718 G_interactive_fd = dup(STDIN_FILENO);
7719 if (G_interactive_fd < 0)
7721 G_interactive_fd = 0;
7724 if (G_interactive_fd) {
7725 close_on_exec_on(G_interactive_fd);
7729 /* We have interactiveness code disabled */
7733 * if interactive but not a login shell, sources ~/.bashrc
7734 * (--norc turns this off, --rcfile <file> overrides)
7737 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7738 /* note: ash and hush share this string */
7739 printf("\n\n%s %s\n"
7740 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7743 "hush - the humble shell"
7747 parse_and_run_file(stdin);
7750 #if ENABLE_FEATURE_CLEAN_UP
7751 if (G.cwd != bb_msg_unknown)
7753 cur_var = G.top_var->next;
7755 struct variable *tmp = cur_var;
7756 if (!cur_var->max_len)
7757 free(cur_var->varstr);
7758 cur_var = cur_var->next;
7762 hush_exit(G.last_exitcode);
7767 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7768 int msh_main(int argc, char **argv)
7770 //bb_error_msg("msh is deprecated, please use hush instead");
7771 return hush_main(argc, argv);
7779 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7784 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7791 return applet_main_func(argc, argv - argc);
7794 static int FAST_FUNC builtin_test(char **argv)
7796 return run_applet_main(argv, test_main);
7799 static int FAST_FUNC builtin_echo(char **argv)
7801 return run_applet_main(argv, echo_main);
7805 static int FAST_FUNC builtin_printf(char **argv)
7807 return run_applet_main(argv, printf_main);
7811 static char **skip_dash_dash(char **argv)
7814 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7819 static int FAST_FUNC builtin_eval(char **argv)
7821 int rcode = EXIT_SUCCESS;
7823 argv = skip_dash_dash(argv);
7825 char *str = expand_strvec_to_string(argv);
7827 * eval "echo Hi; done" ("done" is syntax error):
7828 * "echo Hi" will not execute too.
7830 parse_and_run_string(str);
7832 rcode = G.last_exitcode;
7837 static int FAST_FUNC builtin_cd(char **argv)
7841 argv = skip_dash_dash(argv);
7843 if (newdir == NULL) {
7844 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7845 * bash says "bash: cd: HOME not set" and does nothing
7848 const char *home = get_local_var_value("HOME");
7849 newdir = home ? home : "/";
7851 if (chdir(newdir)) {
7852 /* Mimic bash message exactly */
7853 bb_perror_msg("cd: %s", newdir);
7854 return EXIT_FAILURE;
7856 /* Read current dir (get_cwd(1) is inside) and set PWD.
7857 * Note: do not enforce exporting. If PWD was unset or unexported,
7858 * set it again, but do not export. bash does the same.
7860 set_pwd_var(/*exp:*/ 0);
7861 return EXIT_SUCCESS;
7864 static int FAST_FUNC builtin_exec(char **argv)
7866 argv = skip_dash_dash(argv);
7867 if (argv[0] == NULL)
7868 return EXIT_SUCCESS; /* bash does this */
7870 /* Careful: we can end up here after [v]fork. Do not restore
7871 * tty pgrp then, only top-level shell process does that */
7872 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7873 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7875 /* TODO: if exec fails, bash does NOT exit! We do.
7876 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7877 * and tcsetpgrp, and this is inherently racy.
7879 execvp_or_die(argv);
7882 static int FAST_FUNC builtin_exit(char **argv)
7884 debug_printf_exec("%s()\n", __func__);
7886 /* interactive bash:
7887 * # trap "echo EEE" EXIT
7890 * There are stopped jobs.
7891 * (if there are _stopped_ jobs, running ones don't count)
7894 # EEE (then bash exits)
7896 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
7899 /* note: EXIT trap is run by hush_exit */
7900 argv = skip_dash_dash(argv);
7901 if (argv[0] == NULL)
7902 hush_exit(G.last_exitcode);
7903 /* mimic bash: exit 123abc == exit 255 + error msg */
7904 xfunc_error_retval = 255;
7905 /* bash: exit -2 == exit 254, no error msg */
7906 hush_exit(xatoi(argv[0]) & 0xff);
7909 static void print_escaped(const char *s)
7914 const char *p = strchrnul(s, '\'');
7915 /* print 'xxxx', possibly just '' */
7916 printf("'%.*s'", (int)(p - s), s);
7921 /* s points to '; print "'''...'''" */
7923 do putchar('\''); while (*++s == '\'');
7928 #if !ENABLE_HUSH_LOCAL
7929 #define helper_export_local(argv, exp, lvl) \
7930 helper_export_local(argv, exp)
7932 static void helper_export_local(char **argv, int exp, int lvl)
7936 char *name_end = strchrnul(name, '=');
7938 /* So far we do not check that name is valid (TODO?) */
7940 if (*name_end == '\0') {
7941 struct variable *var, **vpp;
7943 vpp = get_ptr_to_local_var(name, name_end - name);
7944 var = vpp ? *vpp : NULL;
7946 if (exp == -1) { /* unexporting? */
7947 /* export -n NAME (without =VALUE) */
7949 var->flg_export = 0;
7950 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7952 } /* else: export -n NOT_EXISTING_VAR: no-op */
7955 if (exp == 1) { /* exporting? */
7956 /* export NAME (without =VALUE) */
7958 var->flg_export = 1;
7959 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7960 putenv(var->varstr);
7964 /* Exporting non-existing variable.
7965 * bash does not put it in environment,
7966 * but remembers that it is exported,
7967 * and does put it in env when it is set later.
7968 * We just set it to "" and export. */
7969 /* Or, it's "local NAME" (without =VALUE).
7970 * bash sets the value to "". */
7971 name = xasprintf("%s=", name);
7973 /* (Un)exporting/making local NAME=VALUE */
7974 name = xstrdup(name);
7976 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7980 static int FAST_FUNC builtin_export(char **argv)
7982 unsigned opt_unexport;
7984 #if ENABLE_HUSH_EXPORT_N
7985 /* "!": do not abort on errors */
7986 opt_unexport = getopt32(argv, "!n");
7987 if (opt_unexport == (uint32_t)-1)
7988 return EXIT_FAILURE;
7995 if (argv[0] == NULL) {
8002 /* ash emits: export VAR='VAL'
8003 * bash: declare -x VAR="VAL"
8004 * we follow ash example */
8005 const char *s = *e++;
8006 const char *p = strchr(s, '=');
8008 if (!p) /* wtf? take next variable */
8011 printf("export %.*s", (int)(p - s) + 1, s);
8012 print_escaped(p + 1);
8016 /*fflush_all(); - done after each builtin anyway */
8018 return EXIT_SUCCESS;
8021 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8023 return EXIT_SUCCESS;
8026 #if ENABLE_HUSH_LOCAL
8027 static int FAST_FUNC builtin_local(char **argv)
8029 if (G.func_nest_level == 0) {
8030 bb_error_msg("%s: not in a function", argv[0]);
8031 return EXIT_FAILURE; /* bash compat */
8033 helper_export_local(argv, 0, G.func_nest_level);
8034 return EXIT_SUCCESS;
8038 static int FAST_FUNC builtin_trap(char **argv)
8044 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8049 /* No args: print all trapped */
8050 for (i = 0; i < NSIG; ++i) {
8053 print_escaped(G.traps[i]);
8054 /* note: bash adds "SIG", but only if invoked
8055 * as "bash". If called as "sh", or if set -o posix,
8056 * then it prints short signal names.
8057 * We are printing short names: */
8058 printf(" %s\n", get_signame(i));
8061 /*fflush_all(); - done after each builtin anyway */
8062 return EXIT_SUCCESS;
8066 /* If first arg is a number: reset all specified signals */
8067 sig = bb_strtou(*argv, NULL, 10);
8073 sig = get_signum(*argv++);
8074 if (sig < 0 || sig >= NSIG) {
8076 /* Mimic bash message exactly */
8077 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8082 G.traps[sig] = xstrdup(new_cmd);
8084 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8085 get_signame(sig), sig, G.traps[sig]);
8087 /* There is no signal for 0 (EXIT) */
8092 sigaddset(&G.blocked_set, sig);
8094 /* There was a trap handler, we are removing it
8095 * (if sig has non-DFL handling,
8096 * we don't need to do anything) */
8097 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8099 sigdelset(&G.blocked_set, sig);
8102 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8106 if (!argv[1]) { /* no second arg */
8107 bb_error_msg("trap: invalid arguments");
8108 return EXIT_FAILURE;
8111 /* First arg is "-": reset all specified to default */
8112 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8113 /* Everything else: set arg as signal handler
8114 * (includes "" case, which ignores signal) */
8115 if (argv[0][0] == '-') {
8116 if (argv[0][1] == '\0') { /* "-" */
8117 /* new_cmd remains NULL: "reset these sigs" */
8120 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8123 /* else: "-something", no special meaning */
8128 goto process_sig_list;
8131 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8132 static int FAST_FUNC builtin_type(char **argv)
8134 int ret = EXIT_SUCCESS;
8140 if (0) {} /* make conditional compile easier below */
8141 /*else if (find_alias(*argv))
8142 type = "an alias";*/
8143 #if ENABLE_HUSH_FUNCTIONS
8144 else if (find_function(*argv))
8145 type = "a function";
8147 else if (find_builtin(*argv))
8148 type = "a shell builtin";
8149 else if ((path = find_in_path(*argv)) != NULL)
8152 bb_error_msg("type: %s: not found", *argv);
8157 printf("%s is %s\n", *argv, type);
8165 /* built-in 'fg' and 'bg' handler */
8166 static int FAST_FUNC builtin_fg_bg(char **argv)
8171 if (!G_interactive_fd)
8172 return EXIT_FAILURE;
8174 /* If they gave us no args, assume they want the last backgrounded task */
8176 for (pi = G.job_list; pi; pi = pi->next) {
8177 if (pi->jobid == G.last_jobid) {
8181 bb_error_msg("%s: no current job", argv[0]);
8182 return EXIT_FAILURE;
8184 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8185 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8186 return EXIT_FAILURE;
8188 for (pi = G.job_list; pi; pi = pi->next) {
8189 if (pi->jobid == jobnum) {
8193 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8194 return EXIT_FAILURE;
8196 /* TODO: bash prints a string representation
8197 * of job being foregrounded (like "sleep 1 | cat") */
8198 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8199 /* Put the job into the foreground. */
8200 tcsetpgrp(G_interactive_fd, pi->pgrp);
8203 /* Restart the processes in the job */
8204 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8205 for (i = 0; i < pi->num_cmds; i++) {
8206 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8207 pi->cmds[i].is_stopped = 0;
8209 pi->stopped_cmds = 0;
8211 i = kill(- pi->pgrp, SIGCONT);
8213 if (errno == ESRCH) {
8214 delete_finished_bg_job(pi);
8215 return EXIT_SUCCESS;
8217 bb_perror_msg("kill (SIGCONT)");
8220 if (argv[0][0] == 'f') {
8222 return checkjobs_and_fg_shell(pi);
8224 return EXIT_SUCCESS;
8228 #if ENABLE_HUSH_HELP
8229 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8231 const struct built_in_command *x;
8234 "Built-in commands:\n"
8235 "------------------\n");
8236 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8238 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8241 return EXIT_SUCCESS;
8246 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8249 const char *status_string;
8251 for (job = G.job_list; job; job = job->next) {
8252 if (job->alive_cmds == job->stopped_cmds)
8253 status_string = "Stopped";
8255 status_string = "Running";
8257 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8259 return EXIT_SUCCESS;
8264 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8269 # ifdef M_TRIM_THRESHOLD
8270 /* Optional. Reduces probability of false positives */
8273 /* Crude attempt to find where "free memory" starts,
8274 * sans fragmentation. */
8276 l = (unsigned long)p;
8279 if (l < (unsigned long)p) l = (unsigned long)p;
8282 if (!G.memleak_value)
8283 G.memleak_value = l;
8285 l -= G.memleak_value;
8292 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8297 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8300 return EXIT_SUCCESS;
8303 static int FAST_FUNC builtin_read(char **argv)
8312 /* "!": do not abort on errors.
8313 * Option string must start with "sr" to match BUILTIN_READ_xxx
8315 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8316 if (read_flags == (uint32_t)-1)
8317 return EXIT_FAILURE;
8320 r = shell_builtin_read(set_local_var_from_halves,
8322 get_local_var_value("IFS"), /* can be NULL */
8330 if ((uintptr_t)r > 1) {
8331 bb_error_msg("%s", r);
8332 r = (char*)(uintptr_t)1;
8335 return (uintptr_t)r;
8338 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8339 * built-in 'set' handler
8341 * set [-abCefhmnuvx] [-o option] [argument...]
8342 * set [+abCefhmnuvx] [+o option] [argument...]
8343 * set -- [argument...]
8346 * Implementations shall support the options in both their hyphen and
8347 * plus-sign forms. These options can also be specified as options to sh.
8349 * Write out all variables and their values: set
8350 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8351 * Turn on the -x and -v options: set -xv
8352 * Unset all positional parameters: set --
8353 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8354 * Set the positional parameters to the expansion of x, even if x expands
8355 * with a leading '-' or '+': set -- $x
8357 * So far, we only support "set -- [argument...]" and some of the short names.
8359 static int FAST_FUNC builtin_set(char **argv)
8362 char **pp, **g_argv;
8363 char *arg = *++argv;
8367 for (e = G.top_var; e; e = e->next)
8369 return EXIT_SUCCESS;
8373 if (!strcmp(arg, "--")) {
8377 if (arg[0] != '+' && arg[0] != '-')
8379 for (n = 1; arg[n]; ++n)
8380 if (set_mode(arg[0], arg[n]))
8382 } while ((arg = *++argv) != NULL);
8383 /* Now argv[0] is 1st argument */
8386 return EXIT_SUCCESS;
8389 /* NB: G.global_argv[0] ($0) is never freed/changed */
8390 g_argv = G.global_argv;
8391 if (G.global_args_malloced) {
8397 G.global_args_malloced = 1;
8398 pp = xzalloc(sizeof(pp[0]) * 2);
8399 pp[0] = g_argv[0]; /* retain $0 */
8402 /* This realloc's G.global_argv */
8403 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8410 return EXIT_SUCCESS;
8412 /* Nothing known, so abort */
8414 bb_error_msg("set: %s: invalid option", arg);
8415 return EXIT_FAILURE;
8418 static int FAST_FUNC builtin_shift(char **argv)
8421 argv = skip_dash_dash(argv);
8425 if (n >= 0 && n < G.global_argc) {
8426 if (G.global_args_malloced) {
8429 free(G.global_argv[m++]);
8432 memmove(&G.global_argv[1], &G.global_argv[n+1],
8433 G.global_argc * sizeof(G.global_argv[0]));
8434 return EXIT_SUCCESS;
8436 return EXIT_FAILURE;
8439 static int FAST_FUNC builtin_source(char **argv)
8441 char *arg_path, *filename;
8444 #if ENABLE_HUSH_FUNCTIONS
8448 argv = skip_dash_dash(argv);
8451 /* bash says: "bash: .: filename argument required" */
8452 return 2; /* bash compat */
8455 if (!strchr(filename, '/')) {
8456 arg_path = find_in_path(filename);
8458 filename = arg_path;
8460 input = fopen_or_warn(filename, "r");
8463 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8464 return EXIT_FAILURE;
8466 close_on_exec_on(fileno(input));
8468 #if ENABLE_HUSH_FUNCTIONS
8469 sv_flg = G.flag_return_in_progress;
8470 /* "we are inside sourced file, ok to use return" */
8471 G.flag_return_in_progress = -1;
8473 save_and_replace_G_args(&sv, argv);
8475 parse_and_run_file(input);
8478 restore_G_args(&sv, argv);
8479 #if ENABLE_HUSH_FUNCTIONS
8480 G.flag_return_in_progress = sv_flg;
8483 return G.last_exitcode;
8486 static int FAST_FUNC builtin_umask(char **argv)
8492 argv = skip_dash_dash(argv);
8494 mode_t old_mask = mask;
8497 rc = bb_parse_mode(argv[0], &mask);
8502 * bash: umask: 'q': invalid symbolic mode operator
8503 * bash: umask: 999: octal number out of range
8505 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8510 printf("%04o\n", (unsigned) mask);
8511 /* fall through and restore mask which we set to 0 */
8515 return !rc; /* rc != 0 - success */
8518 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8519 static int FAST_FUNC builtin_unset(char **argv)
8524 /* "!": do not abort on errors */
8525 /* "+": stop at 1st non-option */
8526 opts = getopt32(argv, "!+vf");
8527 if (opts == (unsigned)-1)
8528 return EXIT_FAILURE;
8530 bb_error_msg("unset: -v and -f are exclusive");
8531 return EXIT_FAILURE;
8537 if (!(opts & 2)) { /* not -f */
8538 if (unset_local_var(*argv)) {
8539 /* unset <nonexistent_var> doesn't fail.
8540 * Error is when one tries to unset RO var.
8541 * Message was printed by unset_local_var. */
8545 #if ENABLE_HUSH_FUNCTIONS
8555 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8556 static int FAST_FUNC builtin_wait(char **argv)
8558 int ret = EXIT_SUCCESS;
8561 argv = skip_dash_dash(argv);
8562 if (argv[0] == NULL) {
8563 /* Don't care about wait results */
8564 /* Note 1: must wait until there are no more children */
8565 /* Note 2: must be interruptible */
8567 * $ sleep 3 & sleep 6 & wait
8572 * $ sleep 3 & sleep 6 & wait
8576 * ^C <-- after ~4 sec from keyboard
8579 sigaddset(&G.blocked_set, SIGCHLD);
8580 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8583 if (errno == ECHILD)
8585 /* Wait for SIGCHLD or any other signal of interest */
8586 /* sigtimedwait with infinite timeout: */
8587 sig = sigwaitinfo(&G.blocked_set, NULL);
8589 sig = check_and_run_traps(sig);
8590 if (sig && sig != SIGCHLD) { /* see note 2 */
8596 sigdelset(&G.blocked_set, SIGCHLD);
8597 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8601 /* This is probably buggy wrt interruptible-ness */
8603 pid_t pid = bb_strtou(*argv, NULL, 10);
8605 /* mimic bash message */
8606 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8607 return EXIT_FAILURE;
8609 if (waitpid(pid, &status, 0) == pid) {
8610 if (WIFSIGNALED(status))
8611 ret = 128 + WTERMSIG(status);
8612 else if (WIFEXITED(status))
8613 ret = WEXITSTATUS(status);
8617 bb_perror_msg("wait %s", *argv);
8626 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8627 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8630 def = bb_strtou(argv[1], NULL, 10);
8631 if (errno || def < def_min || argv[2]) {
8632 bb_error_msg("%s: bad arguments", argv[0]);
8640 #if ENABLE_HUSH_LOOPS
8641 static int FAST_FUNC builtin_break(char **argv)
8644 if (G.depth_of_loop == 0) {
8645 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8646 return EXIT_SUCCESS; /* bash compat */
8648 G.flag_break_continue++; /* BC_BREAK = 1 */
8650 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8651 if (depth == UINT_MAX)
8652 G.flag_break_continue = BC_BREAK;
8653 if (G.depth_of_loop < depth)
8654 G.depth_break_continue = G.depth_of_loop;
8656 return EXIT_SUCCESS;
8659 static int FAST_FUNC builtin_continue(char **argv)
8661 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8662 return builtin_break(argv);
8666 #if ENABLE_HUSH_FUNCTIONS
8667 static int FAST_FUNC builtin_return(char **argv)
8671 if (G.flag_return_in_progress != -1) {
8672 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8673 return EXIT_FAILURE; /* bash compat */
8676 G.flag_return_in_progress = 1;
8679 * out of range: wraps around at 256, does not error out
8680 * non-numeric param:
8681 * f() { false; return qwe; }; f; echo $?
8682 * bash: return: qwe: numeric argument required <== we do this
8683 * 255 <== we also do this
8685 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);