1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
84 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
85 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
86 || defined(__APPLE__) \
88 # include <malloc.h> /* for malloc_trim */
91 /* #include <dmalloc.h> */
96 #include "shell_common.h"
99 #if ENABLE_HUSH_RANDOM_SUPPORT
102 # define CLEAR_RANDOM_T(rnd) ((void)0)
105 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
108 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
109 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
110 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
111 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
113 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
114 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
117 //config: bool "hush"
120 //config: hush is a small shell (25k). It handles the normal flow control
121 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
122 //config: case/esac. Redirections, here documents, $((arithmetic))
123 //config: and functions are supported.
125 //config: It will compile and work on no-mmu systems.
127 //config: It does not handle select, aliases, tilde expansion,
128 //config: &>file and >&file redirection of stdout+stderr.
130 //config:config HUSH_BASH_COMPAT
131 //config: bool "bash-compatible extensions"
133 //config: depends on HUSH
135 //config: Enable bash-compatible extensions.
137 //config:config HUSH_BRACE_EXPANSION
138 //config: bool "Brace expansion"
140 //config: depends on HUSH_BASH_COMPAT
142 //config: Enable {abc,def} extension.
144 //config:config HUSH_HELP
145 //config: bool "help builtin"
147 //config: depends on HUSH
149 //config: Enable help builtin in hush. Code size + ~1 kbyte.
151 //config:config HUSH_INTERACTIVE
152 //config: bool "Interactive mode"
154 //config: depends on HUSH
156 //config: Enable interactive mode (prompt and command editing).
157 //config: Without this, hush simply reads and executes commands
158 //config: from stdin just like a shell script from a file.
159 //config: No prompt, no PS1/PS2 magic shell variables.
161 //config:config HUSH_SAVEHISTORY
162 //config: bool "Save command history to .hush_history"
164 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
166 //config: Enable history saving in hush.
168 //config:config HUSH_JOB
169 //config: bool "Job control"
171 //config: depends on HUSH_INTERACTIVE
173 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
174 //config: command (not entire shell), fg/bg builtins work. Without this option,
175 //config: "cmd &" still works by simply spawning a process and immediately
176 //config: prompting for next command (or executing next command in a script),
177 //config: but no separate process group is formed.
179 //config:config HUSH_TICK
180 //config: bool "Process substitution"
182 //config: depends on HUSH
184 //config: Enable process substitution `command` and $(command) in hush.
186 //config:config HUSH_IF
187 //config: bool "Support if/then/elif/else/fi"
189 //config: depends on HUSH
191 //config: Enable if/then/elif/else/fi in hush.
193 //config:config HUSH_LOOPS
194 //config: bool "Support for, while and until loops"
196 //config: depends on HUSH
198 //config: Enable for, while and until loops in hush.
200 //config:config HUSH_CASE
201 //config: bool "Support case ... esac statement"
203 //config: depends on HUSH
205 //config: Enable case ... esac statement in hush. +400 bytes.
207 //config:config HUSH_FUNCTIONS
208 //config: bool "Support funcname() { commands; } syntax"
210 //config: depends on HUSH
212 //config: Enable support for shell functions in hush. +800 bytes.
214 //config:config HUSH_LOCAL
215 //config: bool "Support local builtin"
217 //config: depends on HUSH_FUNCTIONS
219 //config: Enable support for local variables in functions.
221 //config:config HUSH_RANDOM_SUPPORT
222 //config: bool "Pseudorandom generator and $RANDOM variable"
224 //config: depends on HUSH
226 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
227 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
229 //config:config HUSH_EXPORT_N
230 //config: bool "Support 'export -n' option"
232 //config: depends on HUSH
234 //config: export -n unexports variables. It is a bash extension.
236 //config:config HUSH_MODE_X
237 //config: bool "Support 'hush -x' option and 'set -x' command"
239 //config: depends on HUSH
241 //config: This instructs hush to print commands before execution.
242 //config: Adds ~300 bytes.
245 //config: bool "msh (deprecated: aliased to hush)"
247 //config: select HUSH
249 //config: msh is deprecated and will be removed, please migrate to hush.
252 /* -i (interactive) and -s (read stdin) are also accepted,
253 * but currently do nothing, therefore aren't shown in help.
254 * NOMMU-specific options are not meant to be used by users,
255 * therefore we don't show them either.
257 //usage:#define hush_trivial_usage
258 //usage: "[-nx] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
259 //usage:#define hush_full_usage "\n\n"
260 //usage: "Unix shell interpreter"
262 //usage:#define msh_trivial_usage hush_trivial_usage
263 //usage:#define msh_full_usage hush_full_usage
265 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
266 //usage:# define sh_trivial_usage hush_trivial_usage
267 //usage:# define sh_full_usage hush_full_usage
269 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
270 //usage:# define bash_trivial_usage hush_trivial_usage
271 //usage:# define bash_full_usage hush_full_usage
276 #define LEAK_HUNTING 0
277 #define BUILD_AS_NOMMU 0
278 /* Enable/disable sanity checks. Ok to enable in production,
279 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
280 * Keeping 1 for now even in released versions.
283 /* Slightly bigger (+200 bytes), but faster hush.
284 * So far it only enables a trick with counting SIGCHLDs and forks,
285 * which allows us to do fewer waitpid's.
286 * (we can detect a case where neither forks were done nor SIGCHLDs happened
287 * and therefore waitpid will return the same result as last time)
289 #define ENABLE_HUSH_FAST 0
290 /* TODO: implement simplified code for users which do not need ${var%...} ops
291 * So far ${var%...} ops are always enabled:
293 #define ENABLE_HUSH_DOLLAR_OPS 1
298 # undef USE_FOR_NOMMU
301 # define USE_FOR_NOMMU(...) __VA_ARGS__
302 # define USE_FOR_MMU(...)
305 #include "NUM_APPLETS.h"
307 /* STANDALONE does not make sense, and won't compile */
308 # undef CONFIG_FEATURE_SH_STANDALONE
309 # undef ENABLE_FEATURE_SH_STANDALONE
310 # undef IF_FEATURE_SH_STANDALONE
311 # undef IF_NOT_FEATURE_SH_STANDALONE
312 # define ENABLE_FEATURE_SH_STANDALONE 0
313 # define IF_FEATURE_SH_STANDALONE(...)
314 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
317 #if !ENABLE_HUSH_INTERACTIVE
318 # undef ENABLE_FEATURE_EDITING
319 # define ENABLE_FEATURE_EDITING 0
320 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
321 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
324 /* Do we support ANY keywords? */
325 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
326 # define HAS_KEYWORDS 1
327 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
328 # define IF_HAS_NO_KEYWORDS(...)
330 # define HAS_KEYWORDS 0
331 # define IF_HAS_KEYWORDS(...)
332 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
335 /* If you comment out one of these below, it will be #defined later
336 * to perform debug printfs to stderr: */
337 #define debug_printf(...) do {} while (0)
338 /* Finer-grained debug switches */
339 #define debug_printf_parse(...) do {} while (0)
340 #define debug_print_tree(a, b) do {} while (0)
341 #define debug_printf_exec(...) do {} while (0)
342 #define debug_printf_env(...) do {} while (0)
343 #define debug_printf_jobs(...) do {} while (0)
344 #define debug_printf_expand(...) do {} while (0)
345 #define debug_printf_varexp(...) do {} while (0)
346 #define debug_printf_glob(...) do {} while (0)
347 #define debug_printf_list(...) do {} while (0)
348 #define debug_printf_subst(...) do {} while (0)
349 #define debug_printf_clean(...) do {} while (0)
351 #define ERR_PTR ((void*)(long)1)
353 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
355 #define _SPECIAL_VARS_STR "_*@$!?#"
356 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
357 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
358 #if ENABLE_HUSH_BASH_COMPAT
359 /* Support / and // replace ops */
360 /* Note that // is stored as \ in "encoded" string representation */
361 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
362 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
363 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
365 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
366 # define VAR_SUBST_OPS "%#:-=+?"
367 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
370 #define SPECIAL_VAR_SYMBOL 3
374 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
376 /* This supports saving pointers malloced in vfork child,
377 * to be freed in the parent.
380 typedef struct nommu_save_t {
382 struct variable *old_vars;
384 char **argv_from_re_execing;
397 #if ENABLE_HUSH_LOOPS
404 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
409 /* three pseudo-keywords support contrived "case" syntax: */
410 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
411 RES_MATCH , /* "word)" */
412 RES_CASE_BODY, /* "this command is inside CASE" */
419 typedef struct o_string {
421 int length; /* position where data is appended */
424 /* At least some part of the string was inside '' or "",
425 * possibly empty one: word"", wo''rd etc. */
426 smallint has_quoted_part;
427 smallint has_empty_slot;
428 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
431 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
433 /* Protect newly added chars against globbing
434 * by prepending \ to *, ?, [, \ */
435 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
438 MAYBE_ASSIGNMENT = 0,
439 DEFINITELY_ASSIGNMENT = 1,
441 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
444 /* Used for initialization: o_string foo = NULL_O_STRING; */
445 #define NULL_O_STRING { NULL }
447 /* I can almost use ordinary FILE*. Is open_memstream() universally
448 * available? Where is it documented? */
449 typedef struct in_str {
451 /* eof_flag=1: last char in ->p is really an EOF */
452 char eof_flag; /* meaningless if ->p == NULL */
454 #if ENABLE_HUSH_INTERACTIVE
455 smallint promptmode; /* 0: PS1, 1: PS2 */
458 int (*get) (struct in_str *) FAST_FUNC;
459 int (*peek) (struct in_str *) FAST_FUNC;
461 #define i_getch(input) ((input)->get(input))
462 #define i_peek(input) ((input)->peek(input))
464 /* The descrip member of this structure is only used to make
465 * debugging output pretty */
466 static const struct {
468 signed char default_fd;
471 { O_RDONLY, 0, "<" },
472 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
473 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
474 { O_CREAT|O_RDWR, 1, "<>" },
475 { O_RDONLY, 0, "<<" },
476 /* Should not be needed. Bogus default_fd helps in debugging */
477 /* { O_RDONLY, 77, "<<" }, */
480 struct redir_struct {
481 struct redir_struct *next;
482 char *rd_filename; /* filename */
483 int rd_fd; /* fd to redirect */
484 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
486 smallint rd_type; /* (enum redir_type) */
487 /* note: for heredocs, rd_filename contains heredoc delimiter,
488 * and subsequently heredoc itself; and rd_dup is a bitmask:
489 * bit 0: do we need to trim leading tabs?
490 * bit 1: is heredoc quoted (<<'delim' syntax) ?
493 typedef enum redir_type {
495 REDIRECT_OVERWRITE = 1,
498 REDIRECT_HEREDOC = 4,
499 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
502 REDIRFD_SYNTAX_ERR = -2,
503 REDIRFD_TO_FILE = -1,
504 /* otherwise, rd_fd is redirected to rd_dup */
506 HEREDOC_SKIPTABS = 1,
512 pid_t pid; /* 0 if exited */
513 int assignment_cnt; /* how many argv[i] are assignments? */
514 smallint is_stopped; /* is the command currently running? */
515 smallint cmd_type; /* CMD_xxx */
517 #define CMD_SUBSHELL 1
518 #if ENABLE_HUSH_BASH_COMPAT
519 /* used for "[[ EXPR ]]" */
520 # define CMD_SINGLEWORD_NOGLOB 2
522 #if ENABLE_HUSH_FUNCTIONS
523 # define CMD_FUNCDEF 3
526 smalluint cmd_exitcode;
527 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
530 char *group_as_string;
532 #if ENABLE_HUSH_FUNCTIONS
533 struct function *child_func;
534 /* This field is used to prevent a bug here:
535 * while...do f1() {a;}; f1; f1() {b;}; f1; done
536 * When we execute "f1() {a;}" cmd, we create new function and clear
537 * cmd->group, cmd->group_as_string, cmd->argv[0].
538 * When we execute "f1() {b;}", we notice that f1 exists,
539 * and that its "parent cmd" struct is still "alive",
540 * we put those fields back into cmd->xxx
541 * (struct function has ->parent_cmd ptr to facilitate that).
542 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
543 * Without this trick, loop would execute a;b;b;b;...
544 * instead of correct sequence a;b;a;b;...
545 * When command is freed, it severs the link
546 * (sets ->child_func->parent_cmd to NULL).
549 char **argv; /* command name and arguments */
550 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
551 * and on execution these are substituted with their values.
552 * Substitution can make _several_ words out of one argv[n]!
553 * Example: argv[0]=='.^C*^C.' here: echo .$*.
554 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
556 struct redir_struct *redirects; /* I/O redirections */
558 /* Is there anything in this command at all? */
559 #define IS_NULL_CMD(cmd) \
560 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
564 int num_cmds; /* total number of commands in pipe */
565 int alive_cmds; /* number of commands running (not exited) */
566 int stopped_cmds; /* number of commands alive, but stopped */
568 int jobid; /* job number */
569 pid_t pgrp; /* process group ID for the job */
570 char *cmdtext; /* name of job */
572 struct command *cmds; /* array of commands in pipe */
573 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
574 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
575 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
577 typedef enum pipe_style {
583 /* Is there anything in this pipe at all? */
584 #define IS_NULL_PIPE(pi) \
585 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
587 /* This holds pointers to the various results of parsing */
588 struct parse_context {
589 /* linked list of pipes */
590 struct pipe *list_head;
591 /* last pipe (being constructed right now) */
593 /* last command in pipe (being constructed right now) */
594 struct command *command;
595 /* last redirect in command->redirects list */
596 struct redir_struct *pending_redirect;
602 smallint ctx_inverted; /* "! cmd | cmd" */
604 smallint ctx_dsemicolon; /* ";;" seen */
606 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
608 /* group we are enclosed in:
609 * example: "if pipe1; pipe2; then pipe3; fi"
610 * when we see "if" or "then", we malloc and copy current context,
611 * and make ->stack point to it. then we parse pipeN.
612 * when closing "then" / fi" / whatever is found,
613 * we move list_head into ->stack->command->group,
614 * copy ->stack into current context, and delete ->stack.
615 * (parsing of { list } and ( list ) doesn't use this method)
617 struct parse_context *stack;
621 /* On program start, environ points to initial environment.
622 * putenv adds new pointers into it, unsetenv removes them.
623 * Neither of these (de)allocates the strings.
624 * setenv allocates new strings in malloc space and does putenv,
625 * and thus setenv is unusable (leaky) for shell's purposes */
626 #define setenv(...) setenv_is_leaky_dont_use()
628 struct variable *next;
629 char *varstr; /* points to "name=" portion */
630 #if ENABLE_HUSH_LOCAL
631 unsigned func_nest_level;
633 int max_len; /* if > 0, name is part of initial env; else name is malloced */
634 smallint flg_export; /* putenv should be done on this var */
635 smallint flg_read_only;
643 #if ENABLE_HUSH_FUNCTIONS
645 struct function *next;
647 struct command *parent_cmd;
650 char *body_as_string;
656 /* set -/+o OPT support. (TODO: make it optional)
657 * bash supports the following opts:
668 * interactive-comments on
686 static const char o_opt_strings[] ALIGN1 =
689 #if ENABLE_HUSH_MODE_X
696 #if ENABLE_HUSH_MODE_X
703 /* "Globals" within this file */
704 /* Sorted roughly by size (smaller offsets == smaller code) */
706 /* interactive_fd != 0 means we are an interactive shell.
707 * If we are, then saved_tty_pgrp can also be != 0, meaning
708 * that controlling tty is available. With saved_tty_pgrp == 0,
709 * job control still works, but terminal signals
710 * (^C, ^Z, ^Y, ^\) won't work at all, and background
711 * process groups can only be created with "cmd &".
712 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
713 * to give tty to the foreground process group,
714 * and will take it back when the group is stopped (^Z)
717 #if ENABLE_HUSH_INTERACTIVE
718 /* 'interactive_fd' is a fd# open to ctty, if we have one
719 * _AND_ if we decided to act interactively */
723 # define G_interactive_fd (G.interactive_fd)
725 # define G_interactive_fd 0
727 #if ENABLE_FEATURE_EDITING
728 line_input_t *line_input_state;
733 #if ENABLE_HUSH_RANDOM_SUPPORT
739 pid_t saved_tty_pgrp;
740 struct pipe *job_list;
741 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
743 # define G_saved_tty_pgrp 0
745 char o_opt[NUM_OPT_O];
746 #if ENABLE_HUSH_MODE_X
747 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
751 smallint flag_SIGINT;
752 #if ENABLE_HUSH_LOOPS
753 smallint flag_break_continue;
755 #if ENABLE_HUSH_FUNCTIONS
756 /* 0: outside of a function (or sourced file)
757 * -1: inside of a function, ok to use return builtin
758 * 1: return is invoked, skip all till end of func
760 smallint flag_return_in_progress;
762 smallint exiting; /* used to prevent EXIT trap recursion */
763 /* These four support $?, $#, and $1 */
764 smalluint last_exitcode;
765 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
766 smalluint global_args_malloced;
767 smalluint inherited_set_is_saved;
768 /* how many non-NULL argv's we have. NB: $# + 1 */
772 char *argv0_for_re_execing;
774 #if ENABLE_HUSH_LOOPS
775 unsigned depth_break_continue;
776 unsigned depth_of_loop;
780 struct variable *top_var;
781 char **expanded_assignments;
782 #if ENABLE_HUSH_FUNCTIONS
783 struct function *top_func;
784 # if ENABLE_HUSH_LOCAL
785 struct variable **shadowed_vars_pp;
786 unsigned func_nest_level;
789 /* Signal and trap handling */
791 unsigned count_SIGCHLD;
792 unsigned handled_SIGCHLD;
793 smallint we_have_children;
795 /* which signals have non-DFL handler (even with no traps set)? */
796 unsigned non_DFL_mask;
797 char **traps; /* char *traps[NSIG] */
798 sigset_t blocked_set;
799 sigset_t inherited_set;
801 unsigned long memleak_value;
804 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
806 #define G (*ptr_to_globals)
807 /* Not #defining name to G.name - this quickly gets unwieldy
808 * (too many defines). Also, I actually prefer to see when a variable
809 * is global, thus "G." prefix is a useful hint */
810 #define INIT_G() do { \
811 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
815 /* Function prototypes for builtins */
816 static int builtin_cd(char **argv) FAST_FUNC;
817 static int builtin_echo(char **argv) FAST_FUNC;
818 static int builtin_eval(char **argv) FAST_FUNC;
819 static int builtin_exec(char **argv) FAST_FUNC;
820 static int builtin_exit(char **argv) FAST_FUNC;
821 static int builtin_export(char **argv) FAST_FUNC;
823 static int builtin_fg_bg(char **argv) FAST_FUNC;
824 static int builtin_jobs(char **argv) FAST_FUNC;
827 static int builtin_help(char **argv) FAST_FUNC;
829 #if ENABLE_HUSH_LOCAL
830 static int builtin_local(char **argv) FAST_FUNC;
833 static int builtin_memleak(char **argv) FAST_FUNC;
836 static int builtin_printf(char **argv) FAST_FUNC;
838 static int builtin_pwd(char **argv) FAST_FUNC;
839 static int builtin_read(char **argv) FAST_FUNC;
840 static int builtin_set(char **argv) FAST_FUNC;
841 static int builtin_shift(char **argv) FAST_FUNC;
842 static int builtin_source(char **argv) FAST_FUNC;
843 static int builtin_test(char **argv) FAST_FUNC;
844 static int builtin_trap(char **argv) FAST_FUNC;
845 static int builtin_type(char **argv) FAST_FUNC;
846 static int builtin_true(char **argv) FAST_FUNC;
847 static int builtin_umask(char **argv) FAST_FUNC;
848 static int builtin_unset(char **argv) FAST_FUNC;
849 static int builtin_wait(char **argv) FAST_FUNC;
850 #if ENABLE_HUSH_LOOPS
851 static int builtin_break(char **argv) FAST_FUNC;
852 static int builtin_continue(char **argv) FAST_FUNC;
854 #if ENABLE_HUSH_FUNCTIONS
855 static int builtin_return(char **argv) FAST_FUNC;
858 /* Table of built-in functions. They can be forked or not, depending on
859 * context: within pipes, they fork. As simple commands, they do not.
860 * When used in non-forking context, they can change global variables
861 * in the parent shell process. If forked, of course they cannot.
862 * For example, 'unset foo | whatever' will parse and run, but foo will
863 * still be set at the end. */
864 struct built_in_command {
866 int (*b_function)(char **argv) FAST_FUNC;
869 # define BLTIN(cmd, func, help) { cmd, func, help }
871 # define BLTIN(cmd, func, help) { cmd, func }
875 static const struct built_in_command bltins1[] = {
876 BLTIN("." , builtin_source , "Run commands in a file"),
877 BLTIN(":" , builtin_true , NULL),
879 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
881 #if ENABLE_HUSH_LOOPS
882 BLTIN("break" , builtin_break , "Exit from a loop"),
884 BLTIN("cd" , builtin_cd , "Change directory"),
885 #if ENABLE_HUSH_LOOPS
886 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
888 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
889 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
890 BLTIN("exit" , builtin_exit , "Exit"),
891 BLTIN("export" , builtin_export , "Set environment variables"),
893 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
896 BLTIN("help" , builtin_help , NULL),
899 BLTIN("jobs" , builtin_jobs , "List jobs"),
901 #if ENABLE_HUSH_LOCAL
902 BLTIN("local" , builtin_local , "Set local variables"),
905 BLTIN("memleak" , builtin_memleak , NULL),
907 BLTIN("read" , builtin_read , "Input into variable"),
908 #if ENABLE_HUSH_FUNCTIONS
909 BLTIN("return" , builtin_return , "Return from a function"),
911 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
912 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
913 #if ENABLE_HUSH_BASH_COMPAT
914 BLTIN("source" , builtin_source , "Run commands in a file"),
916 BLTIN("trap" , builtin_trap , "Trap signals"),
917 BLTIN("type" , builtin_type , "Show command type"),
918 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
919 BLTIN("umask" , builtin_umask , "Set file creation mask"),
920 BLTIN("unset" , builtin_unset , "Unset variables"),
921 BLTIN("wait" , builtin_wait , "Wait for process"),
923 /* For now, echo and test are unconditionally enabled.
924 * Maybe make it configurable? */
925 static const struct built_in_command bltins2[] = {
926 BLTIN("[" , builtin_test , NULL),
927 BLTIN("echo" , builtin_echo , NULL),
929 BLTIN("printf" , builtin_printf , NULL),
931 BLTIN("pwd" , builtin_pwd , NULL),
932 BLTIN("test" , builtin_test , NULL),
939 /* prevent disasters with G.debug_indent < 0 */
940 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
941 # define debug_enter() (G.debug_indent++)
942 # define debug_leave() (G.debug_indent--)
944 # define indent() ((void)0)
945 # define debug_enter() ((void)0)
946 # define debug_leave() ((void)0)
950 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
953 #ifndef debug_printf_parse
954 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
957 #ifndef debug_printf_exec
958 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
961 #ifndef debug_printf_env
962 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
965 #ifndef debug_printf_jobs
966 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
967 # define DEBUG_JOBS 1
969 # define DEBUG_JOBS 0
972 #ifndef debug_printf_expand
973 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
974 # define DEBUG_EXPAND 1
976 # define DEBUG_EXPAND 0
979 #ifndef debug_printf_varexp
980 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
983 #ifndef debug_printf_glob
984 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
985 # define DEBUG_GLOB 1
987 # define DEBUG_GLOB 0
990 #ifndef debug_printf_list
991 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
994 #ifndef debug_printf_subst
995 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
998 #ifndef debug_printf_clean
999 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1000 # define DEBUG_CLEAN 1
1002 # define DEBUG_CLEAN 0
1006 static void debug_print_strings(const char *prefix, char **vv)
1009 fdprintf(2, "%s:\n", prefix);
1011 fdprintf(2, " '%s'\n", *vv++);
1014 # define debug_print_strings(prefix, vv) ((void)0)
1018 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1021 static void *xxmalloc(int lineno, size_t size)
1023 void *ptr = xmalloc((size + 0xff) & ~0xff);
1024 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1027 static void *xxrealloc(int lineno, void *ptr, size_t size)
1029 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1030 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1033 static char *xxstrdup(int lineno, const char *str)
1035 char *ptr = xstrdup(str);
1036 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1039 static void xxfree(void *ptr)
1041 fdprintf(2, "free %p\n", ptr);
1044 # define xmalloc(s) xxmalloc(__LINE__, s)
1045 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1046 # define xstrdup(s) xxstrdup(__LINE__, s)
1047 # define free(p) xxfree(p)
1051 /* Syntax and runtime errors. They always abort scripts.
1052 * In interactive use they usually discard unparsed and/or unexecuted commands
1053 * and return to the prompt.
1054 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1057 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1058 # define syntax_error(lineno, msg) syntax_error(msg)
1059 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1060 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1061 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1062 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1065 static void die_if_script(unsigned lineno, const char *fmt, ...)
1070 bb_error_msg("hush.c:%u", lineno);
1073 bb_verror_msg(fmt, p, NULL);
1075 if (!G_interactive_fd)
1079 static void syntax_error(unsigned lineno, const char *msg)
1082 die_if_script(lineno, "syntax error: %s", msg);
1084 die_if_script(lineno, "syntax error", NULL);
1087 static void syntax_error_at(unsigned lineno, const char *msg)
1089 die_if_script(lineno, "syntax error at '%s'", msg);
1092 static void syntax_error_unterm_str(unsigned lineno, const char *s)
1094 die_if_script(lineno, "syntax error: unterminated %s", s);
1097 /* It so happens that all such cases are totally fatal
1098 * even if shell is interactive: EOF while looking for closing
1099 * delimiter. There is nowhere to read stuff from after that,
1100 * it's EOF! The only choice is to terminate.
1102 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
1103 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1105 char msg[2] = { ch, '\0' };
1106 syntax_error_unterm_str(lineno, msg);
1110 static void syntax_error_unexpected_ch(unsigned lineno, int ch)
1115 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1119 # undef die_if_script
1120 # undef syntax_error
1121 # undef syntax_error_at
1122 # undef syntax_error_unterm_ch
1123 # undef syntax_error_unterm_str
1124 # undef syntax_error_unexpected_ch
1126 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1127 # define syntax_error(msg) syntax_error(__LINE__, msg)
1128 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1129 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1130 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1131 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1135 #if ENABLE_HUSH_INTERACTIVE
1136 static void cmdedit_update_prompt(void);
1138 # define cmdedit_update_prompt() ((void)0)
1142 /* Utility functions
1144 /* Replace each \x with x in place, return ptr past NUL. */
1145 static char *unbackslash(char *src)
1147 char *dst = src = strchrnul(src, '\\');
1151 if ((*dst++ = *src++) == '\0')
1157 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1178 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1179 v[count1 + count2] = NULL;
1182 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1186 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1188 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1189 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1192 #define add_strings_to_strings(strings, add, need_to_dup) \
1193 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1196 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1197 static char **add_string_to_strings(char **strings, char *add)
1202 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1205 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1207 char **ptr = add_string_to_strings(strings, add);
1208 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1211 #define add_string_to_strings(strings, add) \
1212 xx_add_string_to_strings(__LINE__, strings, add)
1215 static void free_strings(char **strings)
1230 /* Helpers for setting new $n and restoring them back
1232 typedef struct save_arg_t {
1236 smallint sv_g_malloced;
1239 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1243 sv->sv_argv0 = argv[0];
1244 sv->sv_g_argv = G.global_argv;
1245 sv->sv_g_argc = G.global_argc;
1246 sv->sv_g_malloced = G.global_args_malloced;
1248 argv[0] = G.global_argv[0]; /* retain $0 */
1249 G.global_argv = argv;
1250 G.global_args_malloced = 0;
1258 static void restore_G_args(save_arg_t *sv, char **argv)
1262 if (G.global_args_malloced) {
1263 /* someone ran "set -- arg1 arg2 ...", undo */
1265 while (*++pp) /* note: does not free $0 */
1267 free(G.global_argv);
1269 argv[0] = sv->sv_argv0;
1270 G.global_argv = sv->sv_g_argv;
1271 G.global_argc = sv->sv_g_argc;
1272 G.global_args_malloced = sv->sv_g_malloced;
1276 /* Basic theory of signal handling in shell
1277 * ========================================
1278 * This does not describe what hush does, rather, it is current understanding
1279 * what it _should_ do. If it doesn't, it's a bug.
1280 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1282 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1283 * is finished or backgrounded. It is the same in interactive and
1284 * non-interactive shells, and is the same regardless of whether
1285 * a user trap handler is installed or a shell special one is in effect.
1286 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1287 * backgrounds (i.e. stops) or kills all members of currently running
1290 * Wait builtin in interruptible by signals for which user trap is set
1291 * or by SIGINT in interactive shell.
1293 * Trap handlers will execute even within trap handlers. (right?)
1295 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1296 * except for handlers set to '' (empty string).
1298 * If job control is off, backgrounded commands ("cmd &")
1299 * have SIGINT, SIGQUIT set to SIG_IGN.
1301 * Commands which are run in command substitution ("`cmd`")
1302 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1304 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1305 * by the shell from its parent.
1307 * Signals which differ from SIG_DFL action
1308 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1311 * SIGTERM (interactive): ignore
1312 * SIGHUP (interactive):
1313 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1314 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1315 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1316 * that all pipe members are stopped. Try this in bash:
1317 * while :; do :; done - ^Z does not background it
1318 * (while :; do :; done) - ^Z backgrounds it
1319 * SIGINT (interactive): wait for last pipe, ignore the rest
1320 * of the command line, show prompt. NB: ^C does not send SIGINT
1321 * to interactive shell while shell is waiting for a pipe,
1322 * since shell is bg'ed (is not in foreground process group).
1323 * Example 1: this waits 5 sec, but does not execute ls:
1324 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1325 * Example 2: this does not wait and does not execute ls:
1326 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1327 * Example 3: this does not wait 5 sec, but executes ls:
1328 * "sleep 5; ls -l" + press ^C
1330 * (What happens to signals which are IGN on shell start?)
1331 * (What happens with signal mask on shell start?)
1333 * Implementation in hush
1334 * ======================
1335 * We use in-kernel pending signal mask to determine which signals were sent.
1336 * We block all signals which we don't want to take action immediately,
1337 * i.e. we block all signals which need to have special handling as described
1338 * above, and all signals which have traps set.
1339 * After each pipe execution, we extract any pending signals via sigtimedwait()
1342 * unsigned non_DFL_mask: a mask of such "special" signals
1343 * sigset_t blocked_set: current blocked signal set
1346 * clear bit in blocked_set unless it is also in non_DFL_mask
1347 * "trap 'cmd' SIGxxx":
1348 * set bit in blocked_set (even if 'cmd' is '')
1349 * after [v]fork, if we plan to be a shell:
1350 * unblock signals with special interactive handling
1351 * (child shell is not interactive),
1352 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1353 * after [v]fork, if we plan to exec:
1354 * POSIX says fork clears pending signal mask in child - no need to clear it.
1355 * Restore blocked signal set to one inherited by shell just prior to exec.
1357 * Note: as a result, we do not use signal handlers much. The only uses
1358 * are to count SIGCHLDs
1359 * and to restore tty pgrp on signal-induced exit.
1362 * Standard says "When a subshell is entered, traps that are not being ignored
1363 * are set to the default actions". bash interprets it so that traps which
1364 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1367 SPECIAL_INTERACTIVE_SIGS = 0
1372 SPECIAL_JOB_SIGS = 0
1380 #if ENABLE_HUSH_FAST
1381 static void SIGCHLD_handler(int sig UNUSED_PARAM)
1384 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1390 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1391 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1392 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1393 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1395 /* Restores tty foreground process group, and exits.
1396 * May be called as signal handler for fatal signal
1397 * (will resend signal to itself, producing correct exit state)
1398 * or called directly with -EXITCODE.
1399 * We also call it if xfunc is exiting. */
1400 static void sigexit(int sig) NORETURN;
1401 static void sigexit(int sig)
1403 /* Disable all signals: job control, SIGPIPE, etc. */
1404 sigprocmask_allsigs(SIG_BLOCK);
1406 /* Careful: we can end up here after [v]fork. Do not restore
1407 * tty pgrp then, only top-level shell process does that */
1408 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1409 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1411 /* Not a signal, just exit */
1415 kill_myself_with_sig(sig); /* does not return */
1419 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1420 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1424 /* Restores tty foreground process group, and exits. */
1425 static void hush_exit(int exitcode) NORETURN;
1426 static void hush_exit(int exitcode)
1429 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1430 /* Prevent recursion:
1431 * trap "echo Hi; exit" EXIT; exit
1434 /* argv[0] is unused */
1435 argv[1] = G.traps[0];
1437 G.exiting = 1; /* prevent EXIT trap recursion */
1438 /* Note: G.traps[0] is not cleared!
1439 * "trap" will still show it, if executed
1444 #if ENABLE_FEATURE_CLEAN_UP
1446 struct variable *cur_var;
1447 if (G.cwd != bb_msg_unknown)
1449 cur_var = G.top_var;
1451 struct variable *tmp = cur_var;
1452 if (!cur_var->max_len)
1453 free(cur_var->varstr);
1454 cur_var = cur_var->next;
1462 sigexit(- (exitcode & 0xff));
1469 static int check_and_run_traps(int sig)
1471 /* I want it in rodata, not in bss.
1472 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1473 * initializer. But other compilers may still use bss.
1474 * TODO: find more portable solution.
1476 static const struct timespec zero_timespec = { 0, 0 };
1477 smalluint save_rcode;
1483 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1488 if (G.traps && G.traps[sig]) {
1489 if (G.traps[sig][0]) {
1490 /* We have user-defined handler */
1492 /* argv[0] is unused */
1493 argv[1] = G.traps[sig];
1495 save_rcode = G.last_exitcode;
1497 G.last_exitcode = save_rcode;
1498 } /* else: "" trap, ignoring signal */
1501 /* not a trap: special action */
1503 #if ENABLE_HUSH_FAST
1506 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1510 /* Builtin was ^C'ed, make it look prettier: */
1517 /* bash is observed to signal whole process groups,
1518 * not individual processes */
1519 for (job = G.job_list; job; job = job->next) {
1522 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1523 if (kill(- job->pgrp, SIGHUP) == 0)
1524 kill(- job->pgrp, SIGCONT);
1529 default: /* ignored: */
1530 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1538 static const char *get_cwd(int force)
1540 if (force || G.cwd == NULL) {
1541 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1542 * we must not try to free(bb_msg_unknown) */
1543 if (G.cwd == bb_msg_unknown)
1545 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1547 G.cwd = bb_msg_unknown;
1554 * Shell and environment variable support
1556 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1558 struct variable **pp;
1559 struct variable *cur;
1562 while ((cur = *pp) != NULL) {
1563 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1570 static const char* FAST_FUNC get_local_var_value(const char *name)
1572 struct variable **vpp;
1573 unsigned len = strlen(name);
1575 if (G.expanded_assignments) {
1576 char **cpp = G.expanded_assignments;
1579 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1580 return cp + len + 1;
1585 vpp = get_ptr_to_local_var(name, len);
1587 return (*vpp)->varstr + len + 1;
1589 if (strcmp(name, "PPID") == 0)
1590 return utoa(G.root_ppid);
1591 // bash compat: UID? EUID?
1592 #if ENABLE_HUSH_RANDOM_SUPPORT
1593 if (strcmp(name, "RANDOM") == 0)
1594 return utoa(next_random(&G.random_gen));
1599 /* str holds "NAME=VAL" and is expected to be malloced.
1600 * We take ownership of it.
1602 * 0: do not change export flag
1603 * (if creating new variable, flag will be 0)
1604 * 1: set export flag and putenv the variable
1605 * -1: clear export flag and unsetenv the variable
1606 * flg_read_only is set only when we handle -R var=val
1608 #if !BB_MMU && ENABLE_HUSH_LOCAL
1609 /* all params are used */
1610 #elif BB_MMU && ENABLE_HUSH_LOCAL
1611 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1612 set_local_var(str, flg_export, local_lvl)
1613 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1614 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1615 set_local_var(str, flg_export)
1616 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1617 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1618 set_local_var(str, flg_export, flg_read_only)
1620 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1622 struct variable **var_pp;
1623 struct variable *cur;
1627 eq_sign = strchr(str, '=');
1628 if (!eq_sign) { /* not expected to ever happen? */
1633 name_len = eq_sign - str + 1; /* including '=' */
1634 var_pp = &G.top_var;
1635 while ((cur = *var_pp) != NULL) {
1636 if (strncmp(cur->varstr, str, name_len) != 0) {
1637 var_pp = &cur->next;
1640 /* We found an existing var with this name */
1641 if (cur->flg_read_only) {
1645 bb_error_msg("%s: readonly variable", str);
1649 if (flg_export == -1) { // "&& cur->flg_export" ?
1650 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1655 #if ENABLE_HUSH_LOCAL
1656 if (cur->func_nest_level < local_lvl) {
1657 /* New variable is declared as local,
1658 * and existing one is global, or local
1659 * from enclosing function.
1660 * Remove and save old one: */
1661 *var_pp = cur->next;
1662 cur->next = *G.shadowed_vars_pp;
1663 *G.shadowed_vars_pp = cur;
1664 /* bash 3.2.33(1) and exported vars:
1666 * # f() { local z=a; env | grep ^z; }
1672 if (cur->flg_export)
1677 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1682 if (cur->max_len != 0) {
1683 if (cur->max_len >= strlen(str)) {
1684 /* This one is from startup env, reuse space */
1685 strcpy(cur->varstr, str);
1689 /* max_len == 0 signifies "malloced" var, which we can
1690 * (and has to) free */
1694 goto set_str_and_exp;
1697 /* Not found - create new variable struct */
1698 cur = xzalloc(sizeof(*cur));
1699 #if ENABLE_HUSH_LOCAL
1700 cur->func_nest_level = local_lvl;
1702 cur->next = *var_pp;
1708 cur->flg_read_only = flg_read_only;
1711 if (flg_export == 1)
1712 cur->flg_export = 1;
1713 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1714 cmdedit_update_prompt();
1715 if (cur->flg_export) {
1716 if (flg_export == -1) {
1717 cur->flg_export = 0;
1718 /* unsetenv was already done */
1720 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1721 return putenv(cur->varstr);
1727 /* Used at startup and after each cd */
1728 static void set_pwd_var(int exp)
1730 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1731 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1734 static int unset_local_var_len(const char *name, int name_len)
1736 struct variable *cur;
1737 struct variable **var_pp;
1740 return EXIT_SUCCESS;
1741 var_pp = &G.top_var;
1742 while ((cur = *var_pp) != NULL) {
1743 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1744 if (cur->flg_read_only) {
1745 bb_error_msg("%s: readonly variable", name);
1746 return EXIT_FAILURE;
1748 *var_pp = cur->next;
1749 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1750 bb_unsetenv(cur->varstr);
1751 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1752 cmdedit_update_prompt();
1756 return EXIT_SUCCESS;
1758 var_pp = &cur->next;
1760 return EXIT_SUCCESS;
1763 static int unset_local_var(const char *name)
1765 return unset_local_var_len(name, strlen(name));
1768 static void unset_vars(char **strings)
1776 const char *eq = strchrnul(*v, '=');
1777 unset_local_var_len(*v, (int)(eq - *v));
1783 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1785 char *var = xasprintf("%s=%s", name, val);
1786 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1791 * Helpers for "var1=val1 var2=val2 cmd" feature
1793 static void add_vars(struct variable *var)
1795 struct variable *next;
1799 var->next = G.top_var;
1801 if (var->flg_export) {
1802 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1803 putenv(var->varstr);
1805 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1811 static struct variable *set_vars_and_save_old(char **strings)
1814 struct variable *old = NULL;
1820 struct variable *var_p;
1821 struct variable **var_pp;
1824 eq = strchr(*s, '=');
1826 var_pp = get_ptr_to_local_var(*s, eq - *s);
1828 /* Remove variable from global linked list */
1830 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1831 *var_pp = var_p->next;
1832 /* Add it to returned list */
1836 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1847 static int FAST_FUNC static_get(struct in_str *i)
1857 static int FAST_FUNC static_peek(struct in_str *i)
1862 #if ENABLE_HUSH_INTERACTIVE
1864 static void cmdedit_update_prompt(void)
1866 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1867 G.PS1 = get_local_var_value("PS1");
1870 G.PS2 = get_local_var_value("PS2");
1878 static const char *setup_prompt_string(int promptmode)
1880 const char *prompt_str;
1881 debug_printf("setup_prompt_string %d ", promptmode);
1882 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1883 /* Set up the prompt */
1884 if (promptmode == 0) { /* PS1 */
1886 /* bash uses $PWD value, even if it is set by user.
1887 * It uses current dir only if PWD is unset.
1888 * We always use current dir. */
1889 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1894 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1895 debug_printf("result '%s'\n", prompt_str);
1899 static void get_user_input(struct in_str *i)
1902 const char *prompt_str;
1904 prompt_str = setup_prompt_string(i->promptmode);
1905 # if ENABLE_FEATURE_EDITING
1906 /* Enable command line editing only while a command line
1907 * is actually being read */
1910 /* buglet: SIGINT will not make new prompt to appear _at once_,
1911 * only after <Enter>. (^C will work) */
1912 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
1913 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1914 check_and_run_traps(0);
1915 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1916 i->eof_flag = (r < 0);
1917 if (i->eof_flag) { /* EOF/error detected */
1918 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1919 G.user_input_buf[1] = '\0';
1924 fputs(prompt_str, stdout);
1926 G.user_input_buf[0] = r = fgetc(i->file);
1927 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1928 //do we need check_and_run_traps(0)? (maybe only if stdin)
1929 } while (G.flag_SIGINT);
1930 i->eof_flag = (r == EOF);
1932 i->p = G.user_input_buf;
1935 #endif /* INTERACTIVE */
1937 /* This is the magic location that prints prompts
1938 * and gets data back from the user */
1939 static int FAST_FUNC file_get(struct in_str *i)
1943 /* If there is data waiting, eat it up */
1944 if (i->p && *i->p) {
1945 #if ENABLE_HUSH_INTERACTIVE
1949 if (i->eof_flag && !*i->p)
1951 /* note: ch is never NUL */
1953 /* need to double check i->file because we might be doing something
1954 * more complicated by now, like sourcing or substituting. */
1955 #if ENABLE_HUSH_INTERACTIVE
1956 if (G_interactive_fd && i->file == stdin) {
1959 } while (!*i->p); /* need non-empty line */
1960 i->promptmode = 1; /* PS2 */
1964 do ch = fgetc(i->file); while (ch == '\0');
1966 debug_printf("file_get: got '%c' %d\n", ch, ch);
1970 /* All callers guarantee this routine will never
1971 * be used right after a newline, so prompting is not needed.
1973 static int FAST_FUNC file_peek(struct in_str *i)
1976 if (i->p && *i->p) {
1977 if (i->eof_flag && !i->p[1])
1980 /* note: ch is never NUL */
1982 do ch = fgetc(i->file); while (ch == '\0');
1983 i->eof_flag = (ch == EOF);
1984 i->peek_buf[0] = ch;
1985 i->peek_buf[1] = '\0';
1987 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1991 static void setup_file_in_str(struct in_str *i, FILE *f)
1993 memset(i, 0, sizeof(*i));
1994 i->peek = file_peek;
1996 /* i->promptmode = 0; - PS1 (memset did it) */
2001 static void setup_string_in_str(struct in_str *i, const char *s)
2003 memset(i, 0, sizeof(*i));
2004 i->peek = static_peek;
2005 i->get = static_get;
2006 /* i->promptmode = 0; - PS1 (memset did it) */
2008 /* i->eof_flag = 0; */
2015 #define B_CHUNK (32 * sizeof(char*))
2017 static void o_reset_to_empty_unquoted(o_string *o)
2020 o->has_quoted_part = 0;
2025 static void o_free(o_string *o)
2028 memset(o, 0, sizeof(*o));
2031 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2036 static void o_grow_by(o_string *o, int len)
2038 if (o->length + len > o->maxlen) {
2039 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2040 o->data = xrealloc(o->data, 1 + o->maxlen);
2044 static void o_addchr(o_string *o, int ch)
2046 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2048 o->data[o->length] = ch;
2050 o->data[o->length] = '\0';
2053 static void o_addblock(o_string *o, const char *str, int len)
2056 memcpy(&o->data[o->length], str, len);
2058 o->data[o->length] = '\0';
2061 static void o_addstr(o_string *o, const char *str)
2063 o_addblock(o, str, strlen(str));
2067 static void nommu_addchr(o_string *o, int ch)
2073 # define nommu_addchr(o, str) ((void)0)
2076 static void o_addstr_with_NUL(o_string *o, const char *str)
2078 o_addblock(o, str, strlen(str) + 1);
2082 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2083 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2084 * Apparently, on unquoted $v bash still does globbing
2085 * ("v='*.txt'; echo $v" prints all .txt files),
2086 * but NOT brace expansion! Thus, there should be TWO independent
2087 * quoting mechanisms on $v expansion side: one protects
2088 * $v from brace expansion, and other additionally protects "$v" against globbing.
2089 * We have only second one.
2092 #if ENABLE_HUSH_BRACE_EXPANSION
2093 # define MAYBE_BRACES "{}"
2095 # define MAYBE_BRACES ""
2098 /* My analysis of quoting semantics tells me that state information
2099 * is associated with a destination, not a source.
2101 static void o_addqchr(o_string *o, int ch)
2104 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2109 o->data[o->length] = '\\';
2112 o->data[o->length] = ch;
2114 o->data[o->length] = '\0';
2117 static void o_addQchr(o_string *o, int ch)
2120 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2121 && strchr("*?[\\" MAYBE_BRACES, ch)
2124 o->data[o->length] = '\\';
2128 o->data[o->length] = ch;
2130 o->data[o->length] = '\0';
2133 static void o_addqblock(o_string *o, const char *str, int len)
2138 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2139 if (ordinary_cnt > len) /* paranoia */
2141 o_addblock(o, str, ordinary_cnt);
2142 if (ordinary_cnt == len)
2144 str += ordinary_cnt;
2145 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2149 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2151 o->data[o->length] = '\\';
2155 o->data[o->length] = ch;
2157 o->data[o->length] = '\0';
2161 static void o_addQblock(o_string *o, const char *str, int len)
2163 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2164 o_addblock(o, str, len);
2167 o_addqblock(o, str, len);
2170 static void o_addQstr(o_string *o, const char *str)
2172 o_addQblock(o, str, strlen(str));
2175 /* A special kind of o_string for $VAR and `cmd` expansion.
2176 * It contains char* list[] at the beginning, which is grown in 16 element
2177 * increments. Actual string data starts at the next multiple of 16 * (char*).
2178 * list[i] contains an INDEX (int!) into this string data.
2179 * It means that if list[] needs to grow, data needs to be moved higher up
2180 * but list[i]'s need not be modified.
2181 * NB: remembering how many list[i]'s you have there is crucial.
2182 * o_finalize_list() operation post-processes this structure - calculates
2183 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2185 #if DEBUG_EXPAND || DEBUG_GLOB
2186 static void debug_print_list(const char *prefix, o_string *o, int n)
2188 char **list = (char**)o->data;
2189 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2193 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2194 prefix, list, n, string_start, o->length, o->maxlen,
2195 !!(o->o_expflags & EXP_FLAG_GLOB),
2197 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2200 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2201 o->data + (int)(uintptr_t)list[i] + string_start,
2202 o->data + (int)(uintptr_t)list[i] + string_start);
2206 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2208 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2212 # define debug_print_list(prefix, o, n) ((void)0)
2215 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2216 * in list[n] so that it points past last stored byte so far.
2217 * It returns n+1. */
2218 static int o_save_ptr_helper(o_string *o, int n)
2220 char **list = (char**)o->data;
2224 if (!o->has_empty_slot) {
2225 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2226 string_len = o->length - string_start;
2227 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2228 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2229 /* list[n] points to string_start, make space for 16 more pointers */
2230 o->maxlen += 0x10 * sizeof(list[0]);
2231 o->data = xrealloc(o->data, o->maxlen + 1);
2232 list = (char**)o->data;
2233 memmove(list + n + 0x10, list + n, string_len);
2234 o->length += 0x10 * sizeof(list[0]);
2236 debug_printf_list("list[%d]=%d string_start=%d\n",
2237 n, string_len, string_start);
2240 /* We have empty slot at list[n], reuse without growth */
2241 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2242 string_len = o->length - string_start;
2243 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2244 n, string_len, string_start);
2245 o->has_empty_slot = 0;
2247 list[n] = (char*)(uintptr_t)string_len;
2251 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2252 static int o_get_last_ptr(o_string *o, int n)
2254 char **list = (char**)o->data;
2255 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2257 return ((int)(uintptr_t)list[n-1]) + string_start;
2260 #if ENABLE_HUSH_BRACE_EXPANSION
2261 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2262 * first, it processes even {a} (no commas), second,
2263 * I didn't manage to make it return strings when they don't match
2264 * existing files. Need to re-implement it.
2268 static int glob_needed(const char *s)
2277 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2283 /* Return pointer to next closing brace or to comma */
2284 static const char *next_brace_sub(const char *cp)
2288 while (*cp != '\0') {
2295 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2301 return *cp != '\0' ? cp : NULL;
2303 /* Recursive brace globber. Note: may garble pattern[]. */
2304 static int glob_brace(char *pattern, o_string *o, int n)
2306 char *new_pattern_buf;
2313 debug_printf_glob("glob_brace('%s')\n", pattern);
2319 if (*begin == '{') {
2320 /* Find the first sub-pattern and at the same time
2321 * find the rest after the closing brace */
2322 next = next_brace_sub(begin);
2324 /* An illegal expression */
2328 /* "{abc}" with no commas - illegal
2329 * brace expr, disregard and skip it */
2335 if (*begin == '\\' && begin[1] != '\0')
2339 debug_printf_glob("begin:%s\n", begin);
2340 debug_printf_glob("next:%s\n", next);
2342 /* Now find the end of the whole brace expression */
2344 while (*rest != '}') {
2345 rest = next_brace_sub(rest);
2347 /* An illegal expression */
2350 debug_printf_glob("rest:%s\n", rest);
2352 rest_len = strlen(++rest) + 1;
2354 /* We are sure the brace expression is well-formed */
2356 /* Allocate working buffer large enough for our work */
2357 new_pattern_buf = xmalloc(strlen(pattern));
2359 /* We have a brace expression. BEGIN points to the opening {,
2360 * NEXT points past the terminator of the first element, and REST
2361 * points past the final }. We will accumulate result names from
2362 * recursive runs for each brace alternative in the buffer using
2367 /* Construct the new glob expression */
2370 mempcpy(new_pattern_buf,
2371 /* We know the prefix for all sub-patterns */
2372 pattern, begin - pattern),
2376 /* Note: glob_brace() may garble new_pattern_buf[].
2377 * That's why we re-copy prefix every time (1st memcpy above).
2379 n = glob_brace(new_pattern_buf, o, n);
2381 /* We saw the last entry */
2385 next = next_brace_sub(next);
2387 free(new_pattern_buf);
2395 memset(&globdata, 0, sizeof(globdata));
2396 gr = glob(pattern, 0, NULL, &globdata);
2397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2399 if (gr == GLOB_NOMATCH) {
2400 globfree(&globdata);
2401 /* NB: garbles parameter */
2402 unbackslash(pattern);
2403 o_addstr_with_NUL(o, pattern);
2404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2405 return o_save_ptr_helper(o, n);
2407 if (gr == GLOB_NOSPACE)
2408 bb_error_msg_and_die(bb_msg_memory_exhausted);
2409 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2410 * but we didn't specify it. Paranoia again. */
2411 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2413 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2414 char **argv = globdata.gl_pathv;
2416 o_addstr_with_NUL(o, *argv);
2417 n = o_save_ptr_helper(o, n);
2423 globfree(&globdata);
2427 /* Performs globbing on last list[],
2428 * saving each result as a new list[].
2430 static int perform_glob(o_string *o, int n)
2432 char *pattern, *copy;
2434 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2436 return o_save_ptr_helper(o, n);
2437 pattern = o->data + o_get_last_ptr(o, n);
2438 debug_printf_glob("glob pattern '%s'\n", pattern);
2439 if (!glob_needed(pattern)) {
2440 /* unbackslash last string in o in place, fix length */
2441 o->length = unbackslash(pattern) - o->data;
2442 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2443 return o_save_ptr_helper(o, n);
2446 copy = xstrdup(pattern);
2447 /* "forget" pattern in o */
2448 o->length = pattern - o->data;
2449 n = glob_brace(copy, o, n);
2452 debug_print_list("perform_glob returning", o, n);
2456 #else /* !HUSH_BRACE_EXPANSION */
2459 static int glob_needed(const char *s)
2468 if (*s == '*' || *s == '[' || *s == '?')
2474 /* Performs globbing on last list[],
2475 * saving each result as a new list[].
2477 static int perform_glob(o_string *o, int n)
2483 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2485 return o_save_ptr_helper(o, n);
2486 pattern = o->data + o_get_last_ptr(o, n);
2487 debug_printf_glob("glob pattern '%s'\n", pattern);
2488 if (!glob_needed(pattern)) {
2490 /* unbackslash last string in o in place, fix length */
2491 o->length = unbackslash(pattern) - o->data;
2492 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2493 return o_save_ptr_helper(o, n);
2496 memset(&globdata, 0, sizeof(globdata));
2497 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2498 * If we glob "*.\*" and don't find anything, we need
2499 * to fall back to using literal "*.*", but GLOB_NOCHECK
2500 * will return "*.\*"!
2502 gr = glob(pattern, 0, NULL, &globdata);
2503 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2505 if (gr == GLOB_NOMATCH) {
2506 globfree(&globdata);
2509 if (gr == GLOB_NOSPACE)
2510 bb_error_msg_and_die(bb_msg_memory_exhausted);
2511 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2512 * but we didn't specify it. Paranoia again. */
2513 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2515 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2516 char **argv = globdata.gl_pathv;
2517 /* "forget" pattern in o */
2518 o->length = pattern - o->data;
2520 o_addstr_with_NUL(o, *argv);
2521 n = o_save_ptr_helper(o, n);
2527 globfree(&globdata);
2529 debug_print_list("perform_glob returning", o, n);
2533 #endif /* !HUSH_BRACE_EXPANSION */
2535 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2536 * Otherwise, just finish current list[] and start new */
2537 static int o_save_ptr(o_string *o, int n)
2539 if (o->o_expflags & EXP_FLAG_GLOB) {
2540 /* If o->has_empty_slot, list[n] was already globbed
2541 * (if it was requested back then when it was filled)
2542 * so don't do that again! */
2543 if (!o->has_empty_slot)
2544 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2546 return o_save_ptr_helper(o, n);
2549 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2550 static char **o_finalize_list(o_string *o, int n)
2555 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2557 debug_print_list("finalized", o, n);
2558 debug_printf_expand("finalized n:%d\n", n);
2559 list = (char**)o->data;
2560 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2564 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2569 static void free_pipe_list(struct pipe *pi);
2571 /* Returns pi->next - next pipe in the list */
2572 static struct pipe *free_pipe(struct pipe *pi)
2577 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2578 for (i = 0; i < pi->num_cmds; i++) {
2579 struct command *command;
2580 struct redir_struct *r, *rnext;
2582 command = &pi->cmds[i];
2583 debug_printf_clean(" command %d:\n", i);
2584 if (command->argv) {
2588 for (a = 0, p = command->argv; *p; a++, p++) {
2589 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2592 free_strings(command->argv);
2593 //command->argv = NULL;
2595 /* not "else if": on syntax error, we may have both! */
2596 if (command->group) {
2597 debug_printf_clean(" begin group (cmd_type:%d)\n",
2599 free_pipe_list(command->group);
2600 debug_printf_clean(" end group\n");
2601 //command->group = NULL;
2603 /* else is crucial here.
2604 * If group != NULL, child_func is meaningless */
2605 #if ENABLE_HUSH_FUNCTIONS
2606 else if (command->child_func) {
2607 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2608 command->child_func->parent_cmd = NULL;
2612 free(command->group_as_string);
2613 //command->group_as_string = NULL;
2615 for (r = command->redirects; r; r = rnext) {
2616 debug_printf_clean(" redirect %d%s",
2617 r->rd_fd, redir_table[r->rd_type].descrip);
2618 /* guard against the case >$FOO, where foo is unset or blank */
2619 if (r->rd_filename) {
2620 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2621 free(r->rd_filename);
2622 //r->rd_filename = NULL;
2624 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2628 //command->redirects = NULL;
2630 free(pi->cmds); /* children are an array, they get freed all at once */
2634 //pi->cmdtext = NULL;
2642 static void free_pipe_list(struct pipe *pi)
2646 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2648 debug_printf_clean("pipe followup code %d\n", pi->followup);
2654 /*** Parsing routines ***/
2656 #ifndef debug_print_tree
2657 static void debug_print_tree(struct pipe *pi, int lvl)
2659 static const char *const PIPE[] = {
2665 static const char *RES[] = {
2666 [RES_NONE ] = "NONE" ,
2669 [RES_THEN ] = "THEN" ,
2670 [RES_ELIF ] = "ELIF" ,
2671 [RES_ELSE ] = "ELSE" ,
2674 # if ENABLE_HUSH_LOOPS
2675 [RES_FOR ] = "FOR" ,
2676 [RES_WHILE] = "WHILE",
2677 [RES_UNTIL] = "UNTIL",
2679 [RES_DONE ] = "DONE" ,
2681 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2684 # if ENABLE_HUSH_CASE
2685 [RES_CASE ] = "CASE" ,
2686 [RES_CASE_IN ] = "CASE_IN" ,
2687 [RES_MATCH] = "MATCH",
2688 [RES_CASE_BODY] = "CASE_BODY",
2689 [RES_ESAC ] = "ESAC" ,
2691 [RES_XXXX ] = "XXXX" ,
2692 [RES_SNTX ] = "SNTX" ,
2694 static const char *const CMDTYPE[] = {
2698 # if ENABLE_HUSH_FUNCTIONS
2707 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2708 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2710 while (prn < pi->num_cmds) {
2711 struct command *command = &pi->cmds[prn];
2712 char **argv = command->argv;
2714 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2716 command->assignment_cnt);
2717 if (command->group) {
2718 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2719 CMDTYPE[command->cmd_type],
2722 , " group_as_string:", command->group_as_string
2727 debug_print_tree(command->group, lvl+1);
2731 if (argv) while (*argv) {
2732 fdprintf(2, " '%s'", *argv);
2742 #endif /* debug_print_tree */
2744 static struct pipe *new_pipe(void)
2747 pi = xzalloc(sizeof(struct pipe));
2748 /*pi->followup = 0; - deliberately invalid value */
2749 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2753 /* Command (member of a pipe) is complete, or we start a new pipe
2754 * if ctx->command is NULL.
2755 * No errors possible here.
2757 static int done_command(struct parse_context *ctx)
2759 /* The command is really already in the pipe structure, so
2760 * advance the pipe counter and make a new, null command. */
2761 struct pipe *pi = ctx->pipe;
2762 struct command *command = ctx->command;
2765 if (IS_NULL_CMD(command)) {
2766 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2770 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2771 //debug_print_tree(ctx->list_head, 20);
2773 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2776 /* Only real trickiness here is that the uncommitted
2777 * command structure is not counted in pi->num_cmds. */
2778 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2779 ctx->command = command = &pi->cmds[pi->num_cmds];
2781 memset(command, 0, sizeof(*command));
2782 return pi->num_cmds; /* used only for 0/nonzero check */
2785 static void done_pipe(struct parse_context *ctx, pipe_style type)
2789 debug_printf_parse("done_pipe entered, followup %d\n", type);
2790 /* Close previous command */
2791 not_null = done_command(ctx);
2792 ctx->pipe->followup = type;
2794 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2795 ctx->ctx_inverted = 0;
2796 ctx->pipe->res_word = ctx->ctx_res_w;
2799 /* Without this check, even just <enter> on command line generates
2800 * tree of three NOPs (!). Which is harmless but annoying.
2801 * IOW: it is safe to do it unconditionally. */
2804 || ctx->ctx_res_w == RES_FI
2806 #if ENABLE_HUSH_LOOPS
2807 || ctx->ctx_res_w == RES_DONE
2808 || ctx->ctx_res_w == RES_FOR
2809 || ctx->ctx_res_w == RES_IN
2811 #if ENABLE_HUSH_CASE
2812 || ctx->ctx_res_w == RES_ESAC
2816 debug_printf_parse("done_pipe: adding new pipe: "
2817 "not_null:%d ctx->ctx_res_w:%d\n",
2818 not_null, ctx->ctx_res_w);
2820 ctx->pipe->next = new_p;
2822 /* RES_THEN, RES_DO etc are "sticky" -
2823 * they remain set for pipes inside if/while.
2824 * This is used to control execution.
2825 * RES_FOR and RES_IN are NOT sticky (needed to support
2826 * cases where variable or value happens to match a keyword):
2828 #if ENABLE_HUSH_LOOPS
2829 if (ctx->ctx_res_w == RES_FOR
2830 || ctx->ctx_res_w == RES_IN)
2831 ctx->ctx_res_w = RES_NONE;
2833 #if ENABLE_HUSH_CASE
2834 if (ctx->ctx_res_w == RES_MATCH)
2835 ctx->ctx_res_w = RES_CASE_BODY;
2836 if (ctx->ctx_res_w == RES_CASE)
2837 ctx->ctx_res_w = RES_CASE_IN;
2839 ctx->command = NULL; /* trick done_command below */
2840 /* Create the memory for command, roughly:
2841 * ctx->pipe->cmds = new struct command;
2842 * ctx->command = &ctx->pipe->cmds[0];
2845 //debug_print_tree(ctx->list_head, 10);
2847 debug_printf_parse("done_pipe return\n");
2850 static void initialize_context(struct parse_context *ctx)
2852 memset(ctx, 0, sizeof(*ctx));
2853 ctx->pipe = ctx->list_head = new_pipe();
2854 /* Create the memory for command, roughly:
2855 * ctx->pipe->cmds = new struct command;
2856 * ctx->command = &ctx->pipe->cmds[0];
2861 /* If a reserved word is found and processed, parse context is modified
2862 * and 1 is returned.
2865 struct reserved_combo {
2868 unsigned char assignment_flag;
2872 FLAG_END = (1 << RES_NONE ),
2874 FLAG_IF = (1 << RES_IF ),
2875 FLAG_THEN = (1 << RES_THEN ),
2876 FLAG_ELIF = (1 << RES_ELIF ),
2877 FLAG_ELSE = (1 << RES_ELSE ),
2878 FLAG_FI = (1 << RES_FI ),
2880 # if ENABLE_HUSH_LOOPS
2881 FLAG_FOR = (1 << RES_FOR ),
2882 FLAG_WHILE = (1 << RES_WHILE),
2883 FLAG_UNTIL = (1 << RES_UNTIL),
2884 FLAG_DO = (1 << RES_DO ),
2885 FLAG_DONE = (1 << RES_DONE ),
2886 FLAG_IN = (1 << RES_IN ),
2888 # if ENABLE_HUSH_CASE
2889 FLAG_MATCH = (1 << RES_MATCH),
2890 FLAG_ESAC = (1 << RES_ESAC ),
2892 FLAG_START = (1 << RES_XXXX ),
2895 static const struct reserved_combo* match_reserved_word(o_string *word)
2897 /* Mostly a list of accepted follow-up reserved words.
2898 * FLAG_END means we are done with the sequence, and are ready
2899 * to turn the compound list into a command.
2900 * FLAG_START means the word must start a new compound list.
2902 static const struct reserved_combo reserved_list[] = {
2904 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2905 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2906 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2907 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2908 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2909 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
2911 # if ENABLE_HUSH_LOOPS
2912 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2913 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2914 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2915 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2916 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2917 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
2919 # if ENABLE_HUSH_CASE
2920 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2921 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
2924 const struct reserved_combo *r;
2926 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2927 if (strcmp(word->data, r->literal) == 0)
2932 /* Return 0: not a keyword, 1: keyword
2934 static int reserved_word(o_string *word, struct parse_context *ctx)
2936 # if ENABLE_HUSH_CASE
2937 static const struct reserved_combo reserved_match = {
2938 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
2941 const struct reserved_combo *r;
2943 if (word->has_quoted_part)
2945 r = match_reserved_word(word);
2949 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2950 # if ENABLE_HUSH_CASE
2951 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2952 /* "case word IN ..." - IN part starts first MATCH part */
2953 r = &reserved_match;
2956 if (r->flag == 0) { /* '!' */
2957 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
2958 syntax_error("! ! command");
2959 ctx->ctx_res_w = RES_SNTX;
2961 ctx->ctx_inverted = 1;
2964 if (r->flag & FLAG_START) {
2965 struct parse_context *old;
2967 old = xmalloc(sizeof(*old));
2968 debug_printf_parse("push stack %p\n", old);
2969 *old = *ctx; /* physical copy */
2970 initialize_context(ctx);
2972 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
2973 syntax_error_at(word->data);
2974 ctx->ctx_res_w = RES_SNTX;
2977 /* "{...} fi" is ok. "{...} if" is not
2979 * if { echo foo; } then { echo bar; } fi */
2980 if (ctx->command->group)
2981 done_pipe(ctx, PIPE_SEQ);
2984 ctx->ctx_res_w = r->res;
2985 ctx->old_flag = r->flag;
2986 word->o_assignment = r->assignment_flag;
2988 if (ctx->old_flag & FLAG_END) {
2989 struct parse_context *old;
2991 done_pipe(ctx, PIPE_SEQ);
2992 debug_printf_parse("pop stack %p\n", ctx->stack);
2994 old->command->group = ctx->list_head;
2995 old->command->cmd_type = CMD_NORMAL;
2997 o_addstr(&old->as_string, ctx->as_string.data);
2998 o_free_unsafe(&ctx->as_string);
2999 old->command->group_as_string = xstrdup(old->as_string.data);
3000 debug_printf_parse("pop, remembering as:'%s'\n",
3001 old->command->group_as_string);
3003 *ctx = *old; /* physical copy */
3008 #endif /* HAS_KEYWORDS */
3010 /* Word is complete, look at it and update parsing context.
3011 * Normal return is 0. Syntax errors return 1.
3012 * Note: on return, word is reset, but not o_free'd!
3014 static int done_word(o_string *word, struct parse_context *ctx)
3016 struct command *command = ctx->command;
3018 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3019 if (word->length == 0 && !word->has_quoted_part) {
3020 debug_printf_parse("done_word return 0: true null, ignored\n");
3024 if (ctx->pending_redirect) {
3025 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3026 * only if run as "bash", not "sh" */
3027 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3029 * ...the word that follows the redirection operator
3030 * shall be subjected to tilde expansion, parameter expansion,
3031 * command substitution, arithmetic expansion, and quote
3032 * removal. Pathname expansion shall not be performed
3033 * on the word by a non-interactive shell; an interactive
3034 * shell may perform it, but shall do so only when
3035 * the expansion would result in one word."
3037 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3038 /* Cater for >\file case:
3039 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3040 * Same with heredocs:
3041 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3043 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3044 unbackslash(ctx->pending_redirect->rd_filename);
3045 /* Is it <<"HEREDOC"? */
3046 if (word->has_quoted_part) {
3047 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3050 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3051 ctx->pending_redirect = NULL;
3053 /* If this word wasn't an assignment, next ones definitely
3054 * can't be assignments. Even if they look like ones. */
3055 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3056 && word->o_assignment != WORD_IS_KEYWORD
3058 word->o_assignment = NOT_ASSIGNMENT;
3060 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3061 command->assignment_cnt++;
3062 word->o_assignment = MAYBE_ASSIGNMENT;
3066 # if ENABLE_HUSH_CASE
3067 if (ctx->ctx_dsemicolon
3068 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3070 /* already done when ctx_dsemicolon was set to 1: */
3071 /* ctx->ctx_res_w = RES_MATCH; */
3072 ctx->ctx_dsemicolon = 0;
3075 if (!command->argv /* if it's the first word... */
3076 # if ENABLE_HUSH_LOOPS
3077 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3078 && ctx->ctx_res_w != RES_IN
3080 # if ENABLE_HUSH_CASE
3081 && ctx->ctx_res_w != RES_CASE
3084 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3085 if (reserved_word(word, ctx)) {
3086 o_reset_to_empty_unquoted(word);
3087 debug_printf_parse("done_word return %d\n",
3088 (ctx->ctx_res_w == RES_SNTX));
3089 return (ctx->ctx_res_w == RES_SNTX);
3091 # if ENABLE_HUSH_BASH_COMPAT
3092 if (strcmp(word->data, "[[") == 0) {
3093 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3099 if (command->group) {
3100 /* "{ echo foo; } echo bar" - bad */
3101 syntax_error_at(word->data);
3102 debug_printf_parse("done_word return 1: syntax error, "
3103 "groups and arglists don't mix\n");
3106 if (word->has_quoted_part
3107 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3108 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3109 /* (otherwise it's known to be not empty and is already safe) */
3111 /* exclude "$@" - it can expand to no word despite "" */
3112 char *p = word->data;
3113 while (p[0] == SPECIAL_VAR_SYMBOL
3114 && (p[1] & 0x7f) == '@'
3115 && p[2] == SPECIAL_VAR_SYMBOL
3119 if (p == word->data || p[0] != '\0') {
3120 /* saw no "$@", or not only "$@" but some
3121 * real text is there too */
3122 /* insert "empty variable" reference, this makes
3123 * e.g. "", $empty"" etc to not disappear */
3124 o_addchr(word, SPECIAL_VAR_SYMBOL);
3125 o_addchr(word, SPECIAL_VAR_SYMBOL);
3128 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3129 debug_print_strings("word appended to argv", command->argv);
3132 #if ENABLE_HUSH_LOOPS
3133 if (ctx->ctx_res_w == RES_FOR) {
3134 if (word->has_quoted_part
3135 || !is_well_formed_var_name(command->argv[0], '\0')
3137 /* bash says just "not a valid identifier" */
3138 syntax_error("not a valid identifier in for");
3141 /* Force FOR to have just one word (variable name) */
3142 /* NB: basically, this makes hush see "for v in ..."
3143 * syntax as if it is "for v; in ...". FOR and IN become
3144 * two pipe structs in parse tree. */
3145 done_pipe(ctx, PIPE_SEQ);
3148 #if ENABLE_HUSH_CASE
3149 /* Force CASE to have just one word */
3150 if (ctx->ctx_res_w == RES_CASE) {
3151 done_pipe(ctx, PIPE_SEQ);
3155 o_reset_to_empty_unquoted(word);
3157 debug_printf_parse("done_word return 0\n");
3162 /* Peek ahead in the input to find out if we have a "&n" construct,
3163 * as in "2>&1", that represents duplicating a file descriptor.
3165 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3166 * REDIRFD_SYNTAX_ERR if syntax error,
3167 * REDIRFD_TO_FILE if no & was seen,
3168 * or the number found.
3171 #define parse_redir_right_fd(as_string, input) \
3172 parse_redir_right_fd(input)
3174 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3180 return REDIRFD_TO_FILE;
3182 ch = i_getch(input); /* get the & */
3183 nommu_addchr(as_string, ch);
3186 ch = i_getch(input);
3187 nommu_addchr(as_string, ch);
3188 return REDIRFD_CLOSE;
3192 while (ch != EOF && isdigit(ch)) {
3193 d = d*10 + (ch-'0');
3195 ch = i_getch(input);
3196 nommu_addchr(as_string, ch);
3201 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3203 bb_error_msg("ambiguous redirect");
3204 return REDIRFD_SYNTAX_ERR;
3207 /* Return code is 0 normal, 1 if a syntax error is detected
3209 static int parse_redirect(struct parse_context *ctx,
3212 struct in_str *input)
3214 struct command *command = ctx->command;
3215 struct redir_struct *redir;
3216 struct redir_struct **redirp;
3219 dup_num = REDIRFD_TO_FILE;
3220 if (style != REDIRECT_HEREDOC) {
3221 /* Check for a '>&1' type redirect */
3222 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3223 if (dup_num == REDIRFD_SYNTAX_ERR)
3226 int ch = i_peek(input);
3227 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3228 if (dup_num) { /* <<-... */
3229 ch = i_getch(input);
3230 nommu_addchr(&ctx->as_string, ch);
3235 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3236 int ch = i_peek(input);
3238 /* >|FILE redirect ("clobbering" >).
3239 * Since we do not support "set -o noclobber" yet,
3240 * >| and > are the same for now. Just eat |.
3242 ch = i_getch(input);
3243 nommu_addchr(&ctx->as_string, ch);
3247 /* Create a new redir_struct and append it to the linked list */
3248 redirp = &command->redirects;
3249 while ((redir = *redirp) != NULL) {
3250 redirp = &(redir->next);
3252 *redirp = redir = xzalloc(sizeof(*redir));
3253 /* redir->next = NULL; */
3254 /* redir->rd_filename = NULL; */
3255 redir->rd_type = style;
3256 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3258 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3259 redir_table[style].descrip);
3261 redir->rd_dup = dup_num;
3262 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3263 /* Erik had a check here that the file descriptor in question
3264 * is legit; I postpone that to "run time"
3265 * A "-" representation of "close me" shows up as a -3 here */
3266 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3267 redir->rd_fd, redir->rd_dup);
3269 /* Set ctx->pending_redirect, so we know what to do at the
3270 * end of the next parsed word. */
3271 ctx->pending_redirect = redir;
3276 /* If a redirect is immediately preceded by a number, that number is
3277 * supposed to tell which file descriptor to redirect. This routine
3278 * looks for such preceding numbers. In an ideal world this routine
3279 * needs to handle all the following classes of redirects...
3280 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3281 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3282 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3283 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3285 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3287 * ... If n is quoted, the number shall not be recognized as part of
3288 * the redirection expression. For example:
3290 * writes the character 2 into file a"
3291 * We are getting it right by setting ->has_quoted_part on any \<char>
3293 * A -1 return means no valid number was found,
3294 * the caller should use the appropriate default for this redirection.
3296 static int redirect_opt_num(o_string *o)
3300 if (o->data == NULL)
3302 num = bb_strtou(o->data, NULL, 10);
3303 if (errno || num < 0)
3305 o_reset_to_empty_unquoted(o);
3310 #define fetch_till_str(as_string, input, word, skip_tabs) \
3311 fetch_till_str(input, word, skip_tabs)
3313 static char *fetch_till_str(o_string *as_string,
3314 struct in_str *input,
3318 o_string heredoc = NULL_O_STRING;
3320 int prev = 0; /* not \ */
3325 ch = i_getch(input);
3327 nommu_addchr(as_string, ch);
3328 if ((ch == '\n' || ch == EOF)
3329 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3331 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3332 heredoc.data[past_EOL] = '\0';
3333 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3334 return heredoc.data;
3336 while (ch == '\n') {
3337 o_addchr(&heredoc, ch);
3340 past_EOL = heredoc.length;
3342 ch = i_getch(input);
3344 nommu_addchr(as_string, ch);
3345 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3349 o_free_unsafe(&heredoc);
3352 o_addchr(&heredoc, ch);
3353 nommu_addchr(as_string, ch);
3354 if (prev == '\\' && ch == '\\')
3355 /* Correctly handle foo\\<eol> (not a line cont.) */
3356 prev = 0; /* not \ */
3362 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3363 * and load them all. There should be exactly heredoc_cnt of them.
3365 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3367 struct pipe *pi = ctx->list_head;
3369 while (pi && heredoc_cnt) {
3371 struct command *cmd = pi->cmds;
3373 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3375 cmd->argv ? cmd->argv[0] : "NONE");
3376 for (i = 0; i < pi->num_cmds; i++) {
3377 struct redir_struct *redir = cmd->redirects;
3379 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3380 i, cmd->argv ? cmd->argv[0] : "NONE");
3382 if (redir->rd_type == REDIRECT_HEREDOC) {
3385 redir->rd_type = REDIRECT_HEREDOC2;
3386 /* redir->rd_dup is (ab)used to indicate <<- */
3387 p = fetch_till_str(&ctx->as_string, input,
3388 redir->rd_filename, redir->rd_dup);
3390 syntax_error("unexpected EOF in here document");
3393 free(redir->rd_filename);
3394 redir->rd_filename = p;
3397 redir = redir->next;
3404 /* Should be 0. If it isn't, it's a parse error */
3406 bb_error_msg_and_die("heredoc BUG 2");
3412 static int run_list(struct pipe *pi);
3414 #define parse_stream(pstring, input, end_trigger) \
3415 parse_stream(input, end_trigger)
3417 static struct pipe *parse_stream(char **pstring,
3418 struct in_str *input,
3422 #if !ENABLE_HUSH_FUNCTIONS
3423 #define parse_group(dest, ctx, input, ch) \
3424 parse_group(ctx, input, ch)
3426 static int parse_group(o_string *dest, struct parse_context *ctx,
3427 struct in_str *input, int ch)
3429 /* dest contains characters seen prior to ( or {.
3430 * Typically it's empty, but for function defs,
3431 * it contains function name (without '()'). */
3432 struct pipe *pipe_list;
3434 struct command *command = ctx->command;
3436 debug_printf_parse("parse_group entered\n");
3437 #if ENABLE_HUSH_FUNCTIONS
3438 if (ch == '(' && !dest->has_quoted_part) {
3440 if (done_word(dest, ctx))
3443 goto skip; /* (... */
3444 if (command->argv[1]) { /* word word ... (... */
3445 syntax_error_unexpected_ch('(');
3448 /* it is "word(..." or "word (..." */
3450 ch = i_getch(input);
3451 while (ch == ' ' || ch == '\t');
3453 syntax_error_unexpected_ch(ch);
3456 nommu_addchr(&ctx->as_string, ch);
3458 ch = i_getch(input);
3459 while (ch == ' ' || ch == '\t' || ch == '\n');
3461 syntax_error_unexpected_ch(ch);
3464 nommu_addchr(&ctx->as_string, ch);
3465 command->cmd_type = CMD_FUNCDEF;
3470 #if 0 /* Prevented by caller */
3471 if (command->argv /* word [word]{... */
3472 || dest->length /* word{... */
3473 || dest->has_quoted_part /* ""{... */
3476 debug_printf_parse("parse_group return 1: "
3477 "syntax error, groups and arglists don't mix\n");
3482 #if ENABLE_HUSH_FUNCTIONS
3488 command->cmd_type = CMD_SUBSHELL;
3490 /* bash does not allow "{echo...", requires whitespace */
3491 ch = i_getch(input);
3492 if (ch != ' ' && ch != '\t' && ch != '\n') {
3493 syntax_error_unexpected_ch(ch);
3496 nommu_addchr(&ctx->as_string, ch);
3501 # define as_string NULL
3503 char *as_string = NULL;
3505 pipe_list = parse_stream(&as_string, input, endch);
3508 o_addstr(&ctx->as_string, as_string);
3510 /* empty ()/{} or parse error? */
3511 if (!pipe_list || pipe_list == ERR_PTR) {
3512 /* parse_stream already emitted error msg */
3515 debug_printf_parse("parse_group return 1: "
3516 "parse_stream returned %p\n", pipe_list);
3519 command->group = pipe_list;
3521 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3522 command->group_as_string = as_string;
3523 debug_printf_parse("end of group, remembering as:'%s'\n",
3524 command->group_as_string);
3528 debug_printf_parse("parse_group return 0\n");
3530 /* command remains "open", available for possible redirects */
3533 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3534 /* Subroutines for copying $(...) and `...` things */
3535 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3537 static void add_till_single_quote(o_string *dest, struct in_str *input)
3540 int ch = i_getch(input);
3542 syntax_error_unterm_ch('\'');
3543 /*xfunc_die(); - redundant */
3550 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3551 static void add_till_double_quote(o_string *dest, struct in_str *input)
3554 int ch = i_getch(input);
3556 syntax_error_unterm_ch('"');
3557 /*xfunc_die(); - redundant */
3561 if (ch == '\\') { /* \x. Copy both chars. */
3563 ch = i_getch(input);
3567 add_till_backquote(dest, input, /*in_dquote:*/ 1);
3571 //if (ch == '$') ...
3574 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3576 * "Within the backquoted style of command substitution, backslash
3577 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3578 * The search for the matching backquote shall be satisfied by the first
3579 * backquote found without a preceding backslash; during this search,
3580 * if a non-escaped backquote is encountered within a shell comment,
3581 * a here-document, an embedded command substitution of the $(command)
3582 * form, or a quoted string, undefined results occur. A single-quoted
3583 * or double-quoted string that begins, but does not end, within the
3584 * "`...`" sequence produces undefined results."
3586 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3588 static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3591 int ch = i_getch(input);
3595 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3596 ch = i_getch(input);
3600 && (!in_dquote || ch != '"')
3602 o_addchr(dest, '\\');
3606 syntax_error_unterm_ch('`');
3607 /*xfunc_die(); - redundant */
3612 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3613 * quoting and nested ()s.
3614 * "With the $(command) style of command substitution, all characters
3615 * following the open parenthesis to the matching closing parenthesis
3616 * constitute the command. Any valid shell script can be used for command,
3617 * except a script consisting solely of redirections which produces
3618 * unspecified results."
3620 * echo $(echo '(TEST)' BEST) (TEST) BEST
3621 * echo $(echo 'TEST)' BEST) TEST) BEST
3622 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3624 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3625 * can contain arbitrary constructs, just like $(cmd).
3626 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3627 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3629 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3630 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3633 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3634 # if ENABLE_HUSH_BASH_COMPAT
3635 char end_char2 = end_ch >> 8;
3637 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3640 ch = i_getch(input);
3642 syntax_error_unterm_ch(end_ch);
3643 /*xfunc_die(); - redundant */
3645 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3648 /* we look for closing )) of $((EXPR)) */
3649 if (i_peek(input) == end_ch) {
3650 i_getch(input); /* eat second ')' */
3655 if (ch == '(' || ch == '{') {
3656 ch = (ch == '(' ? ')' : '}');
3657 add_till_closing_bracket(dest, input, ch);
3662 add_till_single_quote(dest, input);
3667 add_till_double_quote(dest, input);
3672 add_till_backquote(dest, input, /*in_dquote:*/ 0);
3677 /* \x. Copy verbatim. Important for \(, \) */
3678 ch = i_getch(input);
3680 syntax_error_unterm_ch(')');
3681 /*xfunc_die(); - redundant */
3689 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3691 /* Return code: 0 for OK, 1 for syntax error */
3693 #define parse_dollar(as_string, dest, input, quote_mask) \
3694 parse_dollar(dest, input, quote_mask)
3695 #define as_string NULL
3697 static int parse_dollar(o_string *as_string,
3699 struct in_str *input, unsigned char quote_mask)
3701 int ch = i_peek(input); /* first character after the $ */
3703 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3705 ch = i_getch(input);
3706 nommu_addchr(as_string, ch);
3708 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3710 debug_printf_parse(": '%c'\n", ch);
3711 o_addchr(dest, ch | quote_mask);
3714 if (!isalnum(ch) && ch != '_')
3716 ch = i_getch(input);
3717 nommu_addchr(as_string, ch);
3719 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3720 } else if (isdigit(ch)) {
3722 ch = i_getch(input);
3723 nommu_addchr(as_string, ch);
3724 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3725 debug_printf_parse(": '%c'\n", ch);
3726 o_addchr(dest, ch | quote_mask);
3727 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3728 } else switch (ch) {
3730 case '!': /* last bg pid */
3731 case '?': /* last exit code */
3732 case '#': /* number of args */
3733 case '*': /* args */
3734 case '@': /* args */
3735 goto make_one_char_var;
3737 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3739 ch = i_getch(input); /* eat '{' */
3740 nommu_addchr(as_string, ch);
3742 ch = i_getch(input); /* first char after '{' */
3743 /* It should be ${?}, or ${#var},
3744 * or even ${?+subst} - operator acting on a special variable,
3745 * or the beginning of variable name.
3748 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3751 syntax_error_unterm_str("${name}");
3752 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
3755 nommu_addchr(as_string, ch);
3758 /* It's possible to just call add_till_closing_bracket() at this point.
3759 * However, this regresses some of our testsuite cases
3760 * which check invalid constructs like ${%}.
3761 * Oh well... let's check that the var name part is fine... */
3767 debug_printf_parse(": '%c'\n", ch);
3769 ch = i_getch(input);
3770 nommu_addchr(as_string, ch);
3774 if (!isalnum(ch) && ch != '_') {
3776 unsigned char last_ch;
3777 /* handle parameter expansions
3778 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3780 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3781 goto bad_dollar_syntax;
3783 /* Eat everything until closing '}' (or ':') */
3785 if (ENABLE_HUSH_BASH_COMPAT
3787 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3789 /* It's ${var:N[:M]} thing */
3790 end_ch = '}' * 0x100 + ':';
3792 if (ENABLE_HUSH_BASH_COMPAT
3795 /* It's ${var/[/]pattern[/repl]} thing */
3796 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3798 nommu_addchr(as_string, '/');
3801 end_ch = '}' * 0x100 + '/';
3807 #if ENABLE_HUSH_DOLLAR_OPS
3808 last_ch = add_till_closing_bracket(dest, input, end_ch);
3810 #error Simple code to only allow ${var} is not implemented
3813 o_addstr(as_string, dest->data + pos);
3814 o_addchr(as_string, last_ch);
3817 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3818 /* close the first block: */
3819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3820 /* while parsing N from ${var:N[:M]}
3821 * or pattern from ${var/[/]pattern[/repl]} */
3822 if ((end_ch & 0xff) == last_ch) {
3823 /* got ':' or '/'- parse the rest */
3828 if (end_ch == '}' * 0x100 + ':') {
3829 /* it's ${var:N} - emulate :999999999 */
3830 o_addstr(dest, "999999999");
3831 } /* else: it's ${var/[/]pattern} */
3836 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3839 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3843 ch = i_getch(input);
3844 nommu_addchr(as_string, ch);
3845 # if ENABLE_SH_MATH_SUPPORT
3846 if (i_peek(input) == '(') {
3847 ch = i_getch(input);
3848 nommu_addchr(as_string, ch);
3849 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3850 o_addchr(dest, /*quote_mask |*/ '+');
3853 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
3855 o_addstr(as_string, dest->data + pos);
3856 o_addchr(as_string, ')');
3857 o_addchr(as_string, ')');
3859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3863 # if ENABLE_HUSH_TICK
3864 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3865 o_addchr(dest, quote_mask | '`');
3868 add_till_closing_bracket(dest, input, ')');
3870 o_addstr(as_string, dest->data + pos);
3871 o_addchr(as_string, ')');
3873 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3879 ch = i_getch(input);
3880 nommu_addchr(as_string, ch);
3882 if (isalnum(ch)) { /* it's $_name or $_123 */
3887 /* TODO: $_ and $-: */
3888 /* $_ Shell or shell script name; or last argument of last command
3889 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3890 * but in command's env, set to full pathname used to invoke it */
3891 /* $- Option flags set by set builtin or shell options (-i etc) */
3893 o_addQchr(dest, '$');
3895 debug_printf_parse("parse_dollar return 0\n");
3901 # if ENABLE_HUSH_BASH_COMPAT
3902 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3903 encode_string(dest, input, dquote_end, process_bkslash)
3905 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
3906 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3907 encode_string(dest, input, dquote_end)
3909 #define as_string NULL
3913 # if ENABLE_HUSH_BASH_COMPAT
3914 /* all parameters are needed, no macro tricks */
3916 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3917 encode_string(as_string, dest, input, dquote_end)
3920 static int encode_string(o_string *as_string,
3922 struct in_str *input,
3924 int process_bkslash)
3926 #if !ENABLE_HUSH_BASH_COMPAT
3927 const int process_bkslash = 1;
3933 ch = i_getch(input);
3935 nommu_addchr(as_string, ch);
3936 if (ch == dquote_end) { /* may be only '"' or EOF */
3937 debug_printf_parse("encode_string return 0\n");
3940 /* note: can't move it above ch == dquote_end check! */
3942 syntax_error_unterm_ch('"');
3943 /*xfunc_die(); - redundant */
3947 next = i_peek(input);
3949 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
3950 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
3951 if (process_bkslash && ch == '\\') {
3953 syntax_error("\\<eof>");
3957 * "The backslash retains its special meaning [in "..."]
3958 * only when followed by one of the following characters:
3959 * $, `, ", \, or <newline>. A double quote may be quoted
3960 * within double quotes by preceding it with a backslash."
3961 * NB: in (unquoted) heredoc, above does not apply to ",
3962 * therefore we check for it by "next == dquote_end" cond.
3964 if (next == dquote_end || strchr("$`\\\n", next)) {
3965 ch = i_getch(input); /* eat next */
3967 goto again; /* skip \<newline> */
3968 } /* else: ch remains == '\\', and we double it below: */
3969 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
3970 nommu_addchr(as_string, ch);
3974 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
3975 debug_printf_parse("encode_string return 1: "
3976 "parse_dollar returned non-0\n");
3981 #if ENABLE_HUSH_TICK
3983 //unsigned pos = dest->length;
3984 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3985 o_addchr(dest, 0x80 | '`');
3986 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
3987 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3988 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3992 o_addQchr(dest, ch);
3998 * Scan input until EOF or end_trigger char.
3999 * Return a list of pipes to execute, or NULL on EOF
4000 * or if end_trigger character is met.
4001 * On syntax error, exit is shell is not interactive,
4002 * reset parsing machinery and start parsing anew,
4003 * or return ERR_PTR.
4005 static struct pipe *parse_stream(char **pstring,
4006 struct in_str *input,
4009 struct parse_context ctx;
4010 o_string dest = NULL_O_STRING;
4013 /* Single-quote triggers a bypass of the main loop until its mate is
4014 * found. When recursing, quote state is passed in via dest->o_expflags.
4016 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4017 end_trigger ? end_trigger : 'X');
4020 /* If very first arg is "" or '', dest.data may end up NULL.
4021 * Preventing this: */
4022 o_addchr(&dest, '\0');
4025 /* We used to separate words on $IFS here. This was wrong.
4026 * $IFS is used only for word splitting when $var is expanded,
4027 * here we should use blank chars as separators, not $IFS
4030 reset: /* we come back here only on syntax errors in interactive shell */
4032 if (MAYBE_ASSIGNMENT != 0)
4033 dest.o_assignment = MAYBE_ASSIGNMENT;
4034 initialize_context(&ctx);
4037 const char *is_blank;
4038 const char *is_special;
4042 redir_type redir_style;
4044 ch = i_getch(input);
4045 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4046 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4051 syntax_error_unterm_str("here document");
4054 /* end_trigger == '}' case errors out earlier,
4055 * checking only ')' */
4056 if (end_trigger == ')') {
4057 syntax_error_unterm_ch('('); /* exits */
4058 /* goto parse_error; */
4061 if (done_word(&dest, &ctx)) {
4065 done_pipe(&ctx, PIPE_SEQ);
4067 /* If we got nothing... */
4068 /* (this makes bare "&" cmd a no-op.
4069 * bash says: "syntax error near unexpected token '&'") */
4070 if (pi->num_cmds == 0
4071 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4077 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4079 *pstring = ctx.as_string.data;
4081 o_free_unsafe(&ctx.as_string);
4084 debug_printf_parse("parse_stream return %p\n", pi);
4087 nommu_addchr(&ctx.as_string, ch);
4091 next = i_peek(input);
4093 is_special = "{}<>;&|()#'" /* special outside of "str" */
4094 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4095 /* Are { and } special here? */
4096 if (ctx.command->argv /* word [word]{... - non-special */
4097 || dest.length /* word{... - non-special */
4098 || dest.has_quoted_part /* ""{... - non-special */
4099 || (next != ';' /* }; - special */
4100 && next != ')' /* }) - special */
4101 && next != '&' /* }& and }&& ... - special */
4102 && next != '|' /* }|| ... - special */
4103 && !strchr(defifs, next) /* {word - non-special */
4106 /* They are not special, skip "{}" */
4109 is_special = strchr(is_special, ch);
4110 is_blank = strchr(defifs, ch);
4112 if (!is_special && !is_blank) { /* ordinary char */
4114 o_addQchr(&dest, ch);
4115 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4116 || dest.o_assignment == WORD_IS_KEYWORD)
4118 && is_well_formed_var_name(dest.data, '=')
4120 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4126 if (done_word(&dest, &ctx)) {
4130 /* Is this a case when newline is simply ignored?
4132 * "cmd | <newline> cmd ..."
4133 * "case ... in <newline> word) ..."
4135 if (IS_NULL_CMD(ctx.command)
4136 && dest.length == 0 && !dest.has_quoted_part
4138 /* This newline can be ignored. But...
4139 * Without check #1, interactive shell
4140 * ignores even bare <newline>,
4141 * and shows the continuation prompt:
4142 * ps1_prompt$ <enter>
4143 * ps2> _ <=== wrong, should be ps1
4144 * Without check #2, "cmd & <newline>"
4145 * is similarly mistreated.
4146 * (BTW, this makes "cmd & cmd"
4147 * and "cmd && cmd" non-orthogonal.
4148 * Really, ask yourself, why
4149 * "cmd && <newline>" doesn't start
4150 * cmd but waits for more input?
4153 struct pipe *pi = ctx.list_head;
4154 if (pi->num_cmds != 0 /* check #1 */
4155 && pi->followup != PIPE_BG /* check #2 */
4160 /* Treat newline as a command separator. */
4161 done_pipe(&ctx, PIPE_SEQ);
4162 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4164 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4169 dest.o_assignment = MAYBE_ASSIGNMENT;
4171 /* note: if (is_blank) continue;
4172 * will still trigger for us */
4176 /* "cmd}" or "cmd }..." without semicolon or &:
4177 * } is an ordinary char in this case, even inside { cmd; }
4178 * Pathological example: { ""}; } should exec "}" cmd
4181 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4182 || dest.length != 0 /* word} */
4183 || dest.has_quoted_part /* ""} */
4187 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4188 goto skip_end_trigger;
4189 /* else: } does terminate a group */
4192 if (end_trigger && end_trigger == ch
4193 && (ch != ';' || heredoc_cnt == 0)
4194 #if ENABLE_HUSH_CASE
4196 || ctx.ctx_res_w != RES_MATCH
4197 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4202 /* This is technically valid:
4203 * { cat <<HERE; }; echo Ok
4207 * but we don't support this.
4208 * We require heredoc to be in enclosing {}/(),
4211 syntax_error_unterm_str("here document");
4214 if (done_word(&dest, &ctx)) {
4217 done_pipe(&ctx, PIPE_SEQ);
4218 dest.o_assignment = MAYBE_ASSIGNMENT;
4219 /* Do we sit outside of any if's, loops or case's? */
4221 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4225 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4227 *pstring = ctx.as_string.data;
4229 o_free_unsafe(&ctx.as_string);
4232 debug_printf_parse("parse_stream return %p: "
4233 "end_trigger char found\n",
4235 return ctx.list_head;
4242 /* Catch <, > before deciding whether this word is
4243 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4246 redir_fd = redirect_opt_num(&dest);
4247 if (done_word(&dest, &ctx)) {
4250 redir_style = REDIRECT_OVERWRITE;
4252 redir_style = REDIRECT_APPEND;
4253 ch = i_getch(input);
4254 nommu_addchr(&ctx.as_string, ch);
4257 else if (next == '(') {
4258 syntax_error(">(process) not supported");
4262 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4264 continue; /* back to top of while (1) */
4266 redir_fd = redirect_opt_num(&dest);
4267 if (done_word(&dest, &ctx)) {
4270 redir_style = REDIRECT_INPUT;
4272 redir_style = REDIRECT_HEREDOC;
4274 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4275 ch = i_getch(input);
4276 nommu_addchr(&ctx.as_string, ch);
4277 } else if (next == '>') {
4278 redir_style = REDIRECT_IO;
4279 ch = i_getch(input);
4280 nommu_addchr(&ctx.as_string, ch);
4283 else if (next == '(') {
4284 syntax_error("<(process) not supported");
4288 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4290 continue; /* back to top of while (1) */
4292 if (dest.length == 0 && !dest.has_quoted_part) {
4293 /* skip "#comment" */
4296 if (ch == EOF || ch == '\n')
4299 /* note: we do not add it to &ctx.as_string */
4301 nommu_addchr(&ctx.as_string, '\n');
4302 continue; /* back to top of while (1) */
4307 /* It's "\<newline>" */
4309 /* Remove trailing '\' from ctx.as_string */
4310 ctx.as_string.data[--ctx.as_string.length] = '\0';
4312 ch = i_getch(input); /* eat it */
4313 continue; /* back to top of while (1) */
4318 if (dest.o_assignment == MAYBE_ASSIGNMENT
4319 /* check that we are not in word in "a=1 2>word b=1": */
4320 && !ctx.pending_redirect
4322 /* ch is a special char and thus this word
4323 * cannot be an assignment */
4324 dest.o_assignment = NOT_ASSIGNMENT;
4327 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4330 case '#': /* non-comment #: "echo a#b" etc */
4331 o_addQchr(&dest, ch);
4335 syntax_error("\\<eof>");
4338 ch = i_getch(input);
4339 /* note: ch != '\n' (that case does not reach this place) */
4340 o_addchr(&dest, '\\');
4341 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4342 o_addchr(&dest, ch);
4343 nommu_addchr(&ctx.as_string, ch);
4344 /* Example: echo Hello \2>file
4345 * we need to know that word 2 is quoted */
4346 dest.has_quoted_part = 1;
4349 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
4350 debug_printf_parse("parse_stream parse error: "
4351 "parse_dollar returned non-0\n");
4356 dest.has_quoted_part = 1;
4358 ch = i_getch(input);
4360 syntax_error_unterm_ch('\'');
4361 /*xfunc_die(); - redundant */
4363 nommu_addchr(&ctx.as_string, ch);
4366 o_addqchr(&dest, ch);
4370 dest.has_quoted_part = 1;
4371 if (dest.o_assignment == NOT_ASSIGNMENT)
4372 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4373 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4375 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4377 #if ENABLE_HUSH_TICK
4381 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4382 o_addchr(&dest, '`');
4384 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
4386 o_addstr(&ctx.as_string, dest.data + pos);
4387 o_addchr(&ctx.as_string, '`');
4389 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4390 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4395 #if ENABLE_HUSH_CASE
4398 if (done_word(&dest, &ctx)) {
4401 done_pipe(&ctx, PIPE_SEQ);
4402 #if ENABLE_HUSH_CASE
4403 /* Eat multiple semicolons, detect
4404 * whether it means something special */
4409 ch = i_getch(input);
4410 nommu_addchr(&ctx.as_string, ch);
4411 if (ctx.ctx_res_w == RES_CASE_BODY) {
4412 ctx.ctx_dsemicolon = 1;
4413 ctx.ctx_res_w = RES_MATCH;
4419 /* We just finished a cmd. New one may start
4420 * with an assignment */
4421 dest.o_assignment = MAYBE_ASSIGNMENT;
4424 if (done_word(&dest, &ctx)) {
4428 ch = i_getch(input);
4429 nommu_addchr(&ctx.as_string, ch);
4430 done_pipe(&ctx, PIPE_AND);
4432 done_pipe(&ctx, PIPE_BG);
4436 if (done_word(&dest, &ctx)) {
4439 #if ENABLE_HUSH_CASE
4440 if (ctx.ctx_res_w == RES_MATCH)
4441 break; /* we are in case's "word | word)" */
4443 if (next == '|') { /* || */
4444 ch = i_getch(input);
4445 nommu_addchr(&ctx.as_string, ch);
4446 done_pipe(&ctx, PIPE_OR);
4448 /* we could pick up a file descriptor choice here
4449 * with redirect_opt_num(), but bash doesn't do it.
4450 * "echo foo 2| cat" yields "foo 2". */
4453 o_reset_to_empty_unquoted(&ctx.as_string);
4458 #if ENABLE_HUSH_CASE
4459 /* "case... in [(]word)..." - skip '(' */
4460 if (ctx.ctx_res_w == RES_MATCH
4461 && ctx.command->argv == NULL /* not (word|(... */
4462 && dest.length == 0 /* not word(... */
4463 && dest.has_quoted_part == 0 /* not ""(... */
4469 if (parse_group(&dest, &ctx, input, ch) != 0) {
4474 #if ENABLE_HUSH_CASE
4475 if (ctx.ctx_res_w == RES_MATCH)
4479 /* proper use of this character is caught by end_trigger:
4480 * if we see {, we call parse_group(..., end_trigger='}')
4481 * and it will match } earlier (not here). */
4482 syntax_error_unexpected_ch(ch);
4486 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4492 struct parse_context *pctx;
4493 IF_HAS_KEYWORDS(struct parse_context *p2;)
4495 /* Clean up allocated tree.
4496 * Sample for finding leaks on syntax error recovery path.
4497 * Run it from interactive shell, watch pmap `pidof hush`.
4498 * while if false; then false; fi; do break; fi
4499 * Samples to catch leaks at execution:
4500 * while if (true | {true;}); then echo ok; fi; do break; done
4501 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4505 /* Update pipe/command counts,
4506 * otherwise freeing may miss some */
4507 done_pipe(pctx, PIPE_SEQ);
4508 debug_printf_clean("freeing list %p from ctx %p\n",
4509 pctx->list_head, pctx);
4510 debug_print_tree(pctx->list_head, 0);
4511 free_pipe_list(pctx->list_head);
4512 debug_printf_clean("freed list %p\n", pctx->list_head);
4514 o_free_unsafe(&pctx->as_string);
4516 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4520 IF_HAS_KEYWORDS(pctx = p2;)
4521 } while (HAS_KEYWORDS && pctx);
4522 /* Free text, clear all dest fields */
4524 /* If we are not in top-level parse, we return,
4525 * our caller will propagate error.
4527 if (end_trigger != ';') {
4535 /* Discard cached input, force prompt */
4542 /*** Execution routines ***/
4544 /* Expansion can recurse, need forward decls: */
4545 #if !ENABLE_HUSH_BASH_COMPAT
4546 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4547 #define expand_string_to_string(str, do_unbackslash) \
4548 expand_string_to_string(str)
4550 static char *expand_string_to_string(const char *str, int do_unbackslash);
4551 #if ENABLE_HUSH_TICK
4552 static int process_command_subs(o_string *dest, const char *s);
4555 /* expand_strvec_to_strvec() takes a list of strings, expands
4556 * all variable references within and returns a pointer to
4557 * a list of expanded strings, possibly with larger number
4558 * of strings. (Think VAR="a b"; echo $VAR).
4559 * This new list is allocated as a single malloc block.
4560 * NULL-terminated list of char* pointers is at the beginning of it,
4561 * followed by strings themselves.
4562 * Caller can deallocate entire list by single free(list). */
4564 /* A horde of its helpers come first: */
4566 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4568 while (--len >= 0) {
4571 #if ENABLE_HUSH_BRACE_EXPANSION
4572 if (c == '{' || c == '}') {
4573 /* { -> \{, } -> \} */
4575 /* And now we want to add { or } and continue:
4578 * luckily, just falling throught achieves this.
4584 /* \z -> \\\z; \<eol> -> \\<eol> */
4589 o_addchr(o, *str++);
4595 /* Store given string, finalizing the word and starting new one whenever
4596 * we encounter IFS char(s). This is used for expanding variable values.
4597 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4598 static int expand_on_ifs(o_string *output, int n, const char *str)
4601 int word_len = strcspn(str, G.ifs);
4603 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4604 o_addblock(output, str, word_len);
4606 /* Protect backslashes against globbing up :)
4607 * Example: "v='\*'; echo b$v" prints "b\*"
4608 * (and does not try to glob on "*")
4610 o_addblock_duplicate_backslash(output, str, word_len);
4611 /*/ Why can't we do it easier? */
4612 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4613 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4617 if (!*str) /* EOL - do not finalize word */
4619 o_addchr(output, '\0');
4620 debug_print_list("expand_on_ifs", output, n);
4621 n = o_save_ptr(output, n);
4622 str += strspn(str, G.ifs); /* skip ifs chars */
4624 debug_print_list("expand_on_ifs[1]", output, n);
4628 /* Helper to expand $((...)) and heredoc body. These act as if
4629 * they are in double quotes, with the exception that they are not :).
4630 * Just the rules are similar: "expand only $var and `cmd`"
4632 * Returns malloced string.
4633 * As an optimization, we return NULL if expansion is not needed.
4635 #if !ENABLE_HUSH_BASH_COMPAT
4636 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4637 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4638 encode_then_expand_string(str)
4640 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4643 struct in_str input;
4644 o_string dest = NULL_O_STRING;
4646 if (!strchr(str, '$')
4647 && !strchr(str, '\\')
4648 #if ENABLE_HUSH_TICK
4649 && !strchr(str, '`')
4655 /* We need to expand. Example:
4656 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4658 setup_string_in_str(&input, str);
4659 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4660 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4661 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4662 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4663 o_free_unsafe(&dest);
4667 #if ENABLE_SH_MATH_SUPPORT
4668 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4670 arith_state_t math_state;
4674 math_state.lookupvar = get_local_var_value;
4675 math_state.setvar = set_local_var_from_halves;
4676 //math_state.endofname = endofname;
4677 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4678 res = arith(&math_state, exp_str ? exp_str : arg);
4681 *errmsg_p = math_state.errmsg;
4682 if (math_state.errmsg)
4683 die_if_script(math_state.errmsg);
4688 #if ENABLE_HUSH_BASH_COMPAT
4689 /* ${var/[/]pattern[/repl]} helpers */
4690 static char *strstr_pattern(char *val, const char *pattern, int *size)
4693 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4694 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4701 /* Optimization: if "*pat" did not match the start of "string",
4702 * we know that "tring", "ring" etc will not match too:
4704 if (pattern[0] == '*')
4709 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4711 char *result = NULL;
4712 unsigned res_len = 0;
4713 unsigned repl_len = strlen(repl);
4717 char *s = strstr_pattern(val, pattern, &size);
4721 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4722 memcpy(result + res_len, val, s - val);
4724 strcpy(result + res_len, repl);
4725 res_len += repl_len;
4726 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4732 if (val[0] && result) {
4733 result = xrealloc(result, res_len + strlen(val) + 1);
4734 strcpy(result + res_len, val);
4735 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4737 debug_printf_varexp("result:'%s'\n", result);
4743 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4745 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4747 const char *val = NULL;
4748 char *to_be_freed = NULL;
4753 char exp_save = exp_save; /* for compiler */
4754 char *exp_saveptr; /* points to expansion operator */
4755 char *exp_word = exp_word; /* for compiler */
4758 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4760 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4762 first_char = arg[0] = arg0 & 0x7f;
4765 if (first_char == '#' /* ${#... */
4766 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4768 /* It must be length operator: ${#var} */
4772 /* Maybe handle parameter expansion */
4773 if (exp_saveptr /* if 2nd char is one of expansion operators */
4774 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4776 /* ${?:0}, ${#[:]%0} etc */
4777 exp_saveptr = var + 1;
4779 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4780 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4782 exp_op = exp_save = *exp_saveptr;
4784 exp_word = exp_saveptr + 1;
4785 if (exp_op == ':') {
4786 exp_op = *exp_word++;
4787 //TODO: try ${var:} and ${var:bogus} in non-bash config
4788 if (ENABLE_HUSH_BASH_COMPAT
4789 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4791 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4796 *exp_saveptr = '\0';
4797 } /* else: it's not an expansion op, but bare ${var} */
4800 /* Look up the variable in question */
4801 if (isdigit(var[0])) {
4802 /* parse_dollar should have vetted var for us */
4803 int n = xatoi_positive(var);
4804 if (n < G.global_argc)
4805 val = G.global_argv[n];
4806 /* else val remains NULL: $N with too big N */
4810 val = utoa(G.root_pid);
4812 case '!': /* bg pid */
4813 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4815 case '?': /* exitcode */
4816 val = utoa(G.last_exitcode);
4818 case '#': /* argc */
4819 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4822 val = get_local_var_value(var);
4826 /* Handle any expansions */
4827 if (exp_op == 'L') {
4828 debug_printf_expand("expand: length(%s)=", val);
4829 val = utoa(val ? strlen(val) : 0);
4830 debug_printf_expand("%s\n", val);
4831 } else if (exp_op) {
4832 if (exp_op == '%' || exp_op == '#') {
4833 /* Standard-mandated substring removal ops:
4834 * ${parameter%word} - remove smallest suffix pattern
4835 * ${parameter%%word} - remove largest suffix pattern
4836 * ${parameter#word} - remove smallest prefix pattern
4837 * ${parameter##word} - remove largest prefix pattern
4839 * Word is expanded to produce a glob pattern.
4840 * Then var's value is matched to it and matching part removed.
4842 if (val && val[0]) {
4846 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4847 if (exp_op == *exp_word) /* ## or %% */
4849 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4851 exp_word = exp_exp_word;
4852 /* HACK ALERT. We depend here on the fact that
4853 * G.global_argv and results of utoa and get_local_var_value
4854 * are actually in writable memory:
4855 * scan_and_match momentarily stores NULs there. */
4857 loc = scan_and_match(t, exp_word, scan_flags);
4858 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4859 // exp_op, t, exp_word, loc);
4861 if (loc) { /* match was found */
4862 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4863 val = loc; /* take right part */
4865 val = to_be_freed = xstrndup(val, loc - val); /* left */
4869 #if ENABLE_HUSH_BASH_COMPAT
4870 else if (exp_op == '/' || exp_op == '\\') {
4871 /* It's ${var/[/]pattern[/repl]} thing.
4872 * Note that in encoded form it has TWO parts:
4873 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4874 * and if // is used, it is encoded as \:
4875 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4877 /* Empty variable always gives nothing: */
4878 // "v=''; echo ${v/*/w}" prints "", not "w"
4879 if (val && val[0]) {
4880 /* pattern uses non-standard expansion.
4881 * repl should be unbackslashed and globbed
4882 * by the usual expansion rules:
4884 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4885 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4886 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4887 * v='a bz'; echo ${v/a*z/\z} prints "z"
4888 * (note that a*z _pattern_ is never globbed!)
4890 char *pattern, *repl, *t;
4891 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
4893 pattern = xstrdup(exp_word);
4894 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4895 *p++ = SPECIAL_VAR_SYMBOL;
4897 p = strchr(p, SPECIAL_VAR_SYMBOL);
4899 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
4900 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4901 /* HACK ALERT. We depend here on the fact that
4902 * G.global_argv and results of utoa and get_local_var_value
4903 * are actually in writable memory:
4904 * replace_pattern momentarily stores NULs there. */
4906 to_be_freed = replace_pattern(t,
4908 (repl ? repl : exp_word),
4910 if (to_be_freed) /* at least one replace happened */
4917 else if (exp_op == ':') {
4918 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4919 /* It's ${var:N[:M]} bashism.
4920 * Note that in encoded form it has TWO parts:
4921 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4926 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4929 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4930 *p++ = SPECIAL_VAR_SYMBOL;
4932 p = strchr(p, SPECIAL_VAR_SYMBOL);
4934 len = expand_and_evaluate_arith(exp_word, &errmsg);
4937 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
4938 if (len >= 0) { /* bash compat: len < 0 is illegal */
4939 if (beg < 0) /* bash compat */
4941 debug_printf_varexp("from val:'%s'\n", val);
4942 if (len == 0 || !val || beg >= strlen(val)) {
4946 /* Paranoia. What if user entered 9999999999999
4947 * which fits in arith_t but not int? */
4950 val = to_be_freed = xstrndup(val + beg, len);
4952 debug_printf_varexp("val:'%s'\n", val);
4956 die_if_script("malformed ${%s:...}", var);
4959 } else { /* one of "-=+?" */
4960 /* Standard-mandated substitution ops:
4961 * ${var?word} - indicate error if unset
4962 * If var is unset, word (or a message indicating it is unset
4963 * if word is null) is written to standard error
4964 * and the shell exits with a non-zero exit status.
4965 * Otherwise, the value of var is substituted.
4966 * ${var-word} - use default value
4967 * If var is unset, word is substituted.
4968 * ${var=word} - assign and use default value
4969 * If var is unset, word is assigned to var.
4970 * In all cases, final value of var is substituted.
4971 * ${var+word} - use alternative value
4972 * If var is unset, null is substituted.
4973 * Otherwise, word is substituted.
4975 * Word is subjected to tilde expansion, parameter expansion,
4976 * command substitution, and arithmetic expansion.
4977 * If word is not needed, it is not expanded.
4979 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4980 * but also treat null var as if it is unset.
4982 int use_word = (!val || ((exp_save == ':') && !val[0]));
4984 use_word = !use_word;
4985 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4986 (exp_save == ':') ? "true" : "false", use_word);
4988 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4990 exp_word = to_be_freed;
4991 if (exp_op == '?') {
4992 /* mimic bash message */
4993 die_if_script("%s: %s",
4995 exp_word[0] ? exp_word : "parameter null or not set"
4997 //TODO: how interactive bash aborts expansion mid-command?
5002 if (exp_op == '=') {
5003 /* ${var=[word]} or ${var:=[word]} */
5004 if (isdigit(var[0]) || var[0] == '#') {
5005 /* mimic bash message */
5006 die_if_script("$%s: cannot assign in this way", var);
5009 char *new_var = xasprintf("%s=%s", var, val);
5010 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5014 } /* one of "-=+?" */
5016 *exp_saveptr = exp_save;
5022 *to_be_freed_pp = to_be_freed;
5026 /* Expand all variable references in given string, adding words to list[]
5027 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5028 * to be filled). This routine is extremely tricky: has to deal with
5029 * variables/parameters with whitespace, $* and $@, and constructs like
5030 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5031 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5033 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5034 * expansion of right-hand side of assignment == 1-element expand.
5036 char cant_be_null = 0; /* only bit 0x80 matters */
5039 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5040 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5041 debug_print_list("expand_vars_to_list", output, n);
5042 n = o_save_ptr(output, n);
5043 debug_print_list("expand_vars_to_list[0]", output, n);
5045 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5047 char *to_be_freed = NULL;
5048 const char *val = NULL;
5049 #if ENABLE_HUSH_TICK
5050 o_string subst_result = NULL_O_STRING;
5052 #if ENABLE_SH_MATH_SUPPORT
5053 char arith_buf[sizeof(arith_t)*3 + 2];
5055 o_addblock(output, arg, p - arg);
5056 debug_print_list("expand_vars_to_list[1]", output, n);
5058 p = strchr(p, SPECIAL_VAR_SYMBOL);
5060 /* Fetch special var name (if it is indeed one of them)
5061 * and quote bit, force the bit on if singleword expansion -
5062 * important for not getting v=$@ expand to many words. */
5063 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5065 /* Is this variable quoted and thus expansion can't be null?
5066 * "$@" is special. Even if quoted, it can still
5067 * expand to nothing (not even an empty string),
5068 * thus it is excluded. */
5069 if ((first_ch & 0x7f) != '@')
5070 cant_be_null |= first_ch;
5072 switch (first_ch & 0x7f) {
5073 /* Highest bit in first_ch indicates that var is double-quoted */
5077 if (!G.global_argv[1])
5080 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5081 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5082 while (G.global_argv[i]) {
5083 n = expand_on_ifs(output, n, G.global_argv[i]);
5084 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5085 if (G.global_argv[i++][0] && G.global_argv[i]) {
5086 /* this argv[] is not empty and not last:
5087 * put terminating NUL, start new word */
5088 o_addchr(output, '\0');
5089 debug_print_list("expand_vars_to_list[2]", output, n);
5090 n = o_save_ptr(output, n);
5091 debug_print_list("expand_vars_to_list[3]", output, n);
5095 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5096 * and in this case should treat it like '$*' - see 'else...' below */
5097 if (first_ch == ('@'|0x80) /* quoted $@ */
5098 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5101 o_addQstr(output, G.global_argv[i]);
5102 if (++i >= G.global_argc)
5104 o_addchr(output, '\0');
5105 debug_print_list("expand_vars_to_list[4]", output, n);
5106 n = o_save_ptr(output, n);
5108 } else { /* quoted $* (or v="$@" case): add as one word */
5110 o_addQstr(output, G.global_argv[i]);
5111 if (!G.global_argv[++i])
5114 o_addchr(output, G.ifs[0]);
5119 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5120 /* "Empty variable", used to make "" etc to not disappear */
5122 cant_be_null = 0x80;
5124 #if ENABLE_HUSH_TICK
5125 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5126 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5128 /* Can't just stuff it into output o_string,
5129 * expanded result may need to be globbed
5130 * and $IFS-splitted */
5131 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5132 G.last_exitcode = process_command_subs(&subst_result, arg);
5133 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5134 val = subst_result.data;
5137 #if ENABLE_SH_MATH_SUPPORT
5138 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5141 arg++; /* skip '+' */
5142 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5143 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5144 res = expand_and_evaluate_arith(arg, NULL);
5145 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5146 sprintf(arith_buf, ARITH_FMT, res);
5152 val = expand_one_var(&to_be_freed, arg, &p);
5153 IF_HUSH_TICK(store_val:)
5154 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5155 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5156 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5157 if (val && val[0]) {
5158 n = expand_on_ifs(output, n, val);
5161 } else { /* quoted $VAR, val will be appended below */
5162 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5163 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5167 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5169 if (val && val[0]) {
5170 o_addQstr(output, val);
5174 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5175 * Do the check to avoid writing to a const string. */
5176 if (*p != SPECIAL_VAR_SYMBOL)
5177 *p = SPECIAL_VAR_SYMBOL;
5179 #if ENABLE_HUSH_TICK
5180 o_free(&subst_result);
5183 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5186 debug_print_list("expand_vars_to_list[a]", output, n);
5187 /* this part is literal, and it was already pre-quoted
5188 * if needed (much earlier), do not use o_addQstr here! */
5189 o_addstr_with_NUL(output, arg);
5190 debug_print_list("expand_vars_to_list[b]", output, n);
5191 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5192 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5195 /* allow to reuse list[n] later without re-growth */
5196 output->has_empty_slot = 1;
5198 o_addchr(output, '\0');
5204 static char **expand_variables(char **argv, unsigned expflags)
5208 o_string output = NULL_O_STRING;
5210 output.o_expflags = expflags;
5214 n = expand_vars_to_list(&output, n, *argv);
5217 debug_print_list("expand_variables", &output, n);
5219 /* output.data (malloced in one block) gets returned in "list" */
5220 list = o_finalize_list(&output, n);
5221 debug_print_strings("expand_variables[1]", list);
5225 static char **expand_strvec_to_strvec(char **argv)
5227 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5230 #if ENABLE_HUSH_BASH_COMPAT
5231 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5233 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5237 /* Used for expansion of right hand of assignments,
5238 * $((...)), heredocs, variable espansion parts.
5240 * NB: should NOT do globbing!
5241 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5243 static char *expand_string_to_string(const char *str, int do_unbackslash)
5245 #if !ENABLE_HUSH_BASH_COMPAT
5246 const int do_unbackslash = 1;
5248 char *argv[2], **list;
5250 debug_printf_expand("string_to_string<='%s'\n", str);
5251 /* This is generally an optimization, but it also
5252 * handles "", which otherwise trips over !list[0] check below.
5253 * (is this ever happens that we actually get str="" here?)
5255 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5256 //TODO: Can use on strings with \ too, just unbackslash() them?
5257 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5258 return xstrdup(str);
5261 argv[0] = (char*)str;
5263 list = expand_variables(argv, do_unbackslash
5264 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5265 : EXP_FLAG_SINGLEWORD
5268 if (!list[0] || list[1])
5269 bb_error_msg_and_die("BUG in varexp2");
5270 /* actually, just move string 2*sizeof(char*) bytes back */
5271 overlapping_strcpy((char*)list, list[0]);
5273 unbackslash((char*)list);
5274 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5278 /* Used for "eval" builtin */
5279 static char* expand_strvec_to_string(char **argv)
5283 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5284 /* Convert all NULs to spaces */
5289 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5290 bb_error_msg_and_die("BUG in varexp3");
5291 /* bash uses ' ' regardless of $IFS contents */
5296 overlapping_strcpy((char*)list, list[0]);
5297 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5301 static char **expand_assignments(char **argv, int count)
5306 G.expanded_assignments = p = NULL;
5307 /* Expand assignments into one string each */
5308 for (i = 0; i < count; i++) {
5309 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5311 G.expanded_assignments = NULL;
5318 void re_execute_shell(char ***to_free, const char *s,
5319 char *g_argv0, char **g_argv,
5320 char **builtin_argv) NORETURN;
5322 static void reset_traps_to_defaults(void)
5324 /* This function is always called in a child shell
5325 * after fork (not vfork, NOMMU doesn't use this function).
5330 /* Child shells are not interactive.
5331 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5332 * Testcase: (while :; do :; done) + ^Z should background.
5333 * Same goes for SIGTERM, SIGHUP, SIGINT.
5335 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5336 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5338 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5339 * Stupid. It can be done with *single* &= op, but we can't use
5340 * the fact that G.blocked_set is implemented as a bitmask
5342 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5346 /* Careful. Only if no trap or trap is not "" */
5347 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5348 sigdelset(&G.blocked_set, sig);
5355 /* Our homegrown sig mask is saner to work with :) */
5356 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5358 /* Resetting all traps to default except empty ones */
5359 mask = G.non_DFL_mask;
5360 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5361 if (!G.traps[sig] || !G.traps[sig][0])
5364 G.traps[sig] = NULL;
5365 /* There is no signal for 0 (EXIT) */
5368 /* There was a trap handler, we just removed it.
5369 * But if sig still has non-DFL handling,
5370 * we should not unblock the sig. */
5373 sigdelset(&G.blocked_set, sig);
5375 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5380 static void re_execute_shell(char ***to_free, const char *s,
5381 char *g_argv0, char **g_argv,
5382 char **builtin_argv) NORETURN;
5383 static void re_execute_shell(char ***to_free, const char *s,
5384 char *g_argv0, char **g_argv,
5385 char **builtin_argv)
5387 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5388 /* delims + 2 * (number of bytes in printed hex numbers) */
5389 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5390 char *heredoc_argv[4];
5391 struct variable *cur;
5392 # if ENABLE_HUSH_FUNCTIONS
5393 struct function *funcp;
5397 unsigned long long empty_trap_mask;
5399 if (!g_argv0) { /* heredoc */
5400 argv = heredoc_argv;
5401 argv[0] = (char *) G.argv0_for_re_execing;
5402 argv[1] = (char *) "-<";
5403 argv[2] = (char *) s;
5405 pp = &argv[3]; /* used as pointer to empty environment */
5411 if (pp) while (*pp++)
5414 empty_trap_mask = 0;
5417 for (sig = 1; sig < NSIG; sig++) {
5418 if (G.traps[sig] && !G.traps[sig][0])
5419 empty_trap_mask |= 1LL << sig;
5423 sprintf(param_buf, NOMMU_HACK_FMT
5424 , (unsigned) G.root_pid
5425 , (unsigned) G.root_ppid
5426 , (unsigned) G.last_bg_pid
5427 , (unsigned) G.last_exitcode
5430 IF_HUSH_LOOPS(, G.depth_of_loop)
5432 # undef NOMMU_HACK_FMT
5433 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5434 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5437 for (cur = G.top_var; cur; cur = cur->next) {
5438 if (!cur->flg_export || cur->flg_read_only)
5441 # if ENABLE_HUSH_FUNCTIONS
5442 for (funcp = G.top_func; funcp; funcp = funcp->next)
5448 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5449 *pp++ = (char *) G.argv0_for_re_execing;
5451 for (cur = G.top_var; cur; cur = cur->next) {
5452 if (strcmp(cur->varstr, hush_version_str) == 0)
5454 if (cur->flg_read_only) {
5455 *pp++ = (char *) "-R";
5456 *pp++ = cur->varstr;
5457 } else if (!cur->flg_export) {
5458 *pp++ = (char *) "-V";
5459 *pp++ = cur->varstr;
5462 # if ENABLE_HUSH_FUNCTIONS
5463 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5464 *pp++ = (char *) "-F";
5465 *pp++ = funcp->name;
5466 *pp++ = funcp->body_as_string;
5469 /* We can pass activated traps here. Say, -Tnn:trap_string
5471 * However, POSIX says that subshells reset signals with traps
5473 * I tested bash-3.2 and it not only does that with true subshells
5474 * of the form ( list ), but with any forked children shells.
5475 * I set trap "echo W" WINCH; and then tried:
5477 * { echo 1; sleep 20; echo 2; } &
5478 * while true; do echo 1; sleep 20; echo 2; break; done &
5479 * true | { echo 1; sleep 20; echo 2; } | cat
5481 * In all these cases sending SIGWINCH to the child shell
5482 * did not run the trap. If I add trap "echo V" WINCH;
5483 * _inside_ group (just before echo 1), it works.
5485 * I conclude it means we don't need to pass active traps here.
5486 * Even if we would use signal handlers instead of signal masking
5487 * in order to implement trap handling,
5488 * exec syscall below resets signals to SIG_DFL for us.
5490 *pp++ = (char *) "-c";
5493 while (*++builtin_argv)
5494 *pp++ = *builtin_argv;
5495 *pp++ = (char *) "";
5500 /* *pp = NULL; - is already there */
5504 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5505 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5506 execve(bb_busybox_exec_path, argv, pp);
5507 /* Fallback. Useful for init=/bin/hush usage etc */
5508 if (argv[0][0] == '/')
5509 execve(argv[0], argv, pp);
5510 xfunc_error_retval = 127;
5511 bb_error_msg_and_die("can't re-execute the shell");
5513 #endif /* !BB_MMU */
5516 static int run_and_free_list(struct pipe *pi);
5518 /* Executing from string: eval, sh -c '...'
5519 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5520 * end_trigger controls how often we stop parsing
5521 * NUL: parse all, execute, return
5522 * ';': parse till ';' or newline, execute, repeat till EOF
5524 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5526 /* Why we need empty flag?
5527 * An obscure corner case "false; ``; echo $?":
5528 * empty command in `` should still set $? to 0.
5529 * But we can't just set $? to 0 at the start,
5530 * this breaks "false; echo `echo $?`" case.
5534 struct pipe *pipe_list;
5536 #if ENABLE_HUSH_INTERACTIVE
5537 if (end_trigger == ';')
5538 inp->promptmode = 0; /* PS1 */
5540 pipe_list = parse_stream(NULL, inp, end_trigger);
5541 if (!pipe_list) { /* EOF */
5543 G.last_exitcode = 0;
5546 debug_print_tree(pipe_list, 0);
5547 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5548 run_and_free_list(pipe_list);
5553 static void parse_and_run_string(const char *s)
5555 struct in_str input;
5556 setup_string_in_str(&input, s);
5557 parse_and_run_stream(&input, '\0');
5560 static void parse_and_run_file(FILE *f)
5562 struct in_str input;
5563 setup_file_in_str(&input, f);
5564 parse_and_run_stream(&input, ';');
5567 #if ENABLE_HUSH_TICK
5568 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5573 char **to_free = NULL;
5577 pid = BB_MMU ? xfork() : xvfork();
5578 if (pid == 0) { /* child */
5579 disable_restore_tty_pgrp_on_exit();
5580 /* Process substitution is not considered to be usual
5581 * 'command execution'.
5582 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5589 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5590 close(channel[0]); /* NB: close _first_, then move fd! */
5591 xmove_fd(channel[1], 1);
5592 /* Prevent it from trying to handle ctrl-z etc */
5593 IF_HUSH_JOB(G.run_list_level = 1;)
5594 /* Awful hack for `trap` or $(trap).
5596 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5597 * contains an example where "trap" is executed in a subshell:
5599 * save_traps=$(trap)
5601 * eval "$save_traps"
5603 * Standard does not say that "trap" in subshell shall print
5604 * parent shell's traps. It only says that its output
5605 * must have suitable form, but then, in the above example
5606 * (which is not supposed to be normative), it implies that.
5608 * bash (and probably other shell) does implement it
5609 * (traps are reset to defaults, but "trap" still shows them),
5610 * but as a result, "trap" logic is hopelessly messed up:
5613 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5614 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5615 * # true | trap <--- trap is in subshell - no output (ditto)
5616 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5617 * trap -- 'echo Ho' SIGWINCH
5618 * # echo `(trap)` <--- in subshell in subshell - output
5619 * trap -- 'echo Ho' SIGWINCH
5620 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5621 * trap -- 'echo Ho' SIGWINCH
5623 * The rules when to forget and when to not forget traps
5624 * get really complex and nonsensical.
5626 * Our solution: ONLY bare $(trap) or `trap` is special.
5628 s = skip_whitespace(s);
5629 if (strncmp(s, "trap", 4) == 0
5630 && skip_whitespace(s + 4)[0] == '\0'
5632 static const char *const argv[] = { NULL, NULL };
5633 builtin_trap((char**)argv);
5634 exit(0); /* not _exit() - we need to fflush */
5637 reset_traps_to_defaults();
5638 parse_and_run_string(s);
5639 _exit(G.last_exitcode);
5641 /* We re-execute after vfork on NOMMU. This makes this script safe:
5642 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5643 * huge=`cat BIG` # was blocking here forever
5646 re_execute_shell(&to_free,
5656 # if ENABLE_HUSH_FAST
5658 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5659 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5660 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5662 enable_restore_tty_pgrp_on_exit();
5667 close_on_exec_on(channel[0]);
5668 return xfdopen_for_read(channel[0]);
5671 /* Return code is exit status of the process that is run. */
5672 static int process_command_subs(o_string *dest, const char *s)
5675 struct in_str pipe_str;
5677 int status, ch, eol_cnt;
5679 fp = generate_stream_from_string(s, &pid);
5681 /* Now send results of command back into original context */
5682 setup_file_in_str(&pipe_str, fp);
5684 while ((ch = i_getch(&pipe_str)) != EOF) {
5690 o_addchr(dest, '\n');
5693 o_addQchr(dest, ch);
5696 debug_printf("done reading from `cmd` pipe, closing it\n");
5698 /* We need to extract exitcode. Test case
5699 * "true; echo `sleep 1; false` $?"
5701 safe_waitpid(pid, &status, 0);
5702 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5703 return WEXITSTATUS(status);
5705 #endif /* ENABLE_HUSH_TICK */
5708 static void setup_heredoc(struct redir_struct *redir)
5710 struct fd_pair pair;
5713 /* the _body_ of heredoc (misleading field name) */
5714 const char *heredoc = redir->rd_filename;
5721 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5722 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5726 len = strlen(heredoc);
5728 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5730 xmove_fd(pair.rd, redir->rd_fd);
5732 /* Try writing without forking. Newer kernels have
5733 * dynamically growing pipes. Must use non-blocking write! */
5736 written = write(pair.wr, heredoc, len);
5747 ndelay_off(pair.wr);
5749 /* Okay, pipe buffer was not big enough */
5750 /* Note: we must not create a stray child (bastard? :)
5751 * for the unsuspecting parent process. Child creates a grandchild
5752 * and exits before parent execs the process which consumes heredoc
5753 * (that exec happens after we return from this function) */
5760 disable_restore_tty_pgrp_on_exit();
5761 pid = BB_MMU ? xfork() : xvfork();
5765 close(redir->rd_fd); /* read side of the pipe */
5767 full_write(pair.wr, heredoc, len); /* may loop or block */
5770 /* Delegate blocking writes to another process */
5771 xmove_fd(pair.wr, STDOUT_FILENO);
5772 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5776 #if ENABLE_HUSH_FAST
5778 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5780 enable_restore_tty_pgrp_on_exit();
5786 wait(NULL); /* wait till child has died */
5789 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5790 * and stderr if they are redirected. */
5791 static int setup_redirects(struct command *prog, int squirrel[])
5794 struct redir_struct *redir;
5796 for (redir = prog->redirects; redir; redir = redir->next) {
5797 if (redir->rd_type == REDIRECT_HEREDOC2) {
5798 /* rd_fd<<HERE case */
5799 if (squirrel && redir->rd_fd < 3
5800 && squirrel[redir->rd_fd] < 0
5802 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5804 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5806 debug_printf_parse("set heredoc '%s'\n",
5807 redir->rd_filename);
5808 setup_heredoc(redir);
5812 if (redir->rd_dup == REDIRFD_TO_FILE) {
5813 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5815 if (redir->rd_filename == NULL) {
5816 /* Something went wrong in the parse.
5817 * Pretend it didn't happen */
5818 bb_error_msg("bug in redirect parse");
5821 mode = redir_table[redir->rd_type].mode;
5822 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5823 openfd = open_or_warn(p, mode);
5826 /* this could get lost if stderr has been redirected, but
5827 * bash and ash both lose it as well (though zsh doesn't!) */
5828 //what the above comment tries to say?
5832 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5833 openfd = redir->rd_dup;
5836 if (openfd != redir->rd_fd) {
5837 if (squirrel && redir->rd_fd < 3
5838 && squirrel[redir->rd_fd] < 0
5840 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5842 if (openfd == REDIRFD_CLOSE) {
5843 /* "n>-" means "close me" */
5844 close(redir->rd_fd);
5846 xdup2(openfd, redir->rd_fd);
5847 if (redir->rd_dup == REDIRFD_TO_FILE)
5855 static void restore_redirects(int squirrel[])
5858 for (i = 0; i < 3; i++) {
5861 /* We simply die on error */
5867 static char *find_in_path(const char *arg)
5870 const char *PATH = get_local_var_value("PATH");
5876 const char *end = strchrnul(PATH, ':');
5877 int sz = end - PATH; /* must be int! */
5881 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5883 /* We have xxx::yyyy in $PATH,
5884 * it means "use current dir" */
5887 if (access(ret, F_OK) == 0)
5900 static const struct built_in_command *find_builtin_helper(const char *name,
5901 const struct built_in_command *x,
5902 const struct built_in_command *end)
5905 if (strcmp(name, x->b_cmd) != 0) {
5909 debug_printf_exec("found builtin '%s'\n", name);
5914 static const struct built_in_command *find_builtin1(const char *name)
5916 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5918 static const struct built_in_command *find_builtin(const char *name)
5920 const struct built_in_command *x = find_builtin1(name);
5923 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5926 #if ENABLE_HUSH_FUNCTIONS
5927 static struct function **find_function_slot(const char *name)
5929 struct function **funcpp = &G.top_func;
5931 if (strcmp(name, (*funcpp)->name) == 0) {
5934 funcpp = &(*funcpp)->next;
5939 static const struct function *find_function(const char *name)
5941 const struct function *funcp = *find_function_slot(name);
5943 debug_printf_exec("found function '%s'\n", name);
5947 /* Note: takes ownership on name ptr */
5948 static struct function *new_function(char *name)
5950 struct function **funcpp = find_function_slot(name);
5951 struct function *funcp = *funcpp;
5953 if (funcp != NULL) {
5954 struct command *cmd = funcp->parent_cmd;
5955 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5957 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5959 /* Note: if !funcp->body, do not free body_as_string!
5960 * This is a special case of "-F name body" function:
5961 * body_as_string was not malloced! */
5963 free_pipe_list(funcp->body);
5965 free(funcp->body_as_string);
5969 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5970 cmd->argv[0] = funcp->name;
5971 cmd->group = funcp->body;
5973 cmd->group_as_string = funcp->body_as_string;
5977 debug_printf_exec("remembering new function '%s'\n", name);
5978 funcp = *funcpp = xzalloc(sizeof(*funcp));
5979 /*funcp->next = NULL;*/
5986 static void unset_func(const char *name)
5988 struct function **funcpp = find_function_slot(name);
5989 struct function *funcp = *funcpp;
5991 if (funcp != NULL) {
5992 debug_printf_exec("freeing function '%s'\n", funcp->name);
5993 *funcpp = funcp->next;
5994 /* funcp is unlinked now, deleting it.
5995 * Note: if !funcp->body, the function was created by
5996 * "-F name body", do not free ->body_as_string
5997 * and ->name as they were not malloced. */
5999 free_pipe_list(funcp->body);
6002 free(funcp->body_as_string);
6010 #define exec_function(to_free, funcp, argv) \
6011 exec_function(funcp, argv)
6013 static void exec_function(char ***to_free,
6014 const struct function *funcp,
6015 char **argv) NORETURN;
6016 static void exec_function(char ***to_free,
6017 const struct function *funcp,
6023 argv[0] = G.global_argv[0];
6024 G.global_argv = argv;
6028 /* On MMU, funcp->body is always non-NULL */
6029 n = run_list(funcp->body);
6033 re_execute_shell(to_free,
6034 funcp->body_as_string,
6041 static int run_function(const struct function *funcp, char **argv)
6047 save_and_replace_G_args(&sv, argv);
6049 /* "we are in function, ok to use return" */
6050 sv_flg = G.flag_return_in_progress;
6051 G.flag_return_in_progress = -1;
6052 # if ENABLE_HUSH_LOCAL
6053 G.func_nest_level++;
6056 /* On MMU, funcp->body is always non-NULL */
6059 /* Function defined by -F */
6060 parse_and_run_string(funcp->body_as_string);
6061 rc = G.last_exitcode;
6065 rc = run_list(funcp->body);
6068 # if ENABLE_HUSH_LOCAL
6070 struct variable *var;
6071 struct variable **var_pp;
6073 var_pp = &G.top_var;
6074 while ((var = *var_pp) != NULL) {
6075 if (var->func_nest_level < G.func_nest_level) {
6076 var_pp = &var->next;
6080 if (var->flg_export)
6081 bb_unsetenv(var->varstr);
6082 /* Remove from global list */
6083 *var_pp = var->next;
6089 G.func_nest_level--;
6092 G.flag_return_in_progress = sv_flg;
6094 restore_G_args(&sv, argv);
6098 #endif /* ENABLE_HUSH_FUNCTIONS */
6102 #define exec_builtin(to_free, x, argv) \
6103 exec_builtin(x, argv)
6105 #define exec_builtin(to_free, x, argv) \
6106 exec_builtin(to_free, argv)
6108 static void exec_builtin(char ***to_free,
6109 const struct built_in_command *x,
6110 char **argv) NORETURN;
6111 static void exec_builtin(char ***to_free,
6112 const struct built_in_command *x,
6118 rcode = x->b_function(argv);
6123 /* On NOMMU, we must never block!
6124 * Example: { sleep 99 | read line; } & echo Ok
6126 re_execute_shell(to_free,
6135 static void execvp_or_die(char **argv) NORETURN;
6136 static void execvp_or_die(char **argv)
6138 debug_printf_exec("execing '%s'\n", argv[0]);
6139 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6140 execvp(argv[0], argv);
6141 bb_perror_msg("can't execute '%s'", argv[0]);
6142 _exit(127); /* bash compat */
6145 #if ENABLE_HUSH_MODE_X
6146 static void dump_cmd_in_x_mode(char **argv)
6148 if (G_x_mode && argv) {
6149 /* We want to output the line in one write op */
6157 len += strlen(argv[n++]) + 1;
6163 p += sprintf(p, " %s", argv[n++]);
6171 # define dump_cmd_in_x_mode(argv) ((void)0)
6175 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6176 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6177 #define pseudo_exec(nommu_save, command, argv_expanded) \
6178 pseudo_exec(command, argv_expanded)
6181 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6183 * Don't exit() here. If you don't exec, use _exit instead.
6184 * The at_exit handlers apparently confuse the calling process,
6185 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6186 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6187 char **argv, int assignment_cnt,
6188 char **argv_expanded) NORETURN;
6189 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6190 char **argv, int assignment_cnt,
6191 char **argv_expanded)
6195 new_env = expand_assignments(argv, assignment_cnt);
6196 dump_cmd_in_x_mode(new_env);
6198 if (!argv[assignment_cnt]) {
6199 /* Case when we are here: ... | var=val | ...
6200 * (note that we do not exit early, i.e., do not optimize out
6201 * expand_assignments(): think about ... | var=`sleep 1` | ...
6203 free_strings(new_env);
6204 _exit(EXIT_SUCCESS);
6208 set_vars_and_save_old(new_env);
6209 free(new_env); /* optional */
6210 /* we can also destroy set_vars_and_save_old's return value,
6213 nommu_save->new_env = new_env;
6214 nommu_save->old_vars = set_vars_and_save_old(new_env);
6217 if (argv_expanded) {
6218 argv = argv_expanded;
6220 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6222 nommu_save->argv = argv;
6225 dump_cmd_in_x_mode(argv);
6227 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6228 if (strchr(argv[0], '/') != NULL)
6232 /* Check if the command matches any of the builtins.
6233 * Depending on context, this might be redundant. But it's
6234 * easier to waste a few CPU cycles than it is to figure out
6235 * if this is one of those cases.
6238 /* On NOMMU, it is more expensive to re-execute shell
6239 * just in order to run echo or test builtin.
6240 * It's better to skip it here and run corresponding
6241 * non-builtin later. */
6242 const struct built_in_command *x;
6243 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6245 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6248 #if ENABLE_HUSH_FUNCTIONS
6249 /* Check if the command matches any functions */
6251 const struct function *funcp = find_function(argv[0]);
6253 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6258 #if ENABLE_FEATURE_SH_STANDALONE
6259 /* Check if the command matches any busybox applets */
6261 int a = find_applet_by_name(argv[0]);
6263 # if BB_MMU /* see above why on NOMMU it is not allowed */
6264 if (APPLET_IS_NOEXEC(a)) {
6265 debug_printf_exec("running applet '%s'\n", argv[0]);
6266 run_applet_no_and_exit(a, argv);
6269 /* Re-exec ourselves */
6270 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6271 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6272 execv(bb_busybox_exec_path, argv);
6273 /* If they called chroot or otherwise made the binary no longer
6274 * executable, fall through */
6279 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6282 execvp_or_die(argv);
6285 /* Called after [v]fork() in run_pipe
6287 static void pseudo_exec(nommu_save_t *nommu_save,
6288 struct command *command,
6289 char **argv_expanded) NORETURN;
6290 static void pseudo_exec(nommu_save_t *nommu_save,
6291 struct command *command,
6292 char **argv_expanded)
6294 if (command->argv) {
6295 pseudo_exec_argv(nommu_save, command->argv,
6296 command->assignment_cnt, argv_expanded);
6299 if (command->group) {
6300 /* Cases when we are here:
6303 * ... | ( list ) | ...
6304 * ... | { list } | ...
6308 debug_printf_exec("pseudo_exec: run_list\n");
6309 reset_traps_to_defaults();
6310 rcode = run_list(command->group);
6311 /* OK to leak memory by not calling free_pipe_list,
6312 * since this process is about to exit */
6315 re_execute_shell(&nommu_save->argv_from_re_execing,
6316 command->group_as_string,
6323 /* Case when we are here: ... | >file */
6324 debug_printf_exec("pseudo_exec'ed null command\n");
6325 _exit(EXIT_SUCCESS);
6329 static const char *get_cmdtext(struct pipe *pi)
6335 /* This is subtle. ->cmdtext is created only on first backgrounding.
6336 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6337 * On subsequent bg argv is trashed, but we won't use it */
6340 argv = pi->cmds[0].argv;
6341 if (!argv || !argv[0]) {
6342 pi->cmdtext = xzalloc(1);
6348 len += strlen(*argv) + 1;
6352 argv = pi->cmds[0].argv;
6354 len = strlen(*argv);
6355 memcpy(p, *argv, len);
6363 static void insert_bg_job(struct pipe *pi)
6365 struct pipe *job, **jobp;
6368 /* Linear search for the ID of the job to use */
6370 for (job = G.job_list; job; job = job->next)
6371 if (job->jobid >= pi->jobid)
6372 pi->jobid = job->jobid + 1;
6374 /* Add job to the list of running jobs */
6376 while ((job = *jobp) != NULL)
6378 job = *jobp = xmalloc(sizeof(*job));
6380 *job = *pi; /* physical copy */
6382 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6383 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6384 for (i = 0; i < pi->num_cmds; i++) {
6385 job->cmds[i].pid = pi->cmds[i].pid;
6386 /* all other fields are not used and stay zero */
6388 job->cmdtext = xstrdup(get_cmdtext(pi));
6390 if (G_interactive_fd)
6391 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6392 G.last_jobid = job->jobid;
6395 static void remove_bg_job(struct pipe *pi)
6397 struct pipe *prev_pipe;
6399 if (pi == G.job_list) {
6400 G.job_list = pi->next;
6402 prev_pipe = G.job_list;
6403 while (prev_pipe->next != pi)
6404 prev_pipe = prev_pipe->next;
6405 prev_pipe->next = pi->next;
6408 G.last_jobid = G.job_list->jobid;
6413 /* Remove a backgrounded job */
6414 static void delete_finished_bg_job(struct pipe *pi)
6421 /* Check to see if any processes have exited -- if they
6422 * have, figure out why and see if a job has completed */
6423 static int checkjobs(struct pipe *fg_pipe)
6433 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6435 attributes = WUNTRACED;
6436 if (fg_pipe == NULL)
6437 attributes |= WNOHANG;
6440 #if ENABLE_HUSH_FAST
6441 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6442 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6443 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6444 /* There was neither fork nor SIGCHLD since last waitpid */
6445 /* Avoid doing waitpid syscall if possible */
6446 if (!G.we_have_children) {
6450 if (fg_pipe == NULL) { /* is WNOHANG set? */
6451 /* We have children, but they did not exit
6452 * or stop yet (we saw no SIGCHLD) */
6455 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6459 /* Do we do this right?
6460 * bash-3.00# sleep 20 | false
6462 * [3]+ Stopped sleep 20 | false
6463 * bash-3.00# echo $?
6464 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6465 * [hush 1.14.0: yes we do it right]
6472 #if ENABLE_HUSH_FAST
6473 i = G.count_SIGCHLD;
6475 childpid = waitpid(-1, &status, attributes);
6476 if (childpid <= 0) {
6477 if (childpid && errno != ECHILD)
6478 bb_perror_msg("waitpid");
6479 #if ENABLE_HUSH_FAST
6480 else { /* Until next SIGCHLD, waitpid's are useless */
6481 G.we_have_children = (childpid == 0);
6482 G.handled_SIGCHLD = i;
6483 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6488 dead = WIFEXITED(status) || WIFSIGNALED(status);
6491 if (WIFSTOPPED(status))
6492 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6493 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6494 if (WIFSIGNALED(status))
6495 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6496 childpid, WTERMSIG(status), WEXITSTATUS(status));
6497 if (WIFEXITED(status))
6498 debug_printf_jobs("pid %d exited, exitcode %d\n",
6499 childpid, WEXITSTATUS(status));
6501 /* Were we asked to wait for fg pipe? */
6503 i = fg_pipe->num_cmds;
6505 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6506 if (fg_pipe->cmds[i].pid != childpid)
6510 fg_pipe->cmds[i].pid = 0;
6511 fg_pipe->alive_cmds--;
6512 ex = WEXITSTATUS(status);
6513 /* bash prints killer signal's name for *last*
6514 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6515 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6517 if (WIFSIGNALED(status)) {
6518 int sig = WTERMSIG(status);
6519 if (i == fg_pipe->num_cmds-1)
6520 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6521 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6522 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6523 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6524 * Maybe we need to use sig | 128? */
6527 fg_pipe->cmds[i].cmd_exitcode = ex;
6529 fg_pipe->cmds[i].is_stopped = 1;
6530 fg_pipe->stopped_cmds++;
6532 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6533 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6534 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6535 /* All processes in fg pipe have exited or stopped */
6536 i = fg_pipe->num_cmds;
6538 rcode = fg_pipe->cmds[i].cmd_exitcode;
6539 /* usually last process gives overall exitstatus,
6540 * but with "set -o pipefail", last *failed* process does */
6541 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6544 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6545 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6546 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6547 * and "killall -STOP cat" */
6548 if (G_interactive_fd) {
6550 if (fg_pipe->alive_cmds != 0)
6551 insert_bg_job(fg_pipe);
6555 if (fg_pipe->alive_cmds == 0)
6558 /* There are still running processes in the fg pipe */
6559 goto wait_more; /* do waitpid again */
6561 /* it wasnt fg_pipe, look for process in bg pipes */
6565 /* We asked to wait for bg or orphaned children */
6566 /* No need to remember exitcode in this case */
6567 for (pi = G.job_list; pi; pi = pi->next) {
6568 for (i = 0; i < pi->num_cmds; i++) {
6569 if (pi->cmds[i].pid == childpid)
6570 goto found_pi_and_prognum;
6573 /* Happens when shell is used as init process (init=/bin/sh) */
6574 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6575 continue; /* do waitpid again */
6577 found_pi_and_prognum:
6580 pi->cmds[i].pid = 0;
6582 if (!pi->alive_cmds) {
6583 if (G_interactive_fd)
6584 printf(JOB_STATUS_FORMAT, pi->jobid,
6585 "Done", pi->cmdtext);
6586 delete_finished_bg_job(pi);
6590 pi->cmds[i].is_stopped = 1;
6594 } /* while (waitpid succeeds)... */
6600 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6603 int rcode = checkjobs(fg_pipe);
6604 if (G_saved_tty_pgrp) {
6605 /* Job finished, move the shell to the foreground */
6606 p = getpgrp(); /* our process group id */
6607 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6608 tcsetpgrp(G_interactive_fd, p);
6614 /* Start all the jobs, but don't wait for anything to finish.
6617 * Return code is normally -1, when the caller has to wait for children
6618 * to finish to determine the exit status of the pipe. If the pipe
6619 * is a simple builtin command, however, the action is done by the
6620 * time run_pipe returns, and the exit code is provided as the
6623 * Returns -1 only if started some children. IOW: we have to
6624 * mask out retvals of builtins etc with 0xff!
6626 * The only case when we do not need to [v]fork is when the pipe
6627 * is single, non-backgrounded, non-subshell command. Examples:
6628 * cmd ; ... { list } ; ...
6629 * cmd && ... { list } && ...
6630 * cmd || ... { list } || ...
6631 * If it is, then we can run cmd as a builtin, NOFORK,
6632 * or (if SH_STANDALONE) an applet, and we can run the { list }
6633 * with run_list. If it isn't one of these, we fork and exec cmd.
6635 * Cases when we must fork:
6636 * non-single: cmd | cmd
6637 * backgrounded: cmd & { list } &
6638 * subshell: ( list ) [&]
6640 #if !ENABLE_HUSH_MODE_X
6641 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6642 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6644 static int redirect_and_varexp_helper(char ***new_env_p,
6645 struct variable **old_vars_p,
6646 struct command *command,
6648 char **argv_expanded)
6650 /* setup_redirects acts on file descriptors, not FILEs.
6651 * This is perfect for work that comes after exec().
6652 * Is it really safe for inline use? Experimentally,
6653 * things seem to work. */
6654 int rcode = setup_redirects(command, squirrel);
6656 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6657 *new_env_p = new_env;
6658 dump_cmd_in_x_mode(new_env);
6659 dump_cmd_in_x_mode(argv_expanded);
6661 *old_vars_p = set_vars_and_save_old(new_env);
6665 static NOINLINE int run_pipe(struct pipe *pi)
6667 static const char *const null_ptr = NULL;
6671 struct command *command;
6672 char **argv_expanded;
6674 /* it is not always needed, but we aim to smaller code */
6675 int squirrel[] = { -1, -1, -1 };
6678 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6681 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6682 * Result should be 3 lines: q w e, qwe, q w e
6684 G.ifs = get_local_var_value("IFS");
6688 IF_HUSH_JOB(pi->pgrp = -1;)
6689 pi->stopped_cmds = 0;
6690 command = &pi->cmds[0];
6691 argv_expanded = NULL;
6693 if (pi->num_cmds != 1
6694 || pi->followup == PIPE_BG
6695 || command->cmd_type == CMD_SUBSHELL
6702 debug_printf_exec(": group:%p argv:'%s'\n",
6703 command->group, command->argv ? command->argv[0] : "NONE");
6705 if (command->group) {
6706 #if ENABLE_HUSH_FUNCTIONS
6707 if (command->cmd_type == CMD_FUNCDEF) {
6708 /* "executing" func () { list } */
6709 struct function *funcp;
6711 funcp = new_function(command->argv[0]);
6712 /* funcp->name is already set to argv[0] */
6713 funcp->body = command->group;
6715 funcp->body_as_string = command->group_as_string;
6716 command->group_as_string = NULL;
6718 command->group = NULL;
6719 command->argv[0] = NULL;
6720 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6721 funcp->parent_cmd = command;
6722 command->child_func = funcp;
6724 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6726 return EXIT_SUCCESS;
6730 debug_printf("non-subshell group\n");
6731 rcode = 1; /* exitcode if redir failed */
6732 if (setup_redirects(command, squirrel) == 0) {
6733 debug_printf_exec(": run_list\n");
6734 rcode = run_list(command->group) & 0xff;
6736 restore_redirects(squirrel);
6737 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6739 debug_printf_exec("run_pipe: return %d\n", rcode);
6743 argv = command->argv ? command->argv : (char **) &null_ptr;
6745 const struct built_in_command *x;
6746 #if ENABLE_HUSH_FUNCTIONS
6747 const struct function *funcp;
6751 char **new_env = NULL;
6752 struct variable *old_vars = NULL;
6754 if (argv[command->assignment_cnt] == NULL) {
6755 /* Assignments, but no command */
6756 /* Ensure redirects take effect (that is, create files).
6757 * Try "a=t >file" */
6758 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6759 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6760 /* Set shell variables */
6764 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6765 /* Do we need to flag set_local_var() errors?
6766 * "assignment to readonly var" and "putenv error"
6771 /* Redirect error sets $? to 1. Otherwise,
6772 * if evaluating assignment value set $?, retain it.
6773 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6775 rcode = G.last_exitcode;
6776 /* Exit, _skipping_ variable restoring code: */
6777 goto clean_up_and_ret0;
6779 #else /* Older, bigger, but more correct code */
6781 rcode = setup_redirects(command, squirrel);
6782 restore_redirects(squirrel);
6783 /* Set shell variables */
6785 bb_putchar_stderr('+');
6787 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6789 fprintf(stderr, " %s", p);
6790 debug_printf_exec("set shell var:'%s'->'%s'\n",
6792 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6793 /* Do we need to flag set_local_var() errors?
6794 * "assignment to readonly var" and "putenv error"
6799 bb_putchar_stderr('\n');
6800 /* Redirect error sets $? to 1. Otherwise,
6801 * if evaluating assignment value set $?, retain it.
6802 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6804 rcode = G.last_exitcode;
6805 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6807 debug_printf_exec("run_pipe: return %d\n", rcode);
6812 /* Expand the rest into (possibly) many strings each */
6813 #if ENABLE_HUSH_BASH_COMPAT
6814 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6815 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6819 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6822 /* if someone gives us an empty string: `cmd with empty output` */
6823 if (!argv_expanded[0]) {
6824 free(argv_expanded);
6826 return G.last_exitcode;
6829 x = find_builtin(argv_expanded[0]);
6830 #if ENABLE_HUSH_FUNCTIONS
6833 funcp = find_function(argv_expanded[0]);
6837 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6838 debug_printf("exec with redirects only\n");
6839 rcode = setup_redirects(command, NULL);
6840 goto clean_up_and_ret1;
6843 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6846 debug_printf_exec(": builtin '%s' '%s'...\n",
6847 x->b_cmd, argv_expanded[1]);
6849 rcode = x->b_function(argv_expanded) & 0xff;
6852 #if ENABLE_HUSH_FUNCTIONS
6854 # if ENABLE_HUSH_LOCAL
6855 struct variable **sv;
6856 sv = G.shadowed_vars_pp;
6857 G.shadowed_vars_pp = &old_vars;
6859 debug_printf_exec(": function '%s' '%s'...\n",
6860 funcp->name, argv_expanded[1]);
6861 rcode = run_function(funcp, argv_expanded) & 0xff;
6862 # if ENABLE_HUSH_LOCAL
6863 G.shadowed_vars_pp = sv;
6869 unset_vars(new_env);
6871 /* clean_up_and_ret0: */
6872 restore_redirects(squirrel);
6874 free(argv_expanded);
6875 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6877 debug_printf_exec("run_pipe return %d\n", rcode);
6881 if (ENABLE_FEATURE_SH_NOFORK) {
6882 int n = find_applet_by_name(argv_expanded[0]);
6883 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6884 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6886 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6887 argv_expanded[0], argv_expanded[1]);
6888 rcode = run_nofork_applet(n, argv_expanded);
6890 goto clean_up_and_ret;
6893 /* It is neither builtin nor applet. We must fork. */
6897 /* NB: argv_expanded may already be created, and that
6898 * might include `cmd` runs! Do not rerun it! We *must*
6899 * use argv_expanded if it's non-NULL */
6901 /* Going to fork a child per each pipe member */
6906 while (cmd_no < pi->num_cmds) {
6907 struct fd_pair pipefds;
6909 volatile nommu_save_t nommu_save;
6910 nommu_save.new_env = NULL;
6911 nommu_save.old_vars = NULL;
6912 nommu_save.argv = NULL;
6913 nommu_save.argv_from_re_execing = NULL;
6915 command = &pi->cmds[cmd_no];
6917 if (command->argv) {
6918 debug_printf_exec(": pipe member '%s' '%s'...\n",
6919 command->argv[0], command->argv[1]);
6921 debug_printf_exec(": pipe member with no argv\n");
6924 /* pipes are inserted between pairs of commands */
6927 if (cmd_no < pi->num_cmds)
6928 xpiped_pair(pipefds);
6930 command->pid = BB_MMU ? fork() : vfork();
6931 if (!command->pid) { /* child */
6933 disable_restore_tty_pgrp_on_exit();
6934 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6936 /* Every child adds itself to new process group
6937 * with pgid == pid_of_first_child_in_pipe */
6938 if (G.run_list_level == 1 && G_interactive_fd) {
6941 if (pgrp < 0) /* true for 1st process only */
6943 if (setpgid(0, pgrp) == 0
6944 && pi->followup != PIPE_BG
6945 && G_saved_tty_pgrp /* we have ctty */
6947 /* We do it in *every* child, not just first,
6949 tcsetpgrp(G_interactive_fd, pgrp);
6953 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6954 /* 1st cmd in backgrounded pipe
6955 * should have its stdin /dev/null'ed */
6957 if (open(bb_dev_null, O_RDONLY))
6958 xopen("/", O_RDONLY);
6960 xmove_fd(next_infd, 0);
6962 xmove_fd(pipefds.wr, 1);
6965 /* Like bash, explicit redirects override pipes,
6966 * and the pipe fd is available for dup'ing. */
6967 if (setup_redirects(command, NULL))
6970 /* Restore default handlers just prior to exec */
6971 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6973 /* Stores to nommu_save list of env vars putenv'ed
6974 * (NOMMU, on MMU we don't need that) */
6975 /* cast away volatility... */
6976 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6977 /* pseudo_exec() does not return */
6980 /* parent or error */
6981 #if ENABLE_HUSH_FAST
6983 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6985 enable_restore_tty_pgrp_on_exit();
6987 /* Clean up after vforked child */
6988 free(nommu_save.argv);
6989 free(nommu_save.argv_from_re_execing);
6990 unset_vars(nommu_save.new_env);
6991 add_vars(nommu_save.old_vars);
6993 free(argv_expanded);
6994 argv_expanded = NULL;
6995 if (command->pid < 0) { /* [v]fork failed */
6996 /* Clearly indicate, was it fork or vfork */
6997 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7001 /* Second and next children need to know pid of first one */
7003 pi->pgrp = command->pid;
7009 if (cmd_no < pi->num_cmds)
7011 /* Pass read (output) pipe end to next iteration */
7012 next_infd = pipefds.rd;
7015 if (!pi->alive_cmds) {
7017 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7022 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7026 /* NB: called by pseudo_exec, and therefore must not modify any
7027 * global data until exec/_exit (we can be a child after vfork!) */
7028 static int run_list(struct pipe *pi)
7030 #if ENABLE_HUSH_CASE
7031 char *case_word = NULL;
7033 #if ENABLE_HUSH_LOOPS
7034 struct pipe *loop_top = NULL;
7035 char **for_lcur = NULL;
7036 char **for_list = NULL;
7038 smallint last_followup;
7040 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7041 smalluint cond_code = 0;
7043 enum { cond_code = 0 };
7046 smallint rword; /* RES_foo */
7047 smallint last_rword; /* ditto */
7050 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7053 #if ENABLE_HUSH_LOOPS
7054 /* Check syntax for "for" */
7057 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7058 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7060 /* current word is FOR or IN (BOLD in comments below) */
7061 if (cpipe->next == NULL) {
7062 syntax_error("malformed for");
7064 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7067 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7068 if (cpipe->next->res_word == RES_DO)
7070 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7071 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7072 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7074 syntax_error("malformed for");
7076 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7083 /* Past this point, all code paths should jump to ret: label
7084 * in order to return, no direct "return" statements please.
7085 * This helps to ensure that no memory is leaked. */
7093 last_rword = RES_XXXX;
7095 last_followup = PIPE_SEQ;
7096 rcode = G.last_exitcode;
7098 /* Go through list of pipes, (maybe) executing them. */
7099 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7103 IF_HAS_KEYWORDS(rword = pi->res_word;)
7104 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7105 rword, cond_code, last_rword);
7106 #if ENABLE_HUSH_LOOPS
7107 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7108 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7110 /* start of a loop: remember where loop starts */
7115 /* Still in the same "if...", "then..." or "do..." branch? */
7116 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7117 if ((rcode == 0 && last_followup == PIPE_OR)
7118 || (rcode != 0 && last_followup == PIPE_AND)
7120 /* It is "<true> || CMD" or "<false> && CMD"
7121 * and we should not execute CMD */
7122 debug_printf_exec("skipped cmd because of || or &&\n");
7123 last_followup = pi->followup;
7127 last_followup = pi->followup;
7128 IF_HAS_KEYWORDS(last_rword = rword;)
7131 if (rword == RES_THEN) {
7132 /* if false; then ... fi has exitcode 0! */
7133 G.last_exitcode = rcode = EXIT_SUCCESS;
7134 /* "if <false> THEN cmd": skip cmd */
7138 if (rword == RES_ELSE || rword == RES_ELIF) {
7139 /* "if <true> then ... ELSE/ELIF cmd":
7140 * skip cmd and all following ones */
7145 #if ENABLE_HUSH_LOOPS
7146 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7148 /* first loop through for */
7150 static const char encoded_dollar_at[] ALIGN1 = {
7151 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7152 }; /* encoded representation of "$@" */
7153 static const char *const encoded_dollar_at_argv[] = {
7154 encoded_dollar_at, NULL
7155 }; /* argv list with one element: "$@" */
7158 vals = (char**)encoded_dollar_at_argv;
7159 if (pi->next->res_word == RES_IN) {
7160 /* if no variable values after "in" we skip "for" */
7161 if (!pi->next->cmds[0].argv) {
7162 G.last_exitcode = rcode = EXIT_SUCCESS;
7163 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7166 vals = pi->next->cmds[0].argv;
7167 } /* else: "for var; do..." -> assume "$@" list */
7168 /* create list of variable values */
7169 debug_print_strings("for_list made from", vals);
7170 for_list = expand_strvec_to_strvec(vals);
7171 for_lcur = for_list;
7172 debug_print_strings("for_list", for_list);
7175 /* "for" loop is over, clean up */
7181 /* Insert next value from for_lcur */
7182 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7183 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7186 if (rword == RES_IN) {
7187 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7189 if (rword == RES_DONE) {
7190 continue; /* "done" has no cmds too */
7193 #if ENABLE_HUSH_CASE
7194 if (rword == RES_CASE) {
7195 case_word = expand_strvec_to_string(pi->cmds->argv);
7198 if (rword == RES_MATCH) {
7201 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7203 /* all prev words didn't match, does this one match? */
7204 argv = pi->cmds->argv;
7206 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7207 /* TODO: which FNM_xxx flags to use? */
7208 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7210 if (cond_code == 0) { /* match! we will execute this branch */
7211 free(case_word); /* make future "word)" stop */
7219 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7221 continue; /* not matched yet, skip this pipe */
7224 /* Just pressing <enter> in shell should check for jobs.
7225 * OTOH, in non-interactive shell this is useless
7226 * and only leads to extra job checks */
7227 if (pi->num_cmds == 0) {
7228 if (G_interactive_fd)
7229 goto check_jobs_and_continue;
7233 /* After analyzing all keywords and conditions, we decided
7234 * to execute this pipe. NB: have to do checkjobs(NULL)
7235 * after run_pipe to collect any background children,
7236 * even if list execution is to be stopped. */
7237 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7240 #if ENABLE_HUSH_LOOPS
7241 G.flag_break_continue = 0;
7243 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7245 /* We ran a builtin, function, or group.
7246 * rcode is already known
7247 * and we don't need to wait for anything. */
7248 G.last_exitcode = rcode;
7249 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7250 check_and_run_traps(0);
7251 #if ENABLE_HUSH_LOOPS
7252 /* Was it "break" or "continue"? */
7253 if (G.flag_break_continue) {
7254 smallint fbc = G.flag_break_continue;
7255 /* We might fall into outer *loop*,
7256 * don't want to break it too */
7258 G.depth_break_continue--;
7259 if (G.depth_break_continue == 0)
7260 G.flag_break_continue = 0;
7261 /* else: e.g. "continue 2" should *break* once, *then* continue */
7262 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7263 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7264 goto check_jobs_and_break;
7265 /* "continue": simulate end of loop */
7270 #if ENABLE_HUSH_FUNCTIONS
7271 if (G.flag_return_in_progress == 1) {
7272 /* same as "goto check_jobs_and_break" */
7277 } else if (pi->followup == PIPE_BG) {
7278 /* What does bash do with attempts to background builtins? */
7279 /* even bash 3.2 doesn't do that well with nested bg:
7280 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7281 * I'm NOT treating inner &'s as jobs */
7282 check_and_run_traps(0);
7284 if (G.run_list_level == 1)
7287 /* Last command's pid goes to $! */
7288 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7289 G.last_exitcode = rcode = EXIT_SUCCESS;
7290 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7293 if (G.run_list_level == 1 && G_interactive_fd) {
7294 /* Waits for completion, then fg's main shell */
7295 rcode = checkjobs_and_fg_shell(pi);
7296 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7297 check_and_run_traps(0);
7300 { /* This one just waits for completion */
7301 rcode = checkjobs(pi);
7302 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7303 check_and_run_traps(0);
7305 G.last_exitcode = rcode;
7309 /* Analyze how result affects subsequent commands */
7311 if (rword == RES_IF || rword == RES_ELIF)
7314 #if ENABLE_HUSH_LOOPS
7315 /* Beware of "while false; true; do ..."! */
7316 if (pi->next && pi->next->res_word == RES_DO) {
7317 if (rword == RES_WHILE) {
7319 /* "while false; do...done" - exitcode 0 */
7320 G.last_exitcode = rcode = EXIT_SUCCESS;
7321 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7322 goto check_jobs_and_break;
7325 if (rword == RES_UNTIL) {
7327 debug_printf_exec(": until expr is true: breaking\n");
7328 check_jobs_and_break:
7336 check_jobs_and_continue:
7343 #if ENABLE_HUSH_LOOPS
7348 #if ENABLE_HUSH_CASE
7352 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7356 /* Select which version we will use */
7357 static int run_and_free_list(struct pipe *pi)
7360 debug_printf_exec("run_and_free_list entered\n");
7361 if (!G.o_opt[OPT_O_NOEXEC]) {
7362 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7363 rcode = run_list(pi);
7365 /* free_pipe_list has the side effect of clearing memory.
7366 * In the long run that function can be merged with run_list,
7367 * but doing that now would hobble the debugging effort. */
7369 debug_printf_exec("run_and_free_list return %d\n", rcode);
7374 /* Called a few times only (or even once if "sh -c") */
7375 static void init_sigmasks(void)
7379 sigset_t old_blocked_set;
7381 if (!G.inherited_set_is_saved) {
7382 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7383 G.inherited_set = G.blocked_set;
7385 old_blocked_set = G.blocked_set;
7387 mask = (1 << SIGQUIT);
7388 if (G_interactive_fd) {
7389 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
7390 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7391 mask |= SPECIAL_JOB_SIGS;
7393 G.non_DFL_mask = mask;
7398 sigaddset(&G.blocked_set, sig);
7402 sigdelset(&G.blocked_set, SIGCHLD);
7404 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7405 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7407 /* POSIX allows shell to re-enable SIGCHLD
7408 * even if it was SIG_IGN on entry */
7409 #if ENABLE_HUSH_FAST
7410 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7411 if (!G.inherited_set_is_saved)
7412 signal(SIGCHLD, SIGCHLD_handler);
7414 if (!G.inherited_set_is_saved)
7415 signal(SIGCHLD, SIG_DFL);
7418 G.inherited_set_is_saved = 1;
7423 static void maybe_set_to_sigexit(int sig)
7425 void (*handler)(int);
7426 /* non_DFL_mask'ed signals are, well, masked,
7427 * no need to set handler for them.
7429 if (!((G.non_DFL_mask >> sig) & 1)) {
7430 handler = signal(sig, sigexit);
7431 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7432 signal(sig, handler);
7435 /* Set handlers to restore tty pgrp and exit */
7436 static void set_fatal_handlers(void)
7438 /* We _must_ restore tty pgrp on fatal signals */
7440 maybe_set_to_sigexit(SIGILL );
7441 maybe_set_to_sigexit(SIGFPE );
7442 maybe_set_to_sigexit(SIGBUS );
7443 maybe_set_to_sigexit(SIGSEGV);
7444 maybe_set_to_sigexit(SIGTRAP);
7445 } /* else: hush is perfect. what SEGV? */
7446 maybe_set_to_sigexit(SIGABRT);
7447 /* bash 3.2 seems to handle these just like 'fatal' ones */
7448 maybe_set_to_sigexit(SIGPIPE);
7449 maybe_set_to_sigexit(SIGALRM);
7450 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7451 * if we aren't interactive... but in this case
7452 * we never want to restore pgrp on exit, and this fn is not called */
7453 /*maybe_set_to_sigexit(SIGHUP );*/
7454 /*maybe_set_to_sigexit(SIGTERM);*/
7455 /*maybe_set_to_sigexit(SIGINT );*/
7459 static int set_mode(int state, char mode, const char *o_opt)
7464 G.o_opt[OPT_O_NOEXEC] = state;
7467 IF_HUSH_MODE_X(G_x_mode = state;)
7471 /* "set -+o" without parameter.
7472 * in bash, set -o produces this output:
7476 * We always use the second form.
7478 const char *p = o_opt_strings;
7481 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7487 idx = index_in_strings(o_opt_strings, o_opt);
7489 G.o_opt[idx] = state;
7493 return EXIT_FAILURE;
7495 return EXIT_SUCCESS;
7498 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7499 int hush_main(int argc, char **argv)
7502 unsigned builtin_argc;
7504 struct variable *cur_var;
7505 struct variable *shell_ver;
7508 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
7509 G.last_exitcode = EXIT_SUCCESS;
7511 G.argv0_for_re_execing = argv[0];
7513 /* Deal with HUSH_VERSION */
7514 shell_ver = xzalloc(sizeof(*shell_ver));
7515 shell_ver->flg_export = 1;
7516 shell_ver->flg_read_only = 1;
7517 /* Code which handles ${var<op>...} needs writable values for all variables,
7518 * therefore we xstrdup: */
7519 shell_ver->varstr = xstrdup(hush_version_str);
7520 /* Create shell local variables from the values
7521 * currently living in the environment */
7522 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7523 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7524 G.top_var = shell_ver;
7525 cur_var = G.top_var;
7528 char *value = strchr(*e, '=');
7529 if (value) { /* paranoia */
7530 cur_var->next = xzalloc(sizeof(*cur_var));
7531 cur_var = cur_var->next;
7532 cur_var->varstr = *e;
7533 cur_var->max_len = strlen(*e);
7534 cur_var->flg_export = 1;
7538 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7539 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7540 putenv(shell_ver->varstr);
7543 set_pwd_var(/*exp:*/ 1);
7544 /* bash also exports SHLVL and _,
7545 * and sets (but doesn't export) the following variables:
7547 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7548 * BASH_VERSION='3.2.0(1)-release'
7550 * MACHTYPE=i386-pc-linux-gnu
7552 * HOSTNAME=<xxxxxxxxxx>
7553 * PPID=<NNNNN> - we also do it elsewhere
7564 * PIPESTATUS=([0]="0")
7565 * HISTFILE=/<xxx>/.bash_history
7569 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7571 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7581 #if ENABLE_FEATURE_EDITING
7582 G.line_input_state = new_line_input_t(FOR_SHELL);
7583 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7585 const char *hp = get_local_var_value("HISTFILE");
7587 hp = get_local_var_value("HOME");
7589 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7590 //set_local_var(xasprintf("HISTFILE=%s", ...));
7597 G.global_argc = argc;
7598 G.global_argv = argv;
7599 /* Initialize some more globals to non-zero values */
7600 cmdedit_update_prompt();
7602 if (setjmp(die_jmp)) {
7603 /* xfunc has failed! die die die */
7604 /* no EXIT traps, this is an escape hatch! */
7606 hush_exit(xfunc_error_retval);
7609 /* Shell is non-interactive at first. We need to call
7610 * init_sigmasks() if we are going to execute "sh <script>",
7611 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7612 * If we later decide that we are interactive, we run init_sigmasks()
7613 * in order to intercept (more) signals.
7617 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7620 opt = getopt(argc, argv, "+c:xins"
7623 # if ENABLE_HUSH_FUNCTIONS
7633 * sh ... -c 'script'
7634 * sh ... -c 'script' ARG0 [ARG1...]
7635 * On NOMMU, if builtin_argc != 0,
7636 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7637 * "" needs to be replaced with NULL
7638 * and BARGV vector fed to builtin function.
7639 * Note: the form without ARG0 never happens:
7640 * sh ... -c 'builtin' BARGV... ""
7643 G.root_pid = getpid();
7644 G.root_ppid = getppid();
7646 G.global_argv = argv + optind;
7647 G.global_argc = argc - optind;
7649 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7650 const struct built_in_command *x;
7653 x = find_builtin(optarg);
7654 if (x) { /* paranoia */
7655 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7656 G.global_argv += builtin_argc;
7657 G.global_argv[-1] = NULL; /* replace "" */
7659 G.last_exitcode = x->b_function(argv + optind - 1);
7663 if (!G.global_argv[0]) {
7664 /* -c 'script' (no params): prevent empty $0 */
7665 G.global_argv--; /* points to argv[i] of 'script' */
7666 G.global_argv[0] = argv[0];
7668 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7670 parse_and_run_string(optarg);
7673 /* Well, we cannot just declare interactiveness,
7674 * we have to have some stuff (ctty, etc) */
7675 /* G_interactive_fd++; */
7678 /* "-s" means "read from stdin", but this is how we always
7679 * operate, so simply do nothing here. */
7682 case '<': /* "big heredoc" support */
7683 full_write1_str(optarg);
7686 unsigned long long empty_trap_mask;
7688 G.root_pid = bb_strtou(optarg, &optarg, 16);
7690 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7692 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7694 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7696 builtin_argc = bb_strtou(optarg, &optarg, 16);
7698 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7699 if (empty_trap_mask != 0) {
7702 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7703 for (sig = 1; sig < NSIG; sig++) {
7704 if (empty_trap_mask & (1LL << sig)) {
7705 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7706 sigaddset(&G.blocked_set, sig);
7709 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7711 # if ENABLE_HUSH_LOOPS
7713 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7719 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7721 # if ENABLE_HUSH_FUNCTIONS
7723 struct function *funcp = new_function(optarg);
7724 /* funcp->name is already set to optarg */
7725 /* funcp->body is set to NULL. It's a special case. */
7726 funcp->body_as_string = argv[optind];
7734 if (set_mode(1, opt, NULL) == 0) /* no error */
7738 fprintf(stderr, "Usage: sh [FILE]...\n"
7739 " or: sh -c command [args]...\n\n");
7745 } /* option parsing loop */
7748 G.root_pid = getpid();
7749 G.root_ppid = getppid();
7752 /* If we are login shell... */
7753 if (argv[0] && argv[0][0] == '-') {
7755 debug_printf("sourcing /etc/profile\n");
7756 input = fopen_for_read("/etc/profile");
7757 if (input != NULL) {
7758 close_on_exec_on(fileno(input));
7760 parse_and_run_file(input);
7763 /* bash: after sourcing /etc/profile,
7764 * tries to source (in the given order):
7765 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7766 * stopping on first found. --noprofile turns this off.
7767 * bash also sources ~/.bash_logout on exit.
7768 * If called as sh, skips .bash_XXX files.
7775 * "bash <script>" (which is never interactive (unless -i?))
7776 * sources $BASH_ENV here (without scanning $PATH).
7777 * If called as sh, does the same but with $ENV.
7779 debug_printf("running script '%s'\n", argv[optind]);
7780 G.global_argv = argv + optind;
7781 G.global_argc = argc - optind;
7782 input = xfopen_for_read(argv[optind]);
7783 close_on_exec_on(fileno(input));
7785 parse_and_run_file(input);
7786 #if ENABLE_FEATURE_CLEAN_UP
7792 /* Up to here, shell was non-interactive. Now it may become one.
7793 * NB: don't forget to (re)run init_sigmasks() as needed.
7796 /* A shell is interactive if the '-i' flag was given,
7797 * or if all of the following conditions are met:
7799 * no arguments remaining or the -s flag given
7800 * standard input is a terminal
7801 * standard output is a terminal
7802 * Refer to Posix.2, the description of the 'sh' utility.
7805 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7806 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7807 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7808 if (G_saved_tty_pgrp < 0)
7809 G_saved_tty_pgrp = 0;
7811 /* try to dup stdin to high fd#, >= 255 */
7812 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7813 if (G_interactive_fd < 0) {
7814 /* try to dup to any fd */
7815 G_interactive_fd = dup(STDIN_FILENO);
7816 if (G_interactive_fd < 0) {
7818 G_interactive_fd = 0;
7819 G_saved_tty_pgrp = 0;
7822 // TODO: track & disallow any attempts of user
7823 // to (inadvertently) close/redirect G_interactive_fd
7825 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7826 if (G_interactive_fd) {
7827 close_on_exec_on(G_interactive_fd);
7829 if (G_saved_tty_pgrp) {
7830 /* If we were run as 'hush &', sleep until we are
7831 * in the foreground (tty pgrp == our pgrp).
7832 * If we get started under a job aware app (like bash),
7833 * make sure we are now in charge so we don't fight over
7834 * who gets the foreground */
7836 pid_t shell_pgrp = getpgrp();
7837 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7838 if (G_saved_tty_pgrp == shell_pgrp)
7840 /* send TTIN to ourself (should stop us) */
7841 kill(- shell_pgrp, SIGTTIN);
7845 /* Block some signals */
7848 if (G_saved_tty_pgrp) {
7849 /* Set other signals to restore saved_tty_pgrp */
7850 set_fatal_handlers();
7851 /* Put ourselves in our own process group
7852 * (bash, too, does this only if ctty is available) */
7853 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7854 /* Grab control of the terminal */
7855 tcsetpgrp(G_interactive_fd, getpid());
7857 /* -1 is special - makes xfuncs longjmp, not exit
7858 * (we reset die_sleep = 0 whereever we [v]fork) */
7859 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
7863 #elif ENABLE_HUSH_INTERACTIVE
7864 /* No job control compiled in, only prompt/line editing */
7865 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7866 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7867 if (G_interactive_fd < 0) {
7868 /* try to dup to any fd */
7869 G_interactive_fd = dup(STDIN_FILENO);
7870 if (G_interactive_fd < 0)
7872 G_interactive_fd = 0;
7875 if (G_interactive_fd) {
7876 close_on_exec_on(G_interactive_fd);
7880 /* We have interactiveness code disabled */
7884 * if interactive but not a login shell, sources ~/.bashrc
7885 * (--norc turns this off, --rcfile <file> overrides)
7888 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
7889 /* note: ash and hush share this string */
7890 printf("\n\n%s %s\n"
7891 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7894 "hush - the humble shell"
7898 parse_and_run_file(stdin);
7901 hush_exit(G.last_exitcode);
7906 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7907 int msh_main(int argc, char **argv)
7909 //bb_error_msg("msh is deprecated, please use hush instead");
7910 return hush_main(argc, argv);
7918 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
7923 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
7930 return applet_main_func(argc, argv - argc);
7933 static int FAST_FUNC builtin_test(char **argv)
7935 return run_applet_main(argv, test_main);
7938 static int FAST_FUNC builtin_echo(char **argv)
7940 return run_applet_main(argv, echo_main);
7944 static int FAST_FUNC builtin_printf(char **argv)
7946 return run_applet_main(argv, printf_main);
7950 static char **skip_dash_dash(char **argv)
7953 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7958 static int FAST_FUNC builtin_eval(char **argv)
7960 int rcode = EXIT_SUCCESS;
7962 argv = skip_dash_dash(argv);
7964 char *str = expand_strvec_to_string(argv);
7966 * eval "echo Hi; done" ("done" is syntax error):
7967 * "echo Hi" will not execute too.
7969 parse_and_run_string(str);
7971 rcode = G.last_exitcode;
7976 static int FAST_FUNC builtin_cd(char **argv)
7980 argv = skip_dash_dash(argv);
7982 if (newdir == NULL) {
7983 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
7984 * bash says "bash: cd: HOME not set" and does nothing
7987 const char *home = get_local_var_value("HOME");
7988 newdir = home ? home : "/";
7990 if (chdir(newdir)) {
7991 /* Mimic bash message exactly */
7992 bb_perror_msg("cd: %s", newdir);
7993 return EXIT_FAILURE;
7995 /* Read current dir (get_cwd(1) is inside) and set PWD.
7996 * Note: do not enforce exporting. If PWD was unset or unexported,
7997 * set it again, but do not export. bash does the same.
7999 set_pwd_var(/*exp:*/ 0);
8000 return EXIT_SUCCESS;
8003 static int FAST_FUNC builtin_exec(char **argv)
8005 argv = skip_dash_dash(argv);
8006 if (argv[0] == NULL)
8007 return EXIT_SUCCESS; /* bash does this */
8009 /* Careful: we can end up here after [v]fork. Do not restore
8010 * tty pgrp then, only top-level shell process does that */
8011 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8012 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8014 /* TODO: if exec fails, bash does NOT exit! We do.
8015 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8016 * and tcsetpgrp, and this is inherently racy.
8018 execvp_or_die(argv);
8021 static int FAST_FUNC builtin_exit(char **argv)
8023 debug_printf_exec("%s()\n", __func__);
8025 /* interactive bash:
8026 * # trap "echo EEE" EXIT
8029 * There are stopped jobs.
8030 * (if there are _stopped_ jobs, running ones don't count)
8033 # EEE (then bash exits)
8035 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8038 /* note: EXIT trap is run by hush_exit */
8039 argv = skip_dash_dash(argv);
8040 if (argv[0] == NULL)
8041 hush_exit(G.last_exitcode);
8042 /* mimic bash: exit 123abc == exit 255 + error msg */
8043 xfunc_error_retval = 255;
8044 /* bash: exit -2 == exit 254, no error msg */
8045 hush_exit(xatoi(argv[0]) & 0xff);
8048 static void print_escaped(const char *s)
8053 const char *p = strchrnul(s, '\'');
8054 /* print 'xxxx', possibly just '' */
8055 printf("'%.*s'", (int)(p - s), s);
8060 /* s points to '; print "'''...'''" */
8062 do putchar('\''); while (*++s == '\'');
8067 #if !ENABLE_HUSH_LOCAL
8068 #define helper_export_local(argv, exp, lvl) \
8069 helper_export_local(argv, exp)
8071 static void helper_export_local(char **argv, int exp, int lvl)
8075 char *name_end = strchrnul(name, '=');
8077 /* So far we do not check that name is valid (TODO?) */
8079 if (*name_end == '\0') {
8080 struct variable *var, **vpp;
8082 vpp = get_ptr_to_local_var(name, name_end - name);
8083 var = vpp ? *vpp : NULL;
8085 if (exp == -1) { /* unexporting? */
8086 /* export -n NAME (without =VALUE) */
8088 var->flg_export = 0;
8089 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8091 } /* else: export -n NOT_EXISTING_VAR: no-op */
8094 if (exp == 1) { /* exporting? */
8095 /* export NAME (without =VALUE) */
8097 var->flg_export = 1;
8098 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8099 putenv(var->varstr);
8103 /* Exporting non-existing variable.
8104 * bash does not put it in environment,
8105 * but remembers that it is exported,
8106 * and does put it in env when it is set later.
8107 * We just set it to "" and export. */
8108 /* Or, it's "local NAME" (without =VALUE).
8109 * bash sets the value to "". */
8110 name = xasprintf("%s=", name);
8112 /* (Un)exporting/making local NAME=VALUE */
8113 name = xstrdup(name);
8115 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8119 static int FAST_FUNC builtin_export(char **argv)
8121 unsigned opt_unexport;
8123 #if ENABLE_HUSH_EXPORT_N
8124 /* "!": do not abort on errors */
8125 opt_unexport = getopt32(argv, "!n");
8126 if (opt_unexport == (uint32_t)-1)
8127 return EXIT_FAILURE;
8134 if (argv[0] == NULL) {
8141 /* ash emits: export VAR='VAL'
8142 * bash: declare -x VAR="VAL"
8143 * we follow ash example */
8144 const char *s = *e++;
8145 const char *p = strchr(s, '=');
8147 if (!p) /* wtf? take next variable */
8150 printf("export %.*s", (int)(p - s) + 1, s);
8151 print_escaped(p + 1);
8155 /*fflush_all(); - done after each builtin anyway */
8157 return EXIT_SUCCESS;
8160 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8162 return EXIT_SUCCESS;
8165 #if ENABLE_HUSH_LOCAL
8166 static int FAST_FUNC builtin_local(char **argv)
8168 if (G.func_nest_level == 0) {
8169 bb_error_msg("%s: not in a function", argv[0]);
8170 return EXIT_FAILURE; /* bash compat */
8172 helper_export_local(argv, 0, G.func_nest_level);
8173 return EXIT_SUCCESS;
8177 static int FAST_FUNC builtin_trap(char **argv)
8183 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8188 /* No args: print all trapped */
8189 for (i = 0; i < NSIG; ++i) {
8192 print_escaped(G.traps[i]);
8193 /* note: bash adds "SIG", but only if invoked
8194 * as "bash". If called as "sh", or if set -o posix,
8195 * then it prints short signal names.
8196 * We are printing short names: */
8197 printf(" %s\n", get_signame(i));
8200 /*fflush_all(); - done after each builtin anyway */
8201 return EXIT_SUCCESS;
8205 /* If first arg is a number: reset all specified signals */
8206 sig = bb_strtou(*argv, NULL, 10);
8212 sig = get_signum(*argv++);
8213 if (sig < 0 || sig >= NSIG) {
8215 /* Mimic bash message exactly */
8216 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8221 G.traps[sig] = xstrdup(new_cmd);
8223 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8224 get_signame(sig), sig, G.traps[sig]);
8226 /* There is no signal for 0 (EXIT) */
8231 sigaddset(&G.blocked_set, sig);
8233 /* There was a trap handler, we are removing it
8234 * (if sig has non-DFL handling,
8235 * we don't need to do anything) */
8236 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8238 sigdelset(&G.blocked_set, sig);
8241 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8245 if (!argv[1]) { /* no second arg */
8246 bb_error_msg("trap: invalid arguments");
8247 return EXIT_FAILURE;
8250 /* First arg is "-": reset all specified to default */
8251 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8252 /* Everything else: set arg as signal handler
8253 * (includes "" case, which ignores signal) */
8254 if (argv[0][0] == '-') {
8255 if (argv[0][1] == '\0') { /* "-" */
8256 /* new_cmd remains NULL: "reset these sigs" */
8259 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8262 /* else: "-something", no special meaning */
8267 goto process_sig_list;
8270 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8271 static int FAST_FUNC builtin_type(char **argv)
8273 int ret = EXIT_SUCCESS;
8279 if (0) {} /* make conditional compile easier below */
8280 /*else if (find_alias(*argv))
8281 type = "an alias";*/
8282 #if ENABLE_HUSH_FUNCTIONS
8283 else if (find_function(*argv))
8284 type = "a function";
8286 else if (find_builtin(*argv))
8287 type = "a shell builtin";
8288 else if ((path = find_in_path(*argv)) != NULL)
8291 bb_error_msg("type: %s: not found", *argv);
8296 printf("%s is %s\n", *argv, type);
8304 /* built-in 'fg' and 'bg' handler */
8305 static int FAST_FUNC builtin_fg_bg(char **argv)
8310 if (!G_interactive_fd)
8311 return EXIT_FAILURE;
8313 /* If they gave us no args, assume they want the last backgrounded task */
8315 for (pi = G.job_list; pi; pi = pi->next) {
8316 if (pi->jobid == G.last_jobid) {
8320 bb_error_msg("%s: no current job", argv[0]);
8321 return EXIT_FAILURE;
8323 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8324 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8325 return EXIT_FAILURE;
8327 for (pi = G.job_list; pi; pi = pi->next) {
8328 if (pi->jobid == jobnum) {
8332 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8333 return EXIT_FAILURE;
8335 /* TODO: bash prints a string representation
8336 * of job being foregrounded (like "sleep 1 | cat") */
8337 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8338 /* Put the job into the foreground. */
8339 tcsetpgrp(G_interactive_fd, pi->pgrp);
8342 /* Restart the processes in the job */
8343 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8344 for (i = 0; i < pi->num_cmds; i++) {
8345 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8346 pi->cmds[i].is_stopped = 0;
8348 pi->stopped_cmds = 0;
8350 i = kill(- pi->pgrp, SIGCONT);
8352 if (errno == ESRCH) {
8353 delete_finished_bg_job(pi);
8354 return EXIT_SUCCESS;
8356 bb_perror_msg("kill (SIGCONT)");
8359 if (argv[0][0] == 'f') {
8361 return checkjobs_and_fg_shell(pi);
8363 return EXIT_SUCCESS;
8367 #if ENABLE_HUSH_HELP
8368 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8370 const struct built_in_command *x;
8373 "Built-in commands:\n"
8374 "------------------\n");
8375 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8377 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8380 return EXIT_SUCCESS;
8385 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8388 const char *status_string;
8390 for (job = G.job_list; job; job = job->next) {
8391 if (job->alive_cmds == job->stopped_cmds)
8392 status_string = "Stopped";
8394 status_string = "Running";
8396 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8398 return EXIT_SUCCESS;
8403 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8408 # ifdef M_TRIM_THRESHOLD
8409 /* Optional. Reduces probability of false positives */
8412 /* Crude attempt to find where "free memory" starts,
8413 * sans fragmentation. */
8415 l = (unsigned long)p;
8418 if (l < (unsigned long)p) l = (unsigned long)p;
8421 if (!G.memleak_value)
8422 G.memleak_value = l;
8424 l -= G.memleak_value;
8431 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8436 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8439 return EXIT_SUCCESS;
8442 static int FAST_FUNC builtin_read(char **argv)
8451 /* "!": do not abort on errors.
8452 * Option string must start with "sr" to match BUILTIN_READ_xxx
8454 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8455 if (read_flags == (uint32_t)-1)
8456 return EXIT_FAILURE;
8459 r = shell_builtin_read(set_local_var_from_halves,
8461 get_local_var_value("IFS"), /* can be NULL */
8469 if ((uintptr_t)r > 1) {
8470 bb_error_msg("%s", r);
8471 r = (char*)(uintptr_t)1;
8474 return (uintptr_t)r;
8477 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8478 * built-in 'set' handler
8480 * set [-abCefhmnuvx] [-o option] [argument...]
8481 * set [+abCefhmnuvx] [+o option] [argument...]
8482 * set -- [argument...]
8485 * Implementations shall support the options in both their hyphen and
8486 * plus-sign forms. These options can also be specified as options to sh.
8488 * Write out all variables and their values: set
8489 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8490 * Turn on the -x and -v options: set -xv
8491 * Unset all positional parameters: set --
8492 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8493 * Set the positional parameters to the expansion of x, even if x expands
8494 * with a leading '-' or '+': set -- $x
8496 * So far, we only support "set -- [argument...]" and some of the short names.
8498 static int FAST_FUNC builtin_set(char **argv)
8501 char **pp, **g_argv;
8502 char *arg = *++argv;
8506 for (e = G.top_var; e; e = e->next)
8508 return EXIT_SUCCESS;
8512 if (strcmp(arg, "--") == 0) {
8516 if (arg[0] != '+' && arg[0] != '-')
8518 for (n = 1; arg[n]; ++n) {
8519 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8521 if (arg[n] == 'o' && argv[1])
8524 } while ((arg = *++argv) != NULL);
8525 /* Now argv[0] is 1st argument */
8528 return EXIT_SUCCESS;
8531 /* NB: G.global_argv[0] ($0) is never freed/changed */
8532 g_argv = G.global_argv;
8533 if (G.global_args_malloced) {
8539 G.global_args_malloced = 1;
8540 pp = xzalloc(sizeof(pp[0]) * 2);
8541 pp[0] = g_argv[0]; /* retain $0 */
8544 /* This realloc's G.global_argv */
8545 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8552 return EXIT_SUCCESS;
8554 /* Nothing known, so abort */
8556 bb_error_msg("set: %s: invalid option", arg);
8557 return EXIT_FAILURE;
8560 static int FAST_FUNC builtin_shift(char **argv)
8563 argv = skip_dash_dash(argv);
8567 if (n >= 0 && n < G.global_argc) {
8568 if (G.global_args_malloced) {
8571 free(G.global_argv[m++]);
8574 memmove(&G.global_argv[1], &G.global_argv[n+1],
8575 G.global_argc * sizeof(G.global_argv[0]));
8576 return EXIT_SUCCESS;
8578 return EXIT_FAILURE;
8581 static int FAST_FUNC builtin_source(char **argv)
8583 char *arg_path, *filename;
8586 #if ENABLE_HUSH_FUNCTIONS
8590 argv = skip_dash_dash(argv);
8593 /* bash says: "bash: .: filename argument required" */
8594 return 2; /* bash compat */
8597 if (!strchr(filename, '/')) {
8598 arg_path = find_in_path(filename);
8600 filename = arg_path;
8602 input = fopen_or_warn(filename, "r");
8605 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8606 return EXIT_FAILURE;
8608 close_on_exec_on(fileno(input));
8610 #if ENABLE_HUSH_FUNCTIONS
8611 sv_flg = G.flag_return_in_progress;
8612 /* "we are inside sourced file, ok to use return" */
8613 G.flag_return_in_progress = -1;
8615 save_and_replace_G_args(&sv, argv);
8617 parse_and_run_file(input);
8620 restore_G_args(&sv, argv);
8621 #if ENABLE_HUSH_FUNCTIONS
8622 G.flag_return_in_progress = sv_flg;
8625 return G.last_exitcode;
8628 static int FAST_FUNC builtin_umask(char **argv)
8634 argv = skip_dash_dash(argv);
8636 mode_t old_mask = mask;
8639 rc = bb_parse_mode(argv[0], &mask);
8644 * bash: umask: 'q': invalid symbolic mode operator
8645 * bash: umask: 999: octal number out of range
8647 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8652 printf("%04o\n", (unsigned) mask);
8653 /* fall through and restore mask which we set to 0 */
8657 return !rc; /* rc != 0 - success */
8660 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8661 static int FAST_FUNC builtin_unset(char **argv)
8666 /* "!": do not abort on errors */
8667 /* "+": stop at 1st non-option */
8668 opts = getopt32(argv, "!+vf");
8669 if (opts == (unsigned)-1)
8670 return EXIT_FAILURE;
8672 bb_error_msg("unset: -v and -f are exclusive");
8673 return EXIT_FAILURE;
8679 if (!(opts & 2)) { /* not -f */
8680 if (unset_local_var(*argv)) {
8681 /* unset <nonexistent_var> doesn't fail.
8682 * Error is when one tries to unset RO var.
8683 * Message was printed by unset_local_var. */
8687 #if ENABLE_HUSH_FUNCTIONS
8697 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8698 static int FAST_FUNC builtin_wait(char **argv)
8700 int ret = EXIT_SUCCESS;
8703 argv = skip_dash_dash(argv);
8704 if (argv[0] == NULL) {
8705 /* Don't care about wait results */
8706 /* Note 1: must wait until there are no more children */
8707 /* Note 2: must be interruptible */
8709 * $ sleep 3 & sleep 6 & wait
8714 * $ sleep 3 & sleep 6 & wait
8718 * ^C <-- after ~4 sec from keyboard
8721 sigaddset(&G.blocked_set, SIGCHLD);
8722 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8725 if (errno == ECHILD)
8727 /* Wait for SIGCHLD or any other signal of interest */
8728 /* sigtimedwait with infinite timeout: */
8729 sig = sigwaitinfo(&G.blocked_set, NULL);
8731 sig = check_and_run_traps(sig);
8732 if (sig && sig != SIGCHLD) { /* see note 2 */
8738 sigdelset(&G.blocked_set, SIGCHLD);
8739 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8743 /* This is probably buggy wrt interruptible-ness */
8745 pid_t pid = bb_strtou(*argv, NULL, 10);
8747 /* mimic bash message */
8748 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8749 return EXIT_FAILURE;
8751 if (waitpid(pid, &status, 0) == pid) {
8752 if (WIFSIGNALED(status))
8753 ret = 128 + WTERMSIG(status);
8754 else if (WIFEXITED(status))
8755 ret = WEXITSTATUS(status);
8759 bb_perror_msg("wait %s", *argv);
8768 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8769 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8772 def = bb_strtou(argv[1], NULL, 10);
8773 if (errno || def < def_min || argv[2]) {
8774 bb_error_msg("%s: bad arguments", argv[0]);
8782 #if ENABLE_HUSH_LOOPS
8783 static int FAST_FUNC builtin_break(char **argv)
8786 if (G.depth_of_loop == 0) {
8787 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8788 return EXIT_SUCCESS; /* bash compat */
8790 G.flag_break_continue++; /* BC_BREAK = 1 */
8792 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8793 if (depth == UINT_MAX)
8794 G.flag_break_continue = BC_BREAK;
8795 if (G.depth_of_loop < depth)
8796 G.depth_break_continue = G.depth_of_loop;
8798 return EXIT_SUCCESS;
8801 static int FAST_FUNC builtin_continue(char **argv)
8803 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8804 return builtin_break(argv);
8808 #if ENABLE_HUSH_FUNCTIONS
8809 static int FAST_FUNC builtin_return(char **argv)
8813 if (G.flag_return_in_progress != -1) {
8814 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8815 return EXIT_FAILURE; /* bash compat */
8818 G.flag_return_in_progress = 1;
8821 * out of range: wraps around at 256, does not error out
8822 * non-numeric param:
8823 * f() { false; return qwe; }; f; echo $?
8824 * bash: return: qwe: numeric argument required <== we do this
8825 * 255 <== we also do this
8827 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);