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.
1418 * TODO: don't use signal() to install sighandlers: need to mask ALL signals
1419 * while handler runs. I saw signal nesting in one strace, race window isn't small.
1422 SPECIAL_INTERACTIVE_SIGS = 0
1427 SPECIAL_JOBSTOP_SIGS = 0
1436 static void record_pending_signo(int sig)
1438 sigaddset(&G.pending_set, sig);
1439 #if ENABLE_HUSH_FAST
1440 if (sig == SIGCHLD) {
1442 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1449 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1450 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1451 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1452 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1454 /* Restores tty foreground process group, and exits.
1455 * May be called as signal handler for fatal signal
1456 * (will resend signal to itself, producing correct exit state)
1457 * or called directly with -EXITCODE.
1458 * We also call it if xfunc is exiting. */
1459 static void sigexit(int sig) NORETURN;
1460 static void sigexit(int sig)
1462 /* Careful: we can end up here after [v]fork. Do not restore
1463 * tty pgrp then, only top-level shell process does that */
1464 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1465 /* Disable all signals: job control, SIGPIPE, etc.
1466 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1468 sigprocmask_allsigs(SIG_BLOCK);
1469 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1472 /* Not a signal, just exit */
1476 kill_myself_with_sig(sig); /* does not return */
1480 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1481 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1485 static sighandler_t pick_sighandler(unsigned sig)
1487 sighandler_t handler = SIG_DFL;
1488 if (sig < sizeof(unsigned)*8) {
1489 unsigned sigmask = (1 << sig);
1493 if (G_fatal_sig_mask & sigmask)
1497 /* sig has special handling? */
1498 if (G.special_sig_mask & sigmask) {
1499 handler = record_pending_signo;
1500 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1501 * in order to ignore them: they will be raised
1502 * in an endless loop when we try to do some
1503 * terminal ioctls! We do have to _ignore_ these.
1505 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1512 /* Restores tty foreground process group, and exits. */
1513 static void hush_exit(int exitcode) NORETURN;
1514 static void hush_exit(int exitcode)
1517 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1519 /* argv[0] is unused */
1520 argv[1] = G.traps[0];
1522 G.exiting = 1; /* prevent EXIT trap recursion */
1523 /* Note: G.traps[0] is not cleared!
1524 * "trap" will still show it, if executed
1529 #if ENABLE_FEATURE_CLEAN_UP
1531 struct variable *cur_var;
1532 if (G.cwd != bb_msg_unknown)
1534 cur_var = G.top_var;
1536 struct variable *tmp = cur_var;
1537 if (!cur_var->max_len)
1538 free(cur_var->varstr);
1539 cur_var = cur_var->next;
1547 sigexit(- (exitcode & 0xff));
1554 //TODO: return a mask of ALL handled sigs?
1555 static int check_and_run_traps(void)
1562 if (sigisemptyset(&G.pending_set))
1567 if (sigismember(&G.pending_set, sig)) {
1568 sigdelset(&G.pending_set, sig);
1571 } while (sig < NSIG);
1574 if (G.traps && G.traps[sig]) {
1575 if (G.traps[sig][0]) {
1576 /* We have user-defined handler */
1577 smalluint save_rcode;
1579 /* argv[0] is unused */
1580 argv[1] = G.traps[sig];
1582 save_rcode = G.last_exitcode;
1584 G.last_exitcode = save_rcode;
1586 } /* else: "" trap, ignoring signal */
1589 /* not a trap: special action */
1592 /* Builtin was ^C'ed, make it look prettier: */
1600 /* bash is observed to signal whole process groups,
1601 * not individual processes */
1602 for (job = G.job_list; job; job = job->next) {
1605 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1606 if (kill(- job->pgrp, SIGHUP) == 0)
1607 kill(- job->pgrp, SIGCONT);
1612 #if ENABLE_HUSH_FAST
1615 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1617 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1618 * This simplifies wait builtin a bit.
1622 default: /* ignored: */
1623 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1625 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1626 * Example: wait is not interrupted by TERM
1627 * in interactive shell, because TERM is ignored.
1636 static const char *get_cwd(int force)
1638 if (force || G.cwd == NULL) {
1639 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1640 * we must not try to free(bb_msg_unknown) */
1641 if (G.cwd == bb_msg_unknown)
1643 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1645 G.cwd = bb_msg_unknown;
1652 * Shell and environment variable support
1654 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1656 struct variable **pp;
1657 struct variable *cur;
1660 while ((cur = *pp) != NULL) {
1661 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1668 static const char* FAST_FUNC get_local_var_value(const char *name)
1670 struct variable **vpp;
1671 unsigned len = strlen(name);
1673 if (G.expanded_assignments) {
1674 char **cpp = G.expanded_assignments;
1677 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1678 return cp + len + 1;
1683 vpp = get_ptr_to_local_var(name, len);
1685 return (*vpp)->varstr + len + 1;
1687 if (strcmp(name, "PPID") == 0)
1688 return utoa(G.root_ppid);
1689 // bash compat: UID? EUID?
1690 #if ENABLE_HUSH_RANDOM_SUPPORT
1691 if (strcmp(name, "RANDOM") == 0)
1692 return utoa(next_random(&G.random_gen));
1697 /* str holds "NAME=VAL" and is expected to be malloced.
1698 * We take ownership of it.
1700 * 0: do not change export flag
1701 * (if creating new variable, flag will be 0)
1702 * 1: set export flag and putenv the variable
1703 * -1: clear export flag and unsetenv the variable
1704 * flg_read_only is set only when we handle -R var=val
1706 #if !BB_MMU && ENABLE_HUSH_LOCAL
1707 /* all params are used */
1708 #elif BB_MMU && ENABLE_HUSH_LOCAL
1709 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1710 set_local_var(str, flg_export, local_lvl)
1711 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1712 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1713 set_local_var(str, flg_export)
1714 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1715 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1716 set_local_var(str, flg_export, flg_read_only)
1718 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1720 struct variable **var_pp;
1721 struct variable *cur;
1725 eq_sign = strchr(str, '=');
1726 if (!eq_sign) { /* not expected to ever happen? */
1731 name_len = eq_sign - str + 1; /* including '=' */
1732 var_pp = &G.top_var;
1733 while ((cur = *var_pp) != NULL) {
1734 if (strncmp(cur->varstr, str, name_len) != 0) {
1735 var_pp = &cur->next;
1738 /* We found an existing var with this name */
1739 if (cur->flg_read_only) {
1743 bb_error_msg("%s: readonly variable", str);
1747 if (flg_export == -1) { // "&& cur->flg_export" ?
1748 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1753 #if ENABLE_HUSH_LOCAL
1754 if (cur->func_nest_level < local_lvl) {
1755 /* New variable is declared as local,
1756 * and existing one is global, or local
1757 * from enclosing function.
1758 * Remove and save old one: */
1759 *var_pp = cur->next;
1760 cur->next = *G.shadowed_vars_pp;
1761 *G.shadowed_vars_pp = cur;
1762 /* bash 3.2.33(1) and exported vars:
1764 * # f() { local z=a; env | grep ^z; }
1770 if (cur->flg_export)
1775 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1780 if (cur->max_len != 0) {
1781 if (cur->max_len >= strlen(str)) {
1782 /* This one is from startup env, reuse space */
1783 strcpy(cur->varstr, str);
1787 /* max_len == 0 signifies "malloced" var, which we can
1788 * (and has to) free */
1792 goto set_str_and_exp;
1795 /* Not found - create new variable struct */
1796 cur = xzalloc(sizeof(*cur));
1797 #if ENABLE_HUSH_LOCAL
1798 cur->func_nest_level = local_lvl;
1800 cur->next = *var_pp;
1806 cur->flg_read_only = flg_read_only;
1809 if (flg_export == 1)
1810 cur->flg_export = 1;
1811 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1812 cmdedit_update_prompt();
1813 if (cur->flg_export) {
1814 if (flg_export == -1) {
1815 cur->flg_export = 0;
1816 /* unsetenv was already done */
1818 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1819 return putenv(cur->varstr);
1825 /* Used at startup and after each cd */
1826 static void set_pwd_var(int exp)
1828 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1829 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1832 static int unset_local_var_len(const char *name, int name_len)
1834 struct variable *cur;
1835 struct variable **var_pp;
1838 return EXIT_SUCCESS;
1839 var_pp = &G.top_var;
1840 while ((cur = *var_pp) != NULL) {
1841 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1842 if (cur->flg_read_only) {
1843 bb_error_msg("%s: readonly variable", name);
1844 return EXIT_FAILURE;
1846 *var_pp = cur->next;
1847 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1848 bb_unsetenv(cur->varstr);
1849 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1850 cmdedit_update_prompt();
1854 return EXIT_SUCCESS;
1856 var_pp = &cur->next;
1858 return EXIT_SUCCESS;
1861 static int unset_local_var(const char *name)
1863 return unset_local_var_len(name, strlen(name));
1866 static void unset_vars(char **strings)
1874 const char *eq = strchrnul(*v, '=');
1875 unset_local_var_len(*v, (int)(eq - *v));
1881 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1883 char *var = xasprintf("%s=%s", name, val);
1884 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1889 * Helpers for "var1=val1 var2=val2 cmd" feature
1891 static void add_vars(struct variable *var)
1893 struct variable *next;
1897 var->next = G.top_var;
1899 if (var->flg_export) {
1900 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1901 putenv(var->varstr);
1903 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1909 static struct variable *set_vars_and_save_old(char **strings)
1912 struct variable *old = NULL;
1918 struct variable *var_p;
1919 struct variable **var_pp;
1922 eq = strchr(*s, '=');
1924 var_pp = get_ptr_to_local_var(*s, eq - *s);
1926 /* Remove variable from global linked list */
1928 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1929 *var_pp = var_p->next;
1930 /* Add it to returned list */
1934 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1945 static int FAST_FUNC static_get(struct in_str *i)
1956 static int FAST_FUNC static_peek(struct in_str *i)
1961 #if ENABLE_HUSH_INTERACTIVE
1963 static void cmdedit_update_prompt(void)
1965 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1966 G.PS1 = get_local_var_value("PS1");
1969 G.PS2 = get_local_var_value("PS2");
1977 static const char *setup_prompt_string(int promptmode)
1979 const char *prompt_str;
1980 debug_printf("setup_prompt_string %d ", promptmode);
1981 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1982 /* Set up the prompt */
1983 if (promptmode == 0) { /* PS1 */
1985 /* bash uses $PWD value, even if it is set by user.
1986 * It uses current dir only if PWD is unset.
1987 * We always use current dir. */
1988 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
1993 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1994 debug_printf("result '%s'\n", prompt_str);
1998 static void get_user_input(struct in_str *i)
2001 const char *prompt_str;
2003 prompt_str = setup_prompt_string(i->promptmode);
2004 # if ENABLE_FEATURE_EDITING
2005 /* Enable command line editing only while a command line
2006 * is actually being read */
2008 /* Unicode support should be activated even if LANG is set
2009 * _during_ shell execution, not only if it was set when
2010 * shell was started. Therefore, re-check LANG every time:
2012 reinit_unicode(get_local_var_value("LANG"));
2015 /* buglet: SIGINT will not make new prompt to appear _at once_,
2016 * only after <Enter>. (^C will work) */
2017 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2018 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2019 check_and_run_traps();
2020 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2021 i->eof_flag = (r < 0);
2022 if (i->eof_flag) { /* EOF/error detected */
2023 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2024 G.user_input_buf[1] = '\0';
2029 if (i->last_char == '\0' || i->last_char == '\n') {
2030 /* Why check_and_run_traps here? Try this interactively:
2031 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2032 * $ <[enter], repeatedly...>
2033 * Without check_and_run_traps, handler never runs.
2035 check_and_run_traps();
2036 fputs(prompt_str, stdout);
2039 G.user_input_buf[0] = r = fgetc(i->file);
2040 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2041 } while (G.flag_SIGINT);
2042 i->eof_flag = (r == EOF);
2044 i->p = G.user_input_buf;
2047 #endif /* INTERACTIVE */
2049 /* This is the magic location that prints prompts
2050 * and gets data back from the user */
2051 static int FAST_FUNC file_get(struct in_str *i)
2055 /* If there is data waiting, eat it up */
2056 if (i->p && *i->p) {
2057 #if ENABLE_HUSH_INTERACTIVE
2061 if (i->eof_flag && !*i->p)
2063 /* note: ch is never NUL */
2065 /* need to double check i->file because we might be doing something
2066 * more complicated by now, like sourcing or substituting. */
2067 #if ENABLE_HUSH_INTERACTIVE
2068 if (G_interactive_fd && i->file == stdin) {
2071 } while (!*i->p); /* need non-empty line */
2072 i->promptmode = 1; /* PS2 */
2076 do ch = fgetc(i->file); while (ch == '\0');
2078 debug_printf("file_get: got '%c' %d\n", ch, ch);
2083 /* All callers guarantee this routine will never
2084 * be used right after a newline, so prompting is not needed.
2086 static int FAST_FUNC file_peek(struct in_str *i)
2089 if (i->p && *i->p) {
2090 if (i->eof_flag && !i->p[1])
2093 /* note: ch is never NUL */
2095 do ch = fgetc(i->file); while (ch == '\0');
2096 i->eof_flag = (ch == EOF);
2097 i->peek_buf[0] = ch;
2098 i->peek_buf[1] = '\0';
2100 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2104 static void setup_file_in_str(struct in_str *i, FILE *f)
2106 memset(i, 0, sizeof(*i));
2107 i->peek = file_peek;
2109 /* i->promptmode = 0; - PS1 (memset did it) */
2114 static void setup_string_in_str(struct in_str *i, const char *s)
2116 memset(i, 0, sizeof(*i));
2117 i->peek = static_peek;
2118 i->get = static_get;
2119 /* i->promptmode = 0; - PS1 (memset did it) */
2121 /* i->eof_flag = 0; */
2128 #define B_CHUNK (32 * sizeof(char*))
2130 static void o_reset_to_empty_unquoted(o_string *o)
2133 o->has_quoted_part = 0;
2138 static void o_free(o_string *o)
2141 memset(o, 0, sizeof(*o));
2144 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2149 static void o_grow_by(o_string *o, int len)
2151 if (o->length + len > o->maxlen) {
2152 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2153 o->data = xrealloc(o->data, 1 + o->maxlen);
2157 static void o_addchr(o_string *o, int ch)
2159 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2161 o->data[o->length] = ch;
2163 o->data[o->length] = '\0';
2166 static void o_addblock(o_string *o, const char *str, int len)
2169 memcpy(&o->data[o->length], str, len);
2171 o->data[o->length] = '\0';
2174 static void o_addstr(o_string *o, const char *str)
2176 o_addblock(o, str, strlen(str));
2180 static void nommu_addchr(o_string *o, int ch)
2186 # define nommu_addchr(o, str) ((void)0)
2189 static void o_addstr_with_NUL(o_string *o, const char *str)
2191 o_addblock(o, str, strlen(str) + 1);
2195 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2196 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2197 * Apparently, on unquoted $v bash still does globbing
2198 * ("v='*.txt'; echo $v" prints all .txt files),
2199 * but NOT brace expansion! Thus, there should be TWO independent
2200 * quoting mechanisms on $v expansion side: one protects
2201 * $v from brace expansion, and other additionally protects "$v" against globbing.
2202 * We have only second one.
2205 #if ENABLE_HUSH_BRACE_EXPANSION
2206 # define MAYBE_BRACES "{}"
2208 # define MAYBE_BRACES ""
2211 /* My analysis of quoting semantics tells me that state information
2212 * is associated with a destination, not a source.
2214 static void o_addqchr(o_string *o, int ch)
2217 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2222 o->data[o->length] = '\\';
2225 o->data[o->length] = ch;
2227 o->data[o->length] = '\0';
2230 static void o_addQchr(o_string *o, int ch)
2233 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2234 && strchr("*?[\\" MAYBE_BRACES, ch)
2237 o->data[o->length] = '\\';
2241 o->data[o->length] = ch;
2243 o->data[o->length] = '\0';
2246 static void o_addqblock(o_string *o, const char *str, int len)
2251 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2252 if (ordinary_cnt > len) /* paranoia */
2254 o_addblock(o, str, ordinary_cnt);
2255 if (ordinary_cnt == len)
2257 str += ordinary_cnt;
2258 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2262 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2264 o->data[o->length] = '\\';
2268 o->data[o->length] = ch;
2270 o->data[o->length] = '\0';
2274 static void o_addQblock(o_string *o, const char *str, int len)
2276 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2277 o_addblock(o, str, len);
2280 o_addqblock(o, str, len);
2283 static void o_addQstr(o_string *o, const char *str)
2285 o_addQblock(o, str, strlen(str));
2288 /* A special kind of o_string for $VAR and `cmd` expansion.
2289 * It contains char* list[] at the beginning, which is grown in 16 element
2290 * increments. Actual string data starts at the next multiple of 16 * (char*).
2291 * list[i] contains an INDEX (int!) into this string data.
2292 * It means that if list[] needs to grow, data needs to be moved higher up
2293 * but list[i]'s need not be modified.
2294 * NB: remembering how many list[i]'s you have there is crucial.
2295 * o_finalize_list() operation post-processes this structure - calculates
2296 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2298 #if DEBUG_EXPAND || DEBUG_GLOB
2299 static void debug_print_list(const char *prefix, o_string *o, int n)
2301 char **list = (char**)o->data;
2302 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2306 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2307 prefix, list, n, string_start, o->length, o->maxlen,
2308 !!(o->o_expflags & EXP_FLAG_GLOB),
2310 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2313 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2314 o->data + (int)(uintptr_t)list[i] + string_start,
2315 o->data + (int)(uintptr_t)list[i] + string_start);
2319 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2321 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2325 # define debug_print_list(prefix, o, n) ((void)0)
2328 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2329 * in list[n] so that it points past last stored byte so far.
2330 * It returns n+1. */
2331 static int o_save_ptr_helper(o_string *o, int n)
2333 char **list = (char**)o->data;
2337 if (!o->has_empty_slot) {
2338 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2339 string_len = o->length - string_start;
2340 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2341 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2342 /* list[n] points to string_start, make space for 16 more pointers */
2343 o->maxlen += 0x10 * sizeof(list[0]);
2344 o->data = xrealloc(o->data, o->maxlen + 1);
2345 list = (char**)o->data;
2346 memmove(list + n + 0x10, list + n, string_len);
2347 o->length += 0x10 * sizeof(list[0]);
2349 debug_printf_list("list[%d]=%d string_start=%d\n",
2350 n, string_len, string_start);
2353 /* We have empty slot at list[n], reuse without growth */
2354 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2355 string_len = o->length - string_start;
2356 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2357 n, string_len, string_start);
2358 o->has_empty_slot = 0;
2360 list[n] = (char*)(uintptr_t)string_len;
2364 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2365 static int o_get_last_ptr(o_string *o, int n)
2367 char **list = (char**)o->data;
2368 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2370 return ((int)(uintptr_t)list[n-1]) + string_start;
2373 #if ENABLE_HUSH_BRACE_EXPANSION
2374 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2375 * first, it processes even {a} (no commas), second,
2376 * I didn't manage to make it return strings when they don't match
2377 * existing files. Need to re-implement it.
2381 static int glob_needed(const char *s)
2390 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2396 /* Return pointer to next closing brace or to comma */
2397 static const char *next_brace_sub(const char *cp)
2401 while (*cp != '\0') {
2408 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2414 return *cp != '\0' ? cp : NULL;
2416 /* Recursive brace globber. Note: may garble pattern[]. */
2417 static int glob_brace(char *pattern, o_string *o, int n)
2419 char *new_pattern_buf;
2426 debug_printf_glob("glob_brace('%s')\n", pattern);
2432 if (*begin == '{') {
2433 /* Find the first sub-pattern and at the same time
2434 * find the rest after the closing brace */
2435 next = next_brace_sub(begin);
2437 /* An illegal expression */
2441 /* "{abc}" with no commas - illegal
2442 * brace expr, disregard and skip it */
2448 if (*begin == '\\' && begin[1] != '\0')
2452 debug_printf_glob("begin:%s\n", begin);
2453 debug_printf_glob("next:%s\n", next);
2455 /* Now find the end of the whole brace expression */
2457 while (*rest != '}') {
2458 rest = next_brace_sub(rest);
2460 /* An illegal expression */
2463 debug_printf_glob("rest:%s\n", rest);
2465 rest_len = strlen(++rest) + 1;
2467 /* We are sure the brace expression is well-formed */
2469 /* Allocate working buffer large enough for our work */
2470 new_pattern_buf = xmalloc(strlen(pattern));
2472 /* We have a brace expression. BEGIN points to the opening {,
2473 * NEXT points past the terminator of the first element, and REST
2474 * points past the final }. We will accumulate result names from
2475 * recursive runs for each brace alternative in the buffer using
2480 /* Construct the new glob expression */
2483 mempcpy(new_pattern_buf,
2484 /* We know the prefix for all sub-patterns */
2485 pattern, begin - pattern),
2489 /* Note: glob_brace() may garble new_pattern_buf[].
2490 * That's why we re-copy prefix every time (1st memcpy above).
2492 n = glob_brace(new_pattern_buf, o, n);
2494 /* We saw the last entry */
2498 next = next_brace_sub(next);
2500 free(new_pattern_buf);
2508 memset(&globdata, 0, sizeof(globdata));
2509 gr = glob(pattern, 0, NULL, &globdata);
2510 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2512 if (gr == GLOB_NOMATCH) {
2513 globfree(&globdata);
2514 /* NB: garbles parameter */
2515 unbackslash(pattern);
2516 o_addstr_with_NUL(o, pattern);
2517 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2518 return o_save_ptr_helper(o, n);
2520 if (gr == GLOB_NOSPACE)
2521 bb_error_msg_and_die(bb_msg_memory_exhausted);
2522 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2523 * but we didn't specify it. Paranoia again. */
2524 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2526 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2527 char **argv = globdata.gl_pathv;
2529 o_addstr_with_NUL(o, *argv);
2530 n = o_save_ptr_helper(o, n);
2536 globfree(&globdata);
2540 /* Performs globbing on last list[],
2541 * saving each result as a new list[].
2543 static int perform_glob(o_string *o, int n)
2545 char *pattern, *copy;
2547 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2549 return o_save_ptr_helper(o, n);
2550 pattern = o->data + o_get_last_ptr(o, n);
2551 debug_printf_glob("glob pattern '%s'\n", pattern);
2552 if (!glob_needed(pattern)) {
2553 /* unbackslash last string in o in place, fix length */
2554 o->length = unbackslash(pattern) - o->data;
2555 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2556 return o_save_ptr_helper(o, n);
2559 copy = xstrdup(pattern);
2560 /* "forget" pattern in o */
2561 o->length = pattern - o->data;
2562 n = glob_brace(copy, o, n);
2565 debug_print_list("perform_glob returning", o, n);
2569 #else /* !HUSH_BRACE_EXPANSION */
2572 static int glob_needed(const char *s)
2581 if (*s == '*' || *s == '[' || *s == '?')
2587 /* Performs globbing on last list[],
2588 * saving each result as a new list[].
2590 static int perform_glob(o_string *o, int n)
2596 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2598 return o_save_ptr_helper(o, n);
2599 pattern = o->data + o_get_last_ptr(o, n);
2600 debug_printf_glob("glob pattern '%s'\n", pattern);
2601 if (!glob_needed(pattern)) {
2603 /* unbackslash last string in o in place, fix length */
2604 o->length = unbackslash(pattern) - o->data;
2605 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2606 return o_save_ptr_helper(o, n);
2609 memset(&globdata, 0, sizeof(globdata));
2610 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2611 * If we glob "*.\*" and don't find anything, we need
2612 * to fall back to using literal "*.*", but GLOB_NOCHECK
2613 * will return "*.\*"!
2615 gr = glob(pattern, 0, NULL, &globdata);
2616 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2618 if (gr == GLOB_NOMATCH) {
2619 globfree(&globdata);
2622 if (gr == GLOB_NOSPACE)
2623 bb_error_msg_and_die(bb_msg_memory_exhausted);
2624 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2625 * but we didn't specify it. Paranoia again. */
2626 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2628 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2629 char **argv = globdata.gl_pathv;
2630 /* "forget" pattern in o */
2631 o->length = pattern - o->data;
2633 o_addstr_with_NUL(o, *argv);
2634 n = o_save_ptr_helper(o, n);
2640 globfree(&globdata);
2642 debug_print_list("perform_glob returning", o, n);
2646 #endif /* !HUSH_BRACE_EXPANSION */
2648 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2649 * Otherwise, just finish current list[] and start new */
2650 static int o_save_ptr(o_string *o, int n)
2652 if (o->o_expflags & EXP_FLAG_GLOB) {
2653 /* If o->has_empty_slot, list[n] was already globbed
2654 * (if it was requested back then when it was filled)
2655 * so don't do that again! */
2656 if (!o->has_empty_slot)
2657 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2659 return o_save_ptr_helper(o, n);
2662 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2663 static char **o_finalize_list(o_string *o, int n)
2668 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2670 debug_print_list("finalized", o, n);
2671 debug_printf_expand("finalized n:%d\n", n);
2672 list = (char**)o->data;
2673 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2677 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2682 static void free_pipe_list(struct pipe *pi);
2684 /* Returns pi->next - next pipe in the list */
2685 static struct pipe *free_pipe(struct pipe *pi)
2690 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2691 for (i = 0; i < pi->num_cmds; i++) {
2692 struct command *command;
2693 struct redir_struct *r, *rnext;
2695 command = &pi->cmds[i];
2696 debug_printf_clean(" command %d:\n", i);
2697 if (command->argv) {
2701 for (a = 0, p = command->argv; *p; a++, p++) {
2702 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2705 free_strings(command->argv);
2706 //command->argv = NULL;
2708 /* not "else if": on syntax error, we may have both! */
2709 if (command->group) {
2710 debug_printf_clean(" begin group (cmd_type:%d)\n",
2712 free_pipe_list(command->group);
2713 debug_printf_clean(" end group\n");
2714 //command->group = NULL;
2716 /* else is crucial here.
2717 * If group != NULL, child_func is meaningless */
2718 #if ENABLE_HUSH_FUNCTIONS
2719 else if (command->child_func) {
2720 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2721 command->child_func->parent_cmd = NULL;
2725 free(command->group_as_string);
2726 //command->group_as_string = NULL;
2728 for (r = command->redirects; r; r = rnext) {
2729 debug_printf_clean(" redirect %d%s",
2730 r->rd_fd, redir_table[r->rd_type].descrip);
2731 /* guard against the case >$FOO, where foo is unset or blank */
2732 if (r->rd_filename) {
2733 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2734 free(r->rd_filename);
2735 //r->rd_filename = NULL;
2737 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2741 //command->redirects = NULL;
2743 free(pi->cmds); /* children are an array, they get freed all at once */
2747 //pi->cmdtext = NULL;
2755 static void free_pipe_list(struct pipe *pi)
2759 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2761 debug_printf_clean("pipe followup code %d\n", pi->followup);
2767 /*** Parsing routines ***/
2769 #ifndef debug_print_tree
2770 static void debug_print_tree(struct pipe *pi, int lvl)
2772 static const char *const PIPE[] = {
2778 static const char *RES[] = {
2779 [RES_NONE ] = "NONE" ,
2782 [RES_THEN ] = "THEN" ,
2783 [RES_ELIF ] = "ELIF" ,
2784 [RES_ELSE ] = "ELSE" ,
2787 # if ENABLE_HUSH_LOOPS
2788 [RES_FOR ] = "FOR" ,
2789 [RES_WHILE] = "WHILE",
2790 [RES_UNTIL] = "UNTIL",
2792 [RES_DONE ] = "DONE" ,
2794 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2797 # if ENABLE_HUSH_CASE
2798 [RES_CASE ] = "CASE" ,
2799 [RES_CASE_IN ] = "CASE_IN" ,
2800 [RES_MATCH] = "MATCH",
2801 [RES_CASE_BODY] = "CASE_BODY",
2802 [RES_ESAC ] = "ESAC" ,
2804 [RES_XXXX ] = "XXXX" ,
2805 [RES_SNTX ] = "SNTX" ,
2807 static const char *const CMDTYPE[] = {
2811 # if ENABLE_HUSH_FUNCTIONS
2820 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2821 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2823 while (prn < pi->num_cmds) {
2824 struct command *command = &pi->cmds[prn];
2825 char **argv = command->argv;
2827 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2829 command->assignment_cnt);
2830 if (command->group) {
2831 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2832 CMDTYPE[command->cmd_type],
2835 , " group_as_string:", command->group_as_string
2840 debug_print_tree(command->group, lvl+1);
2844 if (argv) while (*argv) {
2845 fdprintf(2, " '%s'", *argv);
2855 #endif /* debug_print_tree */
2857 static struct pipe *new_pipe(void)
2860 pi = xzalloc(sizeof(struct pipe));
2861 /*pi->followup = 0; - deliberately invalid value */
2862 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2866 /* Command (member of a pipe) is complete, or we start a new pipe
2867 * if ctx->command is NULL.
2868 * No errors possible here.
2870 static int done_command(struct parse_context *ctx)
2872 /* The command is really already in the pipe structure, so
2873 * advance the pipe counter and make a new, null command. */
2874 struct pipe *pi = ctx->pipe;
2875 struct command *command = ctx->command;
2878 if (IS_NULL_CMD(command)) {
2879 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2883 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2884 //debug_print_tree(ctx->list_head, 20);
2886 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2889 /* Only real trickiness here is that the uncommitted
2890 * command structure is not counted in pi->num_cmds. */
2891 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2892 ctx->command = command = &pi->cmds[pi->num_cmds];
2894 memset(command, 0, sizeof(*command));
2895 return pi->num_cmds; /* used only for 0/nonzero check */
2898 static void done_pipe(struct parse_context *ctx, pipe_style type)
2902 debug_printf_parse("done_pipe entered, followup %d\n", type);
2903 /* Close previous command */
2904 not_null = done_command(ctx);
2905 ctx->pipe->followup = type;
2907 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2908 ctx->ctx_inverted = 0;
2909 ctx->pipe->res_word = ctx->ctx_res_w;
2912 /* Without this check, even just <enter> on command line generates
2913 * tree of three NOPs (!). Which is harmless but annoying.
2914 * IOW: it is safe to do it unconditionally. */
2917 || ctx->ctx_res_w == RES_FI
2919 #if ENABLE_HUSH_LOOPS
2920 || ctx->ctx_res_w == RES_DONE
2921 || ctx->ctx_res_w == RES_FOR
2922 || ctx->ctx_res_w == RES_IN
2924 #if ENABLE_HUSH_CASE
2925 || ctx->ctx_res_w == RES_ESAC
2929 debug_printf_parse("done_pipe: adding new pipe: "
2930 "not_null:%d ctx->ctx_res_w:%d\n",
2931 not_null, ctx->ctx_res_w);
2933 ctx->pipe->next = new_p;
2935 /* RES_THEN, RES_DO etc are "sticky" -
2936 * they remain set for pipes inside if/while.
2937 * This is used to control execution.
2938 * RES_FOR and RES_IN are NOT sticky (needed to support
2939 * cases where variable or value happens to match a keyword):
2941 #if ENABLE_HUSH_LOOPS
2942 if (ctx->ctx_res_w == RES_FOR
2943 || ctx->ctx_res_w == RES_IN)
2944 ctx->ctx_res_w = RES_NONE;
2946 #if ENABLE_HUSH_CASE
2947 if (ctx->ctx_res_w == RES_MATCH)
2948 ctx->ctx_res_w = RES_CASE_BODY;
2949 if (ctx->ctx_res_w == RES_CASE)
2950 ctx->ctx_res_w = RES_CASE_IN;
2952 ctx->command = NULL; /* trick done_command below */
2953 /* Create the memory for command, roughly:
2954 * ctx->pipe->cmds = new struct command;
2955 * ctx->command = &ctx->pipe->cmds[0];
2958 //debug_print_tree(ctx->list_head, 10);
2960 debug_printf_parse("done_pipe return\n");
2963 static void initialize_context(struct parse_context *ctx)
2965 memset(ctx, 0, sizeof(*ctx));
2966 ctx->pipe = ctx->list_head = new_pipe();
2967 /* Create the memory for command, roughly:
2968 * ctx->pipe->cmds = new struct command;
2969 * ctx->command = &ctx->pipe->cmds[0];
2974 /* If a reserved word is found and processed, parse context is modified
2975 * and 1 is returned.
2978 struct reserved_combo {
2981 unsigned char assignment_flag;
2985 FLAG_END = (1 << RES_NONE ),
2987 FLAG_IF = (1 << RES_IF ),
2988 FLAG_THEN = (1 << RES_THEN ),
2989 FLAG_ELIF = (1 << RES_ELIF ),
2990 FLAG_ELSE = (1 << RES_ELSE ),
2991 FLAG_FI = (1 << RES_FI ),
2993 # if ENABLE_HUSH_LOOPS
2994 FLAG_FOR = (1 << RES_FOR ),
2995 FLAG_WHILE = (1 << RES_WHILE),
2996 FLAG_UNTIL = (1 << RES_UNTIL),
2997 FLAG_DO = (1 << RES_DO ),
2998 FLAG_DONE = (1 << RES_DONE ),
2999 FLAG_IN = (1 << RES_IN ),
3001 # if ENABLE_HUSH_CASE
3002 FLAG_MATCH = (1 << RES_MATCH),
3003 FLAG_ESAC = (1 << RES_ESAC ),
3005 FLAG_START = (1 << RES_XXXX ),
3008 static const struct reserved_combo* match_reserved_word(o_string *word)
3010 /* Mostly a list of accepted follow-up reserved words.
3011 * FLAG_END means we are done with the sequence, and are ready
3012 * to turn the compound list into a command.
3013 * FLAG_START means the word must start a new compound list.
3015 static const struct reserved_combo reserved_list[] = {
3017 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3018 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3019 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3020 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3021 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3022 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3024 # if ENABLE_HUSH_LOOPS
3025 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3026 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3027 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3028 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3029 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3030 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3032 # if ENABLE_HUSH_CASE
3033 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3034 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3037 const struct reserved_combo *r;
3039 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3040 if (strcmp(word->data, r->literal) == 0)
3045 /* Return 0: not a keyword, 1: keyword
3047 static int reserved_word(o_string *word, struct parse_context *ctx)
3049 # if ENABLE_HUSH_CASE
3050 static const struct reserved_combo reserved_match = {
3051 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3054 const struct reserved_combo *r;
3056 if (word->has_quoted_part)
3058 r = match_reserved_word(word);
3062 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3063 # if ENABLE_HUSH_CASE
3064 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3065 /* "case word IN ..." - IN part starts first MATCH part */
3066 r = &reserved_match;
3069 if (r->flag == 0) { /* '!' */
3070 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3071 syntax_error("! ! command");
3072 ctx->ctx_res_w = RES_SNTX;
3074 ctx->ctx_inverted = 1;
3077 if (r->flag & FLAG_START) {
3078 struct parse_context *old;
3080 old = xmalloc(sizeof(*old));
3081 debug_printf_parse("push stack %p\n", old);
3082 *old = *ctx; /* physical copy */
3083 initialize_context(ctx);
3085 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3086 syntax_error_at(word->data);
3087 ctx->ctx_res_w = RES_SNTX;
3090 /* "{...} fi" is ok. "{...} if" is not
3092 * if { echo foo; } then { echo bar; } fi */
3093 if (ctx->command->group)
3094 done_pipe(ctx, PIPE_SEQ);
3097 ctx->ctx_res_w = r->res;
3098 ctx->old_flag = r->flag;
3099 word->o_assignment = r->assignment_flag;
3101 if (ctx->old_flag & FLAG_END) {
3102 struct parse_context *old;
3104 done_pipe(ctx, PIPE_SEQ);
3105 debug_printf_parse("pop stack %p\n", ctx->stack);
3107 old->command->group = ctx->list_head;
3108 old->command->cmd_type = CMD_NORMAL;
3110 o_addstr(&old->as_string, ctx->as_string.data);
3111 o_free_unsafe(&ctx->as_string);
3112 old->command->group_as_string = xstrdup(old->as_string.data);
3113 debug_printf_parse("pop, remembering as:'%s'\n",
3114 old->command->group_as_string);
3116 *ctx = *old; /* physical copy */
3121 #endif /* HAS_KEYWORDS */
3123 /* Word is complete, look at it and update parsing context.
3124 * Normal return is 0. Syntax errors return 1.
3125 * Note: on return, word is reset, but not o_free'd!
3127 static int done_word(o_string *word, struct parse_context *ctx)
3129 struct command *command = ctx->command;
3131 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3132 if (word->length == 0 && !word->has_quoted_part) {
3133 debug_printf_parse("done_word return 0: true null, ignored\n");
3137 if (ctx->pending_redirect) {
3138 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3139 * only if run as "bash", not "sh" */
3140 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3142 * ...the word that follows the redirection operator
3143 * shall be subjected to tilde expansion, parameter expansion,
3144 * command substitution, arithmetic expansion, and quote
3145 * removal. Pathname expansion shall not be performed
3146 * on the word by a non-interactive shell; an interactive
3147 * shell may perform it, but shall do so only when
3148 * the expansion would result in one word."
3150 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3151 /* Cater for >\file case:
3152 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3153 * Same with heredocs:
3154 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3156 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3157 unbackslash(ctx->pending_redirect->rd_filename);
3158 /* Is it <<"HEREDOC"? */
3159 if (word->has_quoted_part) {
3160 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3163 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3164 ctx->pending_redirect = NULL;
3166 /* If this word wasn't an assignment, next ones definitely
3167 * can't be assignments. Even if they look like ones. */
3168 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3169 && word->o_assignment != WORD_IS_KEYWORD
3171 word->o_assignment = NOT_ASSIGNMENT;
3173 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3174 command->assignment_cnt++;
3175 word->o_assignment = MAYBE_ASSIGNMENT;
3179 # if ENABLE_HUSH_CASE
3180 if (ctx->ctx_dsemicolon
3181 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3183 /* already done when ctx_dsemicolon was set to 1: */
3184 /* ctx->ctx_res_w = RES_MATCH; */
3185 ctx->ctx_dsemicolon = 0;
3188 if (!command->argv /* if it's the first word... */
3189 # if ENABLE_HUSH_LOOPS
3190 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3191 && ctx->ctx_res_w != RES_IN
3193 # if ENABLE_HUSH_CASE
3194 && ctx->ctx_res_w != RES_CASE
3197 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
3198 if (reserved_word(word, ctx)) {
3199 o_reset_to_empty_unquoted(word);
3200 debug_printf_parse("done_word return %d\n",
3201 (ctx->ctx_res_w == RES_SNTX));
3202 return (ctx->ctx_res_w == RES_SNTX);
3204 # if ENABLE_HUSH_BASH_COMPAT
3205 if (strcmp(word->data, "[[") == 0) {
3206 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3212 if (command->group) {
3213 /* "{ echo foo; } echo bar" - bad */
3214 syntax_error_at(word->data);
3215 debug_printf_parse("done_word return 1: syntax error, "
3216 "groups and arglists don't mix\n");
3219 if (word->has_quoted_part
3220 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3221 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3222 /* (otherwise it's known to be not empty and is already safe) */
3224 /* exclude "$@" - it can expand to no word despite "" */
3225 char *p = word->data;
3226 while (p[0] == SPECIAL_VAR_SYMBOL
3227 && (p[1] & 0x7f) == '@'
3228 && p[2] == SPECIAL_VAR_SYMBOL
3232 if (p == word->data || p[0] != '\0') {
3233 /* saw no "$@", or not only "$@" but some
3234 * real text is there too */
3235 /* insert "empty variable" reference, this makes
3236 * e.g. "", $empty"" etc to not disappear */
3237 o_addchr(word, SPECIAL_VAR_SYMBOL);
3238 o_addchr(word, SPECIAL_VAR_SYMBOL);
3241 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3242 debug_print_strings("word appended to argv", command->argv);
3245 #if ENABLE_HUSH_LOOPS
3246 if (ctx->ctx_res_w == RES_FOR) {
3247 if (word->has_quoted_part
3248 || !is_well_formed_var_name(command->argv[0], '\0')
3250 /* bash says just "not a valid identifier" */
3251 syntax_error("not a valid identifier in for");
3254 /* Force FOR to have just one word (variable name) */
3255 /* NB: basically, this makes hush see "for v in ..."
3256 * syntax as if it is "for v; in ...". FOR and IN become
3257 * two pipe structs in parse tree. */
3258 done_pipe(ctx, PIPE_SEQ);
3261 #if ENABLE_HUSH_CASE
3262 /* Force CASE to have just one word */
3263 if (ctx->ctx_res_w == RES_CASE) {
3264 done_pipe(ctx, PIPE_SEQ);
3268 o_reset_to_empty_unquoted(word);
3270 debug_printf_parse("done_word return 0\n");
3275 /* Peek ahead in the input to find out if we have a "&n" construct,
3276 * as in "2>&1", that represents duplicating a file descriptor.
3278 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3279 * REDIRFD_SYNTAX_ERR if syntax error,
3280 * REDIRFD_TO_FILE if no & was seen,
3281 * or the number found.
3284 #define parse_redir_right_fd(as_string, input) \
3285 parse_redir_right_fd(input)
3287 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3293 return REDIRFD_TO_FILE;
3295 ch = i_getch(input); /* get the & */
3296 nommu_addchr(as_string, ch);
3299 ch = i_getch(input);
3300 nommu_addchr(as_string, ch);
3301 return REDIRFD_CLOSE;
3305 while (ch != EOF && isdigit(ch)) {
3306 d = d*10 + (ch-'0');
3308 ch = i_getch(input);
3309 nommu_addchr(as_string, ch);
3314 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3316 bb_error_msg("ambiguous redirect");
3317 return REDIRFD_SYNTAX_ERR;
3320 /* Return code is 0 normal, 1 if a syntax error is detected
3322 static int parse_redirect(struct parse_context *ctx,
3325 struct in_str *input)
3327 struct command *command = ctx->command;
3328 struct redir_struct *redir;
3329 struct redir_struct **redirp;
3332 dup_num = REDIRFD_TO_FILE;
3333 if (style != REDIRECT_HEREDOC) {
3334 /* Check for a '>&1' type redirect */
3335 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3336 if (dup_num == REDIRFD_SYNTAX_ERR)
3339 int ch = i_peek(input);
3340 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3341 if (dup_num) { /* <<-... */
3342 ch = i_getch(input);
3343 nommu_addchr(&ctx->as_string, ch);
3348 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3349 int ch = i_peek(input);
3351 /* >|FILE redirect ("clobbering" >).
3352 * Since we do not support "set -o noclobber" yet,
3353 * >| and > are the same for now. Just eat |.
3355 ch = i_getch(input);
3356 nommu_addchr(&ctx->as_string, ch);
3360 /* Create a new redir_struct and append it to the linked list */
3361 redirp = &command->redirects;
3362 while ((redir = *redirp) != NULL) {
3363 redirp = &(redir->next);
3365 *redirp = redir = xzalloc(sizeof(*redir));
3366 /* redir->next = NULL; */
3367 /* redir->rd_filename = NULL; */
3368 redir->rd_type = style;
3369 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3371 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3372 redir_table[style].descrip);
3374 redir->rd_dup = dup_num;
3375 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3376 /* Erik had a check here that the file descriptor in question
3377 * is legit; I postpone that to "run time"
3378 * A "-" representation of "close me" shows up as a -3 here */
3379 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3380 redir->rd_fd, redir->rd_dup);
3382 /* Set ctx->pending_redirect, so we know what to do at the
3383 * end of the next parsed word. */
3384 ctx->pending_redirect = redir;
3389 /* If a redirect is immediately preceded by a number, that number is
3390 * supposed to tell which file descriptor to redirect. This routine
3391 * looks for such preceding numbers. In an ideal world this routine
3392 * needs to handle all the following classes of redirects...
3393 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3394 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3395 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3396 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3398 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3400 * ... If n is quoted, the number shall not be recognized as part of
3401 * the redirection expression. For example:
3403 * writes the character 2 into file a"
3404 * We are getting it right by setting ->has_quoted_part on any \<char>
3406 * A -1 return means no valid number was found,
3407 * the caller should use the appropriate default for this redirection.
3409 static int redirect_opt_num(o_string *o)
3413 if (o->data == NULL)
3415 num = bb_strtou(o->data, NULL, 10);
3416 if (errno || num < 0)
3418 o_reset_to_empty_unquoted(o);
3423 #define fetch_till_str(as_string, input, word, skip_tabs) \
3424 fetch_till_str(input, word, skip_tabs)
3426 static char *fetch_till_str(o_string *as_string,
3427 struct in_str *input,
3431 o_string heredoc = NULL_O_STRING;
3433 int prev = 0; /* not \ */
3439 ch = i_getch(input);
3441 nommu_addchr(as_string, ch);
3442 if ((ch == '\n' || ch == EOF)
3443 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3445 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3446 heredoc.data[past_EOL] = '\0';
3447 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3448 return heredoc.data;
3450 while (ch == '\n') {
3451 o_addchr(&heredoc, ch);
3454 past_EOL = heredoc.length;
3456 ch = i_getch(input);
3458 nommu_addchr(as_string, ch);
3459 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3463 o_free_unsafe(&heredoc);
3466 o_addchr(&heredoc, ch);
3467 nommu_addchr(as_string, ch);
3468 if (prev == '\\' && ch == '\\')
3469 /* Correctly handle foo\\<eol> (not a line cont.) */
3470 prev = 0; /* not \ */
3476 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3477 * and load them all. There should be exactly heredoc_cnt of them.
3479 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3481 struct pipe *pi = ctx->list_head;
3483 while (pi && heredoc_cnt) {
3485 struct command *cmd = pi->cmds;
3487 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3489 cmd->argv ? cmd->argv[0] : "NONE");
3490 for (i = 0; i < pi->num_cmds; i++) {
3491 struct redir_struct *redir = cmd->redirects;
3493 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3494 i, cmd->argv ? cmd->argv[0] : "NONE");
3496 if (redir->rd_type == REDIRECT_HEREDOC) {
3499 redir->rd_type = REDIRECT_HEREDOC2;
3500 /* redir->rd_dup is (ab)used to indicate <<- */
3501 p = fetch_till_str(&ctx->as_string, input,
3502 redir->rd_filename, redir->rd_dup);
3504 syntax_error("unexpected EOF in here document");
3507 free(redir->rd_filename);
3508 redir->rd_filename = p;
3511 redir = redir->next;
3518 /* Should be 0. If it isn't, it's a parse error */
3520 bb_error_msg_and_die("heredoc BUG 2");
3526 static int run_list(struct pipe *pi);
3528 #define parse_stream(pstring, input, end_trigger) \
3529 parse_stream(input, end_trigger)
3531 static struct pipe *parse_stream(char **pstring,
3532 struct in_str *input,
3536 #if !ENABLE_HUSH_FUNCTIONS
3537 #define parse_group(dest, ctx, input, ch) \
3538 parse_group(ctx, input, ch)
3540 static int parse_group(o_string *dest, struct parse_context *ctx,
3541 struct in_str *input, int ch)
3543 /* dest contains characters seen prior to ( or {.
3544 * Typically it's empty, but for function defs,
3545 * it contains function name (without '()'). */
3546 struct pipe *pipe_list;
3548 struct command *command = ctx->command;
3550 debug_printf_parse("parse_group entered\n");
3551 #if ENABLE_HUSH_FUNCTIONS
3552 if (ch == '(' && !dest->has_quoted_part) {
3554 if (done_word(dest, ctx))
3557 goto skip; /* (... */
3558 if (command->argv[1]) { /* word word ... (... */
3559 syntax_error_unexpected_ch('(');
3562 /* it is "word(..." or "word (..." */
3564 ch = i_getch(input);
3565 while (ch == ' ' || ch == '\t');
3567 syntax_error_unexpected_ch(ch);
3570 nommu_addchr(&ctx->as_string, ch);
3572 ch = i_getch(input);
3573 while (ch == ' ' || ch == '\t' || ch == '\n');
3575 syntax_error_unexpected_ch(ch);
3578 nommu_addchr(&ctx->as_string, ch);
3579 command->cmd_type = CMD_FUNCDEF;
3584 #if 0 /* Prevented by caller */
3585 if (command->argv /* word [word]{... */
3586 || dest->length /* word{... */
3587 || dest->has_quoted_part /* ""{... */
3590 debug_printf_parse("parse_group return 1: "
3591 "syntax error, groups and arglists don't mix\n");
3596 #if ENABLE_HUSH_FUNCTIONS
3602 command->cmd_type = CMD_SUBSHELL;
3604 /* bash does not allow "{echo...", requires whitespace */
3605 ch = i_getch(input);
3606 if (ch != ' ' && ch != '\t' && ch != '\n') {
3607 syntax_error_unexpected_ch(ch);
3610 nommu_addchr(&ctx->as_string, ch);
3615 # define as_string NULL
3617 char *as_string = NULL;
3619 pipe_list = parse_stream(&as_string, input, endch);
3622 o_addstr(&ctx->as_string, as_string);
3624 /* empty ()/{} or parse error? */
3625 if (!pipe_list || pipe_list == ERR_PTR) {
3626 /* parse_stream already emitted error msg */
3629 debug_printf_parse("parse_group return 1: "
3630 "parse_stream returned %p\n", pipe_list);
3633 command->group = pipe_list;
3635 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3636 command->group_as_string = as_string;
3637 debug_printf_parse("end of group, remembering as:'%s'\n",
3638 command->group_as_string);
3642 debug_printf_parse("parse_group return 0\n");
3644 /* command remains "open", available for possible redirects */
3647 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3648 /* Subroutines for copying $(...) and `...` things */
3649 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3651 static int add_till_single_quote(o_string *dest, struct in_str *input)
3654 int ch = i_getch(input);
3656 syntax_error_unterm_ch('\'');
3664 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3665 static int add_till_double_quote(o_string *dest, struct in_str *input)
3668 int ch = i_getch(input);
3670 syntax_error_unterm_ch('"');
3675 if (ch == '\\') { /* \x. Copy both chars. */
3677 ch = i_getch(input);
3681 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3686 //if (ch == '$') ...
3689 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3691 * "Within the backquoted style of command substitution, backslash
3692 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3693 * The search for the matching backquote shall be satisfied by the first
3694 * backquote found without a preceding backslash; during this search,
3695 * if a non-escaped backquote is encountered within a shell comment,
3696 * a here-document, an embedded command substitution of the $(command)
3697 * form, or a quoted string, undefined results occur. A single-quoted
3698 * or double-quoted string that begins, but does not end, within the
3699 * "`...`" sequence produces undefined results."
3701 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3703 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3706 int ch = i_getch(input);
3710 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3711 ch = i_getch(input);
3715 && (!in_dquote || ch != '"')
3717 o_addchr(dest, '\\');
3721 syntax_error_unterm_ch('`');
3727 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3728 * quoting and nested ()s.
3729 * "With the $(command) style of command substitution, all characters
3730 * following the open parenthesis to the matching closing parenthesis
3731 * constitute the command. Any valid shell script can be used for command,
3732 * except a script consisting solely of redirections which produces
3733 * unspecified results."
3735 * echo $(echo '(TEST)' BEST) (TEST) BEST
3736 * echo $(echo 'TEST)' BEST) TEST) BEST
3737 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3739 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3740 * can contain arbitrary constructs, just like $(cmd).
3741 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3742 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3744 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3745 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3748 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3749 # if ENABLE_HUSH_BASH_COMPAT
3750 char end_char2 = end_ch >> 8;
3752 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3755 ch = i_getch(input);
3757 syntax_error_unterm_ch(end_ch);
3760 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3763 /* we look for closing )) of $((EXPR)) */
3764 if (i_peek(input) == end_ch) {
3765 i_getch(input); /* eat second ')' */
3770 if (ch == '(' || ch == '{') {
3771 ch = (ch == '(' ? ')' : '}');
3772 if (!add_till_closing_bracket(dest, input, ch))
3778 if (!add_till_single_quote(dest, input))
3784 if (!add_till_double_quote(dest, input))
3790 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3796 /* \x. Copy verbatim. Important for \(, \) */
3797 ch = i_getch(input);
3799 syntax_error_unterm_ch(')');
3808 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3810 /* Return code: 0 for OK, 1 for syntax error */
3812 #define parse_dollar(as_string, dest, input, quote_mask) \
3813 parse_dollar(dest, input, quote_mask)
3814 #define as_string NULL
3816 static int parse_dollar(o_string *as_string,
3818 struct in_str *input, unsigned char quote_mask)
3820 int ch = i_peek(input); /* first character after the $ */
3822 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3824 ch = i_getch(input);
3825 nommu_addchr(as_string, ch);
3827 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3829 debug_printf_parse(": '%c'\n", ch);
3830 o_addchr(dest, ch | quote_mask);
3833 if (!isalnum(ch) && ch != '_')
3835 ch = i_getch(input);
3836 nommu_addchr(as_string, ch);
3838 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3839 } else if (isdigit(ch)) {
3841 ch = i_getch(input);
3842 nommu_addchr(as_string, ch);
3843 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3844 debug_printf_parse(": '%c'\n", ch);
3845 o_addchr(dest, ch | quote_mask);
3846 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3847 } else switch (ch) {
3849 case '!': /* last bg pid */
3850 case '?': /* last exit code */
3851 case '#': /* number of args */
3852 case '*': /* args */
3853 case '@': /* args */
3854 goto make_one_char_var;
3856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3858 ch = i_getch(input); /* eat '{' */
3859 nommu_addchr(as_string, ch);
3861 ch = i_getch(input); /* first char after '{' */
3862 /* It should be ${?}, or ${#var},
3863 * or even ${?+subst} - operator acting on a special variable,
3864 * or the beginning of variable name.
3867 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3870 syntax_error_unterm_str("${name}");
3871 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3874 nommu_addchr(as_string, ch);
3877 /* It's possible to just call add_till_closing_bracket() at this point.
3878 * However, this regresses some of our testsuite cases
3879 * which check invalid constructs like ${%}.
3880 * Oh well... let's check that the var name part is fine... */
3886 debug_printf_parse(": '%c'\n", ch);
3888 ch = i_getch(input);
3889 nommu_addchr(as_string, ch);
3893 if (!isalnum(ch) && ch != '_') {
3895 unsigned char last_ch;
3896 /* handle parameter expansions
3897 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3899 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3900 goto bad_dollar_syntax;
3902 /* Eat everything until closing '}' (or ':') */
3904 if (ENABLE_HUSH_BASH_COMPAT
3906 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3908 /* It's ${var:N[:M]} thing */
3909 end_ch = '}' * 0x100 + ':';
3911 if (ENABLE_HUSH_BASH_COMPAT
3914 /* It's ${var/[/]pattern[/repl]} thing */
3915 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3917 nommu_addchr(as_string, '/');
3920 end_ch = '}' * 0x100 + '/';
3926 #if ENABLE_HUSH_DOLLAR_OPS
3927 last_ch = add_till_closing_bracket(dest, input, end_ch);
3928 if (last_ch == 0) /* error? */
3931 #error Simple code to only allow ${var} is not implemented
3934 o_addstr(as_string, dest->data + pos);
3935 o_addchr(as_string, last_ch);
3938 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3939 /* close the first block: */
3940 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3941 /* while parsing N from ${var:N[:M]}
3942 * or pattern from ${var/[/]pattern[/repl]} */
3943 if ((end_ch & 0xff) == last_ch) {
3944 /* got ':' or '/'- parse the rest */
3949 if (end_ch == '}' * 0x100 + ':') {
3950 /* it's ${var:N} - emulate :999999999 */
3951 o_addstr(dest, "999999999");
3952 } /* else: it's ${var/[/]pattern} */
3957 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3960 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3964 ch = i_getch(input);
3965 nommu_addchr(as_string, ch);
3966 # if ENABLE_SH_MATH_SUPPORT
3967 if (i_peek(input) == '(') {
3968 ch = i_getch(input);
3969 nommu_addchr(as_string, ch);
3970 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3971 o_addchr(dest, /*quote_mask |*/ '+');
3974 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3975 return 0; /* error */
3977 o_addstr(as_string, dest->data + pos);
3978 o_addchr(as_string, ')');
3979 o_addchr(as_string, ')');
3981 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3985 # if ENABLE_HUSH_TICK
3986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3987 o_addchr(dest, quote_mask | '`');
3990 if (!add_till_closing_bracket(dest, input, ')'))
3991 return 0; /* error */
3993 o_addstr(as_string, dest->data + pos);
3994 o_addchr(as_string, ')');
3996 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4002 ch = i_getch(input);
4003 nommu_addchr(as_string, ch);
4005 if (isalnum(ch)) { /* it's $_name or $_123 */
4010 /* TODO: $_ and $-: */
4011 /* $_ Shell or shell script name; or last argument of last command
4012 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4013 * but in command's env, set to full pathname used to invoke it */
4014 /* $- Option flags set by set builtin or shell options (-i etc) */
4016 o_addQchr(dest, '$');
4018 debug_printf_parse("parse_dollar return 1 (ok)\n");
4024 # if ENABLE_HUSH_BASH_COMPAT
4025 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4026 encode_string(dest, input, dquote_end, process_bkslash)
4028 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4029 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4030 encode_string(dest, input, dquote_end)
4032 #define as_string NULL
4036 # if ENABLE_HUSH_BASH_COMPAT
4037 /* all parameters are needed, no macro tricks */
4039 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4040 encode_string(as_string, dest, input, dquote_end)
4043 static int encode_string(o_string *as_string,
4045 struct in_str *input,
4047 int process_bkslash)
4049 #if !ENABLE_HUSH_BASH_COMPAT
4050 const int process_bkslash = 1;
4056 ch = i_getch(input);
4058 nommu_addchr(as_string, ch);
4059 if (ch == dquote_end) { /* may be only '"' or EOF */
4060 debug_printf_parse("encode_string return 1 (ok)\n");
4063 /* note: can't move it above ch == dquote_end check! */
4065 syntax_error_unterm_ch('"');
4066 return 0; /* error */
4070 next = i_peek(input);
4072 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4073 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4074 if (process_bkslash && ch == '\\') {
4076 syntax_error("\\<eof>");
4080 * "The backslash retains its special meaning [in "..."]
4081 * only when followed by one of the following characters:
4082 * $, `, ", \, or <newline>. A double quote may be quoted
4083 * within double quotes by preceding it with a backslash."
4084 * NB: in (unquoted) heredoc, above does not apply to ",
4085 * therefore we check for it by "next == dquote_end" cond.
4087 if (next == dquote_end || strchr("$`\\\n", next)) {
4088 ch = i_getch(input); /* eat next */
4090 goto again; /* skip \<newline> */
4091 } /* else: ch remains == '\\', and we double it below: */
4092 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4093 nommu_addchr(as_string, ch);
4097 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4098 debug_printf_parse("encode_string return 0: "
4099 "parse_dollar returned 0 (error)\n");
4104 #if ENABLE_HUSH_TICK
4106 //unsigned pos = dest->length;
4107 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4108 o_addchr(dest, 0x80 | '`');
4109 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4110 return 0; /* error */
4111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4112 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4116 o_addQchr(dest, ch);
4122 * Scan input until EOF or end_trigger char.
4123 * Return a list of pipes to execute, or NULL on EOF
4124 * or if end_trigger character is met.
4125 * On syntax error, exit if shell is not interactive,
4126 * reset parsing machinery and start parsing anew,
4127 * or return ERR_PTR.
4129 static struct pipe *parse_stream(char **pstring,
4130 struct in_str *input,
4133 struct parse_context ctx;
4134 o_string dest = NULL_O_STRING;
4137 /* Single-quote triggers a bypass of the main loop until its mate is
4138 * found. When recursing, quote state is passed in via dest->o_expflags.
4140 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4141 end_trigger ? end_trigger : 'X');
4144 /* If very first arg is "" or '', dest.data may end up NULL.
4145 * Preventing this: */
4146 o_addchr(&dest, '\0');
4149 /* We used to separate words on $IFS here. This was wrong.
4150 * $IFS is used only for word splitting when $var is expanded,
4151 * here we should use blank chars as separators, not $IFS
4154 if (MAYBE_ASSIGNMENT != 0)
4155 dest.o_assignment = MAYBE_ASSIGNMENT;
4156 initialize_context(&ctx);
4159 const char *is_blank;
4160 const char *is_special;
4164 redir_type redir_style;
4166 ch = i_getch(input);
4167 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4168 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4173 syntax_error_unterm_str("here document");
4176 /* end_trigger == '}' case errors out earlier,
4177 * checking only ')' */
4178 if (end_trigger == ')') {
4179 syntax_error_unterm_ch('(');
4183 if (done_word(&dest, &ctx)) {
4187 done_pipe(&ctx, PIPE_SEQ);
4189 /* If we got nothing... */
4190 /* (this makes bare "&" cmd a no-op.
4191 * bash says: "syntax error near unexpected token '&'") */
4192 if (pi->num_cmds == 0
4193 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4199 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4201 *pstring = ctx.as_string.data;
4203 o_free_unsafe(&ctx.as_string);
4206 debug_printf_parse("parse_stream return %p\n", pi);
4209 nommu_addchr(&ctx.as_string, ch);
4213 next = i_peek(input);
4215 is_special = "{}<>;&|()#'" /* special outside of "str" */
4216 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4217 /* Are { and } special here? */
4218 if (ctx.command->argv /* word [word]{... - non-special */
4219 || dest.length /* word{... - non-special */
4220 || dest.has_quoted_part /* ""{... - non-special */
4221 || (next != ';' /* }; - special */
4222 && next != ')' /* }) - special */
4223 && next != '&' /* }& and }&& ... - special */
4224 && next != '|' /* }|| ... - special */
4225 && !strchr(defifs, next) /* {word - non-special */
4228 /* They are not special, skip "{}" */
4231 is_special = strchr(is_special, ch);
4232 is_blank = strchr(defifs, ch);
4234 if (!is_special && !is_blank) { /* ordinary char */
4236 o_addQchr(&dest, ch);
4237 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4238 || dest.o_assignment == WORD_IS_KEYWORD)
4240 && is_well_formed_var_name(dest.data, '=')
4242 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4248 if (done_word(&dest, &ctx)) {
4252 /* Is this a case when newline is simply ignored?
4254 * "cmd | <newline> cmd ..."
4255 * "case ... in <newline> word) ..."
4257 if (IS_NULL_CMD(ctx.command)
4258 && dest.length == 0 && !dest.has_quoted_part
4260 /* This newline can be ignored. But...
4261 * Without check #1, interactive shell
4262 * ignores even bare <newline>,
4263 * and shows the continuation prompt:
4264 * ps1_prompt$ <enter>
4265 * ps2> _ <=== wrong, should be ps1
4266 * Without check #2, "cmd & <newline>"
4267 * is similarly mistreated.
4268 * (BTW, this makes "cmd & cmd"
4269 * and "cmd && cmd" non-orthogonal.
4270 * Really, ask yourself, why
4271 * "cmd && <newline>" doesn't start
4272 * cmd but waits for more input?
4275 struct pipe *pi = ctx.list_head;
4276 if (pi->num_cmds != 0 /* check #1 */
4277 && pi->followup != PIPE_BG /* check #2 */
4282 /* Treat newline as a command separator. */
4283 done_pipe(&ctx, PIPE_SEQ);
4284 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4286 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4291 dest.o_assignment = MAYBE_ASSIGNMENT;
4293 /* note: if (is_blank) continue;
4294 * will still trigger for us */
4298 /* "cmd}" or "cmd }..." without semicolon or &:
4299 * } is an ordinary char in this case, even inside { cmd; }
4300 * Pathological example: { ""}; } should exec "}" cmd
4303 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4304 || dest.length != 0 /* word} */
4305 || dest.has_quoted_part /* ""} */
4309 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4310 goto skip_end_trigger;
4311 /* else: } does terminate a group */
4314 if (end_trigger && end_trigger == ch
4315 && (ch != ';' || heredoc_cnt == 0)
4316 #if ENABLE_HUSH_CASE
4318 || ctx.ctx_res_w != RES_MATCH
4319 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4324 /* This is technically valid:
4325 * { cat <<HERE; }; echo Ok
4329 * but we don't support this.
4330 * We require heredoc to be in enclosing {}/(),
4333 syntax_error_unterm_str("here document");
4336 if (done_word(&dest, &ctx)) {
4339 done_pipe(&ctx, PIPE_SEQ);
4340 dest.o_assignment = MAYBE_ASSIGNMENT;
4341 /* Do we sit outside of any if's, loops or case's? */
4343 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4347 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4349 *pstring = ctx.as_string.data;
4351 o_free_unsafe(&ctx.as_string);
4354 debug_printf_parse("parse_stream return %p: "
4355 "end_trigger char found\n",
4357 return ctx.list_head;
4364 /* Catch <, > before deciding whether this word is
4365 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4368 redir_fd = redirect_opt_num(&dest);
4369 if (done_word(&dest, &ctx)) {
4372 redir_style = REDIRECT_OVERWRITE;
4374 redir_style = REDIRECT_APPEND;
4375 ch = i_getch(input);
4376 nommu_addchr(&ctx.as_string, ch);
4379 else if (next == '(') {
4380 syntax_error(">(process) not supported");
4384 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4386 continue; /* back to top of while (1) */
4388 redir_fd = redirect_opt_num(&dest);
4389 if (done_word(&dest, &ctx)) {
4392 redir_style = REDIRECT_INPUT;
4394 redir_style = REDIRECT_HEREDOC;
4396 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4397 ch = i_getch(input);
4398 nommu_addchr(&ctx.as_string, ch);
4399 } else if (next == '>') {
4400 redir_style = REDIRECT_IO;
4401 ch = i_getch(input);
4402 nommu_addchr(&ctx.as_string, ch);
4405 else if (next == '(') {
4406 syntax_error("<(process) not supported");
4410 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4412 continue; /* back to top of while (1) */
4414 if (dest.length == 0 && !dest.has_quoted_part) {
4415 /* skip "#comment" */
4418 if (ch == EOF || ch == '\n')
4421 /* note: we do not add it to &ctx.as_string */
4423 nommu_addchr(&ctx.as_string, '\n');
4424 continue; /* back to top of while (1) */
4429 /* It's "\<newline>" */
4431 /* Remove trailing '\' from ctx.as_string */
4432 ctx.as_string.data[--ctx.as_string.length] = '\0';
4434 ch = i_getch(input); /* eat it */
4435 continue; /* back to top of while (1) */
4440 if (dest.o_assignment == MAYBE_ASSIGNMENT
4441 /* check that we are not in word in "a=1 2>word b=1": */
4442 && !ctx.pending_redirect
4444 /* ch is a special char and thus this word
4445 * cannot be an assignment */
4446 dest.o_assignment = NOT_ASSIGNMENT;
4449 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4452 case '#': /* non-comment #: "echo a#b" etc */
4453 o_addQchr(&dest, ch);
4457 syntax_error("\\<eof>");
4460 ch = i_getch(input);
4461 /* note: ch != '\n' (that case does not reach this place) */
4462 o_addchr(&dest, '\\');
4463 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4464 o_addchr(&dest, ch);
4465 nommu_addchr(&ctx.as_string, ch);
4466 /* Example: echo Hello \2>file
4467 * we need to know that word 2 is quoted */
4468 dest.has_quoted_part = 1;
4471 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4472 debug_printf_parse("parse_stream parse error: "
4473 "parse_dollar returned 0 (error)\n");
4478 dest.has_quoted_part = 1;
4480 ch = i_getch(input);
4482 syntax_error_unterm_ch('\'');
4485 nommu_addchr(&ctx.as_string, ch);
4488 o_addqchr(&dest, ch);
4492 dest.has_quoted_part = 1;
4493 if (dest.o_assignment == NOT_ASSIGNMENT)
4494 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4495 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4497 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4499 #if ENABLE_HUSH_TICK
4503 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4504 o_addchr(&dest, '`');
4506 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4509 o_addstr(&ctx.as_string, dest.data + pos);
4510 o_addchr(&ctx.as_string, '`');
4512 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4513 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4518 #if ENABLE_HUSH_CASE
4521 if (done_word(&dest, &ctx)) {
4524 done_pipe(&ctx, PIPE_SEQ);
4525 #if ENABLE_HUSH_CASE
4526 /* Eat multiple semicolons, detect
4527 * whether it means something special */
4532 ch = i_getch(input);
4533 nommu_addchr(&ctx.as_string, ch);
4534 if (ctx.ctx_res_w == RES_CASE_BODY) {
4535 ctx.ctx_dsemicolon = 1;
4536 ctx.ctx_res_w = RES_MATCH;
4542 /* We just finished a cmd. New one may start
4543 * with an assignment */
4544 dest.o_assignment = MAYBE_ASSIGNMENT;
4547 if (done_word(&dest, &ctx)) {
4551 ch = i_getch(input);
4552 nommu_addchr(&ctx.as_string, ch);
4553 done_pipe(&ctx, PIPE_AND);
4555 done_pipe(&ctx, PIPE_BG);
4559 if (done_word(&dest, &ctx)) {
4562 #if ENABLE_HUSH_CASE
4563 if (ctx.ctx_res_w == RES_MATCH)
4564 break; /* we are in case's "word | word)" */
4566 if (next == '|') { /* || */
4567 ch = i_getch(input);
4568 nommu_addchr(&ctx.as_string, ch);
4569 done_pipe(&ctx, PIPE_OR);
4571 /* we could pick up a file descriptor choice here
4572 * with redirect_opt_num(), but bash doesn't do it.
4573 * "echo foo 2| cat" yields "foo 2". */
4576 o_reset_to_empty_unquoted(&ctx.as_string);
4581 #if ENABLE_HUSH_CASE
4582 /* "case... in [(]word)..." - skip '(' */
4583 if (ctx.ctx_res_w == RES_MATCH
4584 && ctx.command->argv == NULL /* not (word|(... */
4585 && dest.length == 0 /* not word(... */
4586 && dest.has_quoted_part == 0 /* not ""(... */
4592 if (parse_group(&dest, &ctx, input, ch) != 0) {
4597 #if ENABLE_HUSH_CASE
4598 if (ctx.ctx_res_w == RES_MATCH)
4602 /* proper use of this character is caught by end_trigger:
4603 * if we see {, we call parse_group(..., end_trigger='}')
4604 * and it will match } earlier (not here). */
4605 syntax_error_unexpected_ch(ch);
4609 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4615 struct parse_context *pctx;
4616 IF_HAS_KEYWORDS(struct parse_context *p2;)
4618 /* Clean up allocated tree.
4619 * Sample for finding leaks on syntax error recovery path.
4620 * Run it from interactive shell, watch pmap `pidof hush`.
4621 * while if false; then false; fi; do break; fi
4622 * Samples to catch leaks at execution:
4623 * while if (true | {true;}); then echo ok; fi; do break; done
4624 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4628 /* Update pipe/command counts,
4629 * otherwise freeing may miss some */
4630 done_pipe(pctx, PIPE_SEQ);
4631 debug_printf_clean("freeing list %p from ctx %p\n",
4632 pctx->list_head, pctx);
4633 debug_print_tree(pctx->list_head, 0);
4634 free_pipe_list(pctx->list_head);
4635 debug_printf_clean("freed list %p\n", pctx->list_head);
4637 o_free_unsafe(&pctx->as_string);
4639 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4643 IF_HAS_KEYWORDS(pctx = p2;)
4644 } while (HAS_KEYWORDS && pctx);
4647 G.last_exitcode = 1;
4658 /*** Execution routines ***/
4660 /* Expansion can recurse, need forward decls: */
4661 #if !ENABLE_HUSH_BASH_COMPAT
4662 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4663 #define expand_string_to_string(str, do_unbackslash) \
4664 expand_string_to_string(str)
4666 static char *expand_string_to_string(const char *str, int do_unbackslash);
4667 #if ENABLE_HUSH_TICK
4668 static int process_command_subs(o_string *dest, const char *s);
4671 /* expand_strvec_to_strvec() takes a list of strings, expands
4672 * all variable references within and returns a pointer to
4673 * a list of expanded strings, possibly with larger number
4674 * of strings. (Think VAR="a b"; echo $VAR).
4675 * This new list is allocated as a single malloc block.
4676 * NULL-terminated list of char* pointers is at the beginning of it,
4677 * followed by strings themselves.
4678 * Caller can deallocate entire list by single free(list). */
4680 /* A horde of its helpers come first: */
4682 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4684 while (--len >= 0) {
4687 #if ENABLE_HUSH_BRACE_EXPANSION
4688 if (c == '{' || c == '}') {
4689 /* { -> \{, } -> \} */
4691 /* And now we want to add { or } and continue:
4694 * luckily, just falling throught achieves this.
4700 /* \z -> \\\z; \<eol> -> \\<eol> */
4705 o_addchr(o, *str++);
4711 /* Store given string, finalizing the word and starting new one whenever
4712 * we encounter IFS char(s). This is used for expanding variable values.
4713 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4714 static int expand_on_ifs(o_string *output, int n, const char *str)
4717 int word_len = strcspn(str, G.ifs);
4719 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4720 o_addblock(output, str, word_len);
4722 /* Protect backslashes against globbing up :)
4723 * Example: "v='\*'; echo b$v" prints "b\*"
4724 * (and does not try to glob on "*")
4726 o_addblock_duplicate_backslash(output, str, word_len);
4727 /*/ Why can't we do it easier? */
4728 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4729 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4733 if (!*str) /* EOL - do not finalize word */
4735 o_addchr(output, '\0');
4736 debug_print_list("expand_on_ifs", output, n);
4737 n = o_save_ptr(output, n);
4738 str += strspn(str, G.ifs); /* skip ifs chars */
4740 debug_print_list("expand_on_ifs[1]", output, n);
4744 /* Helper to expand $((...)) and heredoc body. These act as if
4745 * they are in double quotes, with the exception that they are not :).
4746 * Just the rules are similar: "expand only $var and `cmd`"
4748 * Returns malloced string.
4749 * As an optimization, we return NULL if expansion is not needed.
4751 #if !ENABLE_HUSH_BASH_COMPAT
4752 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4753 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4754 encode_then_expand_string(str)
4756 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4759 struct in_str input;
4760 o_string dest = NULL_O_STRING;
4762 if (!strchr(str, '$')
4763 && !strchr(str, '\\')
4764 #if ENABLE_HUSH_TICK
4765 && !strchr(str, '`')
4771 /* We need to expand. Example:
4772 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4774 setup_string_in_str(&input, str);
4775 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4776 //TODO: error check (encode_string returns 0 on error)?
4777 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4778 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4779 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4780 o_free_unsafe(&dest);
4784 #if ENABLE_SH_MATH_SUPPORT
4785 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4787 arith_state_t math_state;
4791 math_state.lookupvar = get_local_var_value;
4792 math_state.setvar = set_local_var_from_halves;
4793 //math_state.endofname = endofname;
4794 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4795 res = arith(&math_state, exp_str ? exp_str : arg);
4798 *errmsg_p = math_state.errmsg;
4799 if (math_state.errmsg)
4800 die_if_script(math_state.errmsg);
4805 #if ENABLE_HUSH_BASH_COMPAT
4806 /* ${var/[/]pattern[/repl]} helpers */
4807 static char *strstr_pattern(char *val, const char *pattern, int *size)
4810 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4811 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4818 /* Optimization: if "*pat" did not match the start of "string",
4819 * we know that "tring", "ring" etc will not match too:
4821 if (pattern[0] == '*')
4826 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4828 char *result = NULL;
4829 unsigned res_len = 0;
4830 unsigned repl_len = strlen(repl);
4834 char *s = strstr_pattern(val, pattern, &size);
4838 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4839 memcpy(result + res_len, val, s - val);
4841 strcpy(result + res_len, repl);
4842 res_len += repl_len;
4843 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4849 if (val[0] && result) {
4850 result = xrealloc(result, res_len + strlen(val) + 1);
4851 strcpy(result + res_len, val);
4852 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4854 debug_printf_varexp("result:'%s'\n", result);
4860 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4862 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4864 const char *val = NULL;
4865 char *to_be_freed = NULL;
4870 char exp_save = exp_save; /* for compiler */
4871 char *exp_saveptr; /* points to expansion operator */
4872 char *exp_word = exp_word; /* for compiler */
4875 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4877 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4879 first_char = arg[0] = arg0 & 0x7f;
4882 if (first_char == '#' /* ${#... */
4883 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4885 /* It must be length operator: ${#var} */
4889 /* Maybe handle parameter expansion */
4890 if (exp_saveptr /* if 2nd char is one of expansion operators */
4891 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4893 /* ${?:0}, ${#[:]%0} etc */
4894 exp_saveptr = var + 1;
4896 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4897 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4899 exp_op = exp_save = *exp_saveptr;
4901 exp_word = exp_saveptr + 1;
4902 if (exp_op == ':') {
4903 exp_op = *exp_word++;
4904 //TODO: try ${var:} and ${var:bogus} in non-bash config
4905 if (ENABLE_HUSH_BASH_COMPAT
4906 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4908 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4913 *exp_saveptr = '\0';
4914 } /* else: it's not an expansion op, but bare ${var} */
4917 /* Look up the variable in question */
4918 if (isdigit(var[0])) {
4919 /* parse_dollar should have vetted var for us */
4920 int n = xatoi_positive(var);
4921 if (n < G.global_argc)
4922 val = G.global_argv[n];
4923 /* else val remains NULL: $N with too big N */
4927 val = utoa(G.root_pid);
4929 case '!': /* bg pid */
4930 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4932 case '?': /* exitcode */
4933 val = utoa(G.last_exitcode);
4935 case '#': /* argc */
4936 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4939 val = get_local_var_value(var);
4943 /* Handle any expansions */
4944 if (exp_op == 'L') {
4945 debug_printf_expand("expand: length(%s)=", val);
4946 val = utoa(val ? strlen(val) : 0);
4947 debug_printf_expand("%s\n", val);
4948 } else if (exp_op) {
4949 if (exp_op == '%' || exp_op == '#') {
4950 /* Standard-mandated substring removal ops:
4951 * ${parameter%word} - remove smallest suffix pattern
4952 * ${parameter%%word} - remove largest suffix pattern
4953 * ${parameter#word} - remove smallest prefix pattern
4954 * ${parameter##word} - remove largest prefix pattern
4956 * Word is expanded to produce a glob pattern.
4957 * Then var's value is matched to it and matching part removed.
4959 if (val && val[0]) {
4963 unsigned scan_flags = pick_scan(exp_op, *exp_word);
4964 if (exp_op == *exp_word) /* ## or %% */
4966 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4968 exp_word = exp_exp_word;
4969 /* HACK ALERT. We depend here on the fact that
4970 * G.global_argv and results of utoa and get_local_var_value
4971 * are actually in writable memory:
4972 * scan_and_match momentarily stores NULs there. */
4974 loc = scan_and_match(t, exp_word, scan_flags);
4975 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
4976 // exp_op, t, exp_word, loc);
4978 if (loc) { /* match was found */
4979 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
4980 val = loc; /* take right part */
4982 val = to_be_freed = xstrndup(val, loc - val); /* left */
4986 #if ENABLE_HUSH_BASH_COMPAT
4987 else if (exp_op == '/' || exp_op == '\\') {
4988 /* It's ${var/[/]pattern[/repl]} thing.
4989 * Note that in encoded form it has TWO parts:
4990 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4991 * and if // is used, it is encoded as \:
4992 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
4994 /* Empty variable always gives nothing: */
4995 // "v=''; echo ${v/*/w}" prints "", not "w"
4996 if (val && val[0]) {
4997 /* pattern uses non-standard expansion.
4998 * repl should be unbackslashed and globbed
4999 * by the usual expansion rules:
5001 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5002 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5003 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5004 * v='a bz'; echo ${v/a*z/\z} prints "z"
5005 * (note that a*z _pattern_ is never globbed!)
5007 char *pattern, *repl, *t;
5008 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5010 pattern = xstrdup(exp_word);
5011 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5012 *p++ = SPECIAL_VAR_SYMBOL;
5014 p = strchr(p, SPECIAL_VAR_SYMBOL);
5016 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5017 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5018 /* HACK ALERT. We depend here on the fact that
5019 * G.global_argv and results of utoa and get_local_var_value
5020 * are actually in writable memory:
5021 * replace_pattern momentarily stores NULs there. */
5023 to_be_freed = replace_pattern(t,
5025 (repl ? repl : exp_word),
5027 if (to_be_freed) /* at least one replace happened */
5034 else if (exp_op == ':') {
5035 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5036 /* It's ${var:N[:M]} bashism.
5037 * Note that in encoded form it has TWO parts:
5038 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5043 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5046 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5047 *p++ = SPECIAL_VAR_SYMBOL;
5049 p = strchr(p, SPECIAL_VAR_SYMBOL);
5051 len = expand_and_evaluate_arith(exp_word, &errmsg);
5054 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5055 if (len >= 0) { /* bash compat: len < 0 is illegal */
5056 if (beg < 0) /* bash compat */
5058 debug_printf_varexp("from val:'%s'\n", val);
5059 if (len == 0 || !val || beg >= strlen(val)) {
5063 /* Paranoia. What if user entered 9999999999999
5064 * which fits in arith_t but not int? */
5067 val = to_be_freed = xstrndup(val + beg, len);
5069 debug_printf_varexp("val:'%s'\n", val);
5073 die_if_script("malformed ${%s:...}", var);
5076 } else { /* one of "-=+?" */
5077 /* Standard-mandated substitution ops:
5078 * ${var?word} - indicate error if unset
5079 * If var is unset, word (or a message indicating it is unset
5080 * if word is null) is written to standard error
5081 * and the shell exits with a non-zero exit status.
5082 * Otherwise, the value of var is substituted.
5083 * ${var-word} - use default value
5084 * If var is unset, word is substituted.
5085 * ${var=word} - assign and use default value
5086 * If var is unset, word is assigned to var.
5087 * In all cases, final value of var is substituted.
5088 * ${var+word} - use alternative value
5089 * If var is unset, null is substituted.
5090 * Otherwise, word is substituted.
5092 * Word is subjected to tilde expansion, parameter expansion,
5093 * command substitution, and arithmetic expansion.
5094 * If word is not needed, it is not expanded.
5096 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5097 * but also treat null var as if it is unset.
5099 int use_word = (!val || ((exp_save == ':') && !val[0]));
5101 use_word = !use_word;
5102 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5103 (exp_save == ':') ? "true" : "false", use_word);
5105 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5107 exp_word = to_be_freed;
5108 if (exp_op == '?') {
5109 /* mimic bash message */
5110 die_if_script("%s: %s",
5112 exp_word[0] ? exp_word : "parameter null or not set"
5114 //TODO: how interactive bash aborts expansion mid-command?
5119 if (exp_op == '=') {
5120 /* ${var=[word]} or ${var:=[word]} */
5121 if (isdigit(var[0]) || var[0] == '#') {
5122 /* mimic bash message */
5123 die_if_script("$%s: cannot assign in this way", var);
5126 char *new_var = xasprintf("%s=%s", var, val);
5127 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5131 } /* one of "-=+?" */
5133 *exp_saveptr = exp_save;
5139 *to_be_freed_pp = to_be_freed;
5143 /* Expand all variable references in given string, adding words to list[]
5144 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5145 * to be filled). This routine is extremely tricky: has to deal with
5146 * variables/parameters with whitespace, $* and $@, and constructs like
5147 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5148 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5150 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5151 * expansion of right-hand side of assignment == 1-element expand.
5153 char cant_be_null = 0; /* only bit 0x80 matters */
5156 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5157 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5158 debug_print_list("expand_vars_to_list", output, n);
5159 n = o_save_ptr(output, n);
5160 debug_print_list("expand_vars_to_list[0]", output, n);
5162 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5164 char *to_be_freed = NULL;
5165 const char *val = NULL;
5166 #if ENABLE_HUSH_TICK
5167 o_string subst_result = NULL_O_STRING;
5169 #if ENABLE_SH_MATH_SUPPORT
5170 char arith_buf[sizeof(arith_t)*3 + 2];
5172 o_addblock(output, arg, p - arg);
5173 debug_print_list("expand_vars_to_list[1]", output, n);
5175 p = strchr(p, SPECIAL_VAR_SYMBOL);
5177 /* Fetch special var name (if it is indeed one of them)
5178 * and quote bit, force the bit on if singleword expansion -
5179 * important for not getting v=$@ expand to many words. */
5180 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5182 /* Is this variable quoted and thus expansion can't be null?
5183 * "$@" is special. Even if quoted, it can still
5184 * expand to nothing (not even an empty string),
5185 * thus it is excluded. */
5186 if ((first_ch & 0x7f) != '@')
5187 cant_be_null |= first_ch;
5189 switch (first_ch & 0x7f) {
5190 /* Highest bit in first_ch indicates that var is double-quoted */
5194 if (!G.global_argv[1])
5197 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5198 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5199 while (G.global_argv[i]) {
5200 n = expand_on_ifs(output, n, G.global_argv[i]);
5201 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5202 if (G.global_argv[i++][0] && G.global_argv[i]) {
5203 /* this argv[] is not empty and not last:
5204 * put terminating NUL, start new word */
5205 o_addchr(output, '\0');
5206 debug_print_list("expand_vars_to_list[2]", output, n);
5207 n = o_save_ptr(output, n);
5208 debug_print_list("expand_vars_to_list[3]", output, n);
5212 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5213 * and in this case should treat it like '$*' - see 'else...' below */
5214 if (first_ch == ('@'|0x80) /* quoted $@ */
5215 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5218 o_addQstr(output, G.global_argv[i]);
5219 if (++i >= G.global_argc)
5221 o_addchr(output, '\0');
5222 debug_print_list("expand_vars_to_list[4]", output, n);
5223 n = o_save_ptr(output, n);
5225 } else { /* quoted $* (or v="$@" case): add as one word */
5227 o_addQstr(output, G.global_argv[i]);
5228 if (!G.global_argv[++i])
5231 o_addchr(output, G.ifs[0]);
5236 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5237 /* "Empty variable", used to make "" etc to not disappear */
5239 cant_be_null = 0x80;
5241 #if ENABLE_HUSH_TICK
5242 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5243 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5245 /* Can't just stuff it into output o_string,
5246 * expanded result may need to be globbed
5247 * and $IFS-splitted */
5248 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5249 G.last_exitcode = process_command_subs(&subst_result, arg);
5250 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5251 val = subst_result.data;
5254 #if ENABLE_SH_MATH_SUPPORT
5255 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5258 arg++; /* skip '+' */
5259 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5260 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5261 res = expand_and_evaluate_arith(arg, NULL);
5262 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5263 sprintf(arith_buf, ARITH_FMT, res);
5269 val = expand_one_var(&to_be_freed, arg, &p);
5270 IF_HUSH_TICK(store_val:)
5271 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5272 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5273 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5274 if (val && val[0]) {
5275 n = expand_on_ifs(output, n, val);
5278 } else { /* quoted $VAR, val will be appended below */
5279 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5280 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5284 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5286 if (val && val[0]) {
5287 o_addQstr(output, val);
5291 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5292 * Do the check to avoid writing to a const string. */
5293 if (*p != SPECIAL_VAR_SYMBOL)
5294 *p = SPECIAL_VAR_SYMBOL;
5296 #if ENABLE_HUSH_TICK
5297 o_free(&subst_result);
5300 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5303 debug_print_list("expand_vars_to_list[a]", output, n);
5304 /* this part is literal, and it was already pre-quoted
5305 * if needed (much earlier), do not use o_addQstr here! */
5306 o_addstr_with_NUL(output, arg);
5307 debug_print_list("expand_vars_to_list[b]", output, n);
5308 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5309 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5312 /* allow to reuse list[n] later without re-growth */
5313 output->has_empty_slot = 1;
5315 o_addchr(output, '\0');
5321 static char **expand_variables(char **argv, unsigned expflags)
5325 o_string output = NULL_O_STRING;
5327 output.o_expflags = expflags;
5331 n = expand_vars_to_list(&output, n, *argv);
5334 debug_print_list("expand_variables", &output, n);
5336 /* output.data (malloced in one block) gets returned in "list" */
5337 list = o_finalize_list(&output, n);
5338 debug_print_strings("expand_variables[1]", list);
5342 static char **expand_strvec_to_strvec(char **argv)
5344 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5347 #if ENABLE_HUSH_BASH_COMPAT
5348 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5350 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5354 /* Used for expansion of right hand of assignments,
5355 * $((...)), heredocs, variable espansion parts.
5357 * NB: should NOT do globbing!
5358 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5360 static char *expand_string_to_string(const char *str, int do_unbackslash)
5362 #if !ENABLE_HUSH_BASH_COMPAT
5363 const int do_unbackslash = 1;
5365 char *argv[2], **list;
5367 debug_printf_expand("string_to_string<='%s'\n", str);
5368 /* This is generally an optimization, but it also
5369 * handles "", which otherwise trips over !list[0] check below.
5370 * (is this ever happens that we actually get str="" here?)
5372 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5373 //TODO: Can use on strings with \ too, just unbackslash() them?
5374 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5375 return xstrdup(str);
5378 argv[0] = (char*)str;
5380 list = expand_variables(argv, do_unbackslash
5381 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5382 : EXP_FLAG_SINGLEWORD
5385 if (!list[0] || list[1])
5386 bb_error_msg_and_die("BUG in varexp2");
5387 /* actually, just move string 2*sizeof(char*) bytes back */
5388 overlapping_strcpy((char*)list, list[0]);
5390 unbackslash((char*)list);
5391 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5395 /* Used for "eval" builtin */
5396 static char* expand_strvec_to_string(char **argv)
5400 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5401 /* Convert all NULs to spaces */
5406 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5407 bb_error_msg_and_die("BUG in varexp3");
5408 /* bash uses ' ' regardless of $IFS contents */
5413 overlapping_strcpy((char*)list, list[0]);
5414 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5418 static char **expand_assignments(char **argv, int count)
5423 G.expanded_assignments = p = NULL;
5424 /* Expand assignments into one string each */
5425 for (i = 0; i < count; i++) {
5426 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5428 G.expanded_assignments = NULL;
5435 void re_execute_shell(char ***to_free, const char *s,
5436 char *g_argv0, char **g_argv,
5437 char **builtin_argv) NORETURN;
5439 static void switch_off_special_sigs(unsigned mask)
5442 while ((mask >>= 1) != 0) {
5447 if (G.traps[sig] && !G.traps[sig][0])
5448 /* trap is '', has to remain SIG_IGN */
5451 G.traps[sig] = NULL;
5453 /* We are here only if no trap or trap was not '' */
5454 signal(sig, SIG_DFL);
5458 static void reset_traps_to_defaults(void)
5460 /* This function is always called in a child shell
5461 * after fork (not vfork, NOMMU doesn't use this function).
5466 /* Child shells are not interactive.
5467 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5468 * Testcase: (while :; do :; done) + ^Z should background.
5469 * Same goes for SIGTERM, SIGHUP, SIGINT.
5471 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5472 if (!G.traps && !mask)
5473 return; /* already no traps and no special sigs */
5475 /* Switch off special sigs */
5476 switch_off_special_sigs(mask);
5478 G_fatal_sig_mask = 0;
5480 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5481 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5482 * remain set in G.special_sig_mask */
5487 /* Reset all sigs to default except ones with empty traps */
5488 for (sig = 0; sig < NSIG; sig++) {
5490 continue; /* no trap: nothing to do */
5491 if (!G.traps[sig][0])
5492 continue; /* empty trap: has to remain SIG_IGN */
5493 /* sig has non-empty trap, reset it: */
5495 G.traps[sig] = NULL;
5496 /* There is no signal for trap 0 (EXIT) */
5499 signal(sig, pick_sighandler(sig));
5505 static void re_execute_shell(char ***to_free, const char *s,
5506 char *g_argv0, char **g_argv,
5507 char **builtin_argv) NORETURN;
5508 static void re_execute_shell(char ***to_free, const char *s,
5509 char *g_argv0, char **g_argv,
5510 char **builtin_argv)
5512 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5513 /* delims + 2 * (number of bytes in printed hex numbers) */
5514 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5515 char *heredoc_argv[4];
5516 struct variable *cur;
5517 # if ENABLE_HUSH_FUNCTIONS
5518 struct function *funcp;
5522 unsigned long long empty_trap_mask;
5524 if (!g_argv0) { /* heredoc */
5525 argv = heredoc_argv;
5526 argv[0] = (char *) G.argv0_for_re_execing;
5527 argv[1] = (char *) "-<";
5528 argv[2] = (char *) s;
5530 pp = &argv[3]; /* used as pointer to empty environment */
5536 if (pp) while (*pp++)
5539 empty_trap_mask = 0;
5542 for (sig = 1; sig < NSIG; sig++) {
5543 if (G.traps[sig] && !G.traps[sig][0])
5544 empty_trap_mask |= 1LL << sig;
5548 sprintf(param_buf, NOMMU_HACK_FMT
5549 , (unsigned) G.root_pid
5550 , (unsigned) G.root_ppid
5551 , (unsigned) G.last_bg_pid
5552 , (unsigned) G.last_exitcode
5555 IF_HUSH_LOOPS(, G.depth_of_loop)
5557 # undef NOMMU_HACK_FMT
5558 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5559 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5562 for (cur = G.top_var; cur; cur = cur->next) {
5563 if (!cur->flg_export || cur->flg_read_only)
5566 # if ENABLE_HUSH_FUNCTIONS
5567 for (funcp = G.top_func; funcp; funcp = funcp->next)
5573 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5574 *pp++ = (char *) G.argv0_for_re_execing;
5576 for (cur = G.top_var; cur; cur = cur->next) {
5577 if (strcmp(cur->varstr, hush_version_str) == 0)
5579 if (cur->flg_read_only) {
5580 *pp++ = (char *) "-R";
5581 *pp++ = cur->varstr;
5582 } else if (!cur->flg_export) {
5583 *pp++ = (char *) "-V";
5584 *pp++ = cur->varstr;
5587 # if ENABLE_HUSH_FUNCTIONS
5588 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5589 *pp++ = (char *) "-F";
5590 *pp++ = funcp->name;
5591 *pp++ = funcp->body_as_string;
5594 /* We can pass activated traps here. Say, -Tnn:trap_string
5596 * However, POSIX says that subshells reset signals with traps
5598 * I tested bash-3.2 and it not only does that with true subshells
5599 * of the form ( list ), but with any forked children shells.
5600 * I set trap "echo W" WINCH; and then tried:
5602 * { echo 1; sleep 20; echo 2; } &
5603 * while true; do echo 1; sleep 20; echo 2; break; done &
5604 * true | { echo 1; sleep 20; echo 2; } | cat
5606 * In all these cases sending SIGWINCH to the child shell
5607 * did not run the trap. If I add trap "echo V" WINCH;
5608 * _inside_ group (just before echo 1), it works.
5610 * I conclude it means we don't need to pass active traps here.
5612 *pp++ = (char *) "-c";
5615 while (*++builtin_argv)
5616 *pp++ = *builtin_argv;
5617 *pp++ = (char *) "";
5622 /* *pp = NULL; - is already there */
5626 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5627 /* Don't propagate SIG_IGN to the child */
5628 if (SPECIAL_JOBSTOP_SIGS != 0)
5629 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5630 execve(bb_busybox_exec_path, argv, pp);
5631 /* Fallback. Useful for init=/bin/hush usage etc */
5632 if (argv[0][0] == '/')
5633 execve(argv[0], argv, pp);
5634 xfunc_error_retval = 127;
5635 bb_error_msg_and_die("can't re-execute the shell");
5637 #endif /* !BB_MMU */
5640 static int run_and_free_list(struct pipe *pi);
5642 /* Executing from string: eval, sh -c '...'
5643 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5644 * end_trigger controls how often we stop parsing
5645 * NUL: parse all, execute, return
5646 * ';': parse till ';' or newline, execute, repeat till EOF
5648 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5650 /* Why we need empty flag?
5651 * An obscure corner case "false; ``; echo $?":
5652 * empty command in `` should still set $? to 0.
5653 * But we can't just set $? to 0 at the start,
5654 * this breaks "false; echo `echo $?`" case.
5658 struct pipe *pipe_list;
5660 #if ENABLE_HUSH_INTERACTIVE
5661 if (end_trigger == ';')
5662 inp->promptmode = 0; /* PS1 */
5664 pipe_list = parse_stream(NULL, inp, end_trigger);
5665 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5666 /* If we are in "big" script
5667 * (not in `cmd` or something similar)...
5669 if (pipe_list == ERR_PTR && end_trigger == ';') {
5670 /* Discard cached input (rest of line) */
5671 int ch = inp->last_char;
5672 while (ch != EOF && ch != '\n') {
5673 //bb_error_msg("Discarded:'%c'", ch);
5678 /* This stream isn't empty */
5682 if (!pipe_list && empty)
5683 G.last_exitcode = 0;
5686 debug_print_tree(pipe_list, 0);
5687 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5688 run_and_free_list(pipe_list);
5690 #if ENABLE_HUSH_FUNCTIONS
5691 if (G.flag_return_in_progress == 1)
5697 static void parse_and_run_string(const char *s)
5699 struct in_str input;
5700 setup_string_in_str(&input, s);
5701 parse_and_run_stream(&input, '\0');
5704 static void parse_and_run_file(FILE *f)
5706 struct in_str input;
5707 setup_file_in_str(&input, f);
5708 parse_and_run_stream(&input, ';');
5711 #if ENABLE_HUSH_TICK
5712 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5717 char **to_free = NULL;
5721 pid = BB_MMU ? xfork() : xvfork();
5722 if (pid == 0) { /* child */
5723 disable_restore_tty_pgrp_on_exit();
5724 /* Process substitution is not considered to be usual
5725 * 'command execution'.
5726 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5733 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5734 close(channel[0]); /* NB: close _first_, then move fd! */
5735 xmove_fd(channel[1], 1);
5736 /* Prevent it from trying to handle ctrl-z etc */
5737 IF_HUSH_JOB(G.run_list_level = 1;)
5738 /* Awful hack for `trap` or $(trap).
5740 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5741 * contains an example where "trap" is executed in a subshell:
5743 * save_traps=$(trap)
5745 * eval "$save_traps"
5747 * Standard does not say that "trap" in subshell shall print
5748 * parent shell's traps. It only says that its output
5749 * must have suitable form, but then, in the above example
5750 * (which is not supposed to be normative), it implies that.
5752 * bash (and probably other shell) does implement it
5753 * (traps are reset to defaults, but "trap" still shows them),
5754 * but as a result, "trap" logic is hopelessly messed up:
5757 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5758 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5759 * # true | trap <--- trap is in subshell - no output (ditto)
5760 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5761 * trap -- 'echo Ho' SIGWINCH
5762 * # echo `(trap)` <--- in subshell in subshell - output
5763 * trap -- 'echo Ho' SIGWINCH
5764 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5765 * trap -- 'echo Ho' SIGWINCH
5767 * The rules when to forget and when to not forget traps
5768 * get really complex and nonsensical.
5770 * Our solution: ONLY bare $(trap) or `trap` is special.
5772 s = skip_whitespace(s);
5773 if (strncmp(s, "trap", 4) == 0
5774 && skip_whitespace(s + 4)[0] == '\0'
5776 static const char *const argv[] = { NULL, NULL };
5777 builtin_trap((char**)argv);
5778 exit(0); /* not _exit() - we need to fflush */
5781 reset_traps_to_defaults();
5782 parse_and_run_string(s);
5783 _exit(G.last_exitcode);
5785 /* We re-execute after vfork on NOMMU. This makes this script safe:
5786 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5787 * huge=`cat BIG` # was blocking here forever
5790 re_execute_shell(&to_free,
5800 # if ENABLE_HUSH_FAST
5802 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5803 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5804 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5806 enable_restore_tty_pgrp_on_exit();
5811 close_on_exec_on(channel[0]);
5812 return xfdopen_for_read(channel[0]);
5815 /* Return code is exit status of the process that is run. */
5816 static int process_command_subs(o_string *dest, const char *s)
5819 struct in_str pipe_str;
5821 int status, ch, eol_cnt;
5823 fp = generate_stream_from_string(s, &pid);
5825 /* Now send results of command back into original context */
5826 setup_file_in_str(&pipe_str, fp);
5828 while ((ch = i_getch(&pipe_str)) != EOF) {
5834 o_addchr(dest, '\n');
5837 o_addQchr(dest, ch);
5840 debug_printf("done reading from `cmd` pipe, closing it\n");
5842 /* We need to extract exitcode. Test case
5843 * "true; echo `sleep 1; false` $?"
5845 safe_waitpid(pid, &status, 0);
5846 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5847 return WEXITSTATUS(status);
5849 #endif /* ENABLE_HUSH_TICK */
5852 static void setup_heredoc(struct redir_struct *redir)
5854 struct fd_pair pair;
5857 /* the _body_ of heredoc (misleading field name) */
5858 const char *heredoc = redir->rd_filename;
5865 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5866 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5870 len = strlen(heredoc);
5872 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5874 xmove_fd(pair.rd, redir->rd_fd);
5876 /* Try writing without forking. Newer kernels have
5877 * dynamically growing pipes. Must use non-blocking write! */
5880 written = write(pair.wr, heredoc, len);
5891 ndelay_off(pair.wr);
5893 /* Okay, pipe buffer was not big enough */
5894 /* Note: we must not create a stray child (bastard? :)
5895 * for the unsuspecting parent process. Child creates a grandchild
5896 * and exits before parent execs the process which consumes heredoc
5897 * (that exec happens after we return from this function) */
5904 disable_restore_tty_pgrp_on_exit();
5905 pid = BB_MMU ? xfork() : xvfork();
5909 close(redir->rd_fd); /* read side of the pipe */
5911 full_write(pair.wr, heredoc, len); /* may loop or block */
5914 /* Delegate blocking writes to another process */
5915 xmove_fd(pair.wr, STDOUT_FILENO);
5916 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5920 #if ENABLE_HUSH_FAST
5922 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5924 enable_restore_tty_pgrp_on_exit();
5930 wait(NULL); /* wait till child has died */
5933 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
5934 * and stderr if they are redirected. */
5935 static int setup_redirects(struct command *prog, int squirrel[])
5938 struct redir_struct *redir;
5940 for (redir = prog->redirects; redir; redir = redir->next) {
5941 if (redir->rd_type == REDIRECT_HEREDOC2) {
5942 /* rd_fd<<HERE case */
5943 if (squirrel && redir->rd_fd < 3
5944 && squirrel[redir->rd_fd] < 0
5946 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5948 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5950 debug_printf_parse("set heredoc '%s'\n",
5951 redir->rd_filename);
5952 setup_heredoc(redir);
5956 if (redir->rd_dup == REDIRFD_TO_FILE) {
5957 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5959 if (redir->rd_filename == NULL) {
5960 /* Something went wrong in the parse.
5961 * Pretend it didn't happen */
5962 bb_error_msg("bug in redirect parse");
5965 mode = redir_table[redir->rd_type].mode;
5966 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
5967 openfd = open_or_warn(p, mode);
5970 /* this could get lost if stderr has been redirected, but
5971 * bash and ash both lose it as well (though zsh doesn't!) */
5972 //what the above comment tries to say?
5976 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5977 openfd = redir->rd_dup;
5980 if (openfd != redir->rd_fd) {
5981 if (squirrel && redir->rd_fd < 3
5982 && squirrel[redir->rd_fd] < 0
5984 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5986 if (openfd == REDIRFD_CLOSE) {
5987 /* "n>-" means "close me" */
5988 close(redir->rd_fd);
5990 xdup2(openfd, redir->rd_fd);
5991 if (redir->rd_dup == REDIRFD_TO_FILE)
5999 static void restore_redirects(int squirrel[])
6002 for (i = 0; i < 3; i++) {
6005 /* We simply die on error */
6011 static char *find_in_path(const char *arg)
6014 const char *PATH = get_local_var_value("PATH");
6020 const char *end = strchrnul(PATH, ':');
6021 int sz = end - PATH; /* must be int! */
6025 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6027 /* We have xxx::yyyy in $PATH,
6028 * it means "use current dir" */
6031 if (access(ret, F_OK) == 0)
6044 static const struct built_in_command *find_builtin_helper(const char *name,
6045 const struct built_in_command *x,
6046 const struct built_in_command *end)
6049 if (strcmp(name, x->b_cmd) != 0) {
6053 debug_printf_exec("found builtin '%s'\n", name);
6058 static const struct built_in_command *find_builtin1(const char *name)
6060 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6062 static const struct built_in_command *find_builtin(const char *name)
6064 const struct built_in_command *x = find_builtin1(name);
6067 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6070 #if ENABLE_HUSH_FUNCTIONS
6071 static struct function **find_function_slot(const char *name)
6073 struct function **funcpp = &G.top_func;
6075 if (strcmp(name, (*funcpp)->name) == 0) {
6078 funcpp = &(*funcpp)->next;
6083 static const struct function *find_function(const char *name)
6085 const struct function *funcp = *find_function_slot(name);
6087 debug_printf_exec("found function '%s'\n", name);
6091 /* Note: takes ownership on name ptr */
6092 static struct function *new_function(char *name)
6094 struct function **funcpp = find_function_slot(name);
6095 struct function *funcp = *funcpp;
6097 if (funcp != NULL) {
6098 struct command *cmd = funcp->parent_cmd;
6099 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6101 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6103 /* Note: if !funcp->body, do not free body_as_string!
6104 * This is a special case of "-F name body" function:
6105 * body_as_string was not malloced! */
6107 free_pipe_list(funcp->body);
6109 free(funcp->body_as_string);
6113 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6114 cmd->argv[0] = funcp->name;
6115 cmd->group = funcp->body;
6117 cmd->group_as_string = funcp->body_as_string;
6121 debug_printf_exec("remembering new function '%s'\n", name);
6122 funcp = *funcpp = xzalloc(sizeof(*funcp));
6123 /*funcp->next = NULL;*/
6130 static void unset_func(const char *name)
6132 struct function **funcpp = find_function_slot(name);
6133 struct function *funcp = *funcpp;
6135 if (funcp != NULL) {
6136 debug_printf_exec("freeing function '%s'\n", funcp->name);
6137 *funcpp = funcp->next;
6138 /* funcp is unlinked now, deleting it.
6139 * Note: if !funcp->body, the function was created by
6140 * "-F name body", do not free ->body_as_string
6141 * and ->name as they were not malloced. */
6143 free_pipe_list(funcp->body);
6146 free(funcp->body_as_string);
6154 #define exec_function(to_free, funcp, argv) \
6155 exec_function(funcp, argv)
6157 static void exec_function(char ***to_free,
6158 const struct function *funcp,
6159 char **argv) NORETURN;
6160 static void exec_function(char ***to_free,
6161 const struct function *funcp,
6167 argv[0] = G.global_argv[0];
6168 G.global_argv = argv;
6172 /* On MMU, funcp->body is always non-NULL */
6173 n = run_list(funcp->body);
6177 re_execute_shell(to_free,
6178 funcp->body_as_string,
6185 static int run_function(const struct function *funcp, char **argv)
6191 save_and_replace_G_args(&sv, argv);
6193 /* "we are in function, ok to use return" */
6194 sv_flg = G.flag_return_in_progress;
6195 G.flag_return_in_progress = -1;
6196 # if ENABLE_HUSH_LOCAL
6197 G.func_nest_level++;
6200 /* On MMU, funcp->body is always non-NULL */
6203 /* Function defined by -F */
6204 parse_and_run_string(funcp->body_as_string);
6205 rc = G.last_exitcode;
6209 rc = run_list(funcp->body);
6212 # if ENABLE_HUSH_LOCAL
6214 struct variable *var;
6215 struct variable **var_pp;
6217 var_pp = &G.top_var;
6218 while ((var = *var_pp) != NULL) {
6219 if (var->func_nest_level < G.func_nest_level) {
6220 var_pp = &var->next;
6224 if (var->flg_export)
6225 bb_unsetenv(var->varstr);
6226 /* Remove from global list */
6227 *var_pp = var->next;
6233 G.func_nest_level--;
6236 G.flag_return_in_progress = sv_flg;
6238 restore_G_args(&sv, argv);
6242 #endif /* ENABLE_HUSH_FUNCTIONS */
6246 #define exec_builtin(to_free, x, argv) \
6247 exec_builtin(x, argv)
6249 #define exec_builtin(to_free, x, argv) \
6250 exec_builtin(to_free, argv)
6252 static void exec_builtin(char ***to_free,
6253 const struct built_in_command *x,
6254 char **argv) NORETURN;
6255 static void exec_builtin(char ***to_free,
6256 const struct built_in_command *x,
6262 rcode = x->b_function(argv);
6267 /* On NOMMU, we must never block!
6268 * Example: { sleep 99 | read line; } & echo Ok
6270 re_execute_shell(to_free,
6279 static void execvp_or_die(char **argv) NORETURN;
6280 static void execvp_or_die(char **argv)
6282 debug_printf_exec("execing '%s'\n", argv[0]);
6283 /* Don't propagate SIG_IGN to the child */
6284 if (SPECIAL_JOBSTOP_SIGS != 0)
6285 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6286 execvp(argv[0], argv);
6287 bb_perror_msg("can't execute '%s'", argv[0]);
6288 _exit(127); /* bash compat */
6291 #if ENABLE_HUSH_MODE_X
6292 static void dump_cmd_in_x_mode(char **argv)
6294 if (G_x_mode && argv) {
6295 /* We want to output the line in one write op */
6303 len += strlen(argv[n++]) + 1;
6309 p += sprintf(p, " %s", argv[n++]);
6317 # define dump_cmd_in_x_mode(argv) ((void)0)
6321 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6322 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6323 #define pseudo_exec(nommu_save, command, argv_expanded) \
6324 pseudo_exec(command, argv_expanded)
6327 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6329 * Don't exit() here. If you don't exec, use _exit instead.
6330 * The at_exit handlers apparently confuse the calling process,
6331 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6332 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6333 char **argv, int assignment_cnt,
6334 char **argv_expanded) NORETURN;
6335 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6336 char **argv, int assignment_cnt,
6337 char **argv_expanded)
6341 new_env = expand_assignments(argv, assignment_cnt);
6342 dump_cmd_in_x_mode(new_env);
6344 if (!argv[assignment_cnt]) {
6345 /* Case when we are here: ... | var=val | ...
6346 * (note that we do not exit early, i.e., do not optimize out
6347 * expand_assignments(): think about ... | var=`sleep 1` | ...
6349 free_strings(new_env);
6350 _exit(EXIT_SUCCESS);
6354 set_vars_and_save_old(new_env);
6355 free(new_env); /* optional */
6356 /* we can also destroy set_vars_and_save_old's return value,
6359 nommu_save->new_env = new_env;
6360 nommu_save->old_vars = set_vars_and_save_old(new_env);
6363 if (argv_expanded) {
6364 argv = argv_expanded;
6366 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6368 nommu_save->argv = argv;
6371 dump_cmd_in_x_mode(argv);
6373 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6374 if (strchr(argv[0], '/') != NULL)
6378 /* Check if the command matches any of the builtins.
6379 * Depending on context, this might be redundant. But it's
6380 * easier to waste a few CPU cycles than it is to figure out
6381 * if this is one of those cases.
6384 /* On NOMMU, it is more expensive to re-execute shell
6385 * just in order to run echo or test builtin.
6386 * It's better to skip it here and run corresponding
6387 * non-builtin later. */
6388 const struct built_in_command *x;
6389 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6391 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6394 #if ENABLE_HUSH_FUNCTIONS
6395 /* Check if the command matches any functions */
6397 const struct function *funcp = find_function(argv[0]);
6399 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6404 #if ENABLE_FEATURE_SH_STANDALONE
6405 /* Check if the command matches any busybox applets */
6407 int a = find_applet_by_name(argv[0]);
6409 # if BB_MMU /* see above why on NOMMU it is not allowed */
6410 if (APPLET_IS_NOEXEC(a)) {
6411 debug_printf_exec("running applet '%s'\n", argv[0]);
6412 run_applet_no_and_exit(a, argv);
6415 /* Re-exec ourselves */
6416 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6417 /* Don't propagate SIG_IGN to the child */
6418 if (SPECIAL_JOBSTOP_SIGS != 0)
6419 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6420 execv(bb_busybox_exec_path, argv);
6421 /* If they called chroot or otherwise made the binary no longer
6422 * executable, fall through */
6427 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6430 execvp_or_die(argv);
6433 /* Called after [v]fork() in run_pipe
6435 static void pseudo_exec(nommu_save_t *nommu_save,
6436 struct command *command,
6437 char **argv_expanded) NORETURN;
6438 static void pseudo_exec(nommu_save_t *nommu_save,
6439 struct command *command,
6440 char **argv_expanded)
6442 if (command->argv) {
6443 pseudo_exec_argv(nommu_save, command->argv,
6444 command->assignment_cnt, argv_expanded);
6447 if (command->group) {
6448 /* Cases when we are here:
6451 * ... | ( list ) | ...
6452 * ... | { list } | ...
6456 debug_printf_exec("pseudo_exec: run_list\n");
6457 reset_traps_to_defaults();
6458 rcode = run_list(command->group);
6459 /* OK to leak memory by not calling free_pipe_list,
6460 * since this process is about to exit */
6463 re_execute_shell(&nommu_save->argv_from_re_execing,
6464 command->group_as_string,
6471 /* Case when we are here: ... | >file */
6472 debug_printf_exec("pseudo_exec'ed null command\n");
6473 _exit(EXIT_SUCCESS);
6477 static const char *get_cmdtext(struct pipe *pi)
6483 /* This is subtle. ->cmdtext is created only on first backgrounding.
6484 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6485 * On subsequent bg argv is trashed, but we won't use it */
6488 argv = pi->cmds[0].argv;
6489 if (!argv || !argv[0]) {
6490 pi->cmdtext = xzalloc(1);
6496 len += strlen(*argv) + 1;
6500 argv = pi->cmds[0].argv;
6502 len = strlen(*argv);
6503 memcpy(p, *argv, len);
6511 static void insert_bg_job(struct pipe *pi)
6513 struct pipe *job, **jobp;
6516 /* Linear search for the ID of the job to use */
6518 for (job = G.job_list; job; job = job->next)
6519 if (job->jobid >= pi->jobid)
6520 pi->jobid = job->jobid + 1;
6522 /* Add job to the list of running jobs */
6524 while ((job = *jobp) != NULL)
6526 job = *jobp = xmalloc(sizeof(*job));
6528 *job = *pi; /* physical copy */
6530 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6531 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6532 for (i = 0; i < pi->num_cmds; i++) {
6533 job->cmds[i].pid = pi->cmds[i].pid;
6534 /* all other fields are not used and stay zero */
6536 job->cmdtext = xstrdup(get_cmdtext(pi));
6538 if (G_interactive_fd)
6539 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6540 G.last_jobid = job->jobid;
6543 static void remove_bg_job(struct pipe *pi)
6545 struct pipe *prev_pipe;
6547 if (pi == G.job_list) {
6548 G.job_list = pi->next;
6550 prev_pipe = G.job_list;
6551 while (prev_pipe->next != pi)
6552 prev_pipe = prev_pipe->next;
6553 prev_pipe->next = pi->next;
6556 G.last_jobid = G.job_list->jobid;
6561 /* Remove a backgrounded job */
6562 static void delete_finished_bg_job(struct pipe *pi)
6569 /* Check to see if any processes have exited -- if they
6570 * have, figure out why and see if a job has completed */
6571 static int checkjobs(struct pipe *fg_pipe)
6581 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6583 attributes = WUNTRACED;
6584 if (fg_pipe == NULL)
6585 attributes |= WNOHANG;
6588 #if ENABLE_HUSH_FAST
6589 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6590 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6591 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6592 /* There was neither fork nor SIGCHLD since last waitpid */
6593 /* Avoid doing waitpid syscall if possible */
6594 if (!G.we_have_children) {
6598 if (fg_pipe == NULL) { /* is WNOHANG set? */
6599 /* We have children, but they did not exit
6600 * or stop yet (we saw no SIGCHLD) */
6603 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6607 /* Do we do this right?
6608 * bash-3.00# sleep 20 | false
6610 * [3]+ Stopped sleep 20 | false
6611 * bash-3.00# echo $?
6612 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6613 * [hush 1.14.0: yes we do it right]
6620 #if ENABLE_HUSH_FAST
6621 i = G.count_SIGCHLD;
6623 childpid = waitpid(-1, &status, attributes);
6624 if (childpid <= 0) {
6625 if (childpid && errno != ECHILD)
6626 bb_perror_msg("waitpid");
6627 #if ENABLE_HUSH_FAST
6628 else { /* Until next SIGCHLD, waitpid's are useless */
6629 G.we_have_children = (childpid == 0);
6630 G.handled_SIGCHLD = i;
6631 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6636 dead = WIFEXITED(status) || WIFSIGNALED(status);
6639 if (WIFSTOPPED(status))
6640 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6641 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6642 if (WIFSIGNALED(status))
6643 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6644 childpid, WTERMSIG(status), WEXITSTATUS(status));
6645 if (WIFEXITED(status))
6646 debug_printf_jobs("pid %d exited, exitcode %d\n",
6647 childpid, WEXITSTATUS(status));
6649 /* Were we asked to wait for fg pipe? */
6651 i = fg_pipe->num_cmds;
6653 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6654 if (fg_pipe->cmds[i].pid != childpid)
6658 fg_pipe->cmds[i].pid = 0;
6659 fg_pipe->alive_cmds--;
6660 ex = WEXITSTATUS(status);
6661 /* bash prints killer signal's name for *last*
6662 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6663 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6665 if (WIFSIGNALED(status)) {
6666 int sig = WTERMSIG(status);
6667 if (i == fg_pipe->num_cmds-1)
6668 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6669 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6670 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6671 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6672 * Maybe we need to use sig | 128? */
6675 fg_pipe->cmds[i].cmd_exitcode = ex;
6677 fg_pipe->cmds[i].is_stopped = 1;
6678 fg_pipe->stopped_cmds++;
6680 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6681 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6682 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6683 /* All processes in fg pipe have exited or stopped */
6684 i = fg_pipe->num_cmds;
6686 rcode = fg_pipe->cmds[i].cmd_exitcode;
6687 /* usually last process gives overall exitstatus,
6688 * but with "set -o pipefail", last *failed* process does */
6689 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6692 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6693 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6694 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6695 * and "killall -STOP cat" */
6696 if (G_interactive_fd) {
6698 if (fg_pipe->alive_cmds != 0)
6699 insert_bg_job(fg_pipe);
6703 if (fg_pipe->alive_cmds == 0)
6706 /* There are still running processes in the fg pipe */
6707 goto wait_more; /* do waitpid again */
6709 /* it wasnt fg_pipe, look for process in bg pipes */
6713 /* We asked to wait for bg or orphaned children */
6714 /* No need to remember exitcode in this case */
6715 for (pi = G.job_list; pi; pi = pi->next) {
6716 for (i = 0; i < pi->num_cmds; i++) {
6717 if (pi->cmds[i].pid == childpid)
6718 goto found_pi_and_prognum;
6721 /* Happens when shell is used as init process (init=/bin/sh) */
6722 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6723 continue; /* do waitpid again */
6725 found_pi_and_prognum:
6728 pi->cmds[i].pid = 0;
6730 if (!pi->alive_cmds) {
6731 if (G_interactive_fd)
6732 printf(JOB_STATUS_FORMAT, pi->jobid,
6733 "Done", pi->cmdtext);
6734 delete_finished_bg_job(pi);
6738 pi->cmds[i].is_stopped = 1;
6742 } /* while (waitpid succeeds)... */
6748 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6751 int rcode = checkjobs(fg_pipe);
6752 if (G_saved_tty_pgrp) {
6753 /* Job finished, move the shell to the foreground */
6754 p = getpgrp(); /* our process group id */
6755 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6756 tcsetpgrp(G_interactive_fd, p);
6762 /* Start all the jobs, but don't wait for anything to finish.
6765 * Return code is normally -1, when the caller has to wait for children
6766 * to finish to determine the exit status of the pipe. If the pipe
6767 * is a simple builtin command, however, the action is done by the
6768 * time run_pipe returns, and the exit code is provided as the
6771 * Returns -1 only if started some children. IOW: we have to
6772 * mask out retvals of builtins etc with 0xff!
6774 * The only case when we do not need to [v]fork is when the pipe
6775 * is single, non-backgrounded, non-subshell command. Examples:
6776 * cmd ; ... { list } ; ...
6777 * cmd && ... { list } && ...
6778 * cmd || ... { list } || ...
6779 * If it is, then we can run cmd as a builtin, NOFORK,
6780 * or (if SH_STANDALONE) an applet, and we can run the { list }
6781 * with run_list. If it isn't one of these, we fork and exec cmd.
6783 * Cases when we must fork:
6784 * non-single: cmd | cmd
6785 * backgrounded: cmd & { list } &
6786 * subshell: ( list ) [&]
6788 #if !ENABLE_HUSH_MODE_X
6789 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6790 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6792 static int redirect_and_varexp_helper(char ***new_env_p,
6793 struct variable **old_vars_p,
6794 struct command *command,
6796 char **argv_expanded)
6798 /* setup_redirects acts on file descriptors, not FILEs.
6799 * This is perfect for work that comes after exec().
6800 * Is it really safe for inline use? Experimentally,
6801 * things seem to work. */
6802 int rcode = setup_redirects(command, squirrel);
6804 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6805 *new_env_p = new_env;
6806 dump_cmd_in_x_mode(new_env);
6807 dump_cmd_in_x_mode(argv_expanded);
6809 *old_vars_p = set_vars_and_save_old(new_env);
6813 static NOINLINE int run_pipe(struct pipe *pi)
6815 static const char *const null_ptr = NULL;
6819 struct command *command;
6820 char **argv_expanded;
6822 /* it is not always needed, but we aim to smaller code */
6823 int squirrel[] = { -1, -1, -1 };
6826 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6829 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6830 * Result should be 3 lines: q w e, qwe, q w e
6832 G.ifs = get_local_var_value("IFS");
6836 IF_HUSH_JOB(pi->pgrp = -1;)
6837 pi->stopped_cmds = 0;
6838 command = &pi->cmds[0];
6839 argv_expanded = NULL;
6841 if (pi->num_cmds != 1
6842 || pi->followup == PIPE_BG
6843 || command->cmd_type == CMD_SUBSHELL
6850 debug_printf_exec(": group:%p argv:'%s'\n",
6851 command->group, command->argv ? command->argv[0] : "NONE");
6853 if (command->group) {
6854 #if ENABLE_HUSH_FUNCTIONS
6855 if (command->cmd_type == CMD_FUNCDEF) {
6856 /* "executing" func () { list } */
6857 struct function *funcp;
6859 funcp = new_function(command->argv[0]);
6860 /* funcp->name is already set to argv[0] */
6861 funcp->body = command->group;
6863 funcp->body_as_string = command->group_as_string;
6864 command->group_as_string = NULL;
6866 command->group = NULL;
6867 command->argv[0] = NULL;
6868 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6869 funcp->parent_cmd = command;
6870 command->child_func = funcp;
6872 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6874 return EXIT_SUCCESS;
6878 debug_printf("non-subshell group\n");
6879 rcode = 1; /* exitcode if redir failed */
6880 if (setup_redirects(command, squirrel) == 0) {
6881 debug_printf_exec(": run_list\n");
6882 rcode = run_list(command->group) & 0xff;
6884 restore_redirects(squirrel);
6885 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6887 debug_printf_exec("run_pipe: return %d\n", rcode);
6891 argv = command->argv ? command->argv : (char **) &null_ptr;
6893 const struct built_in_command *x;
6894 #if ENABLE_HUSH_FUNCTIONS
6895 const struct function *funcp;
6899 char **new_env = NULL;
6900 struct variable *old_vars = NULL;
6902 if (argv[command->assignment_cnt] == NULL) {
6903 /* Assignments, but no command */
6904 /* Ensure redirects take effect (that is, create files).
6905 * Try "a=t >file" */
6906 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6907 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6908 /* Set shell variables */
6912 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6913 /* Do we need to flag set_local_var() errors?
6914 * "assignment to readonly var" and "putenv error"
6919 /* Redirect error sets $? to 1. Otherwise,
6920 * if evaluating assignment value set $?, retain it.
6921 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6923 rcode = G.last_exitcode;
6924 /* Exit, _skipping_ variable restoring code: */
6925 goto clean_up_and_ret0;
6927 #else /* Older, bigger, but more correct code */
6929 rcode = setup_redirects(command, squirrel);
6930 restore_redirects(squirrel);
6931 /* Set shell variables */
6933 bb_putchar_stderr('+');
6935 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
6937 fprintf(stderr, " %s", p);
6938 debug_printf_exec("set shell var:'%s'->'%s'\n",
6940 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6941 /* Do we need to flag set_local_var() errors?
6942 * "assignment to readonly var" and "putenv error"
6947 bb_putchar_stderr('\n');
6948 /* Redirect error sets $? to 1. Otherwise,
6949 * if evaluating assignment value set $?, retain it.
6950 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6952 rcode = G.last_exitcode;
6953 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6955 debug_printf_exec("run_pipe: return %d\n", rcode);
6960 /* Expand the rest into (possibly) many strings each */
6961 #if ENABLE_HUSH_BASH_COMPAT
6962 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6963 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6967 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6970 /* if someone gives us an empty string: `cmd with empty output` */
6971 if (!argv_expanded[0]) {
6972 free(argv_expanded);
6974 return G.last_exitcode;
6977 x = find_builtin(argv_expanded[0]);
6978 #if ENABLE_HUSH_FUNCTIONS
6981 funcp = find_function(argv_expanded[0]);
6985 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6986 debug_printf("exec with redirects only\n");
6987 rcode = setup_redirects(command, NULL);
6988 goto clean_up_and_ret1;
6991 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6994 debug_printf_exec(": builtin '%s' '%s'...\n",
6995 x->b_cmd, argv_expanded[1]);
6997 rcode = x->b_function(argv_expanded) & 0xff;
7000 #if ENABLE_HUSH_FUNCTIONS
7002 # if ENABLE_HUSH_LOCAL
7003 struct variable **sv;
7004 sv = G.shadowed_vars_pp;
7005 G.shadowed_vars_pp = &old_vars;
7007 debug_printf_exec(": function '%s' '%s'...\n",
7008 funcp->name, argv_expanded[1]);
7009 rcode = run_function(funcp, argv_expanded) & 0xff;
7010 # if ENABLE_HUSH_LOCAL
7011 G.shadowed_vars_pp = sv;
7017 unset_vars(new_env);
7019 /* clean_up_and_ret0: */
7020 restore_redirects(squirrel);
7022 free(argv_expanded);
7023 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7025 debug_printf_exec("run_pipe return %d\n", rcode);
7029 if (ENABLE_FEATURE_SH_NOFORK) {
7030 int n = find_applet_by_name(argv_expanded[0]);
7031 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7032 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7034 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7035 argv_expanded[0], argv_expanded[1]);
7036 rcode = run_nofork_applet(n, argv_expanded);
7038 goto clean_up_and_ret;
7041 /* It is neither builtin nor applet. We must fork. */
7045 /* NB: argv_expanded may already be created, and that
7046 * might include `cmd` runs! Do not rerun it! We *must*
7047 * use argv_expanded if it's non-NULL */
7049 /* Going to fork a child per each pipe member */
7054 while (cmd_no < pi->num_cmds) {
7055 struct fd_pair pipefds;
7057 volatile nommu_save_t nommu_save;
7058 nommu_save.new_env = NULL;
7059 nommu_save.old_vars = NULL;
7060 nommu_save.argv = NULL;
7061 nommu_save.argv_from_re_execing = NULL;
7063 command = &pi->cmds[cmd_no];
7065 if (command->argv) {
7066 debug_printf_exec(": pipe member '%s' '%s'...\n",
7067 command->argv[0], command->argv[1]);
7069 debug_printf_exec(": pipe member with no argv\n");
7072 /* pipes are inserted between pairs of commands */
7075 if (cmd_no < pi->num_cmds)
7076 xpiped_pair(pipefds);
7078 command->pid = BB_MMU ? fork() : vfork();
7079 if (!command->pid) { /* child */
7081 disable_restore_tty_pgrp_on_exit();
7082 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7084 /* Every child adds itself to new process group
7085 * with pgid == pid_of_first_child_in_pipe */
7086 if (G.run_list_level == 1 && G_interactive_fd) {
7089 if (pgrp < 0) /* true for 1st process only */
7091 if (setpgid(0, pgrp) == 0
7092 && pi->followup != PIPE_BG
7093 && G_saved_tty_pgrp /* we have ctty */
7095 /* We do it in *every* child, not just first,
7097 tcsetpgrp(G_interactive_fd, pgrp);
7101 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7102 /* 1st cmd in backgrounded pipe
7103 * should have its stdin /dev/null'ed */
7105 if (open(bb_dev_null, O_RDONLY))
7106 xopen("/", O_RDONLY);
7108 xmove_fd(next_infd, 0);
7110 xmove_fd(pipefds.wr, 1);
7113 /* Like bash, explicit redirects override pipes,
7114 * and the pipe fd is available for dup'ing. */
7115 if (setup_redirects(command, NULL))
7118 /* Stores to nommu_save list of env vars putenv'ed
7119 * (NOMMU, on MMU we don't need that) */
7120 /* cast away volatility... */
7121 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7122 /* pseudo_exec() does not return */
7125 /* parent or error */
7126 #if ENABLE_HUSH_FAST
7128 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7130 enable_restore_tty_pgrp_on_exit();
7132 /* Clean up after vforked child */
7133 free(nommu_save.argv);
7134 free(nommu_save.argv_from_re_execing);
7135 unset_vars(nommu_save.new_env);
7136 add_vars(nommu_save.old_vars);
7138 free(argv_expanded);
7139 argv_expanded = NULL;
7140 if (command->pid < 0) { /* [v]fork failed */
7141 /* Clearly indicate, was it fork or vfork */
7142 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7146 /* Second and next children need to know pid of first one */
7148 pi->pgrp = command->pid;
7154 if (cmd_no < pi->num_cmds)
7156 /* Pass read (output) pipe end to next iteration */
7157 next_infd = pipefds.rd;
7160 if (!pi->alive_cmds) {
7162 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7167 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7171 /* NB: called by pseudo_exec, and therefore must not modify any
7172 * global data until exec/_exit (we can be a child after vfork!) */
7173 static int run_list(struct pipe *pi)
7175 #if ENABLE_HUSH_CASE
7176 char *case_word = NULL;
7178 #if ENABLE_HUSH_LOOPS
7179 struct pipe *loop_top = NULL;
7180 char **for_lcur = NULL;
7181 char **for_list = NULL;
7183 smallint last_followup;
7185 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7186 smalluint cond_code = 0;
7188 enum { cond_code = 0 };
7191 smallint rword; /* RES_foo */
7192 smallint last_rword; /* ditto */
7195 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7198 #if ENABLE_HUSH_LOOPS
7199 /* Check syntax for "for" */
7202 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7203 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7205 /* current word is FOR or IN (BOLD in comments below) */
7206 if (cpipe->next == NULL) {
7207 syntax_error("malformed for");
7209 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7212 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7213 if (cpipe->next->res_word == RES_DO)
7215 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7216 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7217 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7219 syntax_error("malformed for");
7221 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7228 /* Past this point, all code paths should jump to ret: label
7229 * in order to return, no direct "return" statements please.
7230 * This helps to ensure that no memory is leaked. */
7238 last_rword = RES_XXXX;
7240 last_followup = PIPE_SEQ;
7241 rcode = G.last_exitcode;
7243 /* Go through list of pipes, (maybe) executing them. */
7244 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7248 IF_HAS_KEYWORDS(rword = pi->res_word;)
7249 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7250 rword, cond_code, last_rword);
7251 #if ENABLE_HUSH_LOOPS
7252 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7253 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7255 /* start of a loop: remember where loop starts */
7260 /* Still in the same "if...", "then..." or "do..." branch? */
7261 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7262 if ((rcode == 0 && last_followup == PIPE_OR)
7263 || (rcode != 0 && last_followup == PIPE_AND)
7265 /* It is "<true> || CMD" or "<false> && CMD"
7266 * and we should not execute CMD */
7267 debug_printf_exec("skipped cmd because of || or &&\n");
7268 last_followup = pi->followup;
7272 last_followup = pi->followup;
7273 IF_HAS_KEYWORDS(last_rword = rword;)
7276 if (rword == RES_THEN) {
7277 /* if false; then ... fi has exitcode 0! */
7278 G.last_exitcode = rcode = EXIT_SUCCESS;
7279 /* "if <false> THEN cmd": skip cmd */
7283 if (rword == RES_ELSE || rword == RES_ELIF) {
7284 /* "if <true> then ... ELSE/ELIF cmd":
7285 * skip cmd and all following ones */
7290 #if ENABLE_HUSH_LOOPS
7291 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7293 /* first loop through for */
7295 static const char encoded_dollar_at[] ALIGN1 = {
7296 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7297 }; /* encoded representation of "$@" */
7298 static const char *const encoded_dollar_at_argv[] = {
7299 encoded_dollar_at, NULL
7300 }; /* argv list with one element: "$@" */
7303 vals = (char**)encoded_dollar_at_argv;
7304 if (pi->next->res_word == RES_IN) {
7305 /* if no variable values after "in" we skip "for" */
7306 if (!pi->next->cmds[0].argv) {
7307 G.last_exitcode = rcode = EXIT_SUCCESS;
7308 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7311 vals = pi->next->cmds[0].argv;
7312 } /* else: "for var; do..." -> assume "$@" list */
7313 /* create list of variable values */
7314 debug_print_strings("for_list made from", vals);
7315 for_list = expand_strvec_to_strvec(vals);
7316 for_lcur = for_list;
7317 debug_print_strings("for_list", for_list);
7320 /* "for" loop is over, clean up */
7326 /* Insert next value from for_lcur */
7327 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7328 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7331 if (rword == RES_IN) {
7332 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7334 if (rword == RES_DONE) {
7335 continue; /* "done" has no cmds too */
7338 #if ENABLE_HUSH_CASE
7339 if (rword == RES_CASE) {
7340 case_word = expand_strvec_to_string(pi->cmds->argv);
7343 if (rword == RES_MATCH) {
7346 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7348 /* all prev words didn't match, does this one match? */
7349 argv = pi->cmds->argv;
7351 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7352 /* TODO: which FNM_xxx flags to use? */
7353 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7355 if (cond_code == 0) { /* match! we will execute this branch */
7356 free(case_word); /* make future "word)" stop */
7364 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7366 continue; /* not matched yet, skip this pipe */
7369 /* Just pressing <enter> in shell should check for jobs.
7370 * OTOH, in non-interactive shell this is useless
7371 * and only leads to extra job checks */
7372 if (pi->num_cmds == 0) {
7373 if (G_interactive_fd)
7374 goto check_jobs_and_continue;
7378 /* After analyzing all keywords and conditions, we decided
7379 * to execute this pipe. NB: have to do checkjobs(NULL)
7380 * after run_pipe to collect any background children,
7381 * even if list execution is to be stopped. */
7382 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7385 #if ENABLE_HUSH_LOOPS
7386 G.flag_break_continue = 0;
7388 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7390 /* We ran a builtin, function, or group.
7391 * rcode is already known
7392 * and we don't need to wait for anything. */
7393 G.last_exitcode = rcode;
7394 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7395 check_and_run_traps();
7396 #if ENABLE_HUSH_LOOPS
7397 /* Was it "break" or "continue"? */
7398 if (G.flag_break_continue) {
7399 smallint fbc = G.flag_break_continue;
7400 /* We might fall into outer *loop*,
7401 * don't want to break it too */
7403 G.depth_break_continue--;
7404 if (G.depth_break_continue == 0)
7405 G.flag_break_continue = 0;
7406 /* else: e.g. "continue 2" should *break* once, *then* continue */
7407 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7408 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7409 goto check_jobs_and_break;
7410 /* "continue": simulate end of loop */
7415 #if ENABLE_HUSH_FUNCTIONS
7416 if (G.flag_return_in_progress == 1) {
7417 /* same as "goto check_jobs_and_break" */
7422 } else if (pi->followup == PIPE_BG) {
7423 /* What does bash do with attempts to background builtins? */
7424 /* even bash 3.2 doesn't do that well with nested bg:
7425 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7426 * I'm NOT treating inner &'s as jobs */
7427 check_and_run_traps();
7429 if (G.run_list_level == 1)
7432 /* Last command's pid goes to $! */
7433 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7434 G.last_exitcode = rcode = EXIT_SUCCESS;
7435 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7438 if (G.run_list_level == 1 && G_interactive_fd) {
7439 /* Waits for completion, then fg's main shell */
7440 rcode = checkjobs_and_fg_shell(pi);
7441 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7442 check_and_run_traps();
7445 { /* This one just waits for completion */
7446 rcode = checkjobs(pi);
7447 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7448 check_and_run_traps();
7450 G.last_exitcode = rcode;
7454 /* Analyze how result affects subsequent commands */
7456 if (rword == RES_IF || rword == RES_ELIF)
7459 #if ENABLE_HUSH_LOOPS
7460 /* Beware of "while false; true; do ..."! */
7461 if (pi->next && pi->next->res_word == RES_DO) {
7462 if (rword == RES_WHILE) {
7464 /* "while false; do...done" - exitcode 0 */
7465 G.last_exitcode = rcode = EXIT_SUCCESS;
7466 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7467 goto check_jobs_and_break;
7470 if (rword == RES_UNTIL) {
7472 debug_printf_exec(": until expr is true: breaking\n");
7473 check_jobs_and_break:
7481 check_jobs_and_continue:
7488 #if ENABLE_HUSH_LOOPS
7493 #if ENABLE_HUSH_CASE
7497 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7501 /* Select which version we will use */
7502 static int run_and_free_list(struct pipe *pi)
7505 debug_printf_exec("run_and_free_list entered\n");
7506 if (!G.o_opt[OPT_O_NOEXEC]) {
7507 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7508 rcode = run_list(pi);
7510 /* free_pipe_list has the side effect of clearing memory.
7511 * In the long run that function can be merged with run_list,
7512 * but doing that now would hobble the debugging effort. */
7514 debug_printf_exec("run_and_free_list return %d\n", rcode);
7519 static void install_sighandlers(unsigned mask)
7521 sighandler_t old_handler;
7523 while ((mask >>= 1) != 0) {
7527 old_handler = signal(sig, pick_sighandler(sig));
7528 /* POSIX allows shell to re-enable SIGCHLD
7529 * even if it was SIG_IGN on entry.
7530 * Therefore we skip IGN check for it:
7534 if (old_handler == SIG_IGN) {
7535 /* oops... restore back to IGN, and record this fact */
7536 signal(sig, old_handler);
7538 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7540 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7545 /* Called a few times only (or even once if "sh -c") */
7546 static void install_special_sighandlers(void)
7550 /* Which signals are shell-special? */
7551 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7552 if (G_interactive_fd) {
7553 mask |= SPECIAL_INTERACTIVE_SIGS;
7554 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7555 mask |= SPECIAL_JOBSTOP_SIGS;
7557 /* Careful, do not re-install handlers we already installed */
7558 if (G.special_sig_mask != mask) {
7559 unsigned diff = mask & ~G.special_sig_mask;
7560 G.special_sig_mask = mask;
7561 install_sighandlers(diff);
7567 /* Set handlers to restore tty pgrp and exit */
7568 static void install_fatal_sighandlers(void)
7572 /* We will restore tty pgrp on these signals */
7574 + (1 << SIGILL ) * HUSH_DEBUG
7575 + (1 << SIGFPE ) * HUSH_DEBUG
7576 + (1 << SIGBUS ) * HUSH_DEBUG
7577 + (1 << SIGSEGV) * HUSH_DEBUG
7578 + (1 << SIGTRAP) * HUSH_DEBUG
7580 /* bash 3.2 seems to handle these just like 'fatal' ones */
7583 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7584 * if we aren't interactive... but in this case
7585 * we never want to restore pgrp on exit, and this fn is not called
7587 /*+ (1 << SIGHUP )*/
7588 /*+ (1 << SIGTERM)*/
7589 /*+ (1 << SIGINT )*/
7591 G_fatal_sig_mask = mask;
7593 install_sighandlers(mask);
7597 static int set_mode(int state, char mode, const char *o_opt)
7602 G.o_opt[OPT_O_NOEXEC] = state;
7605 IF_HUSH_MODE_X(G_x_mode = state;)
7609 /* "set -+o" without parameter.
7610 * in bash, set -o produces this output:
7614 * We always use the second form.
7616 const char *p = o_opt_strings;
7619 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7625 idx = index_in_strings(o_opt_strings, o_opt);
7627 G.o_opt[idx] = state;
7631 return EXIT_FAILURE;
7633 return EXIT_SUCCESS;
7636 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7637 int hush_main(int argc, char **argv)
7640 OPT_login = (1 << 0),
7644 unsigned builtin_argc;
7646 struct variable *cur_var;
7647 struct variable *shell_ver;
7650 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7651 G.last_exitcode = EXIT_SUCCESS;
7652 #if ENABLE_HUSH_FAST
7653 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7656 G.argv0_for_re_execing = argv[0];
7658 /* Deal with HUSH_VERSION */
7659 shell_ver = xzalloc(sizeof(*shell_ver));
7660 shell_ver->flg_export = 1;
7661 shell_ver->flg_read_only = 1;
7662 /* Code which handles ${var<op>...} needs writable values for all variables,
7663 * therefore we xstrdup: */
7664 shell_ver->varstr = xstrdup(hush_version_str);
7665 /* Create shell local variables from the values
7666 * currently living in the environment */
7667 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7668 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7669 G.top_var = shell_ver;
7670 cur_var = G.top_var;
7673 char *value = strchr(*e, '=');
7674 if (value) { /* paranoia */
7675 cur_var->next = xzalloc(sizeof(*cur_var));
7676 cur_var = cur_var->next;
7677 cur_var->varstr = *e;
7678 cur_var->max_len = strlen(*e);
7679 cur_var->flg_export = 1;
7683 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7684 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7685 putenv(shell_ver->varstr);
7688 set_pwd_var(/*exp:*/ 1);
7689 /* bash also exports SHLVL and _,
7690 * and sets (but doesn't export) the following variables:
7692 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7693 * BASH_VERSION='3.2.0(1)-release'
7695 * MACHTYPE=i386-pc-linux-gnu
7697 * HOSTNAME=<xxxxxxxxxx>
7698 * PPID=<NNNNN> - we also do it elsewhere
7709 * PIPESTATUS=([0]="0")
7710 * HISTFILE=/<xxx>/.bash_history
7714 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7716 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7726 #if ENABLE_FEATURE_EDITING
7727 G.line_input_state = new_line_input_t(FOR_SHELL);
7728 # if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7730 const char *hp = get_local_var_value("HISTFILE");
7732 hp = get_local_var_value("HOME");
7734 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7735 //set_local_var(xasprintf("HISTFILE=%s", ...));
7738 # if ENABLE_FEATURE_SH_HISTFILESIZE
7739 hp = get_local_var_value("HISTFILESIZE");
7740 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7746 /* Initialize some more globals to non-zero values */
7747 cmdedit_update_prompt();
7749 if (setjmp(die_jmp)) {
7750 /* xfunc has failed! die die die */
7751 /* no EXIT traps, this is an escape hatch! */
7753 hush_exit(xfunc_error_retval);
7756 /* Shell is non-interactive at first. We need to call
7757 * install_special_sighandlers() if we are going to execute "sh <script>",
7758 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7759 * If we later decide that we are interactive, we run install_special_sighandlers()
7760 * in order to intercept (more) signals.
7764 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7765 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7768 opt = getopt(argc, argv, "+c:xinsl"
7771 # if ENABLE_HUSH_FUNCTIONS
7781 * sh ... -c 'script'
7782 * sh ... -c 'script' ARG0 [ARG1...]
7783 * On NOMMU, if builtin_argc != 0,
7784 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7785 * "" needs to be replaced with NULL
7786 * and BARGV vector fed to builtin function.
7787 * Note: the form without ARG0 never happens:
7788 * sh ... -c 'builtin' BARGV... ""
7791 G.root_pid = getpid();
7792 G.root_ppid = getppid();
7794 G.global_argv = argv + optind;
7795 G.global_argc = argc - optind;
7797 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7798 const struct built_in_command *x;
7800 install_special_sighandlers();
7801 x = find_builtin(optarg);
7802 if (x) { /* paranoia */
7803 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7804 G.global_argv += builtin_argc;
7805 G.global_argv[-1] = NULL; /* replace "" */
7807 G.last_exitcode = x->b_function(argv + optind - 1);
7811 if (!G.global_argv[0]) {
7812 /* -c 'script' (no params): prevent empty $0 */
7813 G.global_argv--; /* points to argv[i] of 'script' */
7814 G.global_argv[0] = argv[0];
7816 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7817 install_special_sighandlers();
7818 parse_and_run_string(optarg);
7821 /* Well, we cannot just declare interactiveness,
7822 * we have to have some stuff (ctty, etc) */
7823 /* G_interactive_fd++; */
7826 /* "-s" means "read from stdin", but this is how we always
7827 * operate, so simply do nothing here. */
7833 case '<': /* "big heredoc" support */
7834 full_write1_str(optarg);
7837 unsigned long long empty_trap_mask;
7839 G.root_pid = bb_strtou(optarg, &optarg, 16);
7841 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7843 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7845 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7847 builtin_argc = bb_strtou(optarg, &optarg, 16);
7849 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7850 if (empty_trap_mask != 0) {
7852 install_special_sighandlers();
7853 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7854 for (sig = 1; sig < NSIG; sig++) {
7855 if (empty_trap_mask & (1LL << sig)) {
7856 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7857 signal(sig, SIG_IGN);
7861 # if ENABLE_HUSH_LOOPS
7863 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7869 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7871 # if ENABLE_HUSH_FUNCTIONS
7873 struct function *funcp = new_function(optarg);
7874 /* funcp->name is already set to optarg */
7875 /* funcp->body is set to NULL. It's a special case. */
7876 funcp->body_as_string = argv[optind];
7884 if (set_mode(1, opt, NULL) == 0) /* no error */
7888 fprintf(stderr, "Usage: sh [FILE]...\n"
7889 " or: sh -c command [args]...\n\n");
7895 } /* option parsing loop */
7897 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7898 G.global_argc = argc - (optind - 1);
7899 G.global_argv = argv + (optind - 1);
7900 G.global_argv[0] = argv[0];
7903 G.root_pid = getpid();
7904 G.root_ppid = getppid();
7907 /* If we are login shell... */
7908 if (flags & OPT_login) {
7910 debug_printf("sourcing /etc/profile\n");
7911 input = fopen_for_read("/etc/profile");
7912 if (input != NULL) {
7913 close_on_exec_on(fileno(input));
7914 install_special_sighandlers();
7915 parse_and_run_file(input);
7918 /* bash: after sourcing /etc/profile,
7919 * tries to source (in the given order):
7920 * ~/.bash_profile, ~/.bash_login, ~/.profile,
7921 * stopping on first found. --noprofile turns this off.
7922 * bash also sources ~/.bash_logout on exit.
7923 * If called as sh, skips .bash_XXX files.
7927 if (G.global_argv[1]) {
7930 * "bash <script>" (which is never interactive (unless -i?))
7931 * sources $BASH_ENV here (without scanning $PATH).
7932 * If called as sh, does the same but with $ENV.
7936 debug_printf("running script '%s'\n", G.global_argv[0]);
7937 input = xfopen_for_read(G.global_argv[0]);
7938 close_on_exec_on(fileno(input));
7939 install_special_sighandlers();
7940 parse_and_run_file(input);
7941 #if ENABLE_FEATURE_CLEAN_UP
7947 /* Up to here, shell was non-interactive. Now it may become one.
7948 * NB: don't forget to (re)run install_special_sighandlers() as needed.
7951 /* A shell is interactive if the '-i' flag was given,
7952 * or if all of the following conditions are met:
7954 * no arguments remaining or the -s flag given
7955 * standard input is a terminal
7956 * standard output is a terminal
7957 * Refer to Posix.2, the description of the 'sh' utility.
7960 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
7961 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7962 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7963 if (G_saved_tty_pgrp < 0)
7964 G_saved_tty_pgrp = 0;
7966 /* try to dup stdin to high fd#, >= 255 */
7967 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7968 if (G_interactive_fd < 0) {
7969 /* try to dup to any fd */
7970 G_interactive_fd = dup(STDIN_FILENO);
7971 if (G_interactive_fd < 0) {
7973 G_interactive_fd = 0;
7974 G_saved_tty_pgrp = 0;
7977 // TODO: track & disallow any attempts of user
7978 // to (inadvertently) close/redirect G_interactive_fd
7980 debug_printf("interactive_fd:%d\n", G_interactive_fd);
7981 if (G_interactive_fd) {
7982 close_on_exec_on(G_interactive_fd);
7984 if (G_saved_tty_pgrp) {
7985 /* If we were run as 'hush &', sleep until we are
7986 * in the foreground (tty pgrp == our pgrp).
7987 * If we get started under a job aware app (like bash),
7988 * make sure we are now in charge so we don't fight over
7989 * who gets the foreground */
7991 pid_t shell_pgrp = getpgrp();
7992 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7993 if (G_saved_tty_pgrp == shell_pgrp)
7995 /* send TTIN to ourself (should stop us) */
7996 kill(- shell_pgrp, SIGTTIN);
8000 /* Install more signal handlers */
8001 install_special_sighandlers();
8003 if (G_saved_tty_pgrp) {
8004 /* Set other signals to restore saved_tty_pgrp */
8005 install_fatal_sighandlers();
8006 /* Put ourselves in our own process group
8007 * (bash, too, does this only if ctty is available) */
8008 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8009 /* Grab control of the terminal */
8010 tcsetpgrp(G_interactive_fd, getpid());
8012 /* -1 is special - makes xfuncs longjmp, not exit
8013 * (we reset die_sleep = 0 whereever we [v]fork) */
8014 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8016 install_special_sighandlers();
8018 #elif ENABLE_HUSH_INTERACTIVE
8019 /* No job control compiled in, only prompt/line editing */
8020 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8021 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8022 if (G_interactive_fd < 0) {
8023 /* try to dup to any fd */
8024 G_interactive_fd = dup(STDIN_FILENO);
8025 if (G_interactive_fd < 0)
8027 G_interactive_fd = 0;
8030 if (G_interactive_fd) {
8031 close_on_exec_on(G_interactive_fd);
8033 install_special_sighandlers();
8035 /* We have interactiveness code disabled */
8036 install_special_sighandlers();
8039 * if interactive but not a login shell, sources ~/.bashrc
8040 * (--norc turns this off, --rcfile <file> overrides)
8043 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8044 /* note: ash and hush share this string */
8045 printf("\n\n%s %s\n"
8046 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8049 "hush - the humble shell"
8053 parse_and_run_file(stdin);
8056 hush_exit(G.last_exitcode);
8061 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8062 int msh_main(int argc, char **argv)
8064 //bb_error_msg("msh is deprecated, please use hush instead");
8065 return hush_main(argc, argv);
8073 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8078 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8085 return applet_main_func(argc, argv - argc);
8088 static int FAST_FUNC builtin_test(char **argv)
8090 return run_applet_main(argv, test_main);
8093 static int FAST_FUNC builtin_echo(char **argv)
8095 return run_applet_main(argv, echo_main);
8099 static int FAST_FUNC builtin_printf(char **argv)
8101 return run_applet_main(argv, printf_main);
8105 static char **skip_dash_dash(char **argv)
8108 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8113 static int FAST_FUNC builtin_eval(char **argv)
8115 int rcode = EXIT_SUCCESS;
8117 argv = skip_dash_dash(argv);
8119 char *str = expand_strvec_to_string(argv);
8121 * eval "echo Hi; done" ("done" is syntax error):
8122 * "echo Hi" will not execute too.
8124 parse_and_run_string(str);
8126 rcode = G.last_exitcode;
8131 static int FAST_FUNC builtin_cd(char **argv)
8135 argv = skip_dash_dash(argv);
8137 if (newdir == NULL) {
8138 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8139 * bash says "bash: cd: HOME not set" and does nothing
8142 const char *home = get_local_var_value("HOME");
8143 newdir = home ? home : "/";
8145 if (chdir(newdir)) {
8146 /* Mimic bash message exactly */
8147 bb_perror_msg("cd: %s", newdir);
8148 return EXIT_FAILURE;
8150 /* Read current dir (get_cwd(1) is inside) and set PWD.
8151 * Note: do not enforce exporting. If PWD was unset or unexported,
8152 * set it again, but do not export. bash does the same.
8154 set_pwd_var(/*exp:*/ 0);
8155 return EXIT_SUCCESS;
8158 static int FAST_FUNC builtin_exec(char **argv)
8160 argv = skip_dash_dash(argv);
8161 if (argv[0] == NULL)
8162 return EXIT_SUCCESS; /* bash does this */
8164 /* Careful: we can end up here after [v]fork. Do not restore
8165 * tty pgrp then, only top-level shell process does that */
8166 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8167 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8169 /* TODO: if exec fails, bash does NOT exit! We do.
8170 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8171 * and tcsetpgrp, and this is inherently racy.
8173 execvp_or_die(argv);
8176 static int FAST_FUNC builtin_exit(char **argv)
8178 debug_printf_exec("%s()\n", __func__);
8180 /* interactive bash:
8181 * # trap "echo EEE" EXIT
8184 * There are stopped jobs.
8185 * (if there are _stopped_ jobs, running ones don't count)
8188 # EEE (then bash exits)
8190 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8193 /* note: EXIT trap is run by hush_exit */
8194 argv = skip_dash_dash(argv);
8195 if (argv[0] == NULL)
8196 hush_exit(G.last_exitcode);
8197 /* mimic bash: exit 123abc == exit 255 + error msg */
8198 xfunc_error_retval = 255;
8199 /* bash: exit -2 == exit 254, no error msg */
8200 hush_exit(xatoi(argv[0]) & 0xff);
8203 static void print_escaped(const char *s)
8208 const char *p = strchrnul(s, '\'');
8209 /* print 'xxxx', possibly just '' */
8210 printf("'%.*s'", (int)(p - s), s);
8215 /* s points to '; print "'''...'''" */
8217 do putchar('\''); while (*++s == '\'');
8222 #if !ENABLE_HUSH_LOCAL
8223 #define helper_export_local(argv, exp, lvl) \
8224 helper_export_local(argv, exp)
8226 static void helper_export_local(char **argv, int exp, int lvl)
8230 char *name_end = strchrnul(name, '=');
8232 /* So far we do not check that name is valid (TODO?) */
8234 if (*name_end == '\0') {
8235 struct variable *var, **vpp;
8237 vpp = get_ptr_to_local_var(name, name_end - name);
8238 var = vpp ? *vpp : NULL;
8240 if (exp == -1) { /* unexporting? */
8241 /* export -n NAME (without =VALUE) */
8243 var->flg_export = 0;
8244 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8246 } /* else: export -n NOT_EXISTING_VAR: no-op */
8249 if (exp == 1) { /* exporting? */
8250 /* export NAME (without =VALUE) */
8252 var->flg_export = 1;
8253 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8254 putenv(var->varstr);
8258 /* Exporting non-existing variable.
8259 * bash does not put it in environment,
8260 * but remembers that it is exported,
8261 * and does put it in env when it is set later.
8262 * We just set it to "" and export. */
8263 /* Or, it's "local NAME" (without =VALUE).
8264 * bash sets the value to "". */
8265 name = xasprintf("%s=", name);
8267 /* (Un)exporting/making local NAME=VALUE */
8268 name = xstrdup(name);
8270 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8274 static int FAST_FUNC builtin_export(char **argv)
8276 unsigned opt_unexport;
8278 #if ENABLE_HUSH_EXPORT_N
8279 /* "!": do not abort on errors */
8280 opt_unexport = getopt32(argv, "!n");
8281 if (opt_unexport == (uint32_t)-1)
8282 return EXIT_FAILURE;
8289 if (argv[0] == NULL) {
8296 /* ash emits: export VAR='VAL'
8297 * bash: declare -x VAR="VAL"
8298 * we follow ash example */
8299 const char *s = *e++;
8300 const char *p = strchr(s, '=');
8302 if (!p) /* wtf? take next variable */
8305 printf("export %.*s", (int)(p - s) + 1, s);
8306 print_escaped(p + 1);
8310 /*fflush_all(); - done after each builtin anyway */
8312 return EXIT_SUCCESS;
8315 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8317 return EXIT_SUCCESS;
8320 #if ENABLE_HUSH_LOCAL
8321 static int FAST_FUNC builtin_local(char **argv)
8323 if (G.func_nest_level == 0) {
8324 bb_error_msg("%s: not in a function", argv[0]);
8325 return EXIT_FAILURE; /* bash compat */
8327 helper_export_local(argv, 0, G.func_nest_level);
8328 return EXIT_SUCCESS;
8332 static int FAST_FUNC builtin_trap(char **argv)
8338 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8343 /* No args: print all trapped */
8344 for (i = 0; i < NSIG; ++i) {
8347 print_escaped(G.traps[i]);
8348 /* note: bash adds "SIG", but only if invoked
8349 * as "bash". If called as "sh", or if set -o posix,
8350 * then it prints short signal names.
8351 * We are printing short names: */
8352 printf(" %s\n", get_signame(i));
8355 /*fflush_all(); - done after each builtin anyway */
8356 return EXIT_SUCCESS;
8360 /* If first arg is a number: reset all specified signals */
8361 sig = bb_strtou(*argv, NULL, 10);
8367 sighandler_t handler;
8369 sig = get_signum(*argv++);
8370 if (sig < 0 || sig >= NSIG) {
8372 /* Mimic bash message exactly */
8373 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8378 G.traps[sig] = xstrdup(new_cmd);
8380 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8381 get_signame(sig), sig, G.traps[sig]);
8383 /* There is no signal for 0 (EXIT) */
8388 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8390 /* We are removing trap handler */
8391 handler = pick_sighandler(sig);
8392 signal(sig, handler);
8397 if (!argv[1]) { /* no second arg */
8398 bb_error_msg("trap: invalid arguments");
8399 return EXIT_FAILURE;
8402 /* First arg is "-": reset all specified to default */
8403 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8404 /* Everything else: set arg as signal handler
8405 * (includes "" case, which ignores signal) */
8406 if (argv[0][0] == '-') {
8407 if (argv[0][1] == '\0') { /* "-" */
8408 /* new_cmd remains NULL: "reset these sigs" */
8411 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8414 /* else: "-something", no special meaning */
8419 goto process_sig_list;
8422 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8423 static int FAST_FUNC builtin_type(char **argv)
8425 int ret = EXIT_SUCCESS;
8431 if (0) {} /* make conditional compile easier below */
8432 /*else if (find_alias(*argv))
8433 type = "an alias";*/
8434 #if ENABLE_HUSH_FUNCTIONS
8435 else if (find_function(*argv))
8436 type = "a function";
8438 else if (find_builtin(*argv))
8439 type = "a shell builtin";
8440 else if ((path = find_in_path(*argv)) != NULL)
8443 bb_error_msg("type: %s: not found", *argv);
8448 printf("%s is %s\n", *argv, type);
8456 /* built-in 'fg' and 'bg' handler */
8457 static int FAST_FUNC builtin_fg_bg(char **argv)
8462 if (!G_interactive_fd)
8463 return EXIT_FAILURE;
8465 /* If they gave us no args, assume they want the last backgrounded task */
8467 for (pi = G.job_list; pi; pi = pi->next) {
8468 if (pi->jobid == G.last_jobid) {
8472 bb_error_msg("%s: no current job", argv[0]);
8473 return EXIT_FAILURE;
8475 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8476 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8477 return EXIT_FAILURE;
8479 for (pi = G.job_list; pi; pi = pi->next) {
8480 if (pi->jobid == jobnum) {
8484 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8485 return EXIT_FAILURE;
8487 /* TODO: bash prints a string representation
8488 * of job being foregrounded (like "sleep 1 | cat") */
8489 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8490 /* Put the job into the foreground. */
8491 tcsetpgrp(G_interactive_fd, pi->pgrp);
8494 /* Restart the processes in the job */
8495 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8496 for (i = 0; i < pi->num_cmds; i++) {
8497 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8498 pi->cmds[i].is_stopped = 0;
8500 pi->stopped_cmds = 0;
8502 i = kill(- pi->pgrp, SIGCONT);
8504 if (errno == ESRCH) {
8505 delete_finished_bg_job(pi);
8506 return EXIT_SUCCESS;
8508 bb_perror_msg("kill (SIGCONT)");
8511 if (argv[0][0] == 'f') {
8513 return checkjobs_and_fg_shell(pi);
8515 return EXIT_SUCCESS;
8519 #if ENABLE_HUSH_HELP
8520 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8522 const struct built_in_command *x;
8525 "Built-in commands:\n"
8526 "------------------\n");
8527 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8529 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8532 return EXIT_SUCCESS;
8537 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8540 const char *status_string;
8542 for (job = G.job_list; job; job = job->next) {
8543 if (job->alive_cmds == job->stopped_cmds)
8544 status_string = "Stopped";
8546 status_string = "Running";
8548 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8550 return EXIT_SUCCESS;
8555 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8560 # ifdef M_TRIM_THRESHOLD
8561 /* Optional. Reduces probability of false positives */
8564 /* Crude attempt to find where "free memory" starts,
8565 * sans fragmentation. */
8567 l = (unsigned long)p;
8570 if (l < (unsigned long)p) l = (unsigned long)p;
8573 if (!G.memleak_value)
8574 G.memleak_value = l;
8576 l -= G.memleak_value;
8583 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8588 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8591 return EXIT_SUCCESS;
8594 /* Interruptibility of read builtin in bash
8595 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8597 * Empty trap makes read ignore corresponding signal, for any signal.
8600 * - terminates non-interactive shell;
8601 * - interrupts read in interactive shell;
8602 * if it has non-empty trap:
8603 * - executes trap and returns to command prompt in interactive shell;
8604 * - executes trap and returns to read in non-interactive shell;
8606 * - is ignored (does not interrupt) read in interactive shell;
8607 * - terminates non-interactive shell;
8608 * if it has non-empty trap:
8609 * - executes trap and returns to read;
8611 * - terminates shell (regardless of interactivity);
8612 * if it has non-empty trap:
8613 * - executes trap and returns to read;
8615 static int FAST_FUNC builtin_read(char **argv)
8625 /* "!": do not abort on errors.
8626 * Option string must start with "sr" to match BUILTIN_READ_xxx
8628 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8629 if (read_flags == (uint32_t)-1)
8630 return EXIT_FAILURE;
8632 ifs = get_local_var_value("IFS"); /* can be NULL */
8635 r = shell_builtin_read(set_local_var_from_halves,
8645 if ((uintptr_t)r == 1 && errno == EINTR) {
8646 unsigned sig = check_and_run_traps();
8647 if (sig && sig != SIGINT)
8651 if ((uintptr_t)r > 1) {
8652 bb_error_msg("%s", r);
8653 r = (char*)(uintptr_t)1;
8656 return (uintptr_t)r;
8659 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8660 * built-in 'set' handler
8662 * set [-abCefhmnuvx] [-o option] [argument...]
8663 * set [+abCefhmnuvx] [+o option] [argument...]
8664 * set -- [argument...]
8667 * Implementations shall support the options in both their hyphen and
8668 * plus-sign forms. These options can also be specified as options to sh.
8670 * Write out all variables and their values: set
8671 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8672 * Turn on the -x and -v options: set -xv
8673 * Unset all positional parameters: set --
8674 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8675 * Set the positional parameters to the expansion of x, even if x expands
8676 * with a leading '-' or '+': set -- $x
8678 * So far, we only support "set -- [argument...]" and some of the short names.
8680 static int FAST_FUNC builtin_set(char **argv)
8683 char **pp, **g_argv;
8684 char *arg = *++argv;
8688 for (e = G.top_var; e; e = e->next)
8690 return EXIT_SUCCESS;
8694 if (strcmp(arg, "--") == 0) {
8698 if (arg[0] != '+' && arg[0] != '-')
8700 for (n = 1; arg[n]; ++n) {
8701 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8703 if (arg[n] == 'o' && argv[1])
8706 } while ((arg = *++argv) != NULL);
8707 /* Now argv[0] is 1st argument */
8710 return EXIT_SUCCESS;
8713 /* NB: G.global_argv[0] ($0) is never freed/changed */
8714 g_argv = G.global_argv;
8715 if (G.global_args_malloced) {
8721 G.global_args_malloced = 1;
8722 pp = xzalloc(sizeof(pp[0]) * 2);
8723 pp[0] = g_argv[0]; /* retain $0 */
8726 /* This realloc's G.global_argv */
8727 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8734 return EXIT_SUCCESS;
8736 /* Nothing known, so abort */
8738 bb_error_msg("set: %s: invalid option", arg);
8739 return EXIT_FAILURE;
8742 static int FAST_FUNC builtin_shift(char **argv)
8745 argv = skip_dash_dash(argv);
8749 if (n >= 0 && n < G.global_argc) {
8750 if (G.global_args_malloced) {
8753 free(G.global_argv[m++]);
8756 memmove(&G.global_argv[1], &G.global_argv[n+1],
8757 G.global_argc * sizeof(G.global_argv[0]));
8758 return EXIT_SUCCESS;
8760 return EXIT_FAILURE;
8763 static int FAST_FUNC builtin_source(char **argv)
8765 char *arg_path, *filename;
8768 #if ENABLE_HUSH_FUNCTIONS
8772 argv = skip_dash_dash(argv);
8775 /* bash says: "bash: .: filename argument required" */
8776 return 2; /* bash compat */
8779 if (!strchr(filename, '/')) {
8780 arg_path = find_in_path(filename);
8782 filename = arg_path;
8784 input = fopen_or_warn(filename, "r");
8787 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8788 return EXIT_FAILURE;
8790 close_on_exec_on(fileno(input));
8792 #if ENABLE_HUSH_FUNCTIONS
8793 sv_flg = G.flag_return_in_progress;
8794 /* "we are inside sourced file, ok to use return" */
8795 G.flag_return_in_progress = -1;
8797 save_and_replace_G_args(&sv, argv);
8799 parse_and_run_file(input);
8802 restore_G_args(&sv, argv);
8803 #if ENABLE_HUSH_FUNCTIONS
8804 G.flag_return_in_progress = sv_flg;
8807 return G.last_exitcode;
8810 static int FAST_FUNC builtin_umask(char **argv)
8816 argv = skip_dash_dash(argv);
8818 mode_t old_mask = mask;
8821 rc = bb_parse_mode(argv[0], &mask);
8826 * bash: umask: 'q': invalid symbolic mode operator
8827 * bash: umask: 999: octal number out of range
8829 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8834 printf("%04o\n", (unsigned) mask);
8835 /* fall through and restore mask which we set to 0 */
8839 return !rc; /* rc != 0 - success */
8842 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8843 static int FAST_FUNC builtin_unset(char **argv)
8848 /* "!": do not abort on errors */
8849 /* "+": stop at 1st non-option */
8850 opts = getopt32(argv, "!+vf");
8851 if (opts == (unsigned)-1)
8852 return EXIT_FAILURE;
8854 bb_error_msg("unset: -v and -f are exclusive");
8855 return EXIT_FAILURE;
8861 if (!(opts & 2)) { /* not -f */
8862 if (unset_local_var(*argv)) {
8863 /* unset <nonexistent_var> doesn't fail.
8864 * Error is when one tries to unset RO var.
8865 * Message was printed by unset_local_var. */
8869 #if ENABLE_HUSH_FUNCTIONS
8879 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8880 static int FAST_FUNC builtin_wait(char **argv)
8882 int ret = EXIT_SUCCESS;
8885 argv = skip_dash_dash(argv);
8886 if (argv[0] == NULL) {
8887 /* Don't care about wait results */
8888 /* Note 1: must wait until there are no more children */
8889 /* Note 2: must be interruptible */
8891 * $ sleep 3 & sleep 6 & wait
8896 * $ sleep 3 & sleep 6 & wait
8900 * ^C <-- after ~4 sec from keyboard
8905 sigset_t oldset, allsigs;
8907 /* waitpid is not interruptible by SA_RESTARTed
8908 * signals which we use. Thus, this ugly dance:
8911 /* Make sure possible SIGCHLD is stored in kernel's
8912 * pending signal mask before we call waitpid.
8913 * Or else we may race with SIGCHLD, lose it,
8914 * and get stuck in sigwaitinfo...
8916 sigfillset(&allsigs);
8917 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8919 if (!sigisemptyset(&G.pending_set)) {
8920 /* Crap! we raced with some signal! */
8925 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8926 if (errno == ECHILD) {
8927 sigprocmask(SIG_SETMASK, &oldset, NULL);
8931 /* Wait for SIGCHLD or any other signal */
8932 //sig = sigwaitinfo(&allsigs, NULL);
8933 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8934 /* Note: sigsuspend invokes signal handler */
8935 sigsuspend(&oldset);
8937 sigprocmask(SIG_SETMASK, &oldset, NULL);
8939 /* So, did we get a signal? */
8941 // raise(sig); /* run handler */
8942 sig = check_and_run_traps();
8943 if (sig /*&& sig != SIGCHLD - always true */) {
8948 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
8953 /* This is probably buggy wrt interruptible-ness */
8955 pid_t pid = bb_strtou(*argv, NULL, 10);
8957 /* mimic bash message */
8958 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
8959 return EXIT_FAILURE;
8961 if (waitpid(pid, &status, 0) == pid) {
8962 if (WIFSIGNALED(status))
8963 ret = 128 + WTERMSIG(status);
8964 else if (WIFEXITED(status))
8965 ret = WEXITSTATUS(status);
8969 bb_perror_msg("wait %s", *argv);
8978 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8979 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8982 def = bb_strtou(argv[1], NULL, 10);
8983 if (errno || def < def_min || argv[2]) {
8984 bb_error_msg("%s: bad arguments", argv[0]);
8992 #if ENABLE_HUSH_LOOPS
8993 static int FAST_FUNC builtin_break(char **argv)
8996 if (G.depth_of_loop == 0) {
8997 bb_error_msg("%s: only meaningful in a loop", argv[0]);
8998 return EXIT_SUCCESS; /* bash compat */
9000 G.flag_break_continue++; /* BC_BREAK = 1 */
9002 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9003 if (depth == UINT_MAX)
9004 G.flag_break_continue = BC_BREAK;
9005 if (G.depth_of_loop < depth)
9006 G.depth_break_continue = G.depth_of_loop;
9008 return EXIT_SUCCESS;
9011 static int FAST_FUNC builtin_continue(char **argv)
9013 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9014 return builtin_break(argv);
9018 #if ENABLE_HUSH_FUNCTIONS
9019 static int FAST_FUNC builtin_return(char **argv)
9023 if (G.flag_return_in_progress != -1) {
9024 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9025 return EXIT_FAILURE; /* bash compat */
9028 G.flag_return_in_progress = 1;
9031 * out of range: wraps around at 256, does not error out
9032 * non-numeric param:
9033 * f() { false; return qwe; }; f; echo $?
9034 * bash: return: qwe: numeric argument required <== we do this
9035 * 255 <== we also do this
9037 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);