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 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
90 /* #include <dmalloc.h> */
95 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97 #include "shell_common.h"
100 #if ENABLE_HUSH_RANDOM_SUPPORT
103 # define CLEAR_RANDOM_T(rnd) ((void)0)
106 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
109 /* Not every libc has sighandler_t. Fix it */
110 typedef void (*hush_sighandler_t)(int);
111 #define sighandler_t hush_sighandler_t
114 //config: bool "hush"
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
122 //config: It will compile and work on no-mmu systems.
124 //config: It does not handle select, aliases, tilde expansion,
125 //config: &>file and >&file redirection of stdout+stderr.
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
130 //config: depends on HUSH
132 //config: Enable bash-compatible extensions.
134 //config:config HUSH_BRACE_EXPANSION
135 //config: bool "Brace expansion"
137 //config: depends on HUSH_BASH_COMPAT
139 //config: Enable {abc,def} extension.
141 //config:config HUSH_HELP
142 //config: bool "help builtin"
144 //config: depends on HUSH
146 //config: Enable help builtin in hush. Code size + ~1 kbyte.
148 //config:config HUSH_INTERACTIVE
149 //config: bool "Interactive mode"
151 //config: depends on HUSH
153 //config: Enable interactive mode (prompt and command editing).
154 //config: Without this, hush simply reads and executes commands
155 //config: from stdin just like a shell script from a file.
156 //config: No prompt, no PS1/PS2 magic shell variables.
158 //config:config HUSH_SAVEHISTORY
159 //config: bool "Save command history to .hush_history"
161 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163 //config: Enable history saving in hush.
165 //config:config HUSH_JOB
166 //config: bool "Job control"
168 //config: depends on HUSH_INTERACTIVE
170 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config: command (not entire shell), fg/bg builtins work. Without this option,
172 //config: "cmd &" still works by simply spawning a process and immediately
173 //config: prompting for next command (or executing next command in a script),
174 //config: but no separate process group is formed.
176 //config:config HUSH_TICK
177 //config: bool "Process substitution"
179 //config: depends on HUSH
181 //config: Enable process substitution `command` and $(command) in hush.
183 //config:config HUSH_IF
184 //config: bool "Support if/then/elif/else/fi"
186 //config: depends on HUSH
188 //config: Enable if/then/elif/else/fi in hush.
190 //config:config HUSH_LOOPS
191 //config: bool "Support for, while and until loops"
193 //config: depends on HUSH
195 //config: Enable for, while and until loops in hush.
197 //config:config HUSH_CASE
198 //config: bool "Support case ... esac statement"
200 //config: depends on HUSH
202 //config: Enable case ... esac statement in hush. +400 bytes.
204 //config:config HUSH_FUNCTIONS
205 //config: bool "Support funcname() { commands; } syntax"
207 //config: depends on HUSH
209 //config: Enable support for shell functions in hush. +800 bytes.
211 //config:config HUSH_LOCAL
212 //config: bool "Support local builtin"
214 //config: depends on HUSH_FUNCTIONS
216 //config: Enable support for local variables in functions.
218 //config:config HUSH_RANDOM_SUPPORT
219 //config: bool "Pseudorandom generator and $RANDOM variable"
221 //config: depends on HUSH
223 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
226 //config:config HUSH_EXPORT_N
227 //config: bool "Support 'export -n' option"
229 //config: depends on HUSH
231 //config: export -n unexports variables. It is a bash extension.
233 //config:config HUSH_MODE_X
234 //config: bool "Support 'hush -x' option and 'set -x' command"
236 //config: depends on HUSH
238 //config: This instructs hush to print commands before execution.
239 //config: Adds ~300 bytes.
242 //config: bool "msh (deprecated: aliased to hush)"
244 //config: select HUSH
246 //config: msh is deprecated and will be removed, please migrate to hush.
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257 /* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
262 //usage:#define hush_trivial_usage
263 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage: "Unix shell interpreter"
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage hush_full_usage
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage hush_full_usage
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
288 /* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
298 #define ENABLE_HUSH_DOLLAR_OPS 1
303 # undef USE_FOR_NOMMU
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
310 #include "NUM_APPLETS.h"
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
329 /* Do we support ANY keywords? */
330 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
331 # define HAS_KEYWORDS 1
332 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
333 # define IF_HAS_NO_KEYWORDS(...)
335 # define HAS_KEYWORDS 0
336 # define IF_HAS_KEYWORDS(...)
337 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
340 /* If you comment out one of these below, it will be #defined later
341 * to perform debug printfs to stderr: */
342 #define debug_printf(...) do {} while (0)
343 /* Finer-grained debug switches */
344 #define debug_printf_parse(...) do {} while (0)
345 #define debug_print_tree(a, b) do {} while (0)
346 #define debug_printf_exec(...) do {} while (0)
347 #define debug_printf_env(...) do {} while (0)
348 #define debug_printf_jobs(...) do {} while (0)
349 #define debug_printf_expand(...) do {} while (0)
350 #define debug_printf_varexp(...) do {} while (0)
351 #define debug_printf_glob(...) do {} while (0)
352 #define debug_printf_list(...) do {} while (0)
353 #define debug_printf_subst(...) do {} while (0)
354 #define debug_printf_clean(...) do {} while (0)
356 #define ERR_PTR ((void*)(long)1)
358 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
360 #define _SPECIAL_VARS_STR "_*@$!?#"
361 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
362 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
363 #if ENABLE_HUSH_BASH_COMPAT
364 /* Support / and // replace ops */
365 /* Note that // is stored as \ in "encoded" string representation */
366 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
367 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
368 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
370 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
371 # define VAR_SUBST_OPS "%#:-=+?"
372 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
375 #define SPECIAL_VAR_SYMBOL 3
379 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
381 /* This supports saving pointers malloced in vfork child,
382 * to be freed in the parent.
385 typedef struct nommu_save_t {
387 struct variable *old_vars;
389 char **argv_from_re_execing;
402 #if ENABLE_HUSH_LOOPS
409 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
414 /* three pseudo-keywords support contrived "case" syntax: */
415 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
416 RES_MATCH , /* "word)" */
417 RES_CASE_BODY, /* "this command is inside CASE" */
424 typedef struct o_string {
426 int length; /* position where data is appended */
429 /* At least some part of the string was inside '' or "",
430 * possibly empty one: word"", wo''rd etc. */
431 smallint has_quoted_part;
432 smallint has_empty_slot;
433 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
436 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
438 /* Protect newly added chars against globbing
439 * by prepending \ to *, ?, [, \ */
440 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
443 MAYBE_ASSIGNMENT = 0,
444 DEFINITELY_ASSIGNMENT = 1,
446 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
449 /* Used for initialization: o_string foo = NULL_O_STRING; */
450 #define NULL_O_STRING { NULL }
452 typedef struct in_str {
454 /* eof_flag=1: last char in ->p is really an EOF */
455 char eof_flag; /* meaningless if ->p == NULL */
457 #if ENABLE_HUSH_INTERACTIVE
458 smallint promptmode; /* 0: PS1, 1: PS2 */
462 int (*get) (struct in_str *) FAST_FUNC;
463 int (*peek) (struct in_str *) FAST_FUNC;
465 #define i_getch(input) ((input)->get(input))
466 #define i_peek(input) ((input)->peek(input))
468 /* The descrip member of this structure is only used to make
469 * debugging output pretty */
470 static const struct {
472 signed char default_fd;
475 { O_RDONLY, 0, "<" },
476 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
477 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
478 { O_CREAT|O_RDWR, 1, "<>" },
479 { O_RDONLY, 0, "<<" },
480 /* Should not be needed. Bogus default_fd helps in debugging */
481 /* { O_RDONLY, 77, "<<" }, */
484 struct redir_struct {
485 struct redir_struct *next;
486 char *rd_filename; /* filename */
487 int rd_fd; /* fd to redirect */
488 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
490 smallint rd_type; /* (enum redir_type) */
491 /* note: for heredocs, rd_filename contains heredoc delimiter,
492 * and subsequently heredoc itself; and rd_dup is a bitmask:
493 * bit 0: do we need to trim leading tabs?
494 * bit 1: is heredoc quoted (<<'delim' syntax) ?
497 typedef enum redir_type {
499 REDIRECT_OVERWRITE = 1,
502 REDIRECT_HEREDOC = 4,
503 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
506 REDIRFD_SYNTAX_ERR = -2,
507 REDIRFD_TO_FILE = -1,
508 /* otherwise, rd_fd is redirected to rd_dup */
510 HEREDOC_SKIPTABS = 1,
516 pid_t pid; /* 0 if exited */
517 int assignment_cnt; /* how many argv[i] are assignments? */
518 smallint is_stopped; /* is the command currently running? */
519 smallint cmd_type; /* CMD_xxx */
521 #define CMD_SUBSHELL 1
522 #if ENABLE_HUSH_BASH_COMPAT
523 /* used for "[[ EXPR ]]" */
524 # define CMD_SINGLEWORD_NOGLOB 2
526 #if ENABLE_HUSH_FUNCTIONS
527 # define CMD_FUNCDEF 3
530 smalluint cmd_exitcode;
531 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
534 char *group_as_string;
536 #if ENABLE_HUSH_FUNCTIONS
537 struct function *child_func;
538 /* This field is used to prevent a bug here:
539 * while...do f1() {a;}; f1; f1() {b;}; f1; done
540 * When we execute "f1() {a;}" cmd, we create new function and clear
541 * cmd->group, cmd->group_as_string, cmd->argv[0].
542 * When we execute "f1() {b;}", we notice that f1 exists,
543 * and that its "parent cmd" struct is still "alive",
544 * we put those fields back into cmd->xxx
545 * (struct function has ->parent_cmd ptr to facilitate that).
546 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
547 * Without this trick, loop would execute a;b;b;b;...
548 * instead of correct sequence a;b;a;b;...
549 * When command is freed, it severs the link
550 * (sets ->child_func->parent_cmd to NULL).
553 char **argv; /* command name and arguments */
554 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
555 * and on execution these are substituted with their values.
556 * Substitution can make _several_ words out of one argv[n]!
557 * Example: argv[0]=='.^C*^C.' here: echo .$*.
558 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
560 struct redir_struct *redirects; /* I/O redirections */
562 /* Is there anything in this command at all? */
563 #define IS_NULL_CMD(cmd) \
564 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
568 int num_cmds; /* total number of commands in pipe */
569 int alive_cmds; /* number of commands running (not exited) */
570 int stopped_cmds; /* number of commands alive, but stopped */
572 int jobid; /* job number */
573 pid_t pgrp; /* process group ID for the job */
574 char *cmdtext; /* name of job */
576 struct command *cmds; /* array of commands in pipe */
577 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
578 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
579 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
581 typedef enum pipe_style {
587 /* Is there anything in this pipe at all? */
588 #define IS_NULL_PIPE(pi) \
589 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
591 /* This holds pointers to the various results of parsing */
592 struct parse_context {
593 /* linked list of pipes */
594 struct pipe *list_head;
595 /* last pipe (being constructed right now) */
597 /* last command in pipe (being constructed right now) */
598 struct command *command;
599 /* last redirect in command->redirects list */
600 struct redir_struct *pending_redirect;
606 smallint ctx_inverted; /* "! cmd | cmd" */
608 smallint ctx_dsemicolon; /* ";;" seen */
610 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
612 /* group we are enclosed in:
613 * example: "if pipe1; pipe2; then pipe3; fi"
614 * when we see "if" or "then", we malloc and copy current context,
615 * and make ->stack point to it. then we parse pipeN.
616 * when closing "then" / fi" / whatever is found,
617 * we move list_head into ->stack->command->group,
618 * copy ->stack into current context, and delete ->stack.
619 * (parsing of { list } and ( list ) doesn't use this method)
621 struct parse_context *stack;
625 /* On program start, environ points to initial environment.
626 * putenv adds new pointers into it, unsetenv removes them.
627 * Neither of these (de)allocates the strings.
628 * setenv allocates new strings in malloc space and does putenv,
629 * and thus setenv is unusable (leaky) for shell's purposes */
630 #define setenv(...) setenv_is_leaky_dont_use()
632 struct variable *next;
633 char *varstr; /* points to "name=" portion */
634 #if ENABLE_HUSH_LOCAL
635 unsigned func_nest_level;
637 int max_len; /* if > 0, name is part of initial env; else name is malloced */
638 smallint flg_export; /* putenv should be done on this var */
639 smallint flg_read_only;
647 #if ENABLE_HUSH_FUNCTIONS
649 struct function *next;
651 struct command *parent_cmd;
654 char *body_as_string;
660 /* set -/+o OPT support. (TODO: make it optional)
661 * bash supports the following opts:
672 * interactive-comments on
690 static const char o_opt_strings[] ALIGN1 =
693 #if ENABLE_HUSH_MODE_X
700 #if ENABLE_HUSH_MODE_X
707 /* "Globals" within this file */
708 /* Sorted roughly by size (smaller offsets == smaller code) */
710 /* interactive_fd != 0 means we are an interactive shell.
711 * If we are, then saved_tty_pgrp can also be != 0, meaning
712 * that controlling tty is available. With saved_tty_pgrp == 0,
713 * job control still works, but terminal signals
714 * (^C, ^Z, ^Y, ^\) won't work at all, and background
715 * process groups can only be created with "cmd &".
716 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
717 * to give tty to the foreground process group,
718 * and will take it back when the group is stopped (^Z)
721 #if ENABLE_HUSH_INTERACTIVE
722 /* 'interactive_fd' is a fd# open to ctty, if we have one
723 * _AND_ if we decided to act interactively */
727 # define G_interactive_fd (G.interactive_fd)
729 # define G_interactive_fd 0
731 #if ENABLE_FEATURE_EDITING
732 line_input_t *line_input_state;
737 #if ENABLE_HUSH_RANDOM_SUPPORT
743 pid_t saved_tty_pgrp;
744 struct pipe *job_list;
745 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
747 # define G_saved_tty_pgrp 0
749 char o_opt[NUM_OPT_O];
750 #if ENABLE_HUSH_MODE_X
751 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
755 smallint flag_SIGINT;
756 #if ENABLE_HUSH_LOOPS
757 smallint flag_break_continue;
759 #if ENABLE_HUSH_FUNCTIONS
760 /* 0: outside of a function (or sourced file)
761 * -1: inside of a function, ok to use return builtin
762 * 1: return is invoked, skip all till end of func
764 smallint flag_return_in_progress;
766 smallint exiting; /* used to prevent EXIT trap recursion */
767 /* These four support $?, $#, and $1 */
768 smalluint last_exitcode;
769 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
770 smalluint global_args_malloced;
771 /* how many non-NULL argv's we have. NB: $# + 1 */
775 char *argv0_for_re_execing;
777 #if ENABLE_HUSH_LOOPS
778 unsigned depth_break_continue;
779 unsigned depth_of_loop;
783 struct variable *top_var;
784 char **expanded_assignments;
785 #if ENABLE_HUSH_FUNCTIONS
786 struct function *top_func;
787 # if ENABLE_HUSH_LOCAL
788 struct variable **shadowed_vars_pp;
789 unsigned func_nest_level;
792 /* Signal and trap handling */
794 unsigned count_SIGCHLD;
795 unsigned handled_SIGCHLD;
796 smallint we_have_children;
798 /* Which signals have non-DFL handler (even with no traps set)?
799 * Set at the start to:
800 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
801 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
802 * The rest is cleared right before execv syscalls.
803 * Other than these two times, never modified.
805 unsigned special_sig_mask;
807 unsigned fatal_sig_mask;
808 #define G_fatal_sig_mask G.fatal_sig_mask
810 #define G_fatal_sig_mask 0
812 char **traps; /* char *traps[NSIG] */
813 sigset_t pending_set;
815 unsigned long memleak_value;
818 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
820 #define G (*ptr_to_globals)
821 /* Not #defining name to G.name - this quickly gets unwieldy
822 * (too many defines). Also, I actually prefer to see when a variable
823 * is global, thus "G." prefix is a useful hint */
824 #define INIT_G() do { \
825 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
829 /* Function prototypes for builtins */
830 static int builtin_cd(char **argv) FAST_FUNC;
831 static int builtin_echo(char **argv) FAST_FUNC;
832 static int builtin_eval(char **argv) FAST_FUNC;
833 static int builtin_exec(char **argv) FAST_FUNC;
834 static int builtin_exit(char **argv) FAST_FUNC;
835 static int builtin_export(char **argv) FAST_FUNC;
837 static int builtin_fg_bg(char **argv) FAST_FUNC;
838 static int builtin_jobs(char **argv) FAST_FUNC;
841 static int builtin_help(char **argv) FAST_FUNC;
843 #if ENABLE_HUSH_LOCAL
844 static int builtin_local(char **argv) FAST_FUNC;
847 static int builtin_memleak(char **argv) FAST_FUNC;
850 static int builtin_printf(char **argv) FAST_FUNC;
852 static int builtin_pwd(char **argv) FAST_FUNC;
853 static int builtin_read(char **argv) FAST_FUNC;
854 static int builtin_set(char **argv) FAST_FUNC;
855 static int builtin_shift(char **argv) FAST_FUNC;
856 static int builtin_source(char **argv) FAST_FUNC;
857 static int builtin_test(char **argv) FAST_FUNC;
858 static int builtin_trap(char **argv) FAST_FUNC;
859 static int builtin_type(char **argv) FAST_FUNC;
860 static int builtin_true(char **argv) FAST_FUNC;
861 static int builtin_umask(char **argv) FAST_FUNC;
862 static int builtin_unset(char **argv) FAST_FUNC;
863 static int builtin_wait(char **argv) FAST_FUNC;
864 #if ENABLE_HUSH_LOOPS
865 static int builtin_break(char **argv) FAST_FUNC;
866 static int builtin_continue(char **argv) FAST_FUNC;
868 #if ENABLE_HUSH_FUNCTIONS
869 static int builtin_return(char **argv) FAST_FUNC;
872 /* Table of built-in functions. They can be forked or not, depending on
873 * context: within pipes, they fork. As simple commands, they do not.
874 * When used in non-forking context, they can change global variables
875 * in the parent shell process. If forked, of course they cannot.
876 * For example, 'unset foo | whatever' will parse and run, but foo will
877 * still be set at the end. */
878 struct built_in_command {
880 int (*b_function)(char **argv) FAST_FUNC;
883 # define BLTIN(cmd, func, help) { cmd, func, help }
885 # define BLTIN(cmd, func, help) { cmd, func }
889 static const struct built_in_command bltins1[] = {
890 BLTIN("." , builtin_source , "Run commands in a file"),
891 BLTIN(":" , builtin_true , NULL),
893 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
895 #if ENABLE_HUSH_LOOPS
896 BLTIN("break" , builtin_break , "Exit from a loop"),
898 BLTIN("cd" , builtin_cd , "Change directory"),
899 #if ENABLE_HUSH_LOOPS
900 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
902 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
903 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
904 BLTIN("exit" , builtin_exit , "Exit"),
905 BLTIN("export" , builtin_export , "Set environment variables"),
907 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
910 BLTIN("help" , builtin_help , NULL),
913 BLTIN("jobs" , builtin_jobs , "List jobs"),
915 #if ENABLE_HUSH_LOCAL
916 BLTIN("local" , builtin_local , "Set local variables"),
919 BLTIN("memleak" , builtin_memleak , NULL),
921 BLTIN("read" , builtin_read , "Input into variable"),
922 #if ENABLE_HUSH_FUNCTIONS
923 BLTIN("return" , builtin_return , "Return from a function"),
925 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
926 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
927 #if ENABLE_HUSH_BASH_COMPAT
928 BLTIN("source" , builtin_source , "Run commands in a file"),
930 BLTIN("trap" , builtin_trap , "Trap signals"),
931 BLTIN("type" , builtin_type , "Show command type"),
932 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
933 BLTIN("umask" , builtin_umask , "Set file creation mask"),
934 BLTIN("unset" , builtin_unset , "Unset variables"),
935 BLTIN("wait" , builtin_wait , "Wait for process"),
937 /* For now, echo and test are unconditionally enabled.
938 * Maybe make it configurable? */
939 static const struct built_in_command bltins2[] = {
940 BLTIN("[" , builtin_test , NULL),
941 BLTIN("echo" , builtin_echo , NULL),
943 BLTIN("printf" , builtin_printf , NULL),
945 BLTIN("pwd" , builtin_pwd , NULL),
946 BLTIN("test" , builtin_test , NULL),
953 /* prevent disasters with G.debug_indent < 0 */
954 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
955 # define debug_enter() (G.debug_indent++)
956 # define debug_leave() (G.debug_indent--)
958 # define indent() ((void)0)
959 # define debug_enter() ((void)0)
960 # define debug_leave() ((void)0)
964 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
967 #ifndef debug_printf_parse
968 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
971 #ifndef debug_printf_exec
972 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
975 #ifndef debug_printf_env
976 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
979 #ifndef debug_printf_jobs
980 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
981 # define DEBUG_JOBS 1
983 # define DEBUG_JOBS 0
986 #ifndef debug_printf_expand
987 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
988 # define DEBUG_EXPAND 1
990 # define DEBUG_EXPAND 0
993 #ifndef debug_printf_varexp
994 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
997 #ifndef debug_printf_glob
998 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
999 # define DEBUG_GLOB 1
1001 # define DEBUG_GLOB 0
1004 #ifndef debug_printf_list
1005 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1008 #ifndef debug_printf_subst
1009 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1012 #ifndef debug_printf_clean
1013 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1014 # define DEBUG_CLEAN 1
1016 # define DEBUG_CLEAN 0
1020 static void debug_print_strings(const char *prefix, char **vv)
1023 fdprintf(2, "%s:\n", prefix);
1025 fdprintf(2, " '%s'\n", *vv++);
1028 # define debug_print_strings(prefix, vv) ((void)0)
1032 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1035 static void *xxmalloc(int lineno, size_t size)
1037 void *ptr = xmalloc((size + 0xff) & ~0xff);
1038 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1041 static void *xxrealloc(int lineno, void *ptr, size_t size)
1043 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1044 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1047 static char *xxstrdup(int lineno, const char *str)
1049 char *ptr = xstrdup(str);
1050 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1053 static void xxfree(void *ptr)
1055 fdprintf(2, "free %p\n", ptr);
1058 # define xmalloc(s) xxmalloc(__LINE__, s)
1059 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1060 # define xstrdup(s) xxstrdup(__LINE__, s)
1061 # define free(p) xxfree(p)
1065 /* Syntax and runtime errors. They always abort scripts.
1066 * In interactive use they usually discard unparsed and/or unexecuted commands
1067 * and return to the prompt.
1068 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1071 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1072 # define syntax_error(lineno, msg) syntax_error(msg)
1073 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1074 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1075 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1076 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1079 static void die_if_script(unsigned lineno, const char *fmt, ...)
1084 bb_error_msg("hush.c:%u", lineno);
1087 bb_verror_msg(fmt, p, NULL);
1089 if (!G_interactive_fd)
1093 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1096 bb_error_msg("syntax error: %s", msg);
1098 bb_error_msg("syntax error");
1101 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1103 bb_error_msg("syntax error at '%s'", msg);
1106 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1108 bb_error_msg("syntax error: unterminated %s", s);
1111 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1113 char msg[2] = { ch, '\0' };
1114 syntax_error_unterm_str(lineno, msg);
1117 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1122 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1126 # undef die_if_script
1127 # undef syntax_error
1128 # undef syntax_error_at
1129 # undef syntax_error_unterm_ch
1130 # undef syntax_error_unterm_str
1131 # undef syntax_error_unexpected_ch
1133 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1134 # define syntax_error(msg) syntax_error(__LINE__, msg)
1135 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1136 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1137 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1138 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1142 #if ENABLE_HUSH_INTERACTIVE
1143 static void cmdedit_update_prompt(void);
1145 # define cmdedit_update_prompt() ((void)0)
1149 /* Utility functions
1151 /* Replace each \x with x in place, return ptr past NUL. */
1152 static char *unbackslash(char *src)
1154 char *dst = src = strchrnul(src, '\\');
1158 if ((*dst++ = *src++) == '\0')
1164 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1185 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1186 v[count1 + count2] = NULL;
1189 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1193 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1195 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1196 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1199 #define add_strings_to_strings(strings, add, need_to_dup) \
1200 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1203 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1204 static char **add_string_to_strings(char **strings, char *add)
1209 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1212 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1214 char **ptr = add_string_to_strings(strings, add);
1215 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1218 #define add_string_to_strings(strings, add) \
1219 xx_add_string_to_strings(__LINE__, strings, add)
1222 static void free_strings(char **strings)
1237 /* Helpers for setting new $n and restoring them back
1239 typedef struct save_arg_t {
1243 smallint sv_g_malloced;
1246 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1250 sv->sv_argv0 = argv[0];
1251 sv->sv_g_argv = G.global_argv;
1252 sv->sv_g_argc = G.global_argc;
1253 sv->sv_g_malloced = G.global_args_malloced;
1255 argv[0] = G.global_argv[0]; /* retain $0 */
1256 G.global_argv = argv;
1257 G.global_args_malloced = 0;
1265 static void restore_G_args(save_arg_t *sv, char **argv)
1269 if (G.global_args_malloced) {
1270 /* someone ran "set -- arg1 arg2 ...", undo */
1272 while (*++pp) /* note: does not free $0 */
1274 free(G.global_argv);
1276 argv[0] = sv->sv_argv0;
1277 G.global_argv = sv->sv_g_argv;
1278 G.global_argc = sv->sv_g_argc;
1279 G.global_args_malloced = sv->sv_g_malloced;
1283 /* Basic theory of signal handling in shell
1284 * ========================================
1285 * This does not describe what hush does, rather, it is current understanding
1286 * what it _should_ do. If it doesn't, it's a bug.
1287 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1289 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1290 * is finished or backgrounded. It is the same in interactive and
1291 * non-interactive shells, and is the same regardless of whether
1292 * a user trap handler is installed or a shell special one is in effect.
1293 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1294 * backgrounds (i.e. stops) or kills all members of currently running
1297 * Wait builtin in interruptible by signals for which user trap is set
1298 * or by SIGINT in interactive shell.
1300 * Trap handlers will execute even within trap handlers. (right?)
1302 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1303 * except for handlers set to '' (empty string).
1305 * If job control is off, backgrounded commands ("cmd &")
1306 * have SIGINT, SIGQUIT set to SIG_IGN.
1308 * Commands which are run in command substitution ("`cmd`")
1309 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1311 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1312 * by the shell from its parent.
1314 * Signals which differ from SIG_DFL action
1315 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1318 * SIGTERM (interactive): ignore
1319 * SIGHUP (interactive):
1320 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1321 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1322 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1323 * that all pipe members are stopped. Try this in bash:
1324 * while :; do :; done - ^Z does not background it
1325 * (while :; do :; done) - ^Z backgrounds it
1326 * SIGINT (interactive): wait for last pipe, ignore the rest
1327 * of the command line, show prompt. NB: ^C does not send SIGINT
1328 * to interactive shell while shell is waiting for a pipe,
1329 * since shell is bg'ed (is not in foreground process group).
1330 * Example 1: this waits 5 sec, but does not execute ls:
1331 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1332 * Example 2: this does not wait and does not execute ls:
1333 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1334 * Example 3: this does not wait 5 sec, but executes ls:
1335 * "sleep 5; ls -l" + press ^C
1336 * Example 4: this does not wait and does not execute ls:
1337 * "sleep 5 & wait; ls -l" + press ^C
1339 * (What happens to signals which are IGN on shell start?)
1340 * (What happens with signal mask on shell start?)
1342 * Old implementation
1343 * ==================
1344 * We use in-kernel pending signal mask to determine which signals were sent.
1345 * We block all signals which we don't want to take action immediately,
1346 * i.e. we block all signals which need to have special handling as described
1347 * above, and all signals which have traps set.
1348 * After each pipe execution, we extract any pending signals via sigtimedwait()
1351 * unsigned special_sig_mask: a mask of such "special" signals
1352 * sigset_t blocked_set: current blocked signal set
1355 * clear bit in blocked_set unless it is also in special_sig_mask
1356 * "trap 'cmd' SIGxxx":
1357 * set bit in blocked_set (even if 'cmd' is '')
1358 * after [v]fork, if we plan to be a shell:
1359 * unblock signals with special interactive handling
1360 * (child shell is not interactive),
1361 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1362 * after [v]fork, if we plan to exec:
1363 * POSIX says fork clears pending signal mask in child - no need to clear it.
1364 * Restore blocked signal set to one inherited by shell just prior to exec.
1366 * Note: as a result, we do not use signal handlers much. The only uses
1367 * are to count SIGCHLDs
1368 * and to restore tty pgrp on signal-induced exit.
1371 * Standard says "When a subshell is entered, traps that are not being ignored
1372 * are set to the default actions". bash interprets it so that traps which
1373 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1375 * Problem: the above approach makes it unwieldy to catch signals while
1376 * we are in read builtin, of while we read commands from stdin:
1377 * masked signals are not visible!
1379 * New implementation
1380 * ==================
1381 * We record each signal we are interested in by installing signal handler
1382 * for them - a bit like emulating kernel pending signal mask in userspace.
1383 * We are interested in: signals which need to have special handling
1384 * as described above, and all signals which have traps set.
1385 * Signals are rocorded in pending_set.
1386 * After each pipe execution, we extract any pending signals
1389 * unsigned special_sig_mask: a mask of shell-special signals.
1390 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1391 * char *traps[sig] if trap for sig is set (even if it's '').
1392 * sigset_t pending_set: set of sigs we received.
1395 * if sig is in special_sig_mask, set handler back to:
1396 * record_pending_signo, or to IGN if it's a tty stop signal
1397 * if sig is in fatal_sig_mask, set handler back to sigexit.
1398 * else: set handler back to SIG_DFL
1399 * "trap 'cmd' SIGxxx":
1400 * set handler to record_pending_signo.
1402 * set handler to SIG_IGN.
1403 * after [v]fork, if we plan to be a shell:
1404 * set signals with special interactive handling to SIG_DFL
1405 * (because child shell is not interactive),
1406 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1407 * after [v]fork, if we plan to exec:
1408 * POSIX says fork clears pending signal mask in child - no need to clear it.
1410 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1411 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1414 * Standard says "When a subshell is entered, traps that are not being ignored
1415 * are set to the default actions". bash interprets it so that traps which
1416 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1419 SPECIAL_INTERACTIVE_SIGS = 0
1424 SPECIAL_JOBSTOP_SIGS = 0
1433 static void record_pending_signo(int sig)
1435 sigaddset(&G.pending_set, sig);
1436 #if ENABLE_HUSH_FAST
1437 if (sig == SIGCHLD) {
1439 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1446 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1447 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1448 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1449 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1451 /* Restores tty foreground process group, and exits.
1452 * May be called as signal handler for fatal signal
1453 * (will resend signal to itself, producing correct exit state)
1454 * or called directly with -EXITCODE.
1455 * We also call it if xfunc is exiting. */
1456 static void sigexit(int sig) NORETURN;
1457 static void sigexit(int sig)
1459 /* Careful: we can end up here after [v]fork. Do not restore
1460 * tty pgrp then, only top-level shell process does that */
1461 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1462 /* Disable all signals: job control, SIGPIPE, etc.
1463 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1465 sigprocmask_allsigs(SIG_BLOCK);
1466 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1469 /* Not a signal, just exit */
1473 kill_myself_with_sig(sig); /* does not return */
1477 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1478 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1482 static sighandler_t pick_sighandler(unsigned sig)
1484 sighandler_t handler = SIG_DFL;
1485 if (sig < sizeof(unsigned)*8) {
1486 unsigned sigmask = (1 << sig);
1490 if (G_fatal_sig_mask & sigmask)
1493 /* sig has special handling? */
1494 else if (G.special_sig_mask & sigmask) {
1495 handler = record_pending_signo;
1496 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1497 * in order to ignore them: they will be raised
1498 * in an endless loop when we try to do some
1499 * terminal ioctls! We do have to _ignore_ these.
1501 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1508 /* Restores tty foreground process group, and exits. */
1509 static void hush_exit(int exitcode) NORETURN;
1510 static void hush_exit(int exitcode)
1513 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1515 /* argv[0] is unused */
1516 argv[1] = G.traps[0];
1518 G.exiting = 1; /* prevent EXIT trap recursion */
1519 /* Note: G.traps[0] is not cleared!
1520 * "trap" will still show it, if executed
1525 #if ENABLE_FEATURE_CLEAN_UP
1527 struct variable *cur_var;
1528 if (G.cwd != bb_msg_unknown)
1530 cur_var = G.top_var;
1532 struct variable *tmp = cur_var;
1533 if (!cur_var->max_len)
1534 free(cur_var->varstr);
1535 cur_var = cur_var->next;
1543 sigexit(- (exitcode & 0xff));
1550 //TODO: return a mask of ALL handled sigs?
1551 static int check_and_run_traps(void)
1558 if (sigisemptyset(&G.pending_set))
1563 if (sigismember(&G.pending_set, sig)) {
1564 sigdelset(&G.pending_set, sig);
1567 } while (sig < NSIG);
1570 if (G.traps && G.traps[sig]) {
1571 if (G.traps[sig][0]) {
1572 /* We have user-defined handler */
1573 smalluint save_rcode;
1575 /* argv[0] is unused */
1576 argv[1] = G.traps[sig];
1578 save_rcode = G.last_exitcode;
1580 G.last_exitcode = save_rcode;
1582 } /* else: "" trap, ignoring signal */
1585 /* not a trap: special action */
1588 /* Builtin was ^C'ed, make it look prettier: */
1596 /* bash is observed to signal whole process groups,
1597 * not individual processes */
1598 for (job = G.job_list; job; job = job->next) {
1601 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1602 if (kill(- job->pgrp, SIGHUP) == 0)
1603 kill(- job->pgrp, SIGCONT);
1608 #if ENABLE_HUSH_FAST
1611 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1613 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1614 * This simplifies wait builtin a bit.
1618 default: /* ignored: */
1619 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1621 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1622 * Example: wait is not interrupted by TERM
1623 * in interactive shell, because TERM is ignored.
1632 static const char *get_cwd(int force)
1634 if (force || G.cwd == NULL) {
1635 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1636 * we must not try to free(bb_msg_unknown) */
1637 if (G.cwd == bb_msg_unknown)
1639 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1641 G.cwd = bb_msg_unknown;
1648 * Shell and environment variable support
1650 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1652 struct variable **pp;
1653 struct variable *cur;
1656 while ((cur = *pp) != NULL) {
1657 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1664 static const char* FAST_FUNC get_local_var_value(const char *name)
1666 struct variable **vpp;
1667 unsigned len = strlen(name);
1669 if (G.expanded_assignments) {
1670 char **cpp = G.expanded_assignments;
1673 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1674 return cp + len + 1;
1679 vpp = get_ptr_to_local_var(name, len);
1681 return (*vpp)->varstr + len + 1;
1683 if (strcmp(name, "PPID") == 0)
1684 return utoa(G.root_ppid);
1685 // bash compat: UID? EUID?
1686 #if ENABLE_HUSH_RANDOM_SUPPORT
1687 if (strcmp(name, "RANDOM") == 0)
1688 return utoa(next_random(&G.random_gen));
1693 /* str holds "NAME=VAL" and is expected to be malloced.
1694 * We take ownership of it.
1696 * 0: do not change export flag
1697 * (if creating new variable, flag will be 0)
1698 * 1: set export flag and putenv the variable
1699 * -1: clear export flag and unsetenv the variable
1700 * flg_read_only is set only when we handle -R var=val
1702 #if !BB_MMU && ENABLE_HUSH_LOCAL
1703 /* all params are used */
1704 #elif BB_MMU && ENABLE_HUSH_LOCAL
1705 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1706 set_local_var(str, flg_export, local_lvl)
1707 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1708 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1709 set_local_var(str, flg_export)
1710 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1711 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1712 set_local_var(str, flg_export, flg_read_only)
1714 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1716 struct variable **var_pp;
1717 struct variable *cur;
1721 eq_sign = strchr(str, '=');
1722 if (!eq_sign) { /* not expected to ever happen? */
1727 name_len = eq_sign - str + 1; /* including '=' */
1728 var_pp = &G.top_var;
1729 while ((cur = *var_pp) != NULL) {
1730 if (strncmp(cur->varstr, str, name_len) != 0) {
1731 var_pp = &cur->next;
1734 /* We found an existing var with this name */
1735 if (cur->flg_read_only) {
1739 bb_error_msg("%s: readonly variable", str);
1743 if (flg_export == -1) { // "&& cur->flg_export" ?
1744 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1749 #if ENABLE_HUSH_LOCAL
1750 if (cur->func_nest_level < local_lvl) {
1751 /* New variable is declared as local,
1752 * and existing one is global, or local
1753 * from enclosing function.
1754 * Remove and save old one: */
1755 *var_pp = cur->next;
1756 cur->next = *G.shadowed_vars_pp;
1757 *G.shadowed_vars_pp = cur;
1758 /* bash 3.2.33(1) and exported vars:
1760 * # f() { local z=a; env | grep ^z; }
1766 if (cur->flg_export)
1771 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1776 if (cur->max_len != 0) {
1777 if (cur->max_len >= strlen(str)) {
1778 /* This one is from startup env, reuse space */
1779 strcpy(cur->varstr, str);
1783 /* max_len == 0 signifies "malloced" var, which we can
1784 * (and has to) free */
1788 goto set_str_and_exp;
1791 /* Not found - create new variable struct */
1792 cur = xzalloc(sizeof(*cur));
1793 #if ENABLE_HUSH_LOCAL
1794 cur->func_nest_level = local_lvl;
1796 cur->next = *var_pp;
1802 cur->flg_read_only = flg_read_only;
1805 if (flg_export == 1)
1806 cur->flg_export = 1;
1807 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1808 cmdedit_update_prompt();
1809 if (cur->flg_export) {
1810 if (flg_export == -1) {
1811 cur->flg_export = 0;
1812 /* unsetenv was already done */
1814 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1815 return putenv(cur->varstr);
1821 /* Used at startup and after each cd */
1822 static void set_pwd_var(int exp)
1824 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1825 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1828 static int unset_local_var_len(const char *name, int name_len)
1830 struct variable *cur;
1831 struct variable **var_pp;
1834 return EXIT_SUCCESS;
1835 var_pp = &G.top_var;
1836 while ((cur = *var_pp) != NULL) {
1837 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1838 if (cur->flg_read_only) {
1839 bb_error_msg("%s: readonly variable", name);
1840 return EXIT_FAILURE;
1842 *var_pp = cur->next;
1843 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1844 bb_unsetenv(cur->varstr);
1845 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1846 cmdedit_update_prompt();
1850 return EXIT_SUCCESS;
1852 var_pp = &cur->next;
1854 return EXIT_SUCCESS;
1857 static int unset_local_var(const char *name)
1859 return unset_local_var_len(name, strlen(name));
1862 static void unset_vars(char **strings)
1870 const char *eq = strchrnul(*v, '=');
1871 unset_local_var_len(*v, (int)(eq - *v));
1877 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1879 char *var = xasprintf("%s=%s", name, val);
1880 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1885 * Helpers for "var1=val1 var2=val2 cmd" feature
1887 static void add_vars(struct variable *var)
1889 struct variable *next;
1893 var->next = G.top_var;
1895 if (var->flg_export) {
1896 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1897 putenv(var->varstr);
1899 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1905 static struct variable *set_vars_and_save_old(char **strings)
1908 struct variable *old = NULL;
1914 struct variable *var_p;
1915 struct variable **var_pp;
1918 eq = strchr(*s, '=');
1920 var_pp = get_ptr_to_local_var(*s, eq - *s);
1922 /* Remove variable from global linked list */
1924 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1925 *var_pp = var_p->next;
1926 /* Add it to returned list */
1930 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1941 static int FAST_FUNC static_get(struct in_str *i)
1952 static int FAST_FUNC static_peek(struct in_str *i)
1957 #if ENABLE_HUSH_INTERACTIVE
1959 static void cmdedit_update_prompt(void)
1961 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1962 G.PS1 = get_local_var_value("PS1");
1965 G.PS2 = get_local_var_value("PS2");
1973 static const char *setup_prompt_string(int promptmode)
1975 const char *prompt_str;
1976 debug_printf("setup_prompt_string %d ", promptmode);
1977 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1978 /* Set up the prompt */
1979 if (promptmode == 0) { /* PS1 */
1981 /* bash uses $PWD value, even if it is set by user.
1982 * It uses current dir only if PWD is unset.
1983 * We always use current dir. */
1984 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1989 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1990 debug_printf("result '%s'\n", prompt_str);
1994 static void get_user_input(struct in_str *i)
1997 const char *prompt_str;
1999 prompt_str = setup_prompt_string(i->promptmode);
2000 # if ENABLE_FEATURE_EDITING
2001 /* Enable command line editing only while a command line
2002 * is actually being read */
2004 /* Unicode support should be activated even if LANG is set
2005 * _during_ shell execution, not only if it was set when
2006 * shell was started. Therefore, re-check LANG every time:
2008 reinit_unicode(get_local_var_value("LANG"));
2011 /* buglet: SIGINT will not make new prompt to appear _at once_,
2012 * only after <Enter>. (^C will work) */
2013 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2014 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2015 check_and_run_traps();
2016 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2017 i->eof_flag = (r < 0);
2018 if (i->eof_flag) { /* EOF/error detected */
2019 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2020 G.user_input_buf[1] = '\0';
2025 if (i->last_char == '\0' || i->last_char == '\n') {
2026 /* Why check_and_run_traps here? Try this interactively:
2027 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2028 * $ <[enter], repeatedly...>
2029 * Without check_and_run_traps, handler never runs.
2031 check_and_run_traps();
2032 fputs(prompt_str, stdout);
2035 G.user_input_buf[0] = r = fgetc(i->file);
2036 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2037 } while (G.flag_SIGINT);
2038 i->eof_flag = (r == EOF);
2040 i->p = G.user_input_buf;
2043 #endif /* INTERACTIVE */
2045 /* This is the magic location that prints prompts
2046 * and gets data back from the user */
2047 static int FAST_FUNC file_get(struct in_str *i)
2051 /* If there is data waiting, eat it up */
2052 if (i->p && *i->p) {
2053 #if ENABLE_HUSH_INTERACTIVE
2057 if (i->eof_flag && !*i->p)
2059 /* note: ch is never NUL */
2061 /* need to double check i->file because we might be doing something
2062 * more complicated by now, like sourcing or substituting. */
2063 #if ENABLE_HUSH_INTERACTIVE
2064 if (G_interactive_fd && i->file == stdin) {
2067 } while (!*i->p); /* need non-empty line */
2068 i->promptmode = 1; /* PS2 */
2072 do ch = fgetc(i->file); while (ch == '\0');
2074 debug_printf("file_get: got '%c' %d\n", ch, ch);
2079 /* All callers guarantee this routine will never
2080 * be used right after a newline, so prompting is not needed.
2082 static int FAST_FUNC file_peek(struct in_str *i)
2085 if (i->p && *i->p) {
2086 if (i->eof_flag && !i->p[1])
2089 /* note: ch is never NUL */
2091 do ch = fgetc(i->file); while (ch == '\0');
2092 i->eof_flag = (ch == EOF);
2093 i->peek_buf[0] = ch;
2094 i->peek_buf[1] = '\0';
2096 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2100 static void setup_file_in_str(struct in_str *i, FILE *f)
2102 memset(i, 0, sizeof(*i));
2103 i->peek = file_peek;
2105 /* i->promptmode = 0; - PS1 (memset did it) */
2110 static void setup_string_in_str(struct in_str *i, const char *s)
2112 memset(i, 0, sizeof(*i));
2113 i->peek = static_peek;
2114 i->get = static_get;
2115 /* i->promptmode = 0; - PS1 (memset did it) */
2117 /* i->eof_flag = 0; */
2124 #define B_CHUNK (32 * sizeof(char*))
2126 static void o_reset_to_empty_unquoted(o_string *o)
2129 o->has_quoted_part = 0;
2134 static void o_free(o_string *o)
2137 memset(o, 0, sizeof(*o));
2140 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2145 static void o_grow_by(o_string *o, int len)
2147 if (o->length + len > o->maxlen) {
2148 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2149 o->data = xrealloc(o->data, 1 + o->maxlen);
2153 static void o_addchr(o_string *o, int ch)
2155 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2157 o->data[o->length] = ch;
2159 o->data[o->length] = '\0';
2162 static void o_addblock(o_string *o, const char *str, int len)
2165 memcpy(&o->data[o->length], str, len);
2167 o->data[o->length] = '\0';
2170 static void o_addstr(o_string *o, const char *str)
2172 o_addblock(o, str, strlen(str));
2176 static void nommu_addchr(o_string *o, int ch)
2182 # define nommu_addchr(o, str) ((void)0)
2185 static void o_addstr_with_NUL(o_string *o, const char *str)
2187 o_addblock(o, str, strlen(str) + 1);
2191 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2192 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2193 * Apparently, on unquoted $v bash still does globbing
2194 * ("v='*.txt'; echo $v" prints all .txt files),
2195 * but NOT brace expansion! Thus, there should be TWO independent
2196 * quoting mechanisms on $v expansion side: one protects
2197 * $v from brace expansion, and other additionally protects "$v" against globbing.
2198 * We have only second one.
2201 #if ENABLE_HUSH_BRACE_EXPANSION
2202 # define MAYBE_BRACES "{}"
2204 # define MAYBE_BRACES ""
2207 /* My analysis of quoting semantics tells me that state information
2208 * is associated with a destination, not a source.
2210 static void o_addqchr(o_string *o, int ch)
2213 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2218 o->data[o->length] = '\\';
2221 o->data[o->length] = ch;
2223 o->data[o->length] = '\0';
2226 static void o_addQchr(o_string *o, int ch)
2229 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2230 && strchr("*?[\\" MAYBE_BRACES, ch)
2233 o->data[o->length] = '\\';
2237 o->data[o->length] = ch;
2239 o->data[o->length] = '\0';
2242 static void o_addqblock(o_string *o, const char *str, int len)
2247 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2248 if (ordinary_cnt > len) /* paranoia */
2250 o_addblock(o, str, ordinary_cnt);
2251 if (ordinary_cnt == len)
2253 str += ordinary_cnt;
2254 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2258 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2260 o->data[o->length] = '\\';
2264 o->data[o->length] = ch;
2266 o->data[o->length] = '\0';
2270 static void o_addQblock(o_string *o, const char *str, int len)
2272 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2273 o_addblock(o, str, len);
2276 o_addqblock(o, str, len);
2279 static void o_addQstr(o_string *o, const char *str)
2281 o_addQblock(o, str, strlen(str));
2284 /* A special kind of o_string for $VAR and `cmd` expansion.
2285 * It contains char* list[] at the beginning, which is grown in 16 element
2286 * increments. Actual string data starts at the next multiple of 16 * (char*).
2287 * list[i] contains an INDEX (int!) into this string data.
2288 * It means that if list[] needs to grow, data needs to be moved higher up
2289 * but list[i]'s need not be modified.
2290 * NB: remembering how many list[i]'s you have there is crucial.
2291 * o_finalize_list() operation post-processes this structure - calculates
2292 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2294 #if DEBUG_EXPAND || DEBUG_GLOB
2295 static void debug_print_list(const char *prefix, o_string *o, int n)
2297 char **list = (char**)o->data;
2298 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2302 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2303 prefix, list, n, string_start, o->length, o->maxlen,
2304 !!(o->o_expflags & EXP_FLAG_GLOB),
2306 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2309 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2310 o->data + (int)(uintptr_t)list[i] + string_start,
2311 o->data + (int)(uintptr_t)list[i] + string_start);
2315 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2317 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2321 # define debug_print_list(prefix, o, n) ((void)0)
2324 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2325 * in list[n] so that it points past last stored byte so far.
2326 * It returns n+1. */
2327 static int o_save_ptr_helper(o_string *o, int n)
2329 char **list = (char**)o->data;
2333 if (!o->has_empty_slot) {
2334 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2335 string_len = o->length - string_start;
2336 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2337 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2338 /* list[n] points to string_start, make space for 16 more pointers */
2339 o->maxlen += 0x10 * sizeof(list[0]);
2340 o->data = xrealloc(o->data, o->maxlen + 1);
2341 list = (char**)o->data;
2342 memmove(list + n + 0x10, list + n, string_len);
2343 o->length += 0x10 * sizeof(list[0]);
2345 debug_printf_list("list[%d]=%d string_start=%d\n",
2346 n, string_len, string_start);
2349 /* We have empty slot at list[n], reuse without growth */
2350 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2351 string_len = o->length - string_start;
2352 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2353 n, string_len, string_start);
2354 o->has_empty_slot = 0;
2356 list[n] = (char*)(uintptr_t)string_len;
2360 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2361 static int o_get_last_ptr(o_string *o, int n)
2363 char **list = (char**)o->data;
2364 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2366 return ((int)(uintptr_t)list[n-1]) + string_start;
2369 #if ENABLE_HUSH_BRACE_EXPANSION
2370 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2371 * first, it processes even {a} (no commas), second,
2372 * I didn't manage to make it return strings when they don't match
2373 * existing files. Need to re-implement it.
2377 static int glob_needed(const char *s)
2386 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2392 /* Return pointer to next closing brace or to comma */
2393 static const char *next_brace_sub(const char *cp)
2397 while (*cp != '\0') {
2404 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2410 return *cp != '\0' ? cp : NULL;
2412 /* Recursive brace globber. Note: may garble pattern[]. */
2413 static int glob_brace(char *pattern, o_string *o, int n)
2415 char *new_pattern_buf;
2422 debug_printf_glob("glob_brace('%s')\n", pattern);
2428 if (*begin == '{') {
2429 /* Find the first sub-pattern and at the same time
2430 * find the rest after the closing brace */
2431 next = next_brace_sub(begin);
2433 /* An illegal expression */
2437 /* "{abc}" with no commas - illegal
2438 * brace expr, disregard and skip it */
2444 if (*begin == '\\' && begin[1] != '\0')
2448 debug_printf_glob("begin:%s\n", begin);
2449 debug_printf_glob("next:%s\n", next);
2451 /* Now find the end of the whole brace expression */
2453 while (*rest != '}') {
2454 rest = next_brace_sub(rest);
2456 /* An illegal expression */
2459 debug_printf_glob("rest:%s\n", rest);
2461 rest_len = strlen(++rest) + 1;
2463 /* We are sure the brace expression is well-formed */
2465 /* Allocate working buffer large enough for our work */
2466 new_pattern_buf = xmalloc(strlen(pattern));
2468 /* We have a brace expression. BEGIN points to the opening {,
2469 * NEXT points past the terminator of the first element, and REST
2470 * points past the final }. We will accumulate result names from
2471 * recursive runs for each brace alternative in the buffer using
2476 /* Construct the new glob expression */
2479 mempcpy(new_pattern_buf,
2480 /* We know the prefix for all sub-patterns */
2481 pattern, begin - pattern),
2485 /* Note: glob_brace() may garble new_pattern_buf[].
2486 * That's why we re-copy prefix every time (1st memcpy above).
2488 n = glob_brace(new_pattern_buf, o, n);
2490 /* We saw the last entry */
2494 next = next_brace_sub(next);
2496 free(new_pattern_buf);
2504 memset(&globdata, 0, sizeof(globdata));
2505 gr = glob(pattern, 0, NULL, &globdata);
2506 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2508 if (gr == GLOB_NOMATCH) {
2509 globfree(&globdata);
2510 /* NB: garbles parameter */
2511 unbackslash(pattern);
2512 o_addstr_with_NUL(o, pattern);
2513 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2514 return o_save_ptr_helper(o, n);
2516 if (gr == GLOB_NOSPACE)
2517 bb_error_msg_and_die(bb_msg_memory_exhausted);
2518 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2519 * but we didn't specify it. Paranoia again. */
2520 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2522 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2523 char **argv = globdata.gl_pathv;
2525 o_addstr_with_NUL(o, *argv);
2526 n = o_save_ptr_helper(o, n);
2532 globfree(&globdata);
2536 /* Performs globbing on last list[],
2537 * saving each result as a new list[].
2539 static int perform_glob(o_string *o, int n)
2541 char *pattern, *copy;
2543 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2545 return o_save_ptr_helper(o, n);
2546 pattern = o->data + o_get_last_ptr(o, n);
2547 debug_printf_glob("glob pattern '%s'\n", pattern);
2548 if (!glob_needed(pattern)) {
2549 /* unbackslash last string in o in place, fix length */
2550 o->length = unbackslash(pattern) - o->data;
2551 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2552 return o_save_ptr_helper(o, n);
2555 copy = xstrdup(pattern);
2556 /* "forget" pattern in o */
2557 o->length = pattern - o->data;
2558 n = glob_brace(copy, o, n);
2561 debug_print_list("perform_glob returning", o, n);
2565 #else /* !HUSH_BRACE_EXPANSION */
2568 static int glob_needed(const char *s)
2577 if (*s == '*' || *s == '[' || *s == '?')
2583 /* Performs globbing on last list[],
2584 * saving each result as a new list[].
2586 static int perform_glob(o_string *o, int n)
2592 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2594 return o_save_ptr_helper(o, n);
2595 pattern = o->data + o_get_last_ptr(o, n);
2596 debug_printf_glob("glob pattern '%s'\n", pattern);
2597 if (!glob_needed(pattern)) {
2599 /* unbackslash last string in o in place, fix length */
2600 o->length = unbackslash(pattern) - o->data;
2601 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2602 return o_save_ptr_helper(o, n);
2605 memset(&globdata, 0, sizeof(globdata));
2606 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2607 * If we glob "*.\*" and don't find anything, we need
2608 * to fall back to using literal "*.*", but GLOB_NOCHECK
2609 * will return "*.\*"!
2611 gr = glob(pattern, 0, NULL, &globdata);
2612 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2614 if (gr == GLOB_NOMATCH) {
2615 globfree(&globdata);
2618 if (gr == GLOB_NOSPACE)
2619 bb_error_msg_and_die(bb_msg_memory_exhausted);
2620 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2621 * but we didn't specify it. Paranoia again. */
2622 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2624 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2625 char **argv = globdata.gl_pathv;
2626 /* "forget" pattern in o */
2627 o->length = pattern - o->data;
2629 o_addstr_with_NUL(o, *argv);
2630 n = o_save_ptr_helper(o, n);
2636 globfree(&globdata);
2638 debug_print_list("perform_glob returning", o, n);
2642 #endif /* !HUSH_BRACE_EXPANSION */
2644 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2645 * Otherwise, just finish current list[] and start new */
2646 static int o_save_ptr(o_string *o, int n)
2648 if (o->o_expflags & EXP_FLAG_GLOB) {
2649 /* If o->has_empty_slot, list[n] was already globbed
2650 * (if it was requested back then when it was filled)
2651 * so don't do that again! */
2652 if (!o->has_empty_slot)
2653 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2655 return o_save_ptr_helper(o, n);
2658 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2659 static char **o_finalize_list(o_string *o, int n)
2664 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2666 debug_print_list("finalized", o, n);
2667 debug_printf_expand("finalized n:%d\n", n);
2668 list = (char**)o->data;
2669 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2673 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2678 static void free_pipe_list(struct pipe *pi);
2680 /* Returns pi->next - next pipe in the list */
2681 static struct pipe *free_pipe(struct pipe *pi)
2686 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2687 for (i = 0; i < pi->num_cmds; i++) {
2688 struct command *command;
2689 struct redir_struct *r, *rnext;
2691 command = &pi->cmds[i];
2692 debug_printf_clean(" command %d:\n", i);
2693 if (command->argv) {
2697 for (a = 0, p = command->argv; *p; a++, p++) {
2698 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2701 free_strings(command->argv);
2702 //command->argv = NULL;
2704 /* not "else if": on syntax error, we may have both! */
2705 if (command->group) {
2706 debug_printf_clean(" begin group (cmd_type:%d)\n",
2708 free_pipe_list(command->group);
2709 debug_printf_clean(" end group\n");
2710 //command->group = NULL;
2712 /* else is crucial here.
2713 * If group != NULL, child_func is meaningless */
2714 #if ENABLE_HUSH_FUNCTIONS
2715 else if (command->child_func) {
2716 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2717 command->child_func->parent_cmd = NULL;
2721 free(command->group_as_string);
2722 //command->group_as_string = NULL;
2724 for (r = command->redirects; r; r = rnext) {
2725 debug_printf_clean(" redirect %d%s",
2726 r->rd_fd, redir_table[r->rd_type].descrip);
2727 /* guard against the case >$FOO, where foo is unset or blank */
2728 if (r->rd_filename) {
2729 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2730 free(r->rd_filename);
2731 //r->rd_filename = NULL;
2733 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2737 //command->redirects = NULL;
2739 free(pi->cmds); /* children are an array, they get freed all at once */
2743 //pi->cmdtext = NULL;
2751 static void free_pipe_list(struct pipe *pi)
2755 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2757 debug_printf_clean("pipe followup code %d\n", pi->followup);
2763 /*** Parsing routines ***/
2765 #ifndef debug_print_tree
2766 static void debug_print_tree(struct pipe *pi, int lvl)
2768 static const char *const PIPE[] = {
2774 static const char *RES[] = {
2775 [RES_NONE ] = "NONE" ,
2778 [RES_THEN ] = "THEN" ,
2779 [RES_ELIF ] = "ELIF" ,
2780 [RES_ELSE ] = "ELSE" ,
2783 # if ENABLE_HUSH_LOOPS
2784 [RES_FOR ] = "FOR" ,
2785 [RES_WHILE] = "WHILE",
2786 [RES_UNTIL] = "UNTIL",
2788 [RES_DONE ] = "DONE" ,
2790 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2793 # if ENABLE_HUSH_CASE
2794 [RES_CASE ] = "CASE" ,
2795 [RES_CASE_IN ] = "CASE_IN" ,
2796 [RES_MATCH] = "MATCH",
2797 [RES_CASE_BODY] = "CASE_BODY",
2798 [RES_ESAC ] = "ESAC" ,
2800 [RES_XXXX ] = "XXXX" ,
2801 [RES_SNTX ] = "SNTX" ,
2803 static const char *const CMDTYPE[] = {
2807 # if ENABLE_HUSH_FUNCTIONS
2816 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2817 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2819 while (prn < pi->num_cmds) {
2820 struct command *command = &pi->cmds[prn];
2821 char **argv = command->argv;
2823 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2825 command->assignment_cnt);
2826 if (command->group) {
2827 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2828 CMDTYPE[command->cmd_type],
2831 , " group_as_string:", command->group_as_string
2836 debug_print_tree(command->group, lvl+1);
2840 if (argv) while (*argv) {
2841 fdprintf(2, " '%s'", *argv);
2851 #endif /* debug_print_tree */
2853 static struct pipe *new_pipe(void)
2856 pi = xzalloc(sizeof(struct pipe));
2857 /*pi->followup = 0; - deliberately invalid value */
2858 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2862 /* Command (member of a pipe) is complete, or we start a new pipe
2863 * if ctx->command is NULL.
2864 * No errors possible here.
2866 static int done_command(struct parse_context *ctx)
2868 /* The command is really already in the pipe structure, so
2869 * advance the pipe counter and make a new, null command. */
2870 struct pipe *pi = ctx->pipe;
2871 struct command *command = ctx->command;
2874 if (IS_NULL_CMD(command)) {
2875 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2879 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2880 //debug_print_tree(ctx->list_head, 20);
2882 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2885 /* Only real trickiness here is that the uncommitted
2886 * command structure is not counted in pi->num_cmds. */
2887 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2888 ctx->command = command = &pi->cmds[pi->num_cmds];
2890 memset(command, 0, sizeof(*command));
2891 return pi->num_cmds; /* used only for 0/nonzero check */
2894 static void done_pipe(struct parse_context *ctx, pipe_style type)
2898 debug_printf_parse("done_pipe entered, followup %d\n", type);
2899 /* Close previous command */
2900 not_null = done_command(ctx);
2901 ctx->pipe->followup = type;
2903 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2904 ctx->ctx_inverted = 0;
2905 ctx->pipe->res_word = ctx->ctx_res_w;
2908 /* Without this check, even just <enter> on command line generates
2909 * tree of three NOPs (!). Which is harmless but annoying.
2910 * IOW: it is safe to do it unconditionally. */
2913 || ctx->ctx_res_w == RES_FI
2915 #if ENABLE_HUSH_LOOPS
2916 || ctx->ctx_res_w == RES_DONE
2917 || ctx->ctx_res_w == RES_FOR
2918 || ctx->ctx_res_w == RES_IN
2920 #if ENABLE_HUSH_CASE
2921 || ctx->ctx_res_w == RES_ESAC
2925 debug_printf_parse("done_pipe: adding new pipe: "
2926 "not_null:%d ctx->ctx_res_w:%d\n",
2927 not_null, ctx->ctx_res_w);
2929 ctx->pipe->next = new_p;
2931 /* RES_THEN, RES_DO etc are "sticky" -
2932 * they remain set for pipes inside if/while.
2933 * This is used to control execution.
2934 * RES_FOR and RES_IN are NOT sticky (needed to support
2935 * cases where variable or value happens to match a keyword):
2937 #if ENABLE_HUSH_LOOPS
2938 if (ctx->ctx_res_w == RES_FOR
2939 || ctx->ctx_res_w == RES_IN)
2940 ctx->ctx_res_w = RES_NONE;
2942 #if ENABLE_HUSH_CASE
2943 if (ctx->ctx_res_w == RES_MATCH)
2944 ctx->ctx_res_w = RES_CASE_BODY;
2945 if (ctx->ctx_res_w == RES_CASE)
2946 ctx->ctx_res_w = RES_CASE_IN;
2948 ctx->command = NULL; /* trick done_command below */
2949 /* Create the memory for command, roughly:
2950 * ctx->pipe->cmds = new struct command;
2951 * ctx->command = &ctx->pipe->cmds[0];
2954 //debug_print_tree(ctx->list_head, 10);
2956 debug_printf_parse("done_pipe return\n");
2959 static void initialize_context(struct parse_context *ctx)
2961 memset(ctx, 0, sizeof(*ctx));
2962 ctx->pipe = ctx->list_head = new_pipe();
2963 /* Create the memory for command, roughly:
2964 * ctx->pipe->cmds = new struct command;
2965 * ctx->command = &ctx->pipe->cmds[0];
2970 /* If a reserved word is found and processed, parse context is modified
2971 * and 1 is returned.
2974 struct reserved_combo {
2977 unsigned char assignment_flag;
2981 FLAG_END = (1 << RES_NONE ),
2983 FLAG_IF = (1 << RES_IF ),
2984 FLAG_THEN = (1 << RES_THEN ),
2985 FLAG_ELIF = (1 << RES_ELIF ),
2986 FLAG_ELSE = (1 << RES_ELSE ),
2987 FLAG_FI = (1 << RES_FI ),
2989 # if ENABLE_HUSH_LOOPS
2990 FLAG_FOR = (1 << RES_FOR ),
2991 FLAG_WHILE = (1 << RES_WHILE),
2992 FLAG_UNTIL = (1 << RES_UNTIL),
2993 FLAG_DO = (1 << RES_DO ),
2994 FLAG_DONE = (1 << RES_DONE ),
2995 FLAG_IN = (1 << RES_IN ),
2997 # if ENABLE_HUSH_CASE
2998 FLAG_MATCH = (1 << RES_MATCH),
2999 FLAG_ESAC = (1 << RES_ESAC ),
3001 FLAG_START = (1 << RES_XXXX ),
3004 static const struct reserved_combo* match_reserved_word(o_string *word)
3006 /* Mostly a list of accepted follow-up reserved words.
3007 * FLAG_END means we are done with the sequence, and are ready
3008 * to turn the compound list into a command.
3009 * FLAG_START means the word must start a new compound list.
3011 static const struct reserved_combo reserved_list[] = {
3013 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3014 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3015 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3016 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3017 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3018 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3020 # if ENABLE_HUSH_LOOPS
3021 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3022 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3023 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3024 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3025 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3026 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3028 # if ENABLE_HUSH_CASE
3029 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3030 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3033 const struct reserved_combo *r;
3035 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3036 if (strcmp(word->data, r->literal) == 0)
3041 /* Return 0: not a keyword, 1: keyword
3043 static int reserved_word(o_string *word, struct parse_context *ctx)
3045 # if ENABLE_HUSH_CASE
3046 static const struct reserved_combo reserved_match = {
3047 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3050 const struct reserved_combo *r;
3052 if (word->has_quoted_part)
3054 r = match_reserved_word(word);
3058 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3059 # if ENABLE_HUSH_CASE
3060 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3061 /* "case word IN ..." - IN part starts first MATCH part */
3062 r = &reserved_match;
3065 if (r->flag == 0) { /* '!' */
3066 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3067 syntax_error("! ! command");
3068 ctx->ctx_res_w = RES_SNTX;
3070 ctx->ctx_inverted = 1;
3073 if (r->flag & FLAG_START) {
3074 struct parse_context *old;
3076 old = xmalloc(sizeof(*old));
3077 debug_printf_parse("push stack %p\n", old);
3078 *old = *ctx; /* physical copy */
3079 initialize_context(ctx);
3081 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3082 syntax_error_at(word->data);
3083 ctx->ctx_res_w = RES_SNTX;
3086 /* "{...} fi" is ok. "{...} if" is not
3088 * if { echo foo; } then { echo bar; } fi */
3089 if (ctx->command->group)
3090 done_pipe(ctx, PIPE_SEQ);
3093 ctx->ctx_res_w = r->res;
3094 ctx->old_flag = r->flag;
3095 word->o_assignment = r->assignment_flag;
3097 if (ctx->old_flag & FLAG_END) {
3098 struct parse_context *old;
3100 done_pipe(ctx, PIPE_SEQ);
3101 debug_printf_parse("pop stack %p\n", ctx->stack);
3103 old->command->group = ctx->list_head;
3104 old->command->cmd_type = CMD_NORMAL;
3106 o_addstr(&old->as_string, ctx->as_string.data);
3107 o_free_unsafe(&ctx->as_string);
3108 old->command->group_as_string = xstrdup(old->as_string.data);
3109 debug_printf_parse("pop, remembering as:'%s'\n",
3110 old->command->group_as_string);
3112 *ctx = *old; /* physical copy */
3117 #endif /* HAS_KEYWORDS */
3119 /* Word is complete, look at it and update parsing context.
3120 * Normal return is 0. Syntax errors return 1.
3121 * Note: on return, word is reset, but not o_free'd!
3123 static int done_word(o_string *word, struct parse_context *ctx)
3125 struct command *command = ctx->command;
3127 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3128 if (word->length == 0 && !word->has_quoted_part) {
3129 debug_printf_parse("done_word return 0: true null, ignored\n");
3133 if (ctx->pending_redirect) {
3134 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3135 * only if run as "bash", not "sh" */
3136 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3138 * ...the word that follows the redirection operator
3139 * shall be subjected to tilde expansion, parameter expansion,
3140 * command substitution, arithmetic expansion, and quote
3141 * removal. Pathname expansion shall not be performed
3142 * on the word by a non-interactive shell; an interactive
3143 * shell may perform it, but shall do so only when
3144 * the expansion would result in one word."
3146 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3147 /* Cater for >\file case:
3148 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3149 * Same with heredocs:
3150 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3152 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3153 unbackslash(ctx->pending_redirect->rd_filename);
3154 /* Is it <<"HEREDOC"? */
3155 if (word->has_quoted_part) {
3156 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3159 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3160 ctx->pending_redirect = NULL;
3162 /* If this word wasn't an assignment, next ones definitely
3163 * can't be assignments. Even if they look like ones. */
3164 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3165 && word->o_assignment != WORD_IS_KEYWORD
3167 word->o_assignment = NOT_ASSIGNMENT;
3169 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3170 command->assignment_cnt++;
3171 word->o_assignment = MAYBE_ASSIGNMENT;
3175 # if ENABLE_HUSH_CASE
3176 if (ctx->ctx_dsemicolon
3177 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3179 /* already done when ctx_dsemicolon was set to 1: */
3180 /* ctx->ctx_res_w = RES_MATCH; */
3181 ctx->ctx_dsemicolon = 0;
3184 if (!command->argv /* if it's the first word... */
3185 # if ENABLE_HUSH_LOOPS
3186 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3187 && ctx->ctx_res_w != RES_IN
3189 # if ENABLE_HUSH_CASE
3190 && ctx->ctx_res_w != RES_CASE
3193 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3194 if (reserved_word(word, ctx)) {
3195 o_reset_to_empty_unquoted(word);
3196 debug_printf_parse("done_word return %d\n",
3197 (ctx->ctx_res_w == RES_SNTX));
3198 return (ctx->ctx_res_w == RES_SNTX);
3200 # if ENABLE_HUSH_BASH_COMPAT
3201 if (strcmp(word->data, "[[") == 0) {
3202 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3208 if (command->group) {
3209 /* "{ echo foo; } echo bar" - bad */
3210 syntax_error_at(word->data);
3211 debug_printf_parse("done_word return 1: syntax error, "
3212 "groups and arglists don't mix\n");
3215 if (word->has_quoted_part
3216 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3217 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3218 /* (otherwise it's known to be not empty and is already safe) */
3220 /* exclude "$@" - it can expand to no word despite "" */
3221 char *p = word->data;
3222 while (p[0] == SPECIAL_VAR_SYMBOL
3223 && (p[1] & 0x7f) == '@'
3224 && p[2] == SPECIAL_VAR_SYMBOL
3228 if (p == word->data || p[0] != '\0') {
3229 /* saw no "$@", or not only "$@" but some
3230 * real text is there too */
3231 /* insert "empty variable" reference, this makes
3232 * e.g. "", $empty"" etc to not disappear */
3233 o_addchr(word, SPECIAL_VAR_SYMBOL);
3234 o_addchr(word, SPECIAL_VAR_SYMBOL);
3237 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3238 debug_print_strings("word appended to argv", command->argv);
3241 #if ENABLE_HUSH_LOOPS
3242 if (ctx->ctx_res_w == RES_FOR) {
3243 if (word->has_quoted_part
3244 || !is_well_formed_var_name(command->argv[0], '\0')
3246 /* bash says just "not a valid identifier" */
3247 syntax_error("not a valid identifier in for");
3250 /* Force FOR to have just one word (variable name) */
3251 /* NB: basically, this makes hush see "for v in ..."
3252 * syntax as if it is "for v; in ...". FOR and IN become
3253 * two pipe structs in parse tree. */
3254 done_pipe(ctx, PIPE_SEQ);
3257 #if ENABLE_HUSH_CASE
3258 /* Force CASE to have just one word */
3259 if (ctx->ctx_res_w == RES_CASE) {
3260 done_pipe(ctx, PIPE_SEQ);
3264 o_reset_to_empty_unquoted(word);
3266 debug_printf_parse("done_word return 0\n");
3271 /* Peek ahead in the input to find out if we have a "&n" construct,
3272 * as in "2>&1", that represents duplicating a file descriptor.
3274 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3275 * REDIRFD_SYNTAX_ERR if syntax error,
3276 * REDIRFD_TO_FILE if no & was seen,
3277 * or the number found.
3280 #define parse_redir_right_fd(as_string, input) \
3281 parse_redir_right_fd(input)
3283 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3289 return REDIRFD_TO_FILE;
3291 ch = i_getch(input); /* get the & */
3292 nommu_addchr(as_string, ch);
3295 ch = i_getch(input);
3296 nommu_addchr(as_string, ch);
3297 return REDIRFD_CLOSE;
3301 while (ch != EOF && isdigit(ch)) {
3302 d = d*10 + (ch-'0');
3304 ch = i_getch(input);
3305 nommu_addchr(as_string, ch);
3310 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3312 bb_error_msg("ambiguous redirect");
3313 return REDIRFD_SYNTAX_ERR;
3316 /* Return code is 0 normal, 1 if a syntax error is detected
3318 static int parse_redirect(struct parse_context *ctx,
3321 struct in_str *input)
3323 struct command *command = ctx->command;
3324 struct redir_struct *redir;
3325 struct redir_struct **redirp;
3328 dup_num = REDIRFD_TO_FILE;
3329 if (style != REDIRECT_HEREDOC) {
3330 /* Check for a '>&1' type redirect */
3331 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3332 if (dup_num == REDIRFD_SYNTAX_ERR)
3335 int ch = i_peek(input);
3336 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3337 if (dup_num) { /* <<-... */
3338 ch = i_getch(input);
3339 nommu_addchr(&ctx->as_string, ch);
3344 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3345 int ch = i_peek(input);
3347 /* >|FILE redirect ("clobbering" >).
3348 * Since we do not support "set -o noclobber" yet,
3349 * >| and > are the same for now. Just eat |.
3351 ch = i_getch(input);
3352 nommu_addchr(&ctx->as_string, ch);
3356 /* Create a new redir_struct and append it to the linked list */
3357 redirp = &command->redirects;
3358 while ((redir = *redirp) != NULL) {
3359 redirp = &(redir->next);
3361 *redirp = redir = xzalloc(sizeof(*redir));
3362 /* redir->next = NULL; */
3363 /* redir->rd_filename = NULL; */
3364 redir->rd_type = style;
3365 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3367 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3368 redir_table[style].descrip);
3370 redir->rd_dup = dup_num;
3371 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3372 /* Erik had a check here that the file descriptor in question
3373 * is legit; I postpone that to "run time"
3374 * A "-" representation of "close me" shows up as a -3 here */
3375 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3376 redir->rd_fd, redir->rd_dup);
3378 /* Set ctx->pending_redirect, so we know what to do at the
3379 * end of the next parsed word. */
3380 ctx->pending_redirect = redir;
3385 /* If a redirect is immediately preceded by a number, that number is
3386 * supposed to tell which file descriptor to redirect. This routine
3387 * looks for such preceding numbers. In an ideal world this routine
3388 * needs to handle all the following classes of redirects...
3389 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3390 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3391 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3392 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3394 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3396 * ... If n is quoted, the number shall not be recognized as part of
3397 * the redirection expression. For example:
3399 * writes the character 2 into file a"
3400 * We are getting it right by setting ->has_quoted_part on any \<char>
3402 * A -1 return means no valid number was found,
3403 * the caller should use the appropriate default for this redirection.
3405 static int redirect_opt_num(o_string *o)
3409 if (o->data == NULL)
3411 num = bb_strtou(o->data, NULL, 10);
3412 if (errno || num < 0)
3414 o_reset_to_empty_unquoted(o);
3419 #define fetch_till_str(as_string, input, word, skip_tabs) \
3420 fetch_till_str(input, word, skip_tabs)
3422 static char *fetch_till_str(o_string *as_string,
3423 struct in_str *input,
3427 o_string heredoc = NULL_O_STRING;
3429 int prev = 0; /* not \ */
3435 ch = i_getch(input);
3437 nommu_addchr(as_string, ch);
3438 if ((ch == '\n' || ch == EOF)
3439 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3441 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3442 heredoc.data[past_EOL] = '\0';
3443 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3444 return heredoc.data;
3446 while (ch == '\n') {
3447 o_addchr(&heredoc, ch);
3450 past_EOL = heredoc.length;
3452 ch = i_getch(input);
3454 nommu_addchr(as_string, ch);
3455 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3459 o_free_unsafe(&heredoc);
3462 o_addchr(&heredoc, ch);
3463 nommu_addchr(as_string, ch);
3464 if (prev == '\\' && ch == '\\')
3465 /* Correctly handle foo\\<eol> (not a line cont.) */
3466 prev = 0; /* not \ */
3472 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3473 * and load them all. There should be exactly heredoc_cnt of them.
3475 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3477 struct pipe *pi = ctx->list_head;
3479 while (pi && heredoc_cnt) {
3481 struct command *cmd = pi->cmds;
3483 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3485 cmd->argv ? cmd->argv[0] : "NONE");
3486 for (i = 0; i < pi->num_cmds; i++) {
3487 struct redir_struct *redir = cmd->redirects;
3489 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3490 i, cmd->argv ? cmd->argv[0] : "NONE");
3492 if (redir->rd_type == REDIRECT_HEREDOC) {
3495 redir->rd_type = REDIRECT_HEREDOC2;
3496 /* redir->rd_dup is (ab)used to indicate <<- */
3497 p = fetch_till_str(&ctx->as_string, input,
3498 redir->rd_filename, redir->rd_dup);
3500 syntax_error("unexpected EOF in here document");
3503 free(redir->rd_filename);
3504 redir->rd_filename = p;
3507 redir = redir->next;
3514 /* Should be 0. If it isn't, it's a parse error */
3516 bb_error_msg_and_die("heredoc BUG 2");
3522 static int run_list(struct pipe *pi);
3524 #define parse_stream(pstring, input, end_trigger) \
3525 parse_stream(input, end_trigger)
3527 static struct pipe *parse_stream(char **pstring,
3528 struct in_str *input,
3532 #if !ENABLE_HUSH_FUNCTIONS
3533 #define parse_group(dest, ctx, input, ch) \
3534 parse_group(ctx, input, ch)
3536 static int parse_group(o_string *dest, struct parse_context *ctx,
3537 struct in_str *input, int ch)
3539 /* dest contains characters seen prior to ( or {.
3540 * Typically it's empty, but for function defs,
3541 * it contains function name (without '()'). */
3542 struct pipe *pipe_list;
3544 struct command *command = ctx->command;
3546 debug_printf_parse("parse_group entered\n");
3547 #if ENABLE_HUSH_FUNCTIONS
3548 if (ch == '(' && !dest->has_quoted_part) {
3550 if (done_word(dest, ctx))
3553 goto skip; /* (... */
3554 if (command->argv[1]) { /* word word ... (... */
3555 syntax_error_unexpected_ch('(');
3558 /* it is "word(..." or "word (..." */
3560 ch = i_getch(input);
3561 while (ch == ' ' || ch == '\t');
3563 syntax_error_unexpected_ch(ch);
3566 nommu_addchr(&ctx->as_string, ch);
3568 ch = i_getch(input);
3569 while (ch == ' ' || ch == '\t' || ch == '\n');
3571 syntax_error_unexpected_ch(ch);
3574 nommu_addchr(&ctx->as_string, ch);
3575 command->cmd_type = CMD_FUNCDEF;
3580 #if 0 /* Prevented by caller */
3581 if (command->argv /* word [word]{... */
3582 || dest->length /* word{... */
3583 || dest->has_quoted_part /* ""{... */
3586 debug_printf_parse("parse_group return 1: "
3587 "syntax error, groups and arglists don't mix\n");
3592 #if ENABLE_HUSH_FUNCTIONS
3598 command->cmd_type = CMD_SUBSHELL;
3600 /* bash does not allow "{echo...", requires whitespace */
3601 ch = i_getch(input);
3602 if (ch != ' ' && ch != '\t' && ch != '\n') {
3603 syntax_error_unexpected_ch(ch);
3606 nommu_addchr(&ctx->as_string, ch);
3611 # define as_string NULL
3613 char *as_string = NULL;
3615 pipe_list = parse_stream(&as_string, input, endch);
3618 o_addstr(&ctx->as_string, as_string);
3620 /* empty ()/{} or parse error? */
3621 if (!pipe_list || pipe_list == ERR_PTR) {
3622 /* parse_stream already emitted error msg */
3625 debug_printf_parse("parse_group return 1: "
3626 "parse_stream returned %p\n", pipe_list);
3629 command->group = pipe_list;
3631 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3632 command->group_as_string = as_string;
3633 debug_printf_parse("end of group, remembering as:'%s'\n",
3634 command->group_as_string);
3638 debug_printf_parse("parse_group return 0\n");
3640 /* command remains "open", available for possible redirects */
3643 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3644 /* Subroutines for copying $(...) and `...` things */
3645 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3647 static int add_till_single_quote(o_string *dest, struct in_str *input)
3650 int ch = i_getch(input);
3652 syntax_error_unterm_ch('\'');
3660 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3661 static int add_till_double_quote(o_string *dest, struct in_str *input)
3664 int ch = i_getch(input);
3666 syntax_error_unterm_ch('"');
3671 if (ch == '\\') { /* \x. Copy both chars. */
3673 ch = i_getch(input);
3677 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3682 //if (ch == '$') ...
3685 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3687 * "Within the backquoted style of command substitution, backslash
3688 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3689 * The search for the matching backquote shall be satisfied by the first
3690 * backquote found without a preceding backslash; during this search,
3691 * if a non-escaped backquote is encountered within a shell comment,
3692 * a here-document, an embedded command substitution of the $(command)
3693 * form, or a quoted string, undefined results occur. A single-quoted
3694 * or double-quoted string that begins, but does not end, within the
3695 * "`...`" sequence produces undefined results."
3697 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3699 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3702 int ch = i_getch(input);
3706 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3707 ch = i_getch(input);
3711 && (!in_dquote || ch != '"')
3713 o_addchr(dest, '\\');
3717 syntax_error_unterm_ch('`');
3723 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3724 * quoting and nested ()s.
3725 * "With the $(command) style of command substitution, all characters
3726 * following the open parenthesis to the matching closing parenthesis
3727 * constitute the command. Any valid shell script can be used for command,
3728 * except a script consisting solely of redirections which produces
3729 * unspecified results."
3731 * echo $(echo '(TEST)' BEST) (TEST) BEST
3732 * echo $(echo 'TEST)' BEST) TEST) BEST
3733 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3735 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3736 * can contain arbitrary constructs, just like $(cmd).
3737 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3738 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3740 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3741 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3744 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3745 # if ENABLE_HUSH_BASH_COMPAT
3746 char end_char2 = end_ch >> 8;
3748 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3751 ch = i_getch(input);
3753 syntax_error_unterm_ch(end_ch);
3756 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3759 /* we look for closing )) of $((EXPR)) */
3760 if (i_peek(input) == end_ch) {
3761 i_getch(input); /* eat second ')' */
3766 if (ch == '(' || ch == '{') {
3767 ch = (ch == '(' ? ')' : '}');
3768 if (!add_till_closing_bracket(dest, input, ch))
3774 if (!add_till_single_quote(dest, input))
3780 if (!add_till_double_quote(dest, input))
3786 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3792 /* \x. Copy verbatim. Important for \(, \) */
3793 ch = i_getch(input);
3795 syntax_error_unterm_ch(')');
3804 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3806 /* Return code: 0 for OK, 1 for syntax error */
3808 #define parse_dollar(as_string, dest, input, quote_mask) \
3809 parse_dollar(dest, input, quote_mask)
3810 #define as_string NULL
3812 static int parse_dollar(o_string *as_string,
3814 struct in_str *input, unsigned char quote_mask)
3816 int ch = i_peek(input); /* first character after the $ */
3818 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3820 ch = i_getch(input);
3821 nommu_addchr(as_string, ch);
3823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3825 debug_printf_parse(": '%c'\n", ch);
3826 o_addchr(dest, ch | quote_mask);
3829 if (!isalnum(ch) && ch != '_')
3831 ch = i_getch(input);
3832 nommu_addchr(as_string, ch);
3834 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3835 } else if (isdigit(ch)) {
3837 ch = i_getch(input);
3838 nommu_addchr(as_string, ch);
3839 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3840 debug_printf_parse(": '%c'\n", ch);
3841 o_addchr(dest, ch | quote_mask);
3842 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3843 } else switch (ch) {
3845 case '!': /* last bg pid */
3846 case '?': /* last exit code */
3847 case '#': /* number of args */
3848 case '*': /* args */
3849 case '@': /* args */
3850 goto make_one_char_var;
3852 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3854 ch = i_getch(input); /* eat '{' */
3855 nommu_addchr(as_string, ch);
3857 ch = i_getch(input); /* first char after '{' */
3858 /* It should be ${?}, or ${#var},
3859 * or even ${?+subst} - operator acting on a special variable,
3860 * or the beginning of variable name.
3863 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3866 syntax_error_unterm_str("${name}");
3867 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3870 nommu_addchr(as_string, ch);
3873 /* It's possible to just call add_till_closing_bracket() at this point.
3874 * However, this regresses some of our testsuite cases
3875 * which check invalid constructs like ${%}.
3876 * Oh well... let's check that the var name part is fine... */
3882 debug_printf_parse(": '%c'\n", ch);
3884 ch = i_getch(input);
3885 nommu_addchr(as_string, ch);
3889 if (!isalnum(ch) && ch != '_') {
3891 unsigned char last_ch;
3892 /* handle parameter expansions
3893 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3895 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3896 goto bad_dollar_syntax;
3898 /* Eat everything until closing '}' (or ':') */
3900 if (ENABLE_HUSH_BASH_COMPAT
3902 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3904 /* It's ${var:N[:M]} thing */
3905 end_ch = '}' * 0x100 + ':';
3907 if (ENABLE_HUSH_BASH_COMPAT
3910 /* It's ${var/[/]pattern[/repl]} thing */
3911 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3913 nommu_addchr(as_string, '/');
3916 end_ch = '}' * 0x100 + '/';
3922 #if ENABLE_HUSH_DOLLAR_OPS
3923 last_ch = add_till_closing_bracket(dest, input, end_ch);
3924 if (last_ch == 0) /* error? */
3927 #error Simple code to only allow ${var} is not implemented
3930 o_addstr(as_string, dest->data + pos);
3931 o_addchr(as_string, last_ch);
3934 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3935 /* close the first block: */
3936 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3937 /* while parsing N from ${var:N[:M]}
3938 * or pattern from ${var/[/]pattern[/repl]} */
3939 if ((end_ch & 0xff) == last_ch) {
3940 /* got ':' or '/'- parse the rest */
3945 if (end_ch == '}' * 0x100 + ':') {
3946 /* it's ${var:N} - emulate :999999999 */
3947 o_addstr(dest, "999999999");
3948 } /* else: it's ${var/[/]pattern} */
3953 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3956 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3960 ch = i_getch(input);
3961 nommu_addchr(as_string, ch);
3962 # if ENABLE_SH_MATH_SUPPORT
3963 if (i_peek(input) == '(') {
3964 ch = i_getch(input);
3965 nommu_addchr(as_string, ch);
3966 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3967 o_addchr(dest, /*quote_mask |*/ '+');
3970 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3971 return 0; /* error */
3973 o_addstr(as_string, dest->data + pos);
3974 o_addchr(as_string, ')');
3975 o_addchr(as_string, ')');
3977 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3981 # if ENABLE_HUSH_TICK
3982 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3983 o_addchr(dest, quote_mask | '`');
3986 if (!add_till_closing_bracket(dest, input, ')'))
3987 return 0; /* error */
3989 o_addstr(as_string, dest->data + pos);
3990 o_addchr(as_string, ')');
3992 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3998 ch = i_getch(input);
3999 nommu_addchr(as_string, ch);
4001 if (isalnum(ch)) { /* it's $_name or $_123 */
4006 /* TODO: $_ and $-: */
4007 /* $_ Shell or shell script name; or last argument of last command
4008 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4009 * but in command's env, set to full pathname used to invoke it */
4010 /* $- Option flags set by set builtin or shell options (-i etc) */
4012 o_addQchr(dest, '$');
4014 debug_printf_parse("parse_dollar return 1 (ok)\n");
4020 # if ENABLE_HUSH_BASH_COMPAT
4021 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4022 encode_string(dest, input, dquote_end, process_bkslash)
4024 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4025 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4026 encode_string(dest, input, dquote_end)
4028 #define as_string NULL
4032 # if ENABLE_HUSH_BASH_COMPAT
4033 /* all parameters are needed, no macro tricks */
4035 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4036 encode_string(as_string, dest, input, dquote_end)
4039 static int encode_string(o_string *as_string,
4041 struct in_str *input,
4043 int process_bkslash)
4045 #if !ENABLE_HUSH_BASH_COMPAT
4046 const int process_bkslash = 1;
4052 ch = i_getch(input);
4054 nommu_addchr(as_string, ch);
4055 if (ch == dquote_end) { /* may be only '"' or EOF */
4056 debug_printf_parse("encode_string return 1 (ok)\n");
4059 /* note: can't move it above ch == dquote_end check! */
4061 syntax_error_unterm_ch('"');
4062 return 0; /* error */
4066 next = i_peek(input);
4068 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4069 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4070 if (process_bkslash && ch == '\\') {
4072 syntax_error("\\<eof>");
4076 * "The backslash retains its special meaning [in "..."]
4077 * only when followed by one of the following characters:
4078 * $, `, ", \, or <newline>. A double quote may be quoted
4079 * within double quotes by preceding it with a backslash."
4080 * NB: in (unquoted) heredoc, above does not apply to ",
4081 * therefore we check for it by "next == dquote_end" cond.
4083 if (next == dquote_end || strchr("$`\\\n", next)) {
4084 ch = i_getch(input); /* eat next */
4086 goto again; /* skip \<newline> */
4087 } /* else: ch remains == '\\', and we double it below: */
4088 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4089 nommu_addchr(as_string, ch);
4093 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4094 debug_printf_parse("encode_string return 0: "
4095 "parse_dollar returned 0 (error)\n");
4100 #if ENABLE_HUSH_TICK
4102 //unsigned pos = dest->length;
4103 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4104 o_addchr(dest, 0x80 | '`');
4105 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4106 return 0; /* error */
4107 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4108 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4112 o_addQchr(dest, ch);
4118 * Scan input until EOF or end_trigger char.
4119 * Return a list of pipes to execute, or NULL on EOF
4120 * or if end_trigger character is met.
4121 * On syntax error, exit if shell is not interactive,
4122 * reset parsing machinery and start parsing anew,
4123 * or return ERR_PTR.
4125 static struct pipe *parse_stream(char **pstring,
4126 struct in_str *input,
4129 struct parse_context ctx;
4130 o_string dest = NULL_O_STRING;
4133 /* Single-quote triggers a bypass of the main loop until its mate is
4134 * found. When recursing, quote state is passed in via dest->o_expflags.
4136 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4137 end_trigger ? end_trigger : 'X');
4140 /* If very first arg is "" or '', dest.data may end up NULL.
4141 * Preventing this: */
4142 o_addchr(&dest, '\0');
4145 /* We used to separate words on $IFS here. This was wrong.
4146 * $IFS is used only for word splitting when $var is expanded,
4147 * here we should use blank chars as separators, not $IFS
4150 if (MAYBE_ASSIGNMENT != 0)
4151 dest.o_assignment = MAYBE_ASSIGNMENT;
4152 initialize_context(&ctx);
4155 const char *is_blank;
4156 const char *is_special;
4160 redir_type redir_style;
4162 ch = i_getch(input);
4163 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4164 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4169 syntax_error_unterm_str("here document");
4172 /* end_trigger == '}' case errors out earlier,
4173 * checking only ')' */
4174 if (end_trigger == ')') {
4175 syntax_error_unterm_ch('(');
4179 if (done_word(&dest, &ctx)) {
4183 done_pipe(&ctx, PIPE_SEQ);
4185 /* If we got nothing... */
4186 /* (this makes bare "&" cmd a no-op.
4187 * bash says: "syntax error near unexpected token '&'") */
4188 if (pi->num_cmds == 0
4189 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4195 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4197 *pstring = ctx.as_string.data;
4199 o_free_unsafe(&ctx.as_string);
4202 debug_printf_parse("parse_stream return %p\n", pi);
4205 nommu_addchr(&ctx.as_string, ch);
4209 next = i_peek(input);
4211 is_special = "{}<>;&|()#'" /* special outside of "str" */
4212 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4213 /* Are { and } special here? */
4214 if (ctx.command->argv /* word [word]{... - non-special */
4215 || dest.length /* word{... - non-special */
4216 || dest.has_quoted_part /* ""{... - non-special */
4217 || (next != ';' /* }; - special */
4218 && next != ')' /* }) - special */
4219 && next != '&' /* }& and }&& ... - special */
4220 && next != '|' /* }|| ... - special */
4221 && !strchr(defifs, next) /* {word - non-special */
4224 /* They are not special, skip "{}" */
4227 is_special = strchr(is_special, ch);
4228 is_blank = strchr(defifs, ch);
4230 if (!is_special && !is_blank) { /* ordinary char */
4232 o_addQchr(&dest, ch);
4233 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4234 || dest.o_assignment == WORD_IS_KEYWORD)
4236 && is_well_formed_var_name(dest.data, '=')
4238 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4244 if (done_word(&dest, &ctx)) {
4248 /* Is this a case when newline is simply ignored?
4250 * "cmd | <newline> cmd ..."
4251 * "case ... in <newline> word) ..."
4253 if (IS_NULL_CMD(ctx.command)
4254 && dest.length == 0 && !dest.has_quoted_part
4256 /* This newline can be ignored. But...
4257 * Without check #1, interactive shell
4258 * ignores even bare <newline>,
4259 * and shows the continuation prompt:
4260 * ps1_prompt$ <enter>
4261 * ps2> _ <=== wrong, should be ps1
4262 * Without check #2, "cmd & <newline>"
4263 * is similarly mistreated.
4264 * (BTW, this makes "cmd & cmd"
4265 * and "cmd && cmd" non-orthogonal.
4266 * Really, ask yourself, why
4267 * "cmd && <newline>" doesn't start
4268 * cmd but waits for more input?
4271 struct pipe *pi = ctx.list_head;
4272 if (pi->num_cmds != 0 /* check #1 */
4273 && pi->followup != PIPE_BG /* check #2 */
4278 /* Treat newline as a command separator. */
4279 done_pipe(&ctx, PIPE_SEQ);
4280 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4282 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4287 dest.o_assignment = MAYBE_ASSIGNMENT;
4289 /* note: if (is_blank) continue;
4290 * will still trigger for us */
4294 /* "cmd}" or "cmd }..." without semicolon or &:
4295 * } is an ordinary char in this case, even inside { cmd; }
4296 * Pathological example: { ""}; } should exec "}" cmd
4299 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4300 || dest.length != 0 /* word} */
4301 || dest.has_quoted_part /* ""} */
4305 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4306 goto skip_end_trigger;
4307 /* else: } does terminate a group */
4310 if (end_trigger && end_trigger == ch
4311 && (ch != ';' || heredoc_cnt == 0)
4312 #if ENABLE_HUSH_CASE
4314 || ctx.ctx_res_w != RES_MATCH
4315 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4320 /* This is technically valid:
4321 * { cat <<HERE; }; echo Ok
4325 * but we don't support this.
4326 * We require heredoc to be in enclosing {}/(),
4329 syntax_error_unterm_str("here document");
4332 if (done_word(&dest, &ctx)) {
4335 done_pipe(&ctx, PIPE_SEQ);
4336 dest.o_assignment = MAYBE_ASSIGNMENT;
4337 /* Do we sit outside of any if's, loops or case's? */
4339 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4343 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4345 *pstring = ctx.as_string.data;
4347 o_free_unsafe(&ctx.as_string);
4350 debug_printf_parse("parse_stream return %p: "
4351 "end_trigger char found\n",
4353 return ctx.list_head;
4360 /* Catch <, > before deciding whether this word is
4361 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4364 redir_fd = redirect_opt_num(&dest);
4365 if (done_word(&dest, &ctx)) {
4368 redir_style = REDIRECT_OVERWRITE;
4370 redir_style = REDIRECT_APPEND;
4371 ch = i_getch(input);
4372 nommu_addchr(&ctx.as_string, ch);
4375 else if (next == '(') {
4376 syntax_error(">(process) not supported");
4380 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4382 continue; /* back to top of while (1) */
4384 redir_fd = redirect_opt_num(&dest);
4385 if (done_word(&dest, &ctx)) {
4388 redir_style = REDIRECT_INPUT;
4390 redir_style = REDIRECT_HEREDOC;
4392 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4393 ch = i_getch(input);
4394 nommu_addchr(&ctx.as_string, ch);
4395 } else if (next == '>') {
4396 redir_style = REDIRECT_IO;
4397 ch = i_getch(input);
4398 nommu_addchr(&ctx.as_string, ch);
4401 else if (next == '(') {
4402 syntax_error("<(process) not supported");
4406 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4408 continue; /* back to top of while (1) */
4410 if (dest.length == 0 && !dest.has_quoted_part) {
4411 /* skip "#comment" */
4414 if (ch == EOF || ch == '\n')
4417 /* note: we do not add it to &ctx.as_string */
4419 nommu_addchr(&ctx.as_string, '\n');
4420 continue; /* back to top of while (1) */
4425 /* It's "\<newline>" */
4427 /* Remove trailing '\' from ctx.as_string */
4428 ctx.as_string.data[--ctx.as_string.length] = '\0';
4430 ch = i_getch(input); /* eat it */
4431 continue; /* back to top of while (1) */
4436 if (dest.o_assignment == MAYBE_ASSIGNMENT
4437 /* check that we are not in word in "a=1 2>word b=1": */
4438 && !ctx.pending_redirect
4440 /* ch is a special char and thus this word
4441 * cannot be an assignment */
4442 dest.o_assignment = NOT_ASSIGNMENT;
4445 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4448 case '#': /* non-comment #: "echo a#b" etc */
4449 o_addQchr(&dest, ch);
4453 syntax_error("\\<eof>");
4456 ch = i_getch(input);
4457 /* note: ch != '\n' (that case does not reach this place) */
4458 o_addchr(&dest, '\\');
4459 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4460 o_addchr(&dest, ch);
4461 nommu_addchr(&ctx.as_string, ch);
4462 /* Example: echo Hello \2>file
4463 * we need to know that word 2 is quoted */
4464 dest.has_quoted_part = 1;
4467 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4468 debug_printf_parse("parse_stream parse error: "
4469 "parse_dollar returned 0 (error)\n");
4474 dest.has_quoted_part = 1;
4476 ch = i_getch(input);
4478 syntax_error_unterm_ch('\'');
4481 nommu_addchr(&ctx.as_string, ch);
4484 o_addqchr(&dest, ch);
4488 dest.has_quoted_part = 1;
4489 if (dest.o_assignment == NOT_ASSIGNMENT)
4490 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4491 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4493 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4495 #if ENABLE_HUSH_TICK
4499 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4500 o_addchr(&dest, '`');
4502 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4505 o_addstr(&ctx.as_string, dest.data + pos);
4506 o_addchr(&ctx.as_string, '`');
4508 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4509 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4514 #if ENABLE_HUSH_CASE
4517 if (done_word(&dest, &ctx)) {
4520 done_pipe(&ctx, PIPE_SEQ);
4521 #if ENABLE_HUSH_CASE
4522 /* Eat multiple semicolons, detect
4523 * whether it means something special */
4528 ch = i_getch(input);
4529 nommu_addchr(&ctx.as_string, ch);
4530 if (ctx.ctx_res_w == RES_CASE_BODY) {
4531 ctx.ctx_dsemicolon = 1;
4532 ctx.ctx_res_w = RES_MATCH;
4538 /* We just finished a cmd. New one may start
4539 * with an assignment */
4540 dest.o_assignment = MAYBE_ASSIGNMENT;
4543 if (done_word(&dest, &ctx)) {
4547 ch = i_getch(input);
4548 nommu_addchr(&ctx.as_string, ch);
4549 done_pipe(&ctx, PIPE_AND);
4551 done_pipe(&ctx, PIPE_BG);
4555 if (done_word(&dest, &ctx)) {
4558 #if ENABLE_HUSH_CASE
4559 if (ctx.ctx_res_w == RES_MATCH)
4560 break; /* we are in case's "word | word)" */
4562 if (next == '|') { /* || */
4563 ch = i_getch(input);
4564 nommu_addchr(&ctx.as_string, ch);
4565 done_pipe(&ctx, PIPE_OR);
4567 /* we could pick up a file descriptor choice here
4568 * with redirect_opt_num(), but bash doesn't do it.
4569 * "echo foo 2| cat" yields "foo 2". */
4572 o_reset_to_empty_unquoted(&ctx.as_string);
4577 #if ENABLE_HUSH_CASE
4578 /* "case... in [(]word)..." - skip '(' */
4579 if (ctx.ctx_res_w == RES_MATCH
4580 && ctx.command->argv == NULL /* not (word|(... */
4581 && dest.length == 0 /* not word(... */
4582 && dest.has_quoted_part == 0 /* not ""(... */
4588 if (parse_group(&dest, &ctx, input, ch) != 0) {
4593 #if ENABLE_HUSH_CASE
4594 if (ctx.ctx_res_w == RES_MATCH)
4598 /* proper use of this character is caught by end_trigger:
4599 * if we see {, we call parse_group(..., end_trigger='}')
4600 * and it will match } earlier (not here). */
4601 syntax_error_unexpected_ch(ch);
4605 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4611 struct parse_context *pctx;
4612 IF_HAS_KEYWORDS(struct parse_context *p2;)
4614 /* Clean up allocated tree.
4615 * Sample for finding leaks on syntax error recovery path.
4616 * Run it from interactive shell, watch pmap `pidof hush`.
4617 * while if false; then false; fi; do break; fi
4618 * Samples to catch leaks at execution:
4619 * while if (true | {true;}); then echo ok; fi; do break; done
4620 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4624 /* Update pipe/command counts,
4625 * otherwise freeing may miss some */
4626 done_pipe(pctx, PIPE_SEQ);
4627 debug_printf_clean("freeing list %p from ctx %p\n",
4628 pctx->list_head, pctx);
4629 debug_print_tree(pctx->list_head, 0);
4630 free_pipe_list(pctx->list_head);
4631 debug_printf_clean("freed list %p\n", pctx->list_head);
4633 o_free_unsafe(&pctx->as_string);
4635 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4639 IF_HAS_KEYWORDS(pctx = p2;)
4640 } while (HAS_KEYWORDS && pctx);
4643 G.last_exitcode = 1;
4654 /*** Execution routines ***/
4656 /* Expansion can recurse, need forward decls: */
4657 #if !ENABLE_HUSH_BASH_COMPAT
4658 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4659 #define expand_string_to_string(str, do_unbackslash) \
4660 expand_string_to_string(str)
4662 static char *expand_string_to_string(const char *str, int do_unbackslash);
4663 #if ENABLE_HUSH_TICK
4664 static int process_command_subs(o_string *dest, const char *s);
4667 /* expand_strvec_to_strvec() takes a list of strings, expands
4668 * all variable references within and returns a pointer to
4669 * a list of expanded strings, possibly with larger number
4670 * of strings. (Think VAR="a b"; echo $VAR).
4671 * This new list is allocated as a single malloc block.
4672 * NULL-terminated list of char* pointers is at the beginning of it,
4673 * followed by strings themselves.
4674 * Caller can deallocate entire list by single free(list). */
4676 /* A horde of its helpers come first: */
4678 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4680 while (--len >= 0) {
4683 #if ENABLE_HUSH_BRACE_EXPANSION
4684 if (c == '{' || c == '}') {
4685 /* { -> \{, } -> \} */
4687 /* And now we want to add { or } and continue:
4690 * luckily, just falling throught achieves this.
4696 /* \z -> \\\z; \<eol> -> \\<eol> */
4701 o_addchr(o, *str++);
4707 /* Store given string, finalizing the word and starting new one whenever
4708 * we encounter IFS char(s). This is used for expanding variable values.
4709 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4710 static int expand_on_ifs(o_string *output, int n, const char *str)
4713 int word_len = strcspn(str, G.ifs);
4715 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4716 o_addblock(output, str, word_len);
4718 /* Protect backslashes against globbing up :)
4719 * Example: "v='\*'; echo b$v" prints "b\*"
4720 * (and does not try to glob on "*")
4722 o_addblock_duplicate_backslash(output, str, word_len);
4723 /*/ Why can't we do it easier? */
4724 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4725 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4729 if (!*str) /* EOL - do not finalize word */
4731 o_addchr(output, '\0');
4732 debug_print_list("expand_on_ifs", output, n);
4733 n = o_save_ptr(output, n);
4734 str += strspn(str, G.ifs); /* skip ifs chars */
4736 debug_print_list("expand_on_ifs[1]", output, n);
4740 /* Helper to expand $((...)) and heredoc body. These act as if
4741 * they are in double quotes, with the exception that they are not :).
4742 * Just the rules are similar: "expand only $var and `cmd`"
4744 * Returns malloced string.
4745 * As an optimization, we return NULL if expansion is not needed.
4747 #if !ENABLE_HUSH_BASH_COMPAT
4748 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4749 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4750 encode_then_expand_string(str)
4752 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4755 struct in_str input;
4756 o_string dest = NULL_O_STRING;
4758 if (!strchr(str, '$')
4759 && !strchr(str, '\\')
4760 #if ENABLE_HUSH_TICK
4761 && !strchr(str, '`')
4767 /* We need to expand. Example:
4768 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4770 setup_string_in_str(&input, str);
4771 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4772 //TODO: error check (encode_string returns 0 on error)?
4773 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4774 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4775 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4776 o_free_unsafe(&dest);
4780 #if ENABLE_SH_MATH_SUPPORT
4781 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4783 arith_state_t math_state;
4787 math_state.lookupvar = get_local_var_value;
4788 math_state.setvar = set_local_var_from_halves;
4789 //math_state.endofname = endofname;
4790 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4791 res = arith(&math_state, exp_str ? exp_str : arg);
4794 *errmsg_p = math_state.errmsg;
4795 if (math_state.errmsg)
4796 die_if_script(math_state.errmsg);
4801 #if ENABLE_HUSH_BASH_COMPAT
4802 /* ${var/[/]pattern[/repl]} helpers */
4803 static char *strstr_pattern(char *val, const char *pattern, int *size)
4806 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4807 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4814 /* Optimization: if "*pat" did not match the start of "string",
4815 * we know that "tring", "ring" etc will not match too:
4817 if (pattern[0] == '*')
4822 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4824 char *result = NULL;
4825 unsigned res_len = 0;
4826 unsigned repl_len = strlen(repl);
4830 char *s = strstr_pattern(val, pattern, &size);
4834 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4835 memcpy(result + res_len, val, s - val);
4837 strcpy(result + res_len, repl);
4838 res_len += repl_len;
4839 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4845 if (val[0] && result) {
4846 result = xrealloc(result, res_len + strlen(val) + 1);
4847 strcpy(result + res_len, val);
4848 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4850 debug_printf_varexp("result:'%s'\n", result);
4856 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4858 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4860 const char *val = NULL;
4861 char *to_be_freed = NULL;
4866 char exp_save = exp_save; /* for compiler */
4867 char *exp_saveptr; /* points to expansion operator */
4868 char *exp_word = exp_word; /* for compiler */
4871 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4873 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4875 first_char = arg[0] = arg0 & 0x7f;
4878 if (first_char == '#' /* ${#... */
4879 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4881 /* It must be length operator: ${#var} */
4885 /* Maybe handle parameter expansion */
4886 if (exp_saveptr /* if 2nd char is one of expansion operators */
4887 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4889 /* ${?:0}, ${#[:]%0} etc */
4890 exp_saveptr = var + 1;
4892 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4893 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4895 exp_op = exp_save = *exp_saveptr;
4897 exp_word = exp_saveptr + 1;
4898 if (exp_op == ':') {
4899 exp_op = *exp_word++;
4900 //TODO: try ${var:} and ${var:bogus} in non-bash config
4901 if (ENABLE_HUSH_BASH_COMPAT
4902 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4904 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4909 *exp_saveptr = '\0';
4910 } /* else: it's not an expansion op, but bare ${var} */
4913 /* Look up the variable in question */
4914 if (isdigit(var[0])) {
4915 /* parse_dollar should have vetted var for us */
4916 int n = xatoi_positive(var);
4917 if (n < G.global_argc)
4918 val = G.global_argv[n];
4919 /* else val remains NULL: $N with too big N */
4923 val = utoa(G.root_pid);
4925 case '!': /* bg pid */
4926 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4928 case '?': /* exitcode */
4929 val = utoa(G.last_exitcode);
4931 case '#': /* argc */
4932 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4935 val = get_local_var_value(var);
4939 /* Handle any expansions */
4940 if (exp_op == 'L') {
4941 debug_printf_expand("expand: length(%s)=", val);
4942 val = utoa(val ? strlen(val) : 0);
4943 debug_printf_expand("%s\n", val);
4944 } else if (exp_op) {
4945 if (exp_op == '%' || exp_op == '#') {
4946 /* Standard-mandated substring removal ops:
4947 * ${parameter%word} - remove smallest suffix pattern
4948 * ${parameter%%word} - remove largest suffix pattern
4949 * ${parameter#word} - remove smallest prefix pattern
4950 * ${parameter##word} - remove largest prefix pattern
4952 * Word is expanded to produce a glob pattern.
4953 * Then var's value is matched to it and matching part removed.
4955 if (val && val[0]) {
4959 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4960 if (exp_op == *exp_word) /* ## or %% */
4962 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4964 exp_word = exp_exp_word;
4965 /* HACK ALERT. We depend here on the fact that
4966 * G.global_argv and results of utoa and get_local_var_value
4967 * are actually in writable memory:
4968 * scan_and_match momentarily stores NULs there. */
4970 loc = scan_and_match(t, exp_word, scan_flags);
4971 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4972 // exp_op, t, exp_word, loc);
4974 if (loc) { /* match was found */
4975 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4976 val = loc; /* take right part */
4978 val = to_be_freed = xstrndup(val, loc - val); /* left */
4982 #if ENABLE_HUSH_BASH_COMPAT
4983 else if (exp_op == '/' || exp_op == '\\') {
4984 /* It's ${var/[/]pattern[/repl]} thing.
4985 * Note that in encoded form it has TWO parts:
4986 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4987 * and if // is used, it is encoded as \:
4988 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4990 /* Empty variable always gives nothing: */
4991 // "v=''; echo ${v/*/w}" prints "", not "w"
4992 if (val && val[0]) {
4993 /* pattern uses non-standard expansion.
4994 * repl should be unbackslashed and globbed
4995 * by the usual expansion rules:
4997 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4998 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4999 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5000 * v='a bz'; echo ${v/a*z/\z} prints "z"
5001 * (note that a*z _pattern_ is never globbed!)
5003 char *pattern, *repl, *t;
5004 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5006 pattern = xstrdup(exp_word);
5007 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5008 *p++ = SPECIAL_VAR_SYMBOL;
5010 p = strchr(p, SPECIAL_VAR_SYMBOL);
5012 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5013 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5014 /* HACK ALERT. We depend here on the fact that
5015 * G.global_argv and results of utoa and get_local_var_value
5016 * are actually in writable memory:
5017 * replace_pattern momentarily stores NULs there. */
5019 to_be_freed = replace_pattern(t,
5021 (repl ? repl : exp_word),
5023 if (to_be_freed) /* at least one replace happened */
5030 else if (exp_op == ':') {
5031 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5032 /* It's ${var:N[:M]} bashism.
5033 * Note that in encoded form it has TWO parts:
5034 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5039 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5042 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5043 *p++ = SPECIAL_VAR_SYMBOL;
5045 p = strchr(p, SPECIAL_VAR_SYMBOL);
5047 len = expand_and_evaluate_arith(exp_word, &errmsg);
5050 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5051 if (len >= 0) { /* bash compat: len < 0 is illegal */
5052 if (beg < 0) /* bash compat */
5054 debug_printf_varexp("from val:'%s'\n", val);
5055 if (len == 0 || !val || beg >= strlen(val)) {
5059 /* Paranoia. What if user entered 9999999999999
5060 * which fits in arith_t but not int? */
5063 val = to_be_freed = xstrndup(val + beg, len);
5065 debug_printf_varexp("val:'%s'\n", val);
5069 die_if_script("malformed ${%s:...}", var);
5072 } else { /* one of "-=+?" */
5073 /* Standard-mandated substitution ops:
5074 * ${var?word} - indicate error if unset
5075 * If var is unset, word (or a message indicating it is unset
5076 * if word is null) is written to standard error
5077 * and the shell exits with a non-zero exit status.
5078 * Otherwise, the value of var is substituted.
5079 * ${var-word} - use default value
5080 * If var is unset, word is substituted.
5081 * ${var=word} - assign and use default value
5082 * If var is unset, word is assigned to var.
5083 * In all cases, final value of var is substituted.
5084 * ${var+word} - use alternative value
5085 * If var is unset, null is substituted.
5086 * Otherwise, word is substituted.
5088 * Word is subjected to tilde expansion, parameter expansion,
5089 * command substitution, and arithmetic expansion.
5090 * If word is not needed, it is not expanded.
5092 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5093 * but also treat null var as if it is unset.
5095 int use_word = (!val || ((exp_save == ':') && !val[0]));
5097 use_word = !use_word;
5098 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5099 (exp_save == ':') ? "true" : "false", use_word);
5101 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5103 exp_word = to_be_freed;
5104 if (exp_op == '?') {
5105 /* mimic bash message */
5106 die_if_script("%s: %s",
5108 exp_word[0] ? exp_word : "parameter null or not set"
5110 //TODO: how interactive bash aborts expansion mid-command?
5115 if (exp_op == '=') {
5116 /* ${var=[word]} or ${var:=[word]} */
5117 if (isdigit(var[0]) || var[0] == '#') {
5118 /* mimic bash message */
5119 die_if_script("$%s: cannot assign in this way", var);
5122 char *new_var = xasprintf("%s=%s", var, val);
5123 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5127 } /* one of "-=+?" */
5129 *exp_saveptr = exp_save;
5135 *to_be_freed_pp = to_be_freed;
5139 /* Expand all variable references in given string, adding words to list[]
5140 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5141 * to be filled). This routine is extremely tricky: has to deal with
5142 * variables/parameters with whitespace, $* and $@, and constructs like
5143 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5144 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5146 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5147 * expansion of right-hand side of assignment == 1-element expand.
5149 char cant_be_null = 0; /* only bit 0x80 matters */
5152 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5153 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5154 debug_print_list("expand_vars_to_list", output, n);
5155 n = o_save_ptr(output, n);
5156 debug_print_list("expand_vars_to_list[0]", output, n);
5158 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5160 char *to_be_freed = NULL;
5161 const char *val = NULL;
5162 #if ENABLE_HUSH_TICK
5163 o_string subst_result = NULL_O_STRING;
5165 #if ENABLE_SH_MATH_SUPPORT
5166 char arith_buf[sizeof(arith_t)*3 + 2];
5168 o_addblock(output, arg, p - arg);
5169 debug_print_list("expand_vars_to_list[1]", output, n);
5171 p = strchr(p, SPECIAL_VAR_SYMBOL);
5173 /* Fetch special var name (if it is indeed one of them)
5174 * and quote bit, force the bit on if singleword expansion -
5175 * important for not getting v=$@ expand to many words. */
5176 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5178 /* Is this variable quoted and thus expansion can't be null?
5179 * "$@" is special. Even if quoted, it can still
5180 * expand to nothing (not even an empty string),
5181 * thus it is excluded. */
5182 if ((first_ch & 0x7f) != '@')
5183 cant_be_null |= first_ch;
5185 switch (first_ch & 0x7f) {
5186 /* Highest bit in first_ch indicates that var is double-quoted */
5190 if (!G.global_argv[1])
5193 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5194 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5195 while (G.global_argv[i]) {
5196 n = expand_on_ifs(output, n, G.global_argv[i]);
5197 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5198 if (G.global_argv[i++][0] && G.global_argv[i]) {
5199 /* this argv[] is not empty and not last:
5200 * put terminating NUL, start new word */
5201 o_addchr(output, '\0');
5202 debug_print_list("expand_vars_to_list[2]", output, n);
5203 n = o_save_ptr(output, n);
5204 debug_print_list("expand_vars_to_list[3]", output, n);
5208 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5209 * and in this case should treat it like '$*' - see 'else...' below */
5210 if (first_ch == ('@'|0x80) /* quoted $@ */
5211 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5214 o_addQstr(output, G.global_argv[i]);
5215 if (++i >= G.global_argc)
5217 o_addchr(output, '\0');
5218 debug_print_list("expand_vars_to_list[4]", output, n);
5219 n = o_save_ptr(output, n);
5221 } else { /* quoted $* (or v="$@" case): add as one word */
5223 o_addQstr(output, G.global_argv[i]);
5224 if (!G.global_argv[++i])
5227 o_addchr(output, G.ifs[0]);
5232 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5233 /* "Empty variable", used to make "" etc to not disappear */
5235 cant_be_null = 0x80;
5237 #if ENABLE_HUSH_TICK
5238 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5239 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5241 /* Can't just stuff it into output o_string,
5242 * expanded result may need to be globbed
5243 * and $IFS-splitted */
5244 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5245 G.last_exitcode = process_command_subs(&subst_result, arg);
5246 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5247 val = subst_result.data;
5250 #if ENABLE_SH_MATH_SUPPORT
5251 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5254 arg++; /* skip '+' */
5255 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5256 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5257 res = expand_and_evaluate_arith(arg, NULL);
5258 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5259 sprintf(arith_buf, ARITH_FMT, res);
5265 val = expand_one_var(&to_be_freed, arg, &p);
5266 IF_HUSH_TICK(store_val:)
5267 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5268 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5269 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5270 if (val && val[0]) {
5271 n = expand_on_ifs(output, n, val);
5274 } else { /* quoted $VAR, val will be appended below */
5275 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5276 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5280 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5282 if (val && val[0]) {
5283 o_addQstr(output, val);
5287 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5288 * Do the check to avoid writing to a const string. */
5289 if (*p != SPECIAL_VAR_SYMBOL)
5290 *p = SPECIAL_VAR_SYMBOL;
5292 #if ENABLE_HUSH_TICK
5293 o_free(&subst_result);
5296 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5299 debug_print_list("expand_vars_to_list[a]", output, n);
5300 /* this part is literal, and it was already pre-quoted
5301 * if needed (much earlier), do not use o_addQstr here! */
5302 o_addstr_with_NUL(output, arg);
5303 debug_print_list("expand_vars_to_list[b]", output, n);
5304 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5305 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5308 /* allow to reuse list[n] later without re-growth */
5309 output->has_empty_slot = 1;
5311 o_addchr(output, '\0');
5317 static char **expand_variables(char **argv, unsigned expflags)
5321 o_string output = NULL_O_STRING;
5323 output.o_expflags = expflags;
5327 n = expand_vars_to_list(&output, n, *argv);
5330 debug_print_list("expand_variables", &output, n);
5332 /* output.data (malloced in one block) gets returned in "list" */
5333 list = o_finalize_list(&output, n);
5334 debug_print_strings("expand_variables[1]", list);
5338 static char **expand_strvec_to_strvec(char **argv)
5340 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5343 #if ENABLE_HUSH_BASH_COMPAT
5344 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5346 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5350 /* Used for expansion of right hand of assignments,
5351 * $((...)), heredocs, variable espansion parts.
5353 * NB: should NOT do globbing!
5354 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5356 static char *expand_string_to_string(const char *str, int do_unbackslash)
5358 #if !ENABLE_HUSH_BASH_COMPAT
5359 const int do_unbackslash = 1;
5361 char *argv[2], **list;
5363 debug_printf_expand("string_to_string<='%s'\n", str);
5364 /* This is generally an optimization, but it also
5365 * handles "", which otherwise trips over !list[0] check below.
5366 * (is this ever happens that we actually get str="" here?)
5368 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5369 //TODO: Can use on strings with \ too, just unbackslash() them?
5370 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5371 return xstrdup(str);
5374 argv[0] = (char*)str;
5376 list = expand_variables(argv, do_unbackslash
5377 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5378 : EXP_FLAG_SINGLEWORD
5381 if (!list[0] || list[1])
5382 bb_error_msg_and_die("BUG in varexp2");
5383 /* actually, just move string 2*sizeof(char*) bytes back */
5384 overlapping_strcpy((char*)list, list[0]);
5386 unbackslash((char*)list);
5387 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5391 /* Used for "eval" builtin */
5392 static char* expand_strvec_to_string(char **argv)
5396 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5397 /* Convert all NULs to spaces */
5402 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5403 bb_error_msg_and_die("BUG in varexp3");
5404 /* bash uses ' ' regardless of $IFS contents */
5409 overlapping_strcpy((char*)list, list[0]);
5410 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5414 static char **expand_assignments(char **argv, int count)
5419 G.expanded_assignments = p = NULL;
5420 /* Expand assignments into one string each */
5421 for (i = 0; i < count; i++) {
5422 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5424 G.expanded_assignments = NULL;
5431 void re_execute_shell(char ***to_free, const char *s,
5432 char *g_argv0, char **g_argv,
5433 char **builtin_argv) NORETURN;
5435 static void switch_off_special_sigs(unsigned mask)
5438 while ((mask >>= 1) != 0) {
5443 if (G.traps[sig] && !G.traps[sig][0])
5444 /* trap is '', has to remain SIG_IGN */
5447 G.traps[sig] = NULL;
5449 /* We are here only if no trap or trap was not '' */
5450 signal(sig, SIG_DFL);
5454 static void reset_traps_to_defaults(void)
5456 /* This function is always called in a child shell
5457 * after fork (not vfork, NOMMU doesn't use this function).
5462 /* Child shells are not interactive.
5463 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5464 * Testcase: (while :; do :; done) + ^Z should background.
5465 * Same goes for SIGTERM, SIGHUP, SIGINT.
5467 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5468 if (!G.traps && !mask)
5469 return; /* already no traps and no special sigs */
5471 /* Switch off special sigs */
5472 switch_off_special_sigs(mask);
5474 G_fatal_sig_mask = 0;
5476 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5477 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5478 * remain set in G.special_sig_mask */
5483 /* Reset all sigs to default except ones with empty traps */
5484 for (sig = 0; sig < NSIG; sig++) {
5486 continue; /* no trap: nothing to do */
5487 if (!G.traps[sig][0])
5488 continue; /* empty trap: has to remain SIG_IGN */
5489 /* sig has non-empty trap, reset it: */
5491 G.traps[sig] = NULL;
5492 /* There is no signal for trap 0 (EXIT) */
5495 signal(sig, pick_sighandler(sig));
5501 static void re_execute_shell(char ***to_free, const char *s,
5502 char *g_argv0, char **g_argv,
5503 char **builtin_argv) NORETURN;
5504 static void re_execute_shell(char ***to_free, const char *s,
5505 char *g_argv0, char **g_argv,
5506 char **builtin_argv)
5508 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5509 /* delims + 2 * (number of bytes in printed hex numbers) */
5510 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5511 char *heredoc_argv[4];
5512 struct variable *cur;
5513 # if ENABLE_HUSH_FUNCTIONS
5514 struct function *funcp;
5518 unsigned long long empty_trap_mask;
5520 if (!g_argv0) { /* heredoc */
5521 argv = heredoc_argv;
5522 argv[0] = (char *) G.argv0_for_re_execing;
5523 argv[1] = (char *) "-<";
5524 argv[2] = (char *) s;
5526 pp = &argv[3]; /* used as pointer to empty environment */
5532 if (pp) while (*pp++)
5535 empty_trap_mask = 0;
5538 for (sig = 1; sig < NSIG; sig++) {
5539 if (G.traps[sig] && !G.traps[sig][0])
5540 empty_trap_mask |= 1LL << sig;
5544 sprintf(param_buf, NOMMU_HACK_FMT
5545 , (unsigned) G.root_pid
5546 , (unsigned) G.root_ppid
5547 , (unsigned) G.last_bg_pid
5548 , (unsigned) G.last_exitcode
5551 IF_HUSH_LOOPS(, G.depth_of_loop)
5553 # undef NOMMU_HACK_FMT
5554 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5555 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5558 for (cur = G.top_var; cur; cur = cur->next) {
5559 if (!cur->flg_export || cur->flg_read_only)
5562 # if ENABLE_HUSH_FUNCTIONS
5563 for (funcp = G.top_func; funcp; funcp = funcp->next)
5569 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5570 *pp++ = (char *) G.argv0_for_re_execing;
5572 for (cur = G.top_var; cur; cur = cur->next) {
5573 if (strcmp(cur->varstr, hush_version_str) == 0)
5575 if (cur->flg_read_only) {
5576 *pp++ = (char *) "-R";
5577 *pp++ = cur->varstr;
5578 } else if (!cur->flg_export) {
5579 *pp++ = (char *) "-V";
5580 *pp++ = cur->varstr;
5583 # if ENABLE_HUSH_FUNCTIONS
5584 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5585 *pp++ = (char *) "-F";
5586 *pp++ = funcp->name;
5587 *pp++ = funcp->body_as_string;
5590 /* We can pass activated traps here. Say, -Tnn:trap_string
5592 * However, POSIX says that subshells reset signals with traps
5594 * I tested bash-3.2 and it not only does that with true subshells
5595 * of the form ( list ), but with any forked children shells.
5596 * I set trap "echo W" WINCH; and then tried:
5598 * { echo 1; sleep 20; echo 2; } &
5599 * while true; do echo 1; sleep 20; echo 2; break; done &
5600 * true | { echo 1; sleep 20; echo 2; } | cat
5602 * In all these cases sending SIGWINCH to the child shell
5603 * did not run the trap. If I add trap "echo V" WINCH;
5604 * _inside_ group (just before echo 1), it works.
5606 * I conclude it means we don't need to pass active traps here.
5607 * Even if we would use signal handlers instead of signal masking
5608 * in order to implement trap handling,
5609 * exec syscall below resets signals to SIG_DFL for us.
5611 *pp++ = (char *) "-c";
5614 while (*++builtin_argv)
5615 *pp++ = *builtin_argv;
5616 *pp++ = (char *) "";
5621 /* *pp = NULL; - is already there */
5625 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5626 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5627 execve(bb_busybox_exec_path, argv, pp);
5628 /* Fallback. Useful for init=/bin/hush usage etc */
5629 if (argv[0][0] == '/')
5630 execve(argv[0], argv, pp);
5631 xfunc_error_retval = 127;
5632 bb_error_msg_and_die("can't re-execute the shell");
5634 #endif /* !BB_MMU */
5637 static int run_and_free_list(struct pipe *pi);
5639 /* Executing from string: eval, sh -c '...'
5640 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5641 * end_trigger controls how often we stop parsing
5642 * NUL: parse all, execute, return
5643 * ';': parse till ';' or newline, execute, repeat till EOF
5645 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5647 /* Why we need empty flag?
5648 * An obscure corner case "false; ``; echo $?":
5649 * empty command in `` should still set $? to 0.
5650 * But we can't just set $? to 0 at the start,
5651 * this breaks "false; echo `echo $?`" case.
5655 struct pipe *pipe_list;
5657 #if ENABLE_HUSH_INTERACTIVE
5658 if (end_trigger == ';')
5659 inp->promptmode = 0; /* PS1 */
5661 pipe_list = parse_stream(NULL, inp, end_trigger);
5662 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5663 /* If we are in "big" script
5664 * (not in `cmd` or something similar)...
5666 if (pipe_list == ERR_PTR && end_trigger == ';') {
5667 /* Discard cached input (rest of line) */
5668 int ch = inp->last_char;
5669 while (ch != EOF && ch != '\n') {
5670 //bb_error_msg("Discarded:'%c'", ch);
5675 /* This stream isn't empty */
5679 if (!pipe_list && empty)
5680 G.last_exitcode = 0;
5683 debug_print_tree(pipe_list, 0);
5684 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5685 run_and_free_list(pipe_list);
5687 #if ENABLE_HUSH_FUNCTIONS
5688 if (G.flag_return_in_progress == 1)
5694 static void parse_and_run_string(const char *s)
5696 struct in_str input;
5697 setup_string_in_str(&input, s);
5698 parse_and_run_stream(&input, '\0');
5701 static void parse_and_run_file(FILE *f)
5703 struct in_str input;
5704 setup_file_in_str(&input, f);
5705 parse_and_run_stream(&input, ';');
5708 #if ENABLE_HUSH_TICK
5709 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5714 char **to_free = NULL;
5718 pid = BB_MMU ? xfork() : xvfork();
5719 if (pid == 0) { /* child */
5720 disable_restore_tty_pgrp_on_exit();
5721 /* Process substitution is not considered to be usual
5722 * 'command execution'.
5723 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5730 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5731 close(channel[0]); /* NB: close _first_, then move fd! */
5732 xmove_fd(channel[1], 1);
5733 /* Prevent it from trying to handle ctrl-z etc */
5734 IF_HUSH_JOB(G.run_list_level = 1;)
5735 /* Awful hack for `trap` or $(trap).
5737 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5738 * contains an example where "trap" is executed in a subshell:
5740 * save_traps=$(trap)
5742 * eval "$save_traps"
5744 * Standard does not say that "trap" in subshell shall print
5745 * parent shell's traps. It only says that its output
5746 * must have suitable form, but then, in the above example
5747 * (which is not supposed to be normative), it implies that.
5749 * bash (and probably other shell) does implement it
5750 * (traps are reset to defaults, but "trap" still shows them),
5751 * but as a result, "trap" logic is hopelessly messed up:
5754 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5755 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5756 * # true | trap <--- trap is in subshell - no output (ditto)
5757 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5758 * trap -- 'echo Ho' SIGWINCH
5759 * # echo `(trap)` <--- in subshell in subshell - output
5760 * trap -- 'echo Ho' SIGWINCH
5761 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5762 * trap -- 'echo Ho' SIGWINCH
5764 * The rules when to forget and when to not forget traps
5765 * get really complex and nonsensical.
5767 * Our solution: ONLY bare $(trap) or `trap` is special.
5769 s = skip_whitespace(s);
5770 if (strncmp(s, "trap", 4) == 0
5771 && skip_whitespace(s + 4)[0] == '\0'
5773 static const char *const argv[] = { NULL, NULL };
5774 builtin_trap((char**)argv);
5775 exit(0); /* not _exit() - we need to fflush */
5778 reset_traps_to_defaults();
5779 parse_and_run_string(s);
5780 _exit(G.last_exitcode);
5782 /* We re-execute after vfork on NOMMU. This makes this script safe:
5783 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5784 * huge=`cat BIG` # was blocking here forever
5787 re_execute_shell(&to_free,
5797 # if ENABLE_HUSH_FAST
5799 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5800 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5801 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5803 enable_restore_tty_pgrp_on_exit();
5808 close_on_exec_on(channel[0]);
5809 return xfdopen_for_read(channel[0]);
5812 /* Return code is exit status of the process that is run. */
5813 static int process_command_subs(o_string *dest, const char *s)
5816 struct in_str pipe_str;
5818 int status, ch, eol_cnt;
5820 fp = generate_stream_from_string(s, &pid);
5822 /* Now send results of command back into original context */
5823 setup_file_in_str(&pipe_str, fp);
5825 while ((ch = i_getch(&pipe_str)) != EOF) {
5831 o_addchr(dest, '\n');
5834 o_addQchr(dest, ch);
5837 debug_printf("done reading from `cmd` pipe, closing it\n");
5839 /* We need to extract exitcode. Test case
5840 * "true; echo `sleep 1; false` $?"
5842 safe_waitpid(pid, &status, 0);
5843 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5844 return WEXITSTATUS(status);
5846 #endif /* ENABLE_HUSH_TICK */
5849 static void setup_heredoc(struct redir_struct *redir)
5851 struct fd_pair pair;
5854 /* the _body_ of heredoc (misleading field name) */
5855 const char *heredoc = redir->rd_filename;
5862 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5863 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5867 len = strlen(heredoc);
5869 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5871 xmove_fd(pair.rd, redir->rd_fd);
5873 /* Try writing without forking. Newer kernels have
5874 * dynamically growing pipes. Must use non-blocking write! */
5877 written = write(pair.wr, heredoc, len);
5888 ndelay_off(pair.wr);
5890 /* Okay, pipe buffer was not big enough */
5891 /* Note: we must not create a stray child (bastard? :)
5892 * for the unsuspecting parent process. Child creates a grandchild
5893 * and exits before parent execs the process which consumes heredoc
5894 * (that exec happens after we return from this function) */
5901 disable_restore_tty_pgrp_on_exit();
5902 pid = BB_MMU ? xfork() : xvfork();
5906 close(redir->rd_fd); /* read side of the pipe */
5908 full_write(pair.wr, heredoc, len); /* may loop or block */
5911 /* Delegate blocking writes to another process */
5912 xmove_fd(pair.wr, STDOUT_FILENO);
5913 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5917 #if ENABLE_HUSH_FAST
5919 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5921 enable_restore_tty_pgrp_on_exit();
5927 wait(NULL); /* wait till child has died */
5930 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5931 * and stderr if they are redirected. */
5932 static int setup_redirects(struct command *prog, int squirrel[])
5935 struct redir_struct *redir;
5937 for (redir = prog->redirects; redir; redir = redir->next) {
5938 if (redir->rd_type == REDIRECT_HEREDOC2) {
5939 /* rd_fd<<HERE case */
5940 if (squirrel && redir->rd_fd < 3
5941 && squirrel[redir->rd_fd] < 0
5943 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5945 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5947 debug_printf_parse("set heredoc '%s'\n",
5948 redir->rd_filename);
5949 setup_heredoc(redir);
5953 if (redir->rd_dup == REDIRFD_TO_FILE) {
5954 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5956 if (redir->rd_filename == NULL) {
5957 /* Something went wrong in the parse.
5958 * Pretend it didn't happen */
5959 bb_error_msg("bug in redirect parse");
5962 mode = redir_table[redir->rd_type].mode;
5963 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5964 openfd = open_or_warn(p, mode);
5967 /* this could get lost if stderr has been redirected, but
5968 * bash and ash both lose it as well (though zsh doesn't!) */
5969 //what the above comment tries to say?
5973 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5974 openfd = redir->rd_dup;
5977 if (openfd != redir->rd_fd) {
5978 if (squirrel && redir->rd_fd < 3
5979 && squirrel[redir->rd_fd] < 0
5981 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5983 if (openfd == REDIRFD_CLOSE) {
5984 /* "n>-" means "close me" */
5985 close(redir->rd_fd);
5987 xdup2(openfd, redir->rd_fd);
5988 if (redir->rd_dup == REDIRFD_TO_FILE)
5996 static void restore_redirects(int squirrel[])
5999 for (i = 0; i < 3; i++) {
6002 /* We simply die on error */
6008 static char *find_in_path(const char *arg)
6011 const char *PATH = get_local_var_value("PATH");
6017 const char *end = strchrnul(PATH, ':');
6018 int sz = end - PATH; /* must be int! */
6022 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6024 /* We have xxx::yyyy in $PATH,
6025 * it means "use current dir" */
6028 if (access(ret, F_OK) == 0)
6041 static const struct built_in_command *find_builtin_helper(const char *name,
6042 const struct built_in_command *x,
6043 const struct built_in_command *end)
6046 if (strcmp(name, x->b_cmd) != 0) {
6050 debug_printf_exec("found builtin '%s'\n", name);
6055 static const struct built_in_command *find_builtin1(const char *name)
6057 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6059 static const struct built_in_command *find_builtin(const char *name)
6061 const struct built_in_command *x = find_builtin1(name);
6064 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6067 #if ENABLE_HUSH_FUNCTIONS
6068 static struct function **find_function_slot(const char *name)
6070 struct function **funcpp = &G.top_func;
6072 if (strcmp(name, (*funcpp)->name) == 0) {
6075 funcpp = &(*funcpp)->next;
6080 static const struct function *find_function(const char *name)
6082 const struct function *funcp = *find_function_slot(name);
6084 debug_printf_exec("found function '%s'\n", name);
6088 /* Note: takes ownership on name ptr */
6089 static struct function *new_function(char *name)
6091 struct function **funcpp = find_function_slot(name);
6092 struct function *funcp = *funcpp;
6094 if (funcp != NULL) {
6095 struct command *cmd = funcp->parent_cmd;
6096 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6098 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6100 /* Note: if !funcp->body, do not free body_as_string!
6101 * This is a special case of "-F name body" function:
6102 * body_as_string was not malloced! */
6104 free_pipe_list(funcp->body);
6106 free(funcp->body_as_string);
6110 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6111 cmd->argv[0] = funcp->name;
6112 cmd->group = funcp->body;
6114 cmd->group_as_string = funcp->body_as_string;
6118 debug_printf_exec("remembering new function '%s'\n", name);
6119 funcp = *funcpp = xzalloc(sizeof(*funcp));
6120 /*funcp->next = NULL;*/
6127 static void unset_func(const char *name)
6129 struct function **funcpp = find_function_slot(name);
6130 struct function *funcp = *funcpp;
6132 if (funcp != NULL) {
6133 debug_printf_exec("freeing function '%s'\n", funcp->name);
6134 *funcpp = funcp->next;
6135 /* funcp is unlinked now, deleting it.
6136 * Note: if !funcp->body, the function was created by
6137 * "-F name body", do not free ->body_as_string
6138 * and ->name as they were not malloced. */
6140 free_pipe_list(funcp->body);
6143 free(funcp->body_as_string);
6151 #define exec_function(to_free, funcp, argv) \
6152 exec_function(funcp, argv)
6154 static void exec_function(char ***to_free,
6155 const struct function *funcp,
6156 char **argv) NORETURN;
6157 static void exec_function(char ***to_free,
6158 const struct function *funcp,
6164 argv[0] = G.global_argv[0];
6165 G.global_argv = argv;
6169 /* On MMU, funcp->body is always non-NULL */
6170 n = run_list(funcp->body);
6174 re_execute_shell(to_free,
6175 funcp->body_as_string,
6182 static int run_function(const struct function *funcp, char **argv)
6188 save_and_replace_G_args(&sv, argv);
6190 /* "we are in function, ok to use return" */
6191 sv_flg = G.flag_return_in_progress;
6192 G.flag_return_in_progress = -1;
6193 # if ENABLE_HUSH_LOCAL
6194 G.func_nest_level++;
6197 /* On MMU, funcp->body is always non-NULL */
6200 /* Function defined by -F */
6201 parse_and_run_string(funcp->body_as_string);
6202 rc = G.last_exitcode;
6206 rc = run_list(funcp->body);
6209 # if ENABLE_HUSH_LOCAL
6211 struct variable *var;
6212 struct variable **var_pp;
6214 var_pp = &G.top_var;
6215 while ((var = *var_pp) != NULL) {
6216 if (var->func_nest_level < G.func_nest_level) {
6217 var_pp = &var->next;
6221 if (var->flg_export)
6222 bb_unsetenv(var->varstr);
6223 /* Remove from global list */
6224 *var_pp = var->next;
6230 G.func_nest_level--;
6233 G.flag_return_in_progress = sv_flg;
6235 restore_G_args(&sv, argv);
6239 #endif /* ENABLE_HUSH_FUNCTIONS */
6243 #define exec_builtin(to_free, x, argv) \
6244 exec_builtin(x, argv)
6246 #define exec_builtin(to_free, x, argv) \
6247 exec_builtin(to_free, argv)
6249 static void exec_builtin(char ***to_free,
6250 const struct built_in_command *x,
6251 char **argv) NORETURN;
6252 static void exec_builtin(char ***to_free,
6253 const struct built_in_command *x,
6259 rcode = x->b_function(argv);
6264 /* On NOMMU, we must never block!
6265 * Example: { sleep 99 | read line; } & echo Ok
6267 re_execute_shell(to_free,
6276 static void execvp_or_die(char **argv) NORETURN;
6277 static void execvp_or_die(char **argv)
6279 debug_printf_exec("execing '%s'\n", argv[0]);
6280 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6281 execvp(argv[0], argv);
6282 bb_perror_msg("can't execute '%s'", argv[0]);
6283 _exit(127); /* bash compat */
6286 #if ENABLE_HUSH_MODE_X
6287 static void dump_cmd_in_x_mode(char **argv)
6289 if (G_x_mode && argv) {
6290 /* We want to output the line in one write op */
6298 len += strlen(argv[n++]) + 1;
6304 p += sprintf(p, " %s", argv[n++]);
6312 # define dump_cmd_in_x_mode(argv) ((void)0)
6316 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6317 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6318 #define pseudo_exec(nommu_save, command, argv_expanded) \
6319 pseudo_exec(command, argv_expanded)
6322 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6324 * Don't exit() here. If you don't exec, use _exit instead.
6325 * The at_exit handlers apparently confuse the calling process,
6326 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6327 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6328 char **argv, int assignment_cnt,
6329 char **argv_expanded) NORETURN;
6330 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6331 char **argv, int assignment_cnt,
6332 char **argv_expanded)
6336 new_env = expand_assignments(argv, assignment_cnt);
6337 dump_cmd_in_x_mode(new_env);
6339 if (!argv[assignment_cnt]) {
6340 /* Case when we are here: ... | var=val | ...
6341 * (note that we do not exit early, i.e., do not optimize out
6342 * expand_assignments(): think about ... | var=`sleep 1` | ...
6344 free_strings(new_env);
6345 _exit(EXIT_SUCCESS);
6349 set_vars_and_save_old(new_env);
6350 free(new_env); /* optional */
6351 /* we can also destroy set_vars_and_save_old's return value,
6354 nommu_save->new_env = new_env;
6355 nommu_save->old_vars = set_vars_and_save_old(new_env);
6358 if (argv_expanded) {
6359 argv = argv_expanded;
6361 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6363 nommu_save->argv = argv;
6366 dump_cmd_in_x_mode(argv);
6368 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6369 if (strchr(argv[0], '/') != NULL)
6373 /* Check if the command matches any of the builtins.
6374 * Depending on context, this might be redundant. But it's
6375 * easier to waste a few CPU cycles than it is to figure out
6376 * if this is one of those cases.
6379 /* On NOMMU, it is more expensive to re-execute shell
6380 * just in order to run echo or test builtin.
6381 * It's better to skip it here and run corresponding
6382 * non-builtin later. */
6383 const struct built_in_command *x;
6384 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6386 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6389 #if ENABLE_HUSH_FUNCTIONS
6390 /* Check if the command matches any functions */
6392 const struct function *funcp = find_function(argv[0]);
6394 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6399 #if ENABLE_FEATURE_SH_STANDALONE
6400 /* Check if the command matches any busybox applets */
6402 int a = find_applet_by_name(argv[0]);
6404 # if BB_MMU /* see above why on NOMMU it is not allowed */
6405 if (APPLET_IS_NOEXEC(a)) {
6406 debug_printf_exec("running applet '%s'\n", argv[0]);
6407 run_applet_no_and_exit(a, argv);
6410 /* Re-exec ourselves */
6411 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6412 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6413 execv(bb_busybox_exec_path, argv);
6414 /* If they called chroot or otherwise made the binary no longer
6415 * executable, fall through */
6420 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6423 execvp_or_die(argv);
6426 /* Called after [v]fork() in run_pipe
6428 static void pseudo_exec(nommu_save_t *nommu_save,
6429 struct command *command,
6430 char **argv_expanded) NORETURN;
6431 static void pseudo_exec(nommu_save_t *nommu_save,
6432 struct command *command,
6433 char **argv_expanded)
6435 if (command->argv) {
6436 pseudo_exec_argv(nommu_save, command->argv,
6437 command->assignment_cnt, argv_expanded);
6440 if (command->group) {
6441 /* Cases when we are here:
6444 * ... | ( list ) | ...
6445 * ... | { list } | ...
6449 debug_printf_exec("pseudo_exec: run_list\n");
6450 reset_traps_to_defaults();
6451 rcode = run_list(command->group);
6452 /* OK to leak memory by not calling free_pipe_list,
6453 * since this process is about to exit */
6456 re_execute_shell(&nommu_save->argv_from_re_execing,
6457 command->group_as_string,
6464 /* Case when we are here: ... | >file */
6465 debug_printf_exec("pseudo_exec'ed null command\n");
6466 _exit(EXIT_SUCCESS);
6470 static const char *get_cmdtext(struct pipe *pi)
6476 /* This is subtle. ->cmdtext is created only on first backgrounding.
6477 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6478 * On subsequent bg argv is trashed, but we won't use it */
6481 argv = pi->cmds[0].argv;
6482 if (!argv || !argv[0]) {
6483 pi->cmdtext = xzalloc(1);
6489 len += strlen(*argv) + 1;
6493 argv = pi->cmds[0].argv;
6495 len = strlen(*argv);
6496 memcpy(p, *argv, len);
6504 static void insert_bg_job(struct pipe *pi)
6506 struct pipe *job, **jobp;
6509 /* Linear search for the ID of the job to use */
6511 for (job = G.job_list; job; job = job->next)
6512 if (job->jobid >= pi->jobid)
6513 pi->jobid = job->jobid + 1;
6515 /* Add job to the list of running jobs */
6517 while ((job = *jobp) != NULL)
6519 job = *jobp = xmalloc(sizeof(*job));
6521 *job = *pi; /* physical copy */
6523 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6524 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6525 for (i = 0; i < pi->num_cmds; i++) {
6526 job->cmds[i].pid = pi->cmds[i].pid;
6527 /* all other fields are not used and stay zero */
6529 job->cmdtext = xstrdup(get_cmdtext(pi));
6531 if (G_interactive_fd)
6532 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6533 G.last_jobid = job->jobid;
6536 static void remove_bg_job(struct pipe *pi)
6538 struct pipe *prev_pipe;
6540 if (pi == G.job_list) {
6541 G.job_list = pi->next;
6543 prev_pipe = G.job_list;
6544 while (prev_pipe->next != pi)
6545 prev_pipe = prev_pipe->next;
6546 prev_pipe->next = pi->next;
6549 G.last_jobid = G.job_list->jobid;
6554 /* Remove a backgrounded job */
6555 static void delete_finished_bg_job(struct pipe *pi)
6562 /* Check to see if any processes have exited -- if they
6563 * have, figure out why and see if a job has completed */
6564 static int checkjobs(struct pipe *fg_pipe)
6574 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6576 attributes = WUNTRACED;
6577 if (fg_pipe == NULL)
6578 attributes |= WNOHANG;
6581 #if ENABLE_HUSH_FAST
6582 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6583 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6584 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6585 /* There was neither fork nor SIGCHLD since last waitpid */
6586 /* Avoid doing waitpid syscall if possible */
6587 if (!G.we_have_children) {
6591 if (fg_pipe == NULL) { /* is WNOHANG set? */
6592 /* We have children, but they did not exit
6593 * or stop yet (we saw no SIGCHLD) */
6596 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6600 /* Do we do this right?
6601 * bash-3.00# sleep 20 | false
6603 * [3]+ Stopped sleep 20 | false
6604 * bash-3.00# echo $?
6605 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6606 * [hush 1.14.0: yes we do it right]
6613 #if ENABLE_HUSH_FAST
6614 i = G.count_SIGCHLD;
6616 childpid = waitpid(-1, &status, attributes);
6617 if (childpid <= 0) {
6618 if (childpid && errno != ECHILD)
6619 bb_perror_msg("waitpid");
6620 #if ENABLE_HUSH_FAST
6621 else { /* Until next SIGCHLD, waitpid's are useless */
6622 G.we_have_children = (childpid == 0);
6623 G.handled_SIGCHLD = i;
6624 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6629 dead = WIFEXITED(status) || WIFSIGNALED(status);
6632 if (WIFSTOPPED(status))
6633 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6634 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6635 if (WIFSIGNALED(status))
6636 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6637 childpid, WTERMSIG(status), WEXITSTATUS(status));
6638 if (WIFEXITED(status))
6639 debug_printf_jobs("pid %d exited, exitcode %d\n",
6640 childpid, WEXITSTATUS(status));
6642 /* Were we asked to wait for fg pipe? */
6644 i = fg_pipe->num_cmds;
6646 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6647 if (fg_pipe->cmds[i].pid != childpid)
6651 fg_pipe->cmds[i].pid = 0;
6652 fg_pipe->alive_cmds--;
6653 ex = WEXITSTATUS(status);
6654 /* bash prints killer signal's name for *last*
6655 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6656 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6658 if (WIFSIGNALED(status)) {
6659 int sig = WTERMSIG(status);
6660 if (i == fg_pipe->num_cmds-1)
6661 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6662 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6663 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6664 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6665 * Maybe we need to use sig | 128? */
6668 fg_pipe->cmds[i].cmd_exitcode = ex;
6670 fg_pipe->cmds[i].is_stopped = 1;
6671 fg_pipe->stopped_cmds++;
6673 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6674 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6675 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6676 /* All processes in fg pipe have exited or stopped */
6677 i = fg_pipe->num_cmds;
6679 rcode = fg_pipe->cmds[i].cmd_exitcode;
6680 /* usually last process gives overall exitstatus,
6681 * but with "set -o pipefail", last *failed* process does */
6682 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6685 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6686 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6687 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6688 * and "killall -STOP cat" */
6689 if (G_interactive_fd) {
6691 if (fg_pipe->alive_cmds != 0)
6692 insert_bg_job(fg_pipe);
6696 if (fg_pipe->alive_cmds == 0)
6699 /* There are still running processes in the fg pipe */
6700 goto wait_more; /* do waitpid again */
6702 /* it wasnt fg_pipe, look for process in bg pipes */
6706 /* We asked to wait for bg or orphaned children */
6707 /* No need to remember exitcode in this case */
6708 for (pi = G.job_list; pi; pi = pi->next) {
6709 for (i = 0; i < pi->num_cmds; i++) {
6710 if (pi->cmds[i].pid == childpid)
6711 goto found_pi_and_prognum;
6714 /* Happens when shell is used as init process (init=/bin/sh) */
6715 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6716 continue; /* do waitpid again */
6718 found_pi_and_prognum:
6721 pi->cmds[i].pid = 0;
6723 if (!pi->alive_cmds) {
6724 if (G_interactive_fd)
6725 printf(JOB_STATUS_FORMAT, pi->jobid,
6726 "Done", pi->cmdtext);
6727 delete_finished_bg_job(pi);
6731 pi->cmds[i].is_stopped = 1;
6735 } /* while (waitpid succeeds)... */
6741 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6744 int rcode = checkjobs(fg_pipe);
6745 if (G_saved_tty_pgrp) {
6746 /* Job finished, move the shell to the foreground */
6747 p = getpgrp(); /* our process group id */
6748 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6749 tcsetpgrp(G_interactive_fd, p);
6755 /* Start all the jobs, but don't wait for anything to finish.
6758 * Return code is normally -1, when the caller has to wait for children
6759 * to finish to determine the exit status of the pipe. If the pipe
6760 * is a simple builtin command, however, the action is done by the
6761 * time run_pipe returns, and the exit code is provided as the
6764 * Returns -1 only if started some children. IOW: we have to
6765 * mask out retvals of builtins etc with 0xff!
6767 * The only case when we do not need to [v]fork is when the pipe
6768 * is single, non-backgrounded, non-subshell command. Examples:
6769 * cmd ; ... { list } ; ...
6770 * cmd && ... { list } && ...
6771 * cmd || ... { list } || ...
6772 * If it is, then we can run cmd as a builtin, NOFORK,
6773 * or (if SH_STANDALONE) an applet, and we can run the { list }
6774 * with run_list. If it isn't one of these, we fork and exec cmd.
6776 * Cases when we must fork:
6777 * non-single: cmd | cmd
6778 * backgrounded: cmd & { list } &
6779 * subshell: ( list ) [&]
6781 #if !ENABLE_HUSH_MODE_X
6782 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6783 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6785 static int redirect_and_varexp_helper(char ***new_env_p,
6786 struct variable **old_vars_p,
6787 struct command *command,
6789 char **argv_expanded)
6791 /* setup_redirects acts on file descriptors, not FILEs.
6792 * This is perfect for work that comes after exec().
6793 * Is it really safe for inline use? Experimentally,
6794 * things seem to work. */
6795 int rcode = setup_redirects(command, squirrel);
6797 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6798 *new_env_p = new_env;
6799 dump_cmd_in_x_mode(new_env);
6800 dump_cmd_in_x_mode(argv_expanded);
6802 *old_vars_p = set_vars_and_save_old(new_env);
6806 static NOINLINE int run_pipe(struct pipe *pi)
6808 static const char *const null_ptr = NULL;
6812 struct command *command;
6813 char **argv_expanded;
6815 /* it is not always needed, but we aim to smaller code */
6816 int squirrel[] = { -1, -1, -1 };
6819 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6822 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6823 * Result should be 3 lines: q w e, qwe, q w e
6825 G.ifs = get_local_var_value("IFS");
6829 IF_HUSH_JOB(pi->pgrp = -1;)
6830 pi->stopped_cmds = 0;
6831 command = &pi->cmds[0];
6832 argv_expanded = NULL;
6834 if (pi->num_cmds != 1
6835 || pi->followup == PIPE_BG
6836 || command->cmd_type == CMD_SUBSHELL
6843 debug_printf_exec(": group:%p argv:'%s'\n",
6844 command->group, command->argv ? command->argv[0] : "NONE");
6846 if (command->group) {
6847 #if ENABLE_HUSH_FUNCTIONS
6848 if (command->cmd_type == CMD_FUNCDEF) {
6849 /* "executing" func () { list } */
6850 struct function *funcp;
6852 funcp = new_function(command->argv[0]);
6853 /* funcp->name is already set to argv[0] */
6854 funcp->body = command->group;
6856 funcp->body_as_string = command->group_as_string;
6857 command->group_as_string = NULL;
6859 command->group = NULL;
6860 command->argv[0] = NULL;
6861 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6862 funcp->parent_cmd = command;
6863 command->child_func = funcp;
6865 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6867 return EXIT_SUCCESS;
6871 debug_printf("non-subshell group\n");
6872 rcode = 1; /* exitcode if redir failed */
6873 if (setup_redirects(command, squirrel) == 0) {
6874 debug_printf_exec(": run_list\n");
6875 rcode = run_list(command->group) & 0xff;
6877 restore_redirects(squirrel);
6878 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6880 debug_printf_exec("run_pipe: return %d\n", rcode);
6884 argv = command->argv ? command->argv : (char **) &null_ptr;
6886 const struct built_in_command *x;
6887 #if ENABLE_HUSH_FUNCTIONS
6888 const struct function *funcp;
6892 char **new_env = NULL;
6893 struct variable *old_vars = NULL;
6895 if (argv[command->assignment_cnt] == NULL) {
6896 /* Assignments, but no command */
6897 /* Ensure redirects take effect (that is, create files).
6898 * Try "a=t >file" */
6899 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6900 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6901 /* Set shell variables */
6905 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6906 /* Do we need to flag set_local_var() errors?
6907 * "assignment to readonly var" and "putenv error"
6912 /* Redirect error sets $? to 1. Otherwise,
6913 * if evaluating assignment value set $?, retain it.
6914 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6916 rcode = G.last_exitcode;
6917 /* Exit, _skipping_ variable restoring code: */
6918 goto clean_up_and_ret0;
6920 #else /* Older, bigger, but more correct code */
6922 rcode = setup_redirects(command, squirrel);
6923 restore_redirects(squirrel);
6924 /* Set shell variables */
6926 bb_putchar_stderr('+');
6928 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6930 fprintf(stderr, " %s", p);
6931 debug_printf_exec("set shell var:'%s'->'%s'\n",
6933 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6934 /* Do we need to flag set_local_var() errors?
6935 * "assignment to readonly var" and "putenv error"
6940 bb_putchar_stderr('\n');
6941 /* Redirect error sets $? to 1. Otherwise,
6942 * if evaluating assignment value set $?, retain it.
6943 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6945 rcode = G.last_exitcode;
6946 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6948 debug_printf_exec("run_pipe: return %d\n", rcode);
6953 /* Expand the rest into (possibly) many strings each */
6954 #if ENABLE_HUSH_BASH_COMPAT
6955 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6956 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6960 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6963 /* if someone gives us an empty string: `cmd with empty output` */
6964 if (!argv_expanded[0]) {
6965 free(argv_expanded);
6967 return G.last_exitcode;
6970 x = find_builtin(argv_expanded[0]);
6971 #if ENABLE_HUSH_FUNCTIONS
6974 funcp = find_function(argv_expanded[0]);
6978 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6979 debug_printf("exec with redirects only\n");
6980 rcode = setup_redirects(command, NULL);
6981 goto clean_up_and_ret1;
6984 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6987 debug_printf_exec(": builtin '%s' '%s'...\n",
6988 x->b_cmd, argv_expanded[1]);
6990 rcode = x->b_function(argv_expanded) & 0xff;
6993 #if ENABLE_HUSH_FUNCTIONS
6995 # if ENABLE_HUSH_LOCAL
6996 struct variable **sv;
6997 sv = G.shadowed_vars_pp;
6998 G.shadowed_vars_pp = &old_vars;
7000 debug_printf_exec(": function '%s' '%s'...\n",
7001 funcp->name, argv_expanded[1]);
7002 rcode = run_function(funcp, argv_expanded) & 0xff;
7003 # if ENABLE_HUSH_LOCAL
7004 G.shadowed_vars_pp = sv;
7010 unset_vars(new_env);
7012 /* clean_up_and_ret0: */
7013 restore_redirects(squirrel);
7015 free(argv_expanded);
7016 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7018 debug_printf_exec("run_pipe return %d\n", rcode);
7022 if (ENABLE_FEATURE_SH_NOFORK) {
7023 int n = find_applet_by_name(argv_expanded[0]);
7024 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7025 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7027 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7028 argv_expanded[0], argv_expanded[1]);
7029 rcode = run_nofork_applet(n, argv_expanded);
7031 goto clean_up_and_ret;
7034 /* It is neither builtin nor applet. We must fork. */
7038 /* NB: argv_expanded may already be created, and that
7039 * might include `cmd` runs! Do not rerun it! We *must*
7040 * use argv_expanded if it's non-NULL */
7042 /* Going to fork a child per each pipe member */
7047 while (cmd_no < pi->num_cmds) {
7048 struct fd_pair pipefds;
7050 volatile nommu_save_t nommu_save;
7051 nommu_save.new_env = NULL;
7052 nommu_save.old_vars = NULL;
7053 nommu_save.argv = NULL;
7054 nommu_save.argv_from_re_execing = NULL;
7056 command = &pi->cmds[cmd_no];
7058 if (command->argv) {
7059 debug_printf_exec(": pipe member '%s' '%s'...\n",
7060 command->argv[0], command->argv[1]);
7062 debug_printf_exec(": pipe member with no argv\n");
7065 /* pipes are inserted between pairs of commands */
7068 if (cmd_no < pi->num_cmds)
7069 xpiped_pair(pipefds);
7071 command->pid = BB_MMU ? fork() : vfork();
7072 if (!command->pid) { /* child */
7074 disable_restore_tty_pgrp_on_exit();
7075 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7077 /* Every child adds itself to new process group
7078 * with pgid == pid_of_first_child_in_pipe */
7079 if (G.run_list_level == 1 && G_interactive_fd) {
7082 if (pgrp < 0) /* true for 1st process only */
7084 if (setpgid(0, pgrp) == 0
7085 && pi->followup != PIPE_BG
7086 && G_saved_tty_pgrp /* we have ctty */
7088 /* We do it in *every* child, not just first,
7090 tcsetpgrp(G_interactive_fd, pgrp);
7094 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7095 /* 1st cmd in backgrounded pipe
7096 * should have its stdin /dev/null'ed */
7098 if (open(bb_dev_null, O_RDONLY))
7099 xopen("/", O_RDONLY);
7101 xmove_fd(next_infd, 0);
7103 xmove_fd(pipefds.wr, 1);
7106 /* Like bash, explicit redirects override pipes,
7107 * and the pipe fd is available for dup'ing. */
7108 if (setup_redirects(command, NULL))
7111 /* Stores to nommu_save list of env vars putenv'ed
7112 * (NOMMU, on MMU we don't need that) */
7113 /* cast away volatility... */
7114 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7115 /* pseudo_exec() does not return */
7118 /* parent or error */
7119 #if ENABLE_HUSH_FAST
7121 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7123 enable_restore_tty_pgrp_on_exit();
7125 /* Clean up after vforked child */
7126 free(nommu_save.argv);
7127 free(nommu_save.argv_from_re_execing);
7128 unset_vars(nommu_save.new_env);
7129 add_vars(nommu_save.old_vars);
7131 free(argv_expanded);
7132 argv_expanded = NULL;
7133 if (command->pid < 0) { /* [v]fork failed */
7134 /* Clearly indicate, was it fork or vfork */
7135 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7139 /* Second and next children need to know pid of first one */
7141 pi->pgrp = command->pid;
7147 if (cmd_no < pi->num_cmds)
7149 /* Pass read (output) pipe end to next iteration */
7150 next_infd = pipefds.rd;
7153 if (!pi->alive_cmds) {
7155 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7160 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7164 /* NB: called by pseudo_exec, and therefore must not modify any
7165 * global data until exec/_exit (we can be a child after vfork!) */
7166 static int run_list(struct pipe *pi)
7168 #if ENABLE_HUSH_CASE
7169 char *case_word = NULL;
7171 #if ENABLE_HUSH_LOOPS
7172 struct pipe *loop_top = NULL;
7173 char **for_lcur = NULL;
7174 char **for_list = NULL;
7176 smallint last_followup;
7178 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7179 smalluint cond_code = 0;
7181 enum { cond_code = 0 };
7184 smallint rword; /* RES_foo */
7185 smallint last_rword; /* ditto */
7188 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7191 #if ENABLE_HUSH_LOOPS
7192 /* Check syntax for "for" */
7195 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7196 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7198 /* current word is FOR or IN (BOLD in comments below) */
7199 if (cpipe->next == NULL) {
7200 syntax_error("malformed for");
7202 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7205 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7206 if (cpipe->next->res_word == RES_DO)
7208 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7209 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7210 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7212 syntax_error("malformed for");
7214 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7221 /* Past this point, all code paths should jump to ret: label
7222 * in order to return, no direct "return" statements please.
7223 * This helps to ensure that no memory is leaked. */
7231 last_rword = RES_XXXX;
7233 last_followup = PIPE_SEQ;
7234 rcode = G.last_exitcode;
7236 /* Go through list of pipes, (maybe) executing them. */
7237 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7241 IF_HAS_KEYWORDS(rword = pi->res_word;)
7242 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7243 rword, cond_code, last_rword);
7244 #if ENABLE_HUSH_LOOPS
7245 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7246 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7248 /* start of a loop: remember where loop starts */
7253 /* Still in the same "if...", "then..." or "do..." branch? */
7254 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7255 if ((rcode == 0 && last_followup == PIPE_OR)
7256 || (rcode != 0 && last_followup == PIPE_AND)
7258 /* It is "<true> || CMD" or "<false> && CMD"
7259 * and we should not execute CMD */
7260 debug_printf_exec("skipped cmd because of || or &&\n");
7261 last_followup = pi->followup;
7265 last_followup = pi->followup;
7266 IF_HAS_KEYWORDS(last_rword = rword;)
7269 if (rword == RES_THEN) {
7270 /* if false; then ... fi has exitcode 0! */
7271 G.last_exitcode = rcode = EXIT_SUCCESS;
7272 /* "if <false> THEN cmd": skip cmd */
7276 if (rword == RES_ELSE || rword == RES_ELIF) {
7277 /* "if <true> then ... ELSE/ELIF cmd":
7278 * skip cmd and all following ones */
7283 #if ENABLE_HUSH_LOOPS
7284 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7286 /* first loop through for */
7288 static const char encoded_dollar_at[] ALIGN1 = {
7289 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7290 }; /* encoded representation of "$@" */
7291 static const char *const encoded_dollar_at_argv[] = {
7292 encoded_dollar_at, NULL
7293 }; /* argv list with one element: "$@" */
7296 vals = (char**)encoded_dollar_at_argv;
7297 if (pi->next->res_word == RES_IN) {
7298 /* if no variable values after "in" we skip "for" */
7299 if (!pi->next->cmds[0].argv) {
7300 G.last_exitcode = rcode = EXIT_SUCCESS;
7301 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7304 vals = pi->next->cmds[0].argv;
7305 } /* else: "for var; do..." -> assume "$@" list */
7306 /* create list of variable values */
7307 debug_print_strings("for_list made from", vals);
7308 for_list = expand_strvec_to_strvec(vals);
7309 for_lcur = for_list;
7310 debug_print_strings("for_list", for_list);
7313 /* "for" loop is over, clean up */
7319 /* Insert next value from for_lcur */
7320 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7321 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7324 if (rword == RES_IN) {
7325 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7327 if (rword == RES_DONE) {
7328 continue; /* "done" has no cmds too */
7331 #if ENABLE_HUSH_CASE
7332 if (rword == RES_CASE) {
7333 case_word = expand_strvec_to_string(pi->cmds->argv);
7336 if (rword == RES_MATCH) {
7339 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7341 /* all prev words didn't match, does this one match? */
7342 argv = pi->cmds->argv;
7344 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7345 /* TODO: which FNM_xxx flags to use? */
7346 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7348 if (cond_code == 0) { /* match! we will execute this branch */
7349 free(case_word); /* make future "word)" stop */
7357 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7359 continue; /* not matched yet, skip this pipe */
7362 /* Just pressing <enter> in shell should check for jobs.
7363 * OTOH, in non-interactive shell this is useless
7364 * and only leads to extra job checks */
7365 if (pi->num_cmds == 0) {
7366 if (G_interactive_fd)
7367 goto check_jobs_and_continue;
7371 /* After analyzing all keywords and conditions, we decided
7372 * to execute this pipe. NB: have to do checkjobs(NULL)
7373 * after run_pipe to collect any background children,
7374 * even if list execution is to be stopped. */
7375 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7378 #if ENABLE_HUSH_LOOPS
7379 G.flag_break_continue = 0;
7381 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7383 /* We ran a builtin, function, or group.
7384 * rcode is already known
7385 * and we don't need to wait for anything. */
7386 G.last_exitcode = rcode;
7387 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7388 check_and_run_traps();
7389 #if ENABLE_HUSH_LOOPS
7390 /* Was it "break" or "continue"? */
7391 if (G.flag_break_continue) {
7392 smallint fbc = G.flag_break_continue;
7393 /* We might fall into outer *loop*,
7394 * don't want to break it too */
7396 G.depth_break_continue--;
7397 if (G.depth_break_continue == 0)
7398 G.flag_break_continue = 0;
7399 /* else: e.g. "continue 2" should *break* once, *then* continue */
7400 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7401 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7402 goto check_jobs_and_break;
7403 /* "continue": simulate end of loop */
7408 #if ENABLE_HUSH_FUNCTIONS
7409 if (G.flag_return_in_progress == 1) {
7410 /* same as "goto check_jobs_and_break" */
7415 } else if (pi->followup == PIPE_BG) {
7416 /* What does bash do with attempts to background builtins? */
7417 /* even bash 3.2 doesn't do that well with nested bg:
7418 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7419 * I'm NOT treating inner &'s as jobs */
7420 check_and_run_traps();
7422 if (G.run_list_level == 1)
7425 /* Last command's pid goes to $! */
7426 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7427 G.last_exitcode = rcode = EXIT_SUCCESS;
7428 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7431 if (G.run_list_level == 1 && G_interactive_fd) {
7432 /* Waits for completion, then fg's main shell */
7433 rcode = checkjobs_and_fg_shell(pi);
7434 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7435 check_and_run_traps();
7438 { /* This one just waits for completion */
7439 rcode = checkjobs(pi);
7440 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7441 check_and_run_traps();
7443 G.last_exitcode = rcode;
7447 /* Analyze how result affects subsequent commands */
7449 if (rword == RES_IF || rword == RES_ELIF)
7452 #if ENABLE_HUSH_LOOPS
7453 /* Beware of "while false; true; do ..."! */
7454 if (pi->next && pi->next->res_word == RES_DO) {
7455 if (rword == RES_WHILE) {
7457 /* "while false; do...done" - exitcode 0 */
7458 G.last_exitcode = rcode = EXIT_SUCCESS;
7459 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7460 goto check_jobs_and_break;
7463 if (rword == RES_UNTIL) {
7465 debug_printf_exec(": until expr is true: breaking\n");
7466 check_jobs_and_break:
7474 check_jobs_and_continue:
7481 #if ENABLE_HUSH_LOOPS
7486 #if ENABLE_HUSH_CASE
7490 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7494 /* Select which version we will use */
7495 static int run_and_free_list(struct pipe *pi)
7498 debug_printf_exec("run_and_free_list entered\n");
7499 if (!G.o_opt[OPT_O_NOEXEC]) {
7500 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7501 rcode = run_list(pi);
7503 /* free_pipe_list has the side effect of clearing memory.
7504 * In the long run that function can be merged with run_list,
7505 * but doing that now would hobble the debugging effort. */
7507 debug_printf_exec("run_and_free_list return %d\n", rcode);
7512 static void install_sighandlers(unsigned mask)
7514 sighandler_t old_handler;
7516 while ((mask >>= 1) != 0) {
7520 old_handler = signal(sig, pick_sighandler(sig));
7521 /* POSIX allows shell to re-enable SIGCHLD
7522 * even if it was SIG_IGN on entry.
7523 * Therefore we skip IGN check for it:
7527 if (old_handler == SIG_IGN) {
7528 /* oops... restore back to IGN, and record this fact */
7529 signal(sig, old_handler);
7531 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7533 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7538 /* Called a few times only (or even once if "sh -c") */
7539 static void install_special_sighandlers(void)
7543 /* Which signals are shell-special? */
7544 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7545 if (G_interactive_fd) {
7546 mask |= SPECIAL_INTERACTIVE_SIGS;
7547 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7548 mask |= SPECIAL_JOBSTOP_SIGS;
7550 /* Careful, do not re-install handlers we already installed */
7551 if (G.special_sig_mask != mask) {
7552 unsigned diff = mask & ~G.special_sig_mask;
7553 G.special_sig_mask = mask;
7554 install_sighandlers(diff);
7560 /* Set handlers to restore tty pgrp and exit */
7561 static void install_fatal_sighandlers(void)
7565 /* We will restore tty pgrp on these signals */
7567 + (1 << SIGILL ) * HUSH_DEBUG
7568 + (1 << SIGFPE ) * HUSH_DEBUG
7569 + (1 << SIGBUS ) * HUSH_DEBUG
7570 + (1 << SIGSEGV) * HUSH_DEBUG
7571 + (1 << SIGTRAP) * HUSH_DEBUG
7573 /* bash 3.2 seems to handle these just like 'fatal' ones */
7576 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7577 * if we aren't interactive... but in this case
7578 * we never want to restore pgrp on exit, and this fn is not called
7580 /*+ (1 << SIGHUP )*/
7581 /*+ (1 << SIGTERM)*/
7582 /*+ (1 << SIGINT )*/
7584 G_fatal_sig_mask = mask;
7586 install_sighandlers(mask);
7590 static int set_mode(int state, char mode, const char *o_opt)
7595 G.o_opt[OPT_O_NOEXEC] = state;
7598 IF_HUSH_MODE_X(G_x_mode = state;)
7602 /* "set -+o" without parameter.
7603 * in bash, set -o produces this output:
7607 * We always use the second form.
7609 const char *p = o_opt_strings;
7612 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7618 idx = index_in_strings(o_opt_strings, o_opt);
7620 G.o_opt[idx] = state;
7624 return EXIT_FAILURE;
7626 return EXIT_SUCCESS;
7629 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7630 int hush_main(int argc, char **argv)
7633 OPT_login = (1 << 0),
7637 unsigned builtin_argc;
7639 struct variable *cur_var;
7640 struct variable *shell_ver;
7643 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7644 G.last_exitcode = EXIT_SUCCESS;
7645 #if ENABLE_HUSH_FAST
7646 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7649 G.argv0_for_re_execing = argv[0];
7651 /* Deal with HUSH_VERSION */
7652 shell_ver = xzalloc(sizeof(*shell_ver));
7653 shell_ver->flg_export = 1;
7654 shell_ver->flg_read_only = 1;
7655 /* Code which handles ${var<op>...} needs writable values for all variables,
7656 * therefore we xstrdup: */
7657 shell_ver->varstr = xstrdup(hush_version_str);
7658 /* Create shell local variables from the values
7659 * currently living in the environment */
7660 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7661 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7662 G.top_var = shell_ver;
7663 cur_var = G.top_var;
7666 char *value = strchr(*e, '=');
7667 if (value) { /* paranoia */
7668 cur_var->next = xzalloc(sizeof(*cur_var));
7669 cur_var = cur_var->next;
7670 cur_var->varstr = *e;
7671 cur_var->max_len = strlen(*e);
7672 cur_var->flg_export = 1;
7676 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7677 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7678 putenv(shell_ver->varstr);
7681 set_pwd_var(/*exp:*/ 1);
7682 /* bash also exports SHLVL and _,
7683 * and sets (but doesn't export) the following variables:
7685 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7686 * BASH_VERSION='3.2.0(1)-release'
7688 * MACHTYPE=i386-pc-linux-gnu
7690 * HOSTNAME=<xxxxxxxxxx>
7691 * PPID=<NNNNN> - we also do it elsewhere
7702 * PIPESTATUS=([0]="0")
7703 * HISTFILE=/<xxx>/.bash_history
7707 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7709 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7719 #if ENABLE_FEATURE_EDITING
7720 G.line_input_state = new_line_input_t(FOR_SHELL);
7721 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7723 const char *hp = get_local_var_value("HISTFILE");
7725 hp = get_local_var_value("HOME");
7727 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7728 //set_local_var(xasprintf("HISTFILE=%s", ...));
7731 # if ENABLE_FEATURE_SH_HISTFILESIZE
7732 hp = get_local_var_value("HISTFILESIZE");
7733 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7739 /* Initialize some more globals to non-zero values */
7740 cmdedit_update_prompt();
7742 if (setjmp(die_jmp)) {
7743 /* xfunc has failed! die die die */
7744 /* no EXIT traps, this is an escape hatch! */
7746 hush_exit(xfunc_error_retval);
7749 /* Shell is non-interactive at first. We need to call
7750 * install_special_sighandlers() if we are going to execute "sh <script>",
7751 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7752 * If we later decide that we are interactive, we run install_special_sighandlers()
7753 * in order to intercept (more) signals.
7757 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7758 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7761 opt = getopt(argc, argv, "+c:xinsl"
7764 # if ENABLE_HUSH_FUNCTIONS
7774 * sh ... -c 'script'
7775 * sh ... -c 'script' ARG0 [ARG1...]
7776 * On NOMMU, if builtin_argc != 0,
7777 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7778 * "" needs to be replaced with NULL
7779 * and BARGV vector fed to builtin function.
7780 * Note: the form without ARG0 never happens:
7781 * sh ... -c 'builtin' BARGV... ""
7784 G.root_pid = getpid();
7785 G.root_ppid = getppid();
7787 G.global_argv = argv + optind;
7788 G.global_argc = argc - optind;
7790 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7791 const struct built_in_command *x;
7793 install_special_sighandlers();
7794 x = find_builtin(optarg);
7795 if (x) { /* paranoia */
7796 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7797 G.global_argv += builtin_argc;
7798 G.global_argv[-1] = NULL; /* replace "" */
7800 G.last_exitcode = x->b_function(argv + optind - 1);
7804 if (!G.global_argv[0]) {
7805 /* -c 'script' (no params): prevent empty $0 */
7806 G.global_argv--; /* points to argv[i] of 'script' */
7807 G.global_argv[0] = argv[0];
7809 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7810 install_special_sighandlers();
7811 parse_and_run_string(optarg);
7814 /* Well, we cannot just declare interactiveness,
7815 * we have to have some stuff (ctty, etc) */
7816 /* G_interactive_fd++; */
7819 /* "-s" means "read from stdin", but this is how we always
7820 * operate, so simply do nothing here. */
7826 case '<': /* "big heredoc" support */
7827 full_write1_str(optarg);
7830 unsigned long long empty_trap_mask;
7832 G.root_pid = bb_strtou(optarg, &optarg, 16);
7834 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7836 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7838 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7840 builtin_argc = bb_strtou(optarg, &optarg, 16);
7842 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7843 if (empty_trap_mask != 0) {
7845 install_special_sighandlers();
7846 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7847 for (sig = 1; sig < NSIG; sig++) {
7848 if (empty_trap_mask & (1LL << sig)) {
7849 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7850 signal(sig, SIG_IGN);
7854 # if ENABLE_HUSH_LOOPS
7856 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7862 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7864 # if ENABLE_HUSH_FUNCTIONS
7866 struct function *funcp = new_function(optarg);
7867 /* funcp->name is already set to optarg */
7868 /* funcp->body is set to NULL. It's a special case. */
7869 funcp->body_as_string = argv[optind];
7877 if (set_mode(1, opt, NULL) == 0) /* no error */
7881 fprintf(stderr, "Usage: sh [FILE]...\n"
7882 " or: sh -c command [args]...\n\n");
7888 } /* option parsing loop */
7890 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7891 G.global_argc = argc - (optind - 1);
7892 G.global_argv = argv + (optind - 1);
7893 G.global_argv[0] = argv[0];
7896 G.root_pid = getpid();
7897 G.root_ppid = getppid();
7900 /* If we are login shell... */
7901 if (flags & OPT_login) {
7903 debug_printf("sourcing /etc/profile\n");
7904 input = fopen_for_read("/etc/profile");
7905 if (input != NULL) {
7906 close_on_exec_on(fileno(input));
7907 install_special_sighandlers();
7908 parse_and_run_file(input);
7911 /* bash: after sourcing /etc/profile,
7912 * tries to source (in the given order):
7913 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7914 * stopping on first found. --noprofile turns this off.
7915 * bash also sources ~/.bash_logout on exit.
7916 * If called as sh, skips .bash_XXX files.
7920 if (G.global_argv[1]) {
7923 * "bash <script>" (which is never interactive (unless -i?))
7924 * sources $BASH_ENV here (without scanning $PATH).
7925 * If called as sh, does the same but with $ENV.
7929 debug_printf("running script '%s'\n", G.global_argv[0]);
7930 input = xfopen_for_read(G.global_argv[0]);
7931 close_on_exec_on(fileno(input));
7932 install_special_sighandlers();
7933 parse_and_run_file(input);
7934 #if ENABLE_FEATURE_CLEAN_UP
7940 /* Up to here, shell was non-interactive. Now it may become one.
7941 * NB: don't forget to (re)run install_special_sighandlers() as needed.
7944 /* A shell is interactive if the '-i' flag was given,
7945 * or if all of the following conditions are met:
7947 * no arguments remaining or the -s flag given
7948 * standard input is a terminal
7949 * standard output is a terminal
7950 * Refer to Posix.2, the description of the 'sh' utility.
7953 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7954 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7955 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7956 if (G_saved_tty_pgrp < 0)
7957 G_saved_tty_pgrp = 0;
7959 /* try to dup stdin to high fd#, >= 255 */
7960 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7961 if (G_interactive_fd < 0) {
7962 /* try to dup to any fd */
7963 G_interactive_fd = dup(STDIN_FILENO);
7964 if (G_interactive_fd < 0) {
7966 G_interactive_fd = 0;
7967 G_saved_tty_pgrp = 0;
7970 // TODO: track & disallow any attempts of user
7971 // to (inadvertently) close/redirect G_interactive_fd
7973 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7974 if (G_interactive_fd) {
7975 close_on_exec_on(G_interactive_fd);
7977 if (G_saved_tty_pgrp) {
7978 /* If we were run as 'hush &', sleep until we are
7979 * in the foreground (tty pgrp == our pgrp).
7980 * If we get started under a job aware app (like bash),
7981 * make sure we are now in charge so we don't fight over
7982 * who gets the foreground */
7984 pid_t shell_pgrp = getpgrp();
7985 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7986 if (G_saved_tty_pgrp == shell_pgrp)
7988 /* send TTIN to ourself (should stop us) */
7989 kill(- shell_pgrp, SIGTTIN);
7993 /* Install more signal handlers */
7994 install_special_sighandlers();
7996 if (G_saved_tty_pgrp) {
7997 /* Set other signals to restore saved_tty_pgrp */
7998 install_fatal_sighandlers();
7999 /* Put ourselves in our own process group
8000 * (bash, too, does this only if ctty is available) */
8001 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8002 /* Grab control of the terminal */
8003 tcsetpgrp(G_interactive_fd, getpid());
8005 /* -1 is special - makes xfuncs longjmp, not exit
8006 * (we reset die_sleep = 0 whereever we [v]fork) */
8007 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8009 install_special_sighandlers();
8011 #elif ENABLE_HUSH_INTERACTIVE
8012 /* No job control compiled in, only prompt/line editing */
8013 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8014 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8015 if (G_interactive_fd < 0) {
8016 /* try to dup to any fd */
8017 G_interactive_fd = dup(STDIN_FILENO);
8018 if (G_interactive_fd < 0)
8020 G_interactive_fd = 0;
8023 if (G_interactive_fd) {
8024 close_on_exec_on(G_interactive_fd);
8026 install_special_sighandlers();
8028 /* We have interactiveness code disabled */
8029 install_special_sighandlers();
8032 * if interactive but not a login shell, sources ~/.bashrc
8033 * (--norc turns this off, --rcfile <file> overrides)
8036 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8037 /* note: ash and hush share this string */
8038 printf("\n\n%s %s\n"
8039 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8042 "hush - the humble shell"
8046 parse_and_run_file(stdin);
8049 hush_exit(G.last_exitcode);
8054 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8055 int msh_main(int argc, char **argv)
8057 //bb_error_msg("msh is deprecated, please use hush instead");
8058 return hush_main(argc, argv);
8066 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8071 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8078 return applet_main_func(argc, argv - argc);
8081 static int FAST_FUNC builtin_test(char **argv)
8083 return run_applet_main(argv, test_main);
8086 static int FAST_FUNC builtin_echo(char **argv)
8088 return run_applet_main(argv, echo_main);
8092 static int FAST_FUNC builtin_printf(char **argv)
8094 return run_applet_main(argv, printf_main);
8098 static char **skip_dash_dash(char **argv)
8101 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8106 static int FAST_FUNC builtin_eval(char **argv)
8108 int rcode = EXIT_SUCCESS;
8110 argv = skip_dash_dash(argv);
8112 char *str = expand_strvec_to_string(argv);
8114 * eval "echo Hi; done" ("done" is syntax error):
8115 * "echo Hi" will not execute too.
8117 parse_and_run_string(str);
8119 rcode = G.last_exitcode;
8124 static int FAST_FUNC builtin_cd(char **argv)
8128 argv = skip_dash_dash(argv);
8130 if (newdir == NULL) {
8131 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8132 * bash says "bash: cd: HOME not set" and does nothing
8135 const char *home = get_local_var_value("HOME");
8136 newdir = home ? home : "/";
8138 if (chdir(newdir)) {
8139 /* Mimic bash message exactly */
8140 bb_perror_msg("cd: %s", newdir);
8141 return EXIT_FAILURE;
8143 /* Read current dir (get_cwd(1) is inside) and set PWD.
8144 * Note: do not enforce exporting. If PWD was unset or unexported,
8145 * set it again, but do not export. bash does the same.
8147 set_pwd_var(/*exp:*/ 0);
8148 return EXIT_SUCCESS;
8151 static int FAST_FUNC builtin_exec(char **argv)
8153 argv = skip_dash_dash(argv);
8154 if (argv[0] == NULL)
8155 return EXIT_SUCCESS; /* bash does this */
8157 /* Careful: we can end up here after [v]fork. Do not restore
8158 * tty pgrp then, only top-level shell process does that */
8159 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8160 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8162 /* TODO: if exec fails, bash does NOT exit! We do.
8163 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8164 * and tcsetpgrp, and this is inherently racy.
8166 execvp_or_die(argv);
8169 static int FAST_FUNC builtin_exit(char **argv)
8171 debug_printf_exec("%s()\n", __func__);
8173 /* interactive bash:
8174 * # trap "echo EEE" EXIT
8177 * There are stopped jobs.
8178 * (if there are _stopped_ jobs, running ones don't count)
8181 # EEE (then bash exits)
8183 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8186 /* note: EXIT trap is run by hush_exit */
8187 argv = skip_dash_dash(argv);
8188 if (argv[0] == NULL)
8189 hush_exit(G.last_exitcode);
8190 /* mimic bash: exit 123abc == exit 255 + error msg */
8191 xfunc_error_retval = 255;
8192 /* bash: exit -2 == exit 254, no error msg */
8193 hush_exit(xatoi(argv[0]) & 0xff);
8196 static void print_escaped(const char *s)
8201 const char *p = strchrnul(s, '\'');
8202 /* print 'xxxx', possibly just '' */
8203 printf("'%.*s'", (int)(p - s), s);
8208 /* s points to '; print "'''...'''" */
8210 do putchar('\''); while (*++s == '\'');
8215 #if !ENABLE_HUSH_LOCAL
8216 #define helper_export_local(argv, exp, lvl) \
8217 helper_export_local(argv, exp)
8219 static void helper_export_local(char **argv, int exp, int lvl)
8223 char *name_end = strchrnul(name, '=');
8225 /* So far we do not check that name is valid (TODO?) */
8227 if (*name_end == '\0') {
8228 struct variable *var, **vpp;
8230 vpp = get_ptr_to_local_var(name, name_end - name);
8231 var = vpp ? *vpp : NULL;
8233 if (exp == -1) { /* unexporting? */
8234 /* export -n NAME (without =VALUE) */
8236 var->flg_export = 0;
8237 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8239 } /* else: export -n NOT_EXISTING_VAR: no-op */
8242 if (exp == 1) { /* exporting? */
8243 /* export NAME (without =VALUE) */
8245 var->flg_export = 1;
8246 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8247 putenv(var->varstr);
8251 /* Exporting non-existing variable.
8252 * bash does not put it in environment,
8253 * but remembers that it is exported,
8254 * and does put it in env when it is set later.
8255 * We just set it to "" and export. */
8256 /* Or, it's "local NAME" (without =VALUE).
8257 * bash sets the value to "". */
8258 name = xasprintf("%s=", name);
8260 /* (Un)exporting/making local NAME=VALUE */
8261 name = xstrdup(name);
8263 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8267 static int FAST_FUNC builtin_export(char **argv)
8269 unsigned opt_unexport;
8271 #if ENABLE_HUSH_EXPORT_N
8272 /* "!": do not abort on errors */
8273 opt_unexport = getopt32(argv, "!n");
8274 if (opt_unexport == (uint32_t)-1)
8275 return EXIT_FAILURE;
8282 if (argv[0] == NULL) {
8289 /* ash emits: export VAR='VAL'
8290 * bash: declare -x VAR="VAL"
8291 * we follow ash example */
8292 const char *s = *e++;
8293 const char *p = strchr(s, '=');
8295 if (!p) /* wtf? take next variable */
8298 printf("export %.*s", (int)(p - s) + 1, s);
8299 print_escaped(p + 1);
8303 /*fflush_all(); - done after each builtin anyway */
8305 return EXIT_SUCCESS;
8308 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8310 return EXIT_SUCCESS;
8313 #if ENABLE_HUSH_LOCAL
8314 static int FAST_FUNC builtin_local(char **argv)
8316 if (G.func_nest_level == 0) {
8317 bb_error_msg("%s: not in a function", argv[0]);
8318 return EXIT_FAILURE; /* bash compat */
8320 helper_export_local(argv, 0, G.func_nest_level);
8321 return EXIT_SUCCESS;
8325 static int FAST_FUNC builtin_trap(char **argv)
8331 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8336 /* No args: print all trapped */
8337 for (i = 0; i < NSIG; ++i) {
8340 print_escaped(G.traps[i]);
8341 /* note: bash adds "SIG", but only if invoked
8342 * as "bash". If called as "sh", or if set -o posix,
8343 * then it prints short signal names.
8344 * We are printing short names: */
8345 printf(" %s\n", get_signame(i));
8348 /*fflush_all(); - done after each builtin anyway */
8349 return EXIT_SUCCESS;
8353 /* If first arg is a number: reset all specified signals */
8354 sig = bb_strtou(*argv, NULL, 10);
8360 sighandler_t handler;
8362 sig = get_signum(*argv++);
8363 if (sig < 0 || sig >= NSIG) {
8365 /* Mimic bash message exactly */
8366 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8371 G.traps[sig] = xstrdup(new_cmd);
8373 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8374 get_signame(sig), sig, G.traps[sig]);
8376 /* There is no signal for 0 (EXIT) */
8381 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8383 /* We are removing trap handler */
8384 handler = pick_sighandler(sig);
8385 signal(sig, handler);
8390 if (!argv[1]) { /* no second arg */
8391 bb_error_msg("trap: invalid arguments");
8392 return EXIT_FAILURE;
8395 /* First arg is "-": reset all specified to default */
8396 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8397 /* Everything else: set arg as signal handler
8398 * (includes "" case, which ignores signal) */
8399 if (argv[0][0] == '-') {
8400 if (argv[0][1] == '\0') { /* "-" */
8401 /* new_cmd remains NULL: "reset these sigs" */
8404 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8407 /* else: "-something", no special meaning */
8412 goto process_sig_list;
8415 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8416 static int FAST_FUNC builtin_type(char **argv)
8418 int ret = EXIT_SUCCESS;
8424 if (0) {} /* make conditional compile easier below */
8425 /*else if (find_alias(*argv))
8426 type = "an alias";*/
8427 #if ENABLE_HUSH_FUNCTIONS
8428 else if (find_function(*argv))
8429 type = "a function";
8431 else if (find_builtin(*argv))
8432 type = "a shell builtin";
8433 else if ((path = find_in_path(*argv)) != NULL)
8436 bb_error_msg("type: %s: not found", *argv);
8441 printf("%s is %s\n", *argv, type);
8449 /* built-in 'fg' and 'bg' handler */
8450 static int FAST_FUNC builtin_fg_bg(char **argv)
8455 if (!G_interactive_fd)
8456 return EXIT_FAILURE;
8458 /* If they gave us no args, assume they want the last backgrounded task */
8460 for (pi = G.job_list; pi; pi = pi->next) {
8461 if (pi->jobid == G.last_jobid) {
8465 bb_error_msg("%s: no current job", argv[0]);
8466 return EXIT_FAILURE;
8468 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8469 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8470 return EXIT_FAILURE;
8472 for (pi = G.job_list; pi; pi = pi->next) {
8473 if (pi->jobid == jobnum) {
8477 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8478 return EXIT_FAILURE;
8480 /* TODO: bash prints a string representation
8481 * of job being foregrounded (like "sleep 1 | cat") */
8482 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8483 /* Put the job into the foreground. */
8484 tcsetpgrp(G_interactive_fd, pi->pgrp);
8487 /* Restart the processes in the job */
8488 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8489 for (i = 0; i < pi->num_cmds; i++) {
8490 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8491 pi->cmds[i].is_stopped = 0;
8493 pi->stopped_cmds = 0;
8495 i = kill(- pi->pgrp, SIGCONT);
8497 if (errno == ESRCH) {
8498 delete_finished_bg_job(pi);
8499 return EXIT_SUCCESS;
8501 bb_perror_msg("kill (SIGCONT)");
8504 if (argv[0][0] == 'f') {
8506 return checkjobs_and_fg_shell(pi);
8508 return EXIT_SUCCESS;
8512 #if ENABLE_HUSH_HELP
8513 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8515 const struct built_in_command *x;
8518 "Built-in commands:\n"
8519 "------------------\n");
8520 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8522 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8525 return EXIT_SUCCESS;
8530 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8533 const char *status_string;
8535 for (job = G.job_list; job; job = job->next) {
8536 if (job->alive_cmds == job->stopped_cmds)
8537 status_string = "Stopped";
8539 status_string = "Running";
8541 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8543 return EXIT_SUCCESS;
8548 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8553 # ifdef M_TRIM_THRESHOLD
8554 /* Optional. Reduces probability of false positives */
8557 /* Crude attempt to find where "free memory" starts,
8558 * sans fragmentation. */
8560 l = (unsigned long)p;
8563 if (l < (unsigned long)p) l = (unsigned long)p;
8566 if (!G.memleak_value)
8567 G.memleak_value = l;
8569 l -= G.memleak_value;
8576 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8581 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8584 return EXIT_SUCCESS;
8587 /* Interruptibility of read builtin in bash
8588 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8590 * Empty trap makes read ignore corresponding signal, for any signal.
8593 * - terminates non-interactive shell;
8594 * - interrupts read in interactive shell;
8595 * if it has non-empty trap:
8596 * - executes trap and returns to command prompt in interactive shell;
8597 * - executes trap and returns to read in non-interactive shell;
8599 * - is ignored (does not interrupt) read in interactive shell;
8600 * - terminates non-interactive shell;
8601 * if it has non-empty trap:
8602 * - executes trap and returns to read;
8604 * - terminates shell (regardless of interactivity);
8605 * if it has non-empty trap:
8606 * - executes trap and returns to read;
8608 static int FAST_FUNC builtin_read(char **argv)
8618 /* "!": do not abort on errors.
8619 * Option string must start with "sr" to match BUILTIN_READ_xxx
8621 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8622 if (read_flags == (uint32_t)-1)
8623 return EXIT_FAILURE;
8625 ifs = get_local_var_value("IFS"); /* can be NULL */
8628 r = shell_builtin_read(set_local_var_from_halves,
8638 if ((uintptr_t)r == 1 && errno == EINTR) {
8639 unsigned sig = check_and_run_traps();
8640 if (sig && sig != SIGINT)
8644 if ((uintptr_t)r > 1) {
8645 bb_error_msg("%s", r);
8646 r = (char*)(uintptr_t)1;
8649 return (uintptr_t)r;
8652 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8653 * built-in 'set' handler
8655 * set [-abCefhmnuvx] [-o option] [argument...]
8656 * set [+abCefhmnuvx] [+o option] [argument...]
8657 * set -- [argument...]
8660 * Implementations shall support the options in both their hyphen and
8661 * plus-sign forms. These options can also be specified as options to sh.
8663 * Write out all variables and their values: set
8664 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8665 * Turn on the -x and -v options: set -xv
8666 * Unset all positional parameters: set --
8667 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8668 * Set the positional parameters to the expansion of x, even if x expands
8669 * with a leading '-' or '+': set -- $x
8671 * So far, we only support "set -- [argument...]" and some of the short names.
8673 static int FAST_FUNC builtin_set(char **argv)
8676 char **pp, **g_argv;
8677 char *arg = *++argv;
8681 for (e = G.top_var; e; e = e->next)
8683 return EXIT_SUCCESS;
8687 if (strcmp(arg, "--") == 0) {
8691 if (arg[0] != '+' && arg[0] != '-')
8693 for (n = 1; arg[n]; ++n) {
8694 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8696 if (arg[n] == 'o' && argv[1])
8699 } while ((arg = *++argv) != NULL);
8700 /* Now argv[0] is 1st argument */
8703 return EXIT_SUCCESS;
8706 /* NB: G.global_argv[0] ($0) is never freed/changed */
8707 g_argv = G.global_argv;
8708 if (G.global_args_malloced) {
8714 G.global_args_malloced = 1;
8715 pp = xzalloc(sizeof(pp[0]) * 2);
8716 pp[0] = g_argv[0]; /* retain $0 */
8719 /* This realloc's G.global_argv */
8720 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8727 return EXIT_SUCCESS;
8729 /* Nothing known, so abort */
8731 bb_error_msg("set: %s: invalid option", arg);
8732 return EXIT_FAILURE;
8735 static int FAST_FUNC builtin_shift(char **argv)
8738 argv = skip_dash_dash(argv);
8742 if (n >= 0 && n < G.global_argc) {
8743 if (G.global_args_malloced) {
8746 free(G.global_argv[m++]);
8749 memmove(&G.global_argv[1], &G.global_argv[n+1],
8750 G.global_argc * sizeof(G.global_argv[0]));
8751 return EXIT_SUCCESS;
8753 return EXIT_FAILURE;
8756 static int FAST_FUNC builtin_source(char **argv)
8758 char *arg_path, *filename;
8761 #if ENABLE_HUSH_FUNCTIONS
8765 argv = skip_dash_dash(argv);
8768 /* bash says: "bash: .: filename argument required" */
8769 return 2; /* bash compat */
8772 if (!strchr(filename, '/')) {
8773 arg_path = find_in_path(filename);
8775 filename = arg_path;
8777 input = fopen_or_warn(filename, "r");
8780 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8781 return EXIT_FAILURE;
8783 close_on_exec_on(fileno(input));
8785 #if ENABLE_HUSH_FUNCTIONS
8786 sv_flg = G.flag_return_in_progress;
8787 /* "we are inside sourced file, ok to use return" */
8788 G.flag_return_in_progress = -1;
8790 save_and_replace_G_args(&sv, argv);
8792 parse_and_run_file(input);
8795 restore_G_args(&sv, argv);
8796 #if ENABLE_HUSH_FUNCTIONS
8797 G.flag_return_in_progress = sv_flg;
8800 return G.last_exitcode;
8803 static int FAST_FUNC builtin_umask(char **argv)
8809 argv = skip_dash_dash(argv);
8811 mode_t old_mask = mask;
8814 rc = bb_parse_mode(argv[0], &mask);
8819 * bash: umask: 'q': invalid symbolic mode operator
8820 * bash: umask: 999: octal number out of range
8822 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8827 printf("%04o\n", (unsigned) mask);
8828 /* fall through and restore mask which we set to 0 */
8832 return !rc; /* rc != 0 - success */
8835 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8836 static int FAST_FUNC builtin_unset(char **argv)
8841 /* "!": do not abort on errors */
8842 /* "+": stop at 1st non-option */
8843 opts = getopt32(argv, "!+vf");
8844 if (opts == (unsigned)-1)
8845 return EXIT_FAILURE;
8847 bb_error_msg("unset: -v and -f are exclusive");
8848 return EXIT_FAILURE;
8854 if (!(opts & 2)) { /* not -f */
8855 if (unset_local_var(*argv)) {
8856 /* unset <nonexistent_var> doesn't fail.
8857 * Error is when one tries to unset RO var.
8858 * Message was printed by unset_local_var. */
8862 #if ENABLE_HUSH_FUNCTIONS
8872 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8873 static int FAST_FUNC builtin_wait(char **argv)
8875 int ret = EXIT_SUCCESS;
8878 argv = skip_dash_dash(argv);
8879 if (argv[0] == NULL) {
8880 /* Don't care about wait results */
8881 /* Note 1: must wait until there are no more children */
8882 /* Note 2: must be interruptible */
8884 * $ sleep 3 & sleep 6 & wait
8889 * $ sleep 3 & sleep 6 & wait
8893 * ^C <-- after ~4 sec from keyboard
8898 sigset_t oldset, allsigs;
8900 /* waitpid is not interruptible by SA_RESTARTed
8901 * signals which we use. Thus, this ugly dance:
8904 /* Make sure possible SIGCHLD is stored in kernel's
8905 * pending signal mask before we call waitpid.
8906 * Or else we may race with SIGCHLD, lose it,
8907 * and get stuck in sigwaitinfo...
8909 sigfillset(&allsigs);
8910 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8912 if (!sigisemptyset(&G.pending_set)) {
8913 /* Crap! we raced with some signal! */
8918 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8919 if (errno == ECHILD) {
8920 sigprocmask(SIG_SETMASK, &oldset, NULL);
8924 /* Wait for SIGCHLD or any other signal */
8925 //sig = sigwaitinfo(&allsigs, NULL);
8926 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8927 /* Note: sigsuspend invokes signal handler */
8928 sigsuspend(&oldset);
8930 sigprocmask(SIG_SETMASK, &oldset, NULL);
8932 /* So, did we get a signal? */
8934 // raise(sig); /* run handler */
8935 sig = check_and_run_traps();
8936 if (sig /*&& sig != SIGCHLD - always true */) {
8941 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
8946 /* This is probably buggy wrt interruptible-ness */
8948 pid_t pid = bb_strtou(*argv, NULL, 10);
8950 /* mimic bash message */
8951 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8952 return EXIT_FAILURE;
8954 if (waitpid(pid, &status, 0) == pid) {
8955 if (WIFSIGNALED(status))
8956 ret = 128 + WTERMSIG(status);
8957 else if (WIFEXITED(status))
8958 ret = WEXITSTATUS(status);
8962 bb_perror_msg("wait %s", *argv);
8971 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8972 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8975 def = bb_strtou(argv[1], NULL, 10);
8976 if (errno || def < def_min || argv[2]) {
8977 bb_error_msg("%s: bad arguments", argv[0]);
8985 #if ENABLE_HUSH_LOOPS
8986 static int FAST_FUNC builtin_break(char **argv)
8989 if (G.depth_of_loop == 0) {
8990 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8991 return EXIT_SUCCESS; /* bash compat */
8993 G.flag_break_continue++; /* BC_BREAK = 1 */
8995 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8996 if (depth == UINT_MAX)
8997 G.flag_break_continue = BC_BREAK;
8998 if (G.depth_of_loop < depth)
8999 G.depth_break_continue = G.depth_of_loop;
9001 return EXIT_SUCCESS;
9004 static int FAST_FUNC builtin_continue(char **argv)
9006 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9007 return builtin_break(argv);
9011 #if ENABLE_HUSH_FUNCTIONS
9012 static int FAST_FUNC builtin_return(char **argv)
9016 if (G.flag_return_in_progress != -1) {
9017 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9018 return EXIT_FAILURE; /* bash compat */
9021 G.flag_return_in_progress = 1;
9024 * out of range: wraps around at 256, does not error out
9025 * non-numeric param:
9026 * f() { false; return qwe; }; f; echo $?
9027 * bash: return: qwe: numeric argument required <== we do this
9028 * 255 <== we also do this
9030 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);